repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
gravitational/teleport
lib/services/tunnel.go
UnmarshalReverseTunnel
func (*TeleportTunnelMarshaler) UnmarshalReverseTunnel(bytes []byte, opts ...MarshalOption) (ReverseTunnel, error) { return UnmarshalReverseTunnel(bytes, opts...) }
go
func (*TeleportTunnelMarshaler) UnmarshalReverseTunnel(bytes []byte, opts ...MarshalOption) (ReverseTunnel, error) { return UnmarshalReverseTunnel(bytes, opts...) }
[ "func", "(", "*", "TeleportTunnelMarshaler", ")", "UnmarshalReverseTunnel", "(", "bytes", "[", "]", "byte", ",", "opts", "...", "MarshalOption", ")", "(", "ReverseTunnel", ",", "error", ")", "{", "return", "UnmarshalReverseTunnel", "(", "bytes", ",", "opts", "...", ")", "\n", "}" ]
// UnmarshalReverseTunnel unmarshals reverse tunnel from JSON or YAML
[ "UnmarshalReverseTunnel", "unmarshals", "reverse", "tunnel", "from", "JSON", "or", "YAML" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/tunnel.go#L340-L342
train
gravitational/teleport
lib/services/tunnel.go
MarshalReverseTunnel
func (*TeleportTunnelMarshaler) MarshalReverseTunnel(rt ReverseTunnel, opts ...MarshalOption) ([]byte, error) { cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } type tunv1 interface { V1() *ReverseTunnelV1 } type tunv2 interface { V2() *ReverseTunnelV2 } version := cfg.GetVersion() switch version { case V1: v, ok := rt.(tunv1) if !ok { return nil, trace.BadParameter("don't know how to marshal %v", V1) } return json.Marshal(v.V1()) case V2: v, ok := rt.(tunv2) if !ok { return nil, trace.BadParameter("don't know how to marshal %v", V2) } v2 := v.V2() if !cfg.PreserveResourceID { // avoid modifying the original object // to prevent unexpected data races copy := *v2 copy.SetResourceID(0) v2 = &copy } return utils.FastMarshal(v2) default: return nil, trace.BadParameter("version %v is not supported", version) } }
go
func (*TeleportTunnelMarshaler) MarshalReverseTunnel(rt ReverseTunnel, opts ...MarshalOption) ([]byte, error) { cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } type tunv1 interface { V1() *ReverseTunnelV1 } type tunv2 interface { V2() *ReverseTunnelV2 } version := cfg.GetVersion() switch version { case V1: v, ok := rt.(tunv1) if !ok { return nil, trace.BadParameter("don't know how to marshal %v", V1) } return json.Marshal(v.V1()) case V2: v, ok := rt.(tunv2) if !ok { return nil, trace.BadParameter("don't know how to marshal %v", V2) } v2 := v.V2() if !cfg.PreserveResourceID { // avoid modifying the original object // to prevent unexpected data races copy := *v2 copy.SetResourceID(0) v2 = &copy } return utils.FastMarshal(v2) default: return nil, trace.BadParameter("version %v is not supported", version) } }
[ "func", "(", "*", "TeleportTunnelMarshaler", ")", "MarshalReverseTunnel", "(", "rt", "ReverseTunnel", ",", "opts", "...", "MarshalOption", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "cfg", ",", "err", ":=", "collectOptions", "(", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "type", "tunv1", "interface", "{", "V1", "(", ")", "*", "ReverseTunnelV1", "\n", "}", "\n", "type", "tunv2", "interface", "{", "V2", "(", ")", "*", "ReverseTunnelV2", "\n", "}", "\n", "version", ":=", "cfg", ".", "GetVersion", "(", ")", "\n", "switch", "version", "{", "case", "V1", ":", "v", ",", "ok", ":=", "rt", ".", "(", "tunv1", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"don't know how to marshal %v\"", ",", "V1", ")", "\n", "}", "\n", "return", "json", ".", "Marshal", "(", "v", ".", "V1", "(", ")", ")", "\n", "case", "V2", ":", "v", ",", "ok", ":=", "rt", ".", "(", "tunv2", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"don't know how to marshal %v\"", ",", "V2", ")", "\n", "}", "\n", "v2", ":=", "v", ".", "V2", "(", ")", "\n", "if", "!", "cfg", ".", "PreserveResourceID", "{", "copy", ":=", "*", "v2", "\n", "copy", ".", "SetResourceID", "(", "0", ")", "\n", "v2", "=", "&", "copy", "\n", "}", "\n", "return", "utils", ".", "FastMarshal", "(", "v2", ")", "\n", "default", ":", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"version %v is not supported\"", ",", "version", ")", "\n", "}", "\n", "}" ]
// MarshalRole marshalls role into JSON
[ "MarshalRole", "marshalls", "role", "into", "JSON" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/tunnel.go#L345-L381
train
gravitational/teleport
lib/utils/syslog.go
SwitchLoggingtoSyslog
func SwitchLoggingtoSyslog() error { log.StandardLogger().SetHooks(make(log.LevelHooks)) hook, err := logrusSyslog.NewSyslogHook("", "", syslog.LOG_WARNING, "") if err != nil { // syslog is not available log.SetOutput(os.Stderr) return trace.Wrap(err) } log.AddHook(hook) // ... and disable stderr: log.SetOutput(ioutil.Discard) return nil }
go
func SwitchLoggingtoSyslog() error { log.StandardLogger().SetHooks(make(log.LevelHooks)) hook, err := logrusSyslog.NewSyslogHook("", "", syslog.LOG_WARNING, "") if err != nil { // syslog is not available log.SetOutput(os.Stderr) return trace.Wrap(err) } log.AddHook(hook) // ... and disable stderr: log.SetOutput(ioutil.Discard) return nil }
[ "func", "SwitchLoggingtoSyslog", "(", ")", "error", "{", "log", ".", "StandardLogger", "(", ")", ".", "SetHooks", "(", "make", "(", "log", ".", "LevelHooks", ")", ")", "\n", "hook", ",", "err", ":=", "logrusSyslog", ".", "NewSyslogHook", "(", "\"\"", ",", "\"\"", ",", "syslog", ".", "LOG_WARNING", ",", "\"\"", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "SetOutput", "(", "os", ".", "Stderr", ")", "\n", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "log", ".", "AddHook", "(", "hook", ")", "\n", "log", ".", "SetOutput", "(", "ioutil", ".", "Discard", ")", "\n", "return", "nil", "\n", "}" ]
// SwitchLoggingtoSyslog tells the logger to send the output to syslog. This // code is behind a build flag because Windows does not support syslog.
[ "SwitchLoggingtoSyslog", "tells", "the", "logger", "to", "send", "the", "output", "to", "syslog", ".", "This", "code", "is", "behind", "a", "build", "flag", "because", "Windows", "does", "not", "support", "syslog", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/syslog.go#L33-L45
train
gravitational/teleport
lib/auth/rotate.go
Types
func (r *RotateRequest) Types() []services.CertAuthType { switch r.Type { case "": return []services.CertAuthType{services.HostCA, services.UserCA} case services.HostCA: return []services.CertAuthType{services.HostCA} case services.UserCA: return []services.CertAuthType{services.UserCA} } return nil }
go
func (r *RotateRequest) Types() []services.CertAuthType { switch r.Type { case "": return []services.CertAuthType{services.HostCA, services.UserCA} case services.HostCA: return []services.CertAuthType{services.HostCA} case services.UserCA: return []services.CertAuthType{services.UserCA} } return nil }
[ "func", "(", "r", "*", "RotateRequest", ")", "Types", "(", ")", "[", "]", "services", ".", "CertAuthType", "{", "switch", "r", ".", "Type", "{", "case", "\"\"", ":", "return", "[", "]", "services", ".", "CertAuthType", "{", "services", ".", "HostCA", ",", "services", ".", "UserCA", "}", "\n", "case", "services", ".", "HostCA", ":", "return", "[", "]", "services", ".", "CertAuthType", "{", "services", ".", "HostCA", "}", "\n", "case", "services", ".", "UserCA", ":", "return", "[", "]", "services", ".", "CertAuthType", "{", "services", ".", "UserCA", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Types returns cert authority types requested to be rotated.
[ "Types", "returns", "cert", "authority", "types", "requested", "to", "be", "rotated", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/rotate.go#L61-L71
train
gravitational/teleport
lib/auth/rotate.go
CheckAndSetDefaults
func (r *RotateRequest) CheckAndSetDefaults(clock clockwork.Clock) error { if r.TargetPhase == "" { // if phase if not set, imply that the first meaningful phase // is set as a target phase r.TargetPhase = services.RotationPhaseInit } // if mode is not set, default to manual (as it's safer) if r.Mode == "" { r.Mode = services.RotationModeManual } switch r.Type { case "", services.HostCA, services.UserCA: default: return trace.BadParameter("unsupported certificate authority type: %q", r.Type) } if r.GracePeriod == nil { period := defaults.RotationGracePeriod r.GracePeriod = &period } if r.Schedule == nil { var err error r.Schedule, err = services.GenerateSchedule(clock, *r.GracePeriod) if err != nil { return trace.Wrap(err) } } else { if err := r.Schedule.CheckAndSetDefaults(clock); err != nil { return trace.Wrap(err) } } return nil }
go
func (r *RotateRequest) CheckAndSetDefaults(clock clockwork.Clock) error { if r.TargetPhase == "" { // if phase if not set, imply that the first meaningful phase // is set as a target phase r.TargetPhase = services.RotationPhaseInit } // if mode is not set, default to manual (as it's safer) if r.Mode == "" { r.Mode = services.RotationModeManual } switch r.Type { case "", services.HostCA, services.UserCA: default: return trace.BadParameter("unsupported certificate authority type: %q", r.Type) } if r.GracePeriod == nil { period := defaults.RotationGracePeriod r.GracePeriod = &period } if r.Schedule == nil { var err error r.Schedule, err = services.GenerateSchedule(clock, *r.GracePeriod) if err != nil { return trace.Wrap(err) } } else { if err := r.Schedule.CheckAndSetDefaults(clock); err != nil { return trace.Wrap(err) } } return nil }
[ "func", "(", "r", "*", "RotateRequest", ")", "CheckAndSetDefaults", "(", "clock", "clockwork", ".", "Clock", ")", "error", "{", "if", "r", ".", "TargetPhase", "==", "\"\"", "{", "r", ".", "TargetPhase", "=", "services", ".", "RotationPhaseInit", "\n", "}", "\n", "if", "r", ".", "Mode", "==", "\"\"", "{", "r", ".", "Mode", "=", "services", ".", "RotationModeManual", "\n", "}", "\n", "switch", "r", ".", "Type", "{", "case", "\"\"", ",", "services", ".", "HostCA", ",", "services", ".", "UserCA", ":", "default", ":", "return", "trace", ".", "BadParameter", "(", "\"unsupported certificate authority type: %q\"", ",", "r", ".", "Type", ")", "\n", "}", "\n", "if", "r", ".", "GracePeriod", "==", "nil", "{", "period", ":=", "defaults", ".", "RotationGracePeriod", "\n", "r", ".", "GracePeriod", "=", "&", "period", "\n", "}", "\n", "if", "r", ".", "Schedule", "==", "nil", "{", "var", "err", "error", "\n", "r", ".", "Schedule", ",", "err", "=", "services", ".", "GenerateSchedule", "(", "clock", ",", "*", "r", ".", "GracePeriod", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "}", "else", "{", "if", "err", ":=", "r", ".", "Schedule", ".", "CheckAndSetDefaults", "(", "clock", ")", ";", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// CheckAndSetDefaults checks and sets default values.
[ "CheckAndSetDefaults", "checks", "and", "sets", "default", "values", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/rotate.go#L74-L105
train
gravitational/teleport
lib/auth/rotate.go
RotateExternalCertAuthority
func (a *AuthServer) RotateExternalCertAuthority(ca services.CertAuthority) error { if ca == nil { return trace.BadParameter("missing certificate authority") } clusterName, err := a.GetClusterName() if err != nil { return trace.Wrap(err) } // this is just an extra precaution against local admins, // because this is additionally enforced by RBAC as well if ca.GetClusterName() == clusterName.GetClusterName() { return trace.BadParameter("can not rotate local certificate authority") } existing, err := a.Trust.GetCertAuthority(services.CertAuthID{ Type: ca.GetType(), DomainName: ca.GetClusterName(), }, false) if err != nil { return trace.Wrap(err) } updated := existing.Clone() updated.SetCheckingKeys(ca.GetCheckingKeys()) updated.SetTLSKeyPairs(ca.GetTLSKeyPairs()) updated.SetRotation(ca.GetRotation()) // use compare and swap to protect from concurrent updates // by trusted cluster API if err := a.CompareAndSwapCertAuthority(updated, existing); err != nil { return trace.Wrap(err) } return nil }
go
func (a *AuthServer) RotateExternalCertAuthority(ca services.CertAuthority) error { if ca == nil { return trace.BadParameter("missing certificate authority") } clusterName, err := a.GetClusterName() if err != nil { return trace.Wrap(err) } // this is just an extra precaution against local admins, // because this is additionally enforced by RBAC as well if ca.GetClusterName() == clusterName.GetClusterName() { return trace.BadParameter("can not rotate local certificate authority") } existing, err := a.Trust.GetCertAuthority(services.CertAuthID{ Type: ca.GetType(), DomainName: ca.GetClusterName(), }, false) if err != nil { return trace.Wrap(err) } updated := existing.Clone() updated.SetCheckingKeys(ca.GetCheckingKeys()) updated.SetTLSKeyPairs(ca.GetTLSKeyPairs()) updated.SetRotation(ca.GetRotation()) // use compare and swap to protect from concurrent updates // by trusted cluster API if err := a.CompareAndSwapCertAuthority(updated, existing); err != nil { return trace.Wrap(err) } return nil }
[ "func", "(", "a", "*", "AuthServer", ")", "RotateExternalCertAuthority", "(", "ca", "services", ".", "CertAuthority", ")", "error", "{", "if", "ca", "==", "nil", "{", "return", "trace", ".", "BadParameter", "(", "\"missing certificate authority\"", ")", "\n", "}", "\n", "clusterName", ",", "err", ":=", "a", ".", "GetClusterName", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "ca", ".", "GetClusterName", "(", ")", "==", "clusterName", ".", "GetClusterName", "(", ")", "{", "return", "trace", ".", "BadParameter", "(", "\"can not rotate local certificate authority\"", ")", "\n", "}", "\n", "existing", ",", "err", ":=", "a", ".", "Trust", ".", "GetCertAuthority", "(", "services", ".", "CertAuthID", "{", "Type", ":", "ca", ".", "GetType", "(", ")", ",", "DomainName", ":", "ca", ".", "GetClusterName", "(", ")", ",", "}", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "updated", ":=", "existing", ".", "Clone", "(", ")", "\n", "updated", ".", "SetCheckingKeys", "(", "ca", ".", "GetCheckingKeys", "(", ")", ")", "\n", "updated", ".", "SetTLSKeyPairs", "(", "ca", ".", "GetTLSKeyPairs", "(", ")", ")", "\n", "updated", ".", "SetRotation", "(", "ca", ".", "GetRotation", "(", ")", ")", "\n", "if", "err", ":=", "a", ".", "CompareAndSwapCertAuthority", "(", "updated", ",", "existing", ")", ";", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// RotateExternalCertAuthority rotates external certificate authority, // this method is called by remote trusted cluster and is used to update // only public keys and certificates of the certificate authority.
[ "RotateExternalCertAuthority", "rotates", "external", "certificate", "authority", "this", "method", "is", "called", "by", "remote", "trusted", "cluster", "and", "is", "used", "to", "update", "only", "public", "keys", "and", "certificates", "of", "the", "certificate", "authority", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/rotate.go#L245-L280
train
gravitational/teleport
lib/auth/rotate.go
autoRotateCertAuthorities
func (a *AuthServer) autoRotateCertAuthorities() error { clusterName, err := a.GetClusterName() if err != nil { return trace.Wrap(err) } for _, caType := range []services.CertAuthType{services.HostCA, services.UserCA} { ca, err := a.Trust.GetCertAuthority(services.CertAuthID{ Type: caType, DomainName: clusterName.GetClusterName(), }, true) if err != nil { return trace.Wrap(err) } if err := a.autoRotate(ca); err != nil { return trace.Wrap(err) } } return nil }
go
func (a *AuthServer) autoRotateCertAuthorities() error { clusterName, err := a.GetClusterName() if err != nil { return trace.Wrap(err) } for _, caType := range []services.CertAuthType{services.HostCA, services.UserCA} { ca, err := a.Trust.GetCertAuthority(services.CertAuthID{ Type: caType, DomainName: clusterName.GetClusterName(), }, true) if err != nil { return trace.Wrap(err) } if err := a.autoRotate(ca); err != nil { return trace.Wrap(err) } } return nil }
[ "func", "(", "a", "*", "AuthServer", ")", "autoRotateCertAuthorities", "(", ")", "error", "{", "clusterName", ",", "err", ":=", "a", ".", "GetClusterName", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "for", "_", ",", "caType", ":=", "range", "[", "]", "services", ".", "CertAuthType", "{", "services", ".", "HostCA", ",", "services", ".", "UserCA", "}", "{", "ca", ",", "err", ":=", "a", ".", "Trust", ".", "GetCertAuthority", "(", "services", ".", "CertAuthID", "{", "Type", ":", "caType", ",", "DomainName", ":", "clusterName", ".", "GetClusterName", "(", ")", ",", "}", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "err", ":=", "a", ".", "autoRotate", "(", "ca", ")", ";", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// autoRotateCertAuthorities automatically rotates cert authorities, // does nothing if no rotation parameters were set up // or it is too early to rotate per schedule
[ "autoRotateCertAuthorities", "automatically", "rotates", "cert", "authorities", "does", "nothing", "if", "no", "rotation", "parameters", "were", "set", "up", "or", "it", "is", "too", "early", "to", "rotate", "per", "schedule" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/rotate.go#L285-L303
train
gravitational/teleport
lib/auth/rotate.go
processRotationRequest
func processRotationRequest(req rotationReq) (services.CertAuthority, error) { rotation := req.ca.GetRotation() ca := req.ca.Clone() switch req.targetPhase { case services.RotationPhaseInit: // This is the first stage of the rotation - new certificate authorities // are being generated, but no components are using them yet switch rotation.State { case services.RotationStateStandby, "": default: return nil, trace.BadParameter("can not initate rotation while another is in progress") } if err := startNewRotation(req, ca); err != nil { return nil, trace.Wrap(err) } return ca, nil case services.RotationPhaseUpdateClients: // Update client phase clients will start using new credentials // and servers will use the existing credentials, but will trust clients // with both old and new credentials. if rotation.Phase != services.RotationPhaseInit { return nil, trace.BadParameter( "can only switch to phase %v from %v, current phase is %v", services.RotationPhaseUpdateClients, services.RotationPhaseInit, rotation.Phase) } if err := updateClients(ca, req.mode); err != nil { return nil, trace.Wrap(err) } return ca, nil case services.RotationPhaseUpdateServers: // Update server phase uses the new credentials both for servers // and clients, but still trusts clients with old credentials. if rotation.Phase != services.RotationPhaseUpdateClients { return nil, trace.BadParameter( "can only switch to phase %v from %v, current phase is %v", services.RotationPhaseUpdateServers, services.RotationPhaseUpdateClients, rotation.Phase) } // Signal nodes to restart and start serving new signatures // by updating the phase. rotation.Phase = req.targetPhase rotation.Mode = req.mode ca.SetRotation(rotation) return ca, nil case services.RotationPhaseRollback: // Rollback moves back both clients and servers to use the old credentials // but will trust new credentials. switch rotation.Phase { case services.RotationPhaseInit, services.RotationPhaseUpdateClients, services.RotationPhaseUpdateServers: if err := startRollingBackRotation(ca); err != nil { return nil, trace.Wrap(err) } return ca, nil default: return nil, trace.BadParameter("can not transition to phase %q from %q phase.", req.targetPhase, rotation.Phase) } case services.RotationPhaseStandby: // Transition to the standby phase moves rotation process // to standby, servers will only trust one certificate authority. switch rotation.Phase { case services.RotationPhaseUpdateServers, services.RotationPhaseRollback: if err := completeRotation(req.clock, ca); err != nil { return nil, trace.Wrap(err) } return ca, nil default: return nil, trace.BadParameter( "can only switch to phase %v from %v, current phase is %v", services.RotationPhaseUpdateServers, services.RotationPhaseUpdateClients, rotation.Phase) } default: return nil, trace.BadParameter("unsupported phase: %q", req.targetPhase) } }
go
func processRotationRequest(req rotationReq) (services.CertAuthority, error) { rotation := req.ca.GetRotation() ca := req.ca.Clone() switch req.targetPhase { case services.RotationPhaseInit: // This is the first stage of the rotation - new certificate authorities // are being generated, but no components are using them yet switch rotation.State { case services.RotationStateStandby, "": default: return nil, trace.BadParameter("can not initate rotation while another is in progress") } if err := startNewRotation(req, ca); err != nil { return nil, trace.Wrap(err) } return ca, nil case services.RotationPhaseUpdateClients: // Update client phase clients will start using new credentials // and servers will use the existing credentials, but will trust clients // with both old and new credentials. if rotation.Phase != services.RotationPhaseInit { return nil, trace.BadParameter( "can only switch to phase %v from %v, current phase is %v", services.RotationPhaseUpdateClients, services.RotationPhaseInit, rotation.Phase) } if err := updateClients(ca, req.mode); err != nil { return nil, trace.Wrap(err) } return ca, nil case services.RotationPhaseUpdateServers: // Update server phase uses the new credentials both for servers // and clients, but still trusts clients with old credentials. if rotation.Phase != services.RotationPhaseUpdateClients { return nil, trace.BadParameter( "can only switch to phase %v from %v, current phase is %v", services.RotationPhaseUpdateServers, services.RotationPhaseUpdateClients, rotation.Phase) } // Signal nodes to restart and start serving new signatures // by updating the phase. rotation.Phase = req.targetPhase rotation.Mode = req.mode ca.SetRotation(rotation) return ca, nil case services.RotationPhaseRollback: // Rollback moves back both clients and servers to use the old credentials // but will trust new credentials. switch rotation.Phase { case services.RotationPhaseInit, services.RotationPhaseUpdateClients, services.RotationPhaseUpdateServers: if err := startRollingBackRotation(ca); err != nil { return nil, trace.Wrap(err) } return ca, nil default: return nil, trace.BadParameter("can not transition to phase %q from %q phase.", req.targetPhase, rotation.Phase) } case services.RotationPhaseStandby: // Transition to the standby phase moves rotation process // to standby, servers will only trust one certificate authority. switch rotation.Phase { case services.RotationPhaseUpdateServers, services.RotationPhaseRollback: if err := completeRotation(req.clock, ca); err != nil { return nil, trace.Wrap(err) } return ca, nil default: return nil, trace.BadParameter( "can only switch to phase %v from %v, current phase is %v", services.RotationPhaseUpdateServers, services.RotationPhaseUpdateClients, rotation.Phase) } default: return nil, trace.BadParameter("unsupported phase: %q", req.targetPhase) } }
[ "func", "processRotationRequest", "(", "req", "rotationReq", ")", "(", "services", ".", "CertAuthority", ",", "error", ")", "{", "rotation", ":=", "req", ".", "ca", ".", "GetRotation", "(", ")", "\n", "ca", ":=", "req", ".", "ca", ".", "Clone", "(", ")", "\n", "switch", "req", ".", "targetPhase", "{", "case", "services", ".", "RotationPhaseInit", ":", "switch", "rotation", ".", "State", "{", "case", "services", ".", "RotationStateStandby", ",", "\"\"", ":", "default", ":", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"can not initate rotation while another is in progress\"", ")", "\n", "}", "\n", "if", "err", ":=", "startNewRotation", "(", "req", ",", "ca", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "ca", ",", "nil", "\n", "case", "services", ".", "RotationPhaseUpdateClients", ":", "if", "rotation", ".", "Phase", "!=", "services", ".", "RotationPhaseInit", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"can only switch to phase %v from %v, current phase is %v\"", ",", "services", ".", "RotationPhaseUpdateClients", ",", "services", ".", "RotationPhaseInit", ",", "rotation", ".", "Phase", ")", "\n", "}", "\n", "if", "err", ":=", "updateClients", "(", "ca", ",", "req", ".", "mode", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "ca", ",", "nil", "\n", "case", "services", ".", "RotationPhaseUpdateServers", ":", "if", "rotation", ".", "Phase", "!=", "services", ".", "RotationPhaseUpdateClients", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"can only switch to phase %v from %v, current phase is %v\"", ",", "services", ".", "RotationPhaseUpdateServers", ",", "services", ".", "RotationPhaseUpdateClients", ",", "rotation", ".", "Phase", ")", "\n", "}", "\n", "rotation", ".", "Phase", "=", "req", ".", "targetPhase", "\n", "rotation", ".", "Mode", "=", "req", ".", "mode", "\n", "ca", ".", "SetRotation", "(", "rotation", ")", "\n", "return", "ca", ",", "nil", "\n", "case", "services", ".", "RotationPhaseRollback", ":", "switch", "rotation", ".", "Phase", "{", "case", "services", ".", "RotationPhaseInit", ",", "services", ".", "RotationPhaseUpdateClients", ",", "services", ".", "RotationPhaseUpdateServers", ":", "if", "err", ":=", "startRollingBackRotation", "(", "ca", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "ca", ",", "nil", "\n", "default", ":", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"can not transition to phase %q from %q phase.\"", ",", "req", ".", "targetPhase", ",", "rotation", ".", "Phase", ")", "\n", "}", "\n", "case", "services", ".", "RotationPhaseStandby", ":", "switch", "rotation", ".", "Phase", "{", "case", "services", ".", "RotationPhaseUpdateServers", ",", "services", ".", "RotationPhaseRollback", ":", "if", "err", ":=", "completeRotation", "(", "req", ".", "clock", ",", "ca", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "ca", ",", "nil", "\n", "default", ":", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"can only switch to phase %v from %v, current phase is %v\"", ",", "services", ".", "RotationPhaseUpdateServers", ",", "services", ".", "RotationPhaseUpdateClients", ",", "rotation", ".", "Phase", ")", "\n", "}", "\n", "default", ":", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"unsupported phase: %q\"", ",", "req", ".", "targetPhase", ")", "\n", "}", "\n", "}" ]
// processRotationRequest processes rotation request based on the target and // current phase and state.
[ "processRotationRequest", "processes", "rotation", "request", "based", "on", "the", "target", "and", "current", "phase", "and", "state", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/rotate.go#L371-L450
train
gravitational/teleport
lib/auth/rotate.go
startRollingBackRotation
func startRollingBackRotation(ca services.CertAuthority) error { rotation := ca.GetRotation() // Rollback always sets rotation to manual mode. rotation.Mode = services.RotationModeManual signingKeys := ca.GetSigningKeys() checkingKeys := ca.GetCheckingKeys() keyPairs := ca.GetTLSKeyPairs() // Rotation sets the first key to be the new key // and keep only public keys/certs for the new CA. signingKeys = [][]byte{signingKeys[1]} checkingKeys = [][]byte{checkingKeys[1]} // Keep the new certificate as trusted // as during the rollback phase, both types of clients may be present in the cluster. keyPairs = []services.TLSKeyPair{keyPairs[1], services.TLSKeyPair{Cert: keyPairs[0].Cert}} rotation.State = services.RotationStateInProgress rotation.Phase = services.RotationPhaseRollback ca.SetSigningKeys(signingKeys) ca.SetCheckingKeys(checkingKeys) ca.SetTLSKeyPairs(keyPairs) ca.SetRotation(rotation) return nil }
go
func startRollingBackRotation(ca services.CertAuthority) error { rotation := ca.GetRotation() // Rollback always sets rotation to manual mode. rotation.Mode = services.RotationModeManual signingKeys := ca.GetSigningKeys() checkingKeys := ca.GetCheckingKeys() keyPairs := ca.GetTLSKeyPairs() // Rotation sets the first key to be the new key // and keep only public keys/certs for the new CA. signingKeys = [][]byte{signingKeys[1]} checkingKeys = [][]byte{checkingKeys[1]} // Keep the new certificate as trusted // as during the rollback phase, both types of clients may be present in the cluster. keyPairs = []services.TLSKeyPair{keyPairs[1], services.TLSKeyPair{Cert: keyPairs[0].Cert}} rotation.State = services.RotationStateInProgress rotation.Phase = services.RotationPhaseRollback ca.SetSigningKeys(signingKeys) ca.SetCheckingKeys(checkingKeys) ca.SetTLSKeyPairs(keyPairs) ca.SetRotation(rotation) return nil }
[ "func", "startRollingBackRotation", "(", "ca", "services", ".", "CertAuthority", ")", "error", "{", "rotation", ":=", "ca", ".", "GetRotation", "(", ")", "\n", "rotation", ".", "Mode", "=", "services", ".", "RotationModeManual", "\n", "signingKeys", ":=", "ca", ".", "GetSigningKeys", "(", ")", "\n", "checkingKeys", ":=", "ca", ".", "GetCheckingKeys", "(", ")", "\n", "keyPairs", ":=", "ca", ".", "GetTLSKeyPairs", "(", ")", "\n", "signingKeys", "=", "[", "]", "[", "]", "byte", "{", "signingKeys", "[", "1", "]", "}", "\n", "checkingKeys", "=", "[", "]", "[", "]", "byte", "{", "checkingKeys", "[", "1", "]", "}", "\n", "keyPairs", "=", "[", "]", "services", ".", "TLSKeyPair", "{", "keyPairs", "[", "1", "]", ",", "services", ".", "TLSKeyPair", "{", "Cert", ":", "keyPairs", "[", "0", "]", ".", "Cert", "}", "}", "\n", "rotation", ".", "State", "=", "services", ".", "RotationStateInProgress", "\n", "rotation", ".", "Phase", "=", "services", ".", "RotationPhaseRollback", "\n", "ca", ".", "SetSigningKeys", "(", "signingKeys", ")", "\n", "ca", ".", "SetCheckingKeys", "(", "checkingKeys", ")", "\n", "ca", ".", "SetTLSKeyPairs", "(", "keyPairs", ")", "\n", "ca", ".", "SetRotation", "(", "rotation", ")", "\n", "return", "nil", "\n", "}" ]
// startRollingBackRotation starts roll back to the original state.
[ "startRollingBackRotation", "starts", "roll", "back", "to", "the", "original", "state", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/rotate.go#L575-L601
train
gravitational/teleport
lib/auth/rotate.go
completeRollingBackRotation
func completeRollingBackRotation(clock clockwork.Clock, ca services.CertAuthority) error { rotation := ca.GetRotation() // clean up the state rotation.Started = time.Time{} rotation.State = services.RotationStateStandby rotation.Phase = services.RotationPhaseStandby rotation.Mode = "" rotation.Schedule = services.RotationSchedule{} keyPairs := ca.GetTLSKeyPairs() // only keep the original certificate authority as trusted // and remove everything else. keyPairs = []services.TLSKeyPair{keyPairs[0]} ca.SetTLSKeyPairs(keyPairs) ca.SetRotation(rotation) return nil }
go
func completeRollingBackRotation(clock clockwork.Clock, ca services.CertAuthority) error { rotation := ca.GetRotation() // clean up the state rotation.Started = time.Time{} rotation.State = services.RotationStateStandby rotation.Phase = services.RotationPhaseStandby rotation.Mode = "" rotation.Schedule = services.RotationSchedule{} keyPairs := ca.GetTLSKeyPairs() // only keep the original certificate authority as trusted // and remove everything else. keyPairs = []services.TLSKeyPair{keyPairs[0]} ca.SetTLSKeyPairs(keyPairs) ca.SetRotation(rotation) return nil }
[ "func", "completeRollingBackRotation", "(", "clock", "clockwork", ".", "Clock", ",", "ca", "services", ".", "CertAuthority", ")", "error", "{", "rotation", ":=", "ca", ".", "GetRotation", "(", ")", "\n", "rotation", ".", "Started", "=", "time", ".", "Time", "{", "}", "\n", "rotation", ".", "State", "=", "services", ".", "RotationStateStandby", "\n", "rotation", ".", "Phase", "=", "services", ".", "RotationPhaseStandby", "\n", "rotation", ".", "Mode", "=", "\"\"", "\n", "rotation", ".", "Schedule", "=", "services", ".", "RotationSchedule", "{", "}", "\n", "keyPairs", ":=", "ca", ".", "GetTLSKeyPairs", "(", ")", "\n", "keyPairs", "=", "[", "]", "services", ".", "TLSKeyPair", "{", "keyPairs", "[", "0", "]", "}", "\n", "ca", ".", "SetTLSKeyPairs", "(", "keyPairs", ")", "\n", "ca", ".", "SetRotation", "(", "rotation", ")", "\n", "return", "nil", "\n", "}" ]
// completeRollingBackRotation completes rollback of the rotation and sets it to the standby state
[ "completeRollingBackRotation", "completes", "rollback", "of", "the", "rotation", "and", "sets", "it", "to", "the", "standby", "state" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/rotate.go#L604-L622
train
gravitational/teleport
lib/auth/rotate.go
completeRotation
func completeRotation(clock clockwork.Clock, ca services.CertAuthority) error { rotation := ca.GetRotation() signingKeys := ca.GetSigningKeys() checkingKeys := ca.GetCheckingKeys() keyPairs := ca.GetTLSKeyPairs() signingKeys = signingKeys[:1] checkingKeys = checkingKeys[:1] keyPairs = keyPairs[:1] rotation.Started = time.Time{} rotation.State = services.RotationStateStandby rotation.Phase = services.RotationPhaseStandby rotation.LastRotated = clock.Now() rotation.Mode = "" rotation.Schedule = services.RotationSchedule{} ca.SetSigningKeys(signingKeys) ca.SetCheckingKeys(checkingKeys) ca.SetTLSKeyPairs(keyPairs) ca.SetRotation(rotation) return nil }
go
func completeRotation(clock clockwork.Clock, ca services.CertAuthority) error { rotation := ca.GetRotation() signingKeys := ca.GetSigningKeys() checkingKeys := ca.GetCheckingKeys() keyPairs := ca.GetTLSKeyPairs() signingKeys = signingKeys[:1] checkingKeys = checkingKeys[:1] keyPairs = keyPairs[:1] rotation.Started = time.Time{} rotation.State = services.RotationStateStandby rotation.Phase = services.RotationPhaseStandby rotation.LastRotated = clock.Now() rotation.Mode = "" rotation.Schedule = services.RotationSchedule{} ca.SetSigningKeys(signingKeys) ca.SetCheckingKeys(checkingKeys) ca.SetTLSKeyPairs(keyPairs) ca.SetRotation(rotation) return nil }
[ "func", "completeRotation", "(", "clock", "clockwork", ".", "Clock", ",", "ca", "services", ".", "CertAuthority", ")", "error", "{", "rotation", ":=", "ca", ".", "GetRotation", "(", ")", "\n", "signingKeys", ":=", "ca", ".", "GetSigningKeys", "(", ")", "\n", "checkingKeys", ":=", "ca", ".", "GetCheckingKeys", "(", ")", "\n", "keyPairs", ":=", "ca", ".", "GetTLSKeyPairs", "(", ")", "\n", "signingKeys", "=", "signingKeys", "[", ":", "1", "]", "\n", "checkingKeys", "=", "checkingKeys", "[", ":", "1", "]", "\n", "keyPairs", "=", "keyPairs", "[", ":", "1", "]", "\n", "rotation", ".", "Started", "=", "time", ".", "Time", "{", "}", "\n", "rotation", ".", "State", "=", "services", ".", "RotationStateStandby", "\n", "rotation", ".", "Phase", "=", "services", ".", "RotationPhaseStandby", "\n", "rotation", ".", "LastRotated", "=", "clock", ".", "Now", "(", ")", "\n", "rotation", ".", "Mode", "=", "\"\"", "\n", "rotation", ".", "Schedule", "=", "services", ".", "RotationSchedule", "{", "}", "\n", "ca", ".", "SetSigningKeys", "(", "signingKeys", ")", "\n", "ca", ".", "SetCheckingKeys", "(", "checkingKeys", ")", "\n", "ca", ".", "SetTLSKeyPairs", "(", "keyPairs", ")", "\n", "ca", ".", "SetRotation", "(", "rotation", ")", "\n", "return", "nil", "\n", "}" ]
// completeRotation completes the certificate authority rotation.
[ "completeRotation", "completes", "the", "certificate", "authority", "rotation", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/rotate.go#L625-L647
train
gravitational/teleport
lib/utils/unpack.go
Extract
func Extract(r io.Reader, dir string) error { tarball := tar.NewReader(r) for { header, err := tarball.Next() if err == io.EOF { break } else if err != nil { return trace.Wrap(err) } if err := extractFile(tarball, header, dir); err != nil { return trace.Wrap(err) } } return nil }
go
func Extract(r io.Reader, dir string) error { tarball := tar.NewReader(r) for { header, err := tarball.Next() if err == io.EOF { break } else if err != nil { return trace.Wrap(err) } if err := extractFile(tarball, header, dir); err != nil { return trace.Wrap(err) } } return nil }
[ "func", "Extract", "(", "r", "io", ".", "Reader", ",", "dir", "string", ")", "error", "{", "tarball", ":=", "tar", ".", "NewReader", "(", "r", ")", "\n", "for", "{", "header", ",", "err", ":=", "tarball", ".", "Next", "(", ")", "\n", "if", "err", "==", "io", ".", "EOF", "{", "break", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "err", ":=", "extractFile", "(", "tarball", ",", "header", ",", "dir", ")", ";", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Extract extracts the contents of the specified tarball under dir. // The resulting files and directories are created using the current user context.
[ "Extract", "extracts", "the", "contents", "of", "the", "specified", "tarball", "under", "dir", ".", "The", "resulting", "files", "and", "directories", "are", "created", "using", "the", "current", "user", "context", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/unpack.go#L33-L49
train
gravitational/teleport
lib/utils/rand.go
CryptoRandomHex
func CryptoRandomHex(len int) (string, error) { randomBytes := make([]byte, len) if _, err := rand.Reader.Read(randomBytes); err != nil { return "", trace.Wrap(err) } return hex.EncodeToString(randomBytes), nil }
go
func CryptoRandomHex(len int) (string, error) { randomBytes := make([]byte, len) if _, err := rand.Reader.Read(randomBytes); err != nil { return "", trace.Wrap(err) } return hex.EncodeToString(randomBytes), nil }
[ "func", "CryptoRandomHex", "(", "len", "int", ")", "(", "string", ",", "error", ")", "{", "randomBytes", ":=", "make", "(", "[", "]", "byte", ",", "len", ")", "\n", "if", "_", ",", "err", ":=", "rand", ".", "Reader", ".", "Read", "(", "randomBytes", ")", ";", "err", "!=", "nil", "{", "return", "\"\"", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "hex", ".", "EncodeToString", "(", "randomBytes", ")", ",", "nil", "\n", "}" ]
// CryptoRandomHex returns hex encoded random string generated with crypto-strong // pseudo random generator of the given bytes
[ "CryptoRandomHex", "returns", "hex", "encoded", "random", "string", "generated", "with", "crypto", "-", "strong", "pseudo", "random", "generator", "of", "the", "given", "bytes" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/rand.go#L30-L36
train
gravitational/teleport
lib/utils/rand.go
RandomDuration
func RandomDuration(max time.Duration) time.Duration { randomVal, err := rand.Int(rand.Reader, big.NewInt(int64(max))) if err != nil { return max / 2 } return time.Duration(randomVal.Int64()) }
go
func RandomDuration(max time.Duration) time.Duration { randomVal, err := rand.Int(rand.Reader, big.NewInt(int64(max))) if err != nil { return max / 2 } return time.Duration(randomVal.Int64()) }
[ "func", "RandomDuration", "(", "max", "time", ".", "Duration", ")", "time", ".", "Duration", "{", "randomVal", ",", "err", ":=", "rand", ".", "Int", "(", "rand", ".", "Reader", ",", "big", ".", "NewInt", "(", "int64", "(", "max", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "max", "/", "2", "\n", "}", "\n", "return", "time", ".", "Duration", "(", "randomVal", ".", "Int64", "(", ")", ")", "\n", "}" ]
// RandomDuration returns a duration in a range [0, max)
[ "RandomDuration", "returns", "a", "duration", "in", "a", "range", "[", "0", "max", ")" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/rand.go#L39-L45
train
gravitational/teleport
lib/services/suite/suite.go
NewServer
func NewServer(kind, name, addr, namespace string) *services.ServerV2 { return &services.ServerV2{ Kind: kind, Version: services.V2, Metadata: services.Metadata{ Name: name, Namespace: namespace, }, Spec: services.ServerSpecV2{ Addr: addr, PublicAddr: addr, }, } }
go
func NewServer(kind, name, addr, namespace string) *services.ServerV2 { return &services.ServerV2{ Kind: kind, Version: services.V2, Metadata: services.Metadata{ Name: name, Namespace: namespace, }, Spec: services.ServerSpecV2{ Addr: addr, PublicAddr: addr, }, } }
[ "func", "NewServer", "(", "kind", ",", "name", ",", "addr", ",", "namespace", "string", ")", "*", "services", ".", "ServerV2", "{", "return", "&", "services", ".", "ServerV2", "{", "Kind", ":", "kind", ",", "Version", ":", "services", ".", "V2", ",", "Metadata", ":", "services", ".", "Metadata", "{", "Name", ":", "name", ",", "Namespace", ":", "namespace", ",", "}", ",", "Spec", ":", "services", ".", "ServerSpecV2", "{", "Addr", ":", "addr", ",", "PublicAddr", ":", "addr", ",", "}", ",", "}", "\n", "}" ]
// NewServer creates a new server resource
[ "NewServer", "creates", "a", "new", "server", "resource" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/suite/suite.go#L302-L315
train
gravitational/teleport
lib/services/suite/suite.go
AuthPreference
func (s *ServicesTestSuite) AuthPreference(c *check.C) { ap, err := services.NewAuthPreference(services.AuthPreferenceSpecV2{ Type: "local", SecondFactor: "otp", }) c.Assert(err, check.IsNil) err = s.ConfigS.SetAuthPreference(ap) c.Assert(err, check.IsNil) gotAP, err := s.ConfigS.GetAuthPreference() c.Assert(err, check.IsNil) c.Assert(gotAP.GetType(), check.Equals, "local") c.Assert(gotAP.GetSecondFactor(), check.Equals, "otp") }
go
func (s *ServicesTestSuite) AuthPreference(c *check.C) { ap, err := services.NewAuthPreference(services.AuthPreferenceSpecV2{ Type: "local", SecondFactor: "otp", }) c.Assert(err, check.IsNil) err = s.ConfigS.SetAuthPreference(ap) c.Assert(err, check.IsNil) gotAP, err := s.ConfigS.GetAuthPreference() c.Assert(err, check.IsNil) c.Assert(gotAP.GetType(), check.Equals, "local") c.Assert(gotAP.GetSecondFactor(), check.Equals, "otp") }
[ "func", "(", "s", "*", "ServicesTestSuite", ")", "AuthPreference", "(", "c", "*", "check", ".", "C", ")", "{", "ap", ",", "err", ":=", "services", ".", "NewAuthPreference", "(", "services", ".", "AuthPreferenceSpecV2", "{", "Type", ":", "\"local\"", ",", "SecondFactor", ":", "\"otp\"", ",", "}", ")", "\n", "c", ".", "Assert", "(", "err", ",", "check", ".", "IsNil", ")", "\n", "err", "=", "s", ".", "ConfigS", ".", "SetAuthPreference", "(", "ap", ")", "\n", "c", ".", "Assert", "(", "err", ",", "check", ".", "IsNil", ")", "\n", "gotAP", ",", "err", ":=", "s", ".", "ConfigS", ".", "GetAuthPreference", "(", ")", "\n", "c", ".", "Assert", "(", "err", ",", "check", ".", "IsNil", ")", "\n", "c", ".", "Assert", "(", "gotAP", ".", "GetType", "(", ")", ",", "check", ".", "Equals", ",", "\"local\"", ")", "\n", "c", ".", "Assert", "(", "gotAP", ".", "GetSecondFactor", "(", ")", ",", "check", ".", "Equals", ",", "\"otp\"", ")", "\n", "}" ]
// AuthPreference tests authentication preference service
[ "AuthPreference", "tests", "authentication", "preference", "service" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/suite/suite.go#L890-L905
train
gravitational/teleport
lib/services/suite/suite.go
CollectOptions
func CollectOptions(opts ...SuiteOption) SuiteOptions { var suiteOpts SuiteOptions for _, o := range opts { o(&suiteOpts) } return suiteOpts }
go
func CollectOptions(opts ...SuiteOption) SuiteOptions { var suiteOpts SuiteOptions for _, o := range opts { o(&suiteOpts) } return suiteOpts }
[ "func", "CollectOptions", "(", "opts", "...", "SuiteOption", ")", "SuiteOptions", "{", "var", "suiteOpts", "SuiteOptions", "\n", "for", "_", ",", "o", ":=", "range", "opts", "{", "o", "(", "&", "suiteOpts", ")", "\n", "}", "\n", "return", "suiteOpts", "\n", "}" ]
// CollectOptions collects suite options
[ "CollectOptions", "collects", "suite", "options" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/suite/suite.go#L953-L959
train
gravitational/teleport
lib/services/suite/suite.go
ClusterConfig
func (s *ServicesTestSuite) ClusterConfig(c *check.C, opts ...SuiteOption) { config, err := services.NewClusterConfig(services.ClusterConfigSpecV3{ ClientIdleTimeout: services.NewDuration(17 * time.Second), DisconnectExpiredCert: services.NewBool(true), ClusterID: "27", SessionRecording: services.RecordAtProxy, Audit: services.AuditConfig{ Region: "us-west-1", Type: "dynamodb", AuditSessionsURI: "file:///home/log", AuditTableName: "audit_table_name", AuditEventsURI: []string{"dynamodb://audit_table_name", "file:///home/log"}, }, }) c.Assert(err, check.IsNil) err = s.ConfigS.SetClusterConfig(config) c.Assert(err, check.IsNil) gotConfig, err := s.ConfigS.GetClusterConfig() c.Assert(err, check.IsNil) config.SetResourceID(gotConfig.GetResourceID()) fixtures.DeepCompare(c, config, gotConfig) // Some parts (e.g. auth server) will not function // without cluster name or cluster config if CollectOptions(opts...).SkipDelete { return } err = s.ConfigS.DeleteClusterConfig() c.Assert(err, check.IsNil) _, err = s.ConfigS.GetClusterConfig() fixtures.ExpectNotFound(c, err) clusterName, err := services.NewClusterName(services.ClusterNameSpecV2{ ClusterName: "example.com", }) c.Assert(err, check.IsNil) err = s.ConfigS.SetClusterName(clusterName) c.Assert(err, check.IsNil) gotName, err := s.ConfigS.GetClusterName() c.Assert(err, check.IsNil) clusterName.SetResourceID(gotName.GetResourceID()) fixtures.DeepCompare(c, clusterName, gotName) err = s.ConfigS.DeleteClusterName() c.Assert(err, check.IsNil) _, err = s.ConfigS.GetClusterName() fixtures.ExpectNotFound(c, err) err = s.ConfigS.UpsertClusterName(clusterName) c.Assert(err, check.IsNil) gotName, err = s.ConfigS.GetClusterName() c.Assert(err, check.IsNil) clusterName.SetResourceID(gotName.GetResourceID()) fixtures.DeepCompare(c, clusterName, gotName) }
go
func (s *ServicesTestSuite) ClusterConfig(c *check.C, opts ...SuiteOption) { config, err := services.NewClusterConfig(services.ClusterConfigSpecV3{ ClientIdleTimeout: services.NewDuration(17 * time.Second), DisconnectExpiredCert: services.NewBool(true), ClusterID: "27", SessionRecording: services.RecordAtProxy, Audit: services.AuditConfig{ Region: "us-west-1", Type: "dynamodb", AuditSessionsURI: "file:///home/log", AuditTableName: "audit_table_name", AuditEventsURI: []string{"dynamodb://audit_table_name", "file:///home/log"}, }, }) c.Assert(err, check.IsNil) err = s.ConfigS.SetClusterConfig(config) c.Assert(err, check.IsNil) gotConfig, err := s.ConfigS.GetClusterConfig() c.Assert(err, check.IsNil) config.SetResourceID(gotConfig.GetResourceID()) fixtures.DeepCompare(c, config, gotConfig) // Some parts (e.g. auth server) will not function // without cluster name or cluster config if CollectOptions(opts...).SkipDelete { return } err = s.ConfigS.DeleteClusterConfig() c.Assert(err, check.IsNil) _, err = s.ConfigS.GetClusterConfig() fixtures.ExpectNotFound(c, err) clusterName, err := services.NewClusterName(services.ClusterNameSpecV2{ ClusterName: "example.com", }) c.Assert(err, check.IsNil) err = s.ConfigS.SetClusterName(clusterName) c.Assert(err, check.IsNil) gotName, err := s.ConfigS.GetClusterName() c.Assert(err, check.IsNil) clusterName.SetResourceID(gotName.GetResourceID()) fixtures.DeepCompare(c, clusterName, gotName) err = s.ConfigS.DeleteClusterName() c.Assert(err, check.IsNil) _, err = s.ConfigS.GetClusterName() fixtures.ExpectNotFound(c, err) err = s.ConfigS.UpsertClusterName(clusterName) c.Assert(err, check.IsNil) gotName, err = s.ConfigS.GetClusterName() c.Assert(err, check.IsNil) clusterName.SetResourceID(gotName.GetResourceID()) fixtures.DeepCompare(c, clusterName, gotName) }
[ "func", "(", "s", "*", "ServicesTestSuite", ")", "ClusterConfig", "(", "c", "*", "check", ".", "C", ",", "opts", "...", "SuiteOption", ")", "{", "config", ",", "err", ":=", "services", ".", "NewClusterConfig", "(", "services", ".", "ClusterConfigSpecV3", "{", "ClientIdleTimeout", ":", "services", ".", "NewDuration", "(", "17", "*", "time", ".", "Second", ")", ",", "DisconnectExpiredCert", ":", "services", ".", "NewBool", "(", "true", ")", ",", "ClusterID", ":", "\"27\"", ",", "SessionRecording", ":", "services", ".", "RecordAtProxy", ",", "Audit", ":", "services", ".", "AuditConfig", "{", "Region", ":", "\"us-west-1\"", ",", "Type", ":", "\"dynamodb\"", ",", "AuditSessionsURI", ":", "\"file:///home/log\"", ",", "AuditTableName", ":", "\"audit_table_name\"", ",", "AuditEventsURI", ":", "[", "]", "string", "{", "\"dynamodb://audit_table_name\"", ",", "\"file:///home/log\"", "}", ",", "}", ",", "}", ")", "\n", "c", ".", "Assert", "(", "err", ",", "check", ".", "IsNil", ")", "\n", "err", "=", "s", ".", "ConfigS", ".", "SetClusterConfig", "(", "config", ")", "\n", "c", ".", "Assert", "(", "err", ",", "check", ".", "IsNil", ")", "\n", "gotConfig", ",", "err", ":=", "s", ".", "ConfigS", ".", "GetClusterConfig", "(", ")", "\n", "c", ".", "Assert", "(", "err", ",", "check", ".", "IsNil", ")", "\n", "config", ".", "SetResourceID", "(", "gotConfig", ".", "GetResourceID", "(", ")", ")", "\n", "fixtures", ".", "DeepCompare", "(", "c", ",", "config", ",", "gotConfig", ")", "\n", "if", "CollectOptions", "(", "opts", "...", ")", ".", "SkipDelete", "{", "return", "\n", "}", "\n", "err", "=", "s", ".", "ConfigS", ".", "DeleteClusterConfig", "(", ")", "\n", "c", ".", "Assert", "(", "err", ",", "check", ".", "IsNil", ")", "\n", "_", ",", "err", "=", "s", ".", "ConfigS", ".", "GetClusterConfig", "(", ")", "\n", "fixtures", ".", "ExpectNotFound", "(", "c", ",", "err", ")", "\n", "clusterName", ",", "err", ":=", "services", ".", "NewClusterName", "(", "services", ".", "ClusterNameSpecV2", "{", "ClusterName", ":", "\"example.com\"", ",", "}", ")", "\n", "c", ".", "Assert", "(", "err", ",", "check", ".", "IsNil", ")", "\n", "err", "=", "s", ".", "ConfigS", ".", "SetClusterName", "(", "clusterName", ")", "\n", "c", ".", "Assert", "(", "err", ",", "check", ".", "IsNil", ")", "\n", "gotName", ",", "err", ":=", "s", ".", "ConfigS", ".", "GetClusterName", "(", ")", "\n", "c", ".", "Assert", "(", "err", ",", "check", ".", "IsNil", ")", "\n", "clusterName", ".", "SetResourceID", "(", "gotName", ".", "GetResourceID", "(", ")", ")", "\n", "fixtures", ".", "DeepCompare", "(", "c", ",", "clusterName", ",", "gotName", ")", "\n", "err", "=", "s", ".", "ConfigS", ".", "DeleteClusterName", "(", ")", "\n", "c", ".", "Assert", "(", "err", ",", "check", ".", "IsNil", ")", "\n", "_", ",", "err", "=", "s", ".", "ConfigS", ".", "GetClusterName", "(", ")", "\n", "fixtures", ".", "ExpectNotFound", "(", "c", ",", "err", ")", "\n", "err", "=", "s", ".", "ConfigS", ".", "UpsertClusterName", "(", "clusterName", ")", "\n", "c", ".", "Assert", "(", "err", ",", "check", ".", "IsNil", ")", "\n", "gotName", ",", "err", "=", "s", ".", "ConfigS", ".", "GetClusterName", "(", ")", "\n", "c", ".", "Assert", "(", "err", ",", "check", ".", "IsNil", ")", "\n", "clusterName", ".", "SetResourceID", "(", "gotName", ".", "GetResourceID", "(", ")", ")", "\n", "fixtures", ".", "DeepCompare", "(", "c", ",", "clusterName", ",", "gotName", ")", "\n", "}" ]
// ClusterConfig tests cluster configuration
[ "ClusterConfig", "tests", "cluster", "configuration" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/suite/suite.go#L962-L1023
train
gravitational/teleport
lib/services/suite/suite.go
EventsClusterConfig
func (s *ServicesTestSuite) EventsClusterConfig(c *check.C) { testCases := []eventTest{ { name: "Cluster config", kind: services.WatchKind{ Kind: services.KindClusterConfig, }, crud: func() services.Resource { config, err := services.NewClusterConfig(services.ClusterConfigSpecV3{}) c.Assert(err, check.IsNil) err = s.ConfigS.SetClusterConfig(config) c.Assert(err, check.IsNil) out, err := s.ConfigS.GetClusterConfig() c.Assert(err, check.IsNil) err = s.ConfigS.DeleteClusterConfig() c.Assert(err, check.IsNil) return out }, }, { name: "Cluster name", kind: services.WatchKind{ Kind: services.KindClusterName, }, crud: func() services.Resource { clusterName, err := services.NewClusterName(services.ClusterNameSpecV2{ ClusterName: "example.com", }) c.Assert(err, check.IsNil) err = s.ConfigS.SetClusterName(clusterName) c.Assert(err, check.IsNil) out, err := s.ConfigS.GetClusterName() c.Assert(err, check.IsNil) err = s.ConfigS.DeleteClusterName() c.Assert(err, check.IsNil) return out }, }, } s.runEventsTests(c, testCases) }
go
func (s *ServicesTestSuite) EventsClusterConfig(c *check.C) { testCases := []eventTest{ { name: "Cluster config", kind: services.WatchKind{ Kind: services.KindClusterConfig, }, crud: func() services.Resource { config, err := services.NewClusterConfig(services.ClusterConfigSpecV3{}) c.Assert(err, check.IsNil) err = s.ConfigS.SetClusterConfig(config) c.Assert(err, check.IsNil) out, err := s.ConfigS.GetClusterConfig() c.Assert(err, check.IsNil) err = s.ConfigS.DeleteClusterConfig() c.Assert(err, check.IsNil) return out }, }, { name: "Cluster name", kind: services.WatchKind{ Kind: services.KindClusterName, }, crud: func() services.Resource { clusterName, err := services.NewClusterName(services.ClusterNameSpecV2{ ClusterName: "example.com", }) c.Assert(err, check.IsNil) err = s.ConfigS.SetClusterName(clusterName) c.Assert(err, check.IsNil) out, err := s.ConfigS.GetClusterName() c.Assert(err, check.IsNil) err = s.ConfigS.DeleteClusterName() c.Assert(err, check.IsNil) return out }, }, } s.runEventsTests(c, testCases) }
[ "func", "(", "s", "*", "ServicesTestSuite", ")", "EventsClusterConfig", "(", "c", "*", "check", ".", "C", ")", "{", "testCases", ":=", "[", "]", "eventTest", "{", "{", "name", ":", "\"Cluster config\"", ",", "kind", ":", "services", ".", "WatchKind", "{", "Kind", ":", "services", ".", "KindClusterConfig", ",", "}", ",", "crud", ":", "func", "(", ")", "services", ".", "Resource", "{", "config", ",", "err", ":=", "services", ".", "NewClusterConfig", "(", "services", ".", "ClusterConfigSpecV3", "{", "}", ")", "\n", "c", ".", "Assert", "(", "err", ",", "check", ".", "IsNil", ")", "\n", "err", "=", "s", ".", "ConfigS", ".", "SetClusterConfig", "(", "config", ")", "\n", "c", ".", "Assert", "(", "err", ",", "check", ".", "IsNil", ")", "\n", "out", ",", "err", ":=", "s", ".", "ConfigS", ".", "GetClusterConfig", "(", ")", "\n", "c", ".", "Assert", "(", "err", ",", "check", ".", "IsNil", ")", "\n", "err", "=", "s", ".", "ConfigS", ".", "DeleteClusterConfig", "(", ")", "\n", "c", ".", "Assert", "(", "err", ",", "check", ".", "IsNil", ")", "\n", "return", "out", "\n", "}", ",", "}", ",", "{", "name", ":", "\"Cluster name\"", ",", "kind", ":", "services", ".", "WatchKind", "{", "Kind", ":", "services", ".", "KindClusterName", ",", "}", ",", "crud", ":", "func", "(", ")", "services", ".", "Resource", "{", "clusterName", ",", "err", ":=", "services", ".", "NewClusterName", "(", "services", ".", "ClusterNameSpecV2", "{", "ClusterName", ":", "\"example.com\"", ",", "}", ")", "\n", "c", ".", "Assert", "(", "err", ",", "check", ".", "IsNil", ")", "\n", "err", "=", "s", ".", "ConfigS", ".", "SetClusterName", "(", "clusterName", ")", "\n", "c", ".", "Assert", "(", "err", ",", "check", ".", "IsNil", ")", "\n", "out", ",", "err", ":=", "s", ".", "ConfigS", ".", "GetClusterName", "(", ")", "\n", "c", ".", "Assert", "(", "err", ",", "check", ".", "IsNil", ")", "\n", "err", "=", "s", ".", "ConfigS", ".", "DeleteClusterName", "(", ")", "\n", "c", ".", "Assert", "(", "err", ",", "check", ".", "IsNil", ")", "\n", "return", "out", "\n", "}", ",", "}", ",", "}", "\n", "s", ".", "runEventsTests", "(", "c", ",", "testCases", ")", "\n", "}" ]
// EventsClusterConfig tests cluster config resource events
[ "EventsClusterConfig", "tests", "cluster", "config", "resource", "events" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/suite/suite.go#L1310-L1357
train
gravitational/teleport
lib/services/tunnelconn.go
TunnelConnectionStatus
func TunnelConnectionStatus(clock clockwork.Clock, conn TunnelConnection) string { diff := clock.Now().Sub(conn.GetLastHeartbeat()) if diff < defaults.ReverseTunnelOfflineThreshold { return teleport.RemoteClusterStatusOnline } return teleport.RemoteClusterStatusOffline }
go
func TunnelConnectionStatus(clock clockwork.Clock, conn TunnelConnection) string { diff := clock.Now().Sub(conn.GetLastHeartbeat()) if diff < defaults.ReverseTunnelOfflineThreshold { return teleport.RemoteClusterStatusOnline } return teleport.RemoteClusterStatusOffline }
[ "func", "TunnelConnectionStatus", "(", "clock", "clockwork", ".", "Clock", ",", "conn", "TunnelConnection", ")", "string", "{", "diff", ":=", "clock", ".", "Now", "(", ")", ".", "Sub", "(", "conn", ".", "GetLastHeartbeat", "(", ")", ")", "\n", "if", "diff", "<", "defaults", ".", "ReverseTunnelOfflineThreshold", "{", "return", "teleport", ".", "RemoteClusterStatusOnline", "\n", "}", "\n", "return", "teleport", ".", "RemoteClusterStatusOffline", "\n", "}" ]
// IsTunnelConnectionStatus returns tunnel connection status based on the last // heartbeat time recorded for a connection
[ "IsTunnelConnectionStatus", "returns", "tunnel", "connection", "status", "based", "on", "the", "last", "heartbeat", "time", "recorded", "for", "a", "connection" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/tunnelconn.go#L78-L84
train
gravitational/teleport
lib/services/tunnelconn.go
MustCreateTunnelConnection
func MustCreateTunnelConnection(name string, spec TunnelConnectionSpecV2) TunnelConnection { conn, err := NewTunnelConnection(name, spec) if err != nil { panic(err) } return conn }
go
func MustCreateTunnelConnection(name string, spec TunnelConnectionSpecV2) TunnelConnection { conn, err := NewTunnelConnection(name, spec) if err != nil { panic(err) } return conn }
[ "func", "MustCreateTunnelConnection", "(", "name", "string", ",", "spec", "TunnelConnectionSpecV2", ")", "TunnelConnection", "{", "conn", ",", "err", ":=", "NewTunnelConnection", "(", "name", ",", "spec", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "conn", "\n", "}" ]
// MustCreateTunnelConnection returns new connection from V2 spec or panics if // parameters are incorrect
[ "MustCreateTunnelConnection", "returns", "new", "connection", "from", "V2", "spec", "or", "panics", "if", "parameters", "are", "incorrect" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/tunnelconn.go#L88-L94
train
gravitational/teleport
lib/services/tunnelconn.go
NewTunnelConnection
func NewTunnelConnection(name string, spec TunnelConnectionSpecV2) (TunnelConnection, error) { conn := &TunnelConnectionV2{ Kind: KindTunnelConnection, SubKind: spec.ClusterName, Version: V2, Metadata: Metadata{ Name: name, Namespace: defaults.Namespace, }, Spec: spec, } if err := conn.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } return conn, nil }
go
func NewTunnelConnection(name string, spec TunnelConnectionSpecV2) (TunnelConnection, error) { conn := &TunnelConnectionV2{ Kind: KindTunnelConnection, SubKind: spec.ClusterName, Version: V2, Metadata: Metadata{ Name: name, Namespace: defaults.Namespace, }, Spec: spec, } if err := conn.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } return conn, nil }
[ "func", "NewTunnelConnection", "(", "name", "string", ",", "spec", "TunnelConnectionSpecV2", ")", "(", "TunnelConnection", ",", "error", ")", "{", "conn", ":=", "&", "TunnelConnectionV2", "{", "Kind", ":", "KindTunnelConnection", ",", "SubKind", ":", "spec", ".", "ClusterName", ",", "Version", ":", "V2", ",", "Metadata", ":", "Metadata", "{", "Name", ":", "name", ",", "Namespace", ":", "defaults", ".", "Namespace", ",", "}", ",", "Spec", ":", "spec", ",", "}", "\n", "if", "err", ":=", "conn", ".", "CheckAndSetDefaults", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "conn", ",", "nil", "\n", "}" ]
// NewTunnelConnection returns new connection from V2 spec
[ "NewTunnelConnection", "returns", "new", "connection", "from", "V2", "spec" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/tunnelconn.go#L97-L112
train
gravitational/teleport
lib/services/tunnelconn.go
String
func (r *TunnelConnectionV2) String() string { return fmt.Sprintf("TunnelConnection(name=%v, type=%v, cluster=%v, proxy=%v)", r.Metadata.Name, r.Spec.Type, r.Spec.ClusterName, r.Spec.ProxyName) }
go
func (r *TunnelConnectionV2) String() string { return fmt.Sprintf("TunnelConnection(name=%v, type=%v, cluster=%v, proxy=%v)", r.Metadata.Name, r.Spec.Type, r.Spec.ClusterName, r.Spec.ProxyName) }
[ "func", "(", "r", "*", "TunnelConnectionV2", ")", "String", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"TunnelConnection(name=%v, type=%v, cluster=%v, proxy=%v)\"", ",", "r", ".", "Metadata", ".", "Name", ",", "r", ".", "Spec", ".", "Type", ",", "r", ".", "Spec", ".", "ClusterName", ",", "r", ".", "Spec", ".", "ProxyName", ")", "\n", "}" ]
// String returns user-friendly description of this connection
[ "String", "returns", "user", "-", "friendly", "description", "of", "this", "connection" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/tunnelconn.go#L151-L154
train
gravitational/teleport
lib/services/tunnelconn.go
SetLastHeartbeat
func (r *TunnelConnectionV2) SetLastHeartbeat(tm time.Time) { r.Spec.LastHeartbeat = tm }
go
func (r *TunnelConnectionV2) SetLastHeartbeat(tm time.Time) { r.Spec.LastHeartbeat = tm }
[ "func", "(", "r", "*", "TunnelConnectionV2", ")", "SetLastHeartbeat", "(", "tm", "time", ".", "Time", ")", "{", "r", ".", "Spec", ".", "LastHeartbeat", "=", "tm", "\n", "}" ]
// SetLastHeartbeat sets last heartbeat time
[ "SetLastHeartbeat", "sets", "last", "heartbeat", "time" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/tunnelconn.go#L221-L223
train
gravitational/teleport
lib/services/tunnelconn.go
UnmarshalTunnelConnection
func UnmarshalTunnelConnection(data []byte, opts ...MarshalOption) (TunnelConnection, error) { if len(data) == 0 { return nil, trace.BadParameter("missing tunnel connection data") } cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } var h ResourceHeader err = utils.FastUnmarshal(data, &h) if err != nil { return nil, trace.Wrap(err) } switch h.Version { case V2: var r TunnelConnectionV2 if cfg.SkipValidation { if err := utils.FastUnmarshal(data, &r); err != nil { return nil, trace.BadParameter(err.Error()) } } else { if err := utils.UnmarshalWithSchema(GetTunnelConnectionSchema(), &r, data); err != nil { return nil, trace.BadParameter(err.Error()) } } if err := r.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } if cfg.ID != 0 { r.SetResourceID(cfg.ID) } if !cfg.Expires.IsZero() { r.SetExpiry(cfg.Expires) } return &r, nil } return nil, trace.BadParameter("reverse tunnel version %v is not supported", h.Version) }
go
func UnmarshalTunnelConnection(data []byte, opts ...MarshalOption) (TunnelConnection, error) { if len(data) == 0 { return nil, trace.BadParameter("missing tunnel connection data") } cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } var h ResourceHeader err = utils.FastUnmarshal(data, &h) if err != nil { return nil, trace.Wrap(err) } switch h.Version { case V2: var r TunnelConnectionV2 if cfg.SkipValidation { if err := utils.FastUnmarshal(data, &r); err != nil { return nil, trace.BadParameter(err.Error()) } } else { if err := utils.UnmarshalWithSchema(GetTunnelConnectionSchema(), &r, data); err != nil { return nil, trace.BadParameter(err.Error()) } } if err := r.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } if cfg.ID != 0 { r.SetResourceID(cfg.ID) } if !cfg.Expires.IsZero() { r.SetExpiry(cfg.Expires) } return &r, nil } return nil, trace.BadParameter("reverse tunnel version %v is not supported", h.Version) }
[ "func", "UnmarshalTunnelConnection", "(", "data", "[", "]", "byte", ",", "opts", "...", "MarshalOption", ")", "(", "TunnelConnection", ",", "error", ")", "{", "if", "len", "(", "data", ")", "==", "0", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"missing tunnel connection data\"", ")", "\n", "}", "\n", "cfg", ",", "err", ":=", "collectOptions", "(", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "var", "h", "ResourceHeader", "\n", "err", "=", "utils", ".", "FastUnmarshal", "(", "data", ",", "&", "h", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "switch", "h", ".", "Version", "{", "case", "V2", ":", "var", "r", "TunnelConnectionV2", "\n", "if", "cfg", ".", "SkipValidation", "{", "if", "err", ":=", "utils", ".", "FastUnmarshal", "(", "data", ",", "&", "r", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "}", "else", "{", "if", "err", ":=", "utils", ".", "UnmarshalWithSchema", "(", "GetTunnelConnectionSchema", "(", ")", ",", "&", "r", ",", "data", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "}", "\n", "if", "err", ":=", "r", ".", "CheckAndSetDefaults", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "cfg", ".", "ID", "!=", "0", "{", "r", ".", "SetResourceID", "(", "cfg", ".", "ID", ")", "\n", "}", "\n", "if", "!", "cfg", ".", "Expires", ".", "IsZero", "(", ")", "{", "r", ".", "SetExpiry", "(", "cfg", ".", "Expires", ")", "\n", "}", "\n", "return", "&", "r", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"reverse tunnel version %v is not supported\"", ",", "h", ".", "Version", ")", "\n", "}" ]
// UnmarshalTunnelConnection unmarshals reverse tunnel from JSON or YAML, // sets defaults and checks the schema
[ "UnmarshalTunnelConnection", "unmarshals", "reverse", "tunnel", "from", "JSON", "or", "YAML", "sets", "defaults", "and", "checks", "the", "schema" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/tunnelconn.go#L275-L314
train
gravitational/teleport
lib/services/tunnelconn.go
MarshalTunnelConnection
func MarshalTunnelConnection(rt TunnelConnection, opts ...MarshalOption) ([]byte, error) { cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } switch resource := rt.(type) { case *TunnelConnectionV2: if !cfg.PreserveResourceID { // avoid modifying the original object // to prevent unexpected data races copy := *resource copy.SetResourceID(0) resource = &copy } return utils.FastMarshal(resource) default: return nil, trace.BadParameter("unrecognized resource version %T", rt) } }
go
func MarshalTunnelConnection(rt TunnelConnection, opts ...MarshalOption) ([]byte, error) { cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } switch resource := rt.(type) { case *TunnelConnectionV2: if !cfg.PreserveResourceID { // avoid modifying the original object // to prevent unexpected data races copy := *resource copy.SetResourceID(0) resource = &copy } return utils.FastMarshal(resource) default: return nil, trace.BadParameter("unrecognized resource version %T", rt) } }
[ "func", "MarshalTunnelConnection", "(", "rt", "TunnelConnection", ",", "opts", "...", "MarshalOption", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "cfg", ",", "err", ":=", "collectOptions", "(", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "switch", "resource", ":=", "rt", ".", "(", "type", ")", "{", "case", "*", "TunnelConnectionV2", ":", "if", "!", "cfg", ".", "PreserveResourceID", "{", "copy", ":=", "*", "resource", "\n", "copy", ".", "SetResourceID", "(", "0", ")", "\n", "resource", "=", "&", "copy", "\n", "}", "\n", "return", "utils", ".", "FastMarshal", "(", "resource", ")", "\n", "default", ":", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"unrecognized resource version %T\"", ",", "rt", ")", "\n", "}", "\n", "}" ]
// MarshalTunnelConnection marshals tunnel connection
[ "MarshalTunnelConnection", "marshals", "tunnel", "connection" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/tunnelconn.go#L317-L335
train
gravitational/teleport
tool/tctl/common/status_command.go
Initialize
func (c *StatusCommand) Initialize(app *kingpin.Application, config *service.Config) { c.config = config c.status = app.Command("status", "Report cluster status") }
go
func (c *StatusCommand) Initialize(app *kingpin.Application, config *service.Config) { c.config = config c.status = app.Command("status", "Report cluster status") }
[ "func", "(", "c", "*", "StatusCommand", ")", "Initialize", "(", "app", "*", "kingpin", ".", "Application", ",", "config", "*", "service", ".", "Config", ")", "{", "c", ".", "config", "=", "config", "\n", "c", ".", "status", "=", "app", ".", "Command", "(", "\"status\"", ",", "\"Report cluster status\"", ")", "\n", "}" ]
// Initialize allows StatusCommand to plug itself into the CLI parser.
[ "Initialize", "allows", "StatusCommand", "to", "plug", "itself", "into", "the", "CLI", "parser", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/status_command.go#L41-L44
train
gravitational/teleport
tool/tctl/common/status_command.go
Status
func (c *StatusCommand) Status(client auth.ClientI) error { clusterNameResource, err := client.GetClusterName() if err != nil { return trace.Wrap(err) } clusterName := clusterNameResource.GetClusterName() hostCAs, err := client.GetCertAuthorities(services.HostCA, false) if err != nil { return trace.Wrap(err) } userCAs, err := client.GetCertAuthorities(services.UserCA, false) if err != nil { return trace.Wrap(err) } // Calculate the CA pin for this cluster. The CA pin is used by the client // to verify the identity of the Auth Server. caPin, err := calculateCAPin(client) if err != nil { return trace.Wrap(err) } authorities := append(userCAs, hostCAs...) view := func() string { table := asciitable.MakeHeadlessTable(2) table.AddRow([]string{"Cluster", clusterName}) for _, ca := range authorities { if ca.GetClusterName() != clusterName { continue } info := fmt.Sprintf("%v CA ", strings.Title(string(ca.GetType()))) rotation := ca.GetRotation() if c.config.Debug { table.AddRow([]string{info, fmt.Sprintf("%v, update_servers: %v, complete: %v", rotation.String(), rotation.Schedule.UpdateServers.Format(teleport.HumanDateFormatSeconds), rotation.Schedule.Standby.Format(teleport.HumanDateFormatSeconds), )}) } else { table.AddRow([]string{info, rotation.String()}) } } table.AddRow([]string{"CA pin", caPin}) return table.AsBuffer().String() } fmt.Printf(view()) // in debug mode, output mode of remote certificate authorities if c.config.Debug { view := func() string { table := asciitable.MakeHeadlessTable(2) for _, ca := range authorities { if ca.GetClusterName() == clusterName { continue } info := fmt.Sprintf("Remote %v CA %q", strings.Title(string(ca.GetType())), ca.GetClusterName()) rotation := ca.GetRotation() table.AddRow([]string{info, rotation.String()}) } return "Remote clusters\n\n" + table.AsBuffer().String() } fmt.Printf(view()) } return nil }
go
func (c *StatusCommand) Status(client auth.ClientI) error { clusterNameResource, err := client.GetClusterName() if err != nil { return trace.Wrap(err) } clusterName := clusterNameResource.GetClusterName() hostCAs, err := client.GetCertAuthorities(services.HostCA, false) if err != nil { return trace.Wrap(err) } userCAs, err := client.GetCertAuthorities(services.UserCA, false) if err != nil { return trace.Wrap(err) } // Calculate the CA pin for this cluster. The CA pin is used by the client // to verify the identity of the Auth Server. caPin, err := calculateCAPin(client) if err != nil { return trace.Wrap(err) } authorities := append(userCAs, hostCAs...) view := func() string { table := asciitable.MakeHeadlessTable(2) table.AddRow([]string{"Cluster", clusterName}) for _, ca := range authorities { if ca.GetClusterName() != clusterName { continue } info := fmt.Sprintf("%v CA ", strings.Title(string(ca.GetType()))) rotation := ca.GetRotation() if c.config.Debug { table.AddRow([]string{info, fmt.Sprintf("%v, update_servers: %v, complete: %v", rotation.String(), rotation.Schedule.UpdateServers.Format(teleport.HumanDateFormatSeconds), rotation.Schedule.Standby.Format(teleport.HumanDateFormatSeconds), )}) } else { table.AddRow([]string{info, rotation.String()}) } } table.AddRow([]string{"CA pin", caPin}) return table.AsBuffer().String() } fmt.Printf(view()) // in debug mode, output mode of remote certificate authorities if c.config.Debug { view := func() string { table := asciitable.MakeHeadlessTable(2) for _, ca := range authorities { if ca.GetClusterName() == clusterName { continue } info := fmt.Sprintf("Remote %v CA %q", strings.Title(string(ca.GetType())), ca.GetClusterName()) rotation := ca.GetRotation() table.AddRow([]string{info, rotation.String()}) } return "Remote clusters\n\n" + table.AsBuffer().String() } fmt.Printf(view()) } return nil }
[ "func", "(", "c", "*", "StatusCommand", ")", "Status", "(", "client", "auth", ".", "ClientI", ")", "error", "{", "clusterNameResource", ",", "err", ":=", "client", ".", "GetClusterName", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "clusterName", ":=", "clusterNameResource", ".", "GetClusterName", "(", ")", "\n", "hostCAs", ",", "err", ":=", "client", ".", "GetCertAuthorities", "(", "services", ".", "HostCA", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "userCAs", ",", "err", ":=", "client", ".", "GetCertAuthorities", "(", "services", ".", "UserCA", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "caPin", ",", "err", ":=", "calculateCAPin", "(", "client", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "authorities", ":=", "append", "(", "userCAs", ",", "hostCAs", "...", ")", "\n", "view", ":=", "func", "(", ")", "string", "{", "table", ":=", "asciitable", ".", "MakeHeadlessTable", "(", "2", ")", "\n", "table", ".", "AddRow", "(", "[", "]", "string", "{", "\"Cluster\"", ",", "clusterName", "}", ")", "\n", "for", "_", ",", "ca", ":=", "range", "authorities", "{", "if", "ca", ".", "GetClusterName", "(", ")", "!=", "clusterName", "{", "continue", "\n", "}", "\n", "info", ":=", "fmt", ".", "Sprintf", "(", "\"%v CA \"", ",", "strings", ".", "Title", "(", "string", "(", "ca", ".", "GetType", "(", ")", ")", ")", ")", "\n", "rotation", ":=", "ca", ".", "GetRotation", "(", ")", "\n", "if", "c", ".", "config", ".", "Debug", "{", "table", ".", "AddRow", "(", "[", "]", "string", "{", "info", ",", "fmt", ".", "Sprintf", "(", "\"%v, update_servers: %v, complete: %v\"", ",", "rotation", ".", "String", "(", ")", ",", "rotation", ".", "Schedule", ".", "UpdateServers", ".", "Format", "(", "teleport", ".", "HumanDateFormatSeconds", ")", ",", "rotation", ".", "Schedule", ".", "Standby", ".", "Format", "(", "teleport", ".", "HumanDateFormatSeconds", ")", ",", ")", "}", ")", "\n", "}", "else", "{", "table", ".", "AddRow", "(", "[", "]", "string", "{", "info", ",", "rotation", ".", "String", "(", ")", "}", ")", "\n", "}", "\n", "}", "\n", "table", ".", "AddRow", "(", "[", "]", "string", "{", "\"CA pin\"", ",", "caPin", "}", ")", "\n", "return", "table", ".", "AsBuffer", "(", ")", ".", "String", "(", ")", "\n", "}", "\n", "fmt", ".", "Printf", "(", "view", "(", ")", ")", "\n", "if", "c", ".", "config", ".", "Debug", "{", "view", ":=", "func", "(", ")", "string", "{", "table", ":=", "asciitable", ".", "MakeHeadlessTable", "(", "2", ")", "\n", "for", "_", ",", "ca", ":=", "range", "authorities", "{", "if", "ca", ".", "GetClusterName", "(", ")", "==", "clusterName", "{", "continue", "\n", "}", "\n", "info", ":=", "fmt", ".", "Sprintf", "(", "\"Remote %v CA %q\"", ",", "strings", ".", "Title", "(", "string", "(", "ca", ".", "GetType", "(", ")", ")", ")", ",", "ca", ".", "GetClusterName", "(", ")", ")", "\n", "rotation", ":=", "ca", ".", "GetRotation", "(", ")", "\n", "table", ".", "AddRow", "(", "[", "]", "string", "{", "info", ",", "rotation", ".", "String", "(", ")", "}", ")", "\n", "}", "\n", "return", "\"Remote clusters\\n\\n\"", "+", "\\n", "\n", "}", "\n", "\\n", "\n", "}", "\n", "table", ".", "AsBuffer", "(", ")", ".", "String", "(", ")", "\n", "}" ]
// Status is called to execute "status" CLI command.
[ "Status", "is", "called", "to", "execute", "status", "CLI", "command", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/status_command.go#L58-L126
train
gravitational/teleport
lib/auth/trustedcluster.go
DeleteTrustedCluster
func (a *AuthServer) DeleteTrustedCluster(name string) error { err := a.DeleteCertAuthority(services.CertAuthID{Type: services.HostCA, DomainName: name}) if err != nil { if !trace.IsNotFound(err) { return trace.Wrap(err) } } err = a.DeleteCertAuthority(services.CertAuthID{Type: services.UserCA, DomainName: name}) if err != nil { if !trace.IsNotFound(err) { return trace.Wrap(err) } } err = a.DeleteReverseTunnel(name) if err != nil { if !trace.IsNotFound(err) { return trace.Wrap(err) } } err = a.Presence.DeleteTrustedCluster(name) if err != nil { return trace.Wrap(err) } return nil }
go
func (a *AuthServer) DeleteTrustedCluster(name string) error { err := a.DeleteCertAuthority(services.CertAuthID{Type: services.HostCA, DomainName: name}) if err != nil { if !trace.IsNotFound(err) { return trace.Wrap(err) } } err = a.DeleteCertAuthority(services.CertAuthID{Type: services.UserCA, DomainName: name}) if err != nil { if !trace.IsNotFound(err) { return trace.Wrap(err) } } err = a.DeleteReverseTunnel(name) if err != nil { if !trace.IsNotFound(err) { return trace.Wrap(err) } } err = a.Presence.DeleteTrustedCluster(name) if err != nil { return trace.Wrap(err) } return nil }
[ "func", "(", "a", "*", "AuthServer", ")", "DeleteTrustedCluster", "(", "name", "string", ")", "error", "{", "err", ":=", "a", ".", "DeleteCertAuthority", "(", "services", ".", "CertAuthID", "{", "Type", ":", "services", ".", "HostCA", ",", "DomainName", ":", "name", "}", ")", "\n", "if", "err", "!=", "nil", "{", "if", "!", "trace", ".", "IsNotFound", "(", "err", ")", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "}", "\n", "err", "=", "a", ".", "DeleteCertAuthority", "(", "services", ".", "CertAuthID", "{", "Type", ":", "services", ".", "UserCA", ",", "DomainName", ":", "name", "}", ")", "\n", "if", "err", "!=", "nil", "{", "if", "!", "trace", ".", "IsNotFound", "(", "err", ")", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "}", "\n", "err", "=", "a", ".", "DeleteReverseTunnel", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "if", "!", "trace", ".", "IsNotFound", "(", "err", ")", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "}", "\n", "err", "=", "a", ".", "Presence", ".", "DeleteTrustedCluster", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// DeleteTrustedCluster removes services.CertAuthority, services.ReverseTunnel, // and services.TrustedCluster resources.
[ "DeleteTrustedCluster", "removes", "services", ".", "CertAuthority", "services", ".", "ReverseTunnel", "and", "services", ".", "TrustedCluster", "resources", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/trustedcluster.go#L171-L199
train
gravitational/teleport
lib/auth/trustedcluster.go
DeleteRemoteCluster
func (a *AuthServer) DeleteRemoteCluster(clusterName string) error { // To make sure remote cluster exists - to protect against random // clusterName requests (e.g. when clusterName is set to local cluster name) _, err := a.Presence.GetRemoteCluster(clusterName) if err != nil { return trace.Wrap(err) } // delete cert authorities associated with the cluster err = a.DeleteCertAuthority(services.CertAuthID{ Type: services.HostCA, DomainName: clusterName, }) if err != nil { // this method could have succeeded on the first call, // but then if the remote cluster resource could not be deleted // it would be impossible to delete the cluster after then if !trace.IsNotFound(err) { return trace.Wrap(err) } } // there should be no User CA in trusted clusters on the main cluster side // per standard automation but clean up just in case err = a.DeleteCertAuthority(services.CertAuthID{ Type: services.UserCA, DomainName: clusterName, }) if err != nil { if !trace.IsNotFound(err) { return trace.Wrap(err) } } return a.Presence.DeleteRemoteCluster(clusterName) }
go
func (a *AuthServer) DeleteRemoteCluster(clusterName string) error { // To make sure remote cluster exists - to protect against random // clusterName requests (e.g. when clusterName is set to local cluster name) _, err := a.Presence.GetRemoteCluster(clusterName) if err != nil { return trace.Wrap(err) } // delete cert authorities associated with the cluster err = a.DeleteCertAuthority(services.CertAuthID{ Type: services.HostCA, DomainName: clusterName, }) if err != nil { // this method could have succeeded on the first call, // but then if the remote cluster resource could not be deleted // it would be impossible to delete the cluster after then if !trace.IsNotFound(err) { return trace.Wrap(err) } } // there should be no User CA in trusted clusters on the main cluster side // per standard automation but clean up just in case err = a.DeleteCertAuthority(services.CertAuthID{ Type: services.UserCA, DomainName: clusterName, }) if err != nil { if !trace.IsNotFound(err) { return trace.Wrap(err) } } return a.Presence.DeleteRemoteCluster(clusterName) }
[ "func", "(", "a", "*", "AuthServer", ")", "DeleteRemoteCluster", "(", "clusterName", "string", ")", "error", "{", "_", ",", "err", ":=", "a", ".", "Presence", ".", "GetRemoteCluster", "(", "clusterName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "err", "=", "a", ".", "DeleteCertAuthority", "(", "services", ".", "CertAuthID", "{", "Type", ":", "services", ".", "HostCA", ",", "DomainName", ":", "clusterName", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "if", "!", "trace", ".", "IsNotFound", "(", "err", ")", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "}", "\n", "err", "=", "a", ".", "DeleteCertAuthority", "(", "services", ".", "CertAuthID", "{", "Type", ":", "services", ".", "UserCA", ",", "DomainName", ":", "clusterName", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "if", "!", "trace", ".", "IsNotFound", "(", "err", ")", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "}", "\n", "return", "a", ".", "Presence", ".", "DeleteRemoteCluster", "(", "clusterName", ")", "\n", "}" ]
// DeleteRemoteCluster deletes remote cluster resource, all certificate authorities // associated with it
[ "DeleteRemoteCluster", "deletes", "remote", "cluster", "resource", "all", "certificate", "authorities", "associated", "with", "it" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/trustedcluster.go#L293-L325
train
gravitational/teleport
lib/auth/trustedcluster.go
GetRemoteCluster
func (a *AuthServer) GetRemoteCluster(clusterName string) (services.RemoteCluster, error) { // To make sure remote cluster exists - to protect against random // clusterName requests (e.g. when clusterName is set to local cluster name) remoteCluster, err := a.Presence.GetRemoteCluster(clusterName) if err != nil { return nil, trace.Wrap(err) } if err := a.updateRemoteClusterStatus(remoteCluster); err != nil { return nil, trace.Wrap(err) } return remoteCluster, nil }
go
func (a *AuthServer) GetRemoteCluster(clusterName string) (services.RemoteCluster, error) { // To make sure remote cluster exists - to protect against random // clusterName requests (e.g. when clusterName is set to local cluster name) remoteCluster, err := a.Presence.GetRemoteCluster(clusterName) if err != nil { return nil, trace.Wrap(err) } if err := a.updateRemoteClusterStatus(remoteCluster); err != nil { return nil, trace.Wrap(err) } return remoteCluster, nil }
[ "func", "(", "a", "*", "AuthServer", ")", "GetRemoteCluster", "(", "clusterName", "string", ")", "(", "services", ".", "RemoteCluster", ",", "error", ")", "{", "remoteCluster", ",", "err", ":=", "a", ".", "Presence", ".", "GetRemoteCluster", "(", "clusterName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "err", ":=", "a", ".", "updateRemoteClusterStatus", "(", "remoteCluster", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "remoteCluster", ",", "nil", "\n", "}" ]
// GetRemoteCluster returns remote cluster by name
[ "GetRemoteCluster", "returns", "remote", "cluster", "by", "name" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/trustedcluster.go#L328-L339
train
gravitational/teleport
lib/auth/trustedcluster.go
GetRemoteClusters
func (a *AuthServer) GetRemoteClusters(opts ...services.MarshalOption) ([]services.RemoteCluster, error) { // To make sure remote cluster exists - to protect against random // clusterName requests (e.g. when clusterName is set to local cluster name) remoteClusters, err := a.Presence.GetRemoteClusters(opts...) if err != nil { return nil, trace.Wrap(err) } for i := range remoteClusters { if err := a.updateRemoteClusterStatus(remoteClusters[i]); err != nil { return nil, trace.Wrap(err) } } return remoteClusters, nil }
go
func (a *AuthServer) GetRemoteClusters(opts ...services.MarshalOption) ([]services.RemoteCluster, error) { // To make sure remote cluster exists - to protect against random // clusterName requests (e.g. when clusterName is set to local cluster name) remoteClusters, err := a.Presence.GetRemoteClusters(opts...) if err != nil { return nil, trace.Wrap(err) } for i := range remoteClusters { if err := a.updateRemoteClusterStatus(remoteClusters[i]); err != nil { return nil, trace.Wrap(err) } } return remoteClusters, nil }
[ "func", "(", "a", "*", "AuthServer", ")", "GetRemoteClusters", "(", "opts", "...", "services", ".", "MarshalOption", ")", "(", "[", "]", "services", ".", "RemoteCluster", ",", "error", ")", "{", "remoteClusters", ",", "err", ":=", "a", ".", "Presence", ".", "GetRemoteClusters", "(", "opts", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "for", "i", ":=", "range", "remoteClusters", "{", "if", "err", ":=", "a", ".", "updateRemoteClusterStatus", "(", "remoteClusters", "[", "i", "]", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "}", "\n", "return", "remoteClusters", ",", "nil", "\n", "}" ]
// GetRemoteClusters returns remote clusters with updated statuses
[ "GetRemoteClusters", "returns", "remote", "clusters", "with", "updated", "statuses" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/trustedcluster.go#L357-L370
train
gravitational/teleport
lib/auth/trustedcluster.go
activateCertAuthority
func (a *AuthServer) activateCertAuthority(t services.TrustedCluster) error { err := a.ActivateCertAuthority(services.CertAuthID{Type: services.UserCA, DomainName: t.GetName()}) if err != nil { return trace.Wrap(err) } return trace.Wrap(a.ActivateCertAuthority(services.CertAuthID{Type: services.HostCA, DomainName: t.GetName()})) }
go
func (a *AuthServer) activateCertAuthority(t services.TrustedCluster) error { err := a.ActivateCertAuthority(services.CertAuthID{Type: services.UserCA, DomainName: t.GetName()}) if err != nil { return trace.Wrap(err) } return trace.Wrap(a.ActivateCertAuthority(services.CertAuthID{Type: services.HostCA, DomainName: t.GetName()})) }
[ "func", "(", "a", "*", "AuthServer", ")", "activateCertAuthority", "(", "t", "services", ".", "TrustedCluster", ")", "error", "{", "err", ":=", "a", ".", "ActivateCertAuthority", "(", "services", ".", "CertAuthID", "{", "Type", ":", "services", ".", "UserCA", ",", "DomainName", ":", "t", ".", "GetName", "(", ")", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "trace", ".", "Wrap", "(", "a", ".", "ActivateCertAuthority", "(", "services", ".", "CertAuthID", "{", "Type", ":", "services", ".", "HostCA", ",", "DomainName", ":", "t", ".", "GetName", "(", ")", "}", ")", ")", "\n", "}" ]
// activateCertAuthority will activate both the user and host certificate // authority given in the services.TrustedCluster resource.
[ "activateCertAuthority", "will", "activate", "both", "the", "user", "and", "host", "certificate", "authority", "given", "in", "the", "services", ".", "TrustedCluster", "resource", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/trustedcluster.go#L599-L606
train
gravitational/teleport
lib/auth/trustedcluster.go
createReverseTunnel
func (a *AuthServer) createReverseTunnel(t services.TrustedCluster) error { reverseTunnel := services.NewReverseTunnel( t.GetName(), []string{t.GetReverseTunnelAddress()}, ) return trace.Wrap(a.UpsertReverseTunnel(reverseTunnel)) }
go
func (a *AuthServer) createReverseTunnel(t services.TrustedCluster) error { reverseTunnel := services.NewReverseTunnel( t.GetName(), []string{t.GetReverseTunnelAddress()}, ) return trace.Wrap(a.UpsertReverseTunnel(reverseTunnel)) }
[ "func", "(", "a", "*", "AuthServer", ")", "createReverseTunnel", "(", "t", "services", ".", "TrustedCluster", ")", "error", "{", "reverseTunnel", ":=", "services", ".", "NewReverseTunnel", "(", "t", ".", "GetName", "(", ")", ",", "[", "]", "string", "{", "t", ".", "GetReverseTunnelAddress", "(", ")", "}", ",", ")", "\n", "return", "trace", ".", "Wrap", "(", "a", ".", "UpsertReverseTunnel", "(", "reverseTunnel", ")", ")", "\n", "}" ]
// createReverseTunnel will create a services.ReverseTunnel givenin the // services.TrustedCluster resource.
[ "createReverseTunnel", "will", "create", "a", "services", ".", "ReverseTunnel", "givenin", "the", "services", ".", "TrustedCluster", "resource", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/trustedcluster.go#L621-L627
train
gravitational/teleport
lib/services/local/configuration.go
DeleteClusterName
func (s *ClusterConfigurationService) DeleteClusterName() error { err := s.Delete(context.TODO(), backend.Key(clusterConfigPrefix, namePrefix)) if err != nil { if trace.IsNotFound(err) { return trace.NotFound("cluster configuration not found") } return trace.Wrap(err) } return nil }
go
func (s *ClusterConfigurationService) DeleteClusterName() error { err := s.Delete(context.TODO(), backend.Key(clusterConfigPrefix, namePrefix)) if err != nil { if trace.IsNotFound(err) { return trace.NotFound("cluster configuration not found") } return trace.Wrap(err) } return nil }
[ "func", "(", "s", "*", "ClusterConfigurationService", ")", "DeleteClusterName", "(", ")", "error", "{", "err", ":=", "s", ".", "Delete", "(", "context", ".", "TODO", "(", ")", ",", "backend", ".", "Key", "(", "clusterConfigPrefix", ",", "namePrefix", ")", ")", "\n", "if", "err", "!=", "nil", "{", "if", "trace", ".", "IsNotFound", "(", "err", ")", "{", "return", "trace", ".", "NotFound", "(", "\"cluster configuration not found\"", ")", "\n", "}", "\n", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// DeleteClusterName deletes services.ClusterName from the backend.
[ "DeleteClusterName", "deletes", "services", ".", "ClusterName", "from", "the", "backend", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/configuration.go#L54-L63
train
gravitational/teleport
lib/services/local/configuration.go
SetClusterName
func (s *ClusterConfigurationService) SetClusterName(c services.ClusterName) error { value, err := services.GetClusterNameMarshaler().Marshal(c) if err != nil { return trace.Wrap(err) } _, err = s.Create(context.TODO(), backend.Item{ Key: backend.Key(clusterConfigPrefix, namePrefix), Value: value, Expires: c.Expiry(), }) if err != nil { return trace.Wrap(err) } return nil }
go
func (s *ClusterConfigurationService) SetClusterName(c services.ClusterName) error { value, err := services.GetClusterNameMarshaler().Marshal(c) if err != nil { return trace.Wrap(err) } _, err = s.Create(context.TODO(), backend.Item{ Key: backend.Key(clusterConfigPrefix, namePrefix), Value: value, Expires: c.Expiry(), }) if err != nil { return trace.Wrap(err) } return nil }
[ "func", "(", "s", "*", "ClusterConfigurationService", ")", "SetClusterName", "(", "c", "services", ".", "ClusterName", ")", "error", "{", "value", ",", "err", ":=", "services", ".", "GetClusterNameMarshaler", "(", ")", ".", "Marshal", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "_", ",", "err", "=", "s", ".", "Create", "(", "context", ".", "TODO", "(", ")", ",", "backend", ".", "Item", "{", "Key", ":", "backend", ".", "Key", "(", "clusterConfigPrefix", ",", "namePrefix", ")", ",", "Value", ":", "value", ",", "Expires", ":", "c", ".", "Expiry", "(", ")", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// SetClusterName sets the name of the cluster in the backend. SetClusterName // can only be called once on a cluster after which it will return trace.AlreadyExists.
[ "SetClusterName", "sets", "the", "name", "of", "the", "cluster", "in", "the", "backend", ".", "SetClusterName", "can", "only", "be", "called", "once", "on", "a", "cluster", "after", "which", "it", "will", "return", "trace", ".", "AlreadyExists", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/configuration.go#L67-L83
train
gravitational/teleport
lib/services/local/configuration.go
GetAuthPreference
func (s *ClusterConfigurationService) GetAuthPreference() (services.AuthPreference, error) { item, err := s.Get(context.TODO(), backend.Key(authPrefix, preferencePrefix, generalPrefix)) if err != nil { if trace.IsNotFound(err) { return nil, trace.NotFound("authentication preference not found") } return nil, trace.Wrap(err) } return services.GetAuthPreferenceMarshaler().Unmarshal(item.Value, services.WithResourceID(item.ID), services.WithExpires(item.Expires)) }
go
func (s *ClusterConfigurationService) GetAuthPreference() (services.AuthPreference, error) { item, err := s.Get(context.TODO(), backend.Key(authPrefix, preferencePrefix, generalPrefix)) if err != nil { if trace.IsNotFound(err) { return nil, trace.NotFound("authentication preference not found") } return nil, trace.Wrap(err) } return services.GetAuthPreferenceMarshaler().Unmarshal(item.Value, services.WithResourceID(item.ID), services.WithExpires(item.Expires)) }
[ "func", "(", "s", "*", "ClusterConfigurationService", ")", "GetAuthPreference", "(", ")", "(", "services", ".", "AuthPreference", ",", "error", ")", "{", "item", ",", "err", ":=", "s", ".", "Get", "(", "context", ".", "TODO", "(", ")", ",", "backend", ".", "Key", "(", "authPrefix", ",", "preferencePrefix", ",", "generalPrefix", ")", ")", "\n", "if", "err", "!=", "nil", "{", "if", "trace", ".", "IsNotFound", "(", "err", ")", "{", "return", "nil", ",", "trace", ".", "NotFound", "(", "\"authentication preference not found\"", ")", "\n", "}", "\n", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "services", ".", "GetAuthPreferenceMarshaler", "(", ")", ".", "Unmarshal", "(", "item", ".", "Value", ",", "services", ".", "WithResourceID", "(", "item", ".", "ID", ")", ",", "services", ".", "WithExpires", "(", "item", ".", "Expires", ")", ")", "\n", "}" ]
// GetAuthPreference fetches the cluster authentication preferences // from the backend and return them.
[ "GetAuthPreference", "fetches", "the", "cluster", "authentication", "preferences", "from", "the", "backend", "and", "return", "them", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/configuration.go#L151-L161
train
gravitational/teleport
lib/services/local/configuration.go
SetAuthPreference
func (s *ClusterConfigurationService) SetAuthPreference(preferences services.AuthPreference) error { value, err := services.GetAuthPreferenceMarshaler().Marshal(preferences) if err != nil { return trace.Wrap(err) } item := backend.Item{ Key: backend.Key(authPrefix, preferencePrefix, generalPrefix), Value: value, ID: preferences.GetResourceID(), } _, err = s.Put(context.TODO(), item) if err != nil { return trace.Wrap(err) } return nil }
go
func (s *ClusterConfigurationService) SetAuthPreference(preferences services.AuthPreference) error { value, err := services.GetAuthPreferenceMarshaler().Marshal(preferences) if err != nil { return trace.Wrap(err) } item := backend.Item{ Key: backend.Key(authPrefix, preferencePrefix, generalPrefix), Value: value, ID: preferences.GetResourceID(), } _, err = s.Put(context.TODO(), item) if err != nil { return trace.Wrap(err) } return nil }
[ "func", "(", "s", "*", "ClusterConfigurationService", ")", "SetAuthPreference", "(", "preferences", "services", ".", "AuthPreference", ")", "error", "{", "value", ",", "err", ":=", "services", ".", "GetAuthPreferenceMarshaler", "(", ")", ".", "Marshal", "(", "preferences", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "item", ":=", "backend", ".", "Item", "{", "Key", ":", "backend", ".", "Key", "(", "authPrefix", ",", "preferencePrefix", ",", "generalPrefix", ")", ",", "Value", ":", "value", ",", "ID", ":", "preferences", ".", "GetResourceID", "(", ")", ",", "}", "\n", "_", ",", "err", "=", "s", ".", "Put", "(", "context", ".", "TODO", "(", ")", ",", "item", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// SetAuthPreference sets the cluster authentication preferences // on the backend.
[ "SetAuthPreference", "sets", "the", "cluster", "authentication", "preferences", "on", "the", "backend", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/configuration.go#L165-L183
train
gravitational/teleport
lib/services/local/configuration.go
DeleteClusterConfig
func (s *ClusterConfigurationService) DeleteClusterConfig() error { err := s.Delete(context.TODO(), backend.Key(clusterConfigPrefix, generalPrefix)) if err != nil { if trace.IsNotFound(err) { return trace.NotFound("cluster configuration not found") } return trace.Wrap(err) } return nil }
go
func (s *ClusterConfigurationService) DeleteClusterConfig() error { err := s.Delete(context.TODO(), backend.Key(clusterConfigPrefix, generalPrefix)) if err != nil { if trace.IsNotFound(err) { return trace.NotFound("cluster configuration not found") } return trace.Wrap(err) } return nil }
[ "func", "(", "s", "*", "ClusterConfigurationService", ")", "DeleteClusterConfig", "(", ")", "error", "{", "err", ":=", "s", ".", "Delete", "(", "context", ".", "TODO", "(", ")", ",", "backend", ".", "Key", "(", "clusterConfigPrefix", ",", "generalPrefix", ")", ")", "\n", "if", "err", "!=", "nil", "{", "if", "trace", ".", "IsNotFound", "(", "err", ")", "{", "return", "trace", ".", "NotFound", "(", "\"cluster configuration not found\"", ")", "\n", "}", "\n", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// DeleteClusterConfig deletes services.ClusterConfig from the backend.
[ "DeleteClusterConfig", "deletes", "services", ".", "ClusterConfig", "from", "the", "backend", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/configuration.go#L200-L209
train
gravitational/teleport
lib/services/local/configuration.go
SetClusterConfig
func (s *ClusterConfigurationService) SetClusterConfig(c services.ClusterConfig) error { value, err := services.GetClusterConfigMarshaler().Marshal(c) if err != nil { return trace.Wrap(err) } item := backend.Item{ Key: backend.Key(clusterConfigPrefix, generalPrefix), Value: value, ID: c.GetResourceID(), } _, err = s.Put(context.TODO(), item) if err != nil { return trace.Wrap(err) } return nil }
go
func (s *ClusterConfigurationService) SetClusterConfig(c services.ClusterConfig) error { value, err := services.GetClusterConfigMarshaler().Marshal(c) if err != nil { return trace.Wrap(err) } item := backend.Item{ Key: backend.Key(clusterConfigPrefix, generalPrefix), Value: value, ID: c.GetResourceID(), } _, err = s.Put(context.TODO(), item) if err != nil { return trace.Wrap(err) } return nil }
[ "func", "(", "s", "*", "ClusterConfigurationService", ")", "SetClusterConfig", "(", "c", "services", ".", "ClusterConfig", ")", "error", "{", "value", ",", "err", ":=", "services", ".", "GetClusterConfigMarshaler", "(", ")", ".", "Marshal", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "item", ":=", "backend", ".", "Item", "{", "Key", ":", "backend", ".", "Key", "(", "clusterConfigPrefix", ",", "generalPrefix", ")", ",", "Value", ":", "value", ",", "ID", ":", "c", ".", "GetResourceID", "(", ")", ",", "}", "\n", "_", ",", "err", "=", "s", ".", "Put", "(", "context", ".", "TODO", "(", ")", ",", "item", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// SetClusterConfig sets services.ClusterConfig on the backend.
[ "SetClusterConfig", "sets", "services", ".", "ClusterConfig", "on", "the", "backend", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/configuration.go#L212-L230
train
gravitational/teleport
lib/httplib/httpheaders.go
SetNoCacheHeaders
func SetNoCacheHeaders(h http.Header) { h.Set("Cache-Control", "no-cache, no-store, must-revalidate") h.Set("Pragma", "no-cache") h.Set("Expires", "0") }
go
func SetNoCacheHeaders(h http.Header) { h.Set("Cache-Control", "no-cache, no-store, must-revalidate") h.Set("Pragma", "no-cache") h.Set("Expires", "0") }
[ "func", "SetNoCacheHeaders", "(", "h", "http", ".", "Header", ")", "{", "h", ".", "Set", "(", "\"Cache-Control\"", ",", "\"no-cache, no-store, must-revalidate\"", ")", "\n", "h", ".", "Set", "(", "\"Pragma\"", ",", "\"no-cache\"", ")", "\n", "h", ".", "Set", "(", "\"Expires\"", ",", "\"0\"", ")", "\n", "}" ]
// SetNoCacheHeaders tells proxies and browsers do not cache the content
[ "SetNoCacheHeaders", "tells", "proxies", "and", "browsers", "do", "not", "cache", "the", "content" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/httplib/httpheaders.go#L27-L31
train
gravitational/teleport
lib/httplib/httpheaders.go
SetIndexHTMLHeaders
func SetIndexHTMLHeaders(h http.Header) { SetNoCacheHeaders(h) SetSameOriginIFrame(h) SetNoSniff(h) // X-Frame-Options indicates that the page can only be displayed in iframe on the same origin as the page itself h.Set("X-Frame-Options", "SAMEORIGIN") // X-XSS-Protection is a feature of Internet Explorer, Chrome and Safari that stops pages // from loading when they detect reflected cross-site scripting (XSS) attacks. h.Set("X-XSS-Protection", "1; mode=block") // Once a supported browser receives this header that browser will prevent any communications from // being sent over HTTP to the specified domain and will instead send all communications over HTTPS. // It also prevents HTTPS click through prompts on browsers h.Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains") // Prevent web browsers from using content sniffing to discover a file’s MIME type h.Set("X-Content-Type-Options", "nosniff") // Set content policy flags var cspValue = strings.Join([]string{ "script-src 'self'", // 'unsafe-inline' needed for reactjs inline styles "style-src 'self' 'unsafe-inline'", "object-src 'none'", "img-src 'self' data: blob:", }, ";") h.Set("Content-Security-Policy", cspValue) }
go
func SetIndexHTMLHeaders(h http.Header) { SetNoCacheHeaders(h) SetSameOriginIFrame(h) SetNoSniff(h) // X-Frame-Options indicates that the page can only be displayed in iframe on the same origin as the page itself h.Set("X-Frame-Options", "SAMEORIGIN") // X-XSS-Protection is a feature of Internet Explorer, Chrome and Safari that stops pages // from loading when they detect reflected cross-site scripting (XSS) attacks. h.Set("X-XSS-Protection", "1; mode=block") // Once a supported browser receives this header that browser will prevent any communications from // being sent over HTTP to the specified domain and will instead send all communications over HTTPS. // It also prevents HTTPS click through prompts on browsers h.Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains") // Prevent web browsers from using content sniffing to discover a file’s MIME type h.Set("X-Content-Type-Options", "nosniff") // Set content policy flags var cspValue = strings.Join([]string{ "script-src 'self'", // 'unsafe-inline' needed for reactjs inline styles "style-src 'self' 'unsafe-inline'", "object-src 'none'", "img-src 'self' data: blob:", }, ";") h.Set("Content-Security-Policy", cspValue) }
[ "func", "SetIndexHTMLHeaders", "(", "h", "http", ".", "Header", ")", "{", "SetNoCacheHeaders", "(", "h", ")", "\n", "SetSameOriginIFrame", "(", "h", ")", "\n", "SetNoSniff", "(", "h", ")", "\n", "h", ".", "Set", "(", "\"X-Frame-Options\"", ",", "\"SAMEORIGIN\"", ")", "\n", "h", ".", "Set", "(", "\"X-XSS-Protection\"", ",", "\"1; mode=block\"", ")", "\n", "h", ".", "Set", "(", "\"Strict-Transport-Security\"", ",", "\"max-age=31536000; includeSubDomains\"", ")", "\n", "h", ".", "Set", "(", "\"X-Content-Type-Options\"", ",", "\"nosniff\"", ")", "\n", "var", "cspValue", "=", "strings", ".", "Join", "(", "[", "]", "string", "{", "\"script-src 'self'\"", ",", "\"style-src 'self' 'unsafe-inline'\"", ",", "\"object-src 'none'\"", ",", "\"img-src 'self' data: blob:\"", ",", "}", ",", "\";\"", ")", "\n", "h", ".", "Set", "(", "\"Content-Security-Policy\"", ",", "cspValue", ")", "\n", "}" ]
// SetIndexHTMLHeaders sets security header flags for main index.html page
[ "SetIndexHTMLHeaders", "sets", "security", "header", "flags", "for", "main", "index", ".", "html", "page" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/httplib/httpheaders.go#L40-L70
train
gravitational/teleport
lib/kube/proxy/roundtrip.go
NewSpdyRoundTripperWithDialer
func NewSpdyRoundTripperWithDialer(cfg roundTripperConfig) *SpdyRoundTripper { return &SpdyRoundTripper{tlsConfig: cfg.tlsConfig, followRedirects: cfg.followRedirects, dialWithContext: cfg.dial, ctx: cfg.ctx, authCtx: cfg.authCtx, bearerToken: cfg.bearerToken} }
go
func NewSpdyRoundTripperWithDialer(cfg roundTripperConfig) *SpdyRoundTripper { return &SpdyRoundTripper{tlsConfig: cfg.tlsConfig, followRedirects: cfg.followRedirects, dialWithContext: cfg.dial, ctx: cfg.ctx, authCtx: cfg.authCtx, bearerToken: cfg.bearerToken} }
[ "func", "NewSpdyRoundTripperWithDialer", "(", "cfg", "roundTripperConfig", ")", "*", "SpdyRoundTripper", "{", "return", "&", "SpdyRoundTripper", "{", "tlsConfig", ":", "cfg", ".", "tlsConfig", ",", "followRedirects", ":", "cfg", ".", "followRedirects", ",", "dialWithContext", ":", "cfg", ".", "dial", ",", "ctx", ":", "cfg", ".", "ctx", ",", "authCtx", ":", "cfg", ".", "authCtx", ",", "bearerToken", ":", "cfg", ".", "bearerToken", "}", "\n", "}" ]
// NewSpdyRoundTripperWithDialer creates a new SpdyRoundTripper that will use // the specified tlsConfig. This function is mostly meant for unit tests.
[ "NewSpdyRoundTripperWithDialer", "creates", "a", "new", "SpdyRoundTripper", "that", "will", "use", "the", "specified", "tlsConfig", ".", "This", "function", "is", "mostly", "meant", "for", "unit", "tests", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/roundtrip.go#L99-L101
train
gravitational/teleport
lib/kube/proxy/roundtrip.go
dial
func (s *SpdyRoundTripper) dial(req *http.Request) (net.Conn, error) { return s.dialWithoutProxy(req.URL) }
go
func (s *SpdyRoundTripper) dial(req *http.Request) (net.Conn, error) { return s.dialWithoutProxy(req.URL) }
[ "func", "(", "s", "*", "SpdyRoundTripper", ")", "dial", "(", "req", "*", "http", ".", "Request", ")", "(", "net", ".", "Conn", ",", "error", ")", "{", "return", "s", ".", "dialWithoutProxy", "(", "req", ".", "URL", ")", "\n", "}" ]
// dial dials the host specified by req
[ "dial", "dials", "the", "host", "specified", "by", "req" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/roundtrip.go#L125-L127
train
gravitational/teleport
lib/srv/authhandlers.go
CreateIdentityContext
func (h *AuthHandlers) CreateIdentityContext(sconn *ssh.ServerConn) (IdentityContext, error) { identity := IdentityContext{ TeleportUser: sconn.Permissions.Extensions[utils.CertTeleportUser], Certificate: []byte(sconn.Permissions.Extensions[utils.CertTeleportUserCertificate]), Login: sconn.User(), } clusterName, err := h.AccessPoint.GetClusterName() if err != nil { return IdentityContext{}, trace.Wrap(err) } certificate, err := identity.GetCertificate() if err != nil { return IdentityContext{}, trace.Wrap(err) } if certificate.ValidBefore != 0 { identity.CertValidBefore = time.Unix(int64(certificate.ValidBefore), 0) } certAuthority, err := h.authorityForCert(services.UserCA, certificate.SignatureKey) if err != nil { return IdentityContext{}, trace.Wrap(err) } identity.CertAuthority = certAuthority roleSet, err := h.fetchRoleSet(certificate, certAuthority, identity.TeleportUser, clusterName.GetClusterName()) if err != nil { return IdentityContext{}, trace.Wrap(err) } identity.RoleSet = roleSet return identity, nil }
go
func (h *AuthHandlers) CreateIdentityContext(sconn *ssh.ServerConn) (IdentityContext, error) { identity := IdentityContext{ TeleportUser: sconn.Permissions.Extensions[utils.CertTeleportUser], Certificate: []byte(sconn.Permissions.Extensions[utils.CertTeleportUserCertificate]), Login: sconn.User(), } clusterName, err := h.AccessPoint.GetClusterName() if err != nil { return IdentityContext{}, trace.Wrap(err) } certificate, err := identity.GetCertificate() if err != nil { return IdentityContext{}, trace.Wrap(err) } if certificate.ValidBefore != 0 { identity.CertValidBefore = time.Unix(int64(certificate.ValidBefore), 0) } certAuthority, err := h.authorityForCert(services.UserCA, certificate.SignatureKey) if err != nil { return IdentityContext{}, trace.Wrap(err) } identity.CertAuthority = certAuthority roleSet, err := h.fetchRoleSet(certificate, certAuthority, identity.TeleportUser, clusterName.GetClusterName()) if err != nil { return IdentityContext{}, trace.Wrap(err) } identity.RoleSet = roleSet return identity, nil }
[ "func", "(", "h", "*", "AuthHandlers", ")", "CreateIdentityContext", "(", "sconn", "*", "ssh", ".", "ServerConn", ")", "(", "IdentityContext", ",", "error", ")", "{", "identity", ":=", "IdentityContext", "{", "TeleportUser", ":", "sconn", ".", "Permissions", ".", "Extensions", "[", "utils", ".", "CertTeleportUser", "]", ",", "Certificate", ":", "[", "]", "byte", "(", "sconn", ".", "Permissions", ".", "Extensions", "[", "utils", ".", "CertTeleportUserCertificate", "]", ")", ",", "Login", ":", "sconn", ".", "User", "(", ")", ",", "}", "\n", "clusterName", ",", "err", ":=", "h", ".", "AccessPoint", ".", "GetClusterName", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "IdentityContext", "{", "}", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "certificate", ",", "err", ":=", "identity", ".", "GetCertificate", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "IdentityContext", "{", "}", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "certificate", ".", "ValidBefore", "!=", "0", "{", "identity", ".", "CertValidBefore", "=", "time", ".", "Unix", "(", "int64", "(", "certificate", ".", "ValidBefore", ")", ",", "0", ")", "\n", "}", "\n", "certAuthority", ",", "err", ":=", "h", ".", "authorityForCert", "(", "services", ".", "UserCA", ",", "certificate", ".", "SignatureKey", ")", "\n", "if", "err", "!=", "nil", "{", "return", "IdentityContext", "{", "}", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "identity", ".", "CertAuthority", "=", "certAuthority", "\n", "roleSet", ",", "err", ":=", "h", ".", "fetchRoleSet", "(", "certificate", ",", "certAuthority", ",", "identity", ".", "TeleportUser", ",", "clusterName", ".", "GetClusterName", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "IdentityContext", "{", "}", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "identity", ".", "RoleSet", "=", "roleSet", "\n", "return", "identity", ",", "nil", "\n", "}" ]
// BuildIdentityContext returns an IdentityContext populated with information // about the logged in user on the connection.
[ "BuildIdentityContext", "returns", "an", "IdentityContext", "populated", "with", "information", "about", "the", "logged", "in", "user", "on", "the", "connection", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/authhandlers.go#L59-L92
train
gravitational/teleport
lib/srv/authhandlers.go
CheckAgentForward
func (h *AuthHandlers) CheckAgentForward(ctx *ServerContext) error { if err := ctx.Identity.RoleSet.CheckAgentForward(ctx.Identity.Login); err != nil { return trace.Wrap(err) } return nil }
go
func (h *AuthHandlers) CheckAgentForward(ctx *ServerContext) error { if err := ctx.Identity.RoleSet.CheckAgentForward(ctx.Identity.Login); err != nil { return trace.Wrap(err) } return nil }
[ "func", "(", "h", "*", "AuthHandlers", ")", "CheckAgentForward", "(", "ctx", "*", "ServerContext", ")", "error", "{", "if", "err", ":=", "ctx", ".", "Identity", ".", "RoleSet", ".", "CheckAgentForward", "(", "ctx", ".", "Identity", ".", "Login", ")", ";", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// CheckAgentForward checks if agent forwarding is allowed for the users RoleSet.
[ "CheckAgentForward", "checks", "if", "agent", "forwarding", "is", "allowed", "for", "the", "users", "RoleSet", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/authhandlers.go#L95-L101
train
gravitational/teleport
lib/srv/authhandlers.go
CheckPortForward
func (h *AuthHandlers) CheckPortForward(addr string, ctx *ServerContext) error { if ok := ctx.Identity.RoleSet.CanPortForward(); !ok { systemErrorMessage := fmt.Sprintf("port forwarding not allowed by role set: %v", ctx.Identity.RoleSet) userErrorMessage := "port forwarding not allowed" // emit port forward failure event h.AuditLog.EmitAuditEvent(events.PortForwardFailure, events.EventFields{ events.PortForwardAddr: addr, events.PortForwardSuccess: false, events.PortForwardErr: systemErrorMessage, events.EventLogin: ctx.Identity.Login, events.EventUser: ctx.Identity.TeleportUser, events.LocalAddr: ctx.Conn.LocalAddr().String(), events.RemoteAddr: ctx.Conn.RemoteAddr().String(), }) h.Warnf("Port forwarding request denied: %v.", systemErrorMessage) return trace.AccessDenied(userErrorMessage) } return nil }
go
func (h *AuthHandlers) CheckPortForward(addr string, ctx *ServerContext) error { if ok := ctx.Identity.RoleSet.CanPortForward(); !ok { systemErrorMessage := fmt.Sprintf("port forwarding not allowed by role set: %v", ctx.Identity.RoleSet) userErrorMessage := "port forwarding not allowed" // emit port forward failure event h.AuditLog.EmitAuditEvent(events.PortForwardFailure, events.EventFields{ events.PortForwardAddr: addr, events.PortForwardSuccess: false, events.PortForwardErr: systemErrorMessage, events.EventLogin: ctx.Identity.Login, events.EventUser: ctx.Identity.TeleportUser, events.LocalAddr: ctx.Conn.LocalAddr().String(), events.RemoteAddr: ctx.Conn.RemoteAddr().String(), }) h.Warnf("Port forwarding request denied: %v.", systemErrorMessage) return trace.AccessDenied(userErrorMessage) } return nil }
[ "func", "(", "h", "*", "AuthHandlers", ")", "CheckPortForward", "(", "addr", "string", ",", "ctx", "*", "ServerContext", ")", "error", "{", "if", "ok", ":=", "ctx", ".", "Identity", ".", "RoleSet", ".", "CanPortForward", "(", ")", ";", "!", "ok", "{", "systemErrorMessage", ":=", "fmt", ".", "Sprintf", "(", "\"port forwarding not allowed by role set: %v\"", ",", "ctx", ".", "Identity", ".", "RoleSet", ")", "\n", "userErrorMessage", ":=", "\"port forwarding not allowed\"", "\n", "h", ".", "AuditLog", ".", "EmitAuditEvent", "(", "events", ".", "PortForwardFailure", ",", "events", ".", "EventFields", "{", "events", ".", "PortForwardAddr", ":", "addr", ",", "events", ".", "PortForwardSuccess", ":", "false", ",", "events", ".", "PortForwardErr", ":", "systemErrorMessage", ",", "events", ".", "EventLogin", ":", "ctx", ".", "Identity", ".", "Login", ",", "events", ".", "EventUser", ":", "ctx", ".", "Identity", ".", "TeleportUser", ",", "events", ".", "LocalAddr", ":", "ctx", ".", "Conn", ".", "LocalAddr", "(", ")", ".", "String", "(", ")", ",", "events", ".", "RemoteAddr", ":", "ctx", ".", "Conn", ".", "RemoteAddr", "(", ")", ".", "String", "(", ")", ",", "}", ")", "\n", "h", ".", "Warnf", "(", "\"Port forwarding request denied: %v.\"", ",", "systemErrorMessage", ")", "\n", "return", "trace", ".", "AccessDenied", "(", "userErrorMessage", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// CheckPortForward checks if port forwarding is allowed for the users RoleSet.
[ "CheckPortForward", "checks", "if", "port", "forwarding", "is", "allowed", "for", "the", "users", "RoleSet", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/authhandlers.go#L104-L125
train
gravitational/teleport
lib/srv/authhandlers.go
HostKeyAuth
func (h *AuthHandlers) HostKeyAuth(addr string, remote net.Addr, key ssh.PublicKey) error { fingerprint := fmt.Sprintf("%v %v", key.Type(), sshutils.Fingerprint(key)) // update entry to include a fingerprint of the key so admins can track down // the key causing problems h.Entry = log.WithFields(log.Fields{ trace.Component: h.Component, trace.ComponentFields: log.Fields{ "remote": remote.String(), "fingerprint": fingerprint, }, }) // Check if the given host key was signed by a Teleport certificate // authority (CA) or fallback to host key checking if it's allowed. certChecker := utils.CertChecker{ CertChecker: ssh.CertChecker{ IsHostAuthority: h.IsHostAuthority, HostKeyFallback: h.hostKeyCallback, }, } err := certChecker.CheckHostKey(addr, remote, key) if err != nil { return trace.Wrap(err) } return nil }
go
func (h *AuthHandlers) HostKeyAuth(addr string, remote net.Addr, key ssh.PublicKey) error { fingerprint := fmt.Sprintf("%v %v", key.Type(), sshutils.Fingerprint(key)) // update entry to include a fingerprint of the key so admins can track down // the key causing problems h.Entry = log.WithFields(log.Fields{ trace.Component: h.Component, trace.ComponentFields: log.Fields{ "remote": remote.String(), "fingerprint": fingerprint, }, }) // Check if the given host key was signed by a Teleport certificate // authority (CA) or fallback to host key checking if it's allowed. certChecker := utils.CertChecker{ CertChecker: ssh.CertChecker{ IsHostAuthority: h.IsHostAuthority, HostKeyFallback: h.hostKeyCallback, }, } err := certChecker.CheckHostKey(addr, remote, key) if err != nil { return trace.Wrap(err) } return nil }
[ "func", "(", "h", "*", "AuthHandlers", ")", "HostKeyAuth", "(", "addr", "string", ",", "remote", "net", ".", "Addr", ",", "key", "ssh", ".", "PublicKey", ")", "error", "{", "fingerprint", ":=", "fmt", ".", "Sprintf", "(", "\"%v %v\"", ",", "key", ".", "Type", "(", ")", ",", "sshutils", ".", "Fingerprint", "(", "key", ")", ")", "\n", "h", ".", "Entry", "=", "log", ".", "WithFields", "(", "log", ".", "Fields", "{", "trace", ".", "Component", ":", "h", ".", "Component", ",", "trace", ".", "ComponentFields", ":", "log", ".", "Fields", "{", "\"remote\"", ":", "remote", ".", "String", "(", ")", ",", "\"fingerprint\"", ":", "fingerprint", ",", "}", ",", "}", ")", "\n", "certChecker", ":=", "utils", ".", "CertChecker", "{", "CertChecker", ":", "ssh", ".", "CertChecker", "{", "IsHostAuthority", ":", "h", ".", "IsHostAuthority", ",", "HostKeyFallback", ":", "h", ".", "hostKeyCallback", ",", "}", ",", "}", "\n", "err", ":=", "certChecker", ".", "CheckHostKey", "(", "addr", ",", "remote", ",", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// HostKeyAuth implements host key verification and is called by the client // to validate the certificate presented by the target server. If the target // server presents a SSH certificate, we validate that it was Teleport that // generated the certificate. If the target server presents a public key, if // we are strictly checking keys, we reject the target server. If we are not // we take whatever.
[ "HostKeyAuth", "implements", "host", "key", "verification", "and", "is", "called", "by", "the", "client", "to", "validate", "the", "certificate", "presented", "by", "the", "target", "server", ".", "If", "the", "target", "server", "presents", "a", "SSH", "certificate", "we", "validate", "that", "it", "was", "Teleport", "that", "generated", "the", "certificate", ".", "If", "the", "target", "server", "presents", "a", "public", "key", "if", "we", "are", "strictly", "checking", "keys", "we", "reject", "the", "target", "server", ".", "If", "we", "are", "not", "we", "take", "whatever", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/authhandlers.go#L237-L263
train
gravitational/teleport
lib/srv/authhandlers.go
hostKeyCallback
func (h *AuthHandlers) hostKeyCallback(hostname string, remote net.Addr, key ssh.PublicKey) error { // If strict host key checking is enabled, reject host key fallback. clusterConfig, err := h.AccessPoint.GetClusterConfig() if err != nil { return trace.Wrap(err) } if clusterConfig.GetProxyChecksHostKeys() == services.HostKeyCheckYes { return trace.AccessDenied("remote host presented a public key, expected a host certificate") } // If strict host key checking is not enabled, log that Teleport trusted an // insecure key, but allow the request to go through. h.Warn("Insecure configuration! Strict host key checking disabled, allowing login without checking host key of type %v.", key.Type()) return nil }
go
func (h *AuthHandlers) hostKeyCallback(hostname string, remote net.Addr, key ssh.PublicKey) error { // If strict host key checking is enabled, reject host key fallback. clusterConfig, err := h.AccessPoint.GetClusterConfig() if err != nil { return trace.Wrap(err) } if clusterConfig.GetProxyChecksHostKeys() == services.HostKeyCheckYes { return trace.AccessDenied("remote host presented a public key, expected a host certificate") } // If strict host key checking is not enabled, log that Teleport trusted an // insecure key, but allow the request to go through. h.Warn("Insecure configuration! Strict host key checking disabled, allowing login without checking host key of type %v.", key.Type()) return nil }
[ "func", "(", "h", "*", "AuthHandlers", ")", "hostKeyCallback", "(", "hostname", "string", ",", "remote", "net", ".", "Addr", ",", "key", "ssh", ".", "PublicKey", ")", "error", "{", "clusterConfig", ",", "err", ":=", "h", ".", "AccessPoint", ".", "GetClusterConfig", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "clusterConfig", ".", "GetProxyChecksHostKeys", "(", ")", "==", "services", ".", "HostKeyCheckYes", "{", "return", "trace", ".", "AccessDenied", "(", "\"remote host presented a public key, expected a host certificate\"", ")", "\n", "}", "\n", "h", ".", "Warn", "(", "\"Insecure configuration! Strict host key checking disabled, allowing login without checking host key of type %v.\"", ",", "key", ".", "Type", "(", ")", ")", "\n", "return", "nil", "\n", "}" ]
// hostKeyCallback allows connections to hosts that present keys only if // strict host key checking is disabled.
[ "hostKeyCallback", "allows", "connections", "to", "hosts", "that", "present", "keys", "only", "if", "strict", "host", "key", "checking", "is", "disabled", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/authhandlers.go#L267-L281
train
gravitational/teleport
lib/srv/authhandlers.go
IsUserAuthority
func (h *AuthHandlers) IsUserAuthority(cert ssh.PublicKey) bool { if _, err := h.authorityForCert(services.UserCA, cert); err != nil { return false } return true }
go
func (h *AuthHandlers) IsUserAuthority(cert ssh.PublicKey) bool { if _, err := h.authorityForCert(services.UserCA, cert); err != nil { return false } return true }
[ "func", "(", "h", "*", "AuthHandlers", ")", "IsUserAuthority", "(", "cert", "ssh", ".", "PublicKey", ")", "bool", "{", "if", "_", ",", "err", ":=", "h", ".", "authorityForCert", "(", "services", ".", "UserCA", ",", "cert", ")", ";", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}" ]
// IsUserAuthority is called during checking the client key, to see if the // key used to sign the certificate was a Teleport CA.
[ "IsUserAuthority", "is", "called", "during", "checking", "the", "client", "key", "to", "see", "if", "the", "key", "used", "to", "sign", "the", "certificate", "was", "a", "Teleport", "CA", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/authhandlers.go#L285-L291
train
gravitational/teleport
lib/srv/authhandlers.go
IsHostAuthority
func (h *AuthHandlers) IsHostAuthority(cert ssh.PublicKey, address string) bool { if _, err := h.authorityForCert(services.HostCA, cert); err != nil { h.Entry.Debugf("Unable to find SSH host CA: %v.", err) return false } return true }
go
func (h *AuthHandlers) IsHostAuthority(cert ssh.PublicKey, address string) bool { if _, err := h.authorityForCert(services.HostCA, cert); err != nil { h.Entry.Debugf("Unable to find SSH host CA: %v.", err) return false } return true }
[ "func", "(", "h", "*", "AuthHandlers", ")", "IsHostAuthority", "(", "cert", "ssh", ".", "PublicKey", ",", "address", "string", ")", "bool", "{", "if", "_", ",", "err", ":=", "h", ".", "authorityForCert", "(", "services", ".", "HostCA", ",", "cert", ")", ";", "err", "!=", "nil", "{", "h", ".", "Entry", ".", "Debugf", "(", "\"Unable to find SSH host CA: %v.\"", ",", "err", ")", "\n", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}" ]
// IsHostAuthority is called when checking the host certificate a server // presents. It make sure that the key used to sign the host certificate was a // Teleport CA.
[ "IsHostAuthority", "is", "called", "when", "checking", "the", "host", "certificate", "a", "server", "presents", ".", "It", "make", "sure", "that", "the", "key", "used", "to", "sign", "the", "host", "certificate", "was", "a", "Teleport", "CA", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/authhandlers.go#L296-L302
train
gravitational/teleport
lib/srv/authhandlers.go
fetchRoleSet
func (h *AuthHandlers) fetchRoleSet(cert *ssh.Certificate, ca services.CertAuthority, teleportUser string, clusterName string) (services.RoleSet, error) { // for local users, go and check their individual permissions var roles services.RoleSet if clusterName == ca.GetClusterName() { u, err := h.AccessPoint.GetUser(teleportUser) if err != nil { return nil, trace.Wrap(err) } // Pass along the traits so we get the substituted roles for this user. roles, err = services.FetchRoles(u.GetRoles(), h.AccessPoint, u.GetTraits()) if err != nil { return nil, trace.Wrap(err) } } else { certRoles, err := extractRolesFromCert(cert) if err != nil { return nil, trace.AccessDenied("failed to parse certificate roles") } roleNames, err := ca.CombinedMapping().Map(certRoles) if err != nil { return nil, trace.AccessDenied("failed to map roles") } // pass the principals on the certificate along as the login traits // to the remote cluster. traits := map[string][]string{ teleport.TraitLogins: cert.ValidPrincipals, } roles, err = services.FetchRoles(roleNames, h.AccessPoint, traits) if err != nil { return nil, trace.Wrap(err) } } return roles, nil }
go
func (h *AuthHandlers) fetchRoleSet(cert *ssh.Certificate, ca services.CertAuthority, teleportUser string, clusterName string) (services.RoleSet, error) { // for local users, go and check their individual permissions var roles services.RoleSet if clusterName == ca.GetClusterName() { u, err := h.AccessPoint.GetUser(teleportUser) if err != nil { return nil, trace.Wrap(err) } // Pass along the traits so we get the substituted roles for this user. roles, err = services.FetchRoles(u.GetRoles(), h.AccessPoint, u.GetTraits()) if err != nil { return nil, trace.Wrap(err) } } else { certRoles, err := extractRolesFromCert(cert) if err != nil { return nil, trace.AccessDenied("failed to parse certificate roles") } roleNames, err := ca.CombinedMapping().Map(certRoles) if err != nil { return nil, trace.AccessDenied("failed to map roles") } // pass the principals on the certificate along as the login traits // to the remote cluster. traits := map[string][]string{ teleport.TraitLogins: cert.ValidPrincipals, } roles, err = services.FetchRoles(roleNames, h.AccessPoint, traits) if err != nil { return nil, trace.Wrap(err) } } return roles, nil }
[ "func", "(", "h", "*", "AuthHandlers", ")", "fetchRoleSet", "(", "cert", "*", "ssh", ".", "Certificate", ",", "ca", "services", ".", "CertAuthority", ",", "teleportUser", "string", ",", "clusterName", "string", ")", "(", "services", ".", "RoleSet", ",", "error", ")", "{", "var", "roles", "services", ".", "RoleSet", "\n", "if", "clusterName", "==", "ca", ".", "GetClusterName", "(", ")", "{", "u", ",", "err", ":=", "h", ".", "AccessPoint", ".", "GetUser", "(", "teleportUser", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "roles", ",", "err", "=", "services", ".", "FetchRoles", "(", "u", ".", "GetRoles", "(", ")", ",", "h", ".", "AccessPoint", ",", "u", ".", "GetTraits", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "}", "else", "{", "certRoles", ",", "err", ":=", "extractRolesFromCert", "(", "cert", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "AccessDenied", "(", "\"failed to parse certificate roles\"", ")", "\n", "}", "\n", "roleNames", ",", "err", ":=", "ca", ".", "CombinedMapping", "(", ")", ".", "Map", "(", "certRoles", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "AccessDenied", "(", "\"failed to map roles\"", ")", "\n", "}", "\n", "traits", ":=", "map", "[", "string", "]", "[", "]", "string", "{", "teleport", ".", "TraitLogins", ":", "cert", ".", "ValidPrincipals", ",", "}", "\n", "roles", ",", "err", "=", "services", ".", "FetchRoles", "(", "roleNames", ",", "h", ".", "AccessPoint", ",", "traits", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "}", "\n", "return", "roles", ",", "nil", "\n", "}" ]
// fetchRoleSet fetches the services.RoleSet assigned to a Teleport user.
[ "fetchRoleSet", "fetches", "the", "services", ".", "RoleSet", "assigned", "to", "a", "Teleport", "user", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/authhandlers.go#L347-L381
train
gravitational/teleport
lib/srv/authhandlers.go
authorityForCert
func (h *AuthHandlers) authorityForCert(caType services.CertAuthType, key ssh.PublicKey) (services.CertAuthority, error) { // get all certificate authorities for given type cas, err := h.AccessPoint.GetCertAuthorities(caType, false) if err != nil { h.Warnf("%v", trace.DebugReport(err)) return nil, trace.Wrap(err) } // find the one that signed our certificate var ca services.CertAuthority for i := range cas { checkers, err := cas[i].Checkers() if err != nil { h.Warnf("%v", err) return nil, trace.Wrap(err) } for _, checker := range checkers { // if we have a certificate, compare the certificate signing key against // the ca key. otherwise check the public key that was passed in. this is // due to the differences in how this function is called by the user and // host checkers. switch v := key.(type) { case *ssh.Certificate: if sshutils.KeysEqual(v.SignatureKey, checker) { ca = cas[i] break } default: if sshutils.KeysEqual(key, checker) { ca = cas[i] break } } } } // the certificate was signed by unknown authority if ca == nil { return nil, trace.AccessDenied("the certificate signed by untrusted CA") } return ca, nil }
go
func (h *AuthHandlers) authorityForCert(caType services.CertAuthType, key ssh.PublicKey) (services.CertAuthority, error) { // get all certificate authorities for given type cas, err := h.AccessPoint.GetCertAuthorities(caType, false) if err != nil { h.Warnf("%v", trace.DebugReport(err)) return nil, trace.Wrap(err) } // find the one that signed our certificate var ca services.CertAuthority for i := range cas { checkers, err := cas[i].Checkers() if err != nil { h.Warnf("%v", err) return nil, trace.Wrap(err) } for _, checker := range checkers { // if we have a certificate, compare the certificate signing key against // the ca key. otherwise check the public key that was passed in. this is // due to the differences in how this function is called by the user and // host checkers. switch v := key.(type) { case *ssh.Certificate: if sshutils.KeysEqual(v.SignatureKey, checker) { ca = cas[i] break } default: if sshutils.KeysEqual(key, checker) { ca = cas[i] break } } } } // the certificate was signed by unknown authority if ca == nil { return nil, trace.AccessDenied("the certificate signed by untrusted CA") } return ca, nil }
[ "func", "(", "h", "*", "AuthHandlers", ")", "authorityForCert", "(", "caType", "services", ".", "CertAuthType", ",", "key", "ssh", ".", "PublicKey", ")", "(", "services", ".", "CertAuthority", ",", "error", ")", "{", "cas", ",", "err", ":=", "h", ".", "AccessPoint", ".", "GetCertAuthorities", "(", "caType", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "h", ".", "Warnf", "(", "\"%v\"", ",", "trace", ".", "DebugReport", "(", "err", ")", ")", "\n", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "var", "ca", "services", ".", "CertAuthority", "\n", "for", "i", ":=", "range", "cas", "{", "checkers", ",", "err", ":=", "cas", "[", "i", "]", ".", "Checkers", "(", ")", "\n", "if", "err", "!=", "nil", "{", "h", ".", "Warnf", "(", "\"%v\"", ",", "err", ")", "\n", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "for", "_", ",", "checker", ":=", "range", "checkers", "{", "switch", "v", ":=", "key", ".", "(", "type", ")", "{", "case", "*", "ssh", ".", "Certificate", ":", "if", "sshutils", ".", "KeysEqual", "(", "v", ".", "SignatureKey", ",", "checker", ")", "{", "ca", "=", "cas", "[", "i", "]", "\n", "break", "\n", "}", "\n", "default", ":", "if", "sshutils", ".", "KeysEqual", "(", "key", ",", "checker", ")", "{", "ca", "=", "cas", "[", "i", "]", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "ca", "==", "nil", "{", "return", "nil", ",", "trace", ".", "AccessDenied", "(", "\"the certificate signed by untrusted CA\"", ")", "\n", "}", "\n", "return", "ca", ",", "nil", "\n", "}" ]
// authorityForCert checks if the certificate was signed by a Teleport // Certificate Authority and returns it.
[ "authorityForCert", "checks", "if", "the", "certificate", "was", "signed", "by", "a", "Teleport", "Certificate", "Authority", "and", "returns", "it", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/authhandlers.go#L385-L427
train
gravitational/teleport
lib/srv/authhandlers.go
isProxy
func (h *AuthHandlers) isProxy() bool { if h.Component == teleport.ComponentProxy { return true } return false }
go
func (h *AuthHandlers) isProxy() bool { if h.Component == teleport.ComponentProxy { return true } return false }
[ "func", "(", "h", "*", "AuthHandlers", ")", "isProxy", "(", ")", "bool", "{", "if", "h", ".", "Component", "==", "teleport", ".", "ComponentProxy", "{", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// isProxy returns true if it's a regular SSH proxy.
[ "isProxy", "returns", "true", "if", "it", "s", "a", "regular", "SSH", "proxy", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/authhandlers.go#L430-L435
train
gravitational/teleport
lib/srv/authhandlers.go
extractRolesFromCert
func extractRolesFromCert(cert *ssh.Certificate) ([]string, error) { data, ok := cert.Extensions[teleport.CertExtensionTeleportRoles] if !ok { // it's ok to not have any roles in the metadata return nil, nil } return services.UnmarshalCertRoles(data) }
go
func extractRolesFromCert(cert *ssh.Certificate) ([]string, error) { data, ok := cert.Extensions[teleport.CertExtensionTeleportRoles] if !ok { // it's ok to not have any roles in the metadata return nil, nil } return services.UnmarshalCertRoles(data) }
[ "func", "extractRolesFromCert", "(", "cert", "*", "ssh", ".", "Certificate", ")", "(", "[", "]", "string", ",", "error", ")", "{", "data", ",", "ok", ":=", "cert", ".", "Extensions", "[", "teleport", ".", "CertExtensionTeleportRoles", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "return", "services", ".", "UnmarshalCertRoles", "(", "data", ")", "\n", "}" ]
// extractRolesFromCert extracts roles from certificate metadata extensions.
[ "extractRolesFromCert", "extracts", "roles", "from", "certificate", "metadata", "extensions", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/authhandlers.go#L446-L453
train
gravitational/teleport
lib/web/sessions.go
GetUserClient
func (c *SessionContext) GetUserClient(site reversetunnel.RemoteSite) (auth.ClientI, error) { // get the name of the current cluster clt, err := c.GetClient() if err != nil { return nil, trace.Wrap(err) } cn, err := clt.GetClusterName() if err != nil { return nil, trace.Wrap(err) } // if we're trying to access the local cluster, pass back the local client. if cn.GetClusterName() == site.GetName() { return clt, nil } // look to see if we already have a connection to this cluster remoteClt, ok := c.getRemoteClient(site.GetName()) if !ok { rClt, rConn, err := c.newRemoteClient(site) if err != nil { return nil, trace.Wrap(err) } // add a closer for the underlying connection if rConn != nil { c.AddClosers(rConn) } // we'll save the remote client in our session context so we don't have to // build a new connection next time. all remote clients will be closed when // the session context is closed. c.addRemoteClient(site.GetName(), rClt) return rClt, nil } return remoteClt, nil }
go
func (c *SessionContext) GetUserClient(site reversetunnel.RemoteSite) (auth.ClientI, error) { // get the name of the current cluster clt, err := c.GetClient() if err != nil { return nil, trace.Wrap(err) } cn, err := clt.GetClusterName() if err != nil { return nil, trace.Wrap(err) } // if we're trying to access the local cluster, pass back the local client. if cn.GetClusterName() == site.GetName() { return clt, nil } // look to see if we already have a connection to this cluster remoteClt, ok := c.getRemoteClient(site.GetName()) if !ok { rClt, rConn, err := c.newRemoteClient(site) if err != nil { return nil, trace.Wrap(err) } // add a closer for the underlying connection if rConn != nil { c.AddClosers(rConn) } // we'll save the remote client in our session context so we don't have to // build a new connection next time. all remote clients will be closed when // the session context is closed. c.addRemoteClient(site.GetName(), rClt) return rClt, nil } return remoteClt, nil }
[ "func", "(", "c", "*", "SessionContext", ")", "GetUserClient", "(", "site", "reversetunnel", ".", "RemoteSite", ")", "(", "auth", ".", "ClientI", ",", "error", ")", "{", "clt", ",", "err", ":=", "c", ".", "GetClient", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "cn", ",", "err", ":=", "clt", ".", "GetClusterName", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "cn", ".", "GetClusterName", "(", ")", "==", "site", ".", "GetName", "(", ")", "{", "return", "clt", ",", "nil", "\n", "}", "\n", "remoteClt", ",", "ok", ":=", "c", ".", "getRemoteClient", "(", "site", ".", "GetName", "(", ")", ")", "\n", "if", "!", "ok", "{", "rClt", ",", "rConn", ",", "err", ":=", "c", ".", "newRemoteClient", "(", "site", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "rConn", "!=", "nil", "{", "c", ".", "AddClosers", "(", "rConn", ")", "\n", "}", "\n", "c", ".", "addRemoteClient", "(", "site", ".", "GetName", "(", ")", ",", "rClt", ")", "\n", "return", "rClt", ",", "nil", "\n", "}", "\n", "return", "remoteClt", ",", "nil", "\n", "}" ]
// GetUserClient will return an auth.ClientI with the role of the user at // the requested site. If the site is local a client with the users local role // is returned. If the site is remote a client with the users remote role is // returned.
[ "GetUserClient", "will", "return", "an", "auth", ".", "ClientI", "with", "the", "role", "of", "the", "user", "at", "the", "requested", "site", ".", "If", "the", "site", "is", "local", "a", "client", "with", "the", "users", "local", "role", "is", "returned", ".", "If", "the", "site", "is", "remote", "a", "client", "with", "the", "users", "remote", "role", "is", "returned", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/sessions.go#L116-L154
train
gravitational/teleport
lib/web/sessions.go
newRemoteClient
func (c *SessionContext) newRemoteClient(cluster reversetunnel.RemoteSite) (auth.ClientI, net.Conn, error) { clt, err := c.tryRemoteTLSClient(cluster) if err != nil { return nil, nil, trace.Wrap(err) } return clt, nil, nil }
go
func (c *SessionContext) newRemoteClient(cluster reversetunnel.RemoteSite) (auth.ClientI, net.Conn, error) { clt, err := c.tryRemoteTLSClient(cluster) if err != nil { return nil, nil, trace.Wrap(err) } return clt, nil, nil }
[ "func", "(", "c", "*", "SessionContext", ")", "newRemoteClient", "(", "cluster", "reversetunnel", ".", "RemoteSite", ")", "(", "auth", ".", "ClientI", ",", "net", ".", "Conn", ",", "error", ")", "{", "clt", ",", "err", ":=", "c", ".", "tryRemoteTLSClient", "(", "cluster", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "clt", ",", "nil", ",", "nil", "\n", "}" ]
// newRemoteClient returns a client to a remote cluster with the role of // the logged in user.
[ "newRemoteClient", "returns", "a", "client", "to", "a", "remote", "cluster", "with", "the", "role", "of", "the", "logged", "in", "user", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/sessions.go#L158-L164
train
gravitational/teleport
lib/web/sessions.go
clusterDialer
func clusterDialer(remoteCluster reversetunnel.RemoteSite) auth.DialContext { return func(in context.Context, network, _ string) (net.Conn, error) { return remoteCluster.DialAuthServer() } }
go
func clusterDialer(remoteCluster reversetunnel.RemoteSite) auth.DialContext { return func(in context.Context, network, _ string) (net.Conn, error) { return remoteCluster.DialAuthServer() } }
[ "func", "clusterDialer", "(", "remoteCluster", "reversetunnel", ".", "RemoteSite", ")", "auth", ".", "DialContext", "{", "return", "func", "(", "in", "context", ".", "Context", ",", "network", ",", "_", "string", ")", "(", "net", ".", "Conn", ",", "error", ")", "{", "return", "remoteCluster", ".", "DialAuthServer", "(", ")", "\n", "}", "\n", "}" ]
// clusterDialer returns DialContext function using cluster's dial function
[ "clusterDialer", "returns", "DialContext", "function", "using", "cluster", "s", "dial", "function" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/sessions.go#L167-L171
train
gravitational/teleport
lib/web/sessions.go
ClientTLSConfig
func (c *SessionContext) ClientTLSConfig(clusterName ...string) (*tls.Config, error) { var certPool *x509.CertPool if len(clusterName) == 0 { certAuthorities, err := c.parent.proxyClient.GetCertAuthorities(services.HostCA, false) if err != nil { return nil, trace.Wrap(err) } certPool, err = services.CertPoolFromCertAuthorities(certAuthorities) if err != nil { return nil, trace.Wrap(err) } } else { certAuthority, err := c.parent.proxyClient.GetCertAuthority(services.CertAuthID{ Type: services.HostCA, DomainName: clusterName[0], }, false) if err != nil { return nil, trace.Wrap(err) } certPool, err = services.CertPool(certAuthority) if err != nil { return nil, trace.Wrap(err) } } tlsConfig := utils.TLSConfig(c.parent.cipherSuites) tlsCert, err := tls.X509KeyPair(c.sess.GetTLSCert(), c.sess.GetPriv()) if err != nil { return nil, trace.Wrap(err, "failed to parse TLS cert and key") } tlsConfig.Certificates = []tls.Certificate{tlsCert} tlsConfig.RootCAs = certPool tlsConfig.ServerName = auth.EncodeClusterName(c.parent.clusterName) return tlsConfig, nil }
go
func (c *SessionContext) ClientTLSConfig(clusterName ...string) (*tls.Config, error) { var certPool *x509.CertPool if len(clusterName) == 0 { certAuthorities, err := c.parent.proxyClient.GetCertAuthorities(services.HostCA, false) if err != nil { return nil, trace.Wrap(err) } certPool, err = services.CertPoolFromCertAuthorities(certAuthorities) if err != nil { return nil, trace.Wrap(err) } } else { certAuthority, err := c.parent.proxyClient.GetCertAuthority(services.CertAuthID{ Type: services.HostCA, DomainName: clusterName[0], }, false) if err != nil { return nil, trace.Wrap(err) } certPool, err = services.CertPool(certAuthority) if err != nil { return nil, trace.Wrap(err) } } tlsConfig := utils.TLSConfig(c.parent.cipherSuites) tlsCert, err := tls.X509KeyPair(c.sess.GetTLSCert(), c.sess.GetPriv()) if err != nil { return nil, trace.Wrap(err, "failed to parse TLS cert and key") } tlsConfig.Certificates = []tls.Certificate{tlsCert} tlsConfig.RootCAs = certPool tlsConfig.ServerName = auth.EncodeClusterName(c.parent.clusterName) return tlsConfig, nil }
[ "func", "(", "c", "*", "SessionContext", ")", "ClientTLSConfig", "(", "clusterName", "...", "string", ")", "(", "*", "tls", ".", "Config", ",", "error", ")", "{", "var", "certPool", "*", "x509", ".", "CertPool", "\n", "if", "len", "(", "clusterName", ")", "==", "0", "{", "certAuthorities", ",", "err", ":=", "c", ".", "parent", ".", "proxyClient", ".", "GetCertAuthorities", "(", "services", ".", "HostCA", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "certPool", ",", "err", "=", "services", ".", "CertPoolFromCertAuthorities", "(", "certAuthorities", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "}", "else", "{", "certAuthority", ",", "err", ":=", "c", ".", "parent", ".", "proxyClient", ".", "GetCertAuthority", "(", "services", ".", "CertAuthID", "{", "Type", ":", "services", ".", "HostCA", ",", "DomainName", ":", "clusterName", "[", "0", "]", ",", "}", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "certPool", ",", "err", "=", "services", ".", "CertPool", "(", "certAuthority", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "}", "\n", "tlsConfig", ":=", "utils", ".", "TLSConfig", "(", "c", ".", "parent", ".", "cipherSuites", ")", "\n", "tlsCert", ",", "err", ":=", "tls", ".", "X509KeyPair", "(", "c", ".", "sess", ".", "GetTLSCert", "(", ")", ",", "c", ".", "sess", ".", "GetPriv", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ",", "\"failed to parse TLS cert and key\"", ")", "\n", "}", "\n", "tlsConfig", ".", "Certificates", "=", "[", "]", "tls", ".", "Certificate", "{", "tlsCert", "}", "\n", "tlsConfig", ".", "RootCAs", "=", "certPool", "\n", "tlsConfig", ".", "ServerName", "=", "auth", ".", "EncodeClusterName", "(", "c", ".", "parent", ".", "clusterName", ")", "\n", "return", "tlsConfig", ",", "nil", "\n", "}" ]
// ClientTLSConfig returns client TLS authentication associated // with the web session context
[ "ClientTLSConfig", "returns", "client", "TLS", "authentication", "associated", "with", "the", "web", "session", "context" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/sessions.go#L189-L223
train
gravitational/teleport
lib/web/sessions.go
ExtendWebSession
func (c *SessionContext) ExtendWebSession() (services.WebSession, error) { sess, err := c.clt.ExtendWebSession(c.user, c.sess.GetName()) if err != nil { return nil, trace.Wrap(err) } return sess, nil }
go
func (c *SessionContext) ExtendWebSession() (services.WebSession, error) { sess, err := c.clt.ExtendWebSession(c.user, c.sess.GetName()) if err != nil { return nil, trace.Wrap(err) } return sess, nil }
[ "func", "(", "c", "*", "SessionContext", ")", "ExtendWebSession", "(", ")", "(", "services", ".", "WebSession", ",", "error", ")", "{", "sess", ",", "err", ":=", "c", ".", "clt", ".", "ExtendWebSession", "(", "c", ".", "user", ",", "c", ".", "sess", ".", "GetName", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "sess", ",", "nil", "\n", "}" ]
// ExtendWebSession creates a new web session for this user // based on the previous session
[ "ExtendWebSession", "creates", "a", "new", "web", "session", "for", "this", "user", "based", "on", "the", "previous", "session" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/sessions.go#L245-L251
train
gravitational/teleport
lib/web/sessions.go
GetAgent
func (c *SessionContext) GetAgent() (agent.Agent, *ssh.Certificate, error) { pub, _, _, _, err := ssh.ParseAuthorizedKey(c.sess.GetPub()) if err != nil { return nil, nil, trace.Wrap(err) } cert, ok := pub.(*ssh.Certificate) if !ok { return nil, nil, trace.BadParameter("expected certificate, got %T", pub) } if len(cert.ValidPrincipals) == 0 { return nil, nil, trace.BadParameter("expected at least valid principal in certificate") } privateKey, err := ssh.ParseRawPrivateKey(c.sess.GetPriv()) if err != nil { return nil, nil, trace.Wrap(err, "failed to parse SSH private key") } keyring := agent.NewKeyring() err = keyring.Add(agent.AddedKey{ PrivateKey: privateKey, Certificate: cert, }) if err != nil { return nil, nil, trace.Wrap(err) } return keyring, cert, nil }
go
func (c *SessionContext) GetAgent() (agent.Agent, *ssh.Certificate, error) { pub, _, _, _, err := ssh.ParseAuthorizedKey(c.sess.GetPub()) if err != nil { return nil, nil, trace.Wrap(err) } cert, ok := pub.(*ssh.Certificate) if !ok { return nil, nil, trace.BadParameter("expected certificate, got %T", pub) } if len(cert.ValidPrincipals) == 0 { return nil, nil, trace.BadParameter("expected at least valid principal in certificate") } privateKey, err := ssh.ParseRawPrivateKey(c.sess.GetPriv()) if err != nil { return nil, nil, trace.Wrap(err, "failed to parse SSH private key") } keyring := agent.NewKeyring() err = keyring.Add(agent.AddedKey{ PrivateKey: privateKey, Certificate: cert, }) if err != nil { return nil, nil, trace.Wrap(err) } return keyring, cert, nil }
[ "func", "(", "c", "*", "SessionContext", ")", "GetAgent", "(", ")", "(", "agent", ".", "Agent", ",", "*", "ssh", ".", "Certificate", ",", "error", ")", "{", "pub", ",", "_", ",", "_", ",", "_", ",", "err", ":=", "ssh", ".", "ParseAuthorizedKey", "(", "c", ".", "sess", ".", "GetPub", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "cert", ",", "ok", ":=", "pub", ".", "(", "*", "ssh", ".", "Certificate", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "nil", ",", "trace", ".", "BadParameter", "(", "\"expected certificate, got %T\"", ",", "pub", ")", "\n", "}", "\n", "if", "len", "(", "cert", ".", "ValidPrincipals", ")", "==", "0", "{", "return", "nil", ",", "nil", ",", "trace", ".", "BadParameter", "(", "\"expected at least valid principal in certificate\"", ")", "\n", "}", "\n", "privateKey", ",", "err", ":=", "ssh", ".", "ParseRawPrivateKey", "(", "c", ".", "sess", ".", "GetPriv", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "trace", ".", "Wrap", "(", "err", ",", "\"failed to parse SSH private key\"", ")", "\n", "}", "\n", "keyring", ":=", "agent", ".", "NewKeyring", "(", ")", "\n", "err", "=", "keyring", ".", "Add", "(", "agent", ".", "AddedKey", "{", "PrivateKey", ":", "privateKey", ",", "Certificate", ":", "cert", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "keyring", ",", "cert", ",", "nil", "\n", "}" ]
// GetAgent returns agent that can be used to answer challenges // for the web to ssh connection as well as certificate
[ "GetAgent", "returns", "agent", "that", "can", "be", "used", "to", "answer", "challenges", "for", "the", "web", "to", "ssh", "connection", "as", "well", "as", "certificate" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/sessions.go#L255-L281
train
gravitational/teleport
lib/web/sessions.go
Close
func (c *SessionContext) Close() error { closers := c.TransferClosers() for _, closer := range closers { c.Debugf("Closing %v.", closer) closer.Close() } if c.clt != nil { return trace.Wrap(c.clt.Close()) } return nil }
go
func (c *SessionContext) Close() error { closers := c.TransferClosers() for _, closer := range closers { c.Debugf("Closing %v.", closer) closer.Close() } if c.clt != nil { return trace.Wrap(c.clt.Close()) } return nil }
[ "func", "(", "c", "*", "SessionContext", ")", "Close", "(", ")", "error", "{", "closers", ":=", "c", ".", "TransferClosers", "(", ")", "\n", "for", "_", ",", "closer", ":=", "range", "closers", "{", "c", ".", "Debugf", "(", "\"Closing %v.\"", ",", "closer", ")", "\n", "closer", ".", "Close", "(", ")", "\n", "}", "\n", "if", "c", ".", "clt", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "c", ".", "clt", ".", "Close", "(", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Close cleans up connections associated with requests
[ "Close", "cleans", "up", "connections", "associated", "with", "requests" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/sessions.go#L284-L294
train
gravitational/teleport
lib/web/sessions.go
newSessionCache
func newSessionCache(proxyClient auth.ClientI, servers []utils.NetAddr, cipherSuites []uint16) (*sessionCache, error) { clusterName, err := proxyClient.GetClusterName() if err != nil { return nil, trace.Wrap(err) } m, err := ttlmap.New(1024, ttlmap.CallOnExpire(closeContext)) if err != nil { return nil, trace.Wrap(err) } cache := &sessionCache{ clusterName: clusterName.GetClusterName(), proxyClient: proxyClient, contexts: m, authServers: servers, closer: utils.NewCloseBroadcaster(), cipherSuites: cipherSuites, } // periodically close expired and unused sessions go cache.expireSessions() return cache, nil }
go
func newSessionCache(proxyClient auth.ClientI, servers []utils.NetAddr, cipherSuites []uint16) (*sessionCache, error) { clusterName, err := proxyClient.GetClusterName() if err != nil { return nil, trace.Wrap(err) } m, err := ttlmap.New(1024, ttlmap.CallOnExpire(closeContext)) if err != nil { return nil, trace.Wrap(err) } cache := &sessionCache{ clusterName: clusterName.GetClusterName(), proxyClient: proxyClient, contexts: m, authServers: servers, closer: utils.NewCloseBroadcaster(), cipherSuites: cipherSuites, } // periodically close expired and unused sessions go cache.expireSessions() return cache, nil }
[ "func", "newSessionCache", "(", "proxyClient", "auth", ".", "ClientI", ",", "servers", "[", "]", "utils", ".", "NetAddr", ",", "cipherSuites", "[", "]", "uint16", ")", "(", "*", "sessionCache", ",", "error", ")", "{", "clusterName", ",", "err", ":=", "proxyClient", ".", "GetClusterName", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "m", ",", "err", ":=", "ttlmap", ".", "New", "(", "1024", ",", "ttlmap", ".", "CallOnExpire", "(", "closeContext", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "cache", ":=", "&", "sessionCache", "{", "clusterName", ":", "clusterName", ".", "GetClusterName", "(", ")", ",", "proxyClient", ":", "proxyClient", ",", "contexts", ":", "m", ",", "authServers", ":", "servers", ",", "closer", ":", "utils", ".", "NewCloseBroadcaster", "(", ")", ",", "cipherSuites", ":", "cipherSuites", ",", "}", "\n", "go", "cache", ".", "expireSessions", "(", ")", "\n", "return", "cache", ",", "nil", "\n", "}" ]
// newSessionCache returns new instance of the session cache
[ "newSessionCache", "returns", "new", "instance", "of", "the", "session", "cache" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/sessions.go#L297-L317
train
gravitational/teleport
lib/web/sessions.go
closeContext
func closeContext(key string, val interface{}) { go func() { log.Infof("[WEB] closing context %v", key) ctx, ok := val.(*SessionContext) if !ok { log.Warningf("warning, not valid value type %T", val) return } if err := ctx.Close(); err != nil { log.Infof("failed to close context: %v", err) } }() }
go
func closeContext(key string, val interface{}) { go func() { log.Infof("[WEB] closing context %v", key) ctx, ok := val.(*SessionContext) if !ok { log.Warningf("warning, not valid value type %T", val) return } if err := ctx.Close(); err != nil { log.Infof("failed to close context: %v", err) } }() }
[ "func", "closeContext", "(", "key", "string", ",", "val", "interface", "{", "}", ")", "{", "go", "func", "(", ")", "{", "log", ".", "Infof", "(", "\"[WEB] closing context %v\"", ",", "key", ")", "\n", "ctx", ",", "ok", ":=", "val", ".", "(", "*", "SessionContext", ")", "\n", "if", "!", "ok", "{", "log", ".", "Warningf", "(", "\"warning, not valid value type %T\"", ",", "val", ")", "\n", "return", "\n", "}", "\n", "if", "err", ":=", "ctx", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "log", ".", "Infof", "(", "\"failed to close context: %v\"", ",", "err", ")", "\n", "}", "\n", "}", "(", ")", "\n", "}" ]
// closeContext is called when session context expires from // cache and will clean up connections
[ "closeContext", "is", "called", "when", "session", "context", "expires", "from", "cache", "and", "will", "clean", "up", "connections" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/sessions.go#L341-L353
train
gravitational/teleport
lib/auth/github.go
populateGithubClaims
func populateGithubClaims(client githubAPIClientI) (*services.GithubClaims, error) { // find out the username user, err := client.getUser() if err != nil { return nil, trace.Wrap(err, "failed to query Github user info") } // build team memberships teams, err := client.getTeams() if err != nil { return nil, trace.Wrap(err, "failed to query Github user teams") } log.Debugf("Retrieved %v teams for GitHub user %v.", len(teams), user.Login) orgToTeams := make(map[string][]string) for _, team := range teams { orgToTeams[team.Org.Login] = append( orgToTeams[team.Org.Login], team.Slug) } if len(orgToTeams) == 0 { return nil, trace.AccessDenied( "list of user teams is empty, did you grant access?") } claims := &services.GithubClaims{ Username: user.Login, OrganizationToTeams: orgToTeams, } log.WithFields(logrus.Fields{trace.Component: "github"}).Debugf( "Claims: %#v.", claims) return claims, nil }
go
func populateGithubClaims(client githubAPIClientI) (*services.GithubClaims, error) { // find out the username user, err := client.getUser() if err != nil { return nil, trace.Wrap(err, "failed to query Github user info") } // build team memberships teams, err := client.getTeams() if err != nil { return nil, trace.Wrap(err, "failed to query Github user teams") } log.Debugf("Retrieved %v teams for GitHub user %v.", len(teams), user.Login) orgToTeams := make(map[string][]string) for _, team := range teams { orgToTeams[team.Org.Login] = append( orgToTeams[team.Org.Login], team.Slug) } if len(orgToTeams) == 0 { return nil, trace.AccessDenied( "list of user teams is empty, did you grant access?") } claims := &services.GithubClaims{ Username: user.Login, OrganizationToTeams: orgToTeams, } log.WithFields(logrus.Fields{trace.Component: "github"}).Debugf( "Claims: %#v.", claims) return claims, nil }
[ "func", "populateGithubClaims", "(", "client", "githubAPIClientI", ")", "(", "*", "services", ".", "GithubClaims", ",", "error", ")", "{", "user", ",", "err", ":=", "client", ".", "getUser", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ",", "\"failed to query Github user info\"", ")", "\n", "}", "\n", "teams", ",", "err", ":=", "client", ".", "getTeams", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ",", "\"failed to query Github user teams\"", ")", "\n", "}", "\n", "log", ".", "Debugf", "(", "\"Retrieved %v teams for GitHub user %v.\"", ",", "len", "(", "teams", ")", ",", "user", ".", "Login", ")", "\n", "orgToTeams", ":=", "make", "(", "map", "[", "string", "]", "[", "]", "string", ")", "\n", "for", "_", ",", "team", ":=", "range", "teams", "{", "orgToTeams", "[", "team", ".", "Org", ".", "Login", "]", "=", "append", "(", "orgToTeams", "[", "team", ".", "Org", ".", "Login", "]", ",", "team", ".", "Slug", ")", "\n", "}", "\n", "if", "len", "(", "orgToTeams", ")", "==", "0", "{", "return", "nil", ",", "trace", ".", "AccessDenied", "(", "\"list of user teams is empty, did you grant access?\"", ")", "\n", "}", "\n", "claims", ":=", "&", "services", ".", "GithubClaims", "{", "Username", ":", "user", ".", "Login", ",", "OrganizationToTeams", ":", "orgToTeams", ",", "}", "\n", "log", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "trace", ".", "Component", ":", "\"github\"", "}", ")", ".", "Debugf", "(", "\"Claims: %#v.\"", ",", "claims", ")", "\n", "return", "claims", ",", "nil", "\n", "}" ]
// populateGithubClaims retrieves information about user and its team // memberships by calling Github API using the access token
[ "populateGithubClaims", "retrieves", "information", "about", "user", "and", "its", "team", "memberships", "by", "calling", "Github", "API", "using", "the", "access", "token" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/github.go#L366-L395
train
gravitational/teleport
lib/auth/github.go
getUser
func (c *githubAPIClient) getUser() (*userResponse, error) { // Ignore pagination links, we should never get more than a single user here. bytes, _, err := c.get("/user") if err != nil { return nil, trace.Wrap(err) } var user userResponse err = json.Unmarshal(bytes, &user) if err != nil { return nil, trace.Wrap(err) } return &user, nil }
go
func (c *githubAPIClient) getUser() (*userResponse, error) { // Ignore pagination links, we should never get more than a single user here. bytes, _, err := c.get("/user") if err != nil { return nil, trace.Wrap(err) } var user userResponse err = json.Unmarshal(bytes, &user) if err != nil { return nil, trace.Wrap(err) } return &user, nil }
[ "func", "(", "c", "*", "githubAPIClient", ")", "getUser", "(", ")", "(", "*", "userResponse", ",", "error", ")", "{", "bytes", ",", "_", ",", "err", ":=", "c", ".", "get", "(", "\"/user\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "var", "user", "userResponse", "\n", "err", "=", "json", ".", "Unmarshal", "(", "bytes", ",", "&", "user", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "&", "user", ",", "nil", "\n", "}" ]
// getEmails retrieves a list of emails for authenticated user
[ "getEmails", "retrieves", "a", "list", "of", "emails", "for", "authenticated", "user" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/github.go#L450-L462
train
gravitational/teleport
lib/auth/github.go
getTeams
func (c *githubAPIClient) getTeams() ([]teamResponse, error) { var result []teamResponse bytes, nextPage, err := c.get("/user/teams") if err != nil { return nil, trace.Wrap(err) } // Extract the first page of results and append them to the full result set. var teams []teamResponse err = json.Unmarshal(bytes, &teams) if err != nil { return nil, trace.Wrap(err) } result = append(result, teams...) // If the response returned a next page link, continue following the next // page links until all teams have been retrieved. var count int for nextPage != "" { // To prevent this from looping forever, don't fetch more than a set number // of pages, print an error when it does happen, and return the results up // to that point. if count > MaxPages { warningMessage := "Truncating list of teams used to populate claims: " + "hit maximum number pages that can be fetched from GitHub." // Print warning to Teleport logs as well as the Audit Log. log.Warnf(warningMessage) c.authServer.EmitAuditEvent(events.UserSSOLoginFailure, events.EventFields{ events.LoginMethod: events.LoginMethodGithub, events.AuthAttemptMessage: warningMessage, }) return result, nil } u, err := url.Parse(nextPage) if err != nil { return nil, trace.Wrap(err) } bytes, nextPage, err = c.get(u.RequestURI()) if err != nil { return nil, trace.Wrap(err) } err = json.Unmarshal(bytes, &teams) if err != nil { return nil, trace.Wrap(err) } // Append this page of teams to full result set. result = append(result, teams...) count = count + 1 } return result, nil }
go
func (c *githubAPIClient) getTeams() ([]teamResponse, error) { var result []teamResponse bytes, nextPage, err := c.get("/user/teams") if err != nil { return nil, trace.Wrap(err) } // Extract the first page of results and append them to the full result set. var teams []teamResponse err = json.Unmarshal(bytes, &teams) if err != nil { return nil, trace.Wrap(err) } result = append(result, teams...) // If the response returned a next page link, continue following the next // page links until all teams have been retrieved. var count int for nextPage != "" { // To prevent this from looping forever, don't fetch more than a set number // of pages, print an error when it does happen, and return the results up // to that point. if count > MaxPages { warningMessage := "Truncating list of teams used to populate claims: " + "hit maximum number pages that can be fetched from GitHub." // Print warning to Teleport logs as well as the Audit Log. log.Warnf(warningMessage) c.authServer.EmitAuditEvent(events.UserSSOLoginFailure, events.EventFields{ events.LoginMethod: events.LoginMethodGithub, events.AuthAttemptMessage: warningMessage, }) return result, nil } u, err := url.Parse(nextPage) if err != nil { return nil, trace.Wrap(err) } bytes, nextPage, err = c.get(u.RequestURI()) if err != nil { return nil, trace.Wrap(err) } err = json.Unmarshal(bytes, &teams) if err != nil { return nil, trace.Wrap(err) } // Append this page of teams to full result set. result = append(result, teams...) count = count + 1 } return result, nil }
[ "func", "(", "c", "*", "githubAPIClient", ")", "getTeams", "(", ")", "(", "[", "]", "teamResponse", ",", "error", ")", "{", "var", "result", "[", "]", "teamResponse", "\n", "bytes", ",", "nextPage", ",", "err", ":=", "c", ".", "get", "(", "\"/user/teams\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "var", "teams", "[", "]", "teamResponse", "\n", "err", "=", "json", ".", "Unmarshal", "(", "bytes", ",", "&", "teams", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "result", "=", "append", "(", "result", ",", "teams", "...", ")", "\n", "var", "count", "int", "\n", "for", "nextPage", "!=", "\"\"", "{", "if", "count", ">", "MaxPages", "{", "warningMessage", ":=", "\"Truncating list of teams used to populate claims: \"", "+", "\"hit maximum number pages that can be fetched from GitHub.\"", "\n", "log", ".", "Warnf", "(", "warningMessage", ")", "\n", "c", ".", "authServer", ".", "EmitAuditEvent", "(", "events", ".", "UserSSOLoginFailure", ",", "events", ".", "EventFields", "{", "events", ".", "LoginMethod", ":", "events", ".", "LoginMethodGithub", ",", "events", ".", "AuthAttemptMessage", ":", "warningMessage", ",", "}", ")", "\n", "return", "result", ",", "nil", "\n", "}", "\n", "u", ",", "err", ":=", "url", ".", "Parse", "(", "nextPage", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "bytes", ",", "nextPage", ",", "err", "=", "c", ".", "get", "(", "u", ".", "RequestURI", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "bytes", ",", "&", "teams", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "result", "=", "append", "(", "result", ",", "teams", "...", ")", "\n", "count", "=", "count", "+", "1", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// getTeams retrieves a list of teams authenticated user belongs to.
[ "getTeams", "retrieves", "a", "list", "of", "teams", "authenticated", "user", "belongs", "to", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/github.go#L481-L540
train
gravitational/teleport
lib/auth/github.go
get
func (c *githubAPIClient) get(url string) ([]byte, string, error) { request, err := http.NewRequest("GET", fmt.Sprintf("%v%v", GithubAPIURL, url), nil) if err != nil { return nil, "", trace.Wrap(err) } request.Header.Set("Authorization", fmt.Sprintf("token %v", c.token)) response, err := http.DefaultClient.Do(request) if err != nil { return nil, "", trace.Wrap(err) } defer response.Body.Close() bytes, err := ioutil.ReadAll(response.Body) if err != nil { return nil, "", trace.Wrap(err) } if response.StatusCode != 200 { return nil, "", trace.AccessDenied("bad response: %v %v", response.StatusCode, string(bytes)) } // Parse web links header to extract any pagination links. This is used to // return the next link which can be used in a loop to pull back all data. wls := utils.ParseWebLinks(response) return bytes, wls.NextPage, nil }
go
func (c *githubAPIClient) get(url string) ([]byte, string, error) { request, err := http.NewRequest("GET", fmt.Sprintf("%v%v", GithubAPIURL, url), nil) if err != nil { return nil, "", trace.Wrap(err) } request.Header.Set("Authorization", fmt.Sprintf("token %v", c.token)) response, err := http.DefaultClient.Do(request) if err != nil { return nil, "", trace.Wrap(err) } defer response.Body.Close() bytes, err := ioutil.ReadAll(response.Body) if err != nil { return nil, "", trace.Wrap(err) } if response.StatusCode != 200 { return nil, "", trace.AccessDenied("bad response: %v %v", response.StatusCode, string(bytes)) } // Parse web links header to extract any pagination links. This is used to // return the next link which can be used in a loop to pull back all data. wls := utils.ParseWebLinks(response) return bytes, wls.NextPage, nil }
[ "func", "(", "c", "*", "githubAPIClient", ")", "get", "(", "url", "string", ")", "(", "[", "]", "byte", ",", "string", ",", "error", ")", "{", "request", ",", "err", ":=", "http", ".", "NewRequest", "(", "\"GET\"", ",", "fmt", ".", "Sprintf", "(", "\"%v%v\"", ",", "GithubAPIURL", ",", "url", ")", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "\"\"", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "request", ".", "Header", ".", "Set", "(", "\"Authorization\"", ",", "fmt", ".", "Sprintf", "(", "\"token %v\"", ",", "c", ".", "token", ")", ")", "\n", "response", ",", "err", ":=", "http", ".", "DefaultClient", ".", "Do", "(", "request", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "\"\"", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "defer", "response", ".", "Body", ".", "Close", "(", ")", "\n", "bytes", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "response", ".", "Body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "\"\"", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "response", ".", "StatusCode", "!=", "200", "{", "return", "nil", ",", "\"\"", ",", "trace", ".", "AccessDenied", "(", "\"bad response: %v %v\"", ",", "response", ".", "StatusCode", ",", "string", "(", "bytes", ")", ")", "\n", "}", "\n", "wls", ":=", "utils", ".", "ParseWebLinks", "(", "response", ")", "\n", "return", "bytes", ",", "wls", ".", "NextPage", ",", "nil", "\n", "}" ]
// get makes a GET request to the provided URL using the client's token for auth
[ "get", "makes", "a", "GET", "request", "to", "the", "provided", "URL", "using", "the", "client", "s", "token", "for", "auth" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/github.go#L543-L568
train
gravitational/teleport
lib/srv/forward/sshserver.go
CheckDefaults
func (s *ServerConfig) CheckDefaults() error { if s.AuthClient == nil { return trace.BadParameter("auth client required") } if s.DataDir == "" { return trace.BadParameter("missing parameter DataDir") } if s.UserAgent == nil { return trace.BadParameter("user agent required to connect to remote host") } if s.TargetConn == nil { return trace.BadParameter("connection to target connection required") } if s.SrcAddr == nil { return trace.BadParameter("source address required to identify client") } if s.DstAddr == nil { return trace.BadParameter("destination address required to connect to remote host") } if s.HostCertificate == nil { return trace.BadParameter("host certificate required to act on behalf of remote host") } if s.Clock == nil { s.Clock = clockwork.NewRealClock() } return nil }
go
func (s *ServerConfig) CheckDefaults() error { if s.AuthClient == nil { return trace.BadParameter("auth client required") } if s.DataDir == "" { return trace.BadParameter("missing parameter DataDir") } if s.UserAgent == nil { return trace.BadParameter("user agent required to connect to remote host") } if s.TargetConn == nil { return trace.BadParameter("connection to target connection required") } if s.SrcAddr == nil { return trace.BadParameter("source address required to identify client") } if s.DstAddr == nil { return trace.BadParameter("destination address required to connect to remote host") } if s.HostCertificate == nil { return trace.BadParameter("host certificate required to act on behalf of remote host") } if s.Clock == nil { s.Clock = clockwork.NewRealClock() } return nil }
[ "func", "(", "s", "*", "ServerConfig", ")", "CheckDefaults", "(", ")", "error", "{", "if", "s", ".", "AuthClient", "==", "nil", "{", "return", "trace", ".", "BadParameter", "(", "\"auth client required\"", ")", "\n", "}", "\n", "if", "s", ".", "DataDir", "==", "\"\"", "{", "return", "trace", ".", "BadParameter", "(", "\"missing parameter DataDir\"", ")", "\n", "}", "\n", "if", "s", ".", "UserAgent", "==", "nil", "{", "return", "trace", ".", "BadParameter", "(", "\"user agent required to connect to remote host\"", ")", "\n", "}", "\n", "if", "s", ".", "TargetConn", "==", "nil", "{", "return", "trace", ".", "BadParameter", "(", "\"connection to target connection required\"", ")", "\n", "}", "\n", "if", "s", ".", "SrcAddr", "==", "nil", "{", "return", "trace", ".", "BadParameter", "(", "\"source address required to identify client\"", ")", "\n", "}", "\n", "if", "s", ".", "DstAddr", "==", "nil", "{", "return", "trace", ".", "BadParameter", "(", "\"destination address required to connect to remote host\"", ")", "\n", "}", "\n", "if", "s", ".", "HostCertificate", "==", "nil", "{", "return", "trace", ".", "BadParameter", "(", "\"host certificate required to act on behalf of remote host\"", ")", "\n", "}", "\n", "if", "s", ".", "Clock", "==", "nil", "{", "s", ".", "Clock", "=", "clockwork", ".", "NewRealClock", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// CheckDefaults makes sure all required parameters are passed in.
[ "CheckDefaults", "makes", "sure", "all", "required", "parameters", "are", "passed", "in", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/forward/sshserver.go#L162-L189
train
gravitational/teleport
lib/srv/forward/sshserver.go
New
func New(c ServerConfig) (*Server, error) { // Check and make sure we everything we need to build a forwarding node. err := c.CheckDefaults() if err != nil { return nil, trace.Wrap(err) } // Build a pipe connection to hook up the client and the server. we save both // here and will pass them along to the context when we create it so they // can be closed by the context. serverConn, clientConn := utils.DualPipeNetConn(c.SrcAddr, c.DstAddr) if err != nil { return nil, trace.Wrap(err) } s := &Server{ log: logrus.WithFields(logrus.Fields{ trace.Component: teleport.ComponentForwardingNode, trace.ComponentFields: map[string]string{ "src-addr": c.SrcAddr.String(), "dst-addr": c.DstAddr.String(), }, }), id: uuid.New(), targetConn: c.TargetConn, serverConn: utils.NewTrackingConn(serverConn), clientConn: clientConn, userAgent: c.UserAgent, hostCertificate: c.HostCertificate, authClient: c.AuthClient, auditLog: c.AuthClient, authService: c.AuthClient, sessionServer: c.AuthClient, dataDir: c.DataDir, clock: c.Clock, } // Set the ciphers, KEX, and MACs that the in-memory server will send to the // client in its SSH_MSG_KEXINIT. s.ciphers = c.Ciphers s.kexAlgorithms = c.KEXAlgorithms s.macAlgorithms = c.MACAlgorithms s.sessionRegistry, err = srv.NewSessionRegistry(s) if err != nil { return nil, trace.Wrap(err) } // Common auth handlers. s.authHandlers = &srv.AuthHandlers{ Entry: logrus.WithFields(logrus.Fields{ trace.Component: teleport.ComponentForwardingNode, trace.ComponentFields: logrus.Fields{}, }), Server: s, Component: teleport.ComponentForwardingNode, AuditLog: c.AuthClient, AccessPoint: c.AuthClient, } // Common term handlers. s.termHandlers = &srv.TermHandlers{ SessionRegistry: s.sessionRegistry, } // Create a close context that is used internally to signal when the server // is closing and for any blocking goroutines to unblock. s.closeContext, s.closeCancel = context.WithCancel(context.Background()) return s, nil }
go
func New(c ServerConfig) (*Server, error) { // Check and make sure we everything we need to build a forwarding node. err := c.CheckDefaults() if err != nil { return nil, trace.Wrap(err) } // Build a pipe connection to hook up the client and the server. we save both // here and will pass them along to the context when we create it so they // can be closed by the context. serverConn, clientConn := utils.DualPipeNetConn(c.SrcAddr, c.DstAddr) if err != nil { return nil, trace.Wrap(err) } s := &Server{ log: logrus.WithFields(logrus.Fields{ trace.Component: teleport.ComponentForwardingNode, trace.ComponentFields: map[string]string{ "src-addr": c.SrcAddr.String(), "dst-addr": c.DstAddr.String(), }, }), id: uuid.New(), targetConn: c.TargetConn, serverConn: utils.NewTrackingConn(serverConn), clientConn: clientConn, userAgent: c.UserAgent, hostCertificate: c.HostCertificate, authClient: c.AuthClient, auditLog: c.AuthClient, authService: c.AuthClient, sessionServer: c.AuthClient, dataDir: c.DataDir, clock: c.Clock, } // Set the ciphers, KEX, and MACs that the in-memory server will send to the // client in its SSH_MSG_KEXINIT. s.ciphers = c.Ciphers s.kexAlgorithms = c.KEXAlgorithms s.macAlgorithms = c.MACAlgorithms s.sessionRegistry, err = srv.NewSessionRegistry(s) if err != nil { return nil, trace.Wrap(err) } // Common auth handlers. s.authHandlers = &srv.AuthHandlers{ Entry: logrus.WithFields(logrus.Fields{ trace.Component: teleport.ComponentForwardingNode, trace.ComponentFields: logrus.Fields{}, }), Server: s, Component: teleport.ComponentForwardingNode, AuditLog: c.AuthClient, AccessPoint: c.AuthClient, } // Common term handlers. s.termHandlers = &srv.TermHandlers{ SessionRegistry: s.sessionRegistry, } // Create a close context that is used internally to signal when the server // is closing and for any blocking goroutines to unblock. s.closeContext, s.closeCancel = context.WithCancel(context.Background()) return s, nil }
[ "func", "New", "(", "c", "ServerConfig", ")", "(", "*", "Server", ",", "error", ")", "{", "err", ":=", "c", ".", "CheckDefaults", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "serverConn", ",", "clientConn", ":=", "utils", ".", "DualPipeNetConn", "(", "c", ".", "SrcAddr", ",", "c", ".", "DstAddr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "s", ":=", "&", "Server", "{", "log", ":", "logrus", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "trace", ".", "Component", ":", "teleport", ".", "ComponentForwardingNode", ",", "trace", ".", "ComponentFields", ":", "map", "[", "string", "]", "string", "{", "\"src-addr\"", ":", "c", ".", "SrcAddr", ".", "String", "(", ")", ",", "\"dst-addr\"", ":", "c", ".", "DstAddr", ".", "String", "(", ")", ",", "}", ",", "}", ")", ",", "id", ":", "uuid", ".", "New", "(", ")", ",", "targetConn", ":", "c", ".", "TargetConn", ",", "serverConn", ":", "utils", ".", "NewTrackingConn", "(", "serverConn", ")", ",", "clientConn", ":", "clientConn", ",", "userAgent", ":", "c", ".", "UserAgent", ",", "hostCertificate", ":", "c", ".", "HostCertificate", ",", "authClient", ":", "c", ".", "AuthClient", ",", "auditLog", ":", "c", ".", "AuthClient", ",", "authService", ":", "c", ".", "AuthClient", ",", "sessionServer", ":", "c", ".", "AuthClient", ",", "dataDir", ":", "c", ".", "DataDir", ",", "clock", ":", "c", ".", "Clock", ",", "}", "\n", "s", ".", "ciphers", "=", "c", ".", "Ciphers", "\n", "s", ".", "kexAlgorithms", "=", "c", ".", "KEXAlgorithms", "\n", "s", ".", "macAlgorithms", "=", "c", ".", "MACAlgorithms", "\n", "s", ".", "sessionRegistry", ",", "err", "=", "srv", ".", "NewSessionRegistry", "(", "s", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "s", ".", "authHandlers", "=", "&", "srv", ".", "AuthHandlers", "{", "Entry", ":", "logrus", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "trace", ".", "Component", ":", "teleport", ".", "ComponentForwardingNode", ",", "trace", ".", "ComponentFields", ":", "logrus", ".", "Fields", "{", "}", ",", "}", ")", ",", "Server", ":", "s", ",", "Component", ":", "teleport", ".", "ComponentForwardingNode", ",", "AuditLog", ":", "c", ".", "AuthClient", ",", "AccessPoint", ":", "c", ".", "AuthClient", ",", "}", "\n", "s", ".", "termHandlers", "=", "&", "srv", ".", "TermHandlers", "{", "SessionRegistry", ":", "s", ".", "sessionRegistry", ",", "}", "\n", "s", ".", "closeContext", ",", "s", ".", "closeCancel", "=", "context", ".", "WithCancel", "(", "context", ".", "Background", "(", ")", ")", "\n", "return", "s", ",", "nil", "\n", "}" ]
// New creates a new unstarted Server.
[ "New", "creates", "a", "new", "unstarted", "Server", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/forward/sshserver.go#L192-L262
train
gravitational/teleport
lib/srv/forward/sshserver.go
EmitAuditEvent
func (s *Server) EmitAuditEvent(event events.Event, fields events.EventFields) { auditLog := s.GetAuditLog() if auditLog != nil { if err := auditLog.EmitAuditEvent(event, fields); err != nil { s.log.Error(err) } } else { s.log.Warn("SSH server has no audit log") } }
go
func (s *Server) EmitAuditEvent(event events.Event, fields events.EventFields) { auditLog := s.GetAuditLog() if auditLog != nil { if err := auditLog.EmitAuditEvent(event, fields); err != nil { s.log.Error(err) } } else { s.log.Warn("SSH server has no audit log") } }
[ "func", "(", "s", "*", "Server", ")", "EmitAuditEvent", "(", "event", "events", ".", "Event", ",", "fields", "events", ".", "EventFields", ")", "{", "auditLog", ":=", "s", ".", "GetAuditLog", "(", ")", "\n", "if", "auditLog", "!=", "nil", "{", "if", "err", ":=", "auditLog", ".", "EmitAuditEvent", "(", "event", ",", "fields", ")", ";", "err", "!=", "nil", "{", "s", ".", "log", ".", "Error", "(", "err", ")", "\n", "}", "\n", "}", "else", "{", "s", ".", "log", ".", "Warn", "(", "\"SSH server has no audit log\"", ")", "\n", "}", "\n", "}" ]
// EmitAuditEvent sends an event to the Audit Log.
[ "EmitAuditEvent", "sends", "an", "event", "to", "the", "Audit", "Log", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/forward/sshserver.go#L291-L300
train
gravitational/teleport
lib/srv/forward/sshserver.go
Close
func (s *Server) Close() error { conns := []io.Closer{ s.sconn, s.clientConn, s.serverConn, s.targetConn, s.remoteClient, } var errs []error for _, c := range conns { if c == nil { continue } err := c.Close() if err != nil { errs = append(errs, err) } } // Signal to waiting goroutines that the server is closing (for example, // the keep alive loop). s.closeCancel() return trace.NewAggregate(errs...) }
go
func (s *Server) Close() error { conns := []io.Closer{ s.sconn, s.clientConn, s.serverConn, s.targetConn, s.remoteClient, } var errs []error for _, c := range conns { if c == nil { continue } err := c.Close() if err != nil { errs = append(errs, err) } } // Signal to waiting goroutines that the server is closing (for example, // the keep alive loop). s.closeCancel() return trace.NewAggregate(errs...) }
[ "func", "(", "s", "*", "Server", ")", "Close", "(", ")", "error", "{", "conns", ":=", "[", "]", "io", ".", "Closer", "{", "s", ".", "sconn", ",", "s", ".", "clientConn", ",", "s", ".", "serverConn", ",", "s", ".", "targetConn", ",", "s", ".", "remoteClient", ",", "}", "\n", "var", "errs", "[", "]", "error", "\n", "for", "_", ",", "c", ":=", "range", "conns", "{", "if", "c", "==", "nil", "{", "continue", "\n", "}", "\n", "err", ":=", "c", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "errs", "=", "append", "(", "errs", ",", "err", ")", "\n", "}", "\n", "}", "\n", "s", ".", "closeCancel", "(", ")", "\n", "return", "trace", ".", "NewAggregate", "(", "errs", "...", ")", "\n", "}" ]
// Close will close all underlying connections that the forwarding server holds.
[ "Close", "will", "close", "all", "underlying", "connections", "that", "the", "forwarding", "server", "holds", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/forward/sshserver.go#L436-L463
train
gravitational/teleport
lib/service/cfg.go
ApplyToken
func (cfg *Config) ApplyToken(token string) bool { if token != "" { cfg.Token = token return true } return false }
go
func (cfg *Config) ApplyToken(token string) bool { if token != "" { cfg.Token = token return true } return false }
[ "func", "(", "cfg", "*", "Config", ")", "ApplyToken", "(", "token", "string", ")", "bool", "{", "if", "token", "!=", "\"\"", "{", "cfg", ".", "Token", "=", "token", "\n", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// ApplyToken assigns a given token to all internal services but only if token // is not an empty string. // // Returns 'true' if token was modified
[ "ApplyToken", "assigns", "a", "given", "token", "to", "all", "internal", "services", "but", "only", "if", "token", "is", "not", "an", "empty", "string", ".", "Returns", "true", "if", "token", "was", "modified" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/cfg.go#L177-L183
train
gravitational/teleport
lib/service/cfg.go
RoleConfig
func (cfg *Config) RoleConfig() RoleConfig { return RoleConfig{ DataDir: cfg.DataDir, HostUUID: cfg.HostUUID, HostName: cfg.Hostname, AuthServers: cfg.AuthServers, Auth: cfg.Auth, Console: cfg.Console, } }
go
func (cfg *Config) RoleConfig() RoleConfig { return RoleConfig{ DataDir: cfg.DataDir, HostUUID: cfg.HostUUID, HostName: cfg.Hostname, AuthServers: cfg.AuthServers, Auth: cfg.Auth, Console: cfg.Console, } }
[ "func", "(", "cfg", "*", "Config", ")", "RoleConfig", "(", ")", "RoleConfig", "{", "return", "RoleConfig", "{", "DataDir", ":", "cfg", ".", "DataDir", ",", "HostUUID", ":", "cfg", ".", "HostUUID", ",", "HostName", ":", "cfg", ".", "Hostname", ",", "AuthServers", ":", "cfg", ".", "AuthServers", ",", "Auth", ":", "cfg", ".", "Auth", ",", "Console", ":", "cfg", ".", "Console", ",", "}", "\n", "}" ]
// RoleConfig is a config for particular Teleport role
[ "RoleConfig", "is", "a", "config", "for", "particular", "Teleport", "role" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/cfg.go#L186-L195
train
gravitational/teleport
lib/service/cfg.go
GetRecentTTL
func (c *CachePolicy) GetRecentTTL() time.Duration { if c.RecentTTL == nil { return defaults.RecentCacheTTL } return *c.RecentTTL }
go
func (c *CachePolicy) GetRecentTTL() time.Duration { if c.RecentTTL == nil { return defaults.RecentCacheTTL } return *c.RecentTTL }
[ "func", "(", "c", "*", "CachePolicy", ")", "GetRecentTTL", "(", ")", "time", ".", "Duration", "{", "if", "c", ".", "RecentTTL", "==", "nil", "{", "return", "defaults", ".", "RecentCacheTTL", "\n", "}", "\n", "return", "*", "c", ".", "RecentTTL", "\n", "}" ]
// GetRecentTTL either returns TTL that was set, // or default recent TTL value
[ "GetRecentTTL", "either", "returns", "TTL", "that", "was", "set", "or", "default", "recent", "TTL", "value" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/cfg.go#L227-L232
train
gravitational/teleport
lib/service/cfg.go
String
func (c CachePolicy) String() string { if !c.Enabled { return "no cache policy" } recentCachePolicy := "" if c.GetRecentTTL() == 0 { recentCachePolicy = "will not cache frequently accessed items" } else { recentCachePolicy = fmt.Sprintf("will cache frequently accessed items for %v", c.GetRecentTTL()) } if c.NeverExpires { return fmt.Sprintf("cache that will not expire in case if connection to database is lost, %v", recentCachePolicy) } if c.TTL == 0 { return fmt.Sprintf("cache that will expire after connection to database is lost after %v, %v", defaults.CacheTTL, recentCachePolicy) } return fmt.Sprintf("cache that will expire after connection to database is lost after %v, %v", c.TTL, recentCachePolicy) }
go
func (c CachePolicy) String() string { if !c.Enabled { return "no cache policy" } recentCachePolicy := "" if c.GetRecentTTL() == 0 { recentCachePolicy = "will not cache frequently accessed items" } else { recentCachePolicy = fmt.Sprintf("will cache frequently accessed items for %v", c.GetRecentTTL()) } if c.NeverExpires { return fmt.Sprintf("cache that will not expire in case if connection to database is lost, %v", recentCachePolicy) } if c.TTL == 0 { return fmt.Sprintf("cache that will expire after connection to database is lost after %v, %v", defaults.CacheTTL, recentCachePolicy) } return fmt.Sprintf("cache that will expire after connection to database is lost after %v, %v", c.TTL, recentCachePolicy) }
[ "func", "(", "c", "CachePolicy", ")", "String", "(", ")", "string", "{", "if", "!", "c", ".", "Enabled", "{", "return", "\"no cache policy\"", "\n", "}", "\n", "recentCachePolicy", ":=", "\"\"", "\n", "if", "c", ".", "GetRecentTTL", "(", ")", "==", "0", "{", "recentCachePolicy", "=", "\"will not cache frequently accessed items\"", "\n", "}", "else", "{", "recentCachePolicy", "=", "fmt", ".", "Sprintf", "(", "\"will cache frequently accessed items for %v\"", ",", "c", ".", "GetRecentTTL", "(", ")", ")", "\n", "}", "\n", "if", "c", ".", "NeverExpires", "{", "return", "fmt", ".", "Sprintf", "(", "\"cache that will not expire in case if connection to database is lost, %v\"", ",", "recentCachePolicy", ")", "\n", "}", "\n", "if", "c", ".", "TTL", "==", "0", "{", "return", "fmt", ".", "Sprintf", "(", "\"cache that will expire after connection to database is lost after %v, %v\"", ",", "defaults", ".", "CacheTTL", ",", "recentCachePolicy", ")", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"cache that will expire after connection to database is lost after %v, %v\"", ",", "c", ".", "TTL", ",", "recentCachePolicy", ")", "\n", "}" ]
// String returns human-friendly representation of the policy
[ "String", "returns", "human", "-", "friendly", "representation", "of", "the", "policy" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/cfg.go#L235-L252
train
gravitational/teleport
lib/service/cfg.go
ApplyDefaults
func ApplyDefaults(cfg *Config) { // Get defaults for Cipher, Kex algorithms, and MAC algorithms from // golang.org/x/crypto/ssh default config. var sc ssh.Config sc.SetDefaults() // Remove insecure and (borderline insecure) cryptographic primitives from // default configuration. These can still be added back in file configuration by // users, but not supported by default by Teleport. See #1856 for more // details. kex := utils.RemoveFromSlice(sc.KeyExchanges, defaults.DiffieHellmanGroup1SHA1, defaults.DiffieHellmanGroup14SHA1) macs := utils.RemoveFromSlice(sc.MACs, defaults.HMACSHA1, defaults.HMACSHA196) hostname, err := os.Hostname() if err != nil { hostname = "localhost" log.Errorf("Failed to determine hostname: %v.", err) } // global defaults cfg.Hostname = hostname cfg.DataDir = defaults.DataDir cfg.Console = os.Stdout cfg.CipherSuites = utils.DefaultCipherSuites() cfg.Ciphers = sc.Ciphers cfg.KEXAlgorithms = kex cfg.MACAlgorithms = macs // defaults for the auth service: cfg.Auth.Enabled = true cfg.Auth.SSHAddr = *defaults.AuthListenAddr() cfg.Auth.StorageConfig.Type = dir.GetName() cfg.Auth.StorageConfig.Params = backend.Params{defaults.BackendPath: filepath.Join(cfg.DataDir, defaults.BackendDir)} cfg.Auth.StaticTokens = services.DefaultStaticTokens() cfg.Auth.ClusterConfig = services.DefaultClusterConfig() defaults.ConfigureLimiter(&cfg.Auth.Limiter) // set new style default auth preferences ap := &services.AuthPreferenceV2{} ap.CheckAndSetDefaults() cfg.Auth.Preference = ap cfg.Auth.LicenseFile = filepath.Join(cfg.DataDir, defaults.LicenseFile) // defaults for the SSH proxy service: cfg.Proxy.Enabled = true cfg.Proxy.SSHAddr = *defaults.ProxyListenAddr() cfg.Proxy.WebAddr = *defaults.ProxyWebListenAddr() cfg.Proxy.ReverseTunnelListenAddr = *defaults.ReverseTunnellListenAddr() defaults.ConfigureLimiter(&cfg.Proxy.Limiter) // defaults for the Kubernetes proxy service cfg.Proxy.Kube.Enabled = false cfg.Proxy.Kube.ListenAddr = *defaults.KubeProxyListenAddr() // defaults for the SSH service: cfg.SSH.Enabled = true cfg.SSH.Addr = *defaults.SSHServerListenAddr() cfg.SSH.Shell = defaults.DefaultShell defaults.ConfigureLimiter(&cfg.SSH.Limiter) cfg.SSH.PAM = &pam.Config{Enabled: false} }
go
func ApplyDefaults(cfg *Config) { // Get defaults for Cipher, Kex algorithms, and MAC algorithms from // golang.org/x/crypto/ssh default config. var sc ssh.Config sc.SetDefaults() // Remove insecure and (borderline insecure) cryptographic primitives from // default configuration. These can still be added back in file configuration by // users, but not supported by default by Teleport. See #1856 for more // details. kex := utils.RemoveFromSlice(sc.KeyExchanges, defaults.DiffieHellmanGroup1SHA1, defaults.DiffieHellmanGroup14SHA1) macs := utils.RemoveFromSlice(sc.MACs, defaults.HMACSHA1, defaults.HMACSHA196) hostname, err := os.Hostname() if err != nil { hostname = "localhost" log.Errorf("Failed to determine hostname: %v.", err) } // global defaults cfg.Hostname = hostname cfg.DataDir = defaults.DataDir cfg.Console = os.Stdout cfg.CipherSuites = utils.DefaultCipherSuites() cfg.Ciphers = sc.Ciphers cfg.KEXAlgorithms = kex cfg.MACAlgorithms = macs // defaults for the auth service: cfg.Auth.Enabled = true cfg.Auth.SSHAddr = *defaults.AuthListenAddr() cfg.Auth.StorageConfig.Type = dir.GetName() cfg.Auth.StorageConfig.Params = backend.Params{defaults.BackendPath: filepath.Join(cfg.DataDir, defaults.BackendDir)} cfg.Auth.StaticTokens = services.DefaultStaticTokens() cfg.Auth.ClusterConfig = services.DefaultClusterConfig() defaults.ConfigureLimiter(&cfg.Auth.Limiter) // set new style default auth preferences ap := &services.AuthPreferenceV2{} ap.CheckAndSetDefaults() cfg.Auth.Preference = ap cfg.Auth.LicenseFile = filepath.Join(cfg.DataDir, defaults.LicenseFile) // defaults for the SSH proxy service: cfg.Proxy.Enabled = true cfg.Proxy.SSHAddr = *defaults.ProxyListenAddr() cfg.Proxy.WebAddr = *defaults.ProxyWebListenAddr() cfg.Proxy.ReverseTunnelListenAddr = *defaults.ReverseTunnellListenAddr() defaults.ConfigureLimiter(&cfg.Proxy.Limiter) // defaults for the Kubernetes proxy service cfg.Proxy.Kube.Enabled = false cfg.Proxy.Kube.ListenAddr = *defaults.KubeProxyListenAddr() // defaults for the SSH service: cfg.SSH.Enabled = true cfg.SSH.Addr = *defaults.SSHServerListenAddr() cfg.SSH.Shell = defaults.DefaultShell defaults.ConfigureLimiter(&cfg.SSH.Limiter) cfg.SSH.PAM = &pam.Config{Enabled: false} }
[ "func", "ApplyDefaults", "(", "cfg", "*", "Config", ")", "{", "var", "sc", "ssh", ".", "Config", "\n", "sc", ".", "SetDefaults", "(", ")", "\n", "kex", ":=", "utils", ".", "RemoveFromSlice", "(", "sc", ".", "KeyExchanges", ",", "defaults", ".", "DiffieHellmanGroup1SHA1", ",", "defaults", ".", "DiffieHellmanGroup14SHA1", ")", "\n", "macs", ":=", "utils", ".", "RemoveFromSlice", "(", "sc", ".", "MACs", ",", "defaults", ".", "HMACSHA1", ",", "defaults", ".", "HMACSHA196", ")", "\n", "hostname", ",", "err", ":=", "os", ".", "Hostname", "(", ")", "\n", "if", "err", "!=", "nil", "{", "hostname", "=", "\"localhost\"", "\n", "log", ".", "Errorf", "(", "\"Failed to determine hostname: %v.\"", ",", "err", ")", "\n", "}", "\n", "cfg", ".", "Hostname", "=", "hostname", "\n", "cfg", ".", "DataDir", "=", "defaults", ".", "DataDir", "\n", "cfg", ".", "Console", "=", "os", ".", "Stdout", "\n", "cfg", ".", "CipherSuites", "=", "utils", ".", "DefaultCipherSuites", "(", ")", "\n", "cfg", ".", "Ciphers", "=", "sc", ".", "Ciphers", "\n", "cfg", ".", "KEXAlgorithms", "=", "kex", "\n", "cfg", ".", "MACAlgorithms", "=", "macs", "\n", "cfg", ".", "Auth", ".", "Enabled", "=", "true", "\n", "cfg", ".", "Auth", ".", "SSHAddr", "=", "*", "defaults", ".", "AuthListenAddr", "(", ")", "\n", "cfg", ".", "Auth", ".", "StorageConfig", ".", "Type", "=", "dir", ".", "GetName", "(", ")", "\n", "cfg", ".", "Auth", ".", "StorageConfig", ".", "Params", "=", "backend", ".", "Params", "{", "defaults", ".", "BackendPath", ":", "filepath", ".", "Join", "(", "cfg", ".", "DataDir", ",", "defaults", ".", "BackendDir", ")", "}", "\n", "cfg", ".", "Auth", ".", "StaticTokens", "=", "services", ".", "DefaultStaticTokens", "(", ")", "\n", "cfg", ".", "Auth", ".", "ClusterConfig", "=", "services", ".", "DefaultClusterConfig", "(", ")", "\n", "defaults", ".", "ConfigureLimiter", "(", "&", "cfg", ".", "Auth", ".", "Limiter", ")", "\n", "ap", ":=", "&", "services", ".", "AuthPreferenceV2", "{", "}", "\n", "ap", ".", "CheckAndSetDefaults", "(", ")", "\n", "cfg", ".", "Auth", ".", "Preference", "=", "ap", "\n", "cfg", ".", "Auth", ".", "LicenseFile", "=", "filepath", ".", "Join", "(", "cfg", ".", "DataDir", ",", "defaults", ".", "LicenseFile", ")", "\n", "cfg", ".", "Proxy", ".", "Enabled", "=", "true", "\n", "cfg", ".", "Proxy", ".", "SSHAddr", "=", "*", "defaults", ".", "ProxyListenAddr", "(", ")", "\n", "cfg", ".", "Proxy", ".", "WebAddr", "=", "*", "defaults", ".", "ProxyWebListenAddr", "(", ")", "\n", "cfg", ".", "Proxy", ".", "ReverseTunnelListenAddr", "=", "*", "defaults", ".", "ReverseTunnellListenAddr", "(", ")", "\n", "defaults", ".", "ConfigureLimiter", "(", "&", "cfg", ".", "Proxy", ".", "Limiter", ")", "\n", "cfg", ".", "Proxy", ".", "Kube", ".", "Enabled", "=", "false", "\n", "cfg", ".", "Proxy", ".", "Kube", ".", "ListenAddr", "=", "*", "defaults", ".", "KubeProxyListenAddr", "(", ")", "\n", "cfg", ".", "SSH", ".", "Enabled", "=", "true", "\n", "cfg", ".", "SSH", ".", "Addr", "=", "*", "defaults", ".", "SSHServerListenAddr", "(", ")", "\n", "cfg", ".", "SSH", ".", "Shell", "=", "defaults", ".", "DefaultShell", "\n", "defaults", ".", "ConfigureLimiter", "(", "&", "cfg", ".", "SSH", ".", "Limiter", ")", "\n", "cfg", ".", "SSH", ".", "PAM", "=", "&", "pam", ".", "Config", "{", "Enabled", ":", "false", "}", "\n", "}" ]
// ApplyDefaults applies default values to the existing config structure
[ "ApplyDefaults", "applies", "default", "values", "to", "the", "existing", "config", "structure" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/cfg.go#L412-L475
train
gravitational/teleport
lib/srv/keepalive.go
StartKeepAliveLoop
func StartKeepAliveLoop(p KeepAliveParams) { var missedCount int64 log := logrus.WithFields(logrus.Fields{ trace.Component: teleport.ComponentKeepAlive, }) log.Debugf("Starting keep-alive loop with with interval %v and max count %v.", p.Interval, p.MaxCount) tickerCh := time.NewTicker(p.Interval) defer tickerCh.Stop() for { select { case <-tickerCh.C: var sentCount int // Send a keep alive message on all connections and make sure a response // was received on all. for _, conn := range p.Conns { ok := sendKeepAliveWithTimeout(conn, defaults.ReadHeadersTimeout, p.CloseContext) if ok { sentCount += 1 } } if sentCount == len(p.Conns) { missedCount = 0 continue } // If enough keep-alives are missed, the connection is dead, call cancel // and notify the server to disconnect and cleanup. missedCount = missedCount + 1 if missedCount > p.MaxCount { log.Infof("Missed %v keep-alive messages, closing connection.", missedCount) p.CloseCancel() return } // If an external caller closed the context (connection is done) then no // more need to wait around for keep-alives. case <-p.CloseContext.Done(): return } } }
go
func StartKeepAliveLoop(p KeepAliveParams) { var missedCount int64 log := logrus.WithFields(logrus.Fields{ trace.Component: teleport.ComponentKeepAlive, }) log.Debugf("Starting keep-alive loop with with interval %v and max count %v.", p.Interval, p.MaxCount) tickerCh := time.NewTicker(p.Interval) defer tickerCh.Stop() for { select { case <-tickerCh.C: var sentCount int // Send a keep alive message on all connections and make sure a response // was received on all. for _, conn := range p.Conns { ok := sendKeepAliveWithTimeout(conn, defaults.ReadHeadersTimeout, p.CloseContext) if ok { sentCount += 1 } } if sentCount == len(p.Conns) { missedCount = 0 continue } // If enough keep-alives are missed, the connection is dead, call cancel // and notify the server to disconnect and cleanup. missedCount = missedCount + 1 if missedCount > p.MaxCount { log.Infof("Missed %v keep-alive messages, closing connection.", missedCount) p.CloseCancel() return } // If an external caller closed the context (connection is done) then no // more need to wait around for keep-alives. case <-p.CloseContext.Done(): return } } }
[ "func", "StartKeepAliveLoop", "(", "p", "KeepAliveParams", ")", "{", "var", "missedCount", "int64", "\n", "log", ":=", "logrus", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "trace", ".", "Component", ":", "teleport", ".", "ComponentKeepAlive", ",", "}", ")", "\n", "log", ".", "Debugf", "(", "\"Starting keep-alive loop with with interval %v and max count %v.\"", ",", "p", ".", "Interval", ",", "p", ".", "MaxCount", ")", "\n", "tickerCh", ":=", "time", ".", "NewTicker", "(", "p", ".", "Interval", ")", "\n", "defer", "tickerCh", ".", "Stop", "(", ")", "\n", "for", "{", "select", "{", "case", "<-", "tickerCh", ".", "C", ":", "var", "sentCount", "int", "\n", "for", "_", ",", "conn", ":=", "range", "p", ".", "Conns", "{", "ok", ":=", "sendKeepAliveWithTimeout", "(", "conn", ",", "defaults", ".", "ReadHeadersTimeout", ",", "p", ".", "CloseContext", ")", "\n", "if", "ok", "{", "sentCount", "+=", "1", "\n", "}", "\n", "}", "\n", "if", "sentCount", "==", "len", "(", "p", ".", "Conns", ")", "{", "missedCount", "=", "0", "\n", "continue", "\n", "}", "\n", "missedCount", "=", "missedCount", "+", "1", "\n", "if", "missedCount", ">", "p", ".", "MaxCount", "{", "log", ".", "Infof", "(", "\"Missed %v keep-alive messages, closing connection.\"", ",", "missedCount", ")", "\n", "p", ".", "CloseCancel", "(", ")", "\n", "return", "\n", "}", "\n", "case", "<-", "p", ".", "CloseContext", ".", "Done", "(", ")", ":", "return", "\n", "}", "\n", "}", "\n", "}" ]
// StartKeepAliveLoop starts the keep-alive loop.
[ "StartKeepAliveLoop", "starts", "the", "keep", "-", "alive", "loop", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/keepalive.go#L59-L102
train
gravitational/teleport
lib/srv/keepalive.go
sendKeepAliveWithTimeout
func sendKeepAliveWithTimeout(conn RequestSender, timeout time.Duration, closeContext context.Context) bool { errorCh := make(chan error, 1) go func() { // SendRequest will unblock when connection or channel is closed. _, _, err := conn.SendRequest(teleport.KeepAliveReqType, true, nil) errorCh <- err }() select { case err := <-errorCh: if err != nil { return false } return true case <-time.After(timeout): return false case <-closeContext.Done(): return false } }
go
func sendKeepAliveWithTimeout(conn RequestSender, timeout time.Duration, closeContext context.Context) bool { errorCh := make(chan error, 1) go func() { // SendRequest will unblock when connection or channel is closed. _, _, err := conn.SendRequest(teleport.KeepAliveReqType, true, nil) errorCh <- err }() select { case err := <-errorCh: if err != nil { return false } return true case <-time.After(timeout): return false case <-closeContext.Done(): return false } }
[ "func", "sendKeepAliveWithTimeout", "(", "conn", "RequestSender", ",", "timeout", "time", ".", "Duration", ",", "closeContext", "context", ".", "Context", ")", "bool", "{", "errorCh", ":=", "make", "(", "chan", "error", ",", "1", ")", "\n", "go", "func", "(", ")", "{", "_", ",", "_", ",", "err", ":=", "conn", ".", "SendRequest", "(", "teleport", ".", "KeepAliveReqType", ",", "true", ",", "nil", ")", "\n", "errorCh", "<-", "err", "\n", "}", "(", ")", "\n", "select", "{", "case", "err", ":=", "<-", "errorCh", ":", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "return", "true", "\n", "case", "<-", "time", ".", "After", "(", "timeout", ")", ":", "return", "false", "\n", "case", "<-", "closeContext", ".", "Done", "(", ")", ":", "return", "false", "\n", "}", "\n", "}" ]
// sendKeepAliveWithTimeout sends a keepalive@openssh.com message to the remote // client. A manual timeout is needed here because SendRequest will wait for a // response forever.
[ "sendKeepAliveWithTimeout", "sends", "a", "keepalive" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/keepalive.go#L107-L127
train
gravitational/teleport
lib/services/namespace.go
MarshalNamespace
func MarshalNamespace(resource Namespace, opts ...MarshalOption) ([]byte, error) { cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } if !cfg.PreserveResourceID { // avoid modifying the original object // to prevent unexpected data races copy := resource copy.SetResourceID(0) resource = copy } return utils.FastMarshal(resource) }
go
func MarshalNamespace(resource Namespace, opts ...MarshalOption) ([]byte, error) { cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } if !cfg.PreserveResourceID { // avoid modifying the original object // to prevent unexpected data races copy := resource copy.SetResourceID(0) resource = copy } return utils.FastMarshal(resource) }
[ "func", "MarshalNamespace", "(", "resource", "Namespace", ",", "opts", "...", "MarshalOption", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "cfg", ",", "err", ":=", "collectOptions", "(", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "!", "cfg", ".", "PreserveResourceID", "{", "copy", ":=", "resource", "\n", "copy", ".", "SetResourceID", "(", "0", ")", "\n", "resource", "=", "copy", "\n", "}", "\n", "return", "utils", ".", "FastMarshal", "(", "resource", ")", "\n", "}" ]
// MarshalNamespace marshals namespace to JSON
[ "MarshalNamespace", "marshals", "namespace", "to", "JSON" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/namespace.go#L128-L141
train
gravitational/teleport
lib/services/namespace.go
UnmarshalNamespace
func UnmarshalNamespace(data []byte, opts ...MarshalOption) (*Namespace, error) { if len(data) == 0 { return nil, trace.BadParameter("missing namespace data") } cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } // always skip schema validation on namespaces unmarshal // the namespace is always created by teleport now var namespace Namespace if err := utils.FastUnmarshal(data, &namespace); err != nil { return nil, trace.BadParameter(err.Error()) } if err := namespace.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } if cfg.ID != 0 { namespace.Metadata.ID = cfg.ID } if !cfg.Expires.IsZero() { namespace.Metadata.Expires = &cfg.Expires } return &namespace, nil }
go
func UnmarshalNamespace(data []byte, opts ...MarshalOption) (*Namespace, error) { if len(data) == 0 { return nil, trace.BadParameter("missing namespace data") } cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } // always skip schema validation on namespaces unmarshal // the namespace is always created by teleport now var namespace Namespace if err := utils.FastUnmarshal(data, &namespace); err != nil { return nil, trace.BadParameter(err.Error()) } if err := namespace.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } if cfg.ID != 0 { namespace.Metadata.ID = cfg.ID } if !cfg.Expires.IsZero() { namespace.Metadata.Expires = &cfg.Expires } return &namespace, nil }
[ "func", "UnmarshalNamespace", "(", "data", "[", "]", "byte", ",", "opts", "...", "MarshalOption", ")", "(", "*", "Namespace", ",", "error", ")", "{", "if", "len", "(", "data", ")", "==", "0", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"missing namespace data\"", ")", "\n", "}", "\n", "cfg", ",", "err", ":=", "collectOptions", "(", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "var", "namespace", "Namespace", "\n", "if", "err", ":=", "utils", ".", "FastUnmarshal", "(", "data", ",", "&", "namespace", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "if", "err", ":=", "namespace", ".", "CheckAndSetDefaults", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "cfg", ".", "ID", "!=", "0", "{", "namespace", ".", "Metadata", ".", "ID", "=", "cfg", ".", "ID", "\n", "}", "\n", "if", "!", "cfg", ".", "Expires", ".", "IsZero", "(", ")", "{", "namespace", ".", "Metadata", ".", "Expires", "=", "&", "cfg", ".", "Expires", "\n", "}", "\n", "return", "&", "namespace", ",", "nil", "\n", "}" ]
// UnmarshalNamespace unmarshals role from JSON or YAML, // sets defaults and checks the schema
[ "UnmarshalNamespace", "unmarshals", "role", "from", "JSON", "or", "YAML", "sets", "defaults", "and", "checks", "the", "schema" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/namespace.go#L145-L174
train
gravitational/teleport
tool/tctl/common/top_command.go
Initialize
func (c *TopCommand) Initialize(app *kingpin.Application, config *service.Config) { c.config = config c.top = app.Command("top", "Report diagnostic information") c.diagURL = c.top.Arg("diag-addr", "Diagnostic HTTP URL").Default("http://127.0.0.1:3434").String() c.refreshPeriod = c.top.Arg("refresh", "Refresh period").Default("5s").Duration() }
go
func (c *TopCommand) Initialize(app *kingpin.Application, config *service.Config) { c.config = config c.top = app.Command("top", "Report diagnostic information") c.diagURL = c.top.Arg("diag-addr", "Diagnostic HTTP URL").Default("http://127.0.0.1:3434").String() c.refreshPeriod = c.top.Arg("refresh", "Refresh period").Default("5s").Duration() }
[ "func", "(", "c", "*", "TopCommand", ")", "Initialize", "(", "app", "*", "kingpin", ".", "Application", ",", "config", "*", "service", ".", "Config", ")", "{", "c", ".", "config", "=", "config", "\n", "c", ".", "top", "=", "app", ".", "Command", "(", "\"top\"", ",", "\"Report diagnostic information\"", ")", "\n", "c", ".", "diagURL", "=", "c", ".", "top", ".", "Arg", "(", "\"diag-addr\"", ",", "\"Diagnostic HTTP URL\"", ")", ".", "Default", "(", "\"http://127.0.0.1:3434\"", ")", ".", "String", "(", ")", "\n", "c", ".", "refreshPeriod", "=", "c", ".", "top", ".", "Arg", "(", "\"refresh\"", ",", "\"Refresh period\"", ")", ".", "Default", "(", "\"5s\"", ")", ".", "Duration", "(", ")", "\n", "}" ]
// Initialize allows TopCommand to plug itself into the CLI parser.
[ "Initialize", "allows", "TopCommand", "to", "plug", "itself", "into", "the", "CLI", "parser", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/top_command.go#L55-L60
train
gravitational/teleport
tool/tctl/common/top_command.go
Top
func (c *TopCommand) Top(client *roundtrip.Client) error { if err := ui.Init(); err != nil { return trace.Wrap(err) } defer ui.Close() ctx, cancel := context.WithCancel(context.TODO()) defer cancel() uiEvents := ui.PollEvents() ticker := time.NewTicker(*c.refreshPeriod) defer ticker.Stop() // fetch and render first time var prev *Report re, err := c.fetchAndGenerateReport(ctx, client, nil) if err != nil { return trace.Wrap(err) } lastTab := "" if err := c.render(ctx, *re, lastTab); err != nil { return trace.Wrap(err) } for { select { case e := <-uiEvents: switch e.ID { // event string/identifier case "q", "<C-c>": // press 'q' or 'C-c' to quit return nil } if e.ID == "1" || e.ID == "2" || e.ID == "3" { lastTab = e.ID } // render previously fetched data on the resize event if re != nil { if err := c.render(ctx, *re, lastTab); err != nil { return trace.Wrap(err) } } case <-ticker.C: // fetch data and re-render on ticker prev = re re, err = c.fetchAndGenerateReport(ctx, client, prev) if err != nil { return trace.Wrap(err) } if err := c.render(ctx, *re, lastTab); err != nil { return trace.Wrap(err) } } } }
go
func (c *TopCommand) Top(client *roundtrip.Client) error { if err := ui.Init(); err != nil { return trace.Wrap(err) } defer ui.Close() ctx, cancel := context.WithCancel(context.TODO()) defer cancel() uiEvents := ui.PollEvents() ticker := time.NewTicker(*c.refreshPeriod) defer ticker.Stop() // fetch and render first time var prev *Report re, err := c.fetchAndGenerateReport(ctx, client, nil) if err != nil { return trace.Wrap(err) } lastTab := "" if err := c.render(ctx, *re, lastTab); err != nil { return trace.Wrap(err) } for { select { case e := <-uiEvents: switch e.ID { // event string/identifier case "q", "<C-c>": // press 'q' or 'C-c' to quit return nil } if e.ID == "1" || e.ID == "2" || e.ID == "3" { lastTab = e.ID } // render previously fetched data on the resize event if re != nil { if err := c.render(ctx, *re, lastTab); err != nil { return trace.Wrap(err) } } case <-ticker.C: // fetch data and re-render on ticker prev = re re, err = c.fetchAndGenerateReport(ctx, client, prev) if err != nil { return trace.Wrap(err) } if err := c.render(ctx, *re, lastTab); err != nil { return trace.Wrap(err) } } } }
[ "func", "(", "c", "*", "TopCommand", ")", "Top", "(", "client", "*", "roundtrip", ".", "Client", ")", "error", "{", "if", "err", ":=", "ui", ".", "Init", "(", ")", ";", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "defer", "ui", ".", "Close", "(", ")", "\n", "ctx", ",", "cancel", ":=", "context", ".", "WithCancel", "(", "context", ".", "TODO", "(", ")", ")", "\n", "defer", "cancel", "(", ")", "\n", "uiEvents", ":=", "ui", ".", "PollEvents", "(", ")", "\n", "ticker", ":=", "time", ".", "NewTicker", "(", "*", "c", ".", "refreshPeriod", ")", "\n", "defer", "ticker", ".", "Stop", "(", ")", "\n", "var", "prev", "*", "Report", "\n", "re", ",", "err", ":=", "c", ".", "fetchAndGenerateReport", "(", "ctx", ",", "client", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "lastTab", ":=", "\"\"", "\n", "if", "err", ":=", "c", ".", "render", "(", "ctx", ",", "*", "re", ",", "lastTab", ")", ";", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "for", "{", "select", "{", "case", "e", ":=", "<-", "uiEvents", ":", "switch", "e", ".", "ID", "{", "case", "\"q\"", ",", "\"<C-c>\"", ":", "return", "nil", "\n", "}", "\n", "if", "e", ".", "ID", "==", "\"1\"", "||", "e", ".", "ID", "==", "\"2\"", "||", "e", ".", "ID", "==", "\"3\"", "{", "lastTab", "=", "e", ".", "ID", "\n", "}", "\n", "if", "re", "!=", "nil", "{", "if", "err", ":=", "c", ".", "render", "(", "ctx", ",", "*", "re", ",", "lastTab", ")", ";", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "}", "\n", "case", "<-", "ticker", ".", "C", ":", "prev", "=", "re", "\n", "re", ",", "err", "=", "c", ".", "fetchAndGenerateReport", "(", "ctx", ",", "client", ",", "prev", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "err", ":=", "c", ".", "render", "(", "ctx", ",", "*", "re", ",", "lastTab", ")", ";", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// Top is called to execute "status" CLI command.
[ "Top", "is", "called", "to", "execute", "status", "CLI", "command", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/top_command.go#L82-L133
train
gravitational/teleport
tool/tctl/common/top_command.go
SortedTopRequests
func (b *BackendStats) SortedTopRequests() []Request { out := make([]Request, 0, len(b.TopRequests)) for _, req := range b.TopRequests { out = append(out, req) } sort.Slice(out, func(i, j int) bool { if out[i].GetFreq() == out[j].GetFreq() { return out[i].Count > out[j].Count } return out[i].GetFreq() > out[j].GetFreq() }) return out }
go
func (b *BackendStats) SortedTopRequests() []Request { out := make([]Request, 0, len(b.TopRequests)) for _, req := range b.TopRequests { out = append(out, req) } sort.Slice(out, func(i, j int) bool { if out[i].GetFreq() == out[j].GetFreq() { return out[i].Count > out[j].Count } return out[i].GetFreq() > out[j].GetFreq() }) return out }
[ "func", "(", "b", "*", "BackendStats", ")", "SortedTopRequests", "(", ")", "[", "]", "Request", "{", "out", ":=", "make", "(", "[", "]", "Request", ",", "0", ",", "len", "(", "b", ".", "TopRequests", ")", ")", "\n", "for", "_", ",", "req", ":=", "range", "b", ".", "TopRequests", "{", "out", "=", "append", "(", "out", ",", "req", ")", "\n", "}", "\n", "sort", ".", "Slice", "(", "out", ",", "func", "(", "i", ",", "j", "int", ")", "bool", "{", "if", "out", "[", "i", "]", ".", "GetFreq", "(", ")", "==", "out", "[", "j", "]", ".", "GetFreq", "(", ")", "{", "return", "out", "[", "i", "]", ".", "Count", ">", "out", "[", "j", "]", ".", "Count", "\n", "}", "\n", "return", "out", "[", "i", "]", ".", "GetFreq", "(", ")", ">", "out", "[", "j", "]", ".", "GetFreq", "(", ")", "\n", "}", ")", "\n", "return", "out", "\n", "}" ]
// SortedTopRequests returns top requests sorted either // by frequency if frequency is present, or by count otherwise
[ "SortedTopRequests", "returns", "top", "requests", "sorted", "either", "by", "frequency", "if", "frequency", "is", "present", "or", "by", "count", "otherwise" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/top_command.go#L393-L405
train
gravitational/teleport
tool/tctl/common/top_command.go
SetFreq
func (c *Counter) SetFreq(prevCount Counter, period time.Duration) { if period == 0 { return } freq := float64(c.Count-prevCount.Count) / float64(period/time.Second) c.Freq = &freq }
go
func (c *Counter) SetFreq(prevCount Counter, period time.Duration) { if period == 0 { return } freq := float64(c.Count-prevCount.Count) / float64(period/time.Second) c.Freq = &freq }
[ "func", "(", "c", "*", "Counter", ")", "SetFreq", "(", "prevCount", "Counter", ",", "period", "time", ".", "Duration", ")", "{", "if", "period", "==", "0", "{", "return", "\n", "}", "\n", "freq", ":=", "float64", "(", "c", ".", "Count", "-", "prevCount", ".", "Count", ")", "/", "float64", "(", "period", "/", "time", ".", "Second", ")", "\n", "c", ".", "Freq", "=", "&", "freq", "\n", "}" ]
// SetFreq sets counter frequency based on the previous value // and the time period
[ "SetFreq", "sets", "counter", "frequency", "based", "on", "the", "previous", "value", "and", "the", "time", "period" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/top_command.go#L487-L493
train
gravitational/teleport
tool/tctl/common/top_command.go
AsPercentiles
func (h Histogram) AsPercentiles() []Percentile { if h.Count == 0 { return nil } var percentiles []Percentile for _, bucket := range h.Buckets { if bucket.Count == 0 { continue } if bucket.Count == h.Count || math.IsInf(bucket.UpperBound, 0) { percentiles = append(percentiles, Percentile{ Percentile: 100, Value: time.Duration(bucket.UpperBound * float64(time.Second)), }) return percentiles } percentiles = append(percentiles, Percentile{ Percentile: 100 * (float64(bucket.Count) / float64(h.Count)), Value: time.Duration(bucket.UpperBound * float64(time.Second)), }) } return percentiles }
go
func (h Histogram) AsPercentiles() []Percentile { if h.Count == 0 { return nil } var percentiles []Percentile for _, bucket := range h.Buckets { if bucket.Count == 0 { continue } if bucket.Count == h.Count || math.IsInf(bucket.UpperBound, 0) { percentiles = append(percentiles, Percentile{ Percentile: 100, Value: time.Duration(bucket.UpperBound * float64(time.Second)), }) return percentiles } percentiles = append(percentiles, Percentile{ Percentile: 100 * (float64(bucket.Count) / float64(h.Count)), Value: time.Duration(bucket.UpperBound * float64(time.Second)), }) } return percentiles }
[ "func", "(", "h", "Histogram", ")", "AsPercentiles", "(", ")", "[", "]", "Percentile", "{", "if", "h", ".", "Count", "==", "0", "{", "return", "nil", "\n", "}", "\n", "var", "percentiles", "[", "]", "Percentile", "\n", "for", "_", ",", "bucket", ":=", "range", "h", ".", "Buckets", "{", "if", "bucket", ".", "Count", "==", "0", "{", "continue", "\n", "}", "\n", "if", "bucket", ".", "Count", "==", "h", ".", "Count", "||", "math", ".", "IsInf", "(", "bucket", ".", "UpperBound", ",", "0", ")", "{", "percentiles", "=", "append", "(", "percentiles", ",", "Percentile", "{", "Percentile", ":", "100", ",", "Value", ":", "time", ".", "Duration", "(", "bucket", ".", "UpperBound", "*", "float64", "(", "time", ".", "Second", ")", ")", ",", "}", ")", "\n", "return", "percentiles", "\n", "}", "\n", "percentiles", "=", "append", "(", "percentiles", ",", "Percentile", "{", "Percentile", ":", "100", "*", "(", "float64", "(", "bucket", ".", "Count", ")", "/", "float64", "(", "h", ".", "Count", ")", ")", ",", "Value", ":", "time", ".", "Duration", "(", "bucket", ".", "UpperBound", "*", "float64", "(", "time", ".", "Second", ")", ")", ",", "}", ")", "\n", "}", "\n", "return", "percentiles", "\n", "}" ]
// AsPercentiles interprets historgram as a bucket of percentiles // and returns calculated percentiles
[ "AsPercentiles", "interprets", "historgram", "as", "a", "bucket", "of", "percentiles", "and", "returns", "calculated", "percentiles" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/top_command.go#L521-L543
train
gravitational/teleport
lib/fixtures/fixtures.go
ExpectNotFound
func ExpectNotFound(c *check.C, err error) { c.Assert(trace.IsNotFound(err), check.Equals, true, check.Commentf("expected NotFound, got %T %v at %v", trace.Unwrap(err), err, string(debug.Stack()))) }
go
func ExpectNotFound(c *check.C, err error) { c.Assert(trace.IsNotFound(err), check.Equals, true, check.Commentf("expected NotFound, got %T %v at %v", trace.Unwrap(err), err, string(debug.Stack()))) }
[ "func", "ExpectNotFound", "(", "c", "*", "check", ".", "C", ",", "err", "error", ")", "{", "c", ".", "Assert", "(", "trace", ".", "IsNotFound", "(", "err", ")", ",", "check", ".", "Equals", ",", "true", ",", "check", ".", "Commentf", "(", "\"expected NotFound, got %T %v at %v\"", ",", "trace", ".", "Unwrap", "(", "err", ")", ",", "err", ",", "string", "(", "debug", ".", "Stack", "(", ")", ")", ")", ")", "\n", "}" ]
// ExpectNotFound expects not found error
[ "ExpectNotFound", "expects", "not", "found", "error" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/fixtures/fixtures.go#L13-L15
train
gravitational/teleport
lib/fixtures/fixtures.go
ExpectBadParameter
func ExpectBadParameter(c *check.C, err error) { c.Assert(trace.IsBadParameter(err), check.Equals, true, check.Commentf("expected BadParameter, got %T %v at %v", trace.Unwrap(err), err, string(debug.Stack()))) }
go
func ExpectBadParameter(c *check.C, err error) { c.Assert(trace.IsBadParameter(err), check.Equals, true, check.Commentf("expected BadParameter, got %T %v at %v", trace.Unwrap(err), err, string(debug.Stack()))) }
[ "func", "ExpectBadParameter", "(", "c", "*", "check", ".", "C", ",", "err", "error", ")", "{", "c", ".", "Assert", "(", "trace", ".", "IsBadParameter", "(", "err", ")", ",", "check", ".", "Equals", ",", "true", ",", "check", ".", "Commentf", "(", "\"expected BadParameter, got %T %v at %v\"", ",", "trace", ".", "Unwrap", "(", "err", ")", ",", "err", ",", "string", "(", "debug", ".", "Stack", "(", ")", ")", ")", ")", "\n", "}" ]
// ExpectBadParameter expects bad parameter error
[ "ExpectBadParameter", "expects", "bad", "parameter", "error" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/fixtures/fixtures.go#L18-L20
train
gravitational/teleport
lib/fixtures/fixtures.go
ExpectCompareFailed
func ExpectCompareFailed(c *check.C, err error) { c.Assert(trace.IsCompareFailed(err), check.Equals, true, check.Commentf("expected CompareFailed, got %T %v at %v", trace.Unwrap(err), err, string(debug.Stack()))) }
go
func ExpectCompareFailed(c *check.C, err error) { c.Assert(trace.IsCompareFailed(err), check.Equals, true, check.Commentf("expected CompareFailed, got %T %v at %v", trace.Unwrap(err), err, string(debug.Stack()))) }
[ "func", "ExpectCompareFailed", "(", "c", "*", "check", ".", "C", ",", "err", "error", ")", "{", "c", ".", "Assert", "(", "trace", ".", "IsCompareFailed", "(", "err", ")", ",", "check", ".", "Equals", ",", "true", ",", "check", ".", "Commentf", "(", "\"expected CompareFailed, got %T %v at %v\"", ",", "trace", ".", "Unwrap", "(", "err", ")", ",", "err", ",", "string", "(", "debug", ".", "Stack", "(", ")", ")", ")", ")", "\n", "}" ]
// ExpectCompareFailed expects compare failed error
[ "ExpectCompareFailed", "expects", "compare", "failed", "error" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/fixtures/fixtures.go#L23-L25
train
gravitational/teleport
lib/fixtures/fixtures.go
ExpectAccessDenied
func ExpectAccessDenied(c *check.C, err error) { c.Assert(trace.IsAccessDenied(err), check.Equals, true, check.Commentf("expected AccessDenied, got %T %v at %v", trace.Unwrap(err), err, string(debug.Stack()))) }
go
func ExpectAccessDenied(c *check.C, err error) { c.Assert(trace.IsAccessDenied(err), check.Equals, true, check.Commentf("expected AccessDenied, got %T %v at %v", trace.Unwrap(err), err, string(debug.Stack()))) }
[ "func", "ExpectAccessDenied", "(", "c", "*", "check", ".", "C", ",", "err", "error", ")", "{", "c", ".", "Assert", "(", "trace", ".", "IsAccessDenied", "(", "err", ")", ",", "check", ".", "Equals", ",", "true", ",", "check", ".", "Commentf", "(", "\"expected AccessDenied, got %T %v at %v\"", ",", "trace", ".", "Unwrap", "(", "err", ")", ",", "err", ",", "string", "(", "debug", ".", "Stack", "(", ")", ")", ")", ")", "\n", "}" ]
// ExpectAccessDenied expects error to be access denied
[ "ExpectAccessDenied", "expects", "error", "to", "be", "access", "denied" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/fixtures/fixtures.go#L28-L30
train
gravitational/teleport
lib/fixtures/fixtures.go
ExpectAlreadyExists
func ExpectAlreadyExists(c *check.C, err error) { c.Assert(trace.IsAlreadyExists(err), check.Equals, true, check.Commentf("expected AlreadyExists, got %T %v at %v", trace.Unwrap(err), err, string(debug.Stack()))) }
go
func ExpectAlreadyExists(c *check.C, err error) { c.Assert(trace.IsAlreadyExists(err), check.Equals, true, check.Commentf("expected AlreadyExists, got %T %v at %v", trace.Unwrap(err), err, string(debug.Stack()))) }
[ "func", "ExpectAlreadyExists", "(", "c", "*", "check", ".", "C", ",", "err", "error", ")", "{", "c", ".", "Assert", "(", "trace", ".", "IsAlreadyExists", "(", "err", ")", ",", "check", ".", "Equals", ",", "true", ",", "check", ".", "Commentf", "(", "\"expected AlreadyExists, got %T %v at %v\"", ",", "trace", ".", "Unwrap", "(", "err", ")", ",", "err", ",", "string", "(", "debug", ".", "Stack", "(", ")", ")", ")", ")", "\n", "}" ]
// ExpectAlreadyExists expects already exists error
[ "ExpectAlreadyExists", "expects", "already", "exists", "error" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/fixtures/fixtures.go#L33-L35
train
gravitational/teleport
lib/fixtures/fixtures.go
ExpectConnectionProblem
func ExpectConnectionProblem(c *check.C, err error) { c.Assert(trace.IsConnectionProblem(err), check.Equals, true, check.Commentf("expected ConnectionProblem, got %T %v at %v", trace.Unwrap(err), err, string(debug.Stack()))) }
go
func ExpectConnectionProblem(c *check.C, err error) { c.Assert(trace.IsConnectionProblem(err), check.Equals, true, check.Commentf("expected ConnectionProblem, got %T %v at %v", trace.Unwrap(err), err, string(debug.Stack()))) }
[ "func", "ExpectConnectionProblem", "(", "c", "*", "check", ".", "C", ",", "err", "error", ")", "{", "c", ".", "Assert", "(", "trace", ".", "IsConnectionProblem", "(", "err", ")", ",", "check", ".", "Equals", ",", "true", ",", "check", ".", "Commentf", "(", "\"expected ConnectionProblem, got %T %v at %v\"", ",", "trace", ".", "Unwrap", "(", "err", ")", ",", "err", ",", "string", "(", "debug", ".", "Stack", "(", ")", ")", ")", ")", "\n", "}" ]
// ExpectConnectionProblem expects connection problem error
[ "ExpectConnectionProblem", "expects", "connection", "problem", "error" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/fixtures/fixtures.go#L38-L40
train
gravitational/teleport
lib/fixtures/fixtures.go
DeepCompare
func DeepCompare(c *check.C, a, b interface{}) { d := &spew.ConfigState{Indent: " ", DisableMethods: true, DisablePointerMethods: true, DisablePointerAddresses: true} c.Assert(a, check.DeepEquals, b, check.Commentf("%v\nStack:\n%v\n", diff.Diff(d.Sdump(a), d.Sdump(b)), string(debug.Stack()))) }
go
func DeepCompare(c *check.C, a, b interface{}) { d := &spew.ConfigState{Indent: " ", DisableMethods: true, DisablePointerMethods: true, DisablePointerAddresses: true} c.Assert(a, check.DeepEquals, b, check.Commentf("%v\nStack:\n%v\n", diff.Diff(d.Sdump(a), d.Sdump(b)), string(debug.Stack()))) }
[ "func", "DeepCompare", "(", "c", "*", "check", ".", "C", ",", "a", ",", "b", "interface", "{", "}", ")", "{", "d", ":=", "&", "spew", ".", "ConfigState", "{", "Indent", ":", "\" \"", ",", "DisableMethods", ":", "true", ",", "DisablePointerMethods", ":", "true", ",", "DisablePointerAddresses", ":", "true", "}", "\n", "c", ".", "Assert", "(", "a", ",", "check", ".", "DeepEquals", ",", "b", ",", "check", ".", "Commentf", "(", "\"%v\\nStack:\\n%v\\n\"", ",", "\\n", ",", "\\n", ")", ")", "\n", "}" ]
// DeepCompare uses gocheck DeepEquals but provides nice diff if things are not equal
[ "DeepCompare", "uses", "gocheck", "DeepEquals", "but", "provides", "nice", "diff", "if", "things", "are", "not", "equal" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/fixtures/fixtures.go#L43-L47
train
gravitational/teleport
lib/sshutils/req.go
Check
func (p *PTYReqParams) Check() error { if p.W > maxSize || p.W < minSize { return trace.BadParameter("bad width: %v", p.W) } if p.H > maxSize || p.H < minSize { return trace.BadParameter("bad height: %v", p.H) } return nil }
go
func (p *PTYReqParams) Check() error { if p.W > maxSize || p.W < minSize { return trace.BadParameter("bad width: %v", p.W) } if p.H > maxSize || p.H < minSize { return trace.BadParameter("bad height: %v", p.H) } return nil }
[ "func", "(", "p", "*", "PTYReqParams", ")", "Check", "(", ")", "error", "{", "if", "p", ".", "W", ">", "maxSize", "||", "p", ".", "W", "<", "minSize", "{", "return", "trace", ".", "BadParameter", "(", "\"bad width: %v\"", ",", "p", ".", "W", ")", "\n", "}", "\n", "if", "p", ".", "H", ">", "maxSize", "||", "p", ".", "H", "<", "minSize", "{", "return", "trace", ".", "BadParameter", "(", "\"bad height: %v\"", ",", "p", ".", "H", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Check validates PTY parameters.
[ "Check", "validates", "PTY", "parameters", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/req.go#L102-L111
train
gravitational/teleport
lib/sshutils/req.go
CheckAndSetDefaults
func (p *PTYReqParams) CheckAndSetDefaults() error { if p.W > maxSize || p.W < minSize { p.W = teleport.DefaultTerminalWidth } if p.H > maxSize || p.H < minSize { p.H = teleport.DefaultTerminalHeight } return nil }
go
func (p *PTYReqParams) CheckAndSetDefaults() error { if p.W > maxSize || p.W < minSize { p.W = teleport.DefaultTerminalWidth } if p.H > maxSize || p.H < minSize { p.H = teleport.DefaultTerminalHeight } return nil }
[ "func", "(", "p", "*", "PTYReqParams", ")", "CheckAndSetDefaults", "(", ")", "error", "{", "if", "p", ".", "W", ">", "maxSize", "||", "p", ".", "W", "<", "minSize", "{", "p", ".", "W", "=", "teleport", ".", "DefaultTerminalWidth", "\n", "}", "\n", "if", "p", ".", "H", ">", "maxSize", "||", "p", ".", "H", "<", "minSize", "{", "p", ".", "H", "=", "teleport", ".", "DefaultTerminalHeight", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// CheckAndSetDefaults validates PTY parameters and ensures parameters // are within default values.
[ "CheckAndSetDefaults", "validates", "PTY", "parameters", "and", "ensures", "parameters", "are", "within", "default", "values", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/req.go#L115-L124
train
gravitational/teleport
lib/kube/proxy/portforward.go
removeStreamPair
func (h *portForwardProxy) removeStreamPair(requestID string) { h.streamPairsLock.Lock() defer h.streamPairsLock.Unlock() delete(h.streamPairs, requestID) }
go
func (h *portForwardProxy) removeStreamPair(requestID string) { h.streamPairsLock.Lock() defer h.streamPairsLock.Unlock() delete(h.streamPairs, requestID) }
[ "func", "(", "h", "*", "portForwardProxy", ")", "removeStreamPair", "(", "requestID", "string", ")", "{", "h", ".", "streamPairsLock", ".", "Lock", "(", ")", "\n", "defer", "h", ".", "streamPairsLock", ".", "Unlock", "(", ")", "\n", "delete", "(", "h", ".", "streamPairs", ",", "requestID", ")", "\n", "}" ]
// removeStreamPair removes the stream pair identified by requestID from streamPairs.
[ "removeStreamPair", "removes", "the", "stream", "pair", "identified", "by", "requestID", "from", "streamPairs", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/portforward.go#L284-L289
train
gravitational/teleport
lib/kube/proxy/portforward.go
run
func (h *portForwardProxy) run() { h.Debugf("Waiting for port forward streams.") for { select { case <-h.context.Done(): h.Debugf("Context is closing, returning.") return case <-h.sourceConn.CloseChan(): h.Debugf("Upgraded connection closed.") return case stream := <-h.streamChan: requestID, err := h.requestID(stream) if err != nil { h.Warningf("Failed to parse request id: %v.", err) return } streamType := stream.Headers().Get(StreamType) h.Debugf("Received new stream %v of type %v.", requestID, streamType) p, created := h.getStreamPair(requestID) if created { go h.monitorStreamPair(p, time.After(h.streamCreationTimeout)) } if complete, err := p.add(stream); err != nil { msg := fmt.Sprintf("error processing stream for request %s: %v", requestID, err) p.printError(msg) } else if complete { go h.portForward(p) } } } }
go
func (h *portForwardProxy) run() { h.Debugf("Waiting for port forward streams.") for { select { case <-h.context.Done(): h.Debugf("Context is closing, returning.") return case <-h.sourceConn.CloseChan(): h.Debugf("Upgraded connection closed.") return case stream := <-h.streamChan: requestID, err := h.requestID(stream) if err != nil { h.Warningf("Failed to parse request id: %v.", err) return } streamType := stream.Headers().Get(StreamType) h.Debugf("Received new stream %v of type %v.", requestID, streamType) p, created := h.getStreamPair(requestID) if created { go h.monitorStreamPair(p, time.After(h.streamCreationTimeout)) } if complete, err := p.add(stream); err != nil { msg := fmt.Sprintf("error processing stream for request %s: %v", requestID, err) p.printError(msg) } else if complete { go h.portForward(p) } } } }
[ "func", "(", "h", "*", "portForwardProxy", ")", "run", "(", ")", "{", "h", ".", "Debugf", "(", "\"Waiting for port forward streams.\"", ")", "\n", "for", "{", "select", "{", "case", "<-", "h", ".", "context", ".", "Done", "(", ")", ":", "h", ".", "Debugf", "(", "\"Context is closing, returning.\"", ")", "\n", "return", "\n", "case", "<-", "h", ".", "sourceConn", ".", "CloseChan", "(", ")", ":", "h", ".", "Debugf", "(", "\"Upgraded connection closed.\"", ")", "\n", "return", "\n", "case", "stream", ":=", "<-", "h", ".", "streamChan", ":", "requestID", ",", "err", ":=", "h", ".", "requestID", "(", "stream", ")", "\n", "if", "err", "!=", "nil", "{", "h", ".", "Warningf", "(", "\"Failed to parse request id: %v.\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "streamType", ":=", "stream", ".", "Headers", "(", ")", ".", "Get", "(", "StreamType", ")", "\n", "h", ".", "Debugf", "(", "\"Received new stream %v of type %v.\"", ",", "requestID", ",", "streamType", ")", "\n", "p", ",", "created", ":=", "h", ".", "getStreamPair", "(", "requestID", ")", "\n", "if", "created", "{", "go", "h", ".", "monitorStreamPair", "(", "p", ",", "time", ".", "After", "(", "h", ".", "streamCreationTimeout", ")", ")", "\n", "}", "\n", "if", "complete", ",", "err", ":=", "p", ".", "add", "(", "stream", ")", ";", "err", "!=", "nil", "{", "msg", ":=", "fmt", ".", "Sprintf", "(", "\"error processing stream for request %s: %v\"", ",", "requestID", ",", "err", ")", "\n", "p", ".", "printError", "(", "msg", ")", "\n", "}", "else", "if", "complete", "{", "go", "h", ".", "portForward", "(", "p", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// run is the main loop for the portForwardProxy. It processes new // streams, invoking portForward for each complete stream pair. The loop exits // when the httpstream.Connection is closed.
[ "run", "is", "the", "main", "loop", "for", "the", "portForwardProxy", ".", "It", "processes", "new", "streams", "invoking", "portForward", "for", "each", "complete", "stream", "pair", ".", "The", "loop", "exits", "when", "the", "httpstream", ".", "Connection", "is", "closed", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/portforward.go#L303-L334
train
gravitational/teleport
lib/kube/proxy/portforward.go
portForward
func (h *portForwardProxy) portForward(p *httpStreamPair) { defer p.dataStream.Close() defer p.errorStream.Close() portString := p.dataStream.Headers().Get(PortHeader) port, _ := strconv.ParseInt(portString, 10, 32) h.Debugf("Forwrarding port %v -> %v.", p.requestID, portString) err := h.forwardStreamPair(p, port) h.Debugf("Completed forwrarding port %v -> %v.", p.requestID, portString) if err != nil { msg := fmt.Errorf("error forwarding port %d to pod %s: %v", port, h.podName, err) fmt.Fprint(p.errorStream, msg.Error()) } }
go
func (h *portForwardProxy) portForward(p *httpStreamPair) { defer p.dataStream.Close() defer p.errorStream.Close() portString := p.dataStream.Headers().Get(PortHeader) port, _ := strconv.ParseInt(portString, 10, 32) h.Debugf("Forwrarding port %v -> %v.", p.requestID, portString) err := h.forwardStreamPair(p, port) h.Debugf("Completed forwrarding port %v -> %v.", p.requestID, portString) if err != nil { msg := fmt.Errorf("error forwarding port %d to pod %s: %v", port, h.podName, err) fmt.Fprint(p.errorStream, msg.Error()) } }
[ "func", "(", "h", "*", "portForwardProxy", ")", "portForward", "(", "p", "*", "httpStreamPair", ")", "{", "defer", "p", ".", "dataStream", ".", "Close", "(", ")", "\n", "defer", "p", ".", "errorStream", ".", "Close", "(", ")", "\n", "portString", ":=", "p", ".", "dataStream", ".", "Headers", "(", ")", ".", "Get", "(", "PortHeader", ")", "\n", "port", ",", "_", ":=", "strconv", ".", "ParseInt", "(", "portString", ",", "10", ",", "32", ")", "\n", "h", ".", "Debugf", "(", "\"Forwrarding port %v -> %v.\"", ",", "p", ".", "requestID", ",", "portString", ")", "\n", "err", ":=", "h", ".", "forwardStreamPair", "(", "p", ",", "port", ")", "\n", "h", ".", "Debugf", "(", "\"Completed forwrarding port %v -> %v.\"", ",", "p", ".", "requestID", ",", "portString", ")", "\n", "if", "err", "!=", "nil", "{", "msg", ":=", "fmt", ".", "Errorf", "(", "\"error forwarding port %d to pod %s: %v\"", ",", "port", ",", "h", ".", "podName", ",", "err", ")", "\n", "fmt", ".", "Fprint", "(", "p", ".", "errorStream", ",", "msg", ".", "Error", "(", ")", ")", "\n", "}", "\n", "}" ]
// portForward invokes the portForwardProxy's forwarder.PortForward // function for the given stream pair.
[ "portForward", "invokes", "the", "portForwardProxy", "s", "forwarder", ".", "PortForward", "function", "for", "the", "given", "stream", "pair", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/portforward.go#L338-L353
train
gravitational/teleport
lib/kube/proxy/portforward.go
add
func (p *httpStreamPair) add(stream httpstream.Stream) (bool, error) { p.lock.Lock() defer p.lock.Unlock() switch stream.Headers().Get(StreamType) { case StreamTypeError: if p.errorStream != nil { return false, trace.BadParameter("error stream already assigned") } p.errorStream = stream case StreamTypeData: if p.dataStream != nil { return false, trace.BadParameter("data stream already assigned") } p.dataStream = stream } complete := p.errorStream != nil && p.dataStream != nil if complete { close(p.complete) } return complete, nil }
go
func (p *httpStreamPair) add(stream httpstream.Stream) (bool, error) { p.lock.Lock() defer p.lock.Unlock() switch stream.Headers().Get(StreamType) { case StreamTypeError: if p.errorStream != nil { return false, trace.BadParameter("error stream already assigned") } p.errorStream = stream case StreamTypeData: if p.dataStream != nil { return false, trace.BadParameter("data stream already assigned") } p.dataStream = stream } complete := p.errorStream != nil && p.dataStream != nil if complete { close(p.complete) } return complete, nil }
[ "func", "(", "p", "*", "httpStreamPair", ")", "add", "(", "stream", "httpstream", ".", "Stream", ")", "(", "bool", ",", "error", ")", "{", "p", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "lock", ".", "Unlock", "(", ")", "\n", "switch", "stream", ".", "Headers", "(", ")", ".", "Get", "(", "StreamType", ")", "{", "case", "StreamTypeError", ":", "if", "p", ".", "errorStream", "!=", "nil", "{", "return", "false", ",", "trace", ".", "BadParameter", "(", "\"error stream already assigned\"", ")", "\n", "}", "\n", "p", ".", "errorStream", "=", "stream", "\n", "case", "StreamTypeData", ":", "if", "p", ".", "dataStream", "!=", "nil", "{", "return", "false", ",", "trace", ".", "BadParameter", "(", "\"data stream already assigned\"", ")", "\n", "}", "\n", "p", ".", "dataStream", "=", "stream", "\n", "}", "\n", "complete", ":=", "p", ".", "errorStream", "!=", "nil", "&&", "p", ".", "dataStream", "!=", "nil", "\n", "if", "complete", "{", "close", "(", "p", ".", "complete", ")", "\n", "}", "\n", "return", "complete", ",", "nil", "\n", "}" ]
// add adds the stream to the httpStreamPair. If the pair already // contains a stream for the new stream's type, an error is returned. add // returns true if both the data and error streams for this pair have been // received.
[ "add", "adds", "the", "stream", "to", "the", "httpStreamPair", ".", "If", "the", "pair", "already", "contains", "a", "stream", "for", "the", "new", "stream", "s", "type", "an", "error", "is", "returned", ".", "add", "returns", "true", "if", "both", "the", "data", "and", "error", "streams", "for", "this", "pair", "have", "been", "received", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/portforward.go#L377-L399
train
gravitational/teleport
lib/utils/replace.go
SliceMatchesRegex
func SliceMatchesRegex(input string, expressions []string) (bool, error) { for _, expression := range expressions { if !strings.HasPrefix(expression, "^") || !strings.HasSuffix(expression, "$") { // replace glob-style wildcards with regexp wildcards // for plain strings, and quote all characters that could // be interpreted in regular expression expression = "^" + GlobToRegexp(expression) + "$" } expr, err := regexp.Compile(expression) if err != nil { return false, trace.BadParameter(err.Error()) } // Since the expression is always surrounded by ^ and $ this is an exact // match for either a a plain string (for example ^hello$) or for a regexp // (for example ^hel*o$). if expr.MatchString(input) { return true, nil } } return false, nil }
go
func SliceMatchesRegex(input string, expressions []string) (bool, error) { for _, expression := range expressions { if !strings.HasPrefix(expression, "^") || !strings.HasSuffix(expression, "$") { // replace glob-style wildcards with regexp wildcards // for plain strings, and quote all characters that could // be interpreted in regular expression expression = "^" + GlobToRegexp(expression) + "$" } expr, err := regexp.Compile(expression) if err != nil { return false, trace.BadParameter(err.Error()) } // Since the expression is always surrounded by ^ and $ this is an exact // match for either a a plain string (for example ^hello$) or for a regexp // (for example ^hel*o$). if expr.MatchString(input) { return true, nil } } return false, nil }
[ "func", "SliceMatchesRegex", "(", "input", "string", ",", "expressions", "[", "]", "string", ")", "(", "bool", ",", "error", ")", "{", "for", "_", ",", "expression", ":=", "range", "expressions", "{", "if", "!", "strings", ".", "HasPrefix", "(", "expression", ",", "\"^\"", ")", "||", "!", "strings", ".", "HasSuffix", "(", "expression", ",", "\"$\"", ")", "{", "expression", "=", "\"^\"", "+", "GlobToRegexp", "(", "expression", ")", "+", "\"$\"", "\n", "}", "\n", "expr", ",", "err", ":=", "regexp", ".", "Compile", "(", "expression", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "trace", ".", "BadParameter", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "if", "expr", ".", "MatchString", "(", "input", ")", "{", "return", "true", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "false", ",", "nil", "\n", "}" ]
// SliceMatchesRegex checks if input matches any of the expressions. The // match is always evaluated as a regex either an exact match or regexp.
[ "SliceMatchesRegex", "checks", "if", "input", "matches", "any", "of", "the", "expressions", ".", "The", "match", "is", "always", "evaluated", "as", "a", "regex", "either", "an", "exact", "match", "or", "regexp", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/replace.go#L51-L74
train