* Move the authorizer into its own package.
The Authorizer and associated functions and constants have been moved into
their own package `authz`. This will allow us to more easily create separate
services for gRPC functionality so that we're not pushing as much into the
`lib/auth` package.
Though this PR is large, the only actual code change here is making
`ContextForLocalUser` exported and changing the `permissions_test.go` so that
it doesn't rely on the `lib/auth` package.
* Use context functions.
* Test and linting fixes.
* Add in a temporary alias file to ensure e still compiles.
* Use functions instead of var aliases for performance reasons.
* Adding in godocs, cleaning up tests.
* Fix tests.
* Add a few more aliases.
This command allows you to modify a resource in place by opening
the resource YAML in your text editor.
The editor is selected by checking the following, in order of
precedence:
- the TELEPORT_EDITOR environment variable
- the VISUAL environment variable
- the EDITOR environment variable
- defaulting to 'vi'
We also prevent renaming resources with this command.
See gravitational/webapps#1465 where we do the same for the web UI.
Remove the Upsert and Delete methods from the SAMLService interface. It
was intended for these to be part of the SAML "plugin", however they are
needed for the operator tests to be able to create and delete the SAML
connectors.
The methods are back to being implemented directly in the `auth.Server`.
This does not cause any real issues with the rest in the enterprise repo
as the upsert/delete logic is just manipulating the local backend with
no actual SAML logic in it. The `Get*` methods had already been kept in
the `auth.Server` for the same reason.
This narrows the `SAMLService` interface to just creating the SAML auth
request and validating the response that comes back from the SAML
identity provider. This is the core of the SAML-specific logic.
Issue: https://github.com/gravitational/teleport.e/issues/525
Create a new type - `SAMLAuthService` - and move the implementation of
the SAML connector from the auth Service to this new type. This
decoupling will make it easier to move out of tree in a later commit.
This also lays the basic groundwork for running without the SAML
connector at all, returning a NotImplemented error for all the SAML
logic if the SAMLAuthService is not plugged in.
A number of names in the `auth` package have been exported to facilitate
moving the SAML connector out of this repository. The types exported do
not need to be exported for this commit, but for subsequent commits that
move the `SAMLAuthService` out of the `auth` package.
Also apply a small fix to to emit `apievents.SAMLConnector*` events of
`apievents.OIDCConnector*` events in the SAML connector.
Move the validation for SAML connectors being inserted or updated (Upsert)
from before the role check for Insert/Update to after it. The validation
can perform an HTTP GET request if the `entity_descriptor_url` field is
set. This should at least require that the user have permission to
Upsert a SAML OIDC connector.
Ensure that roles exist that are referenced in SAML connectors, as the
roles in SAML connectors are validated as the connector is inserted or
updated. The validation has moved to auth.Server (from grpcserver) so
that is now required in tests that operate against auth.Server.
Add a test case to test that an access denied error is returned when
upserting an invalid SAML connector instead of a validation failure,
showing that we are not using input from untrusted sources. Also test
that validation is still performed when access is permitted and that a
valid SAML connector can be upserted.
* Embed auth.Cache in auth.Server
* Hit the backend during Auth initialization
* Bypass the cache when rotating CAs
* Services.UpsertTrustedCluster is different
* Bypass the cache in waitForTunnelConnections
* Fix infinite recursion
* More cache bypassing during init and rotations
* Rename Services to Uncached in auth.Server
* Further cleanups
* Don't start the auth cache immediately
* Go back to Services rather than Uncached
* Comments and a missing method
This change, along with gravitational/webapps#530, adds a new error message for when a user successfully authenticates with SSO but fails to match any roles.
* Changes for tctl sso test, tctl sso configure commands.
* Log SSO diagnostic information for SSO test flows.
Co-authored-by: Roman Tkachenko <roman@goteleport.com>
* Fix goroutine and memory leak in watchCertAuthorities
The CA Watcher was blocking both on writing to a channel when the watcher
was closed and on HTTP calls that had no request timeout or context passed
to cause cancellation.
All resourceWatcher implementations that had a bug which may cause them to block
on writing to a channel forever were fixed by selecting on the write and ctx.Done.
Adding context.Context to all Get/Put/Post/Delete methods on the auth HTTPClient to
force callers to propagate context. Prior all calls used context.TODO which
prevents requests from being properly cancelled.
Add context propagation to RotateCertAuthority, RotateExternalCertAuthority,
GetCertAuthority, GetCertAuthorities. This is needed to get the correct ctx
from the CertAtuhorityWatcher all the way down to the HTTPClient that makes
the call.
Closes#10648
* Refactor most uses of `UserMetadata` into a handful of functions
* Add access requests to `UserMetadata`
* Explanation for the reserved field in SessionStart
* Add workaround for PingID SAML auth
PingID's SAML auth requires `SigAlg` and `Signature` fields to be set
as query parameters during auth requests when "Enforce Signed Authn
Request" is enabled in the Ping app settings. This adds a workaround
to force gosaml2 to include these parameters when it otherwise would
not. This workaround is enabled when `provider: ping` is set in the
connector properties.
* Add `TestPingSAMLWorkaround` unit test
* Consistently refer to Ping (PingId, PingOne, etc) as just Ping
* Revert fixtures change as metadata is now embedded in `saml_test`
* Improve comments for Ping behavior workarounds
* Improve comment explanation for the `Ping` constant
* Use cmp.Equal instead of manual Equals methods
Equals methods can get out-of-sync with the fields added in structs they
compare. Using `cmp.Equal` handles that, removes a ton of code and makes
it more explicit when specific fields are excluded from comparison.
* Use gogoproto equal plugin for comparing proto values
This will be faster than reflect-based go-cmp.
- Preserve login time with WebSession when user first creates a web session to derive
"default" expiry when user wants to switch back
- Change the signature of ExtendWebSession to accept a
NewWebSessionRequest struct that contains session information
- Create renewSessionRequest object to read from web request for endpoint renewSession
- Endpoint now also returns SessionExpires time that is used as countdown in UI
Purpose is to allow users with admin privilege that are able to view audit logs,
to be able to debug SSO login failures from the UI as much as possible
* Return generic error message for sso console login failures to hide
sensitive data from reaching client. Previously errors were returning as
empty messages b/c of a trace bug.
* Remove emit event for createOIDCClient to allow outer caller to
emit event and prevent double emits on error.
* Temporarily direct users to check teleports log on errors that come back
empty to tsh client.
Fixes#5352
```yaml
allow:
impersonate:
users: ['alice', 'bob']
roles: ['*']
where: 'contains(user.spec.traits["groups"], impersonate_role.traits)'
```
Adds "impersonator" to all X.509 and SSH client certs
issued using impersonation and does best effort to track
requests by impersonators in audit events.
Limits certs TTL to the impersonator's max session TTL.
Prevents impersonating users to recursively impersonate
other users.
Allows impersonating users to renew their own certificate,
for example to set route to cluster.
Adds missing token permission for editor role.
* Use fake clock consistently in units tests.
* Split web session management into two interfaces and implement them separately for clear separation
* Split session management into New/Validate to make it aparent where the sessions are created and where existing sessions are managed. Remove ttlmap in favor of a simple map and handle expirations
explicitly.
Add web session management to gRPC server for the cache.
* Reintroduce web sessions APIs under a getter interface.
* Add SubKind to WatchKind for gRPC and add conversions from/to protobuf. Fix web sessions unit tests.
* lib/web: create/insert session context in ValidateSession if the session has not yet been added to session cache.
lib/cache: add event filter for web session in auth cache.
lib/auth: propagate web session subkind in gRPC event.
* Add implicit migrations for legacy web session key path for queries.
* Integrate web token in lib/web
* Add a bearer token when upserting a web session
* Fix tests. Use fake clock wherever possible.
* Converge session cache handling in lib/web
* Clean up and add doc comments where necessary
* Use correct form of sessions/tokens controller for ServerWithRoles. Use fake time in web tests
* Converge the web sessions/tokens handling in lib/auth to match the old behavior w.r.t access checking (e.g. implicit handling of the local user identity).
* Use cached reads and waiters only when necessary. Query sessions/tokens using best-effort - first looking in the cache and falling back to a proxy client
* Properly propagate events about deletes for values with subkind.
* Update to retrofit changes after recent teleport API refactorings
* Update comment on removing legacy code to move the deadline to 7.x
* Do not close the resources on the session when it expires - this beats the purpose of this PR.
Also avoid a race between closing the cached clients and an existing reference to the session by letting the session linger for longer before removing it.
* Move web session/token request structs to the api client proto package
* Only set HTTP fs on the web handler if the UI is enabled
* Properly tear down web session test by releasing resources at the end. Fix the web UI assets configuration by removing DisableUI and instead use the presence of assets (HTTP file system) as an indicator that the web UI has been enabled.
* Decrease the expired session cache clean up threshold to 2m. Only log the expiration error message for errors other than not found
* Add test for terminal disconnect when using two proxies in HA mode
Various improvements related to extending the dynamic access
API, including:
- Support for users with no statically defined roles.
- Unify trait mapping logic (e.g. claims_to_roles) across
the connector types.
- Support for matcher syntax and claims_to_roles mappings when
configuring which roles a user is able to request.
- Allow tsh or the web UI to automatically generate wildcard
access requests when dictated by role configuration.
- Allow RBAC configuration to attach annotations to pending
access requests which can be consumed by plugins.
- Allow plugins to attach annotations to approvals/denials
which appear in the audit log, and may also be looked up
later to determine additional info about a resolution.
- Support prompts, request reasons, and approval/denial
reasons for access requests.
K8s cluster name is specified during login (for now) and gets plumbed to
a new extensions on the TLS cert. The name is validated against all
known k8s clusters reported via proxy heartbeats. If no name is
provided, the extension remains empty.
The name in the cert will get used by proxies for routing, once we fully
support multiple k8s clusters per teleport cluster.
This was tested with direct and github login flows.
This commit introduces GRPC API for streaming sessions.
It adds structured events and sync streaming
that avoids storing events on disk.
You can find design in rfd/0002-streaming.md RFD.
Our auth middleware already attaches a TLS identity as context value.
Plumb contexts through and extract the username when recording events.
If the received context doesn't have an identity attached, use "system"
as username.
Lots of noise here due to missing context.Context plumbing :(
We should eventually plumb contexts to all those RPC interfaces.
Updates #3816
* Add UpdateUser rpc to proto
* Differentiate between create and update in github,oidc,saml
* Edit updated_by event field to be more generic (used with contexts to capture user modifying records)
* Update security issue by removing secrets from user when update/upsert/create (forrest)
* Update createUser in resource_command and require force for updates
Fixed findings:
```
lib/auth/clt.go:294:12: SA1019: grpc.WithDialer is deprecated: use WithContextDialer instead. Will be supported throughout 1.x. (staticcheck)
dialer := grpc.WithDialer(func(addr string, timeout time.Duration) (net.Conn, error) {ion error: desc = "transport: Erro
^
lib/auth/clt.go:1462:5: SA1019: grpc.Code is deprecated: use status.Code instead. (staticcheck)site-A Type:proxy Addr:{Addr:local
if grpc.Code(err) != codes.Unimplemented {
^
lib/auth/clt.go:1500:5: SA1019: grpc.Code is deprecated: use status.Code instead. (staticcheck)rsetunnel/agentpool.go:312
if grpc.Code(err) != codes.Unimplemented {
^
lib/auth/saml.go:294:33: SA5011: possible nil pointer dereference (staticcheck)
events.EventUser: re.auth.Username,
^
lib/auth/auth_test.go:119:2: SA4006: this value of `ws` is never used (staticcheck)ats. stats:map[connected:1 connect
ws, err := s.a.AuthenticateWebUser(AuthenticateUserRequest{
^
lib/auth/auth_test.go:160:2: SA4006: this value of `ws` is never used (staticcheck)ver.go:425
ws, err := s.a.AuthenticateWebUser(AuthenticateUserRequest{
^
lib/auth/auth_test.go:243:2: SA4006: this value of `roles` is never used (staticcheck)es that discovery protocol recover
roles, err = s.a.ValidateToken(tok)
^
lib/auth/password_test.go:228:2: SA4006: this value of `err` is never used (staticcheck)necting -> connected. leaseID:5 ta
token, err := s.a.CreateResetPasswordToken(context.TODO(), CreateResetPasswordTokenRequest{7.0.0.1:46150. reversetunnel/srv.g
^
lib/auth/tls_test.go:109:2: SA4006: this value of `err` is never used (staticcheck)ry(c *check.C) {
err = s.server.AuthServer.Trust(remoteServer, nil)
^
lib/auth/tls_test.go:195:2: SA4006: this value of `err` is never used (staticcheck)meout=10000&_sync=OFF, poll stream
err = s.server.AuthServer.Trust(remoteServer, nil)
^
lib/auth/tls_test.go:360:2: SA4006: this value of `newProxy` is never used (staticcheck) be received and the connection ad
newProxy, err := s.server.NewClient(TestBuiltin(teleport.RoleProxy))o/src/github.com/gravitational/tel
^
lib/auth/tls_test.go:388:2: SA4006: this value of `err` is never used (staticcheck)o/src/github.com/gravitational/tel
err = s.server.Auth().autoRotateCertAuthorities()
^
lib/auth/tls_test.go:1074:2: SA4006: this value of `err` is never used (staticcheck)uest, we will recover session id a
err = os.MkdirAll(filepath.Join(uploadDir, "upload", "sessions", defaults.Namespace), 0755)reversetunnel/agent.go:458
^
lib/auth/tls_test.go:1263:2: SA4006: this value of `err` is never used (staticcheck)quests channel. leaseID:5 target:l
err = clt.UpsertPassword(user, pass)
^
lib/auth/tls_test.go:1691:2: SA4006: this value of `err` is never used (staticcheck)
userCerts, err = adminClient.GenerateUserCerts(context.TODO(), proto.UserCertsRequest{et:localhost:20088 reversetunnel/t
^
lib/auth/auth_with_roles.go:860:32: SA1029: should not use built-in type string as key for value; define your own type to avoid collisions (staticcheck)
return context.WithValue(ctx, events.AccessRequestUpdateBy, user)ts is received, if it's been longe
^
lib/auth/auth_with_roles.go:876:32: SA1029: should not use built-in type string as key for value; define your own type to avoid collisions (staticcheck)
return context.WithValue(ctx, events.AccessRequestDelegator, delegator)ime = f.process.Clock.Now()
^
lib/auth/middleware.go:316:69: SA1029: should not use built-in type string as key for value; define your own type to avoid collisions (staticcheck)
requestWithContext := r.WithContext(context.WithValue(baseContext, ContextUser, user))rocess.Infof("Teleport has recover
^ion to @remote-auth-server [] in r
lib/auth/apiserver.go:285:42: SA1029: should not use built-in type string as key for value; define your own type to avoid collisions (staticcheck)
ctx := context.WithValue(r.Context(), contextParams, p)et:localhost:20088 reversetunnel/t
^
```