repo
stringlengths
5
67
sha
stringlengths
40
40
path
stringlengths
4
234
url
stringlengths
85
339
language
stringclasses
6 values
split
stringclasses
3 values
doc
stringlengths
3
51.2k
sign
stringlengths
5
8.01k
problem
stringlengths
13
51.2k
output
stringlengths
0
3.87M
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/ctx.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/ctx.go#L412-L417
go
train
// GetTerm returns a Terminal.
func (c *ServerContext) GetTerm() Terminal
// GetTerm returns a Terminal. func (c *ServerContext) GetTerm() Terminal
{ c.RLock() defer c.RUnlock() return c.term }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/ctx.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/ctx.go#L420-L425
go
train
// SetTerm set a Terminal.
func (c *ServerContext) SetTerm(t Terminal)
// SetTerm set a Terminal. func (c *ServerContext) SetTerm(t Terminal)
{ c.Lock() defer c.Unlock() c.term = t }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/ctx.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/ctx.go#L428-L430
go
train
// SetEnv sets a environment variable within this context.
func (c *ServerContext) SetEnv(key, val string)
// SetEnv sets a environment variable within this context. func (c *ServerContext) SetEnv(key, val string)
{ c.env[key] = val }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/ctx.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/ctx.go#L433-L436
go
train
// GetEnv returns a environment variable within this context.
func (c *ServerContext) GetEnv(key string) (string, bool)
// GetEnv returns a environment variable within this context. func (c *ServerContext) GetEnv(key string) (string, bool)
{ val, ok := c.env[key] return val, ok }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/ctx.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/ctx.go#L440-L457
go
train
// takeClosers returns all resources that should be closed and sets the properties to null // we do this to avoid calling Close() under lock to avoid potential deadlocks
func (c *ServerContext) takeClosers() []io.Closer
// takeClosers returns all resources that should be closed and sets the properties to null // we do this to avoid calling Close() under lock to avoid potential deadlocks func (c *ServerContext) takeClosers() []io.Closer
{ // this is done to avoid any operation holding the lock for too long c.Lock() defer c.Unlock() closers := []io.Closer{} if c.term != nil { closers = append(closers, c.term) c.term = nil } if c.agentChannel != nil { closers = append(closers, c.agentChannel) c.agentChannel = nil } closers = append(closers, c.closers...) c.closers = nil return closers }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/ctx.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/ctx.go#L461-L497
go
train
// When the ServerContext (connection) is closed, emit "session.data" event // containing how much data was transmitted and received over the net.Conn.
func (c *ServerContext) reportStats(conn utils.Stater)
// When the ServerContext (connection) is closed, emit "session.data" event // containing how much data was transmitted and received over the net.Conn. func (c *ServerContext) reportStats(conn utils.Stater)
{ // Never emit session data events for the proxy or from a Teleport node if // sessions are being recorded at the proxy (this would result in double // events). if c.GetServer().Component() == teleport.ComponentProxy { return } if c.ClusterConfig.GetSessionRecording() == services.RecordAtProxy && c.GetServer().Component() == teleport.ComponentNode { return } // Get the TX and RX bytes. txBytes, rxBytes := conn.Stat() // Build and emit session data event. Note that TX and RX are reversed // below, that is because the connection is held from the perspective of // the server not the client, but the logs are from the perspective of the // client. eventFields := events.EventFields{ events.DataTransmitted: rxBytes, events.DataReceived: txBytes, events.SessionServerID: c.GetServer().ID(), events.EventLogin: c.Identity.Login, events.EventUser: c.Identity.TeleportUser, events.LocalAddr: c.Conn.LocalAddr().String(), events.RemoteAddr: c.Conn.RemoteAddr().String(), } if c.session != nil { eventFields[events.SessionEventID] = c.session.id } c.GetServer().GetAuditLog().EmitAuditEvent(events.SessionData, eventFields) // Emit TX and RX bytes to their respective Prometheus counters. serverTX.Add(float64(txBytes)) serverRX.Add(float64(rxBytes)) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/ctx.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/ctx.go#L520-L526
go
train
// SendExecResult sends the result of execution of the "exec" command over the // ExecResultCh.
func (c *ServerContext) SendExecResult(r ExecResult)
// SendExecResult sends the result of execution of the "exec" command over the // ExecResultCh. func (c *ServerContext) SendExecResult(r ExecResult)
{ select { case c.ExecResultCh <- r: default: log.Infof("blocked on sending exec result %v", r) } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/ctx.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/ctx.go#L530-L536
go
train
// SendSubsystemResult sends the result of running the subsystem over the // SubsystemResultCh.
func (c *ServerContext) SendSubsystemResult(r SubsystemResult)
// SendSubsystemResult sends the result of running the subsystem over the // SubsystemResultCh. func (c *ServerContext) SendSubsystemResult(r SubsystemResult)
{ select { case c.SubsystemResultCh <- r: default: c.Infof("blocked on sending subsystem result") } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/ctx.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/ctx.go#L541-L562
go
train
// ProxyPublicAddress tries to get the public address from the first // available proxy. if public_address is not set, fall back to the hostname // of the first proxy we get back.
func (c *ServerContext) ProxyPublicAddress() string
// ProxyPublicAddress tries to get the public address from the first // available proxy. if public_address is not set, fall back to the hostname // of the first proxy we get back. func (c *ServerContext) ProxyPublicAddress() string
{ proxyHost := "<proxyhost>:3080" if c.srv == nil { return proxyHost } proxies, err := c.srv.GetAccessPoint().GetProxies() if err != nil { c.Errorf("Unable to retrieve proxy list: %v", err) } if len(proxies) > 0 { proxyHost = proxies[0].GetPublicAddr() if proxyHost == "" { proxyHost = fmt.Sprintf("%v:%v", proxies[0].GetHostname(), defaults.HTTPListenPort) c.Debugf("public_address not set for proxy, returning proxyHost: %q", proxyHost) } } return proxyHost }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/ctx.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/ctx.go#L595-L597
go
train
// NewTrackingReader returns a new instance of // activity tracking reader.
func NewTrackingReader(ctx *ServerContext, r io.Reader) *TrackingReader
// NewTrackingReader returns a new instance of // activity tracking reader. func NewTrackingReader(ctx *ServerContext, r io.Reader) *TrackingReader
{ return &TrackingReader{ctx: ctx, r: r} }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/ctx.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/ctx.go#L609-L612
go
train
// Read passes the read through to internal // reader, and updates activity of the server context
func (a *TrackingReader) Read(b []byte) (int, error)
// Read passes the read through to internal // reader, and updates activity of the server context func (a *TrackingReader) Read(b []byte) (int, error)
{ a.ctx.UpdateClientActivity() return a.r.Read(b) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/pam/config.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/pam/config.go#L53-L71
go
train
// CheckDefaults makes sure the Config structure has minimum required values.
func (c *Config) CheckDefaults() error
// CheckDefaults makes sure the Config structure has minimum required values. func (c *Config) CheckDefaults() error
{ if c.ServiceName == "" { return trace.BadParameter("required parameter ServiceName missing") } if c.Username == "" { return trace.BadParameter("required parameter Username missing") } if c.Stdin == nil { return trace.BadParameter("required parameter Stdin missing") } if c.Stdout == nil { return trace.BadParameter("required parameter Stdout missing") } if c.Stderr == nil { return trace.BadParameter("required parameter Stderr missing") } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/permissions.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/permissions.go#L31-L37
go
train
// NewAdminContext returns new admin auth context
func NewAdminContext() (*AuthContext, error)
// NewAdminContext returns new admin auth context func NewAdminContext() (*AuthContext, error)
{ authContext, err := contextForBuiltinRole("", nil, teleport.RoleAdmin, fmt.Sprintf("%v", teleport.RoleAdmin)) if err != nil { return nil, trace.Wrap(err) } return authContext, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/permissions.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/permissions.go#L40-L46
go
train
// NewRoleAuthorizer authorizes everyone as predefined role, used in tests
func NewRoleAuthorizer(clusterName string, clusterConfig services.ClusterConfig, r teleport.Role) (Authorizer, error)
// NewRoleAuthorizer authorizes everyone as predefined role, used in tests func NewRoleAuthorizer(clusterName string, clusterConfig services.ClusterConfig, r teleport.Role) (Authorizer, error)
{ authContext, err := contextForBuiltinRole(clusterName, clusterConfig, r, fmt.Sprintf("%v", r)) if err != nil { return nil, trace.Wrap(err) } return &contextAuthorizer{authContext: *authContext}, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/permissions.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/permissions.go#L55-L57
go
train
// Authorize authorizes user based on identity supplied via context
func (r *contextAuthorizer) Authorize(ctx context.Context) (*AuthContext, error)
// Authorize authorizes user based on identity supplied via context func (r *contextAuthorizer) Authorize(ctx context.Context) (*AuthContext, error)
{ return &r.authContext, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/permissions.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/permissions.go#L60-L66
go
train
// NewUserAuthorizer authorizes everyone as predefined local user
func NewUserAuthorizer(username string, identity services.UserGetter, access services.Access) (Authorizer, error)
// NewUserAuthorizer authorizes everyone as predefined local user func NewUserAuthorizer(username string, identity services.UserGetter, access services.Access) (Authorizer, error)
{ authContext, err := contextForLocalUser(username, identity, access) if err != nil { return nil, trace.Wrap(err) } return &contextAuthorizer{authContext: *authContext}, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/permissions.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/permissions.go#L69-L80
go
train
// NewAuthorizer returns new authorizer using backends
func NewAuthorizer(access services.Access, identity services.UserGetter, trust services.Trust) (Authorizer, error)
// NewAuthorizer returns new authorizer using backends func NewAuthorizer(access services.Access, identity services.UserGetter, trust services.Trust) (Authorizer, error)
{ if access == nil { return nil, trace.BadParameter("missing parameter access") } if identity == nil { return nil, trace.BadParameter("missing parameter identity") } if trust == nil { return nil, trace.BadParameter("missing parameter trust") } return &authorizer{access: access, identity: identity, trust: trust}, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/permissions.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/permissions.go#L104-L121
go
train
// Authorize authorizes user based on identity supplied via context
func (a *authorizer) Authorize(ctx context.Context) (*AuthContext, error)
// Authorize authorizes user based on identity supplied via context func (a *authorizer) Authorize(ctx context.Context) (*AuthContext, error)
{ if ctx == nil { return nil, trace.AccessDenied("missing authentication context") } userI := ctx.Value(ContextUser) switch user := userI.(type) { case LocalUser: return a.authorizeLocalUser(user) case RemoteUser: return a.authorizeRemoteUser(user) case BuiltinRole: return a.authorizeBuiltinRole(user) case RemoteBuiltinRole: return a.authorizeRemoteBuiltinRole(user) default: return nil, trace.AccessDenied("unsupported context type %T", userI) } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/permissions.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/permissions.go#L124-L126
go
train
// authorizeLocalUser returns authz context based on the username
func (a *authorizer) authorizeLocalUser(u LocalUser) (*AuthContext, error)
// authorizeLocalUser returns authz context based on the username func (a *authorizer) authorizeLocalUser(u LocalUser) (*AuthContext, error)
{ return contextForLocalUser(u.Username, a.identity, a.access) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/permissions.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/permissions.go#L129-L170
go
train
// authorizeRemoteUser returns checker based on cert authority roles
func (a *authorizer) authorizeRemoteUser(u RemoteUser) (*AuthContext, error)
// authorizeRemoteUser returns checker based on cert authority roles func (a *authorizer) authorizeRemoteUser(u RemoteUser) (*AuthContext, error)
{ ca, err := a.trust.GetCertAuthority(services.CertAuthID{Type: services.UserCA, DomainName: u.ClusterName}, false) if err != nil { return nil, trace.Wrap(err) } roleNames, err := ca.CombinedMapping().Map(u.RemoteRoles) if err != nil { return nil, trace.AccessDenied("failed to map roles for remote user %q from cluster %q", u.Username, u.ClusterName) } if len(roleNames) == 0 { return nil, trace.AccessDenied("no roles mapped for remote user %q from cluster %q", u.Username, u.ClusterName) } // Set "logins" trait and "kubernetes_groups" for the remote user. This allows Teleport to work by // passing exact logins and kubernetes groups to the remote cluster. Note that claims (OIDC/SAML) // are not passed, but rather the exact logins, this is done to prevent // leaking too much of identity to the remote cluster, and instead of focus // on main cluster's interpretation of this identity traits := map[string][]string{ teleport.TraitLogins: u.Principals, teleport.TraitKubeGroups: u.KubernetesGroups, } log.Debugf("Mapped roles %v of remote user %q to local roles %v and traits %v.", u.RemoteRoles, u.Username, roleNames, traits) checker, err := services.FetchRoles(roleNames, a.access, traits) if err != nil { return nil, trace.Wrap(err) } // The user is prefixed with "remote-" and suffixed with cluster name with // the hope that it does not match a real local user. user, err := services.NewUser(fmt.Sprintf("remote-%v-%v", u.Username, u.ClusterName)) if err != nil { return nil, trace.Wrap(err) } user.SetTraits(traits) // Set the list of roles this user has in the remote cluster. user.SetRoles(roleNames) return &AuthContext{ User: user, Checker: checker, }, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/permissions.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/permissions.go#L173-L179
go
train
// authorizeBuiltinRole authorizes builtin role
func (a *authorizer) authorizeBuiltinRole(r BuiltinRole) (*AuthContext, error)
// authorizeBuiltinRole authorizes builtin role func (a *authorizer) authorizeBuiltinRole(r BuiltinRole) (*AuthContext, error)
{ config, err := r.GetClusterConfig() if err != nil { return nil, trace.Wrap(err) } return contextForBuiltinRole(r.ClusterName, config, r.Role, r.Username) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/permissions.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/permissions.go#L230-L428
go
train
// GetCheckerForBuiltinRole returns checkers for embedded builtin role
func GetCheckerForBuiltinRole(clusterName string, clusterConfig services.ClusterConfig, role teleport.Role) (services.RoleSet, error)
// GetCheckerForBuiltinRole returns checkers for embedded builtin role func GetCheckerForBuiltinRole(clusterName string, clusterConfig services.ClusterConfig, role teleport.Role) (services.RoleSet, error)
{ switch role { case teleport.RoleAuth: return services.FromSpec( role.String(), services.RoleSpecV3{ Allow: services.RoleConditions{ Namespaces: []string{services.Wildcard}, Rules: []services.Rule{ services.NewRule(services.KindAuthServer, services.RW()), }, }, }) case teleport.RoleProvisionToken: return services.FromSpec(role.String(), services.RoleSpecV3{}) case teleport.RoleNode: return services.FromSpec( role.String(), services.RoleSpecV3{ Allow: services.RoleConditions{ Namespaces: []string{services.Wildcard}, Rules: []services.Rule{ services.NewRule(services.KindNode, services.RW()), services.NewRule(services.KindSSHSession, services.RW()), services.NewRule(services.KindEvent, services.RW()), services.NewRule(services.KindProxy, services.RO()), services.NewRule(services.KindCertAuthority, services.ReadNoSecrets()), services.NewRule(services.KindUser, services.RO()), services.NewRule(services.KindNamespace, services.RO()), services.NewRule(services.KindRole, services.RO()), services.NewRule(services.KindAuthServer, services.RO()), services.NewRule(services.KindReverseTunnel, services.RW()), services.NewRule(services.KindTunnelConnection, services.RO()), services.NewRule(services.KindClusterConfig, services.RO()), }, }, }) case teleport.RoleProxy: // if in recording mode, return a different set of permissions than regular // mode. recording proxy needs to be able to generate host certificates. if clusterConfig.GetSessionRecording() == services.RecordAtProxy { return services.FromSpec( role.String(), services.RoleSpecV3{ Allow: services.RoleConditions{ Namespaces: []string{services.Wildcard}, Rules: []services.Rule{ services.NewRule(services.KindProxy, services.RW()), services.NewRule(services.KindOIDCRequest, services.RW()), services.NewRule(services.KindSSHSession, services.RW()), services.NewRule(services.KindSession, services.RO()), services.NewRule(services.KindEvent, services.RW()), services.NewRule(services.KindSAMLRequest, services.RW()), services.NewRule(services.KindOIDC, services.ReadNoSecrets()), services.NewRule(services.KindSAML, services.ReadNoSecrets()), services.NewRule(services.KindGithub, services.ReadNoSecrets()), services.NewRule(services.KindGithubRequest, services.RW()), services.NewRule(services.KindNamespace, services.RO()), services.NewRule(services.KindNode, services.RO()), services.NewRule(services.KindAuthServer, services.RO()), services.NewRule(services.KindReverseTunnel, services.RO()), services.NewRule(services.KindCertAuthority, services.ReadNoSecrets()), services.NewRule(services.KindUser, services.RO()), services.NewRule(services.KindRole, services.RO()), services.NewRule(services.KindClusterAuthPreference, services.RO()), services.NewRule(services.KindClusterConfig, services.RO()), services.NewRule(services.KindClusterName, services.RO()), services.NewRule(services.KindStaticTokens, services.RO()), services.NewRule(services.KindTunnelConnection, services.RW()), services.NewRule(services.KindHostCert, services.RW()), services.NewRule(services.KindRemoteCluster, services.RO()), // this rule allows local proxy to update the remote cluster's host certificate authorities // during certificates renewal { Resources: []string{services.KindCertAuthority}, Verbs: []string{services.VerbCreate, services.VerbRead, services.VerbUpdate}, // allow administrative access to the host certificate authorities // matching any cluster name except local Where: builder.And( builder.Equals(services.CertAuthorityTypeExpr, builder.String(string(services.HostCA))), builder.Not( builder.Equals( services.ResourceNameExpr, builder.String(clusterName), ), ), ).String(), }, }, }, }) } return services.FromSpec( role.String(), services.RoleSpecV3{ Allow: services.RoleConditions{ Namespaces: []string{services.Wildcard}, Rules: []services.Rule{ services.NewRule(services.KindProxy, services.RW()), services.NewRule(services.KindOIDCRequest, services.RW()), services.NewRule(services.KindSSHSession, services.RW()), services.NewRule(services.KindSession, services.RO()), services.NewRule(services.KindEvent, services.RW()), services.NewRule(services.KindSAMLRequest, services.RW()), services.NewRule(services.KindOIDC, services.ReadNoSecrets()), services.NewRule(services.KindSAML, services.ReadNoSecrets()), services.NewRule(services.KindGithub, services.ReadNoSecrets()), services.NewRule(services.KindGithubRequest, services.RW()), services.NewRule(services.KindNamespace, services.RO()), services.NewRule(services.KindNode, services.RO()), services.NewRule(services.KindAuthServer, services.RO()), services.NewRule(services.KindReverseTunnel, services.RO()), services.NewRule(services.KindCertAuthority, services.ReadNoSecrets()), services.NewRule(services.KindUser, services.RO()), services.NewRule(services.KindRole, services.RO()), services.NewRule(services.KindClusterAuthPreference, services.RO()), services.NewRule(services.KindClusterConfig, services.RO()), services.NewRule(services.KindClusterName, services.RO()), services.NewRule(services.KindStaticTokens, services.RO()), services.NewRule(services.KindTunnelConnection, services.RW()), services.NewRule(services.KindRemoteCluster, services.RO()), // this rule allows local proxy to update the remote cluster's host certificate authorities // during certificates renewal { Resources: []string{services.KindCertAuthority}, Verbs: []string{services.VerbCreate, services.VerbRead, services.VerbUpdate}, // allow administrative access to the certificate authority names // matching any cluster name except local Where: builder.And( builder.Equals(services.CertAuthorityTypeExpr, builder.String(string(services.HostCA))), builder.Not( builder.Equals( services.ResourceNameExpr, builder.String(clusterName), ), ), ).String(), }, }, }, }) case teleport.RoleWeb: return services.FromSpec( role.String(), services.RoleSpecV3{ Allow: services.RoleConditions{ Namespaces: []string{services.Wildcard}, Rules: []services.Rule{ services.NewRule(services.KindWebSession, services.RW()), services.NewRule(services.KindSSHSession, services.RW()), services.NewRule(services.KindAuthServer, services.RO()), services.NewRule(services.KindUser, services.RO()), services.NewRule(services.KindRole, services.RO()), services.NewRule(services.KindNamespace, services.RO()), services.NewRule(services.KindTrustedCluster, services.RO()), }, }, }) case teleport.RoleSignup: return services.FromSpec( role.String(), services.RoleSpecV3{ Allow: services.RoleConditions{ Namespaces: []string{services.Wildcard}, Rules: []services.Rule{ services.NewRule(services.KindAuthServer, services.RO()), services.NewRule(services.KindClusterAuthPreference, services.RO()), }, }, }) case teleport.RoleAdmin: return services.FromSpec( role.String(), services.RoleSpecV3{ Options: services.RoleOptions{ MaxSessionTTL: services.MaxDuration(), }, Allow: services.RoleConditions{ Namespaces: []string{services.Wildcard}, Logins: []string{}, NodeLabels: services.Labels{services.Wildcard: []string{services.Wildcard}}, Rules: []services.Rule{ services.NewRule(services.Wildcard, services.RW()), }, }, }) case teleport.RoleNop: return services.FromSpec( role.String(), services.RoleSpecV3{ Allow: services.RoleConditions{ Namespaces: []string{}, Rules: []services.Rule{}, }, }) } return nil, trace.NotFound("%v is not reconginzed", role.String()) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/user_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/user_command.go#L57-L84
go
train
// Initialize allows UserCommand to plug itself into the CLI parser
func (u *UserCommand) Initialize(app *kingpin.Application, config *service.Config)
// Initialize allows UserCommand to plug itself into the CLI parser func (u *UserCommand) Initialize(app *kingpin.Application, config *service.Config)
{ u.config = config users := app.Command("users", "Manage user accounts") u.userAdd = users.Command("add", "Generate a user invitation token") u.userAdd.Arg("account", "Teleport user account name").Required().StringVar(&u.login) u.userAdd.Arg("local-logins", "Local UNIX users this account can log in as [login]"). Default("").StringVar(&u.allowedLogins) u.userAdd.Flag("k8s-groups", "Kubernetes groups to assign to a user."). Default("").StringVar(&u.kubeGroups) u.userAdd.Flag("ttl", fmt.Sprintf("Set expiration time for token, default is %v hour, maximum is %v hours", int(defaults.SignupTokenTTL/time.Hour), int(defaults.MaxSignupTokenTTL/time.Hour))). Default(fmt.Sprintf("%v", defaults.SignupTokenTTL)).DurationVar(&u.ttl) u.userAdd.Flag("format", "Output format, 'text' or 'json'").Hidden().Default(teleport.Text).StringVar(&u.format) u.userAdd.Alias(AddUserHelp) u.userUpdate = users.Command("update", "Update properties for existing user").Hidden() u.userUpdate.Arg("login", "Teleport user login").Required().StringVar(&u.login) u.userUpdate.Flag("set-roles", "Roles to assign to this user"). Default("").StringVar(&u.roles) u.userList = users.Command("ls", "List all user accounts") u.userList.Flag("format", "Output format, 'text' or 'json'").Hidden().Default(teleport.Text).StringVar(&u.format) u.userDelete = users.Command("rm", "Deletes user accounts").Alias("del") u.userDelete.Arg("logins", "Comma-separated list of user logins to delete"). Required().StringVar(&u.login) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/user_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/user_command.go#L87-L101
go
train
// TryRun takes the CLI command as an argument (like "users add") and executes it.
func (u *UserCommand) TryRun(cmd string, client auth.ClientI) (match bool, err error)
// TryRun takes the CLI command as an argument (like "users add") and executes it. func (u *UserCommand) TryRun(cmd string, client auth.ClientI) (match bool, err error)
{ switch cmd { case u.userAdd.FullCommand(): err = u.Add(client) case u.userUpdate.FullCommand(): err = u.Update(client) case u.userList.FullCommand(): err = u.List(client) case u.userDelete.FullCommand(): err = u.Delete(client) default: return false, nil } return true, trace.Wrap(err) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/user_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/user_command.go#L105-L126
go
train
// Add creates a new sign-up token and prints a token URL to stdout. // A user is not created until he visits the sign-up URL and completes the process
func (u *UserCommand) Add(client auth.ClientI) error
// Add creates a new sign-up token and prints a token URL to stdout. // A user is not created until he visits the sign-up URL and completes the process func (u *UserCommand) Add(client auth.ClientI) error
{ // if no local logins were specified, default to 'login' if u.allowedLogins == "" { u.allowedLogins = u.login } var kubeGroups []string if u.kubeGroups != "" { kubeGroups = strings.Split(u.kubeGroups, ",") } user := services.UserV1{ Name: u.login, AllowedLogins: strings.Split(u.allowedLogins, ","), KubeGroups: kubeGroups, } token, err := client.CreateSignupToken(user, u.ttl) if err != nil { return err } // try to auto-suggest the activation link return u.PrintSignupURL(client, token, u.ttl, u.format) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/user_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/user_command.go#L129-L144
go
train
// PrintSignupURL prints signup URL
func (u *UserCommand) PrintSignupURL(client auth.ClientI, token string, ttl time.Duration, format string) error
// PrintSignupURL prints signup URL func (u *UserCommand) PrintSignupURL(client auth.ClientI, token string, ttl time.Duration, format string) error
{ signupURL, proxyHost := web.CreateSignupLink(client, token) if format == teleport.Text { fmt.Printf("Signup token has been created and is valid for %v hours. Share this URL with the user:\n%v\n\n", int(ttl/time.Hour), signupURL) fmt.Printf("NOTE: Make sure %v points at a Teleport proxy which users can access.\n", proxyHost) } else { out, err := json.MarshalIndent(services.NewInviteToken(token, signupURL, time.Now().Add(ttl).UTC()), "", " ") if err != nil { return trace.Wrap(err, "failed to marshal signup infos") } fmt.Printf(string(out)) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/user_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/user_command.go#L147-L164
go
train
// Update updates existing user
func (u *UserCommand) Update(client auth.ClientI) error
// Update updates existing user func (u *UserCommand) Update(client auth.ClientI) error
{ user, err := client.GetUser(u.login) if err != nil { return trace.Wrap(err) } roles := strings.Split(u.roles, ",") for _, role := range roles { if _, err := client.GetRole(role); err != nil { return trace.Wrap(err) } } user.SetRoles(roles) if err := client.UpsertUser(user); err != nil { return trace.Wrap(err) } fmt.Printf("%v has been updated with roles %v\n", user.GetName(), strings.Join(user.GetRoles(), ",")) return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/user_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/user_command.go#L167-L191
go
train
// List prints all existing user accounts
func (u *UserCommand) List(client auth.ClientI) error
// List prints all existing user accounts func (u *UserCommand) List(client auth.ClientI) error
{ users, err := client.GetUsers() if err != nil { return trace.Wrap(err) } if u.format == teleport.Text { if len(users) == 0 { fmt.Println("No users found") return nil } t := asciitable.MakeTable([]string{"User", "Allowed logins"}) for _, u := range users { logins, _ := u.GetTraits()[teleport.TraitLogins] t.AddRow([]string{u.GetName(), strings.Join(logins, ",")}) } fmt.Println(t.AsBuffer().String()) } else { out, err := json.MarshalIndent(users, "", " ") if err != nil { return trace.Wrap(err, "failed to marshal users") } fmt.Printf(string(out)) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/user_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/user_command.go#L195-L203
go
train
// Delete deletes teleport user(s). User IDs are passed as a comma-separated // list in UserCommand.login
func (u *UserCommand) Delete(client auth.ClientI) error
// Delete deletes teleport user(s). User IDs are passed as a comma-separated // list in UserCommand.login func (u *UserCommand) Delete(client auth.ClientI) error
{ for _, l := range strings.Split(u.login, ",") { if err := client.DeleteUser(l); err != nil { return trace.Wrap(err) } fmt.Printf("User '%v' has been deleted\n", l) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/teleagent/agent.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/teleagent/agent.go#L30-L46
go
train
// ListenUnixSocket starts listening and serving agent assuming that
func (a *AgentServer) ListenUnixSocket(path string, uid, gid int, mode os.FileMode) error
// ListenUnixSocket starts listening and serving agent assuming that func (a *AgentServer) ListenUnixSocket(path string, uid, gid int, mode os.FileMode) error
{ l, err := net.Listen("unix", path) if err != nil { return trace.Wrap(err) } if err := os.Chown(path, uid, gid); err != nil { l.Close() return trace.ConvertSystemError(err) } if err := os.Chmod(path, mode); err != nil { l.Close() return trace.ConvertSystemError(err) } a.listener = l a.path = path return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/teleagent/agent.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/teleagent/agent.go#L49-L88
go
train
// Serve starts serving on the listener, assumes that Listen was called before
func (a *AgentServer) Serve() error
// Serve starts serving on the listener, assumes that Listen was called before func (a *AgentServer) Serve() error
{ if a.listener == nil { return trace.BadParameter("Serve needs a Listen call first") } var tempDelay time.Duration // how long to sleep on accept failure for { conn, err := a.listener.Accept() if err != nil { neterr, ok := err.(net.Error) if !ok { return trace.Wrap(err, "unknown error") } if !neterr.Temporary() { if !strings.Contains(neterr.Error(), "use of closed network connection") { log.Errorf("got permanent error: %v", err) } return err } if tempDelay == 0 { tempDelay = 5 * time.Millisecond } else { tempDelay *= 2 } if max := 1 * time.Second; tempDelay > max { tempDelay = max } log.Errorf("got temp error: %v, will sleep %v", err, tempDelay) time.Sleep(tempDelay) continue } tempDelay = 0 go func() { if err := agent.ServeAgent(a.Agent, conn); err != nil { if err != io.EOF { log.Errorf(err.Error()) } } }() } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/teleagent/agent.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/teleagent/agent.go#L91-L98
go
train
// ListenAndServe is similar http.ListenAndServe
func (a *AgentServer) ListenAndServe(addr utils.NetAddr) error
// ListenAndServe is similar http.ListenAndServe func (a *AgentServer) ListenAndServe(addr utils.NetAddr) error
{ l, err := net.Listen(addr.AddrNetwork, addr.Addr) if err != nil { return trace.Wrap(err) } a.listener = l return a.Serve() }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/teleagent/agent.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/teleagent/agent.go#L101-L115
go
train
// Close closes listener and stops serving agent
func (a *AgentServer) Close() error
// Close closes listener and stops serving agent func (a *AgentServer) Close() error
{ var errors []error if a.listener != nil { log.Debugf("AgentServer(%v) is closing", a.listener.Addr()) if err := a.listener.Close(); err != nil { errors = append(errors, trace.ConvertSystemError(err)) } } if a.path != "" { if err := os.Remove(a.path); err != nil { errors = append(errors, trace.ConvertSystemError(err)) } } return trace.NewAggregate(errors...) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/httplib/csrf/csrf.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/httplib/csrf/csrf.go#L42-L53
go
train
// AddCSRFProtection adds CSRF token into the user session via secure cookie, // it implements "double submit cookie" approach to check against CSRF attacks // https://www.owasp.org/index.php/Cross-Site_Request_Forgery_%28CSRF%29_Prevention_Cheat_Sheet#Double_Submit_Cookie
func AddCSRFProtection(w http.ResponseWriter, r *http.Request) (string, error)
// AddCSRFProtection adds CSRF token into the user session via secure cookie, // it implements "double submit cookie" approach to check against CSRF attacks // https://www.owasp.org/index.php/Cross-Site_Request_Forgery_%28CSRF%29_Prevention_Cheat_Sheet#Double_Submit_Cookie func AddCSRFProtection(w http.ResponseWriter, r *http.Request) (string, error)
{ token, err := ExtractTokenFromCookie(r) // if there was an error retrieving the token, the token doesn't exist if err != nil || len(token) == 0 { token, err = utils.CryptoRandomHex(tokenLenBytes) if err != nil { return "", trace.Wrap(err) } } save(token, w) return token, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/httplib/csrf/csrf.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/httplib/csrf/csrf.go#L56-L68
go
train
// VerifyHTTPHeader checks if HTTP header value matches the cookie.
func VerifyHTTPHeader(r *http.Request) error
// VerifyHTTPHeader checks if HTTP header value matches the cookie. func VerifyHTTPHeader(r *http.Request) error
{ token := r.Header.Get(HeaderName) if len(token) == 0 { return trace.BadParameter("cannot retrieve CSRF token from HTTP header %q", HeaderName) } err := VerifyToken(token, r) if err != nil { return trace.Wrap(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/httplib/csrf/csrf.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/httplib/csrf/csrf.go#L71-L92
go
train
// VerifyToken validates given token based on HTTP request cookie
func VerifyToken(token string, r *http.Request) error
// VerifyToken validates given token based on HTTP request cookie func VerifyToken(token string, r *http.Request) error
{ realToken, err := ExtractTokenFromCookie(r) if err != nil { return trace.Wrap(err, "unable to extract CSRF token from cookie") } decodedTokenA, err := decode(token) if err != nil { return trace.Wrap(err, "unable to decode CSRF token") } decodedTokenB, err := decode(realToken) if err != nil { return trace.Wrap(err, "unable to decode cookie CSRF token") } if !compareTokens(decodedTokenA, decodedTokenB) { return trace.BadParameter("CSRF tokens do not match") } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/httplib/csrf/csrf.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/httplib/csrf/csrf.go#L95-L102
go
train
// ExtractTokenFromCookie retrieves a CSRF token from the session cookie.
func ExtractTokenFromCookie(r *http.Request) (string, error)
// ExtractTokenFromCookie retrieves a CSRF token from the session cookie. func ExtractTokenFromCookie(r *http.Request) (string, error)
{ cookie, err := r.Cookie(CookieName) if err != nil { return "", trace.Wrap(err) } return cookie.Value, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/httplib/csrf/csrf.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/httplib/csrf/csrf.go#L105-L116
go
train
// decode decodes a cookie using base64.
func decode(token string) ([]byte, error)
// decode decodes a cookie using base64. func decode(token string) ([]byte, error)
{ decoded, err := hex.DecodeString(token) if err != nil { return nil, trace.Wrap(err) } if len(decoded) != tokenLenBytes { return nil, trace.BadParameter("invalid CSRF token byte length, expected %v, got %v", tokenLenBytes, len(decoded)) } return decoded, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/httplib/csrf/csrf.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/httplib/csrf/csrf.go#L124-L138
go
train
// save stores encoded CSRF token in the session cookie.
func save(encodedToken string, w http.ResponseWriter) string
// save stores encoded CSRF token in the session cookie. func save(encodedToken string, w http.ResponseWriter) string
{ cookie := &http.Cookie{ Name: CookieName, Value: encodedToken, MaxAge: defaultMaxAge, HttpOnly: true, Secure: true, Path: "/", } // write the authenticated cookie to the response. http.SetCookie(w, cookie) w.Header().Add("Vary", "Cookie") return encodedToken }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/oidc.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/oidc.go#L128-L145
go
train
// ValidateOIDCAuthCallback is called by the proxy to check OIDC query parameters // returned by OIDC Provider, if everything checks out, auth server // will respond with OIDCAuthResponse, otherwise it will return error
func (a *AuthServer) ValidateOIDCAuthCallback(q url.Values) (*OIDCAuthResponse, error)
// ValidateOIDCAuthCallback is called by the proxy to check OIDC query parameters // returned by OIDC Provider, if everything checks out, auth server // will respond with OIDCAuthResponse, otherwise it will return error func (a *AuthServer) ValidateOIDCAuthCallback(q url.Values) (*OIDCAuthResponse, error)
{ re, err := a.validateOIDCAuthCallback(q) if err != nil { a.EmitAuditEvent(events.UserSSOLoginFailure, events.EventFields{ events.LoginMethod: events.LoginMethodOIDC, events.AuthAttemptSuccess: false, // log the original internal error in audit log events.AuthAttemptErr: trace.Unwrap(err).Error(), }) } else { a.EmitAuditEvent(events.UserSSOLogin, events.EventFields{ events.EventUser: re.Username, events.AuthAttemptSuccess: true, events.LoginMethod: events.LoginMethodOIDC, }) } return re, err }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/oidc.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/oidc.go#L301-L308
go
train
// buildOIDCRoles takes a connector and claims and returns a slice of roles.
func (a *AuthServer) buildOIDCRoles(connector services.OIDCConnector, claims jose.Claims) ([]string, error)
// buildOIDCRoles takes a connector and claims and returns a slice of roles. func (a *AuthServer) buildOIDCRoles(connector services.OIDCConnector, claims jose.Claims) ([]string, error)
{ roles := connector.MapClaims(claims) if len(roles) == 0 { return nil, trace.AccessDenied("unable to map claims to role for connector: %v", connector.GetName()) } return roles, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/oidc.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/oidc.go#L312-L327
go
train
// claimsToTraitMap extracts all string claims and creates a map of traits // that can be used to populate role variables.
func claimsToTraitMap(claims jose.Claims) map[string][]string
// claimsToTraitMap extracts all string claims and creates a map of traits // that can be used to populate role variables. func claimsToTraitMap(claims jose.Claims) map[string][]string
{ traits := make(map[string][]string) for claimName := range claims { claimValue, ok, _ := claims.StringClaim(claimName) if ok { traits[claimName] = []string{claimValue} } claimValues, ok, _ := claims.StringsClaim(claimName) if ok { traits[claimName] = claimValues } } return traits }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/oidc.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/oidc.go#L422-L441
go
train
// claimsFromIDToken extracts claims from the ID token.
func claimsFromIDToken(oidcClient *oidc.Client, idToken string) (jose.Claims, error)
// claimsFromIDToken extracts claims from the ID token. func claimsFromIDToken(oidcClient *oidc.Client, idToken string) (jose.Claims, error)
{ jwt, err := jose.ParseJWT(idToken) if err != nil { return nil, trace.Wrap(err) } err = oidcClient.VerifyJWT(jwt) if err != nil { return nil, trace.Wrap(err) } log.Debugf("Extracting OIDC claims from ID token.") claims, err := jwt.Claims() if err != nil { return nil, trace.Wrap(err) } return claims, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/oidc.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/oidc.go#L448-L500
go
train
// claimsFromUserInfo finds the UserInfo endpoint from the provider config and then extracts claims from it. // // Note: We don't request signed JWT responses for UserInfo, instead we force the provider config and // the issuer to be HTTPS and leave integrity and confidentiality to TLS. Authenticity is taken care of // during the token exchange.
func claimsFromUserInfo(oidcClient *oidc.Client, issuerURL string, accessToken string) (jose.Claims, error)
// claimsFromUserInfo finds the UserInfo endpoint from the provider config and then extracts claims from it. // // Note: We don't request signed JWT responses for UserInfo, instead we force the provider config and // the issuer to be HTTPS and leave integrity and confidentiality to TLS. Authenticity is taken care of // during the token exchange. func claimsFromUserInfo(oidcClient *oidc.Client, issuerURL string, accessToken string) (jose.Claims, error)
{ err := isHTTPS(issuerURL) if err != nil { return nil, trace.Wrap(err) } oac, err := oidcClient.OAuthClient() if err != nil { return nil, trace.Wrap(err) } hc := oac.HttpClient() // go get the provider config so we can find out where the UserInfo endpoint // is. if the provider doesn't offer a UserInfo endpoint return not found. pc, err := oidc.FetchProviderConfig(oac.HttpClient(), issuerURL) if err != nil { return nil, trace.Wrap(err) } if pc.UserInfoEndpoint == nil { return nil, trace.NotFound("UserInfo endpoint not found") } endpoint := pc.UserInfoEndpoint.String() err = isHTTPS(endpoint) if err != nil { return nil, trace.Wrap(err) } log.Debugf("Fetching OIDC claims from UserInfo endpoint: %q.", endpoint) req, err := http.NewRequest("GET", endpoint, nil) if err != nil { return nil, trace.Wrap(err) } req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", accessToken)) resp, err := hc.Do(req) if err != nil { return nil, trace.Wrap(err) } defer resp.Body.Close() if resp.StatusCode < 200 || resp.StatusCode > 299 { return nil, trace.AccessDenied("bad status code: %v", resp.StatusCode) } var claims jose.Claims err = json.NewDecoder(resp.Body).Decode(&claims) if err != nil { return nil, trace.Wrap(err) } return claims, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/oidc.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/oidc.go#L545-L575
go
train
// fetchGroups fetches GSuite groups a user belongs to and returns // "groups" claim with
func (g *gsuiteClient) fetchGroups() (jose.Claims, error)
// fetchGroups fetches GSuite groups a user belongs to and returns // "groups" claim with func (g *gsuiteClient) fetchGroups() (jose.Claims, error)
{ count := 0 var groups []string var nextPageToken string collect: for { if count > MaxPages { warningMessage := "Truncating list of teams used to populate claims: " + "hit maximum number pages that can be fetched from GSuite." // Print warning to Teleport logs as well as the Audit Log. log.Warnf(warningMessage) g.auditLog.EmitAuditEvent(events.UserSSOLoginFailure, events.EventFields{ events.LoginMethod: events.LoginMethodOIDC, events.AuthAttemptMessage: warningMessage, }) break collect } response, err := g.fetchGroupsPage(nextPageToken) if err != nil { return nil, trace.Wrap(err) } groups = append(groups, response.groups()...) if response.NextPageToken == "" { break collect } count++ nextPageToken = response.NextPageToken } return jose.Claims{"groups": groups}, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/oidc.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/oidc.go#L635-L644
go
train
// mergeClaims merges b into a.
func mergeClaims(a jose.Claims, b jose.Claims) (jose.Claims, error)
// mergeClaims merges b into a. func mergeClaims(a jose.Claims, b jose.Claims) (jose.Claims, error)
{ for k, v := range b { _, ok := a[k] if !ok { a[k] = v } } return a, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/oidc.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/oidc.go#L647-L728
go
train
// getClaims gets claims from ID token and UserInfo and returns UserInfo claims merged into ID token claims.
func (a *AuthServer) getClaims(oidcClient *oidc.Client, issuerURL string, scope []string, code string) (jose.Claims, error)
// getClaims gets claims from ID token and UserInfo and returns UserInfo claims merged into ID token claims. func (a *AuthServer) getClaims(oidcClient *oidc.Client, issuerURL string, scope []string, code string) (jose.Claims, error)
{ var err error oac, err := oidcClient.OAuthClient() if err != nil { return nil, trace.Wrap(err) } t, err := oac.RequestToken(oauth2.GrantTypeAuthCode, code) if err != nil { return nil, trace.Wrap(err) } idTokenClaims, err := claimsFromIDToken(oidcClient, t.IDToken) if err != nil { log.Debugf("Unable to fetch OIDC ID token claims: %v.", err) return nil, trace.Wrap(err) } log.Debugf("OIDC ID Token claims: %v.", idTokenClaims) userInfoClaims, err := claimsFromUserInfo(oidcClient, issuerURL, t.AccessToken) if err != nil { if trace.IsNotFound(err) { log.Debugf("OIDC provider doesn't offer UserInfo endpoint. Returning token claims: %v.", idTokenClaims) return idTokenClaims, nil } log.Debugf("Unable to fetch UserInfo claims: %v.", err) return nil, trace.Wrap(err) } log.Debugf("UserInfo claims: %v.", userInfoClaims) // make sure that the subject in the userinfo claim matches the subject in // the id token otherwise there is the possibility of a token substitution attack. // see section 16.11 of the oidc spec for more details. var idsub string var uisub string var exists bool if idsub, exists, err = idTokenClaims.StringClaim("sub"); err != nil || !exists { log.Debugf("Unable to extract OIDC sub claim from ID token.") return nil, trace.Wrap(err) } if uisub, exists, err = userInfoClaims.StringClaim("sub"); err != nil || !exists { log.Debugf("Unable to extract OIDC sub claim from UserInfo.") return nil, trace.Wrap(err) } if idsub != uisub { log.Debugf("OIDC claim subjects don't match '%v' != '%v'.", idsub, uisub) return nil, trace.BadParameter("invalid subject in UserInfo") } claims, err := mergeClaims(idTokenClaims, userInfoClaims) if err != nil { log.Debugf("Unable to merge OIDC claims: %v.", err) return nil, trace.Wrap(err) } // for GSuite users, fetch extra data from the proprietary google API // only if scope includes admin groups readonly scope if issuerURL == teleport.GSuiteIssuerURL && utils.SliceContainsStr(scope, teleport.GSuiteGroupsScope) { email, _, err := claims.StringClaim("email") if err != nil { return nil, trace.Wrap(err) } gsuiteClaims, err := a.claimsFromGSuite(oidcClient, issuerURL, email, t.AccessToken) if err != nil { if !trace.IsNotFound(err) { return nil, trace.Wrap(err) } log.Debugf("Found no GSuite claims.") } else { if gsuiteClaims != nil { log.Debugf("Got GSuiteclaims: %v.", gsuiteClaims) } claims, err = mergeClaims(claims, gsuiteClaims) if err != nil { return nil, trace.Wrap(err) } } } return claims, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/oidc.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/oidc.go#L733-L787
go
train
// validateACRValues validates that we get an appropriate response for acr values. By default // we expect the same value we send, but this function also handles Identity Provider specific // forms of validation.
func (a *AuthServer) validateACRValues(acrValue string, identityProvider string, claims jose.Claims) error
// validateACRValues validates that we get an appropriate response for acr values. By default // we expect the same value we send, but this function also handles Identity Provider specific // forms of validation. func (a *AuthServer) validateACRValues(acrValue string, identityProvider string, claims jose.Claims) error
{ switch identityProvider { case teleport.NetIQ: log.Debugf("Validating OIDC ACR values with '%v' rules.", identityProvider) tokenAcr, ok := claims["acr"] if !ok { return trace.BadParameter("acr not found in claims") } tokenAcrMap, ok := tokenAcr.(map[string]interface{}) if !ok { return trace.BadParameter("acr unexpected type: %T", tokenAcr) } tokenAcrValues, ok := tokenAcrMap["values"] if !ok { return trace.BadParameter("acr.values not found in claims") } tokenAcrValuesSlice, ok := tokenAcrValues.([]interface{}) if !ok { return trace.BadParameter("acr.values unexpected type: %T", tokenAcr) } acrValueMatched := false for _, v := range tokenAcrValuesSlice { vv, ok := v.(string) if !ok { continue } if acrValue == vv { acrValueMatched = true break } } if !acrValueMatched { log.Debugf("No OIDC ACR match found for '%v' in '%v'.", acrValue, tokenAcrValues) return trace.BadParameter("acr claim does not match") } default: log.Debugf("Validating OIDC ACR values with default rules.") claimValue, exists, err := claims.StringClaim("acr") if !exists { return trace.BadParameter("acr claim does not exist") } if err != nil { return trace.Wrap(err) } if claimValue != acrValue { log.Debugf("No OIDC ACR match found '%v' != '%v'.", acrValue, claimValue) return trace.BadParameter("acr claim does not match") } } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/bench.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/bench.go#L60-L147
go
train
// Benchmark connects to remote server and executes requests in parallel according // to benchmark spec. It returns benchmark result when completed. // This is a blocking function that can be cancelled via context argument.
func (tc *TeleportClient) Benchmark(ctx context.Context, bench Benchmark) (*BenchmarkResult, error)
// Benchmark connects to remote server and executes requests in parallel according // to benchmark spec. It returns benchmark result when completed. // This is a blocking function that can be cancelled via context argument. func (tc *TeleportClient) Benchmark(ctx context.Context, bench Benchmark) (*BenchmarkResult, error)
{ tc.Stdout = ioutil.Discard tc.Stderr = ioutil.Discard tc.Stdin = &bytes.Buffer{} ctx, cancel := context.WithTimeout(ctx, bench.Duration) defer cancel() requestC := make(chan *benchMeasure) responseC := make(chan *benchMeasure, bench.Threads) // create goroutines for concurrency for i := 0; i < bench.Threads; i++ { thread := &benchmarkThread{ id: i, ctx: ctx, client: tc, command: bench.Command, interactive: bench.Interactive, receiveC: requestC, sendC: responseC, } go thread.run() } // producer goroutine go func() { interval := time.Duration(float64(1) / float64(bench.Rate) * float64(time.Second)) ticker := time.NewTicker(interval) defer ticker.Stop() for { select { case <-ticker.C: // notice how we start the timer regardless of whether any goroutine can process it // this is to account for coordinated omission, // http://psy-lob-saw.blogspot.com/2015/03/fixing-ycsb-coordinated-omission.html measure := &benchMeasure{ Start: time.Now(), } select { case requestC <- measure: case <-ctx.Done(): return } case <-ctx.Done(): return } } }() var result BenchmarkResult // from one millisecond to 60000 milliseconds (minute) with 3 digits precision result.Histogram = hdrhistogram.New(1, 60000, 3) var doneThreads int var timeoutC <-chan time.Time doneC := ctx.Done() for { select { case <-timeoutC: result.LastError = trace.BadParameter("several requests hang: timeout waiting for %v threads to finish", bench.Threads-doneThreads) return &result, nil case <-doneC: // give it a couple of seconds to wrap up the goroutines, // set up the timer that will fire up if the all goroutines were not finished doneC = nil waitTime := time.Duration(result.Histogram.Max()) * time.Millisecond // going to wait latency + buffer to give requests in flight to wrap up waitTime = time.Duration(1.2 * float64(waitTime)) timeoutC = time.After(waitTime) case measure := <-responseC: if measure.ThreadCompleted { doneThreads += 1 if doneThreads == bench.Threads { return &result, nil } } else { if measure.Error != nil { result.RequestsFailed += 1 result.LastError = measure.Error } result.RequestsOriginated += 1 result.Histogram.RecordValue(int64(measure.End.Sub(measure.Start) / time.Millisecond)) } } } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/conn.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/conn.go#L33-L38
go
train
// NewCloserConn returns new connection wrapper that // when closed will also close passed closers
func NewCloserConn(conn net.Conn, closers ...io.Closer) *CloserConn
// NewCloserConn returns new connection wrapper that // when closed will also close passed closers func NewCloserConn(conn net.Conn, closers ...io.Closer) *CloserConn
{ return &CloserConn{ Conn: conn, closers: closers, } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/conn.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/conn.go#L48-L50
go
train
// AddCloser adds any closer in ctx that will be called // whenever server closes session channel
func (c *CloserConn) AddCloser(closer io.Closer)
// AddCloser adds any closer in ctx that will be called // whenever server closes session channel func (c *CloserConn) AddCloser(closer io.Closer)
{ c.closers = append(c.closers, closer) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/conn.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/conn.go#L64-L71
go
train
// Roundtrip is a single connection simplistic HTTP client // that allows us to bypass a connection pool to test load balancing // used in tests, as it only supports GET request on /
func Roundtrip(addr string) (string, error)
// Roundtrip is a single connection simplistic HTTP client // that allows us to bypass a connection pool to test load balancing // used in tests, as it only supports GET request on / func Roundtrip(addr string) (string, error)
{ conn, err := net.Dial("tcp", addr) if err != nil { return "", err } defer conn.Close() return RoundtripWithConn(conn) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/conn.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/conn.go#L75-L91
go
train
// RoundtripWithConn uses HTTP GET on the existing connection, // used in tests as it only performs GET request on /
func RoundtripWithConn(conn net.Conn) (string, error)
// RoundtripWithConn uses HTTP GET on the existing connection, // used in tests as it only performs GET request on / func RoundtripWithConn(conn net.Conn) (string, error)
{ _, err := fmt.Fprintf(conn, "GET / HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n") if err != nil { return "", err } re, err := http.ReadResponse(bufio.NewReader(conn), nil) if err != nil { return "", err } defer re.Body.Close() out, err := ioutil.ReadAll(re.Body) if err != nil { return "", err } return string(out), nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/conn.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/conn.go#L124-L126
go
train
// Stat returns the transmitted (TX) and received (RX) bytes over the net.Conn.
func (s *TrackingConn) Stat() (uint64, uint64)
// Stat returns the transmitted (TX) and received (RX) bytes over the net.Conn. func (s *TrackingConn) Stat() (uint64, uint64)
{ return atomic.LoadUint64(&s.txBytes), atomic.LoadUint64(&s.rxBytes) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/interfaces.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/interfaces.go#L62-L82
go
train
// TLSConfig returns client TLS configuration used // to authenticate against API servers
func (k *Key) ClientTLSConfig() (*tls.Config, error)
// TLSConfig returns client TLS configuration used // to authenticate against API servers func (k *Key) ClientTLSConfig() (*tls.Config, error)
{ // Because Teleport clients can't be configured (yet), they take the default // list of cipher suites from Go. tlsConfig := utils.TLSConfig(nil) pool := x509.NewCertPool() for _, ca := range k.TrustedCA { for _, certPEM := range ca.TLSCertificates { if !pool.AppendCertsFromPEM(certPEM) { return nil, trace.BadParameter("failed to parse certificate received from the proxy") } } } tlsConfig.RootCAs = pool tlsCert, err := tls.X509KeyPair(k.TLSCert, k.Priv) if err != nil { return nil, trace.Wrap(err, "failed to parse TLS cert and key") } tlsConfig.Certificates = append(tlsConfig.Certificates, tlsCert) return tlsConfig, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/interfaces.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/interfaces.go#L85-L95
go
train
// CertUsername returns the name of the Teleport user encoded in the SSH certificate.
func (k *Key) CertUsername() (string, error)
// CertUsername returns the name of the Teleport user encoded in the SSH certificate. func (k *Key) CertUsername() (string, error)
{ pubKey, _, _, _, err := ssh.ParseAuthorizedKey(k.Cert) if err != nil { return "", trace.Wrap(err) } cert, ok := pubKey.(*ssh.Certificate) if !ok { return "", trace.BadParameter("expected SSH certificate, got public key") } return cert.KeyId, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/interfaces.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/interfaces.go#L98-L108
go
train
// CertPrincipals returns the principals listed on the SSH certificate.
func (k *Key) CertPrincipals() ([]string, error)
// CertPrincipals returns the principals listed on the SSH certificate. func (k *Key) CertPrincipals() ([]string, error)
{ publicKey, _, _, _, err := ssh.ParseAuthorizedKey(k.Cert) if err != nil { return nil, trace.Wrap(err) } cert, ok := publicKey.(*ssh.Certificate) if !ok { return nil, trace.BadParameter("no certificate found") } return cert.ValidPrincipals, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/interfaces.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/interfaces.go#L112-L169
go
train
// AsAgentKeys converts client.Key struct to a []*agent.AddedKey. All elements // of the []*agent.AddedKey slice need to be loaded into the agent!
func (k *Key) AsAgentKeys() ([]*agent.AddedKey, error)
// AsAgentKeys converts client.Key struct to a []*agent.AddedKey. All elements // of the []*agent.AddedKey slice need to be loaded into the agent! func (k *Key) AsAgentKeys() ([]*agent.AddedKey, error)
{ // unmarshal certificate bytes into a ssh.PublicKey publicKey, _, _, _, err := ssh.ParseAuthorizedKey(k.Cert) if err != nil { return nil, trace.Wrap(err) } // unmarshal private key bytes into a *rsa.PrivateKey privateKey, err := ssh.ParseRawPrivateKey(k.Priv) if err != nil { return nil, trace.Wrap(err) } // put a teleport identifier along with the teleport user into the comment field comment := fmt.Sprintf("teleport:%v", publicKey.(*ssh.Certificate).KeyId) // On Windows, return the certificate with the private key embedded. if runtime.GOOS == teleport.WindowsOS { return []*agent.AddedKey{ &agent.AddedKey{ PrivateKey: privateKey, Certificate: publicKey.(*ssh.Certificate), Comment: comment, LifetimeSecs: 0, ConfirmBeforeUse: false, }, }, nil } // On Unix, return the certificate (with embedded private key) as well as // a private key. // // This is done because OpenSSH clients older than OpenSSH 7.3/7.3p1 // (2016-08-01) have a bug in how they use certificates that have been loaded // in an agent. Specifically when you add a certificate to an agent, you can't // just embed the private key within the certificate, you have to add the // certificate and private key to the agent separately. Teleport works around // this behavior to ensure OpenSSH interoperability. // // For more details see the following: https://bugzilla.mindrot.org/show_bug.cgi?id=2550 // WARNING: callers expect the returned slice to be __exactly as it is__ return []*agent.AddedKey{ &agent.AddedKey{ PrivateKey: privateKey, Certificate: publicKey.(*ssh.Certificate), Comment: comment, LifetimeSecs: 0, ConfirmBeforeUse: false, }, &agent.AddedKey{ PrivateKey: privateKey, Certificate: nil, Comment: comment, LifetimeSecs: 0, ConfirmBeforeUse: false, }, }, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/interfaces.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/interfaces.go#L173-L181
go
train
// EqualsTo returns true if this key is the same as the other. // Primarily used in tests
func (k *Key) EqualsTo(other *Key) bool
// EqualsTo returns true if this key is the same as the other. // Primarily used in tests func (k *Key) EqualsTo(other *Key) bool
{ if k == other { return true } return bytes.Equal(k.Cert, other.Cert) && bytes.Equal(k.Priv, other.Priv) && bytes.Equal(k.Pub, other.Pub) && bytes.Equal(k.TLSCert, other.TLSCert) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/interfaces.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/interfaces.go#L184-L190
go
train
// TLSCertValidBefore returns the time of the TLS cert expiration
func (k *Key) TLSCertValidBefore() (t time.Time, err error)
// TLSCertValidBefore returns the time of the TLS cert expiration func (k *Key) TLSCertValidBefore() (t time.Time, err error)
{ cert, err := tlsca.ParseCertificatePEM(k.TLSCert) if err != nil { return t, trace.Wrap(err) } return cert.NotAfter, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/interfaces.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/interfaces.go#L193-L203
go
train
// CertValidBefore returns the time of the cert expiration
func (k *Key) CertValidBefore() (t time.Time, err error)
// CertValidBefore returns the time of the cert expiration func (k *Key) CertValidBefore() (t time.Time, err error)
{ pcert, _, _, _, err := ssh.ParseAuthorizedKey(k.Cert) if err != nil { return t, trace.Wrap(err) } cert, ok := pcert.(*ssh.Certificate) if !ok { return t, trace.Errorf("not supported certificate type") } return time.Unix(int64(cert.ValidBefore), 0), nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/interfaces.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/interfaces.go#L208-L221
go
train
// AsAuthMethod returns an "auth method" interface, a common abstraction // used by Golang SSH library. This is how you actually use a Key to feed // it into the SSH lib.
func (k *Key) AsAuthMethod() (ssh.AuthMethod, error)
// AsAuthMethod returns an "auth method" interface, a common abstraction // used by Golang SSH library. This is how you actually use a Key to feed // it into the SSH lib. func (k *Key) AsAuthMethod() (ssh.AuthMethod, error)
{ keys, err := k.AsAgentKeys() if err != nil { return nil, trace.Wrap(err) } signer, err := ssh.NewSignerFromKey(keys[0].PrivateKey) if err != nil { return nil, trace.Wrap(err) } if signer, err = ssh.NewCertSigner(keys[0].Certificate, signer); err != nil { return nil, trace.Wrap(err) } return NewAuthMethodForCert(signer), nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/interfaces.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/interfaces.go#L224-L247
go
train
// CheckCert makes sure the SSH certificate is valid.
func (k *Key) CheckCert() error
// CheckCert makes sure the SSH certificate is valid. func (k *Key) CheckCert() error
{ key, _, _, _, err := ssh.ParseAuthorizedKey(k.Cert) if err != nil { return trace.Wrap(err) } cert, ok := key.(*ssh.Certificate) if !ok { return trace.BadParameter("found key, not certificate") } if len(cert.ValidPrincipals) == 0 { return trace.BadParameter("principals are required") } // A valid principal is always passed in because the principals are not being // checked here, but rather the validity period, signature, and algorithms. certChecker := utils.CertChecker{} err = certChecker.CheckCert(cert.ValidPrincipals[0], cert) if err != nil { return trace.Wrap(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/dynamo/shards.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/dynamo/shards.go#L202-L219
go
train
// collectActiveShards collects shards
func (b *DynamoDBBackend) collectActiveShards(ctx context.Context, streamArn *string) ([]*dynamodbstreams.Shard, error)
// collectActiveShards collects shards func (b *DynamoDBBackend) collectActiveShards(ctx context.Context, streamArn *string) ([]*dynamodbstreams.Shard, error)
{ var out []*dynamodbstreams.Shard input := &dynamodbstreams.DescribeStreamInput{ StreamArn: streamArn, } for { streamInfo, err := b.streams.DescribeStreamWithContext(ctx, input) if err != nil { return nil, convertError(err) } out = append(out, streamInfo.StreamDescription.Shards...) if streamInfo.StreamDescription.LastEvaluatedShardId == nil { return filterActiveShards(out), nil } input.ExclusiveStartShardId = streamInfo.StreamDescription.LastEvaluatedShardId } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/dynamo/dynamodbbk.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/dynamo/dynamodbbk.go#L73-L94
go
train
// CheckAndSetDefaults is a helper returns an error if the supplied configuration // is not enough to connect to DynamoDB
func (cfg *DynamoConfig) CheckAndSetDefaults() error
// CheckAndSetDefaults is a helper returns an error if the supplied configuration // is not enough to connect to DynamoDB func (cfg *DynamoConfig) CheckAndSetDefaults() error
{ // table is not configured? if cfg.Tablename == "" { return trace.BadParameter("DynamoDB: table_name is not specified") } if cfg.ReadCapacityUnits == 0 { cfg.ReadCapacityUnits = DefaultReadCapacityUnits } if cfg.WriteCapacityUnits == 0 { cfg.WriteCapacityUnits = DefaultWriteCapacityUnits } if cfg.BufferSize == 0 { cfg.BufferSize = backend.DefaultBufferSize } if cfg.PollStreamPeriod == 0 { cfg.PollStreamPeriod = backend.DefaultPollStreamPeriod } if cfg.RetryPeriod == 0 { cfg.RetryPeriod = defaults.HighResPollingPeriod } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/dynamo/dynamodbbk.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/dynamo/dynamodbbk.go#L169-L265
go
train
// New returns new instance of DynamoDB backend. // It's an implementation of backend API's NewFunc
func New(ctx context.Context, params backend.Params) (*DynamoDBBackend, error)
// New returns new instance of DynamoDB backend. // It's an implementation of backend API's NewFunc func New(ctx context.Context, params backend.Params) (*DynamoDBBackend, error)
{ l := log.WithFields(log.Fields{trace.Component: BackendName}) var cfg *DynamoConfig err := utils.ObjectToStruct(params, &cfg) if err != nil { return nil, trace.BadParameter("DynamoDB configuration is invalid: %v", err) } l.Infof("Initializing backend. Table: %q, poll streams every %v.", cfg.Tablename, cfg.PollStreamPeriod) defer l.Debug("AWS session is created.") if err := cfg.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } buf, err := backend.NewCircularBuffer(ctx, cfg.BufferSize) if err != nil { return nil, trace.Wrap(err) } closeCtx, cancel := context.WithCancel(ctx) watchStarted, signalWatchStart := context.WithCancel(ctx) b := &DynamoDBBackend{ Entry: l, DynamoConfig: *cfg, clock: clockwork.NewRealClock(), buf: buf, ctx: closeCtx, cancel: cancel, watchStarted: watchStarted, signalWatchStart: signalWatchStart, } // create an AWS session using default SDK behavior, i.e. it will interpret // the environment and ~/.aws directory just like an AWS CLI tool would: sess, err := session.NewSessionWithOptions(session.Options{ SharedConfigState: session.SharedConfigEnable, }) if err != nil { return nil, trace.Wrap(err) } // override the default environment (region + credentials) with the values // from the YAML file: if cfg.Region != "" { sess.Config.Region = aws.String(cfg.Region) } if cfg.AccessKey != "" || cfg.SecretKey != "" { creds := credentials.NewStaticCredentials(cfg.AccessKey, cfg.SecretKey, "") sess.Config.Credentials = creds } // Increase the size of the connection pool. This substantially improves the // performance of Teleport under load as it reduces the number of TLS // handshakes performed. httpClient := &http.Client{ Transport: &http.Transport{ MaxIdleConns: defaults.HTTPMaxIdleConns, MaxIdleConnsPerHost: defaults.HTTPMaxIdleConnsPerHost, }, } sess.Config.HTTPClient = httpClient // create DynamoDB service: b.svc = dynamodb.New(sess) b.streams = dynamodbstreams.New(sess) // check if the table exists? ts, err := b.getTableStatus(ctx, b.Tablename) if err != nil { return nil, trace.Wrap(err) } switch ts { case tableStatusOK: break case tableStatusMissing: err = b.createTable(ctx, b.Tablename, fullPathKey) case tableStatusNeedsMigration: return nil, trace.BadParameter("unsupported schema") } if err != nil { return nil, trace.Wrap(err) } err = b.turnOnTimeToLive(ctx) if err != nil { return nil, trace.Wrap(err) } err = b.turnOnStreams(ctx) if err != nil { return nil, trace.Wrap(err) } go b.asyncPollStreams(ctx) // Wrap backend in a input sanitizer and return it. return b, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/dynamo/dynamodbbk.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/dynamo/dynamodbbk.go#L268-L277
go
train
// Create creates item if it does not exist
func (b *DynamoDBBackend) Create(ctx context.Context, item backend.Item) (*backend.Lease, error)
// Create creates item if it does not exist func (b *DynamoDBBackend) Create(ctx context.Context, item backend.Item) (*backend.Lease, error)
{ err := b.create(ctx, item, modeCreate) if trace.IsCompareFailed(err) { err = trace.AlreadyExists(err.Error()) } if err != nil { return nil, trace.Wrap(err) } return b.newLease(item), nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/dynamo/dynamodbbk.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/dynamo/dynamodbbk.go#L281-L287
go
train
// Put puts value into backend (creates if it does not // exists, updates it otherwise)
func (b *DynamoDBBackend) Put(ctx context.Context, item backend.Item) (*backend.Lease, error)
// Put puts value into backend (creates if it does not // exists, updates it otherwise) func (b *DynamoDBBackend) Put(ctx context.Context, item backend.Item) (*backend.Lease, error)
{ err := b.create(ctx, item, modePut) if err != nil { return nil, trace.Wrap(err) } return b.newLease(item), nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/dynamo/dynamodbbk.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/dynamo/dynamodbbk.go#L290-L299
go
train
// Update updates value in the backend
func (b *DynamoDBBackend) Update(ctx context.Context, item backend.Item) (*backend.Lease, error)
// Update updates value in the backend func (b *DynamoDBBackend) Update(ctx context.Context, item backend.Item) (*backend.Lease, error)
{ err := b.create(ctx, item, modeUpdate) if trace.IsCompareFailed(err) { err = trace.NotFound(err.Error()) } if err != nil { return nil, trace.Wrap(err) } return b.newLease(item), nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/dynamo/dynamodbbk.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/dynamo/dynamodbbk.go#L302-L325
go
train
// GetRange returns range of elements
func (b *DynamoDBBackend) GetRange(ctx context.Context, startKey []byte, endKey []byte, limit int) (*backend.GetResult, error)
// GetRange returns range of elements func (b *DynamoDBBackend) GetRange(ctx context.Context, startKey []byte, endKey []byte, limit int) (*backend.GetResult, error)
{ if len(startKey) == 0 { return nil, trace.BadParameter("missing parameter startKey") } if len(endKey) == 0 { return nil, trace.BadParameter("missing parameter endKey") } result, err := b.getAllRecords(ctx, startKey, endKey, limit) if err != nil { return nil, trace.Wrap(err) } sort.Sort(records(result.records)) values := make([]backend.Item, len(result.records)) for i, r := range result.records { values[i] = backend.Item{ Key: trimPrefix(r.FullPath), Value: r.Value, } if r.Expires != nil { values[i].Expires = time.Unix(*r.Expires, 0).UTC() } } return &backend.GetResult{Items: values}, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/dynamo/dynamodbbk.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/dynamo/dynamodbbk.go#L347-L391
go
train
// DeleteRange deletes range of items with keys between startKey and endKey
func (b *DynamoDBBackend) DeleteRange(ctx context.Context, startKey, endKey []byte) error
// DeleteRange deletes range of items with keys between startKey and endKey func (b *DynamoDBBackend) DeleteRange(ctx context.Context, startKey, endKey []byte) error
{ if len(startKey) == 0 { return trace.BadParameter("missing parameter startKey") } if len(endKey) == 0 { return trace.BadParameter("missing parameter endKey") } // keep fetching and deleting until no records left, // keep the very large limit, just in case if someone else // keeps adding records for i := 0; i < backend.DefaultLargeLimit/100; i++ { result, err := b.getRecords(ctx, prependPrefix(startKey), prependPrefix(endKey), 100, nil) if err != nil { return trace.Wrap(err) } if len(result.records) == 0 { return nil } requests := make([]*dynamodb.WriteRequest, 0, len(result.records)) for _, record := range result.records { requests = append(requests, &dynamodb.WriteRequest{ DeleteRequest: &dynamodb.DeleteRequest{ Key: map[string]*dynamodb.AttributeValue{ hashKeyKey: { S: aws.String(hashKey), }, fullPathKey: { S: aws.String(record.FullPath), }, }, }, }) } input := dynamodb.BatchWriteItemInput{ RequestItems: map[string][]*dynamodb.WriteRequest{ b.Tablename: requests, }, } if _, err = b.svc.BatchWriteItemWithContext(ctx, &input); err != nil { return trace.Wrap(err) } } return trace.ConnectionProblem(nil, "not all items deleted, too many requests") }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/dynamo/dynamodbbk.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/dynamo/dynamodbbk.go#L394-L408
go
train
// Get returns a single item or not found error
func (b *DynamoDBBackend) Get(ctx context.Context, key []byte) (*backend.Item, error)
// Get returns a single item or not found error func (b *DynamoDBBackend) Get(ctx context.Context, key []byte) (*backend.Item, error)
{ r, err := b.getKey(ctx, key) if err != nil { return nil, err } item := &backend.Item{ Key: trimPrefix(r.FullPath), Value: r.Value, ID: r.ID, } if r.Expires != nil { item.Expires = time.Unix(*r.Expires, 0) } return item, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/dynamo/dynamodbbk.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/dynamo/dynamodbbk.go#L413-L460
go
train
// CompareAndSwap compares and swap values in atomic operation // CompareAndSwap compares item with existing item // and replaces is with replaceWith item
func (b *DynamoDBBackend) CompareAndSwap(ctx context.Context, expected backend.Item, replaceWith backend.Item) (*backend.Lease, error)
// CompareAndSwap compares and swap values in atomic operation // CompareAndSwap compares item with existing item // and replaces is with replaceWith item func (b *DynamoDBBackend) CompareAndSwap(ctx context.Context, expected backend.Item, replaceWith backend.Item) (*backend.Lease, error)
{ if len(expected.Key) == 0 { return nil, trace.BadParameter("missing parameter Key") } if len(replaceWith.Key) == 0 { return nil, trace.BadParameter("missing parameter Key") } if bytes.Compare(expected.Key, replaceWith.Key) != 0 { return nil, trace.BadParameter("expected and replaceWith keys should match") } r := record{ HashKey: hashKey, FullPath: prependPrefix(replaceWith.Key), Value: replaceWith.Value, Timestamp: time.Now().UTC().Unix(), ID: time.Now().UTC().UnixNano(), } if !replaceWith.Expires.IsZero() { r.Expires = aws.Int64(replaceWith.Expires.UTC().Unix()) } av, err := dynamodbattribute.MarshalMap(r) if err != nil { return nil, trace.Wrap(err) } input := dynamodb.PutItemInput{ Item: av, TableName: aws.String(b.Tablename), } input.SetConditionExpression("#v = :prev") input.SetExpressionAttributeNames(map[string]*string{ "#v": aws.String("Value"), }) input.SetExpressionAttributeValues(map[string]*dynamodb.AttributeValue{ ":prev": &dynamodb.AttributeValue{ B: expected.Value, }, }) _, err = b.svc.PutItemWithContext(ctx, &input) err = convertError(err) if err != nil { // in this case let's use more specific compare failed error if trace.IsAlreadyExists(err) { return nil, trace.CompareFailed(err.Error()) } return nil, trace.Wrap(err) } return b.newLease(replaceWith), nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/dynamo/dynamodbbk.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/dynamo/dynamodbbk.go#L463-L471
go
train
// Delete deletes item by key
func (b *DynamoDBBackend) Delete(ctx context.Context, key []byte) error
// Delete deletes item by key func (b *DynamoDBBackend) Delete(ctx context.Context, key []byte) error
{ if len(key) == 0 { return trace.BadParameter("missing parameter key") } if _, err := b.getKey(ctx, key); err != nil { return err } return b.deleteKey(ctx, key) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/dynamo/dynamodbbk.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/dynamo/dynamodbbk.go#L487-L518
go
train
// KeepAlive keeps object from expiring, updates lease on the existing object, // expires contains the new expiry to set on the lease, // some backends may ignore expires based on the implementation // in case if the lease managed server side
func (b *DynamoDBBackend) KeepAlive(ctx context.Context, lease backend.Lease, expires time.Time) error
// KeepAlive keeps object from expiring, updates lease on the existing object, // expires contains the new expiry to set on the lease, // some backends may ignore expires based on the implementation // in case if the lease managed server side func (b *DynamoDBBackend) KeepAlive(ctx context.Context, lease backend.Lease, expires time.Time) error
{ if len(lease.Key) == 0 { return trace.BadParameter("lease is missing key") } input := &dynamodb.UpdateItemInput{ ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{ ":expires": { N: aws.String(strconv.FormatInt(expires.UTC().Unix(), 10)), }, ":timestamp": { N: aws.String(strconv.FormatInt(b.clock.Now().UTC().Unix(), 10)), }, }, TableName: aws.String(b.Tablename), Key: map[string]*dynamodb.AttributeValue{ hashKeyKey: { S: aws.String(hashKey), }, fullPathKey: { S: aws.String(prependPrefix(lease.Key)), }, }, UpdateExpression: aws.String("SET Expires = :expires"), } input.SetConditionExpression("attribute_exists(FullPath) AND (attribute_not_exists(Expires) OR Expires >= :timestamp)") _, err := b.svc.UpdateItemWithContext(ctx, input) err = convertError(err) if trace.IsCompareFailed(err) { err = trace.NotFound(err.Error()) } return err }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/dynamo/dynamodbbk.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/dynamo/dynamodbbk.go#L530-L534
go
train
// Close closes the DynamoDB driver // and releases associated resources
func (b *DynamoDBBackend) Close() error
// Close closes the DynamoDB driver // and releases associated resources func (b *DynamoDBBackend) Close() error
{ b.setClosed() b.cancel() return b.buf.Close() }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/dynamo/dynamodbbk.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/dynamo/dynamodbbk.go#L566-L583
go
train
// getTableStatus checks if a given table exists
func (b *DynamoDBBackend) getTableStatus(ctx context.Context, tableName string) (tableStatus, error)
// getTableStatus checks if a given table exists func (b *DynamoDBBackend) getTableStatus(ctx context.Context, tableName string) (tableStatus, error)
{ td, err := b.svc.DescribeTableWithContext(ctx, &dynamodb.DescribeTableInput{ TableName: aws.String(tableName), }) err = convertError(err) if err != nil { if trace.IsNotFound(err) { return tableStatusMissing, nil } return tableStatusError, trace.Wrap(err) } for _, attr := range td.Table.AttributeDefinitions { if *attr.AttributeName == oldPathAttr { return tableStatusNeedsMigration, nil } } return tableStatusOK, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/dynamo/dynamodbbk.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/dynamo/dynamodbbk.go#L591-L634
go
train
// createTable creates a DynamoDB table with a requested name and applies // the back-end schema to it. The table must not exist. // // rangeKey is the name of the 'range key' the schema requires. // currently is always set to "FullPath" (used to be something else, that's // why it's a parameter for migration purposes)
func (b *DynamoDBBackend) createTable(ctx context.Context, tableName string, rangeKey string) error
// createTable creates a DynamoDB table with a requested name and applies // the back-end schema to it. The table must not exist. // // rangeKey is the name of the 'range key' the schema requires. // currently is always set to "FullPath" (used to be something else, that's // why it's a parameter for migration purposes) func (b *DynamoDBBackend) createTable(ctx context.Context, tableName string, rangeKey string) error
{ pThroughput := dynamodb.ProvisionedThroughput{ ReadCapacityUnits: aws.Int64(b.ReadCapacityUnits), WriteCapacityUnits: aws.Int64(b.WriteCapacityUnits), } def := []*dynamodb.AttributeDefinition{ { AttributeName: aws.String(hashKeyKey), AttributeType: aws.String("S"), }, { AttributeName: aws.String(rangeKey), AttributeType: aws.String("S"), }, } elems := []*dynamodb.KeySchemaElement{ { AttributeName: aws.String(hashKeyKey), KeyType: aws.String("HASH"), }, { AttributeName: aws.String(rangeKey), KeyType: aws.String("RANGE"), }, } c := dynamodb.CreateTableInput{ TableName: aws.String(tableName), AttributeDefinitions: def, KeySchema: elems, ProvisionedThroughput: &pThroughput, } _, err := b.svc.CreateTable(&c) if err != nil { return trace.Wrap(err) } b.Infof("Waiting until table %q is created.", tableName) err = b.svc.WaitUntilTableExistsWithContext(ctx, &dynamodb.DescribeTableInput{ TableName: aws.String(tableName), }) if err == nil { b.Infof("Table %q has been created.", tableName) } return trace.Wrap(err) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/dynamo/dynamodbbk.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/dynamo/dynamodbbk.go#L637-L648
go
train
// deleteTable deletes DynamoDB table with a given name
func (b *DynamoDBBackend) deleteTable(ctx context.Context, tableName string, wait bool) error
// deleteTable deletes DynamoDB table with a given name func (b *DynamoDBBackend) deleteTable(ctx context.Context, tableName string, wait bool) error
{ tn := aws.String(tableName) _, err := b.svc.DeleteTable(&dynamodb.DeleteTableInput{TableName: tn}) if err != nil { return trace.Wrap(err) } if wait { return trace.Wrap( b.svc.WaitUntilTableNotExists(&dynamodb.DescribeTableInput{TableName: tn})) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/dynamo/dynamodbbk.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/dynamo/dynamodbbk.go#L659-L700
go
train
// getRecords retrieves all keys by path
func (b *DynamoDBBackend) getRecords(ctx context.Context, startKey, endKey string, limit int, lastEvaluatedKey map[string]*dynamodb.AttributeValue) (*getResult, error)
// getRecords retrieves all keys by path func (b *DynamoDBBackend) getRecords(ctx context.Context, startKey, endKey string, limit int, lastEvaluatedKey map[string]*dynamodb.AttributeValue) (*getResult, error)
{ query := "HashKey = :hashKey AND FullPath BETWEEN :fullPath AND :rangeEnd" attrV := map[string]interface{}{ ":fullPath": startKey, ":hashKey": hashKey, ":timestamp": b.clock.Now().UTC().Unix(), ":rangeEnd": endKey, } // filter out expired items, otherwise they might show up in the query // http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/howitworks-ttl.html filter := fmt.Sprintf("attribute_not_exists(Expires) OR Expires >= :timestamp") av, err := dynamodbattribute.MarshalMap(attrV) if err != nil { return nil, convertError(err) } input := dynamodb.QueryInput{ KeyConditionExpression: aws.String(query), TableName: &b.Tablename, ExpressionAttributeValues: av, FilterExpression: aws.String(filter), ConsistentRead: aws.Bool(true), ExclusiveStartKey: lastEvaluatedKey, } if limit > 0 { input.Limit = aws.Int64(int64(limit)) } out, err := b.svc.Query(&input) if err != nil { return nil, trace.Wrap(err) } var result getResult for _, item := range out.Items { var r record dynamodbattribute.UnmarshalMap(item, &r) result.records = append(result.records, r) } sort.Sort(records(result.records)) result.records = removeDuplicates(result.records) result.lastEvaluatedKey = out.LastEvaluatedKey return &result, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/dynamo/dynamodbbk.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/dynamo/dynamodbbk.go#L704-L710
go
train
// isExpired returns 'true' if the given object (record) has a TTL and // it's due.
func (r *record) isExpired() bool
// isExpired returns 'true' if the given object (record) has a TTL and // it's due. func (r *record) isExpired() bool
{ if r.Expires == nil { return false } expiryDateUTC := time.Unix(*r.Expires, 0).UTC() return time.Now().UTC().After(expiryDateUTC) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/dynamo/dynamodbbk.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/dynamo/dynamodbbk.go#L750-L784
go
train
// create helper creates a new key/value pair in Dynamo with a given expiration // depending on mode, either creates, updates or forces create/update
func (b *DynamoDBBackend) create(ctx context.Context, item backend.Item, mode int) error
// create helper creates a new key/value pair in Dynamo with a given expiration // depending on mode, either creates, updates or forces create/update func (b *DynamoDBBackend) create(ctx context.Context, item backend.Item, mode int) error
{ r := record{ HashKey: hashKey, FullPath: prependPrefix(item.Key), Value: item.Value, Timestamp: time.Now().UTC().Unix(), ID: time.Now().UTC().UnixNano(), } if !item.Expires.IsZero() { r.Expires = aws.Int64(item.Expires.UTC().Unix()) } av, err := dynamodbattribute.MarshalMap(r) if err != nil { return trace.Wrap(err) } input := dynamodb.PutItemInput{ Item: av, TableName: aws.String(b.Tablename), } switch mode { case modeCreate: input.SetConditionExpression("attribute_not_exists(FullPath)") case modeUpdate: input.SetConditionExpression("attribute_exists(FullPath)") case modePut: default: return trace.BadParameter("unrecognized mode") } _, err = b.svc.PutItemWithContext(ctx, &input) err = convertError(err) if err != nil { return trace.Wrap(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/dynamo/dynamodbbk.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/dynamo/dynamodbbk.go#L862-L864
go
train
// Swap is part of sort.Interface.
func (r records) Swap(i, j int)
// Swap is part of sort.Interface. func (r records) Swap(i, j int)
{ r[i], r[j] = r[j], r[i] }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/dynamo/dynamodbbk.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/dynamo/dynamodbbk.go#L867-L869
go
train
// Less is part of sort.Interface.
func (r records) Less(i, j int) bool
// Less is part of sort.Interface. func (r records) Less(i, j int) bool
{ return r[i].FullPath < r[j].FullPath }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/buffer.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/buffer.go#L48-L66
go
train
// NewCircularBuffer returns a new instance of circular buffer
func NewCircularBuffer(ctx context.Context, size int) (*CircularBuffer, error)
// NewCircularBuffer returns a new instance of circular buffer func NewCircularBuffer(ctx context.Context, size int) (*CircularBuffer, error)
{ if size <= 0 { return nil, trace.BadParameter("circular buffer size should be > 0") } ctx, cancel := context.WithCancel(ctx) buf := &CircularBuffer{ Entry: log.WithFields(log.Fields{ trace.Component: teleport.ComponentBuffer, }), ctx: ctx, cancel: cancel, events: make([]Event, size), start: -1, end: -1, size: 0, watchers: newWatcherTree(), } return buf, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/buffer.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/buffer.go#L70-L84
go
train
// Reset resets all events from the queue // and closes all active watchers
func (c *CircularBuffer) Reset()
// Reset resets all events from the queue // and closes all active watchers func (c *CircularBuffer) Reset()
{ c.Lock() defer c.Unlock() // could close mulitple times c.watchers.walk(func(w *BufferWatcher) { w.Close() }) c.watchers = newWatcherTree() c.start = -1 c.end = -1 c.size = 0 for i := 0; i < len(c.events); i++ { c.events[i] = Event{} } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/buffer.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/buffer.go#L99-L103
go
train
// Events returns a copy of records as arranged from start to end
func (c *CircularBuffer) Events() []Event
// Events returns a copy of records as arranged from start to end func (c *CircularBuffer) Events() []Event
{ c.Lock() defer c.Unlock() return c.eventsCopy() }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/buffer.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/buffer.go#L106-L119
go
train
// eventsCopy returns a copy of events as arranged from start to end
func (c *CircularBuffer) eventsCopy() []Event
// eventsCopy returns a copy of events as arranged from start to end func (c *CircularBuffer) eventsCopy() []Event
{ if c.size == 0 { return nil } var out []Event for i := 0; i < c.size; i++ { index := (c.start + i) % len(c.events) if out == nil { out = make([]Event, 0, c.size) } out = append(out, c.events[index]) } return out }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/buffer.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/buffer.go#L122-L129
go
train
// PushBatch pushes elements to the queue as a batch
func (c *CircularBuffer) PushBatch(events []Event)
// PushBatch pushes elements to the queue as a batch func (c *CircularBuffer) PushBatch(events []Event)
{ c.Lock() defer c.Unlock() for i := range events { c.push(events[i]) } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/buffer.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/buffer.go#L132-L136
go
train
// Push pushes elements to the queue
func (c *CircularBuffer) Push(r Event)
// Push pushes elements to the queue func (c *CircularBuffer) Push(r Event)
{ c.Lock() defer c.Unlock() c.push(r) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/buffer.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/buffer.go#L203-L247
go
train
// NewWatcher adds a new watcher to the events buffer
func (c *CircularBuffer) NewWatcher(ctx context.Context, watch Watch) (Watcher, error)
// NewWatcher adds a new watcher to the events buffer func (c *CircularBuffer) NewWatcher(ctx context.Context, watch Watch) (Watcher, error)
{ c.Lock() defer c.Unlock() select { case <-c.ctx.Done(): return nil, trace.BadParameter("buffer is closed") default: } if watch.QueueSize == 0 { watch.QueueSize = len(c.events) } if len(watch.Prefixes) == 0 { // if watcher has no prefixes, assume it will match anything // starting from the separator (what includes all keys in backend invariant, see Keys function) watch.Prefixes = append(watch.Prefixes, []byte{Separator}) } else { // if watcher's prefixes are redundant, keep only shorter prefixes // to avoid double fan out watch.Prefixes = removeRedundantPrefixes(watch.Prefixes) } closeCtx, cancel := context.WithCancel(ctx) w := &BufferWatcher{ Watch: watch, eventsC: make(chan Event, watch.QueueSize), ctx: closeCtx, cancel: cancel, capacity: watch.QueueSize, } c.Debugf("Add %v.", w) select { case w.eventsC <- Event{Type: OpInit}: case <-c.ctx.Done(): return nil, trace.BadParameter("buffer is closed") default: c.Warningf("Closing %v, buffer overflow.", w) w.Close() return nil, trace.BadParameter("buffer overflow") } c.watchers.add(w) return w, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/buffer.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/buffer.go#L268-L270
go
train
// String returns user-friendly representation // of the buffer watcher
func (w *BufferWatcher) String() string
// String returns user-friendly representation // of the buffer watcher func (w *BufferWatcher) String() string
{ return fmt.Sprintf("Watcher(name=%v, prefixes=%v, capacity=%v, size=%v)", w.Name, string(bytes.Join(w.Prefixes, []byte(", "))), w.capacity, len(w.eventsC)) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/buffer.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/buffer.go#L300-L311
go
train
// add adds buffer watcher to the tree
func (t *watcherTree) add(w *BufferWatcher)
// add adds buffer watcher to the tree func (t *watcherTree) add(w *BufferWatcher)
{ for _, p := range w.Prefixes { prefix := string(p) val, ok := t.Tree.Get(prefix) var watchers []*BufferWatcher if ok { watchers = val.([]*BufferWatcher) } watchers = append(watchers, w) t.Tree.Insert(prefix, watchers) } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/buffer.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/buffer.go#L314-L341
go
train
// rm removes the buffer watcher from the prefix tree
func (t *watcherTree) rm(w *BufferWatcher) bool
// rm removes the buffer watcher from the prefix tree func (t *watcherTree) rm(w *BufferWatcher) bool
{ if w == nil { return false } var found bool for _, p := range w.Prefixes { prefix := string(p) val, ok := t.Tree.Get(prefix) if !ok { continue } buffers := val.([]*BufferWatcher) prevLen := len(buffers) for i := range buffers { if buffers[i] == w { buffers = append(buffers[:i], buffers[i+1:]...) found = true break } } if len(buffers) == 0 { t.Tree.Delete(prefix) } else if len(buffers) != prevLen { t.Tree.Insert(prefix, buffers) } } return found }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/buffer.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/buffer.go#L348-L356
go
train
// walkPath walks the tree above the longest matching prefix // and calls fn callback for every buffer watcher
func (t *watcherTree) walkPath(key string, fn walkFn)
// walkPath walks the tree above the longest matching prefix // and calls fn callback for every buffer watcher func (t *watcherTree) walkPath(key string, fn walkFn)
{ t.Tree.WalkPath(key, func(prefix string, val interface{}) bool { watchers := val.([]*BufferWatcher) for _, w := range watchers { fn(w) } return false }) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/buffer.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/buffer.go#L359-L367
go
train
// walk calls fn for every matching leaf of the tree
func (t *watcherTree) walk(fn walkFn)
// walk calls fn for every matching leaf of the tree func (t *watcherTree) walk(fn walkFn)
{ t.Tree.Walk(func(prefix string, val interface{}) bool { watchers := val.([]*BufferWatcher) for _, w := range watchers { fn(w) } return false }) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/kube/client/kubeclient.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/client/kubeclient.go#L26-L73
go
train
// UpdateKubeconfig adds Teleport configuration to kubeconfig.
func UpdateKubeconfig(tc *client.TeleportClient) error
// UpdateKubeconfig adds Teleport configuration to kubeconfig. func UpdateKubeconfig(tc *client.TeleportClient) error
{ config, err := LoadKubeConfig() if err != nil { return trace.Wrap(err) } clusterName, proxyPort := tc.KubeProxyHostPort() var clusterAddr string if tc.SiteName != "" { // In case of a remote cluster, use SNI subdomain to "point" to a remote cluster name clusterAddr = fmt.Sprintf("https://%v.%v:%v", kubeutils.EncodeClusterName(tc.SiteName), clusterName, proxyPort) clusterName = tc.SiteName } else { clusterAddr = fmt.Sprintf("https://%v:%v", clusterName, proxyPort) } creds, err := tc.LocalAgent().GetKey() if err != nil { return trace.Wrap(err) } certAuthorities, err := tc.LocalAgent().GetCertsPEM() if err != nil { return trace.Wrap(err) } config.AuthInfos[clusterName] = &clientcmdapi.AuthInfo{ ClientCertificateData: creds.TLSCert, ClientKeyData: creds.Priv, } config.Clusters[clusterName] = &clientcmdapi.Cluster{ Server: clusterAddr, CertificateAuthorityData: certAuthorities, } lastContext := config.Contexts[clusterName] newContext := &clientcmdapi.Context{ Cluster: clusterName, AuthInfo: clusterName, } if lastContext != nil { newContext.Namespace = lastContext.Namespace newContext.Extensions = lastContext.Extensions } config.Contexts[clusterName] = newContext config.CurrentContext = clusterName return SaveKubeConfig(*config) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/kube/client/kubeclient.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/client/kubeclient.go#L76-L100
go
train
// RemoveKubeconifg removes Teleport configuration from kubeconfig.
func RemoveKubeconifg(tc *client.TeleportClient, clusterName string) error
// RemoveKubeconifg removes Teleport configuration from kubeconfig. func RemoveKubeconifg(tc *client.TeleportClient, clusterName string) error
{ // Load existing kubeconfig from disk. config, err := LoadKubeConfig() if err != nil { return trace.Wrap(err) } // Remove Teleport related AuthInfos, Clusters, and Contexts from kubeconfig. delete(config.AuthInfos, clusterName) delete(config.Clusters, clusterName) delete(config.Contexts, clusterName) // Take an element from the list of contexts and make it the current context. if len(config.Contexts) > 0 { var currentContext *clientcmdapi.Context for _, cc := range config.Contexts { currentContext = cc break } config.CurrentContext = currentContext.Cluster } // Update kubeconfig on disk. return SaveKubeConfig(*config) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/kube/client/kubeclient.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/client/kubeclient.go#L104-L121
go
train
// LoadKubeconfig tries to read a kubeconfig file and if it can't, returns an error. // One exception, missing files result in empty configs, not an error.
func LoadKubeConfig() (*clientcmdapi.Config, error)
// LoadKubeconfig tries to read a kubeconfig file and if it can't, returns an error. // One exception, missing files result in empty configs, not an error. func LoadKubeConfig() (*clientcmdapi.Config, error)
{ filename, err := utils.EnsureLocalPath( kubeconfigFromEnv(), teleport.KubeConfigDir, teleport.KubeConfigFile) if err != nil { return nil, trace.Wrap(err) } config, err := clientcmd.LoadFromFile(filename) if err != nil && !os.IsNotExist(err) { return nil, trace.ConvertSystemError(err) } if config == nil { config = clientcmdapi.NewConfig() } return config, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/kube/client/kubeclient.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/client/kubeclient.go#L125-L139
go
train
// SaveKubeConfig saves updated config to location specified by environment variable or // default location
func SaveKubeConfig(config clientcmdapi.Config) error
// SaveKubeConfig saves updated config to location specified by environment variable or // default location func SaveKubeConfig(config clientcmdapi.Config) error
{ filename, err := utils.EnsureLocalPath( kubeconfigFromEnv(), teleport.KubeConfigDir, teleport.KubeConfigFile) if err != nil { return trace.Wrap(err) } err = clientcmd.WriteToFile(config, filename) if err != nil { return trace.ConvertSystemError(err) } return nil }