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/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1322-L1334
go
train
// FetchRoles fetches roles by their names, applies the traits to role // variables, and returns the RoleSet.
func FetchRoles(roleNames []string, access RoleGetter, traits map[string][]string) (RoleSet, error)
// FetchRoles fetches roles by their names, applies the traits to role // variables, and returns the RoleSet. func FetchRoles(roleNames []string, access RoleGetter, traits map[string][]string) (RoleSet, error)
{ var roles []Role for _, roleName := range roleNames { role, err := access.GetRole(roleName) if err != nil { return nil, trace.Wrap(err) } roles = append(roles, role.ApplyTraits(traits)) } return NewRoleSet(roles...), nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1337-L1344
go
train
// NewRoleSet returns new RoleSet based on the roles
func NewRoleSet(roles ...Role) RoleSet
// NewRoleSet returns new RoleSet based on the roles func NewRoleSet(roles ...Role) RoleSet
{ // unauthenticated Nop role should not have any privileges // by default, otherwise it is too permissive if len(roles) == 1 && roles[0].GetName() == string(teleport.RoleNop) { return roles } return append(roles, NewImplicitRole()) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1351-L1358
go
train
// MatchNamespace returns true if given list of namespace matches // target namespace, wildcard matches everything.
func MatchNamespace(selectors []string, namespace string) (bool, string)
// MatchNamespace returns true if given list of namespace matches // target namespace, wildcard matches everything. func MatchNamespace(selectors []string, namespace string) (bool, string)
{ for _, n := range selectors { if n == namespace || n == Wildcard { return true, "matched" } } return false, fmt.Sprintf("no match, role selectors %v, server namespace: %v", selectors, namespace) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1361-L1368
go
train
// MatchLogin returns true if attempted login matches any of the logins.
func MatchLogin(selectors []string, login string) (bool, string)
// MatchLogin returns true if attempted login matches any of the logins. func MatchLogin(selectors []string, login string) (bool, string)
{ for _, l := range selectors { if l == login { return true, "matched" } } return false, fmt.Sprintf("no match, role selectors %v, login: %v", selectors, login) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1372-L1403
go
train
// MatchLabels matches selector against target. Empty selector matches // nothing, wildcard matches everything.
func MatchLabels(selector Labels, target map[string]string) (bool, string, error)
// MatchLabels matches selector against target. Empty selector matches // nothing, wildcard matches everything. func MatchLabels(selector Labels, target map[string]string) (bool, string, error)
{ // Empty selector matches nothing. if len(selector) == 0 { return false, "no match, empty selector", nil } // *: * matches everything even empty target set. selectorValues := selector[Wildcard] if len(selectorValues) == 1 && selectorValues[0] == Wildcard { return true, "matched", nil } // Perform full ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1406-L1412
go
train
// RoleNames returns a slice with role names
func (set RoleSet) RoleNames() []string
// RoleNames returns a slice with role names func (set RoleSet) RoleNames() []string
{ out := make([]string, len(set)) for i, r := range set { out[i] = r.GetName() } return out }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1415-L1422
go
train
// HasRole checks if the role set has the role
func (set RoleSet) HasRole(role string) bool
// HasRole checks if the role set has the role func (set RoleSet) HasRole(role string) bool
{ for _, r := range set { if r.GetName() == role { return true } } return false }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1426-L1434
go
train
// AdjustSessionTTL will reduce the requested ttl to lowest max allowed TTL // for this role set, otherwise it returns ttl unchanged
func (set RoleSet) AdjustSessionTTL(ttl time.Duration) time.Duration
// AdjustSessionTTL will reduce the requested ttl to lowest max allowed TTL // for this role set, otherwise it returns ttl unchanged func (set RoleSet) AdjustSessionTTL(ttl time.Duration) time.Duration
{ for _, role := range set { maxSessionTTL := role.GetOptions().MaxSessionTTL.Value() if maxSessionTTL != 0 && ttl > maxSessionTTL { ttl = maxSessionTTL } } return ttl }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1439-L1460
go
train
// AdjustClientIdleTimeout adjusts requested idle timeout // to the lowest max allowed timeout, the most restrictive // option will be picked, negative values will be assumed as 0
func (set RoleSet) AdjustClientIdleTimeout(timeout time.Duration) time.Duration
// AdjustClientIdleTimeout adjusts requested idle timeout // to the lowest max allowed timeout, the most restrictive // option will be picked, negative values will be assumed as 0 func (set RoleSet) AdjustClientIdleTimeout(timeout time.Duration) time.Duration
{ if timeout < 0 { timeout = 0 } for _, role := range set { roleTimeout := role.GetOptions().ClientIdleTimeout // 0 means not set, so it can't be most restrictive, disregard it too if roleTimeout.Duration() <= 0 { continue } switch { // in case if timeout is 0, means that incoming value // does n...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1464-L1471
go
train
// AdjustDisconnectExpiredCert adjusts the value based on the role set // the most restrictive option will be picked
func (set RoleSet) AdjustDisconnectExpiredCert(disconnect bool) bool
// AdjustDisconnectExpiredCert adjusts the value based on the role set // the most restrictive option will be picked func (set RoleSet) AdjustDisconnectExpiredCert(disconnect bool) bool
{ for _, role := range set { if role.GetOptions().DisconnectExpiredCert.Value() { disconnect = true } } return disconnect }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1475-L1498
go
train
// CheckKubeGroups check if role can login into kubernetes // and returns a combined list of allowed groups
func (set RoleSet) CheckKubeGroups(ttl time.Duration) ([]string, error)
// CheckKubeGroups check if role can login into kubernetes // and returns a combined list of allowed groups func (set RoleSet) CheckKubeGroups(ttl time.Duration) ([]string, error)
{ groups := make(map[string]bool) var matchedTTL bool for _, role := range set { maxSessionTTL := role.GetOptions().MaxSessionTTL.Value() if ttl <= maxSessionTTL && maxSessionTTL != 0 { matchedTTL = true for _, group := range role.GetKubeGroups(Allow) { groups[group] = true } } } if !matchedTTL...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1502-L1526
go
train
// CheckLoginDuration checks if role set can login up to given duration and // returns a combined list of allowed logins.
func (set RoleSet) CheckLoginDuration(ttl time.Duration) ([]string, error)
// CheckLoginDuration checks if role set can login up to given duration and // returns a combined list of allowed logins. func (set RoleSet) CheckLoginDuration(ttl time.Duration) ([]string, error)
{ logins := make(map[string]bool) var matchedTTL bool for _, role := range set { maxSessionTTL := role.GetOptions().MaxSessionTTL.Value() if ttl <= maxSessionTTL && maxSessionTTL != 0 { matchedTTL = true for _, login := range role.GetLogins(Allow) { logins[login] = true } } } if !matchedTTL { ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1535-L1583
go
train
// CheckAccessToServer checks if a role has access to a node. Deny rules are // checked first then allow rules. Access to a node is determined by // namespaces, labels, and logins. // // Note, logging in this function only happens in debug mode, this is because // adding logging to this function (which is called on eve...
func (set RoleSet) CheckAccessToServer(login string, s Server) error
// CheckAccessToServer checks if a role has access to a node. Deny rules are // checked first then allow rules. Access to a node is determined by // namespaces, labels, and logins. // // Note, logging in this function only happens in debug mode, this is because // adding logging to this function (which is called on eve...
{ var errs []error // Check deny rules first: a single matching namespace, label, or login from // the deny role set prohibits access. for _, role := range set { matchNamespace, namespaceMessage := MatchNamespace(role.GetNamespaces(Deny), s.GetNamespace()) matchLabels, labelsMessage, err := MatchLabels(role.G...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1586-L1593
go
train
// CanForwardAgents returns true if role set allows forwarding agents.
func (set RoleSet) CanForwardAgents() bool
// CanForwardAgents returns true if role set allows forwarding agents. func (set RoleSet) CanForwardAgents() bool
{ for _, role := range set { if role.GetOptions().ForwardAgent.Value() { return true } } return false }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1596-L1603
go
train
// CanPortForward returns true if a role in the RoleSet allows port forwarding.
func (set RoleSet) CanPortForward() bool
// CanPortForward returns true if a role in the RoleSet allows port forwarding. func (set RoleSet) CanPortForward() bool
{ for _, role := range set { if BoolDefaultTrue(role.GetOptions().PortForwarding) { return true } } return false }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1607-L1632
go
train
// CertificateFormat returns the most permissive certificate format in a // RoleSet.
func (set RoleSet) CertificateFormat() string
// CertificateFormat returns the most permissive certificate format in a // RoleSet. func (set RoleSet) CertificateFormat() string
{ var formats []string for _, role := range set { // get the certificate format for each individual role. if a role does not // have a certificate format (like implicit roles) skip over it certificateFormat := role.GetOptions().CertificateFormat if certificateFormat == "" { continue } formats = appe...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1649-L1661
go
train
// CheckAgentForward checks if the role can request to forward the SSH agent // for this user.
func (set RoleSet) CheckAgentForward(login string) error
// CheckAgentForward checks if the role can request to forward the SSH agent // for this user. func (set RoleSet) CheckAgentForward(login string) error
{ // check if we have permission to login and forward agent. we don't check // for deny rules because if you can't forward an agent if you can't login // in the first place. for _, role := range set { for _, l := range role.GetLogins(Allow) { if role.GetOptions().ForwardAgent.Value() && l == login { retur...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1789-L1791
go
train
// MarshalTo marshals value to the array
func (l Labels) MarshalTo(data []byte) (int, error)
// MarshalTo marshals value to the array func (l Labels) MarshalTo(data []byte) (int, error)
{ return l.protoType().MarshalTo(data) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1794-L1808
go
train
// Unmarshal unmarshals value from protobuf
func (l *Labels) Unmarshal(data []byte) error
// Unmarshal unmarshals value from protobuf func (l *Labels) Unmarshal(data []byte) error
{ protoValues := &LabelValues{} err := proto.Unmarshal(data, protoValues) if err != nil { return err } if protoValues.Values == nil { return nil } *l = make(map[string]utils.Strings, len(protoValues.Values)) for key := range protoValues.Values { (*l)[key] = protoValues.Values[key].Values } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1816-L1827
go
train
// Clone returns non-shallow copy of the labels set
func (l Labels) Clone() Labels
// Clone returns non-shallow copy of the labels set func (l Labels) Clone() Labels
{ if l == nil { return nil } out := make(Labels, len(l)) for key, vals := range l { cvals := make([]string, len(vals)) copy(cvals, vals) out[key] = cvals } return out }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1830-L1840
go
train
// Equals returns true if two label sets are equal
func (l Labels) Equals(o Labels) bool
// Equals returns true if two label sets are equal func (l Labels) Equals(o Labels) bool
{ if len(l) != len(o) { return false } for key := range l { if !utils.StringSlicesEqual(l[key], o[key]) { return false } } return true }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1869-L1891
go
train
// UnmarshalJSON unmarshals JSON from string or bool, // in case if value is missing or not recognized, defaults to false
func (b *Bool) UnmarshalJSON(data []byte) error
// UnmarshalJSON unmarshals JSON from string or bool, // in case if value is missing or not recognized, defaults to false func (b *Bool) UnmarshalJSON(data []byte) error
{ if len(data) == 0 { return nil } var boolVal bool // check if it's a bool variable if err := json.Unmarshal(data, &boolVal); err == nil { *b = Bool(boolVal) return nil } // also support string variables var stringVar string if err := json.Unmarshal(data, &stringVar); err != nil { return trace.Wrap(e...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1933-L1935
go
train
// MarshalTo marshals value to the slice
func (b BoolOption) MarshalTo(data []byte) (int, error)
// MarshalTo marshals value to the slice func (b BoolOption) MarshalTo(data []byte) (int, error)
{ return b.protoType().MarshalTo(data) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1943-L1951
go
train
// Unmarshal unmarshals value from protobuf
func (b *BoolOption) Unmarshal(data []byte) error
// Unmarshal unmarshals value from protobuf func (b *BoolOption) Unmarshal(data []byte) error
{ protoValue := &BoolValue{} err := proto.Unmarshal(data, protoValue) if err != nil { return err } b.Value = protoValue.Value return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1965-L1972
go
train
// UnmarshalJSON unmarshals JSON from string or bool, // in case if value is missing or not recognized, defaults to false
func (b *BoolOption) UnmarshalJSON(data []byte) error
// UnmarshalJSON unmarshals JSON from string or bool, // in case if value is missing or not recognized, defaults to false func (b *BoolOption) UnmarshalJSON(data []byte) error
{ var val Bool if err := val.UnmarshalJSON(data); err != nil { return err } b.Value = val.Value() return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L2007-L2025
go
train
// UnmarshalJSON marshals Duration to string
func (d *Duration) UnmarshalJSON(data []byte) error
// UnmarshalJSON marshals Duration to string func (d *Duration) UnmarshalJSON(data []byte) error
{ if len(data) == 0 { return nil } var stringVar string if err := json.Unmarshal(data, &stringVar); err != nil { return trace.Wrap(err) } if stringVar == teleport.DurationNever { *d = Duration(0) } else { out, err := time.ParseDuration(stringVar) if err != nil { return trace.BadParameter(err.Error(...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L2158-L2175
go
train
// GetRoleSchema returns role schema for the version requested with optionally // injected schema for extensions.
func GetRoleSchema(version string, extensionSchema string) string
// GetRoleSchema returns role schema for the version requested with optionally // injected schema for extensions. func GetRoleSchema(version string, extensionSchema string) string
{ schemaDefinitions := "," + RoleSpecV3SchemaDefinitions if version == V2 { schemaDefinitions = DefaultDefinitions } schemaTemplate := RoleSpecV3SchemaTemplate if version == V2 { schemaTemplate = RoleSpecV2SchemaTemplate } schema := fmt.Sprintf(schemaTemplate, ``) if extensionSchema != "" { schema = fm...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L2178-L2230
go
train
// UnmarshalRole unmarshals role from JSON, sets defaults, and checks schema.
func UnmarshalRole(data []byte, opts ...MarshalOption) (*RoleV3, error)
// UnmarshalRole unmarshals role from JSON, sets defaults, and checks schema. func UnmarshalRole(data []byte, opts ...MarshalOption) (*RoleV3, error)
{ var h ResourceHeader err := json.Unmarshal(data, &h) if err != nil { h.Version = V2 } cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } switch h.Version { case V2: var role RoleV2 if err := utils.UnmarshalWithSchema(GetRoleSchema(V2, ""), &role, data); err != nil { ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L2258-L2260
go
train
// UnmarshalRole unmarshals role from JSON.
func (*TeleportRoleMarshaler) UnmarshalRole(bytes []byte, opts ...MarshalOption) (Role, error)
// UnmarshalRole unmarshals role from JSON. func (*TeleportRoleMarshaler) UnmarshalRole(bytes []byte, opts ...MarshalOption) (Role, error)
{ return UnmarshalRole(bytes, opts...) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L2263-L2281
go
train
// MarshalRole marshalls role into JSON.
func (*TeleportRoleMarshaler) MarshalRole(r Role, opts ...MarshalOption) ([]byte, error)
// MarshalRole marshalls role into JSON. func (*TeleportRoleMarshaler) MarshalRole(r Role, opts ...MarshalOption) ([]byte, error)
{ cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } switch role := r.(type) { case *RoleV3: if !cfg.PreserveResourceID { // avoid modifying the original object // to prevent unexpected data races copy := *role copy.SetResourceID(0) role = &copy } return utils.Fa...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L2292-L2294
go
train
// Less compares roles by name
func (s SortedRoles) Less(i, j int) bool
// Less compares roles by name func (s SortedRoles) Less(i, j int) bool
{ return s[i].GetName() < s[j].GetName() }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L2297-L2299
go
train
// Swap swaps two roles in a list
func (s SortedRoles) Swap(i, j int)
// Swap swaps two roles in a list func (s SortedRoles) Swap(i, j int)
{ s[i], s[j] = s[j], s[i] }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/legacy/dir/migrate.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/migrate.go#L33-L116
go
train
// DELETE IN: 2.8.0 // migrate old directory backend to the new flat keyspace.
func migrate(rootDir string, b *Backend) error
// DELETE IN: 2.8.0 // migrate old directory backend to the new flat keyspace. func migrate(rootDir string, b *Backend) error
{ // Check if the directory structure is the old bucket format. ok, err := isOld(rootDir) if err != nil { return trace.Wrap(err) } // Found the new flat keyspace directory backend, nothing to do. if !ok { b.log.Debugf("Found new flat keyspace, skipping migration.") return nil } // The old directory back...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/legacy/dir/migrate.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/migrate.go#L121-L145
go
train
// DELETE IN: 2.8.0 // readTTL reads in TTL for the given key. If no TTL key is found, // legacy.Forever is returned.
func readTTL(rootDir string, bucket string, key string) (time.Duration, bool, error)
// DELETE IN: 2.8.0 // readTTL reads in TTL for the given key. If no TTL key is found, // legacy.Forever is returned. func readTTL(rootDir string, bucket string, key string) (time.Duration, bool, error)
{ filename := filepath.Join(rootDir, bucket, "."+key+".ttl") bytes, err := ioutil.ReadFile(filename) if err != nil { if os.IsNotExist(err) { return legacy.Forever, false, nil } return legacy.Forever, false, trace.Wrap(err) } if len(bytes) == 0 { return legacy.Forever, false, nil } var expiryTime ti...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/legacy/dir/migrate.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/migrate.go#L149-L168
go
train
// DELETE IN: 2.8.0 // isOld checks if the directory backend is in the old format or not.
func isOld(rootDir string) (bool, error)
// DELETE IN: 2.8.0 // isOld checks if the directory backend is in the old format or not. func isOld(rootDir string) (bool, error)
{ d, err := os.Open(rootDir) if err != nil { return false, trace.ConvertSystemError(err) } defer d.Close() files, err := d.Readdir(0) if err != nil { return false, trace.ConvertSystemError(err) } for _, fi := range files { if fi.IsDir() { return true, nil } } return false, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/resource_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/resource_command.go#L71-L94
go
train
// Initialize allows ResourceCommand to plug itself into the CLI parser
func (g *ResourceCommand) Initialize(app *kingpin.Application, config *service.Config)
// Initialize allows ResourceCommand to plug itself into the CLI parser func (g *ResourceCommand) Initialize(app *kingpin.Application, config *service.Config)
{ g.CreateHandlers = map[ResourceKind]ResourceCreateHandler{ services.KindUser: g.createUser, services.KindTrustedCluster: g.createTrustedCluster, services.KindGithubConnector: g.createGithubConnector, services.KindCertAuthority: g.createCertAuthority, } g.config = config g.createCmd = app.C...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/resource_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/resource_command.go#L98-L113
go
train
// TryRun takes the CLI command as an argument (like "auth gen") and executes it // or returns match=false if 'cmd' does not belong to it
func (g *ResourceCommand) TryRun(cmd string, client auth.ClientI) (match bool, err error)
// TryRun takes the CLI command as an argument (like "auth gen") and executes it // or returns match=false if 'cmd' does not belong to it func (g *ResourceCommand) TryRun(cmd string, client auth.ClientI) (match bool, err error)
{ switch cmd { // tctl get case g.getCmd.FullCommand(): err = g.Get(client) // tctl create case g.createCmd.FullCommand(): err = g.Create(client) // tctl rm case g.deleteCmd.FullCommand(): err = g.Delete(client) default: return false, nil } return true, trace.Wrap(err) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/resource_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/resource_command.go#L116-L118
go
train
// IsDeleteSubcommand returns 'true' if the given command is `tctl rm`
func (g *ResourceCommand) IsDeleteSubcommand(cmd string) bool
// IsDeleteSubcommand returns 'true' if the given command is `tctl rm` func (g *ResourceCommand) IsDeleteSubcommand(cmd string) bool
{ return cmd == g.deleteCmd.FullCommand() }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/resource_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/resource_command.go#L127-L144
go
train
// Get prints one or many resources of a certain type
func (g *ResourceCommand) Get(client auth.ClientI) error
// Get prints one or many resources of a certain type func (g *ResourceCommand) Get(client auth.ClientI) error
{ collection, err := g.getCollection(client) if err != nil { return trace.Wrap(err) } // Note that only YAML is officially supported. Support for text and JSON // is experimental. switch g.format { case teleport.YAML: return collection.writeYAML(os.Stdout) case teleport.Text: return collection.writeText...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/resource_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/resource_command.go#L147-L179
go
train
// Create updates or insterts one or many resources
func (u *ResourceCommand) Create(client auth.ClientI) error
// Create updates or insterts one or many resources func (u *ResourceCommand) Create(client auth.ClientI) error
{ reader, err := utils.OpenFile(u.filename) if err != nil { return trace.Wrap(err) } decoder := kyaml.NewYAMLOrJSONDecoder(reader, 32*1024) count := 0 for { var raw services.UnknownResource err := decoder.Decode(&raw) if err != nil { if err == io.EOF { if count == 0 { return trace.BadParamete...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/resource_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/resource_command.go#L182-L216
go
train
// createTrustedCluster implements `tctl create cluster.yaml` command
func (u *ResourceCommand) createTrustedCluster(client auth.ClientI, raw services.UnknownResource) error
// createTrustedCluster implements `tctl create cluster.yaml` command func (u *ResourceCommand) createTrustedCluster(client auth.ClientI, raw services.UnknownResource) error
{ tc, err := services.GetTrustedClusterMarshaler().Unmarshal(raw.Raw) if err != nil { return trace.Wrap(err) } // check if such cluster already exists: name := tc.GetName() _, err = client.GetTrustedCluster(name) if err != nil && !trace.IsNotFound(err) { return trace.Wrap(err) } exists := (err == nil) i...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/resource_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/resource_command.go#L219-L229
go
train
// createCertAuthority creates certificate authority
func (u *ResourceCommand) createCertAuthority(client auth.ClientI, raw services.UnknownResource) error
// createCertAuthority creates certificate authority func (u *ResourceCommand) createCertAuthority(client auth.ClientI, raw services.UnknownResource) error
{ certAuthority, err := services.GetCertAuthorityMarshaler().UnmarshalCertAuthority(raw.Raw) if err != nil { return trace.Wrap(err) } if err := client.UpsertCertAuthority(certAuthority); err != nil { return trace.Wrap(err) } fmt.Printf("certificate authority '%s' has been updated\n", certAuthority.GetName())...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/resource_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/resource_command.go#L255-L266
go
train
// createUser implements 'tctl create user.yaml' command
func (u *ResourceCommand) createUser(client auth.ClientI, raw services.UnknownResource) error
// createUser implements 'tctl create user.yaml' command func (u *ResourceCommand) createUser(client auth.ClientI, raw services.UnknownResource) error
{ user, err := services.GetUserMarshaler().UnmarshalUser(raw.Raw) if err != nil { return trace.Wrap(err) } userName := user.GetName() if err := client.UpsertUser(user); err != nil { return trace.Wrap(err) } fmt.Printf("user '%s' has been updated\n", userName) return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/resource_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/resource_command.go#L269-L319
go
train
// Delete deletes resource by name
func (d *ResourceCommand) Delete(client auth.ClientI) (err error)
// Delete deletes resource by name func (d *ResourceCommand) Delete(client auth.ClientI) (err error)
{ if d.ref.Kind == "" || d.ref.Name == "" { return trace.BadParameter("provide a full resource name to delete, for example:\n$ tctl rm cluster/east\n") } switch d.ref.Kind { case services.KindNode: if err = client.DeleteNode(defaults.Namespace, d.ref.Name); err != nil { return trace.Wrap(err) } fmt.Pri...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/reversetunnel/cache.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/cache.go#L45-L56
go
train
// NewHostCertificateCache creates a shared host certificate cache that is // used by the forwarding server.
func NewHostCertificateCache(keygen sshca.Authority, authClient auth.ClientI) (*certificateCache, error)
// NewHostCertificateCache creates a shared host certificate cache that is // used by the forwarding server. func NewHostCertificateCache(keygen sshca.Authority, authClient auth.ClientI) (*certificateCache, error)
{ cache, err := ttlmap.New(defaults.HostCertCacheSize) if err != nil { return nil, trace.Wrap(err) } return &certificateCache{ keygen: keygen, cache: cache, authClient: authClient, }, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/reversetunnel/cache.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/cache.go#L63-L86
go
train
// GetHostCertificate will fetch a certificate from the cache. If the certificate // is not in the cache, it will be generated, put in the cache, and returned. Mul // Multiple callers can arrive and generate a host certificate at the same time. // This is a tradeoff to prevent long delays here due to the expensive // c...
func (c *certificateCache) GetHostCertificate(addr string, additionalPrincipals []string) (ssh.Signer, error)
// GetHostCertificate will fetch a certificate from the cache. If the certificate // is not in the cache, it will be generated, put in the cache, and returned. Mul // Multiple callers can arrive and generate a host certificate at the same time. // This is a tradeoff to prevent long delays here due to the expensive // c...
{ var certificate ssh.Signer var err error var ok bool var principals []string principals = append(principals, addr) principals = append(principals, additionalPrincipals...) certificate, ok = c.get(strings.Join(principals, ".")) if !ok { certificate, err = c.generateHostCert(principals) if err != nil { ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/reversetunnel/cache.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/cache.go#L90-L105
go
train
// get is goroutine safe and will return a ssh.Signer for a principal from // the cache.
func (c *certificateCache) get(addr string) (ssh.Signer, bool)
// get is goroutine safe and will return a ssh.Signer for a principal from // the cache. func (c *certificateCache) get(addr string) (ssh.Signer, bool)
{ c.mu.Lock() defer c.mu.Unlock() certificate, ok := c.cache.Get(addr) if !ok { return nil, false } certificateSigner, ok := certificate.(ssh.Signer) if !ok { return nil, false } return certificateSigner, true }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/reversetunnel/cache.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/cache.go#L109-L119
go
train
// set is goroutine safe and will set a ssh.Signer for a principal in // the cache.
func (c *certificateCache) set(addr string, certificate ssh.Signer, ttl time.Duration) error
// set is goroutine safe and will set a ssh.Signer for a principal in // the cache. func (c *certificateCache) set(addr string, certificate ssh.Signer, ttl time.Duration) error
{ c.mu.Lock() defer c.mu.Unlock() err := c.cache.Set(addr, certificate, ttl) if err != nil { return trace.Wrap(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/reversetunnel/cache.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/cache.go#L123-L173
go
train
// generateHostCert will generate a SSH host certificate for a given // principal.
func (c *certificateCache) generateHostCert(principals []string) (ssh.Signer, error)
// generateHostCert will generate a SSH host certificate for a given // principal. func (c *certificateCache) generateHostCert(principals []string) (ssh.Signer, error)
{ if len(principals) == 0 { return nil, trace.BadParameter("at least one principal must be provided") } // Generate public/private keypair. privBytes, pubBytes, err := c.keygen.GetNewKeyPairFromPool() if err != nil { return nil, trace.Wrap(err) } // Generate a SSH host certificate. clusterName, err := c....
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/monitor.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/monitor.go#L81-L104
go
train
// CheckAndSetDefaults checks values and sets defaults
func (m *MonitorConfig) CheckAndSetDefaults() error
// CheckAndSetDefaults checks values and sets defaults func (m *MonitorConfig) CheckAndSetDefaults() error
{ if m.Context == nil { return trace.BadParameter("missing parameter Context") } if m.DisconnectExpiredCert.IsZero() && m.ClientIdleTimeout == 0 { return trace.BadParameter("either DisconnectExpiredCert or ClientIdleTimeout should be set") } if m.Conn == nil { return trace.BadParameter("missing parameter Co...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/monitor.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/monitor.go#L107-L114
go
train
// NewMonitor returns a new monitor
func NewMonitor(cfg MonitorConfig) (*Monitor, error)
// NewMonitor returns a new monitor func NewMonitor(cfg MonitorConfig) (*Monitor, error)
{ if err := cfg.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } return &Monitor{ MonitorConfig: cfg, }, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/monitor.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/monitor.go#L125-L187
go
train
// Start starts monitoring connection
func (w *Monitor) Start()
// Start starts monitoring connection func (w *Monitor) Start()
{ var certTime <-chan time.Time if !w.DisconnectExpiredCert.IsZero() { t := time.NewTimer(w.DisconnectExpiredCert.Sub(w.Clock.Now().UTC())) defer t.Stop() certTime = t.C } var idleTimer *time.Timer var idleTime <-chan time.Time if w.ClientIdleTimeout != 0 { idleTimer = time.NewTimer(w.ClientIdleTimeout)...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/teleport/common/teleport.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/teleport/common/teleport.go#L50-L166
go
train
// Run inits/starts the process according to the provided options
func Run(options Options) (executedCommand string, conf *service.Config)
// Run inits/starts the process according to the provided options func Run(options Options) (executedCommand string, conf *service.Config)
{ var err error // configure trace's errors to produce full stack traces isDebug, _ := strconv.ParseBool(os.Getenv(teleport.VerboseLogsEnvVar)) if isDebug { trace.SetDebug(true) } // configure logger for a typical CLI scenario until configuration file is // parsed utils.InitLogger(utils.LoggingForDaemon, lo...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/teleport/common/teleport.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/teleport/common/teleport.go#L169-L171
go
train
// OnStart is the handler for "start" CLI command
func OnStart(config *service.Config) error
// OnStart is the handler for "start" CLI command func OnStart(config *service.Config) error
{ return service.Run(context.TODO(), *config, nil) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/teleport/common/teleport.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/teleport/common/teleport.go#L174-L195
go
train
// onStatus is the handler for "status" CLI command
func onStatus() error
// onStatus is the handler for "status" CLI command func onStatus() error
{ sshClient := os.Getenv("SSH_CLIENT") systemUser := os.Getenv("USER") teleportUser := os.Getenv(teleport.SSHTeleportUser) proxyHost := os.Getenv(teleport.SSHSessionWebproxyAddr) clusterName := os.Getenv(teleport.SSHTeleportClusterName) hostUUID := os.Getenv(teleport.SSHTeleportHostUUID) sid := os.Getenv(telepo...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/teleport/common/teleport.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/teleport/common/teleport.go#L208-L248
go
train
// onSCP implements handling of 'scp' requests on the server side. When the teleport SSH daemon // receives an SSH "scp" request, it launches itself with 'scp' flag under the requested // user's privileges // // This is the entry point of "teleport scp" call (the parent process is the teleport daemon)
func onSCP(scpFlags *scp.Flags) (err error)
// onSCP implements handling of 'scp' requests on the server side. When the teleport SSH daemon // receives an SSH "scp" request, it launches itself with 'scp' flag under the requested // user's privileges // // This is the entry point of "teleport scp" call (the parent process is the teleport daemon) func onSCP(scpFla...
{ // when 'teleport scp' is executed, it cannot write logs to stderr (because // they're automatically replayed by the scp client) utils.SwitchLoggingtoSyslog() if len(scpFlags.Target) == 0 { return trace.BadParameter("teleport scp: missing an argument") } // get user's home dir (it serves as a default destin...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/copy.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/copy.go#L20-L27
go
train
// CopyByteSlice returns a copy of the byte slice.
func CopyByteSlice(in []byte) []byte
// CopyByteSlice returns a copy of the byte slice. func CopyByteSlice(in []byte) []byte
{ if in == nil { return nil } out := make([]byte, len(in)) copy(out, in) return out }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/copy.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/copy.go#L30-L39
go
train
// CopyByteSlices returns a copy of the byte slices.
func CopyByteSlices(in [][]byte) [][]byte
// CopyByteSlices returns a copy of the byte slices. func CopyByteSlices(in [][]byte) [][]byte
{ if in == nil { return nil } out := make([][]byte, len(in)) for i := range in { out[i] = CopyByteSlice(in[i]) } return out }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/copy.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/copy.go#L42-L50
go
train
// JoinStringSlices joins two string slices and returns a resulting slice
func JoinStringSlices(a []string, b []string) []string
// JoinStringSlices joins two string slices and returns a resulting slice func JoinStringSlices(a []string, b []string) []string
{ if len(a)+len(b) == 0 { return nil } out := make([]string, 0, len(a)+len(b)) out = append(out, a...) out = append(out, b...) return out }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/copy.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/copy.go#L54-L63
go
train
// CopyStrings makes a deep copy of the passed in string slice and returns // the copy.
func CopyStrings(in []string) []string
// CopyStrings makes a deep copy of the passed in string slice and returns // the copy. func CopyStrings(in []string) []string
{ if in == nil { return nil } out := make([]string, len(in)) copy(out, in) return out }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/copy.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/copy.go#L67-L80
go
train
// CopyStringMapSlices makes a deep copy of the passed in map[string][]string // and returns the copy.
func CopyStringMapSlices(a map[string][]string) map[string][]string
// CopyStringMapSlices makes a deep copy of the passed in map[string][]string // and returns the copy. func CopyStringMapSlices(a map[string][]string) map[string][]string
{ if a == nil { return nil } out := make(map[string][]string) for key, values := range a { vout := make([]string, len(values)) copy(vout, values) out[key] = vout } return out }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/copy.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/copy.go#L83-L94
go
train
// CopyStringMap makes a deep copy of a map[string]string and returns the copy.
func CopyStringMap(a map[string]string) map[string]string
// CopyStringMap makes a deep copy of a map[string]string and returns the copy. func CopyStringMap(a map[string]string) map[string]string
{ if a == nil { return nil } out := make(map[string]string) for key, value := range a { out[key] = value } return out }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/copy.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/copy.go#L98-L109
go
train
// CopyStringMapInterface makes a deep copy of the passed in map[string]interface{} // and returns the copy.
func CopyStringMapInterface(a map[string]interface{}) map[string]interface{}
// CopyStringMapInterface makes a deep copy of the passed in map[string]interface{} // and returns the copy. func CopyStringMapInterface(a map[string]interface{}) map[string]interface{}
{ if a == nil { return nil } out := make(map[string]interface{}) for key, value := range a { out[key] = value } return out }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/copy.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/copy.go#L112-L124
go
train
// ReplaceInSlice replaces element old with new and returns a new slice.
func ReplaceInSlice(s []string, old string, new string) []string
// ReplaceInSlice replaces element old with new and returns a new slice. func ReplaceInSlice(s []string, old string, new string) []string
{ out := make([]string, 0, len(s)) for _, x := range s { if x == old { out = append(out, new) } else { out = append(out, x) } } return out }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/service/connect.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/connect.go#L41-L68
go
train
// reconnectToAuthService continuously attempts to reconnect to the auth // service until succeeds or process gets shut down
func (process *TeleportProcess) reconnectToAuthService(role teleport.Role) (*Connector, error)
// reconnectToAuthService continuously attempts to reconnect to the auth // service until succeeds or process gets shut down func (process *TeleportProcess) reconnectToAuthService(role teleport.Role) (*Connector, error)
{ retryTime := defaults.HighResPollingPeriod for { connector, err := process.connectToAuthService(role) if err == nil { // if connected and client is present, make sure the connector's // client works, by using call that should succeed at all times if connector.Client != nil { _, err = connector.Cli...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/service/connect.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/connect.go#L72-L82
go
train
// connectToAuthService attempts to login into the auth servers specified in the // configuration and receive credentials.
func (process *TeleportProcess) connectToAuthService(role teleport.Role) (*Connector, error)
// connectToAuthService attempts to login into the auth servers specified in the // configuration and receive credentials. func (process *TeleportProcess) connectToAuthService(role teleport.Role) (*Connector, error)
{ connector, err := process.connect(role) if err != nil { return nil, trace.Wrap(err) } process.Debugf("Connected client: %v", connector.ClientIdentity) process.Debugf("Connected server: %v", connector.ServerIdentity) process.addConnector(connector) return connector, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/service/connect.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/connect.go#L279-L284
go
train
// newWatcher returns a new watcher, // either using local auth server connection or remote client
func (process *TeleportProcess) newWatcher(conn *Connector, watch services.Watch) (services.Watcher, error)
// newWatcher returns a new watcher, // either using local auth server connection or remote client func (process *TeleportProcess) newWatcher(conn *Connector, watch services.Watch) (services.Watcher, error)
{ if conn.ClientIdentity.ID.Role == teleport.RoleAdmin || conn.ClientIdentity.ID.Role == teleport.RoleAuth { return process.localAuth.NewWatcher(process.ExitContext(), watch) } return conn.Client.NewWatcher(process.ExitContext(), watch) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/service/connect.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/connect.go#L289-L294
go
train
// getCertAuthority returns cert authority by ID. // In case if auth servers, the role is 'TeleportAdmin' and instead of using // TLS client this method uses the local auth server.
func (process *TeleportProcess) getCertAuthority(conn *Connector, id services.CertAuthID, loadPrivateKeys bool) (services.CertAuthority, error)
// getCertAuthority returns cert authority by ID. // In case if auth servers, the role is 'TeleportAdmin' and instead of using // TLS client this method uses the local auth server. func (process *TeleportProcess) getCertAuthority(conn *Connector, id services.CertAuthID, loadPrivateKeys bool) (services.CertAuthority, er...
{ if conn.ClientIdentity.ID.Role == teleport.RoleAdmin || conn.ClientIdentity.ID.Role == teleport.RoleAuth { return process.localAuth.GetCertAuthority(id, loadPrivateKeys) } return conn.Client.GetCertAuthority(id, loadPrivateKeys) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/service/connect.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/connect.go#L299-L323
go
train
// reRegister receives new identity credentials for proxy, node and auth. // In case if auth servers, the role is 'TeleportAdmin' and instead of using // TLS client this method uses the local auth server.
func (process *TeleportProcess) reRegister(conn *Connector, additionalPrincipals []string, dnsNames []string, rotation services.Rotation) (*auth.Identity, error)
// reRegister receives new identity credentials for proxy, node and auth. // In case if auth servers, the role is 'TeleportAdmin' and instead of using // TLS client this method uses the local auth server. func (process *TeleportProcess) reRegister(conn *Connector, additionalPrincipals []string, dnsNames []string, rotat...
{ if conn.ClientIdentity.ID.Role == teleport.RoleAdmin || conn.ClientIdentity.ID.Role == teleport.RoleAuth { return auth.GenerateIdentity(process.localAuth, conn.ClientIdentity.ID, additionalPrincipals, dnsNames) } const reason = "re-register" keyPair, err := process.generateKeyPair(conn.ClientIdentity.ID.Role, ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/service/connect.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/connect.go#L441-L466
go
train
// periodicSyncRotationState checks rotation state periodically and // takes action if necessary
func (process *TeleportProcess) periodicSyncRotationState() error
// periodicSyncRotationState checks rotation state periodically and // takes action if necessary func (process *TeleportProcess) periodicSyncRotationState() error
{ // start rotation only after teleport process has started eventC := make(chan Event, 1) process.WaitForEvent(process.ExitContext(), TeleportReadyEvent, eventC) select { case <-eventC: process.Infof("The new service has started successfully. Starting syncing rotation status with period %v.", process.Config.Pol...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/service/connect.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/connect.go#L475-L542
go
train
// syncRotationCycle executes a rotation cycle that returns: // // * nil whenever rotation state leads to teleport reload event // * error whenever rotation sycle has to be restarted // // the function accepts extra delay timer extraDelay in case if parent // function needs a
func (process *TeleportProcess) syncRotationStateCycle() error
// syncRotationCycle executes a rotation cycle that returns: // // * nil whenever rotation state leads to teleport reload event // * error whenever rotation sycle has to be restarted // // the function accepts extra delay timer extraDelay in case if parent // function needs a func (process *TeleportProcess) syncRotatio...
{ connectors := process.getConnectors() if len(connectors) == 0 { return trace.BadParameter("no connectors found") } // it is important to use the same view of the certificate authority // for all internal services at the same time, so that the same // procedure will be applied at the same time for multiple se...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/service/connect.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/connect.go#L546-L570
go
train
// syncRotationStateAndBroadcast syncs rotation state and broadcasts events // when phase has been changed or reload happened
func (process *TeleportProcess) syncRotationStateAndBroadcast(conn *Connector) (*rotationStatus, error)
// syncRotationStateAndBroadcast syncs rotation state and broadcasts events // when phase has been changed or reload happened func (process *TeleportProcess) syncRotationStateAndBroadcast(conn *Connector) (*rotationStatus, error)
{ status, err := process.syncRotationState(conn) if err != nil { process.BroadcastEvent(Event{Name: TeleportDegradedEvent, Payload: nil}) if trace.IsConnectionProblem(err) { process.Warningf("Connection problem: sync rotation state: %v.", err) } else { process.Warningf("Failed to sync rotation state: %v....
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/service/connect.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/connect.go#L574-L598
go
train
// syncRotationState compares cluster rotation state with the state of // internal services and performs the rotation if necessary.
func (process *TeleportProcess) syncRotationState(conn *Connector) (*rotationStatus, error)
// syncRotationState compares cluster rotation state with the state of // internal services and performs the rotation if necessary. func (process *TeleportProcess) syncRotationState(conn *Connector) (*rotationStatus, error)
{ connectors := process.getConnectors() ca, err := process.getCertAuthority(conn, services.CertAuthID{ DomainName: conn.ClientIdentity.ClusterName, Type: services.HostCA, }, false) if err != nil { return nil, trace.Wrap(err) } var status rotationStatus status.ca = ca for _, conn := range connectors...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/service/connect.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/connect.go#L602-L608
go
train
// syncServiceRotationState syncs up rotation state for internal services (Auth, Proxy, Node) and // if necessary, updates credentials. Returns true if the service will need to reload.
func (process *TeleportProcess) syncServiceRotationState(ca services.CertAuthority, conn *Connector) (*rotationStatus, error)
// syncServiceRotationState syncs up rotation state for internal services (Auth, Proxy, Node) and // if necessary, updates credentials. Returns true if the service will need to reload. func (process *TeleportProcess) syncServiceRotationState(ca services.CertAuthority, conn *Connector) (*rotationStatus, error)
{ state, err := process.storage.GetState(conn.ClientIdentity.ID.Role) if err != nil { return nil, trace.Wrap(err) } return process.rotate(conn, *state, ca.GetRotation()) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/service/connect.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/connect.go#L623-L774
go
train
// rotate is called to check if rotation should be triggered.
func (process *TeleportProcess) rotate(conn *Connector, localState auth.StateV2, remote services.Rotation) (*rotationStatus, error)
// rotate is called to check if rotation should be triggered. func (process *TeleportProcess) rotate(conn *Connector, localState auth.StateV2, remote services.Rotation) (*rotationStatus, error)
{ id := conn.ClientIdentity.ID local := localState.Spec.Rotation additionalPrincipals, dnsNames, err := process.getAdditionalPrincipals(id.Role) if err != nil { return nil, trace.Wrap(err) } additionalPrincipals = utils.ReplaceInSlice( additionalPrincipals, defaults.AnyAddress, defaults.Localhost, ) ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/service/connect.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/connect.go#L778-L806
go
train
// newClient attempts to connect directly to the Auth Server. If it fails, it // falls back to trying to connect to the Auth Server through the proxy.
func (process *TeleportProcess) newClient(authServers []utils.NetAddr, identity *auth.Identity) (*auth.Client, bool, error)
// newClient attempts to connect directly to the Auth Server. If it fails, it // falls back to trying to connect to the Auth Server through the proxy. func (process *TeleportProcess) newClient(authServers []utils.NetAddr, identity *auth.Identity) (*auth.Client, bool, error)
{ directClient, err := process.newClientDirect(authServers, identity) if err != nil { return nil, false, trace.Wrap(err) } // Try and connect to the Auth Server. If the request fails, try and // connect through a tunnel. log.Debugf("Attempting to connect to Auth Server directly.") _, err = directClient.GetLo...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/service/connect.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/connect.go#L810-L835
go
train
// findReverseTunnel uses the web proxy to discover where the SSH reverse tunnel // server is running.
func (process *TeleportProcess) findReverseTunnel(addrs []utils.NetAddr) (string, error)
// findReverseTunnel uses the web proxy to discover where the SSH reverse tunnel // server is running. func (process *TeleportProcess) findReverseTunnel(addrs []utils.NetAddr) (string, error)
{ var errs []error for _, addr := range addrs { // In insecure mode, any certificate is accepted. In secure mode the hosts // CAs are used to validate the certificate on the proxy. clt, err := client.NewCredentialsClient( addr.String(), lib.IsInsecureDevMode(), nil) if err != nil { return "", tra...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/kube/proxy/server.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/server.go#L47-L68
go
train
// CheckAndSetDefaults checks and sets default values
func (c *TLSServerConfig) CheckAndSetDefaults() error
// CheckAndSetDefaults checks and sets default values func (c *TLSServerConfig) CheckAndSetDefaults() error
{ if err := c.ForwarderConfig.CheckAndSetDefaults(); err != nil { return trace.Wrap(err) } if c.TLS == nil { return trace.BadParameter("missing parameter TLS") } c.TLS.ClientAuth = tls.RequireAndVerifyClientCert if c.TLS.ClientCAs == nil { return trace.BadParameter("missing parameter TLS.ClientCAs") } if...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/kube/proxy/server.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/server.go#L78-L113
go
train
// NewTLSServer returns new unstarted TLS server
func NewTLSServer(cfg TLSServerConfig) (*TLSServer, error)
// NewTLSServer returns new unstarted TLS server func NewTLSServer(cfg TLSServerConfig) (*TLSServer, error)
{ if err := cfg.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } // limiter limits requests by frequency and amount of simultaneous // connections per client limiter, err := limiter.NewLimiter(cfg.LimiterConfig) if err != nil { return nil, trace.Wrap(err) } fwd, err := NewForwarder(cfg.For...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/kube/proxy/server.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/server.go#L123-L144
go
train
// GetConfigForClient is getting called on every connection // and server's GetConfigForClient reloads the list of trusted // local and remote certificate authorities
func (t *TLSServer) GetConfigForClient(info *tls.ClientHelloInfo) (*tls.Config, error)
// GetConfigForClient is getting called on every connection // and server's GetConfigForClient reloads the list of trusted // local and remote certificate authorities func (t *TLSServer) GetConfigForClient(info *tls.ClientHelloInfo) (*tls.Config, error)
{ var clusterName string var err error if info.ServerName != "" { clusterName, err = auth.DecodeClusterName(info.ServerName) if err != nil { if !trace.IsNotFound(err) { log.Debugf("Ignoring unsupported cluster name name %q.", info.ServerName) clusterName = "" } } } pool, err := auth.ClientCert...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/spki.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/spki.go#L30-L33
go
train
// CalculateSPKI the hash value of the SPKI header in a certificate.
func CalculateSPKI(cert *x509.Certificate) string
// CalculateSPKI the hash value of the SPKI header in a certificate. func CalculateSPKI(cert *x509.Certificate) string
{ sum := sha256.Sum256(cert.RawSubjectPublicKeyInfo) return "sha256:" + hex.EncodeToString(sum[:]) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/spki.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/spki.go#L36-L53
go
train
// CheckSPKI the passed in pin against the calculated value from a certificate.
func CheckSPKI(pin string, cert *x509.Certificate) error
// CheckSPKI the passed in pin against the calculated value from a certificate. func CheckSPKI(pin string, cert *x509.Certificate) error
{ // Check that the format of the pin is valid. parts := strings.Split(pin, ":") if len(parts) != 2 { return trace.BadParameter("invalid format for certificate pin, expected algorithm:pin") } if parts[0] != "sha256" { return trace.BadParameter("sha256 only supported hashing algorithm for certificate pin") } ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/httplib/httplib.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/httplib/httplib.go#L45-L59
go
train
// MakeHandler returns a new httprouter.Handle func from a handler func
func MakeHandler(fn HandlerFunc) httprouter.Handle
// MakeHandler returns a new httprouter.Handle func from a handler func func MakeHandler(fn HandlerFunc) httprouter.Handle
{ return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) { // ensure that neither proxies nor browsers cache http traffic SetNoCacheHeaders(w.Header()) out, err := fn(w, r, p) if err != nil { trace.WriteError(w, err) return } if out != nil { roundtrip.ReplyJSON(w, http.StatusOK...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/httplib/httplib.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/httplib/httplib.go#L62-L76
go
train
// MakeStdHandler returns a new http.Handle func from http.HandlerFunc
func MakeStdHandler(fn StdHandlerFunc) http.HandlerFunc
// MakeStdHandler returns a new http.Handle func from http.HandlerFunc func MakeStdHandler(fn StdHandlerFunc) http.HandlerFunc
{ return func(w http.ResponseWriter, r *http.Request) { // ensure that neither proxies nor browsers cache http traffic SetNoCacheHeaders(w.Header()) out, err := fn(w, r) if err != nil { trace.WriteError(w, err) return } if out != nil { roundtrip.ReplyJSON(w, http.StatusOK, out) } } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/httplib/httplib.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/httplib/httplib.go#L79-L90
go
train
// WithCSRFProtection ensures that request to unauthenticated API is checked against CSRF attacks
func WithCSRFProtection(fn HandlerFunc) httprouter.Handle
// WithCSRFProtection ensures that request to unauthenticated API is checked against CSRF attacks func WithCSRFProtection(fn HandlerFunc) httprouter.Handle
{ hanlderFn := MakeHandler(fn) return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) { err := csrf.VerifyHTTPHeader(r) if err != nil { log.Warningf("unable to validate CSRF token %v", err) trace.WriteError(w, trace.AccessDenied("access denied")) return } hanlderFn(w, r, p) } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/httplib/httplib.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/httplib/httplib.go#L94-L103
go
train
// ReadJSON reads HTTP json request and unmarshals it // into passed interface{} obj
func ReadJSON(r *http.Request, val interface{}) error
// ReadJSON reads HTTP json request and unmarshals it // into passed interface{} obj func ReadJSON(r *http.Request, val interface{}) error
{ data, err := ioutil.ReadAll(r.Body) if err != nil { return trace.Wrap(err) } if err := json.Unmarshal(data, &val); err != nil { return trace.BadParameter("request: %v", err.Error()) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/httplib/httplib.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/httplib/httplib.go#L107-L115
go
train
// ConvertResponse converts http error to internal error type // based on HTTP response code and HTTP body contents
func ConvertResponse(re *roundtrip.Response, err error) (*roundtrip.Response, error)
// ConvertResponse converts http error to internal error type // based on HTTP response code and HTTP body contents func ConvertResponse(re *roundtrip.Response, err error) (*roundtrip.Response, error)
{ if err != nil { if uerr, ok := err.(*url.Error); ok && uerr != nil && uerr.Err != nil { return nil, trace.ConnectionProblem(uerr.Err, uerr.Error()) } return nil, trace.ConvertSystemError(err) } return re, trace.ReadError(re.Code(), re.Bytes()) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/httplib/httplib.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/httplib/httplib.go#L119-L131
go
train
// ParseBool will parse boolean variable from url query // returns value, ok, error
func ParseBool(q url.Values, name string) (bool, bool, error)
// ParseBool will parse boolean variable from url query // returns value, ok, error func ParseBool(q url.Values, name string) (bool, bool, error)
{ stringVal := q.Get(name) if stringVal == "" { return false, false, nil } val, err := strconv.ParseBool(stringVal) if err != nil { return false, false, trace.BadParameter( "'%v': expected 'true' or 'false', got %v", name, stringVal) } return val, true, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/httplib/httplib.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/httplib/httplib.go#L143-L148
go
train
// Rewrite creates a rewrite pair, panics if in epxression // is not a valid regular expressoin
func Rewrite(in, out string) RewritePair
// Rewrite creates a rewrite pair, panics if in epxression // is not a valid regular expressoin func Rewrite(in, out string) RewritePair
{ return RewritePair{ Expr: regexp.MustCompile(in), Replacement: out, } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/httplib/httplib.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/httplib/httplib.go#L151-L158
go
train
// RewritePaths creates a middleware that rewrites paths in incoming request
func RewritePaths(next http.Handler, rewrites ...RewritePair) http.Handler
// RewritePaths creates a middleware that rewrites paths in incoming request func RewritePaths(next http.Handler, rewrites ...RewritePair) http.Handler
{ return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { for _, rewrite := range rewrites { req.URL.Path = rewrite.Expr.ReplaceAllString(req.URL.Path, rewrite.Replacement) } next.ServeHTTP(w, req) }) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/httplib/httplib.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/httplib/httplib.go#L161-L168
go
train
// SafeRedirect performs a relative redirect to the URI part of the provided redirect URL
func SafeRedirect(w http.ResponseWriter, r *http.Request, redirectURL string) error
// SafeRedirect performs a relative redirect to the URI part of the provided redirect URL func SafeRedirect(w http.ResponseWriter, r *http.Request, redirectURL string) error
{ parsedURL, err := url.Parse(redirectURL) if err != nil { return trace.Wrap(err) } http.Redirect(w, r, parsedURL.RequestURI(), http.StatusFound) return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/ctx.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/ctx.go#L138-L150
go
train
// GetCertificate parses the SSH certificate bytes and returns a *ssh.Certificate.
func (c IdentityContext) GetCertificate() (*ssh.Certificate, error)
// GetCertificate parses the SSH certificate bytes and returns a *ssh.Certificate. func (c IdentityContext) GetCertificate() (*ssh.Certificate, error)
{ k, _, _, _, err := ssh.ParseAuthorizedKey(c.Certificate) if err != nil { return nil, trace.Wrap(err) } cert, ok := k.(*ssh.Certificate) if !ok { return nil, trace.BadParameter("not a certificate") } return cert, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/ctx.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/ctx.go#L246-L313
go
train
// NewServerContext creates a new *ServerContext which is used to pass and // manage resources.
func NewServerContext(srv Server, conn *ssh.ServerConn, identityContext IdentityContext) (*ServerContext, error)
// NewServerContext creates a new *ServerContext which is used to pass and // manage resources. func NewServerContext(srv Server, conn *ssh.ServerConn, identityContext IdentityContext) (*ServerContext, error)
{ clusterConfig, err := srv.GetAccessPoint().GetClusterConfig() if err != nil { return nil, trace.Wrap(err) } cancelContext, cancel := context.WithCancel(context.TODO()) ctx := &ServerContext{ id: int(atomic.AddInt32(&ctxID, int32(1))), env: make(map[string]string), srv: ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/ctx.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/ctx.go#L332-L360
go
train
// CreateOrJoinSession will look in the SessionRegistry for the session ID. If // no session is found, a new one is created. If one is found, it is returned.
func (c *ServerContext) CreateOrJoinSession(reg *SessionRegistry) error
// CreateOrJoinSession will look in the SessionRegistry for the session ID. If // no session is found, a new one is created. If one is found, it is returned. func (c *ServerContext) CreateOrJoinSession(reg *SessionRegistry) error
{ // As SSH conversation progresses, at some point a session will be created and // its ID will be added to the environment ssid, found := c.GetEnv(sshutils.SessionEnvVar) if !found { return nil } // make sure whatever session is requested is a valid session _, err := rsession.ParseID(ssid) if err != nil { ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/ctx.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/ctx.go#L363-L367
go
train
// GetClientLastActive returns time when client was last active
func (c *ServerContext) GetClientLastActive() time.Time
// GetClientLastActive returns time when client was last active func (c *ServerContext) GetClientLastActive() time.Time
{ c.RLock() defer c.RUnlock() return c.clientLastActive }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/ctx.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/ctx.go#L371-L375
go
train
// UpdateClientActivity sets last recorded client activity associated with this context // either channel or session
func (c *ServerContext) UpdateClientActivity()
// UpdateClientActivity sets last recorded client activity associated with this context // either channel or session func (c *ServerContext) UpdateClientActivity()
{ c.Lock() defer c.Unlock() c.clientLastActive = c.srv.GetClock().Now().UTC() }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/ctx.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/ctx.go#L379-L383
go
train
// AddCloser adds any closer in ctx that will be called // whenever server closes session channel
func (c *ServerContext) AddCloser(closer io.Closer)
// AddCloser adds any closer in ctx that will be called // whenever server closes session channel func (c *ServerContext) AddCloser(closer io.Closer)
{ c.Lock() defer c.Unlock() c.closers = append(c.closers, closer) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/ctx.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/ctx.go#L386-L390
go
train
// GetAgent returns a agent.Agent which represents the capabilities of an SSH agent.
func (c *ServerContext) GetAgent() agent.Agent
// GetAgent returns a agent.Agent which represents the capabilities of an SSH agent. func (c *ServerContext) GetAgent() agent.Agent
{ c.RLock() defer c.RUnlock() return c.agent }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/ctx.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/ctx.go#L393-L397
go
train
// GetAgentChannel returns the channel over which communication with the agent occurs.
func (c *ServerContext) GetAgentChannel() ssh.Channel
// GetAgentChannel returns the channel over which communication with the agent occurs. func (c *ServerContext) GetAgentChannel() ssh.Channel
{ c.RLock() defer c.RUnlock() return c.agentChannel }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/ctx.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/ctx.go#L400-L409
go
train
// SetAgent sets the agent and channel over which communication with the agent occurs.
func (c *ServerContext) SetAgent(a agent.Agent, channel ssh.Channel)
// SetAgent sets the agent and channel over which communication with the agent occurs. func (c *ServerContext) SetAgent(a agent.Agent, channel ssh.Channel)
{ c.Lock() defer c.Unlock() if c.agentChannel != nil { c.Infof("closing previous agent channel") c.agentChannel.Close() } c.agentChannel = channel c.agent = a }