repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
gravitational/teleport
lib/services/local/users.go
GetSAMLConnector
func (s *IdentityService) GetSAMLConnector(name string, withSecrets bool) (services.SAMLConnector, error) { if name == "" { return nil, trace.BadParameter("missing parameter name") } item, err := s.Get(context.TODO(), backend.Key(webPrefix, connectorsPrefix, samlPrefix, connectorsPrefix, name)) if err != nil { if trace.IsNotFound(err) { return nil, trace.NotFound("SAML connector %q is not configured", name) } return nil, trace.Wrap(err) } conn, err := services.GetSAMLConnectorMarshaler().UnmarshalSAMLConnector( item.Value, services.WithExpires(item.Expires)) if err != nil { return nil, trace.Wrap(err) } if !withSecrets { keyPair := conn.GetSigningKeyPair() if keyPair != nil { keyPair.PrivateKey = "" conn.SetSigningKeyPair(keyPair) } } return conn, nil }
go
func (s *IdentityService) GetSAMLConnector(name string, withSecrets bool) (services.SAMLConnector, error) { if name == "" { return nil, trace.BadParameter("missing parameter name") } item, err := s.Get(context.TODO(), backend.Key(webPrefix, connectorsPrefix, samlPrefix, connectorsPrefix, name)) if err != nil { if trace.IsNotFound(err) { return nil, trace.NotFound("SAML connector %q is not configured", name) } return nil, trace.Wrap(err) } conn, err := services.GetSAMLConnectorMarshaler().UnmarshalSAMLConnector( item.Value, services.WithExpires(item.Expires)) if err != nil { return nil, trace.Wrap(err) } if !withSecrets { keyPair := conn.GetSigningKeyPair() if keyPair != nil { keyPair.PrivateKey = "" conn.SetSigningKeyPair(keyPair) } } return conn, nil }
[ "func", "(", "s", "*", "IdentityService", ")", "GetSAMLConnector", "(", "name", "string", ",", "withSecrets", "bool", ")", "(", "services", ".", "SAMLConnector", ",", "error", ")", "{", "if", "name", "==", "\"", "\"", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n", "item", ",", "err", ":=", "s", ".", "Get", "(", "context", ".", "TODO", "(", ")", ",", "backend", ".", "Key", "(", "webPrefix", ",", "connectorsPrefix", ",", "samlPrefix", ",", "connectorsPrefix", ",", "name", ")", ")", "\n", "if", "err", "!=", "nil", "{", "if", "trace", ".", "IsNotFound", "(", "err", ")", "{", "return", "nil", ",", "trace", ".", "NotFound", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "conn", ",", "err", ":=", "services", ".", "GetSAMLConnectorMarshaler", "(", ")", ".", "UnmarshalSAMLConnector", "(", "item", ".", "Value", ",", "services", ".", "WithExpires", "(", "item", ".", "Expires", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "!", "withSecrets", "{", "keyPair", ":=", "conn", ".", "GetSigningKeyPair", "(", ")", "\n", "if", "keyPair", "!=", "nil", "{", "keyPair", ".", "PrivateKey", "=", "\"", "\"", "\n", "conn", ".", "SetSigningKeyPair", "(", "keyPair", ")", "\n", "}", "\n", "}", "\n", "return", "conn", ",", "nil", "\n", "}" ]
// GetSAMLConnector returns SAML connector data, // withSecrets includes or excludes secrets from return results
[ "GetSAMLConnector", "returns", "SAML", "connector", "data", "withSecrets", "includes", "or", "excludes", "secrets", "from", "return", "results" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L912-L936
train
gravitational/teleport
lib/services/local/users.go
GetSAMLConnectors
func (s *IdentityService) GetSAMLConnectors(withSecrets bool) ([]services.SAMLConnector, error) { startKey := backend.Key(webPrefix, connectorsPrefix, samlPrefix, connectorsPrefix) result, err := s.GetRange(context.TODO(), startKey, backend.RangeEnd(startKey), backend.NoLimit) if err != nil { return nil, trace.Wrap(err) } connectors := make([]services.SAMLConnector, len(result.Items)) for i, item := range result.Items { conn, err := services.GetSAMLConnectorMarshaler().UnmarshalSAMLConnector( item.Value, services.WithExpires(item.Expires)) if err != nil { return nil, trace.Wrap(err) } if !withSecrets { keyPair := conn.GetSigningKeyPair() if keyPair != nil { keyPair.PrivateKey = "" conn.SetSigningKeyPair(keyPair) } } connectors[i] = conn } return connectors, nil }
go
func (s *IdentityService) GetSAMLConnectors(withSecrets bool) ([]services.SAMLConnector, error) { startKey := backend.Key(webPrefix, connectorsPrefix, samlPrefix, connectorsPrefix) result, err := s.GetRange(context.TODO(), startKey, backend.RangeEnd(startKey), backend.NoLimit) if err != nil { return nil, trace.Wrap(err) } connectors := make([]services.SAMLConnector, len(result.Items)) for i, item := range result.Items { conn, err := services.GetSAMLConnectorMarshaler().UnmarshalSAMLConnector( item.Value, services.WithExpires(item.Expires)) if err != nil { return nil, trace.Wrap(err) } if !withSecrets { keyPair := conn.GetSigningKeyPair() if keyPair != nil { keyPair.PrivateKey = "" conn.SetSigningKeyPair(keyPair) } } connectors[i] = conn } return connectors, nil }
[ "func", "(", "s", "*", "IdentityService", ")", "GetSAMLConnectors", "(", "withSecrets", "bool", ")", "(", "[", "]", "services", ".", "SAMLConnector", ",", "error", ")", "{", "startKey", ":=", "backend", ".", "Key", "(", "webPrefix", ",", "connectorsPrefix", ",", "samlPrefix", ",", "connectorsPrefix", ")", "\n", "result", ",", "err", ":=", "s", ".", "GetRange", "(", "context", ".", "TODO", "(", ")", ",", "startKey", ",", "backend", ".", "RangeEnd", "(", "startKey", ")", ",", "backend", ".", "NoLimit", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "connectors", ":=", "make", "(", "[", "]", "services", ".", "SAMLConnector", ",", "len", "(", "result", ".", "Items", ")", ")", "\n", "for", "i", ",", "item", ":=", "range", "result", ".", "Items", "{", "conn", ",", "err", ":=", "services", ".", "GetSAMLConnectorMarshaler", "(", ")", ".", "UnmarshalSAMLConnector", "(", "item", ".", "Value", ",", "services", ".", "WithExpires", "(", "item", ".", "Expires", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "!", "withSecrets", "{", "keyPair", ":=", "conn", ".", "GetSigningKeyPair", "(", ")", "\n", "if", "keyPair", "!=", "nil", "{", "keyPair", ".", "PrivateKey", "=", "\"", "\"", "\n", "conn", ".", "SetSigningKeyPair", "(", "keyPair", ")", "\n", "}", "\n", "}", "\n", "connectors", "[", "i", "]", "=", "conn", "\n", "}", "\n", "return", "connectors", ",", "nil", "\n", "}" ]
// GetSAMLConnectors returns registered connectors // withSecrets includes or excludes private key values from return results
[ "GetSAMLConnectors", "returns", "registered", "connectors", "withSecrets", "includes", "or", "excludes", "private", "key", "values", "from", "return", "results" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L940-L963
train
gravitational/teleport
lib/services/local/users.go
CreateSAMLAuthRequest
func (s *IdentityService) CreateSAMLAuthRequest(req services.SAMLAuthRequest, ttl time.Duration) error { if err := req.Check(); err != nil { return trace.Wrap(err) } value, err := json.Marshal(req) if err != nil { return trace.Wrap(err) } item := backend.Item{ Key: backend.Key(webPrefix, connectorsPrefix, samlPrefix, requestsPrefix, req.ID), Value: value, Expires: backend.Expiry(s.Clock(), ttl), } _, err = s.Create(context.TODO(), item) if err != nil { return trace.Wrap(err) } return nil }
go
func (s *IdentityService) CreateSAMLAuthRequest(req services.SAMLAuthRequest, ttl time.Duration) error { if err := req.Check(); err != nil { return trace.Wrap(err) } value, err := json.Marshal(req) if err != nil { return trace.Wrap(err) } item := backend.Item{ Key: backend.Key(webPrefix, connectorsPrefix, samlPrefix, requestsPrefix, req.ID), Value: value, Expires: backend.Expiry(s.Clock(), ttl), } _, err = s.Create(context.TODO(), item) if err != nil { return trace.Wrap(err) } return nil }
[ "func", "(", "s", "*", "IdentityService", ")", "CreateSAMLAuthRequest", "(", "req", "services", ".", "SAMLAuthRequest", ",", "ttl", "time", ".", "Duration", ")", "error", "{", "if", "err", ":=", "req", ".", "Check", "(", ")", ";", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "value", ",", "err", ":=", "json", ".", "Marshal", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "item", ":=", "backend", ".", "Item", "{", "Key", ":", "backend", ".", "Key", "(", "webPrefix", ",", "connectorsPrefix", ",", "samlPrefix", ",", "requestsPrefix", ",", "req", ".", "ID", ")", ",", "Value", ":", "value", ",", "Expires", ":", "backend", ".", "Expiry", "(", "s", ".", "Clock", "(", ")", ",", "ttl", ")", ",", "}", "\n", "_", ",", "err", "=", "s", ".", "Create", "(", "context", ".", "TODO", "(", ")", ",", "item", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// CreateSAMLAuthRequest creates new auth request
[ "CreateSAMLAuthRequest", "creates", "new", "auth", "request" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L966-L984
train
gravitational/teleport
lib/services/local/users.go
GetSAMLAuthRequest
func (s *IdentityService) GetSAMLAuthRequest(id string) (*services.SAMLAuthRequest, error) { if id == "" { return nil, trace.BadParameter("missing parameter id") } item, err := s.Get(context.TODO(), backend.Key(webPrefix, connectorsPrefix, samlPrefix, requestsPrefix, id)) if err != nil { return nil, trace.Wrap(err) } var req services.SAMLAuthRequest if err := json.Unmarshal(item.Value, &req); err != nil { return nil, trace.Wrap(err) } return &req, nil }
go
func (s *IdentityService) GetSAMLAuthRequest(id string) (*services.SAMLAuthRequest, error) { if id == "" { return nil, trace.BadParameter("missing parameter id") } item, err := s.Get(context.TODO(), backend.Key(webPrefix, connectorsPrefix, samlPrefix, requestsPrefix, id)) if err != nil { return nil, trace.Wrap(err) } var req services.SAMLAuthRequest if err := json.Unmarshal(item.Value, &req); err != nil { return nil, trace.Wrap(err) } return &req, nil }
[ "func", "(", "s", "*", "IdentityService", ")", "GetSAMLAuthRequest", "(", "id", "string", ")", "(", "*", "services", ".", "SAMLAuthRequest", ",", "error", ")", "{", "if", "id", "==", "\"", "\"", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n", "item", ",", "err", ":=", "s", ".", "Get", "(", "context", ".", "TODO", "(", ")", ",", "backend", ".", "Key", "(", "webPrefix", ",", "connectorsPrefix", ",", "samlPrefix", ",", "requestsPrefix", ",", "id", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "var", "req", "services", ".", "SAMLAuthRequest", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "item", ".", "Value", ",", "&", "req", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "&", "req", ",", "nil", "\n", "}" ]
// GetSAMLAuthRequest returns SAML auth request if found
[ "GetSAMLAuthRequest", "returns", "SAML", "auth", "request", "if", "found" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L987-L1000
train
gravitational/teleport
lib/services/local/users.go
GetGithubConnector
func (s *IdentityService) GetGithubConnector(name string, withSecrets bool) (services.GithubConnector, error) { if name == "" { return nil, trace.BadParameter("missing parameter name") } item, err := s.Get(context.TODO(), backend.Key(webPrefix, connectorsPrefix, githubPrefix, connectorsPrefix, name)) if err != nil { if trace.IsNotFound(err) { return nil, trace.NotFound("github connector %q is not configured", name) } return nil, trace.Wrap(err) } connector, err := services.GetGithubConnectorMarshaler().Unmarshal(item.Value) if err != nil { return nil, trace.Wrap(err) } if !withSecrets { connector.SetClientSecret("") } return connector, nil }
go
func (s *IdentityService) GetGithubConnector(name string, withSecrets bool) (services.GithubConnector, error) { if name == "" { return nil, trace.BadParameter("missing parameter name") } item, err := s.Get(context.TODO(), backend.Key(webPrefix, connectorsPrefix, githubPrefix, connectorsPrefix, name)) if err != nil { if trace.IsNotFound(err) { return nil, trace.NotFound("github connector %q is not configured", name) } return nil, trace.Wrap(err) } connector, err := services.GetGithubConnectorMarshaler().Unmarshal(item.Value) if err != nil { return nil, trace.Wrap(err) } if !withSecrets { connector.SetClientSecret("") } return connector, nil }
[ "func", "(", "s", "*", "IdentityService", ")", "GetGithubConnector", "(", "name", "string", ",", "withSecrets", "bool", ")", "(", "services", ".", "GithubConnector", ",", "error", ")", "{", "if", "name", "==", "\"", "\"", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n", "item", ",", "err", ":=", "s", ".", "Get", "(", "context", ".", "TODO", "(", ")", ",", "backend", ".", "Key", "(", "webPrefix", ",", "connectorsPrefix", ",", "githubPrefix", ",", "connectorsPrefix", ",", "name", ")", ")", "\n", "if", "err", "!=", "nil", "{", "if", "trace", ".", "IsNotFound", "(", "err", ")", "{", "return", "nil", ",", "trace", ".", "NotFound", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "connector", ",", "err", ":=", "services", ".", "GetGithubConnectorMarshaler", "(", ")", ".", "Unmarshal", "(", "item", ".", "Value", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "!", "withSecrets", "{", "connector", ".", "SetClientSecret", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "connector", ",", "nil", "\n", "}" ]
// GetGithubConnectot returns a particular Github connector
[ "GetGithubConnectot", "returns", "a", "particular", "Github", "connector" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L1067-L1086
train
gravitational/teleport
lib/services/local/users.go
DeleteGithubConnector
func (s *IdentityService) DeleteGithubConnector(name string) error { if name == "" { return trace.BadParameter("missing parameter name") } return trace.Wrap(s.Delete(context.TODO(), backend.Key(webPrefix, connectorsPrefix, githubPrefix, connectorsPrefix, name))) }
go
func (s *IdentityService) DeleteGithubConnector(name string) error { if name == "" { return trace.BadParameter("missing parameter name") } return trace.Wrap(s.Delete(context.TODO(), backend.Key(webPrefix, connectorsPrefix, githubPrefix, connectorsPrefix, name))) }
[ "func", "(", "s", "*", "IdentityService", ")", "DeleteGithubConnector", "(", "name", "string", ")", "error", "{", "if", "name", "==", "\"", "\"", "{", "return", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "trace", ".", "Wrap", "(", "s", ".", "Delete", "(", "context", ".", "TODO", "(", ")", ",", "backend", ".", "Key", "(", "webPrefix", ",", "connectorsPrefix", ",", "githubPrefix", ",", "connectorsPrefix", ",", "name", ")", ")", ")", "\n", "}" ]
// DeleteGithubConnector deletes the specified connector
[ "DeleteGithubConnector", "deletes", "the", "specified", "connector" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L1089-L1094
train
gravitational/teleport
lib/services/local/users.go
CreateGithubAuthRequest
func (s *IdentityService) CreateGithubAuthRequest(req services.GithubAuthRequest) error { err := req.Check() if err != nil { return trace.Wrap(err) } value, err := json.Marshal(req) if err != nil { return trace.Wrap(err) } item := backend.Item{ Key: backend.Key(webPrefix, connectorsPrefix, githubPrefix, requestsPrefix, req.StateToken), Value: value, Expires: req.Expiry(), } _, err = s.Create(context.TODO(), item) if err != nil { return trace.Wrap(err) } return nil }
go
func (s *IdentityService) CreateGithubAuthRequest(req services.GithubAuthRequest) error { err := req.Check() if err != nil { return trace.Wrap(err) } value, err := json.Marshal(req) if err != nil { return trace.Wrap(err) } item := backend.Item{ Key: backend.Key(webPrefix, connectorsPrefix, githubPrefix, requestsPrefix, req.StateToken), Value: value, Expires: req.Expiry(), } _, err = s.Create(context.TODO(), item) if err != nil { return trace.Wrap(err) } return nil }
[ "func", "(", "s", "*", "IdentityService", ")", "CreateGithubAuthRequest", "(", "req", "services", ".", "GithubAuthRequest", ")", "error", "{", "err", ":=", "req", ".", "Check", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "value", ",", "err", ":=", "json", ".", "Marshal", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "item", ":=", "backend", ".", "Item", "{", "Key", ":", "backend", ".", "Key", "(", "webPrefix", ",", "connectorsPrefix", ",", "githubPrefix", ",", "requestsPrefix", ",", "req", ".", "StateToken", ")", ",", "Value", ":", "value", ",", "Expires", ":", "req", ".", "Expiry", "(", ")", ",", "}", "\n", "_", ",", "err", "=", "s", ".", "Create", "(", "context", ".", "TODO", "(", ")", ",", "item", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// CreateGithubAuthRequest creates a new auth request for Github OAuth2 flow
[ "CreateGithubAuthRequest", "creates", "a", "new", "auth", "request", "for", "Github", "OAuth2", "flow" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L1097-L1116
train
gravitational/teleport
lib/services/local/users.go
GetGithubAuthRequest
func (s *IdentityService) GetGithubAuthRequest(stateToken string) (*services.GithubAuthRequest, error) { if stateToken == "" { return nil, trace.BadParameter("missing parameter stateToken") } item, err := s.Get(context.TODO(), backend.Key(webPrefix, connectorsPrefix, githubPrefix, requestsPrefix, stateToken)) if err != nil { return nil, trace.Wrap(err) } var req services.GithubAuthRequest err = json.Unmarshal(item.Value, &req) if err != nil { return nil, trace.Wrap(err) } return &req, nil }
go
func (s *IdentityService) GetGithubAuthRequest(stateToken string) (*services.GithubAuthRequest, error) { if stateToken == "" { return nil, trace.BadParameter("missing parameter stateToken") } item, err := s.Get(context.TODO(), backend.Key(webPrefix, connectorsPrefix, githubPrefix, requestsPrefix, stateToken)) if err != nil { return nil, trace.Wrap(err) } var req services.GithubAuthRequest err = json.Unmarshal(item.Value, &req) if err != nil { return nil, trace.Wrap(err) } return &req, nil }
[ "func", "(", "s", "*", "IdentityService", ")", "GetGithubAuthRequest", "(", "stateToken", "string", ")", "(", "*", "services", ".", "GithubAuthRequest", ",", "error", ")", "{", "if", "stateToken", "==", "\"", "\"", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n", "item", ",", "err", ":=", "s", ".", "Get", "(", "context", ".", "TODO", "(", ")", ",", "backend", ".", "Key", "(", "webPrefix", ",", "connectorsPrefix", ",", "githubPrefix", ",", "requestsPrefix", ",", "stateToken", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "var", "req", "services", ".", "GithubAuthRequest", "\n", "err", "=", "json", ".", "Unmarshal", "(", "item", ".", "Value", ",", "&", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "&", "req", ",", "nil", "\n", "}" ]
// GetGithubAuthRequest retrieves Github auth request by the token
[ "GetGithubAuthRequest", "retrieves", "Github", "auth", "request", "by", "the", "token" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L1119-L1133
train
gravitational/teleport
lib/services/server.go
ServersToV1
func ServersToV1(in []Server) []ServerV1 { out := make([]ServerV1, len(in)) for i := range in { out[i] = *(in[i].V1()) } return out }
go
func ServersToV1(in []Server) []ServerV1 { out := make([]ServerV1, len(in)) for i := range in { out[i] = *(in[i].V1()) } return out }
[ "func", "ServersToV1", "(", "in", "[", "]", "Server", ")", "[", "]", "ServerV1", "{", "out", ":=", "make", "(", "[", "]", "ServerV1", ",", "len", "(", "in", ")", ")", "\n", "for", "i", ":=", "range", "in", "{", "out", "[", "i", "]", "=", "*", "(", "in", "[", "i", "]", ".", "V1", "(", ")", ")", "\n", "}", "\n", "return", "out", "\n", "}" ]
// ServersToV1 converts list of servers to slice of V1 style ones
[ "ServersToV1", "converts", "list", "of", "servers", "to", "slice", "of", "V1", "style", "ones" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/server.go#L81-L87
train
gravitational/teleport
lib/services/server.go
GetCmdLabels
func (s *ServerV2) GetCmdLabels() map[string]CommandLabel { if s.Spec.CmdLabels == nil { return nil } out := make(map[string]CommandLabel, len(s.Spec.CmdLabels)) for key := range s.Spec.CmdLabels { val := s.Spec.CmdLabels[key] out[key] = &val } return out }
go
func (s *ServerV2) GetCmdLabels() map[string]CommandLabel { if s.Spec.CmdLabels == nil { return nil } out := make(map[string]CommandLabel, len(s.Spec.CmdLabels)) for key := range s.Spec.CmdLabels { val := s.Spec.CmdLabels[key] out[key] = &val } return out }
[ "func", "(", "s", "*", "ServerV2", ")", "GetCmdLabels", "(", ")", "map", "[", "string", "]", "CommandLabel", "{", "if", "s", ".", "Spec", ".", "CmdLabels", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "out", ":=", "make", "(", "map", "[", "string", "]", "CommandLabel", ",", "len", "(", "s", ".", "Spec", ".", "CmdLabels", ")", ")", "\n", "for", "key", ":=", "range", "s", ".", "Spec", ".", "CmdLabels", "{", "val", ":=", "s", ".", "Spec", ".", "CmdLabels", "[", "key", "]", "\n", "out", "[", "key", "]", "=", "&", "val", "\n", "}", "\n", "return", "out", "\n", "}" ]
// GetCmdLabels returns command labels
[ "GetCmdLabels", "returns", "command", "labels" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/server.go#L232-L242
train
gravitational/teleport
lib/services/server.go
MatchAgainst
func (s *ServerV2) MatchAgainst(labels map[string]string) bool { if labels != nil { myLabels := s.GetAllLabels() for key, value := range labels { if myLabels[key] != value { return false } } } return true }
go
func (s *ServerV2) MatchAgainst(labels map[string]string) bool { if labels != nil { myLabels := s.GetAllLabels() for key, value := range labels { if myLabels[key] != value { return false } } } return true }
[ "func", "(", "s", "*", "ServerV2", ")", "MatchAgainst", "(", "labels", "map", "[", "string", "]", "string", ")", "bool", "{", "if", "labels", "!=", "nil", "{", "myLabels", ":=", "s", ".", "GetAllLabels", "(", ")", "\n", "for", "key", ",", "value", ":=", "range", "labels", "{", "if", "myLabels", "[", "key", "]", "!=", "value", "{", "return", "false", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// MatchAgainst takes a map of labels and returns True if this server // has ALL of them // // Any server matches against an empty label set
[ "MatchAgainst", "takes", "a", "map", "of", "labels", "and", "returns", "True", "if", "this", "server", "has", "ALL", "of", "them", "Any", "server", "matches", "against", "an", "empty", "label", "set" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/server.go#L270-L280
train
gravitational/teleport
lib/services/server.go
LabelsString
func (s *ServerV2) LabelsString() string { labels := []string{} for key, val := range s.Metadata.Labels { labels = append(labels, fmt.Sprintf("%s=%s", key, val)) } for key, val := range s.Spec.CmdLabels { labels = append(labels, fmt.Sprintf("%s=%s", key, val.Result)) } sort.Strings(labels) return strings.Join(labels, ",") }
go
func (s *ServerV2) LabelsString() string { labels := []string{} for key, val := range s.Metadata.Labels { labels = append(labels, fmt.Sprintf("%s=%s", key, val)) } for key, val := range s.Spec.CmdLabels { labels = append(labels, fmt.Sprintf("%s=%s", key, val.Result)) } sort.Strings(labels) return strings.Join(labels, ",") }
[ "func", "(", "s", "*", "ServerV2", ")", "LabelsString", "(", ")", "string", "{", "labels", ":=", "[", "]", "string", "{", "}", "\n", "for", "key", ",", "val", ":=", "range", "s", ".", "Metadata", ".", "Labels", "{", "labels", "=", "append", "(", "labels", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "key", ",", "val", ")", ")", "\n", "}", "\n", "for", "key", ",", "val", ":=", "range", "s", ".", "Spec", ".", "CmdLabels", "{", "labels", "=", "append", "(", "labels", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "key", ",", "val", ".", "Result", ")", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "labels", ")", "\n", "return", "strings", ".", "Join", "(", "labels", ",", "\"", "\"", ")", "\n", "}" ]
// LabelsString returns a comma separated string with all node's labels
[ "LabelsString", "returns", "a", "comma", "separated", "string", "with", "all", "node", "s", "labels" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/server.go#L283-L293
train
gravitational/teleport
lib/services/server.go
CmdLabelMapsEqual
func CmdLabelMapsEqual(a, b map[string]CommandLabel) bool { if len(a) != len(b) { return false } for key, val := range a { val2, ok := b[key] if !ok { return false } if !val.Equals(val2) { return false } } return true }
go
func CmdLabelMapsEqual(a, b map[string]CommandLabel) bool { if len(a) != len(b) { return false } for key, val := range a { val2, ok := b[key] if !ok { return false } if !val.Equals(val2) { return false } } return true }
[ "func", "CmdLabelMapsEqual", "(", "a", ",", "b", "map", "[", "string", "]", "CommandLabel", ")", "bool", "{", "if", "len", "(", "a", ")", "!=", "len", "(", "b", ")", "{", "return", "false", "\n", "}", "\n", "for", "key", ",", "val", ":=", "range", "a", "{", "val2", ",", "ok", ":=", "b", "[", "key", "]", "\n", "if", "!", "ok", "{", "return", "false", "\n", "}", "\n", "if", "!", "val", ".", "Equals", "(", "val2", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// CmdLabelMapsEqual compares two maps with command labels, // returns true if label sets are equal
[ "CmdLabelMapsEqual", "compares", "two", "maps", "with", "command", "labels", "returns", "true", "if", "label", "sets", "are", "equal" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/server.go#L353-L367
train
gravitational/teleport
lib/services/server.go
LabelsToV2
func LabelsToV2(labels map[string]CommandLabel) map[string]CommandLabelV2 { out := make(map[string]CommandLabelV2, len(labels)) for key, val := range labels { out[key] = CommandLabelV2{ Period: NewDuration(val.GetPeriod()), Result: val.GetResult(), Command: val.GetCommand(), } } return out }
go
func LabelsToV2(labels map[string]CommandLabel) map[string]CommandLabelV2 { out := make(map[string]CommandLabelV2, len(labels)) for key, val := range labels { out[key] = CommandLabelV2{ Period: NewDuration(val.GetPeriod()), Result: val.GetResult(), Command: val.GetCommand(), } } return out }
[ "func", "LabelsToV2", "(", "labels", "map", "[", "string", "]", "CommandLabel", ")", "map", "[", "string", "]", "CommandLabelV2", "{", "out", ":=", "make", "(", "map", "[", "string", "]", "CommandLabelV2", ",", "len", "(", "labels", ")", ")", "\n", "for", "key", ",", "val", ":=", "range", "labels", "{", "out", "[", "key", "]", "=", "CommandLabelV2", "{", "Period", ":", "NewDuration", "(", "val", ".", "GetPeriod", "(", ")", ")", ",", "Result", ":", "val", ".", "GetResult", "(", ")", ",", "Command", ":", "val", ".", "GetCommand", "(", ")", ",", "}", "\n", "}", "\n", "return", "out", "\n", "}" ]
// LabelsToV2 converts labels from interface to V2 spec
[ "LabelsToV2", "converts", "labels", "from", "interface", "to", "V2", "spec" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/server.go#L449-L459
train
gravitational/teleport
lib/services/server.go
Equals
func (c *CommandLabelV2) Equals(other CommandLabel) bool { if c.GetPeriod() != other.GetPeriod() { return false } if c.GetResult() != other.GetResult() { return false } if !utils.StringSlicesEqual(c.GetCommand(), other.GetCommand()) { return false } return true }
go
func (c *CommandLabelV2) Equals(other CommandLabel) bool { if c.GetPeriod() != other.GetPeriod() { return false } if c.GetResult() != other.GetResult() { return false } if !utils.StringSlicesEqual(c.GetCommand(), other.GetCommand()) { return false } return true }
[ "func", "(", "c", "*", "CommandLabelV2", ")", "Equals", "(", "other", "CommandLabel", ")", "bool", "{", "if", "c", ".", "GetPeriod", "(", ")", "!=", "other", ".", "GetPeriod", "(", ")", "{", "return", "false", "\n", "}", "\n", "if", "c", ".", "GetResult", "(", ")", "!=", "other", ".", "GetResult", "(", ")", "{", "return", "false", "\n", "}", "\n", "if", "!", "utils", ".", "StringSlicesEqual", "(", "c", ".", "GetCommand", "(", ")", ",", "other", ".", "GetCommand", "(", ")", ")", "{", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}" ]
// Equals returns true if labels are equal, false otherwise
[ "Equals", "returns", "true", "if", "labels", "are", "equal", "false", "otherwise" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/server.go#L482-L493
train
gravitational/teleport
lib/services/server.go
Clone
func (c *CommandLabelV2) Clone() CommandLabel { command := make([]string, len(c.Command)) copy(command, c.Command) return &CommandLabelV2{ Command: command, Period: c.Period, Result: c.Result, } }
go
func (c *CommandLabelV2) Clone() CommandLabel { command := make([]string, len(c.Command)) copy(command, c.Command) return &CommandLabelV2{ Command: command, Period: c.Period, Result: c.Result, } }
[ "func", "(", "c", "*", "CommandLabelV2", ")", "Clone", "(", ")", "CommandLabel", "{", "command", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "c", ".", "Command", ")", ")", "\n", "copy", "(", "command", ",", "c", ".", "Command", ")", "\n", "return", "&", "CommandLabelV2", "{", "Command", ":", "command", ",", "Period", ":", "c", ".", "Period", ",", "Result", ":", "c", ".", "Result", ",", "}", "\n", "}" ]
// Clone returns non-shallow copy of the label
[ "Clone", "returns", "non", "-", "shallow", "copy", "of", "the", "label" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/server.go#L496-L504
train
gravitational/teleport
lib/services/server.go
SetPeriod
func (c *CommandLabelV2) SetPeriod(p time.Duration) { c.Period = Duration(p) }
go
func (c *CommandLabelV2) SetPeriod(p time.Duration) { c.Period = Duration(p) }
[ "func", "(", "c", "*", "CommandLabelV2", ")", "SetPeriod", "(", "p", "time", ".", "Duration", ")", "{", "c", ".", "Period", "=", "Duration", "(", "p", ")", "\n", "}" ]
// SetPeriod sets label period
[ "SetPeriod", "sets", "label", "period" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/server.go#L512-L514
train
gravitational/teleport
lib/services/server.go
Clone
func (c *CommandLabels) Clone() CommandLabels { out := make(CommandLabels, len(*c)) for name, label := range *c { out[name] = label.Clone() } return out }
go
func (c *CommandLabels) Clone() CommandLabels { out := make(CommandLabels, len(*c)) for name, label := range *c { out[name] = label.Clone() } return out }
[ "func", "(", "c", "*", "CommandLabels", ")", "Clone", "(", ")", "CommandLabels", "{", "out", ":=", "make", "(", "CommandLabels", ",", "len", "(", "*", "c", ")", ")", "\n", "for", "name", ",", "label", ":=", "range", "*", "c", "{", "out", "[", "name", "]", "=", "label", ".", "Clone", "(", ")", "\n", "}", "\n", "return", "out", "\n", "}" ]
// Clone returns copy of the set
[ "Clone", "returns", "copy", "of", "the", "set" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/server.go#L546-L552
train
gravitational/teleport
lib/services/server.go
SetEnv
func (c *CommandLabels) SetEnv(v string) error { if err := json.Unmarshal([]byte(v), c); err != nil { return trace.Wrap(err, "can not parse Command Labels") } return nil }
go
func (c *CommandLabels) SetEnv(v string) error { if err := json.Unmarshal([]byte(v), c); err != nil { return trace.Wrap(err, "can not parse Command Labels") } return nil }
[ "func", "(", "c", "*", "CommandLabels", ")", "SetEnv", "(", "v", "string", ")", "error", "{", "if", "err", ":=", "json", ".", "Unmarshal", "(", "[", "]", "byte", "(", "v", ")", ",", "c", ")", ";", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// SetEnv sets the value of the label from environment variable
[ "SetEnv", "sets", "the", "value", "of", "the", "label", "from", "environment", "variable" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/server.go#L555-L560
train
gravitational/teleport
lib/services/server.go
GetServerSchema
func GetServerSchema() string { return fmt.Sprintf(V2SchemaTemplate, MetadataSchema, fmt.Sprintf(ServerSpecV2Schema, RotationSchema), DefaultDefinitions) }
go
func GetServerSchema() string { return fmt.Sprintf(V2SchemaTemplate, MetadataSchema, fmt.Sprintf(ServerSpecV2Schema, RotationSchema), DefaultDefinitions) }
[ "func", "GetServerSchema", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "V2SchemaTemplate", ",", "MetadataSchema", ",", "fmt", ".", "Sprintf", "(", "ServerSpecV2Schema", ",", "RotationSchema", ")", ",", "DefaultDefinitions", ")", "\n", "}" ]
// GetServerSchema returns role schema with optionally injected // schema for extensions
[ "GetServerSchema", "returns", "role", "schema", "with", "optionally", "injected", "schema", "for", "extensions" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/server.go#L564-L566
train
gravitational/teleport
lib/services/server.go
UnmarshalServerResource
func UnmarshalServerResource(data []byte, kind string, cfg *MarshalConfig) (Server, error) { if len(data) == 0 { return nil, trace.BadParameter("missing server data") } var h ResourceHeader err := utils.FastUnmarshal(data, &h) if err != nil { return nil, trace.Wrap(err) } switch h.Version { case "": var s ServerV1 err := utils.FastUnmarshal(data, &s) if err != nil { return nil, trace.Wrap(err) } s.Kind = kind v2 := s.V2() if cfg.ID != 0 { v2.SetResourceID(cfg.ID) } if !cfg.Expires.IsZero() { v2.SetExpiry(cfg.Expires) } return v2, nil case V2: var s ServerV2 if cfg.SkipValidation { if err := utils.FastUnmarshal(data, &s); err != nil { return nil, trace.BadParameter(err.Error()) } } else { if err := utils.UnmarshalWithSchema(GetServerSchema(), &s, data); err != nil { return nil, trace.BadParameter(err.Error()) } } s.Kind = kind if err := s.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } if cfg.ID != 0 { s.SetResourceID(cfg.ID) } if !cfg.Expires.IsZero() { s.SetExpiry(cfg.Expires) } return &s, nil } return nil, trace.BadParameter("server resource version %q is not supported", h.Version) }
go
func UnmarshalServerResource(data []byte, kind string, cfg *MarshalConfig) (Server, error) { if len(data) == 0 { return nil, trace.BadParameter("missing server data") } var h ResourceHeader err := utils.FastUnmarshal(data, &h) if err != nil { return nil, trace.Wrap(err) } switch h.Version { case "": var s ServerV1 err := utils.FastUnmarshal(data, &s) if err != nil { return nil, trace.Wrap(err) } s.Kind = kind v2 := s.V2() if cfg.ID != 0 { v2.SetResourceID(cfg.ID) } if !cfg.Expires.IsZero() { v2.SetExpiry(cfg.Expires) } return v2, nil case V2: var s ServerV2 if cfg.SkipValidation { if err := utils.FastUnmarshal(data, &s); err != nil { return nil, trace.BadParameter(err.Error()) } } else { if err := utils.UnmarshalWithSchema(GetServerSchema(), &s, data); err != nil { return nil, trace.BadParameter(err.Error()) } } s.Kind = kind if err := s.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } if cfg.ID != 0 { s.SetResourceID(cfg.ID) } if !cfg.Expires.IsZero() { s.SetExpiry(cfg.Expires) } return &s, nil } return nil, trace.BadParameter("server resource version %q is not supported", h.Version) }
[ "func", "UnmarshalServerResource", "(", "data", "[", "]", "byte", ",", "kind", "string", ",", "cfg", "*", "MarshalConfig", ")", "(", "Server", ",", "error", ")", "{", "if", "len", "(", "data", ")", "==", "0", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n\n", "var", "h", "ResourceHeader", "\n", "err", ":=", "utils", ".", "FastUnmarshal", "(", "data", ",", "&", "h", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "switch", "h", ".", "Version", "{", "case", "\"", "\"", ":", "var", "s", "ServerV1", "\n", "err", ":=", "utils", ".", "FastUnmarshal", "(", "data", ",", "&", "s", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "s", ".", "Kind", "=", "kind", "\n", "v2", ":=", "s", ".", "V2", "(", ")", "\n", "if", "cfg", ".", "ID", "!=", "0", "{", "v2", ".", "SetResourceID", "(", "cfg", ".", "ID", ")", "\n", "}", "\n", "if", "!", "cfg", ".", "Expires", ".", "IsZero", "(", ")", "{", "v2", ".", "SetExpiry", "(", "cfg", ".", "Expires", ")", "\n", "}", "\n", "return", "v2", ",", "nil", "\n", "case", "V2", ":", "var", "s", "ServerV2", "\n\n", "if", "cfg", ".", "SkipValidation", "{", "if", "err", ":=", "utils", ".", "FastUnmarshal", "(", "data", ",", "&", "s", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "}", "else", "{", "if", "err", ":=", "utils", ".", "UnmarshalWithSchema", "(", "GetServerSchema", "(", ")", ",", "&", "s", ",", "data", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "}", "\n", "s", ".", "Kind", "=", "kind", "\n", "if", "err", ":=", "s", ".", "CheckAndSetDefaults", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "cfg", ".", "ID", "!=", "0", "{", "s", ".", "SetResourceID", "(", "cfg", ".", "ID", ")", "\n", "}", "\n", "if", "!", "cfg", ".", "Expires", ".", "IsZero", "(", ")", "{", "s", ".", "SetExpiry", "(", "cfg", ".", "Expires", ")", "\n", "}", "\n", "return", "&", "s", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ",", "h", ".", "Version", ")", "\n", "}" ]
// UnmarshalServerResource unmarshals role from JSON or YAML, // sets defaults and checks the schema
[ "UnmarshalServerResource", "unmarshals", "role", "from", "JSON", "or", "YAML", "sets", "defaults", "and", "checks", "the", "schema" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/server.go#L570-L622
train
gravitational/teleport
lib/services/server.go
UnmarshalServer
func (*TeleportServerMarshaler) UnmarshalServer(bytes []byte, kind string, opts ...MarshalOption) (Server, error) { cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } return UnmarshalServerResource(bytes, kind, cfg) }
go
func (*TeleportServerMarshaler) UnmarshalServer(bytes []byte, kind string, opts ...MarshalOption) (Server, error) { cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } return UnmarshalServerResource(bytes, kind, cfg) }
[ "func", "(", "*", "TeleportServerMarshaler", ")", "UnmarshalServer", "(", "bytes", "[", "]", "byte", ",", "kind", "string", ",", "opts", "...", "MarshalOption", ")", "(", "Server", ",", "error", ")", "{", "cfg", ",", "err", ":=", "collectOptions", "(", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "return", "UnmarshalServerResource", "(", "bytes", ",", "kind", ",", "cfg", ")", "\n", "}" ]
// UnmarshalServer unmarshals server from JSON
[ "UnmarshalServer", "unmarshals", "server", "from", "JSON" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/server.go#L659-L666
train
gravitational/teleport
lib/services/server.go
MarshalServer
func (*TeleportServerMarshaler) MarshalServer(s Server, opts ...MarshalOption) ([]byte, error) { cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } type serverv1 interface { V1() *ServerV1 } type serverv2 interface { V2() *ServerV2 } version := cfg.GetVersion() switch version { case V1: v, ok := s.(serverv1) if !ok { return nil, trace.BadParameter("don't know how to marshal %v", V1) } return utils.FastMarshal(v.V1()) case V2: v, ok := s.(serverv2) 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 (*TeleportServerMarshaler) MarshalServer(s Server, opts ...MarshalOption) ([]byte, error) { cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } type serverv1 interface { V1() *ServerV1 } type serverv2 interface { V2() *ServerV2 } version := cfg.GetVersion() switch version { case V1: v, ok := s.(serverv1) if !ok { return nil, trace.BadParameter("don't know how to marshal %v", V1) } return utils.FastMarshal(v.V1()) case V2: v, ok := s.(serverv2) 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", "(", "*", "TeleportServerMarshaler", ")", "MarshalServer", "(", "s", "Server", ",", "opts", "...", "MarshalOption", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "cfg", ",", "err", ":=", "collectOptions", "(", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "type", "serverv1", "interface", "{", "V1", "(", ")", "*", "ServerV1", "\n", "}", "\n", "type", "serverv2", "interface", "{", "V2", "(", ")", "*", "ServerV2", "\n", "}", "\n", "version", ":=", "cfg", ".", "GetVersion", "(", ")", "\n", "switch", "version", "{", "case", "V1", ":", "v", ",", "ok", ":=", "s", ".", "(", "serverv1", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ",", "V1", ")", "\n", "}", "\n", "return", "utils", ".", "FastMarshal", "(", "v", ".", "V1", "(", ")", ")", "\n", "case", "V2", ":", "v", ",", "ok", ":=", "s", ".", "(", "serverv2", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ",", "V2", ")", "\n", "}", "\n", "v2", ":=", "v", ".", "V2", "(", ")", "\n", "if", "!", "cfg", ".", "PreserveResourceID", "{", "// avoid modifying the original object", "// to prevent unexpected data races", "copy", ":=", "*", "v2", "\n", "copy", ".", "SetResourceID", "(", "0", ")", "\n", "v2", "=", "&", "copy", "\n", "}", "\n", "return", "utils", ".", "FastMarshal", "(", "v2", ")", "\n", "default", ":", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ",", "version", ")", "\n", "}", "\n", "}" ]
// MarshalServer marshals server into JSON.
[ "MarshalServer", "marshals", "server", "into", "JSON", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/server.go#L669-L705
train
gravitational/teleport
lib/services/server.go
UnmarshalServers
func (*TeleportServerMarshaler) UnmarshalServers(bytes []byte) ([]Server, error) { var servers []ServerV2 err := utils.FastUnmarshal(bytes, &servers) if err != nil { return nil, trace.Wrap(err) } out := make([]Server, len(servers)) for i, v := range servers { out[i] = Server(&v) } return out, nil }
go
func (*TeleportServerMarshaler) UnmarshalServers(bytes []byte) ([]Server, error) { var servers []ServerV2 err := utils.FastUnmarshal(bytes, &servers) if err != nil { return nil, trace.Wrap(err) } out := make([]Server, len(servers)) for i, v := range servers { out[i] = Server(&v) } return out, nil }
[ "func", "(", "*", "TeleportServerMarshaler", ")", "UnmarshalServers", "(", "bytes", "[", "]", "byte", ")", "(", "[", "]", "Server", ",", "error", ")", "{", "var", "servers", "[", "]", "ServerV2", "\n\n", "err", ":=", "utils", ".", "FastUnmarshal", "(", "bytes", ",", "&", "servers", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "out", ":=", "make", "(", "[", "]", "Server", ",", "len", "(", "servers", ")", ")", "\n", "for", "i", ",", "v", ":=", "range", "servers", "{", "out", "[", "i", "]", "=", "Server", "(", "&", "v", ")", "\n", "}", "\n", "return", "out", ",", "nil", "\n", "}" ]
// UnmarshalServers is used to unmarshal multiple servers from their // binary representation.
[ "UnmarshalServers", "is", "used", "to", "unmarshal", "multiple", "servers", "from", "their", "binary", "representation", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/server.go#L709-L722
train
gravitational/teleport
lib/services/server.go
MarshalServers
func (*TeleportServerMarshaler) MarshalServers(s []Server) ([]byte, error) { bytes, err := utils.FastMarshal(s) if err != nil { return nil, trace.Wrap(err) } return bytes, nil }
go
func (*TeleportServerMarshaler) MarshalServers(s []Server) ([]byte, error) { bytes, err := utils.FastMarshal(s) if err != nil { return nil, trace.Wrap(err) } return bytes, nil }
[ "func", "(", "*", "TeleportServerMarshaler", ")", "MarshalServers", "(", "s", "[", "]", "Server", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "bytes", ",", "err", ":=", "utils", ".", "FastMarshal", "(", "s", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "return", "bytes", ",", "nil", "\n", "}" ]
// MarshalServers is used to marshal multiple servers to their binary // representation.
[ "MarshalServers", "is", "used", "to", "marshal", "multiple", "servers", "to", "their", "binary", "representation", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/server.go#L726-L733
train
gravitational/teleport
lib/web/ui/cluster.go
NewAvailableClusters
func NewAvailableClusters(currentClusterName string, remoteClusters []reversetunnel.RemoteSite) *AvailableClusters { out := AvailableClusters{} for _, item := range remoteClusters { cluster := Cluster{ Name: item.GetName(), LastConnected: item.GetLastConnected(), Status: item.GetStatus(), } if item.GetName() == currentClusterName { out.Current = cluster } else { out.Trusted = append(out.Trusted, cluster) } } sort.Slice(out.Trusted, func(i, j int) bool { return out.Trusted[i].Name < out.Trusted[j].Name }) return &out }
go
func NewAvailableClusters(currentClusterName string, remoteClusters []reversetunnel.RemoteSite) *AvailableClusters { out := AvailableClusters{} for _, item := range remoteClusters { cluster := Cluster{ Name: item.GetName(), LastConnected: item.GetLastConnected(), Status: item.GetStatus(), } if item.GetName() == currentClusterName { out.Current = cluster } else { out.Trusted = append(out.Trusted, cluster) } } sort.Slice(out.Trusted, func(i, j int) bool { return out.Trusted[i].Name < out.Trusted[j].Name }) return &out }
[ "func", "NewAvailableClusters", "(", "currentClusterName", "string", ",", "remoteClusters", "[", "]", "reversetunnel", ".", "RemoteSite", ")", "*", "AvailableClusters", "{", "out", ":=", "AvailableClusters", "{", "}", "\n", "for", "_", ",", "item", ":=", "range", "remoteClusters", "{", "cluster", ":=", "Cluster", "{", "Name", ":", "item", ".", "GetName", "(", ")", ",", "LastConnected", ":", "item", ".", "GetLastConnected", "(", ")", ",", "Status", ":", "item", ".", "GetStatus", "(", ")", ",", "}", "\n\n", "if", "item", ".", "GetName", "(", ")", "==", "currentClusterName", "{", "out", ".", "Current", "=", "cluster", "\n", "}", "else", "{", "out", ".", "Trusted", "=", "append", "(", "out", ".", "Trusted", ",", "cluster", ")", "\n", "}", "\n", "}", "\n\n", "sort", ".", "Slice", "(", "out", ".", "Trusted", ",", "func", "(", "i", ",", "j", "int", ")", "bool", "{", "return", "out", ".", "Trusted", "[", "i", "]", ".", "Name", "<", "out", ".", "Trusted", "[", "j", "]", ".", "Name", "\n", "}", ")", "\n\n", "return", "&", "out", "\n", "}" ]
// NewAvailableClusters returns all available clusters
[ "NewAvailableClusters", "returns", "all", "available", "clusters" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/ui/cluster.go#L45-L66
train
gravitational/teleport
lib/backend/legacy/import.go
Import
func Import(ctx context.Context, importer Importer, newExporter NewExporterFunc) error { log := logrus.WithFields(logrus.Fields{ trace.Component: teleport.Component(teleport.ComponentMigrate), }) err := func() error { imported, err := importer.Imported(ctx) if err != nil { return trace.Wrap(err) } if imported { log.Debugf("Detected legacy backend, data has already been imported.") return nil } log.Infof("Importing data from legacy backend.") exporter, err := newExporter() if err != nil { return trace.Wrap(err) } defer exporter.Close() items, err := exporter.Export() if err != nil { return trace.Wrap(err) } if err := importer.Import(ctx, items); err != nil { return trace.Wrap(err) } log.Infof("Successfully imported %v items.", len(items)) return nil }() if err != nil { if err := importer.Close(); err != nil { log.Errorf("Failed to close backend: %v.", err) } } return trace.Wrap(err) }
go
func Import(ctx context.Context, importer Importer, newExporter NewExporterFunc) error { log := logrus.WithFields(logrus.Fields{ trace.Component: teleport.Component(teleport.ComponentMigrate), }) err := func() error { imported, err := importer.Imported(ctx) if err != nil { return trace.Wrap(err) } if imported { log.Debugf("Detected legacy backend, data has already been imported.") return nil } log.Infof("Importing data from legacy backend.") exporter, err := newExporter() if err != nil { return trace.Wrap(err) } defer exporter.Close() items, err := exporter.Export() if err != nil { return trace.Wrap(err) } if err := importer.Import(ctx, items); err != nil { return trace.Wrap(err) } log.Infof("Successfully imported %v items.", len(items)) return nil }() if err != nil { if err := importer.Close(); err != nil { log.Errorf("Failed to close backend: %v.", err) } } return trace.Wrap(err) }
[ "func", "Import", "(", "ctx", "context", ".", "Context", ",", "importer", "Importer", ",", "newExporter", "NewExporterFunc", ")", "error", "{", "log", ":=", "logrus", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "trace", ".", "Component", ":", "teleport", ".", "Component", "(", "teleport", ".", "ComponentMigrate", ")", ",", "}", ")", "\n", "err", ":=", "func", "(", ")", "error", "{", "imported", ",", "err", ":=", "importer", ".", "Imported", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "imported", "{", "log", ".", "Debugf", "(", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", "\n", "log", ".", "Infof", "(", "\"", "\"", ")", "\n", "exporter", ",", "err", ":=", "newExporter", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "defer", "exporter", ".", "Close", "(", ")", "\n", "items", ",", "err", ":=", "exporter", ".", "Export", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "err", ":=", "importer", ".", "Import", "(", "ctx", ",", "items", ")", ";", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "log", ".", "Infof", "(", "\"", "\"", ",", "len", "(", "items", ")", ")", "\n", "return", "nil", "\n", "}", "(", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", ":=", "importer", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}" ]
// Import imports backend data into importer unless importer has already // imported data. If Importer has no imported data yet, exporter will // not be initialized. This function can be called many times on the // same importer. Importer will be closed if import has failed.
[ "Import", "imports", "backend", "data", "into", "importer", "unless", "importer", "has", "already", "imported", "data", ".", "If", "Importer", "has", "no", "imported", "data", "yet", "exporter", "will", "not", "be", "initialized", ".", "This", "function", "can", "be", "called", "many", "times", "on", "the", "same", "importer", ".", "Importer", "will", "be", "closed", "if", "import", "has", "failed", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/import.go#L39-L74
train
gravitational/teleport
lib/service/info.go
writeDebugInfo
func writeDebugInfo(w io.Writer) { fmt.Fprintf(w, "Runtime stats\n") runtimeStats(w) fmt.Fprintf(w, "Memory stats\n") memStats(w) fmt.Fprintf(w, "Goroutines\n") goroutineDump(w) }
go
func writeDebugInfo(w io.Writer) { fmt.Fprintf(w, "Runtime stats\n") runtimeStats(w) fmt.Fprintf(w, "Memory stats\n") memStats(w) fmt.Fprintf(w, "Goroutines\n") goroutineDump(w) }
[ "func", "writeDebugInfo", "(", "w", "io", ".", "Writer", ")", "{", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ")", "\n", "runtimeStats", "(", "w", ")", "\n\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ")", "\n", "memStats", "(", "w", ")", "\n\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ")", "\n", "goroutineDump", "(", "w", ")", "\n", "}" ]
// writeDebugInfo writes debugging information // about this process
[ "writeDebugInfo", "writes", "debugging", "information", "about", "this", "process" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/info.go#L33-L42
train
gravitational/teleport
lib/multiplexer/wrappers.go
Read
func (c *Conn) Read(p []byte) (int, error) { return c.reader.Read(p) }
go
func (c *Conn) Read(p []byte) (int, error) { return c.reader.Read(p) }
[ "func", "(", "c", "*", "Conn", ")", "Read", "(", "p", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "return", "c", ".", "reader", ".", "Read", "(", "p", ")", "\n", "}" ]
// Read reads from connection
[ "Read", "reads", "from", "connection" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/multiplexer/wrappers.go#L39-L41
train
gravitational/teleport
lib/multiplexer/wrappers.go
LocalAddr
func (c *Conn) LocalAddr() net.Addr { if c.proxyLine != nil { return &c.proxyLine.Destination } return c.Conn.LocalAddr() }
go
func (c *Conn) LocalAddr() net.Addr { if c.proxyLine != nil { return &c.proxyLine.Destination } return c.Conn.LocalAddr() }
[ "func", "(", "c", "*", "Conn", ")", "LocalAddr", "(", ")", "net", ".", "Addr", "{", "if", "c", ".", "proxyLine", "!=", "nil", "{", "return", "&", "c", ".", "proxyLine", ".", "Destination", "\n", "}", "\n", "return", "c", ".", "Conn", ".", "LocalAddr", "(", ")", "\n", "}" ]
// LocalAddr returns local address of the connection
[ "LocalAddr", "returns", "local", "address", "of", "the", "connection" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/multiplexer/wrappers.go#L44-L49
train
gravitational/teleport
lib/multiplexer/wrappers.go
RemoteAddr
func (c *Conn) RemoteAddr() net.Addr { if c.proxyLine != nil { return &c.proxyLine.Source } return c.Conn.RemoteAddr() }
go
func (c *Conn) RemoteAddr() net.Addr { if c.proxyLine != nil { return &c.proxyLine.Source } return c.Conn.RemoteAddr() }
[ "func", "(", "c", "*", "Conn", ")", "RemoteAddr", "(", ")", "net", ".", "Addr", "{", "if", "c", ".", "proxyLine", "!=", "nil", "{", "return", "&", "c", ".", "proxyLine", ".", "Source", "\n", "}", "\n", "return", "c", ".", "Conn", ".", "RemoteAddr", "(", ")", "\n", "}" ]
// RemoteAddr returns remote address of the connection
[ "RemoteAddr", "returns", "remote", "address", "of", "the", "connection" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/multiplexer/wrappers.go#L52-L57
train
gravitational/teleport
lib/multiplexer/wrappers.go
Accept
func (l *Listener) Accept() (net.Conn, error) { select { case <-l.context.Done(): return nil, trace.ConnectionProblem(nil, "listener is closed") case conn := <-l.connC: if conn == nil { return nil, trace.ConnectionProblem(nil, "listener is closed") } return conn, nil } }
go
func (l *Listener) Accept() (net.Conn, error) { select { case <-l.context.Done(): return nil, trace.ConnectionProblem(nil, "listener is closed") case conn := <-l.connC: if conn == nil { return nil, trace.ConnectionProblem(nil, "listener is closed") } return conn, nil } }
[ "func", "(", "l", "*", "Listener", ")", "Accept", "(", ")", "(", "net", ".", "Conn", ",", "error", ")", "{", "select", "{", "case", "<-", "l", ".", "context", ".", "Done", "(", ")", ":", "return", "nil", ",", "trace", ".", "ConnectionProblem", "(", "nil", ",", "\"", "\"", ")", "\n", "case", "conn", ":=", "<-", "l", ".", "connC", ":", "if", "conn", "==", "nil", "{", "return", "nil", ",", "trace", ".", "ConnectionProblem", "(", "nil", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "conn", ",", "nil", "\n", "}", "\n", "}" ]
// Accept accepts connections from parent multiplexer listener
[ "Accept", "accepts", "connections", "from", "parent", "multiplexer", "listener" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/multiplexer/wrappers.go#L84-L94
train
gravitational/teleport
lib/services/identity.go
Equals
func (i *ExternalIdentity) Equals(other *ExternalIdentity) bool { return i.ConnectorID == other.ConnectorID && i.Username == other.Username }
go
func (i *ExternalIdentity) Equals(other *ExternalIdentity) bool { return i.ConnectorID == other.ConnectorID && i.Username == other.Username }
[ "func", "(", "i", "*", "ExternalIdentity", ")", "Equals", "(", "other", "*", "ExternalIdentity", ")", "bool", "{", "return", "i", ".", "ConnectorID", "==", "other", ".", "ConnectorID", "&&", "i", ".", "Username", "==", "other", ".", "Username", "\n", "}" ]
// Equals returns true if this identity equals to passed one
[ "Equals", "returns", "true", "if", "this", "identity", "equals", "to", "passed", "one" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/identity.go#L257-L259
train
gravitational/teleport
lib/services/identity.go
Check
func (r *GithubAuthRequest) Check() error { if r.ConnectorID == "" { return trace.BadParameter("missing ConnectorID") } if r.StateToken == "" { return trace.BadParameter("missing StateToken") } if len(r.PublicKey) != 0 { _, _, _, _, err := ssh.ParseAuthorizedKey(r.PublicKey) if err != nil { return trace.BadParameter("bad PublicKey: %v", err) } if (r.CertTTL > defaults.MaxCertDuration) || (r.CertTTL < defaults.MinCertDuration) { return trace.BadParameter("wrong CertTTL") } } return nil }
go
func (r *GithubAuthRequest) Check() error { if r.ConnectorID == "" { return trace.BadParameter("missing ConnectorID") } if r.StateToken == "" { return trace.BadParameter("missing StateToken") } if len(r.PublicKey) != 0 { _, _, _, _, err := ssh.ParseAuthorizedKey(r.PublicKey) if err != nil { return trace.BadParameter("bad PublicKey: %v", err) } if (r.CertTTL > defaults.MaxCertDuration) || (r.CertTTL < defaults.MinCertDuration) { return trace.BadParameter("wrong CertTTL") } } return nil }
[ "func", "(", "r", "*", "GithubAuthRequest", ")", "Check", "(", ")", "error", "{", "if", "r", ".", "ConnectorID", "==", "\"", "\"", "{", "return", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "r", ".", "StateToken", "==", "\"", "\"", "{", "return", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "r", ".", "PublicKey", ")", "!=", "0", "{", "_", ",", "_", ",", "_", ",", "_", ",", "err", ":=", "ssh", ".", "ParseAuthorizedKey", "(", "r", ".", "PublicKey", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "BadParameter", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "(", "r", ".", "CertTTL", ">", "defaults", ".", "MaxCertDuration", ")", "||", "(", "r", ".", "CertTTL", "<", "defaults", ".", "MinCertDuration", ")", "{", "return", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Check makes sure the request is valid
[ "Check", "makes", "sure", "the", "request", "is", "valid" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/identity.go#L320-L337
train
gravitational/teleport
lib/services/identity.go
Swap
func (s SortedLoginAttempts) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
go
func (s SortedLoginAttempts) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
[ "func", "(", "s", "SortedLoginAttempts", ")", "Swap", "(", "i", ",", "j", "int", ")", "{", "s", "[", "i", "]", ",", "s", "[", "j", "]", "=", "s", "[", "j", "]", ",", "s", "[", "i", "]", "\n", "}" ]
// Swap swaps two attempts
[ "Swap", "swaps", "two", "attempts" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/identity.go#L491-L493
train
gravitational/teleport
lib/services/identity.go
LastFailed
func LastFailed(x int, attempts []LoginAttempt) bool { var failed int for i := len(attempts) - 1; i >= 0; i-- { if !attempts[i].Success { failed++ } else { return false } if failed >= x { return true } } return false }
go
func LastFailed(x int, attempts []LoginAttempt) bool { var failed int for i := len(attempts) - 1; i >= 0; i-- { if !attempts[i].Success { failed++ } else { return false } if failed >= x { return true } } return false }
[ "func", "LastFailed", "(", "x", "int", ",", "attempts", "[", "]", "LoginAttempt", ")", "bool", "{", "var", "failed", "int", "\n", "for", "i", ":=", "len", "(", "attempts", ")", "-", "1", ";", "i", ">=", "0", ";", "i", "--", "{", "if", "!", "attempts", "[", "i", "]", ".", "Success", "{", "failed", "++", "\n", "}", "else", "{", "return", "false", "\n", "}", "\n", "if", "failed", ">=", "x", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// LastFailed calculates last x successive attempts are failed
[ "LastFailed", "calculates", "last", "x", "successive", "attempts", "are", "failed" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/identity.go#L496-L509
train
gravitational/teleport
lib/web/terminal.go
NewTerminal
func NewTerminal(req TerminalRequest, authProvider AuthProvider, ctx *SessionContext) (*TerminalHandler, error) { // Make sure whatever session is requested is a valid session. _, err := session.ParseID(string(req.SessionID)) if err != nil { return nil, trace.BadParameter("sid: invalid session id") } if req.Login == "" { return nil, trace.BadParameter("login: missing login") } if req.Term.W <= 0 || req.Term.H <= 0 { return nil, trace.BadParameter("term: bad term dimensions") } servers, err := authProvider.GetNodes(req.Namespace, services.SkipValidation()) if err != nil { return nil, trace.Wrap(err) } hostName, hostPort, err := resolveServerHostPort(req.Server, servers) if err != nil { return nil, trace.BadParameter("invalid server name %q: %v", req.Server, err) } return &TerminalHandler{ log: logrus.WithFields(logrus.Fields{ trace.Component: teleport.ComponentWebsocket, }), params: req, ctx: ctx, hostName: hostName, hostPort: hostPort, authProvider: authProvider, encoder: unicode.UTF8.NewEncoder(), decoder: unicode.UTF8.NewDecoder(), }, nil }
go
func NewTerminal(req TerminalRequest, authProvider AuthProvider, ctx *SessionContext) (*TerminalHandler, error) { // Make sure whatever session is requested is a valid session. _, err := session.ParseID(string(req.SessionID)) if err != nil { return nil, trace.BadParameter("sid: invalid session id") } if req.Login == "" { return nil, trace.BadParameter("login: missing login") } if req.Term.W <= 0 || req.Term.H <= 0 { return nil, trace.BadParameter("term: bad term dimensions") } servers, err := authProvider.GetNodes(req.Namespace, services.SkipValidation()) if err != nil { return nil, trace.Wrap(err) } hostName, hostPort, err := resolveServerHostPort(req.Server, servers) if err != nil { return nil, trace.BadParameter("invalid server name %q: %v", req.Server, err) } return &TerminalHandler{ log: logrus.WithFields(logrus.Fields{ trace.Component: teleport.ComponentWebsocket, }), params: req, ctx: ctx, hostName: hostName, hostPort: hostPort, authProvider: authProvider, encoder: unicode.UTF8.NewEncoder(), decoder: unicode.UTF8.NewDecoder(), }, nil }
[ "func", "NewTerminal", "(", "req", "TerminalRequest", ",", "authProvider", "AuthProvider", ",", "ctx", "*", "SessionContext", ")", "(", "*", "TerminalHandler", ",", "error", ")", "{", "// Make sure whatever session is requested is a valid session.", "_", ",", "err", ":=", "session", ".", "ParseID", "(", "string", "(", "req", ".", "SessionID", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "req", ".", "Login", "==", "\"", "\"", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "req", ".", "Term", ".", "W", "<=", "0", "||", "req", ".", "Term", ".", "H", "<=", "0", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n\n", "servers", ",", "err", ":=", "authProvider", ".", "GetNodes", "(", "req", ".", "Namespace", ",", "services", ".", "SkipValidation", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "hostName", ",", "hostPort", ",", "err", ":=", "resolveServerHostPort", "(", "req", ".", "Server", ",", "servers", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ",", "req", ".", "Server", ",", "err", ")", "\n", "}", "\n\n", "return", "&", "TerminalHandler", "{", "log", ":", "logrus", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "trace", ".", "Component", ":", "teleport", ".", "ComponentWebsocket", ",", "}", ")", ",", "params", ":", "req", ",", "ctx", ":", "ctx", ",", "hostName", ":", "hostName", ",", "hostPort", ":", "hostPort", ",", "authProvider", ":", "authProvider", ",", "encoder", ":", "unicode", ".", "UTF8", ".", "NewEncoder", "(", ")", ",", "decoder", ":", "unicode", ".", "UTF8", ".", "NewDecoder", "(", ")", ",", "}", ",", "nil", "\n", "}" ]
// NewTerminal creates a web-based terminal based on WebSockets and returns a // new TerminalHandler.
[ "NewTerminal", "creates", "a", "web", "-", "based", "terminal", "based", "on", "WebSockets", "and", "returns", "a", "new", "TerminalHandler", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/terminal.go#L84-L121
train
gravitational/teleport
lib/web/terminal.go
Close
func (t *TerminalHandler) Close() error { // Close the websocket connection to the client web browser. if t.ws != nil { t.ws.Close() } // Close the SSH connection to the remote node. if t.sshSession != nil { t.sshSession.Close() } // If the terminal handler was closed (most likely due to the *SessionContext // closing) then the stream should be closed as well. t.terminalCancel() return nil }
go
func (t *TerminalHandler) Close() error { // Close the websocket connection to the client web browser. if t.ws != nil { t.ws.Close() } // Close the SSH connection to the remote node. if t.sshSession != nil { t.sshSession.Close() } // If the terminal handler was closed (most likely due to the *SessionContext // closing) then the stream should be closed as well. t.terminalCancel() return nil }
[ "func", "(", "t", "*", "TerminalHandler", ")", "Close", "(", ")", "error", "{", "// Close the websocket connection to the client web browser.", "if", "t", ".", "ws", "!=", "nil", "{", "t", ".", "ws", ".", "Close", "(", ")", "\n", "}", "\n\n", "// Close the SSH connection to the remote node.", "if", "t", ".", "sshSession", "!=", "nil", "{", "t", ".", "sshSession", ".", "Close", "(", ")", "\n", "}", "\n\n", "// If the terminal handler was closed (most likely due to the *SessionContext", "// closing) then the stream should be closed as well.", "t", ".", "terminalCancel", "(", ")", "\n\n", "return", "nil", "\n", "}" ]
// Close the websocket stream.
[ "Close", "the", "websocket", "stream", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/terminal.go#L191-L207
train
gravitational/teleport
lib/web/terminal.go
handler
func (t *TerminalHandler) handler(ws *websocket.Conn) { // Create a Teleport client, if not able to, show the reason to the user in // the terminal. tc, err := t.makeClient(ws) if err != nil { er := t.writeError(err, ws) if er != nil { t.log.Warnf("Unable to send error to terminal: %v: %v.", err, er) } return } // Create a context for signaling when the terminal session is over. t.terminalContext, t.terminalCancel = context.WithCancel(context.Background()) t.log.Debugf("Creating websocket stream for %v.", t.params.SessionID) // Pump raw terminal in/out and audit events into the websocket. go t.streamTerminal(ws, tc) go t.streamEvents(ws, tc) // Block until the terminal session is complete. <-t.terminalContext.Done() t.log.Debugf("Closing websocket stream for %v.", t.params.SessionID) }
go
func (t *TerminalHandler) handler(ws *websocket.Conn) { // Create a Teleport client, if not able to, show the reason to the user in // the terminal. tc, err := t.makeClient(ws) if err != nil { er := t.writeError(err, ws) if er != nil { t.log.Warnf("Unable to send error to terminal: %v: %v.", err, er) } return } // Create a context for signaling when the terminal session is over. t.terminalContext, t.terminalCancel = context.WithCancel(context.Background()) t.log.Debugf("Creating websocket stream for %v.", t.params.SessionID) // Pump raw terminal in/out and audit events into the websocket. go t.streamTerminal(ws, tc) go t.streamEvents(ws, tc) // Block until the terminal session is complete. <-t.terminalContext.Done() t.log.Debugf("Closing websocket stream for %v.", t.params.SessionID) }
[ "func", "(", "t", "*", "TerminalHandler", ")", "handler", "(", "ws", "*", "websocket", ".", "Conn", ")", "{", "// Create a Teleport client, if not able to, show the reason to the user in", "// the terminal.", "tc", ",", "err", ":=", "t", ".", "makeClient", "(", "ws", ")", "\n", "if", "err", "!=", "nil", "{", "er", ":=", "t", ".", "writeError", "(", "err", ",", "ws", ")", "\n", "if", "er", "!=", "nil", "{", "t", ".", "log", ".", "Warnf", "(", "\"", "\"", ",", "err", ",", "er", ")", "\n", "}", "\n", "return", "\n", "}", "\n\n", "// Create a context for signaling when the terminal session is over.", "t", ".", "terminalContext", ",", "t", ".", "terminalCancel", "=", "context", ".", "WithCancel", "(", "context", ".", "Background", "(", ")", ")", "\n\n", "t", ".", "log", ".", "Debugf", "(", "\"", "\"", ",", "t", ".", "params", ".", "SessionID", ")", "\n\n", "// Pump raw terminal in/out and audit events into the websocket.", "go", "t", ".", "streamTerminal", "(", "ws", ",", "tc", ")", "\n", "go", "t", ".", "streamEvents", "(", "ws", ",", "tc", ")", "\n\n", "// Block until the terminal session is complete.", "<-", "t", ".", "terminalContext", ".", "Done", "(", ")", "\n", "t", ".", "log", ".", "Debugf", "(", "\"", "\"", ",", "t", ".", "params", ".", "SessionID", ")", "\n", "}" ]
// handler is the main websocket loop. It creates a Teleport client and then // pumps raw events and audit events back to the client until the SSH session // is complete.
[ "handler", "is", "the", "main", "websocket", "loop", ".", "It", "creates", "a", "Teleport", "client", "and", "then", "pumps", "raw", "events", "and", "audit", "events", "back", "to", "the", "client", "until", "the", "SSH", "session", "is", "complete", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/terminal.go#L212-L236
train
gravitational/teleport
lib/web/terminal.go
streamTerminal
func (t *TerminalHandler) streamTerminal(ws *websocket.Conn, tc *client.TeleportClient) { defer t.terminalCancel() // Establish SSH connection to the server. This function will block until // either an error occurs or it completes successfully. err := tc.SSH(t.terminalContext, t.params.InteractiveCommand, false) if err != nil { t.log.Warnf("Unable to stream terminal: %v.", err) er := t.writeError(err, ws) if er != nil { t.log.Warnf("Unable to send error to terminal: %v: %v.", err, er) } return } // Send close envelope to web terminal upon exit without an error. envelope := &Envelope{ Version: defaults.WebsocketVersion, Type: defaults.WebsocketClose, Payload: "", } envelopeBytes, err := proto.Marshal(envelope) if err != nil { t.log.Errorf("Unable to marshal close event for web client.") return } err = websocket.Message.Send(ws, envelopeBytes) if err != nil { t.log.Errorf("Unable to send close event to web client.") return } t.log.Debugf("Sent close event to web client.") }
go
func (t *TerminalHandler) streamTerminal(ws *websocket.Conn, tc *client.TeleportClient) { defer t.terminalCancel() // Establish SSH connection to the server. This function will block until // either an error occurs or it completes successfully. err := tc.SSH(t.terminalContext, t.params.InteractiveCommand, false) if err != nil { t.log.Warnf("Unable to stream terminal: %v.", err) er := t.writeError(err, ws) if er != nil { t.log.Warnf("Unable to send error to terminal: %v: %v.", err, er) } return } // Send close envelope to web terminal upon exit without an error. envelope := &Envelope{ Version: defaults.WebsocketVersion, Type: defaults.WebsocketClose, Payload: "", } envelopeBytes, err := proto.Marshal(envelope) if err != nil { t.log.Errorf("Unable to marshal close event for web client.") return } err = websocket.Message.Send(ws, envelopeBytes) if err != nil { t.log.Errorf("Unable to send close event to web client.") return } t.log.Debugf("Sent close event to web client.") }
[ "func", "(", "t", "*", "TerminalHandler", ")", "streamTerminal", "(", "ws", "*", "websocket", ".", "Conn", ",", "tc", "*", "client", ".", "TeleportClient", ")", "{", "defer", "t", ".", "terminalCancel", "(", ")", "\n\n", "// Establish SSH connection to the server. This function will block until", "// either an error occurs or it completes successfully.", "err", ":=", "tc", ".", "SSH", "(", "t", ".", "terminalContext", ",", "t", ".", "params", ".", "InteractiveCommand", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "t", ".", "log", ".", "Warnf", "(", "\"", "\"", ",", "err", ")", "\n", "er", ":=", "t", ".", "writeError", "(", "err", ",", "ws", ")", "\n", "if", "er", "!=", "nil", "{", "t", ".", "log", ".", "Warnf", "(", "\"", "\"", ",", "err", ",", "er", ")", "\n", "}", "\n", "return", "\n", "}", "\n\n", "// Send close envelope to web terminal upon exit without an error.", "envelope", ":=", "&", "Envelope", "{", "Version", ":", "defaults", ".", "WebsocketVersion", ",", "Type", ":", "defaults", ".", "WebsocketClose", ",", "Payload", ":", "\"", "\"", ",", "}", "\n", "envelopeBytes", ",", "err", ":=", "proto", ".", "Marshal", "(", "envelope", ")", "\n", "if", "err", "!=", "nil", "{", "t", ".", "log", ".", "Errorf", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "err", "=", "websocket", ".", "Message", ".", "Send", "(", "ws", ",", "envelopeBytes", ")", "\n", "if", "err", "!=", "nil", "{", "t", ".", "log", ".", "Errorf", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "t", ".", "log", ".", "Debugf", "(", "\"", "\"", ")", "\n", "}" ]
// streamTerminal opens a SSH connection to the remote host and streams // events back to the web client.
[ "streamTerminal", "opens", "a", "SSH", "connection", "to", "the", "remote", "host", "and", "streams", "events", "back", "to", "the", "web", "client", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/terminal.go#L288-L320
train
gravitational/teleport
lib/web/terminal.go
streamEvents
func (t *TerminalHandler) streamEvents(ws *websocket.Conn, tc *client.TeleportClient) { for { select { // Send push events that come over the events channel to the web client. case event := <-tc.EventsChannel(): data, err := json.Marshal(event) if err != nil { t.log.Errorf("Unable to marshal audit event %v: %v.", event.GetType(), err) continue } t.log.Debugf("Sending audit event %v to web client.", event.GetType()) // UTF-8 encode the error message and then wrap it in a raw envelope. encodedPayload, err := t.encoder.String(string(data)) if err != nil { t.log.Debugf("Unable to send audit event %v to web client: %v.", event.GetType(), err) continue } envelope := &Envelope{ Version: defaults.WebsocketVersion, Type: defaults.WebsocketAudit, Payload: encodedPayload, } envelopeBytes, err := proto.Marshal(envelope) if err != nil { t.log.Debugf("Unable to send audit event %v to web client: %v.", event.GetType(), err) continue } // Send bytes over the websocket to the web client. err = websocket.Message.Send(ws, envelopeBytes) if err != nil { t.log.Errorf("Unable to send audit event %v to web client: %v.", event.GetType(), err) continue } // Once the terminal stream is over (and the close envelope has been sent), // close stop streaming envelopes. case <-t.terminalContext.Done(): return } } }
go
func (t *TerminalHandler) streamEvents(ws *websocket.Conn, tc *client.TeleportClient) { for { select { // Send push events that come over the events channel to the web client. case event := <-tc.EventsChannel(): data, err := json.Marshal(event) if err != nil { t.log.Errorf("Unable to marshal audit event %v: %v.", event.GetType(), err) continue } t.log.Debugf("Sending audit event %v to web client.", event.GetType()) // UTF-8 encode the error message and then wrap it in a raw envelope. encodedPayload, err := t.encoder.String(string(data)) if err != nil { t.log.Debugf("Unable to send audit event %v to web client: %v.", event.GetType(), err) continue } envelope := &Envelope{ Version: defaults.WebsocketVersion, Type: defaults.WebsocketAudit, Payload: encodedPayload, } envelopeBytes, err := proto.Marshal(envelope) if err != nil { t.log.Debugf("Unable to send audit event %v to web client: %v.", event.GetType(), err) continue } // Send bytes over the websocket to the web client. err = websocket.Message.Send(ws, envelopeBytes) if err != nil { t.log.Errorf("Unable to send audit event %v to web client: %v.", event.GetType(), err) continue } // Once the terminal stream is over (and the close envelope has been sent), // close stop streaming envelopes. case <-t.terminalContext.Done(): return } } }
[ "func", "(", "t", "*", "TerminalHandler", ")", "streamEvents", "(", "ws", "*", "websocket", ".", "Conn", ",", "tc", "*", "client", ".", "TeleportClient", ")", "{", "for", "{", "select", "{", "// Send push events that come over the events channel to the web client.", "case", "event", ":=", "<-", "tc", ".", "EventsChannel", "(", ")", ":", "data", ",", "err", ":=", "json", ".", "Marshal", "(", "event", ")", "\n", "if", "err", "!=", "nil", "{", "t", ".", "log", ".", "Errorf", "(", "\"", "\"", ",", "event", ".", "GetType", "(", ")", ",", "err", ")", "\n", "continue", "\n", "}", "\n\n", "t", ".", "log", ".", "Debugf", "(", "\"", "\"", ",", "event", ".", "GetType", "(", ")", ")", "\n\n", "// UTF-8 encode the error message and then wrap it in a raw envelope.", "encodedPayload", ",", "err", ":=", "t", ".", "encoder", ".", "String", "(", "string", "(", "data", ")", ")", "\n", "if", "err", "!=", "nil", "{", "t", ".", "log", ".", "Debugf", "(", "\"", "\"", ",", "event", ".", "GetType", "(", ")", ",", "err", ")", "\n", "continue", "\n", "}", "\n", "envelope", ":=", "&", "Envelope", "{", "Version", ":", "defaults", ".", "WebsocketVersion", ",", "Type", ":", "defaults", ".", "WebsocketAudit", ",", "Payload", ":", "encodedPayload", ",", "}", "\n", "envelopeBytes", ",", "err", ":=", "proto", ".", "Marshal", "(", "envelope", ")", "\n", "if", "err", "!=", "nil", "{", "t", ".", "log", ".", "Debugf", "(", "\"", "\"", ",", "event", ".", "GetType", "(", ")", ",", "err", ")", "\n", "continue", "\n", "}", "\n\n", "// Send bytes over the websocket to the web client.", "err", "=", "websocket", ".", "Message", ".", "Send", "(", "ws", ",", "envelopeBytes", ")", "\n", "if", "err", "!=", "nil", "{", "t", ".", "log", ".", "Errorf", "(", "\"", "\"", ",", "event", ".", "GetType", "(", ")", ",", "err", ")", "\n", "continue", "\n", "}", "\n", "// Once the terminal stream is over (and the close envelope has been sent),", "// close stop streaming envelopes.", "case", "<-", "t", ".", "terminalContext", ".", "Done", "(", ")", ":", "return", "\n", "}", "\n", "}", "\n", "}" ]
// streamEvents receives events over the SSH connection and forwards them to // the web client.
[ "streamEvents", "receives", "events", "over", "the", "SSH", "connection", "and", "forwards", "them", "to", "the", "web", "client", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/terminal.go#L324-L366
train
gravitational/teleport
lib/web/terminal.go
windowChange
func (t *TerminalHandler) windowChange(params *session.TerminalParams) error { if t.sshSession == nil { return nil } _, err := t.sshSession.SendRequest( sshutils.WindowChangeRequest, false, ssh.Marshal(sshutils.WinChangeReqParams{ W: uint32(params.W), H: uint32(params.H), })) if err != nil { t.log.Error(err) } return trace.Wrap(err) }
go
func (t *TerminalHandler) windowChange(params *session.TerminalParams) error { if t.sshSession == nil { return nil } _, err := t.sshSession.SendRequest( sshutils.WindowChangeRequest, false, ssh.Marshal(sshutils.WinChangeReqParams{ W: uint32(params.W), H: uint32(params.H), })) if err != nil { t.log.Error(err) } return trace.Wrap(err) }
[ "func", "(", "t", "*", "TerminalHandler", ")", "windowChange", "(", "params", "*", "session", ".", "TerminalParams", ")", "error", "{", "if", "t", ".", "sshSession", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "_", ",", "err", ":=", "t", ".", "sshSession", ".", "SendRequest", "(", "sshutils", ".", "WindowChangeRequest", ",", "false", ",", "ssh", ".", "Marshal", "(", "sshutils", ".", "WinChangeReqParams", "{", "W", ":", "uint32", "(", "params", ".", "W", ")", ",", "H", ":", "uint32", "(", "params", ".", "H", ")", ",", "}", ")", ")", "\n", "if", "err", "!=", "nil", "{", "t", ".", "log", ".", "Error", "(", "err", ")", "\n", "}", "\n\n", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}" ]
// windowChange is called when the browser window is resized. It sends a // "window-change" channel request to the server.
[ "windowChange", "is", "called", "when", "the", "browser", "window", "is", "resized", ".", "It", "sends", "a", "window", "-", "change", "channel", "request", "to", "the", "server", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/terminal.go#L370-L387
train
gravitational/teleport
lib/web/terminal.go
writeError
func (t *TerminalHandler) writeError(err error, ws *websocket.Conn) error { // Replace \n with \r\n so the message correctly aligned. r := strings.NewReplacer("\r\n", "\r\n", "\n", "\r\n") errMessage := r.Replace(err.Error()) _, err = t.write([]byte(errMessage), ws) if err != nil { return trace.Wrap(err) } return nil }
go
func (t *TerminalHandler) writeError(err error, ws *websocket.Conn) error { // Replace \n with \r\n so the message correctly aligned. r := strings.NewReplacer("\r\n", "\r\n", "\n", "\r\n") errMessage := r.Replace(err.Error()) _, err = t.write([]byte(errMessage), ws) if err != nil { return trace.Wrap(err) } return nil }
[ "func", "(", "t", "*", "TerminalHandler", ")", "writeError", "(", "err", "error", ",", "ws", "*", "websocket", ".", "Conn", ")", "error", "{", "// Replace \\n with \\r\\n so the message correctly aligned.", "r", ":=", "strings", ".", "NewReplacer", "(", "\"", "\\r", "\\n", "\"", ",", "\"", "\\r", "\\n", "\"", ",", "\"", "\\n", "\"", ",", "\"", "\\r", "\\n", "\"", ")", "\n", "errMessage", ":=", "r", ".", "Replace", "(", "err", ".", "Error", "(", ")", ")", "\n", "_", ",", "err", "=", "t", ".", "write", "(", "[", "]", "byte", "(", "errMessage", ")", ",", "ws", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// writeError displays an error in the terminal window.
[ "writeError", "displays", "an", "error", "in", "the", "terminal", "window", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/terminal.go#L390-L400
train
gravitational/teleport
lib/web/terminal.go
resolveServerHostPort
func resolveServerHostPort(servername string, existingServers []services.Server) (string, int, error) { // If port is 0, client wants us to figure out which port to use. var defaultPort = 0 if servername == "" { return "", defaultPort, trace.BadParameter("empty server name") } // Check if servername is UUID. for i := range existingServers { node := existingServers[i] if node.GetName() == servername { return node.GetHostname(), defaultPort, nil } } if !strings.Contains(servername, ":") { return servername, defaultPort, nil } // Check for explicitly specified port. host, portString, err := utils.SplitHostPort(servername) if err != nil { return "", defaultPort, trace.Wrap(err) } port, err := strconv.Atoi(portString) if err != nil { return "", defaultPort, trace.BadParameter("invalid port: %v", err) } return host, port, nil }
go
func resolveServerHostPort(servername string, existingServers []services.Server) (string, int, error) { // If port is 0, client wants us to figure out which port to use. var defaultPort = 0 if servername == "" { return "", defaultPort, trace.BadParameter("empty server name") } // Check if servername is UUID. for i := range existingServers { node := existingServers[i] if node.GetName() == servername { return node.GetHostname(), defaultPort, nil } } if !strings.Contains(servername, ":") { return servername, defaultPort, nil } // Check for explicitly specified port. host, portString, err := utils.SplitHostPort(servername) if err != nil { return "", defaultPort, trace.Wrap(err) } port, err := strconv.Atoi(portString) if err != nil { return "", defaultPort, trace.BadParameter("invalid port: %v", err) } return host, port, nil }
[ "func", "resolveServerHostPort", "(", "servername", "string", ",", "existingServers", "[", "]", "services", ".", "Server", ")", "(", "string", ",", "int", ",", "error", ")", "{", "// If port is 0, client wants us to figure out which port to use.", "var", "defaultPort", "=", "0", "\n\n", "if", "servername", "==", "\"", "\"", "{", "return", "\"", "\"", ",", "defaultPort", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Check if servername is UUID.", "for", "i", ":=", "range", "existingServers", "{", "node", ":=", "existingServers", "[", "i", "]", "\n", "if", "node", ".", "GetName", "(", ")", "==", "servername", "{", "return", "node", ".", "GetHostname", "(", ")", ",", "defaultPort", ",", "nil", "\n", "}", "\n", "}", "\n\n", "if", "!", "strings", ".", "Contains", "(", "servername", ",", "\"", "\"", ")", "{", "return", "servername", ",", "defaultPort", ",", "nil", "\n", "}", "\n\n", "// Check for explicitly specified port.", "host", ",", "portString", ",", "err", ":=", "utils", ".", "SplitHostPort", "(", "servername", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "defaultPort", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "port", ",", "err", ":=", "strconv", ".", "Atoi", "(", "portString", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "defaultPort", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "return", "host", ",", "port", ",", "nil", "\n", "}" ]
// resolveServerHostPort parses server name and attempts to resolve hostname // and port.
[ "resolveServerHostPort", "parses", "server", "name", "and", "attempts", "to", "resolve", "hostname", "and", "port", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/terminal.go#L404-L436
train
gravitational/teleport
lib/web/terminal.go
Write
func (w *terminalStream) Write(data []byte) (n int, err error) { return w.terminal.write(data, w.ws) }
go
func (w *terminalStream) Write(data []byte) (n int, err error) { return w.terminal.write(data, w.ws) }
[ "func", "(", "w", "*", "terminalStream", ")", "Write", "(", "data", "[", "]", "byte", ")", "(", "n", "int", ",", "err", "error", ")", "{", "return", "w", ".", "terminal", ".", "write", "(", "data", ",", "w", ".", "ws", ")", "\n", "}" ]
// Write wraps the data bytes in a raw envelope and sends.
[ "Write", "wraps", "the", "data", "bytes", "in", "a", "raw", "envelope", "and", "sends", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/terminal.go#L544-L546
train
gravitational/teleport
lib/web/terminal.go
SetReadDeadline
func (w *terminalStream) SetReadDeadline(t time.Time) error { return w.ws.SetReadDeadline(t) }
go
func (w *terminalStream) SetReadDeadline(t time.Time) error { return w.ws.SetReadDeadline(t) }
[ "func", "(", "w", "*", "terminalStream", ")", "SetReadDeadline", "(", "t", "time", ".", "Time", ")", "error", "{", "return", "w", ".", "ws", ".", "SetReadDeadline", "(", "t", ")", "\n", "}" ]
// SetReadDeadline sets the network read deadline on the underlying websocket.
[ "SetReadDeadline", "sets", "the", "network", "read", "deadline", "on", "the", "underlying", "websocket", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/terminal.go#L555-L557
train
gravitational/teleport
lib/kube/proxy/forwarder.go
NewForwarder
func NewForwarder(cfg ForwarderConfig) (*Forwarder, error) { if err := cfg.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } creds, err := getKubeCreds(cfg.KubeconfigPath) if err != nil { return nil, trace.Wrap(err) } clusterSessions, err := ttlmap.New(defaults.ClientCacheSize) if err != nil { return nil, trace.Wrap(err) } closeCtx, close := context.WithCancel(cfg.Context) fwd := &Forwarder{ creds: *creds, Entry: log.WithFields(log.Fields{ trace.Component: teleport.Component(teleport.ComponentKube), }), Router: *httprouter.New(), ForwarderConfig: cfg, clusterSessions: clusterSessions, activeRequests: make(map[string]context.Context), ctx: closeCtx, close: close, } fwd.POST("/api/:ver/namespaces/:podNamespace/pods/:podName/exec", fwd.withAuth(fwd.exec)) fwd.GET("/api/:ver/namespaces/:podNamespace/pods/:podName/exec", fwd.withAuth(fwd.exec)) fwd.POST("/api/:ver/namespaces/:podNamespace/pods/:podName/attach", fwd.withAuth(fwd.exec)) fwd.GET("/api/:ver/namespaces/:podNamespace/pods/:podName/attach", fwd.withAuth(fwd.exec)) fwd.POST("/api/:ver/namespaces/:podNamespace/pods/:podName/portforward", fwd.withAuth(fwd.portForward)) fwd.GET("/api/:ver/namespaces/:podNamespace/pods/:podName/portforward", fwd.withAuth(fwd.portForward)) fwd.NotFound = fwd.withAuthStd(fwd.catchAll) if cfg.ClusterOverride != "" { fwd.Debugf("Cluster override is set, forwarder will send all requests to remote cluster %v.", cfg.ClusterOverride) } return fwd, nil }
go
func NewForwarder(cfg ForwarderConfig) (*Forwarder, error) { if err := cfg.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } creds, err := getKubeCreds(cfg.KubeconfigPath) if err != nil { return nil, trace.Wrap(err) } clusterSessions, err := ttlmap.New(defaults.ClientCacheSize) if err != nil { return nil, trace.Wrap(err) } closeCtx, close := context.WithCancel(cfg.Context) fwd := &Forwarder{ creds: *creds, Entry: log.WithFields(log.Fields{ trace.Component: teleport.Component(teleport.ComponentKube), }), Router: *httprouter.New(), ForwarderConfig: cfg, clusterSessions: clusterSessions, activeRequests: make(map[string]context.Context), ctx: closeCtx, close: close, } fwd.POST("/api/:ver/namespaces/:podNamespace/pods/:podName/exec", fwd.withAuth(fwd.exec)) fwd.GET("/api/:ver/namespaces/:podNamespace/pods/:podName/exec", fwd.withAuth(fwd.exec)) fwd.POST("/api/:ver/namespaces/:podNamespace/pods/:podName/attach", fwd.withAuth(fwd.exec)) fwd.GET("/api/:ver/namespaces/:podNamespace/pods/:podName/attach", fwd.withAuth(fwd.exec)) fwd.POST("/api/:ver/namespaces/:podNamespace/pods/:podName/portforward", fwd.withAuth(fwd.portForward)) fwd.GET("/api/:ver/namespaces/:podNamespace/pods/:podName/portforward", fwd.withAuth(fwd.portForward)) fwd.NotFound = fwd.withAuthStd(fwd.catchAll) if cfg.ClusterOverride != "" { fwd.Debugf("Cluster override is set, forwarder will send all requests to remote cluster %v.", cfg.ClusterOverride) } return fwd, nil }
[ "func", "NewForwarder", "(", "cfg", "ForwarderConfig", ")", "(", "*", "Forwarder", ",", "error", ")", "{", "if", "err", ":=", "cfg", ".", "CheckAndSetDefaults", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "creds", ",", "err", ":=", "getKubeCreds", "(", "cfg", ".", "KubeconfigPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "clusterSessions", ",", "err", ":=", "ttlmap", ".", "New", "(", "defaults", ".", "ClientCacheSize", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "closeCtx", ",", "close", ":=", "context", ".", "WithCancel", "(", "cfg", ".", "Context", ")", "\n", "fwd", ":=", "&", "Forwarder", "{", "creds", ":", "*", "creds", ",", "Entry", ":", "log", ".", "WithFields", "(", "log", ".", "Fields", "{", "trace", ".", "Component", ":", "teleport", ".", "Component", "(", "teleport", ".", "ComponentKube", ")", ",", "}", ")", ",", "Router", ":", "*", "httprouter", ".", "New", "(", ")", ",", "ForwarderConfig", ":", "cfg", ",", "clusterSessions", ":", "clusterSessions", ",", "activeRequests", ":", "make", "(", "map", "[", "string", "]", "context", ".", "Context", ")", ",", "ctx", ":", "closeCtx", ",", "close", ":", "close", ",", "}", "\n\n", "fwd", ".", "POST", "(", "\"", "\"", ",", "fwd", ".", "withAuth", "(", "fwd", ".", "exec", ")", ")", "\n", "fwd", ".", "GET", "(", "\"", "\"", ",", "fwd", ".", "withAuth", "(", "fwd", ".", "exec", ")", ")", "\n\n", "fwd", ".", "POST", "(", "\"", "\"", ",", "fwd", ".", "withAuth", "(", "fwd", ".", "exec", ")", ")", "\n", "fwd", ".", "GET", "(", "\"", "\"", ",", "fwd", ".", "withAuth", "(", "fwd", ".", "exec", ")", ")", "\n\n", "fwd", ".", "POST", "(", "\"", "\"", ",", "fwd", ".", "withAuth", "(", "fwd", ".", "portForward", ")", ")", "\n", "fwd", ".", "GET", "(", "\"", "\"", ",", "fwd", ".", "withAuth", "(", "fwd", ".", "portForward", ")", ")", "\n\n", "fwd", ".", "NotFound", "=", "fwd", ".", "withAuthStd", "(", "fwd", ".", "catchAll", ")", "\n\n", "if", "cfg", ".", "ClusterOverride", "!=", "\"", "\"", "{", "fwd", ".", "Debugf", "(", "\"", "\"", ",", "cfg", ".", "ClusterOverride", ")", "\n", "}", "\n", "return", "fwd", ",", "nil", "\n", "}" ]
// NewForwarder returns new instance of Kubernetes request // forwarding proxy.
[ "NewForwarder", "returns", "new", "instance", "of", "Kubernetes", "request", "forwarding", "proxy", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/forwarder.go#L144-L187
train
gravitational/teleport
lib/kube/proxy/forwarder.go
authenticate
func (f *Forwarder) authenticate(req *http.Request) (*authContext, error) { const accessDeniedMsg = "[00] access denied" var isRemoteUser bool userTypeI := req.Context().Value(auth.ContextUser) switch userTypeI.(type) { case auth.LocalUser: case auth.RemoteUser: isRemoteUser = true default: f.Warningf("Denying proxy access to unsupported user type: %T.", userTypeI) return nil, trace.AccessDenied(accessDeniedMsg) } userContext, err := f.Auth.Authorize(req.Context()) if err != nil { switch { // propagate connection problem error so we can differentiate // between connection failed and access denied case trace.IsConnectionProblem(err): return nil, trace.ConnectionProblem(err, "[07] failed to connect to the database") case trace.IsAccessDenied(err): // don't print stack trace, just log the warning f.Warn(err) return nil, trace.AccessDenied(accessDeniedMsg) default: f.Warn(trace.DebugReport(err)) return nil, trace.AccessDenied(accessDeniedMsg) } } peers := req.TLS.PeerCertificates if len(peers) > 1 { // when turning intermediaries on, don't forget to verify // https://github.com/kubernetes/kubernetes/pull/34524/files#diff-2b283dde198c92424df5355f39544aa4R59 return nil, trace.AccessDenied("access denied: intermediaries are not supported") } if len(peers) == 0 { return nil, trace.AccessDenied("access denied: only mutual TLS authentication is supported") } clientCert := peers[0] authContext, err := f.setupContext(*userContext, req, isRemoteUser, clientCert.NotAfter) if err != nil { f.Warn(err.Error()) return nil, trace.AccessDenied(accessDeniedMsg) } return authContext, nil }
go
func (f *Forwarder) authenticate(req *http.Request) (*authContext, error) { const accessDeniedMsg = "[00] access denied" var isRemoteUser bool userTypeI := req.Context().Value(auth.ContextUser) switch userTypeI.(type) { case auth.LocalUser: case auth.RemoteUser: isRemoteUser = true default: f.Warningf("Denying proxy access to unsupported user type: %T.", userTypeI) return nil, trace.AccessDenied(accessDeniedMsg) } userContext, err := f.Auth.Authorize(req.Context()) if err != nil { switch { // propagate connection problem error so we can differentiate // between connection failed and access denied case trace.IsConnectionProblem(err): return nil, trace.ConnectionProblem(err, "[07] failed to connect to the database") case trace.IsAccessDenied(err): // don't print stack trace, just log the warning f.Warn(err) return nil, trace.AccessDenied(accessDeniedMsg) default: f.Warn(trace.DebugReport(err)) return nil, trace.AccessDenied(accessDeniedMsg) } } peers := req.TLS.PeerCertificates if len(peers) > 1 { // when turning intermediaries on, don't forget to verify // https://github.com/kubernetes/kubernetes/pull/34524/files#diff-2b283dde198c92424df5355f39544aa4R59 return nil, trace.AccessDenied("access denied: intermediaries are not supported") } if len(peers) == 0 { return nil, trace.AccessDenied("access denied: only mutual TLS authentication is supported") } clientCert := peers[0] authContext, err := f.setupContext(*userContext, req, isRemoteUser, clientCert.NotAfter) if err != nil { f.Warn(err.Error()) return nil, trace.AccessDenied(accessDeniedMsg) } return authContext, nil }
[ "func", "(", "f", "*", "Forwarder", ")", "authenticate", "(", "req", "*", "http", ".", "Request", ")", "(", "*", "authContext", ",", "error", ")", "{", "const", "accessDeniedMsg", "=", "\"", "\"", "\n\n", "var", "isRemoteUser", "bool", "\n", "userTypeI", ":=", "req", ".", "Context", "(", ")", ".", "Value", "(", "auth", ".", "ContextUser", ")", "\n", "switch", "userTypeI", ".", "(", "type", ")", "{", "case", "auth", ".", "LocalUser", ":", "case", "auth", ".", "RemoteUser", ":", "isRemoteUser", "=", "true", "\n", "default", ":", "f", ".", "Warningf", "(", "\"", "\"", ",", "userTypeI", ")", "\n", "return", "nil", ",", "trace", ".", "AccessDenied", "(", "accessDeniedMsg", ")", "\n", "}", "\n\n", "userContext", ",", "err", ":=", "f", ".", "Auth", ".", "Authorize", "(", "req", ".", "Context", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "switch", "{", "// propagate connection problem error so we can differentiate", "// between connection failed and access denied", "case", "trace", ".", "IsConnectionProblem", "(", "err", ")", ":", "return", "nil", ",", "trace", ".", "ConnectionProblem", "(", "err", ",", "\"", "\"", ")", "\n", "case", "trace", ".", "IsAccessDenied", "(", "err", ")", ":", "// don't print stack trace, just log the warning", "f", ".", "Warn", "(", "err", ")", "\n", "return", "nil", ",", "trace", ".", "AccessDenied", "(", "accessDeniedMsg", ")", "\n", "default", ":", "f", ".", "Warn", "(", "trace", ".", "DebugReport", "(", "err", ")", ")", "\n", "return", "nil", ",", "trace", ".", "AccessDenied", "(", "accessDeniedMsg", ")", "\n", "}", "\n", "}", "\n", "peers", ":=", "req", ".", "TLS", ".", "PeerCertificates", "\n", "if", "len", "(", "peers", ")", ">", "1", "{", "// when turning intermediaries on, don't forget to verify", "// https://github.com/kubernetes/kubernetes/pull/34524/files#diff-2b283dde198c92424df5355f39544aa4R59", "return", "nil", ",", "trace", ".", "AccessDenied", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "peers", ")", "==", "0", "{", "return", "nil", ",", "trace", ".", "AccessDenied", "(", "\"", "\"", ")", "\n", "}", "\n", "clientCert", ":=", "peers", "[", "0", "]", "\n", "authContext", ",", "err", ":=", "f", ".", "setupContext", "(", "*", "userContext", ",", "req", ",", "isRemoteUser", ",", "clientCert", ".", "NotAfter", ")", "\n", "if", "err", "!=", "nil", "{", "f", ".", "Warn", "(", "err", ".", "Error", "(", ")", ")", "\n", "return", "nil", ",", "trace", ".", "AccessDenied", "(", "accessDeniedMsg", ")", "\n", "}", "\n", "return", "authContext", ",", "nil", "\n", "}" ]
// authenticate function authenticates request
[ "authenticate", "function", "authenticates", "request" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/forwarder.go#L274-L321
train
gravitational/teleport
lib/kube/proxy/forwarder.go
portForward
func (f *Forwarder) portForward(ctx *authContext, w http.ResponseWriter, req *http.Request, p httprouter.Params) (interface{}, error) { f.Debugf("Port forward: %v. req headers: %v", req.URL.String(), req.Header) sess, err := f.getOrCreateClusterSession(*ctx) if err != nil { return nil, trace.Wrap(err) } if err := f.setupForwardingHeaders(ctx, sess, req); err != nil { f.Debugf("DENIED Port forward: %v.", req.URL.String()) return nil, trace.Wrap(err) } dialer, err := f.getDialer(*ctx, sess, req) if err != nil { return nil, trace.Wrap(err) } onPortForward := func(addr string, success bool) { event := events.PortForward if !success { event = events.PortForwardFailure } f.AuditLog.EmitAuditEvent(event, events.EventFields{ events.EventProtocol: events.EventProtocolKube, events.PortForwardAddr: addr, events.PortForwardSuccess: success, events.EventLogin: ctx.User.GetName(), events.EventUser: ctx.User.GetName(), events.LocalAddr: sess.cluster.targetAddr, events.RemoteAddr: req.RemoteAddr, }) } q := req.URL.Query() request := portForwardRequest{ podNamespace: p.ByName("podNamespace"), podName: p.ByName("podName"), ports: q["ports"], context: req.Context(), httpRequest: req, httpResponseWriter: w, onPortForward: onPortForward, targetDialer: dialer, } f.Debugf("Starting %v.", request) err = runPortForwarding(request) if err != nil { return nil, trace.Wrap(err) } f.Debugf("Done %v.", request) return nil, nil }
go
func (f *Forwarder) portForward(ctx *authContext, w http.ResponseWriter, req *http.Request, p httprouter.Params) (interface{}, error) { f.Debugf("Port forward: %v. req headers: %v", req.URL.String(), req.Header) sess, err := f.getOrCreateClusterSession(*ctx) if err != nil { return nil, trace.Wrap(err) } if err := f.setupForwardingHeaders(ctx, sess, req); err != nil { f.Debugf("DENIED Port forward: %v.", req.URL.String()) return nil, trace.Wrap(err) } dialer, err := f.getDialer(*ctx, sess, req) if err != nil { return nil, trace.Wrap(err) } onPortForward := func(addr string, success bool) { event := events.PortForward if !success { event = events.PortForwardFailure } f.AuditLog.EmitAuditEvent(event, events.EventFields{ events.EventProtocol: events.EventProtocolKube, events.PortForwardAddr: addr, events.PortForwardSuccess: success, events.EventLogin: ctx.User.GetName(), events.EventUser: ctx.User.GetName(), events.LocalAddr: sess.cluster.targetAddr, events.RemoteAddr: req.RemoteAddr, }) } q := req.URL.Query() request := portForwardRequest{ podNamespace: p.ByName("podNamespace"), podName: p.ByName("podName"), ports: q["ports"], context: req.Context(), httpRequest: req, httpResponseWriter: w, onPortForward: onPortForward, targetDialer: dialer, } f.Debugf("Starting %v.", request) err = runPortForwarding(request) if err != nil { return nil, trace.Wrap(err) } f.Debugf("Done %v.", request) return nil, nil }
[ "func", "(", "f", "*", "Forwarder", ")", "portForward", "(", "ctx", "*", "authContext", ",", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ",", "p", "httprouter", ".", "Params", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "f", ".", "Debugf", "(", "\"", "\"", ",", "req", ".", "URL", ".", "String", "(", ")", ",", "req", ".", "Header", ")", "\n", "sess", ",", "err", ":=", "f", ".", "getOrCreateClusterSession", "(", "*", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "if", "err", ":=", "f", ".", "setupForwardingHeaders", "(", "ctx", ",", "sess", ",", "req", ")", ";", "err", "!=", "nil", "{", "f", ".", "Debugf", "(", "\"", "\"", ",", "req", ".", "URL", ".", "String", "(", ")", ")", "\n", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "dialer", ",", "err", ":=", "f", ".", "getDialer", "(", "*", "ctx", ",", "sess", ",", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "onPortForward", ":=", "func", "(", "addr", "string", ",", "success", "bool", ")", "{", "event", ":=", "events", ".", "PortForward", "\n", "if", "!", "success", "{", "event", "=", "events", ".", "PortForwardFailure", "\n", "}", "\n", "f", ".", "AuditLog", ".", "EmitAuditEvent", "(", "event", ",", "events", ".", "EventFields", "{", "events", ".", "EventProtocol", ":", "events", ".", "EventProtocolKube", ",", "events", ".", "PortForwardAddr", ":", "addr", ",", "events", ".", "PortForwardSuccess", ":", "success", ",", "events", ".", "EventLogin", ":", "ctx", ".", "User", ".", "GetName", "(", ")", ",", "events", ".", "EventUser", ":", "ctx", ".", "User", ".", "GetName", "(", ")", ",", "events", ".", "LocalAddr", ":", "sess", ".", "cluster", ".", "targetAddr", ",", "events", ".", "RemoteAddr", ":", "req", ".", "RemoteAddr", ",", "}", ")", "\n", "}", "\n\n", "q", ":=", "req", ".", "URL", ".", "Query", "(", ")", "\n", "request", ":=", "portForwardRequest", "{", "podNamespace", ":", "p", ".", "ByName", "(", "\"", "\"", ")", ",", "podName", ":", "p", ".", "ByName", "(", "\"", "\"", ")", ",", "ports", ":", "q", "[", "\"", "\"", "]", ",", "context", ":", "req", ".", "Context", "(", ")", ",", "httpRequest", ":", "req", ",", "httpResponseWriter", ":", "w", ",", "onPortForward", ":", "onPortForward", ",", "targetDialer", ":", "dialer", ",", "}", "\n", "f", ".", "Debugf", "(", "\"", "\"", ",", "request", ")", "\n", "err", "=", "runPortForwarding", "(", "request", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "f", ".", "Debugf", "(", "\"", "\"", ",", "request", ")", "\n", "return", "nil", ",", "nil", "\n", "}" ]
// portForward starts port forwarding to the remote cluster
[ "portForward", "starts", "port", "forwarding", "to", "the", "remote", "cluster" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/forwarder.go#L568-L619
train
gravitational/teleport
lib/kube/proxy/forwarder.go
catchAll
func (f *Forwarder) catchAll(ctx *authContext, w http.ResponseWriter, req *http.Request) (interface{}, error) { sess, err := f.getOrCreateClusterSession(*ctx) if err != nil { return nil, trace.Wrap(err) } if err := f.setupForwardingHeaders(ctx, sess, req); err != nil { return nil, trace.Wrap(err) } sess.forwarder.ServeHTTP(w, req) return nil, nil }
go
func (f *Forwarder) catchAll(ctx *authContext, w http.ResponseWriter, req *http.Request) (interface{}, error) { sess, err := f.getOrCreateClusterSession(*ctx) if err != nil { return nil, trace.Wrap(err) } if err := f.setupForwardingHeaders(ctx, sess, req); err != nil { return nil, trace.Wrap(err) } sess.forwarder.ServeHTTP(w, req) return nil, nil }
[ "func", "(", "f", "*", "Forwarder", ")", "catchAll", "(", "ctx", "*", "authContext", ",", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "sess", ",", "err", ":=", "f", ".", "getOrCreateClusterSession", "(", "*", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "err", ":=", "f", ".", "setupForwardingHeaders", "(", "ctx", ",", "sess", ",", "req", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "sess", ".", "forwarder", ".", "ServeHTTP", "(", "w", ",", "req", ")", "\n", "return", "nil", ",", "nil", "\n", "}" ]
// catchAll forwards all HTTP requests to the target k8s API server
[ "catchAll", "forwards", "all", "HTTP", "requests", "to", "the", "target", "k8s", "API", "server" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/forwarder.go#L655-L665
train
gravitational/teleport
lib/kube/proxy/forwarder.go
UpdateClientActivity
func (t *trackingConn) UpdateClientActivity() { t.Lock() defer t.Unlock() t.lastActive = t.clock.Now().UTC() }
go
func (t *trackingConn) UpdateClientActivity() { t.Lock() defer t.Unlock() t.lastActive = t.clock.Now().UTC() }
[ "func", "(", "t", "*", "trackingConn", ")", "UpdateClientActivity", "(", ")", "{", "t", ".", "Lock", "(", ")", "\n", "defer", "t", ".", "Unlock", "(", ")", "\n", "t", ".", "lastActive", "=", "t", ".", "clock", ".", "Now", "(", ")", ".", "UTC", "(", ")", "\n", "}" ]
// UpdateClientActivity sets last recorded client activity
[ "UpdateClientActivity", "sets", "last", "recorded", "client", "activity" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/forwarder.go#L778-L782
train
gravitational/teleport
lib/kube/proxy/forwarder.go
getOrCreateRequestContext
func (f *Forwarder) getOrCreateRequestContext(key string) (context.Context, context.CancelFunc) { f.Lock() defer f.Unlock() ctx, ok := f.activeRequests[key] if ok { return ctx, nil } ctx, cancel := context.WithCancel(context.TODO()) f.activeRequests[key] = ctx return ctx, func() { cancel() f.Lock() defer f.Unlock() delete(f.activeRequests, key) } }
go
func (f *Forwarder) getOrCreateRequestContext(key string) (context.Context, context.CancelFunc) { f.Lock() defer f.Unlock() ctx, ok := f.activeRequests[key] if ok { return ctx, nil } ctx, cancel := context.WithCancel(context.TODO()) f.activeRequests[key] = ctx return ctx, func() { cancel() f.Lock() defer f.Unlock() delete(f.activeRequests, key) } }
[ "func", "(", "f", "*", "Forwarder", ")", "getOrCreateRequestContext", "(", "key", "string", ")", "(", "context", ".", "Context", ",", "context", ".", "CancelFunc", ")", "{", "f", ".", "Lock", "(", ")", "\n", "defer", "f", ".", "Unlock", "(", ")", "\n", "ctx", ",", "ok", ":=", "f", ".", "activeRequests", "[", "key", "]", "\n", "if", "ok", "{", "return", "ctx", ",", "nil", "\n", "}", "\n", "ctx", ",", "cancel", ":=", "context", ".", "WithCancel", "(", "context", ".", "TODO", "(", ")", ")", "\n", "f", ".", "activeRequests", "[", "key", "]", "=", "ctx", "\n", "return", "ctx", ",", "func", "(", ")", "{", "cancel", "(", ")", "\n", "f", ".", "Lock", "(", ")", "\n", "defer", "f", ".", "Unlock", "(", ")", "\n", "delete", "(", "f", ".", "activeRequests", ",", "key", ")", "\n", "}", "\n", "}" ]
// getOrCreateRequestContext creates a new certificate request for a given context, // if there is no active CSR request in progress, or returns an existing one. // if the new context has been created, cancel function is returned as a // second argument. Caller should call this function to signal that CSR has been // completed or failed.
[ "getOrCreateRequestContext", "creates", "a", "new", "certificate", "request", "for", "a", "given", "context", "if", "there", "is", "no", "active", "CSR", "request", "in", "progress", "or", "returns", "an", "existing", "one", ".", "if", "the", "new", "context", "has", "been", "created", "cancel", "function", "is", "returned", "as", "a", "second", "argument", ".", "Caller", "should", "call", "this", "function", "to", "signal", "that", "CSR", "has", "been", "completed", "or", "failed", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/forwarder.go#L936-L951
train
gravitational/teleport
lib/multiplexer/proxyline.go
String
func (p *ProxyLine) String() string { return fmt.Sprintf("PROXY %s %s %s %d %d\r\n", p.Protocol, p.Source.IP.String(), p.Destination.IP.String(), p.Source.Port, p.Destination.Port) }
go
func (p *ProxyLine) String() string { return fmt.Sprintf("PROXY %s %s %s %d %d\r\n", p.Protocol, p.Source.IP.String(), p.Destination.IP.String(), p.Source.Port, p.Destination.Port) }
[ "func", "(", "p", "*", "ProxyLine", ")", "String", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\\r", "\\n", "\"", ",", "p", ".", "Protocol", ",", "p", ".", "Source", ".", "IP", ".", "String", "(", ")", ",", "p", ".", "Destination", ".", "IP", ".", "String", "(", ")", ",", "p", ".", "Source", ".", "Port", ",", "p", ".", "Destination", ".", "Port", ")", "\n", "}" ]
// String returns on-the wire string representation of the proxy line
[ "String", "returns", "on", "-", "the", "wire", "string", "representation", "of", "the", "proxy", "line" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/multiplexer/proxyline.go#L55-L57
train
gravitational/teleport
lib/multiplexer/proxyline.go
ReadProxyLine
func ReadProxyLine(reader *bufio.Reader) (*ProxyLine, error) { line, err := reader.ReadString('\n') if err != nil { return nil, trace.Wrap(err) } if !strings.HasSuffix(line, proxyCRLF) { return nil, trace.BadParameter("expected CRLF in proxy protocol, got something else") } tokens := strings.Split(line[:len(line)-2], proxySep) ret := ProxyLine{} if len(tokens) < 6 { return nil, trace.BadParameter("malformed PROXY line protocol string") } switch tokens[1] { case TCP4: ret.Protocol = TCP4 case TCP6: ret.Protocol = TCP6 default: ret.Protocol = UNKNOWN } sourceIP, err := parseIP(ret.Protocol, tokens[2]) if err != nil { return nil, trace.Wrap(err) } destIP, err := parseIP(ret.Protocol, tokens[3]) if err != nil { return nil, trace.Wrap(err) } sourcePort, err := parsePortNumber(tokens[4]) if err != nil { return nil, trace.Wrap(err) } destPort, err := parsePortNumber(tokens[5]) if err != nil { return nil, err } ret.Source = net.TCPAddr{IP: sourceIP, Port: sourcePort} ret.Destination = net.TCPAddr{IP: destIP, Port: destPort} return &ret, nil }
go
func ReadProxyLine(reader *bufio.Reader) (*ProxyLine, error) { line, err := reader.ReadString('\n') if err != nil { return nil, trace.Wrap(err) } if !strings.HasSuffix(line, proxyCRLF) { return nil, trace.BadParameter("expected CRLF in proxy protocol, got something else") } tokens := strings.Split(line[:len(line)-2], proxySep) ret := ProxyLine{} if len(tokens) < 6 { return nil, trace.BadParameter("malformed PROXY line protocol string") } switch tokens[1] { case TCP4: ret.Protocol = TCP4 case TCP6: ret.Protocol = TCP6 default: ret.Protocol = UNKNOWN } sourceIP, err := parseIP(ret.Protocol, tokens[2]) if err != nil { return nil, trace.Wrap(err) } destIP, err := parseIP(ret.Protocol, tokens[3]) if err != nil { return nil, trace.Wrap(err) } sourcePort, err := parsePortNumber(tokens[4]) if err != nil { return nil, trace.Wrap(err) } destPort, err := parsePortNumber(tokens[5]) if err != nil { return nil, err } ret.Source = net.TCPAddr{IP: sourceIP, Port: sourcePort} ret.Destination = net.TCPAddr{IP: destIP, Port: destPort} return &ret, nil }
[ "func", "ReadProxyLine", "(", "reader", "*", "bufio", ".", "Reader", ")", "(", "*", "ProxyLine", ",", "error", ")", "{", "line", ",", "err", ":=", "reader", ".", "ReadString", "(", "'\\n'", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "!", "strings", ".", "HasSuffix", "(", "line", ",", "proxyCRLF", ")", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n", "tokens", ":=", "strings", ".", "Split", "(", "line", "[", ":", "len", "(", "line", ")", "-", "2", "]", ",", "proxySep", ")", "\n", "ret", ":=", "ProxyLine", "{", "}", "\n", "if", "len", "(", "tokens", ")", "<", "6", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n", "switch", "tokens", "[", "1", "]", "{", "case", "TCP4", ":", "ret", ".", "Protocol", "=", "TCP4", "\n", "case", "TCP6", ":", "ret", ".", "Protocol", "=", "TCP6", "\n", "default", ":", "ret", ".", "Protocol", "=", "UNKNOWN", "\n", "}", "\n", "sourceIP", ",", "err", ":=", "parseIP", "(", "ret", ".", "Protocol", ",", "tokens", "[", "2", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "destIP", ",", "err", ":=", "parseIP", "(", "ret", ".", "Protocol", ",", "tokens", "[", "3", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "sourcePort", ",", "err", ":=", "parsePortNumber", "(", "tokens", "[", "4", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "destPort", ",", "err", ":=", "parsePortNumber", "(", "tokens", "[", "5", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "ret", ".", "Source", "=", "net", ".", "TCPAddr", "{", "IP", ":", "sourceIP", ",", "Port", ":", "sourcePort", "}", "\n", "ret", ".", "Destination", "=", "net", ".", "TCPAddr", "{", "IP", ":", "destIP", ",", "Port", ":", "destPort", "}", "\n", "return", "&", "ret", ",", "nil", "\n", "}" ]
// ReadProxyLine reads proxy line protocol from the reader
[ "ReadProxyLine", "reads", "proxy", "line", "protocol", "from", "the", "reader" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/multiplexer/proxyline.go#L60-L100
train
gravitational/teleport
lib/service/state.go
newProcessState
func newProcessState(process *TeleportProcess) *processState { return &processState{ process: process, recoveryTime: process.Clock.Now(), currentState: stateOK, } }
go
func newProcessState(process *TeleportProcess) *processState { return &processState{ process: process, recoveryTime: process.Clock.Now(), currentState: stateOK, } }
[ "func", "newProcessState", "(", "process", "*", "TeleportProcess", ")", "*", "processState", "{", "return", "&", "processState", "{", "process", ":", "process", ",", "recoveryTime", ":", "process", ".", "Clock", ".", "Now", "(", ")", ",", "currentState", ":", "stateOK", ",", "}", "\n", "}" ]
// newProcessState returns a new FSM that tracks the state of the Teleport process.
[ "newProcessState", "returns", "a", "new", "FSM", "that", "tracks", "the", "state", "of", "the", "Teleport", "process", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/state.go#L46-L52
train
gravitational/teleport
lib/service/state.go
Process
func (f *processState) Process(event Event) { switch event.Name { // Ready event means Teleport has started successfully. case TeleportReadyEvent: atomic.StoreInt64(&f.currentState, stateOK) f.process.Infof("Detected that service started and joined the cluster successfully.") // If a degraded event was received, always change the state to degraded. case TeleportDegradedEvent: atomic.StoreInt64(&f.currentState, stateDegraded) f.process.Infof("Detected Teleport is running in a degraded state.") // If the current state is degraded, and a OK event has been // received, change the state to recovering. If the current state is // recovering and a OK events is received, if it's been longer // than the recovery time (2 time the server keep alive ttl), change // state to OK. case TeleportOKEvent: switch atomic.LoadInt64(&f.currentState) { case stateDegraded: atomic.StoreInt64(&f.currentState, stateRecovering) f.recoveryTime = f.process.Clock.Now() f.process.Infof("Teleport is recovering from a degraded state.") case stateRecovering: if f.process.Clock.Now().Sub(f.recoveryTime) > defaults.ServerKeepAliveTTL*2 { atomic.StoreInt64(&f.currentState, stateOK) f.process.Infof("Teleport has recovered from a degraded state.") } } } }
go
func (f *processState) Process(event Event) { switch event.Name { // Ready event means Teleport has started successfully. case TeleportReadyEvent: atomic.StoreInt64(&f.currentState, stateOK) f.process.Infof("Detected that service started and joined the cluster successfully.") // If a degraded event was received, always change the state to degraded. case TeleportDegradedEvent: atomic.StoreInt64(&f.currentState, stateDegraded) f.process.Infof("Detected Teleport is running in a degraded state.") // If the current state is degraded, and a OK event has been // received, change the state to recovering. If the current state is // recovering and a OK events is received, if it's been longer // than the recovery time (2 time the server keep alive ttl), change // state to OK. case TeleportOKEvent: switch atomic.LoadInt64(&f.currentState) { case stateDegraded: atomic.StoreInt64(&f.currentState, stateRecovering) f.recoveryTime = f.process.Clock.Now() f.process.Infof("Teleport is recovering from a degraded state.") case stateRecovering: if f.process.Clock.Now().Sub(f.recoveryTime) > defaults.ServerKeepAliveTTL*2 { atomic.StoreInt64(&f.currentState, stateOK) f.process.Infof("Teleport has recovered from a degraded state.") } } } }
[ "func", "(", "f", "*", "processState", ")", "Process", "(", "event", "Event", ")", "{", "switch", "event", ".", "Name", "{", "// Ready event means Teleport has started successfully.", "case", "TeleportReadyEvent", ":", "atomic", ".", "StoreInt64", "(", "&", "f", ".", "currentState", ",", "stateOK", ")", "\n", "f", ".", "process", ".", "Infof", "(", "\"", "\"", ")", "\n", "// If a degraded event was received, always change the state to degraded.", "case", "TeleportDegradedEvent", ":", "atomic", ".", "StoreInt64", "(", "&", "f", ".", "currentState", ",", "stateDegraded", ")", "\n", "f", ".", "process", ".", "Infof", "(", "\"", "\"", ")", "\n", "// If the current state is degraded, and a OK event has been", "// received, change the state to recovering. If the current state is", "// recovering and a OK events is received, if it's been longer", "// than the recovery time (2 time the server keep alive ttl), change", "// state to OK.", "case", "TeleportOKEvent", ":", "switch", "atomic", ".", "LoadInt64", "(", "&", "f", ".", "currentState", ")", "{", "case", "stateDegraded", ":", "atomic", ".", "StoreInt64", "(", "&", "f", ".", "currentState", ",", "stateRecovering", ")", "\n", "f", ".", "recoveryTime", "=", "f", ".", "process", ".", "Clock", ".", "Now", "(", ")", "\n", "f", ".", "process", ".", "Infof", "(", "\"", "\"", ")", "\n", "case", "stateRecovering", ":", "if", "f", ".", "process", ".", "Clock", ".", "Now", "(", ")", ".", "Sub", "(", "f", ".", "recoveryTime", ")", ">", "defaults", ".", "ServerKeepAliveTTL", "*", "2", "{", "atomic", ".", "StoreInt64", "(", "&", "f", ".", "currentState", ",", "stateOK", ")", "\n", "f", ".", "process", ".", "Infof", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// Process updates the state of Teleport.
[ "Process", "updates", "the", "state", "of", "Teleport", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/state.go#L55-L83
train
gravitational/teleport
lib/utils/addr.go
Host
func (a *NetAddr) Host() string { host, _, err := net.SplitHostPort(a.Addr) if err != nil { return a.Addr } return host }
go
func (a *NetAddr) Host() string { host, _, err := net.SplitHostPort(a.Addr) if err != nil { return a.Addr } return host }
[ "func", "(", "a", "*", "NetAddr", ")", "Host", "(", ")", "string", "{", "host", ",", "_", ",", "err", ":=", "net", ".", "SplitHostPort", "(", "a", ".", "Addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "a", ".", "Addr", "\n", "}", "\n", "return", "host", "\n", "}" ]
// Host returns host part of address without port
[ "Host", "returns", "host", "part", "of", "address", "without", "port" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/addr.go#L42-L48
train
gravitational/teleport
lib/utils/addr.go
Port
func (a *NetAddr) Port(defaultPort int) int { _, port, err := net.SplitHostPort(a.Addr) if err != nil { return defaultPort } porti, err := strconv.Atoi(port) if err != nil { return defaultPort } return porti }
go
func (a *NetAddr) Port(defaultPort int) int { _, port, err := net.SplitHostPort(a.Addr) if err != nil { return defaultPort } porti, err := strconv.Atoi(port) if err != nil { return defaultPort } return porti }
[ "func", "(", "a", "*", "NetAddr", ")", "Port", "(", "defaultPort", "int", ")", "int", "{", "_", ",", "port", ",", "err", ":=", "net", ".", "SplitHostPort", "(", "a", ".", "Addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "defaultPort", "\n", "}", "\n", "porti", ",", "err", ":=", "strconv", ".", "Atoi", "(", "port", ")", "\n", "if", "err", "!=", "nil", "{", "return", "defaultPort", "\n", "}", "\n", "return", "porti", "\n", "}" ]
// Port returns defaultPort if no port is set or is invalid, // the real port otherwise
[ "Port", "returns", "defaultPort", "if", "no", "port", "is", "set", "or", "is", "invalid", "the", "real", "port", "otherwise" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/addr.go#L52-L62
train
gravitational/teleport
lib/utils/addr.go
Equals
func (a *NetAddr) Equals(other NetAddr) bool { return a.Addr == other.Addr && a.AddrNetwork == other.AddrNetwork && a.Path == other.Path }
go
func (a *NetAddr) Equals(other NetAddr) bool { return a.Addr == other.Addr && a.AddrNetwork == other.AddrNetwork && a.Path == other.Path }
[ "func", "(", "a", "*", "NetAddr", ")", "Equals", "(", "other", "NetAddr", ")", "bool", "{", "return", "a", ".", "Addr", "==", "other", ".", "Addr", "&&", "a", ".", "AddrNetwork", "==", "other", ".", "AddrNetwork", "&&", "a", ".", "Path", "==", "other", ".", "Path", "\n", "}" ]
// Equals returns true if address is equal to other
[ "Equals", "returns", "true", "if", "address", "is", "equal", "to", "other" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/addr.go#L65-L67
train
gravitational/teleport
lib/utils/addr.go
IsLocal
func (a *NetAddr) IsLocal() bool { host, _, err := net.SplitHostPort(a.Addr) if err != nil { return false } return IsLocalhost(host) }
go
func (a *NetAddr) IsLocal() bool { host, _, err := net.SplitHostPort(a.Addr) if err != nil { return false } return IsLocalhost(host) }
[ "func", "(", "a", "*", "NetAddr", ")", "IsLocal", "(", ")", "bool", "{", "host", ",", "_", ",", "err", ":=", "net", ".", "SplitHostPort", "(", "a", ".", "Addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "return", "IsLocalhost", "(", "host", ")", "\n", "}" ]
// IsLocal returns true if this is a local address
[ "IsLocal", "returns", "true", "if", "this", "is", "a", "local", "address" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/addr.go#L70-L76
train
gravitational/teleport
lib/utils/addr.go
IsEmpty
func (a *NetAddr) IsEmpty() bool { return a.Addr == "" && a.AddrNetwork == "" && a.Path == "" }
go
func (a *NetAddr) IsEmpty() bool { return a.Addr == "" && a.AddrNetwork == "" && a.Path == "" }
[ "func", "(", "a", "*", "NetAddr", ")", "IsEmpty", "(", ")", "bool", "{", "return", "a", ".", "Addr", "==", "\"", "\"", "&&", "a", ".", "AddrNetwork", "==", "\"", "\"", "&&", "a", ".", "Path", "==", "\"", "\"", "\n", "}" ]
// IsEmpty returns true if address is empty
[ "IsEmpty", "returns", "true", "if", "address", "is", "empty" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/addr.go#L84-L86
train
gravitational/teleport
lib/utils/addr.go
MarshalYAML
func (a *NetAddr) MarshalYAML() (interface{}, error) { url := url.URL{Scheme: a.AddrNetwork, Host: a.Addr, Path: a.Path} return strings.TrimLeft(url.String(), "/"), nil }
go
func (a *NetAddr) MarshalYAML() (interface{}, error) { url := url.URL{Scheme: a.AddrNetwork, Host: a.Addr, Path: a.Path} return strings.TrimLeft(url.String(), "/"), nil }
[ "func", "(", "a", "*", "NetAddr", ")", "MarshalYAML", "(", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "url", ":=", "url", ".", "URL", "{", "Scheme", ":", "a", ".", "AddrNetwork", ",", "Host", ":", "a", ".", "Addr", ",", "Path", ":", "a", ".", "Path", "}", "\n", "return", "strings", ".", "TrimLeft", "(", "url", ".", "String", "(", ")", ",", "\"", "\"", ")", ",", "nil", "\n", "}" ]
// MarshalYAML defines how a network address should be marshalled to a string
[ "MarshalYAML", "defines", "how", "a", "network", "address", "should", "be", "marshalled", "to", "a", "string" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/addr.go#L104-L107
train
gravitational/teleport
lib/utils/addr.go
UnmarshalYAML
func (a *NetAddr) UnmarshalYAML(unmarshal func(interface{}) error) error { var addr string err := unmarshal(&addr) if err != nil { return err } parsedAddr, err := ParseAddr(addr) if err != nil { return err } *a = *parsedAddr return nil }
go
func (a *NetAddr) UnmarshalYAML(unmarshal func(interface{}) error) error { var addr string err := unmarshal(&addr) if err != nil { return err } parsedAddr, err := ParseAddr(addr) if err != nil { return err } *a = *parsedAddr return nil }
[ "func", "(", "a", "*", "NetAddr", ")", "UnmarshalYAML", "(", "unmarshal", "func", "(", "interface", "{", "}", ")", "error", ")", "error", "{", "var", "addr", "string", "\n", "err", ":=", "unmarshal", "(", "&", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "parsedAddr", ",", "err", ":=", "ParseAddr", "(", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "*", "a", "=", "*", "parsedAddr", "\n", "return", "nil", "\n", "}" ]
// UnmarshalYAML defines how a string can be unmarshalled into a network address
[ "UnmarshalYAML", "defines", "how", "a", "string", "can", "be", "unmarshalled", "into", "a", "network", "address" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/addr.go#L110-L124
train
gravitational/teleport
lib/utils/addr.go
MustParseAddr
func MustParseAddr(a string) *NetAddr { addr, err := ParseAddr(a) if err != nil { panic(fmt.Sprintf("failed to parse %v: %v", a, err)) } return addr }
go
func MustParseAddr(a string) *NetAddr { addr, err := ParseAddr(a) if err != nil { panic(fmt.Sprintf("failed to parse %v: %v", a, err)) } return addr }
[ "func", "MustParseAddr", "(", "a", "string", ")", "*", "NetAddr", "{", "addr", ",", "err", ":=", "ParseAddr", "(", "a", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "a", ",", "err", ")", ")", "\n", "}", "\n", "return", "addr", "\n", "}" ]
// MustParseAddr parses the provided string into NetAddr or panics on an error
[ "MustParseAddr", "parses", "the", "provided", "string", "into", "NetAddr", "or", "panics", "on", "an", "error" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/addr.go#L162-L168
train
gravitational/teleport
lib/utils/addr.go
FromAddr
func FromAddr(a net.Addr) NetAddr { return NetAddr{AddrNetwork: a.Network(), Addr: a.String()} }
go
func FromAddr(a net.Addr) NetAddr { return NetAddr{AddrNetwork: a.Network(), Addr: a.String()} }
[ "func", "FromAddr", "(", "a", "net", ".", "Addr", ")", "NetAddr", "{", "return", "NetAddr", "{", "AddrNetwork", ":", "a", ".", "Network", "(", ")", ",", "Addr", ":", "a", ".", "String", "(", ")", "}", "\n", "}" ]
// FromAddr returns NetAddr from golang standard net.Addr
[ "FromAddr", "returns", "NetAddr", "from", "golang", "standard", "net", ".", "Addr" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/addr.go#L171-L173
train
gravitational/teleport
lib/utils/addr.go
JoinAddrSlices
func JoinAddrSlices(a []NetAddr, b []NetAddr) []NetAddr { if len(a)+len(b) == 0 { return nil } out := make([]NetAddr, 0, len(a)+len(b)) out = append(out, a...) out = append(out, b...) return out }
go
func JoinAddrSlices(a []NetAddr, b []NetAddr) []NetAddr { if len(a)+len(b) == 0 { return nil } out := make([]NetAddr, 0, len(a)+len(b)) out = append(out, a...) out = append(out, b...) return out }
[ "func", "JoinAddrSlices", "(", "a", "[", "]", "NetAddr", ",", "b", "[", "]", "NetAddr", ")", "[", "]", "NetAddr", "{", "if", "len", "(", "a", ")", "+", "len", "(", "b", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "out", ":=", "make", "(", "[", "]", "NetAddr", ",", "0", ",", "len", "(", "a", ")", "+", "len", "(", "b", ")", ")", "\n", "out", "=", "append", "(", "out", ",", "a", "...", ")", "\n", "out", "=", "append", "(", "out", ",", "b", "...", ")", "\n", "return", "out", "\n", "}" ]
// JoinAddrSlices joins two addr slices and returns a resulting slice
[ "JoinAddrSlices", "joins", "two", "addr", "slices", "and", "returns", "a", "resulting", "slice" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/addr.go#L176-L184
train
gravitational/teleport
lib/utils/addr.go
DialAddrFromListenAddr
func DialAddrFromListenAddr(listenAddr NetAddr) NetAddr { if listenAddr.IsEmpty() { return listenAddr } return NetAddr{Addr: ReplaceLocalhost(listenAddr.Addr, "127.0.0.1")} }
go
func DialAddrFromListenAddr(listenAddr NetAddr) NetAddr { if listenAddr.IsEmpty() { return listenAddr } return NetAddr{Addr: ReplaceLocalhost(listenAddr.Addr, "127.0.0.1")} }
[ "func", "DialAddrFromListenAddr", "(", "listenAddr", "NetAddr", ")", "NetAddr", "{", "if", "listenAddr", ".", "IsEmpty", "(", ")", "{", "return", "listenAddr", "\n", "}", "\n", "return", "NetAddr", "{", "Addr", ":", "ReplaceLocalhost", "(", "listenAddr", ".", "Addr", ",", "\"", "\"", ")", "}", "\n", "}" ]
// DialAddrFromListenAddr returns dial address from listen address
[ "DialAddrFromListenAddr", "returns", "dial", "address", "from", "listen", "address" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/addr.go#L204-L209
train
gravitational/teleport
lib/utils/addr.go
Addresses
func (nl *NetAddrList) Addresses() []string { var ns []string for _, n := range *nl { ns = append(ns, n.FullAddress()) } return ns }
go
func (nl *NetAddrList) Addresses() []string { var ns []string for _, n := range *nl { ns = append(ns, n.FullAddress()) } return ns }
[ "func", "(", "nl", "*", "NetAddrList", ")", "Addresses", "(", ")", "[", "]", "string", "{", "var", "ns", "[", "]", "string", "\n", "for", "_", ",", "n", ":=", "range", "*", "nl", "{", "ns", "=", "append", "(", "ns", ",", "n", ".", "FullAddress", "(", ")", ")", "\n", "}", "\n", "return", "ns", "\n", "}" ]
// Addresses returns a slice of strings converted from the addresses
[ "Addresses", "returns", "a", "slice", "of", "strings", "converted", "from", "the", "addresses" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/addr.go#L242-L248
train
gravitational/teleport
lib/utils/addr.go
Set
func (nl *NetAddrList) Set(s string) error { v, err := ParseAddr(s) if err != nil { return err } *nl = append(*nl, *v) return nil }
go
func (nl *NetAddrList) Set(s string) error { v, err := ParseAddr(s) if err != nil { return err } *nl = append(*nl, *v) return nil }
[ "func", "(", "nl", "*", "NetAddrList", ")", "Set", "(", "s", "string", ")", "error", "{", "v", ",", "err", ":=", "ParseAddr", "(", "s", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "*", "nl", "=", "append", "(", "*", "nl", ",", "*", "v", ")", "\n", "return", "nil", "\n", "}" ]
// Set is called by CLI tools
[ "Set", "is", "called", "by", "CLI", "tools" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/addr.go#L251-L259
train
gravitational/teleport
lib/utils/addr.go
String
func (nl *NetAddrList) String() string { var ns []string for _, n := range *nl { ns = append(ns, n.FullAddress()) } return strings.Join(ns, " ") }
go
func (nl *NetAddrList) String() string { var ns []string for _, n := range *nl { ns = append(ns, n.FullAddress()) } return strings.Join(ns, " ") }
[ "func", "(", "nl", "*", "NetAddrList", ")", "String", "(", ")", "string", "{", "var", "ns", "[", "]", "string", "\n", "for", "_", ",", "n", ":=", "range", "*", "nl", "{", "ns", "=", "append", "(", "ns", ",", "n", ".", "FullAddress", "(", ")", ")", "\n", "}", "\n", "return", "strings", ".", "Join", "(", "ns", ",", "\"", "\"", ")", "\n", "}" ]
// String returns debug-friendly representation of the tool
[ "String", "returns", "debug", "-", "friendly", "representation", "of", "the", "tool" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/addr.go#L262-L268
train
gravitational/teleport
lib/utils/addr.go
IsLocalhost
func IsLocalhost(host string) bool { if host == "localhost" { return true } ip := net.ParseIP(host) return ip.IsLoopback() || ip.IsUnspecified() }
go
func IsLocalhost(host string) bool { if host == "localhost" { return true } ip := net.ParseIP(host) return ip.IsLoopback() || ip.IsUnspecified() }
[ "func", "IsLocalhost", "(", "host", "string", ")", "bool", "{", "if", "host", "==", "\"", "\"", "{", "return", "true", "\n", "}", "\n", "ip", ":=", "net", ".", "ParseIP", "(", "host", ")", "\n", "return", "ip", ".", "IsLoopback", "(", ")", "||", "ip", ".", "IsUnspecified", "(", ")", "\n", "}" ]
// IsLocalhost returns true if this is a local hostname or ip
[ "IsLocalhost", "returns", "true", "if", "this", "is", "a", "local", "hostname", "or", "ip" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/addr.go#L291-L297
train
gravitational/teleport
lib/utils/addr.go
IsLoopback
func IsLoopback(host string) bool { if strings.Contains(host, ":") { var err error host, _, err = net.SplitHostPort(host) if err != nil { return false } } ips, err := net.LookupIP(host) if err != nil { return false } for _, ip := range ips { if ip.IsLoopback() { return true } } return false }
go
func IsLoopback(host string) bool { if strings.Contains(host, ":") { var err error host, _, err = net.SplitHostPort(host) if err != nil { return false } } ips, err := net.LookupIP(host) if err != nil { return false } for _, ip := range ips { if ip.IsLoopback() { return true } } return false }
[ "func", "IsLoopback", "(", "host", "string", ")", "bool", "{", "if", "strings", ".", "Contains", "(", "host", ",", "\"", "\"", ")", "{", "var", "err", "error", "\n", "host", ",", "_", ",", "err", "=", "net", ".", "SplitHostPort", "(", "host", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "}", "\n", "ips", ",", "err", ":=", "net", ".", "LookupIP", "(", "host", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "for", "_", ",", "ip", ":=", "range", "ips", "{", "if", "ip", ".", "IsLoopback", "(", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsLoopback returns 'true' if a given hostname resolves to local // host's loopback interface
[ "IsLoopback", "returns", "true", "if", "a", "given", "hostname", "resolves", "to", "local", "host", "s", "loopback", "interface" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/addr.go#L301-L319
train
gravitational/teleport
lib/utils/addr.go
GuessHostIP
func GuessHostIP() (ip net.IP, err error) { ifaces, err := net.Interfaces() if err != nil { return nil, trace.Wrap(err) } adrs := make([]net.Addr, 0) for _, iface := range ifaces { ifadrs, err := iface.Addrs() if err != nil { log.Warn(err) } else { adrs = append(adrs, ifadrs...) } } return guessHostIP(adrs), nil }
go
func GuessHostIP() (ip net.IP, err error) { ifaces, err := net.Interfaces() if err != nil { return nil, trace.Wrap(err) } adrs := make([]net.Addr, 0) for _, iface := range ifaces { ifadrs, err := iface.Addrs() if err != nil { log.Warn(err) } else { adrs = append(adrs, ifadrs...) } } return guessHostIP(adrs), nil }
[ "func", "GuessHostIP", "(", ")", "(", "ip", "net", ".", "IP", ",", "err", "error", ")", "{", "ifaces", ",", "err", ":=", "net", ".", "Interfaces", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "adrs", ":=", "make", "(", "[", "]", "net", ".", "Addr", ",", "0", ")", "\n", "for", "_", ",", "iface", ":=", "range", "ifaces", "{", "ifadrs", ",", "err", ":=", "iface", ".", "Addrs", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Warn", "(", "err", ")", "\n", "}", "else", "{", "adrs", "=", "append", "(", "adrs", ",", "ifadrs", "...", ")", "\n", "}", "\n", "}", "\n", "return", "guessHostIP", "(", "adrs", ")", ",", "nil", "\n", "}" ]
// GuessIP tries to guess an IP address this machine is reachable at on the // internal network, always picking IPv4 from the internal address space // // If no internal IPs are found, it returns 127.0.0.1 but it never returns // an address from the public IP space
[ "GuessIP", "tries", "to", "guess", "an", "IP", "address", "this", "machine", "is", "reachable", "at", "on", "the", "internal", "network", "always", "picking", "IPv4", "from", "the", "internal", "address", "space", "If", "no", "internal", "IPs", "are", "found", "it", "returns", "127", ".", "0", ".", "0", ".", "1", "but", "it", "never", "returns", "an", "address", "from", "the", "public", "IP", "space" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/addr.go#L326-L341
train
gravitational/teleport
lib/auth/mocku2f/mocku2f.go
decodeBase64
func decodeBase64(s string) ([]byte, error) { for i := 0; i < len(s)%4; i++ { s += "=" } return base64.URLEncoding.DecodeString(s) }
go
func decodeBase64(s string) ([]byte, error) { for i := 0; i < len(s)%4; i++ { s += "=" } return base64.URLEncoding.DecodeString(s) }
[ "func", "decodeBase64", "(", "s", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "s", ")", "%", "4", ";", "i", "++", "{", "s", "+=", "\"", "\"", "\n", "}", "\n", "return", "base64", ".", "URLEncoding", ".", "DecodeString", "(", "s", ")", "\n", "}" ]
// The "websafe-base64 encoding" in the U2F specifications removes the padding
[ "The", "websafe", "-", "base64", "encoding", "in", "the", "U2F", "specifications", "removes", "the", "padding" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/mocku2f/mocku2f.go#L52-L57
train
gravitational/teleport
lib/reversetunnel/peer.go
newClusterPeer
func newClusterPeer(srv *server, connInfo services.TunnelConnection) (*clusterPeer, error) { clusterPeer := &clusterPeer{ srv: srv, connInfo: connInfo, log: log.WithFields(log.Fields{ trace.Component: teleport.ComponentReverseTunnelServer, trace.ComponentFields: map[string]string{ "cluster": connInfo.GetClusterName(), }, }), } return clusterPeer, nil }
go
func newClusterPeer(srv *server, connInfo services.TunnelConnection) (*clusterPeer, error) { clusterPeer := &clusterPeer{ srv: srv, connInfo: connInfo, log: log.WithFields(log.Fields{ trace.Component: teleport.ComponentReverseTunnelServer, trace.ComponentFields: map[string]string{ "cluster": connInfo.GetClusterName(), }, }), } return clusterPeer, nil }
[ "func", "newClusterPeer", "(", "srv", "*", "server", ",", "connInfo", "services", ".", "TunnelConnection", ")", "(", "*", "clusterPeer", ",", "error", ")", "{", "clusterPeer", ":=", "&", "clusterPeer", "{", "srv", ":", "srv", ",", "connInfo", ":", "connInfo", ",", "log", ":", "log", ".", "WithFields", "(", "log", ".", "Fields", "{", "trace", ".", "Component", ":", "teleport", ".", "ComponentReverseTunnelServer", ",", "trace", ".", "ComponentFields", ":", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "connInfo", ".", "GetClusterName", "(", ")", ",", "}", ",", "}", ")", ",", "}", "\n\n", "return", "clusterPeer", ",", "nil", "\n", "}" ]
// newClusterPeer returns new cluster peer
[ "newClusterPeer", "returns", "new", "cluster", "peer" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/peer.go#L136-L149
train
gravitational/teleport
lib/utils/otp.go
GenerateQRCode
func GenerateQRCode(u string) ([]byte, error) { otpKey, err := otp.NewKeyFromURL(u) if err != nil { return nil, trace.Wrap(err) } otpImage, err := otpKey.Image(450, 450) if err != nil { return nil, trace.Wrap(err) } var otpQR bytes.Buffer err = png.Encode(&otpQR, otpImage) if err != nil { return nil, trace.Wrap(err) } return otpQR.Bytes(), nil }
go
func GenerateQRCode(u string) ([]byte, error) { otpKey, err := otp.NewKeyFromURL(u) if err != nil { return nil, trace.Wrap(err) } otpImage, err := otpKey.Image(450, 450) if err != nil { return nil, trace.Wrap(err) } var otpQR bytes.Buffer err = png.Encode(&otpQR, otpImage) if err != nil { return nil, trace.Wrap(err) } return otpQR.Bytes(), nil }
[ "func", "GenerateQRCode", "(", "u", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "otpKey", ",", "err", ":=", "otp", ".", "NewKeyFromURL", "(", "u", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "otpImage", ",", "err", ":=", "otpKey", ".", "Image", "(", "450", ",", "450", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "var", "otpQR", "bytes", ".", "Buffer", "\n", "err", "=", "png", ".", "Encode", "(", "&", "otpQR", ",", "otpImage", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "return", "otpQR", ".", "Bytes", "(", ")", ",", "nil", "\n", "}" ]
// GenerateQRCode takes in a OTP Key URL and returns a PNG-encoded QR code.
[ "GenerateQRCode", "takes", "in", "a", "OTP", "Key", "URL", "and", "returns", "a", "PNG", "-", "encoded", "QR", "code", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/otp.go#L15-L33
train
gravitational/teleport
lib/web/password.go
changePassword
func (h *Handler) changePassword(w http.ResponseWriter, r *http.Request, p httprouter.Params, ctx *SessionContext) (interface{}, error) { var req *changePasswordReq if err := httplib.ReadJSON(r, &req); err != nil { return nil, trace.Wrap(err) } clt, err := ctx.GetClient() if err != nil { return nil, trace.Wrap(err) } servicedReq := services.ChangePasswordReq{ User: ctx.GetUser(), OldPassword: req.OldPassword, NewPassword: req.NewPassword, SecondFactorToken: req.SecondFactorToken, U2FSignResponse: req.U2FSignResponse, } err = clt.ChangePassword(servicedReq) if err != nil { return nil, trace.Wrap(err) } return ok(), nil }
go
func (h *Handler) changePassword(w http.ResponseWriter, r *http.Request, p httprouter.Params, ctx *SessionContext) (interface{}, error) { var req *changePasswordReq if err := httplib.ReadJSON(r, &req); err != nil { return nil, trace.Wrap(err) } clt, err := ctx.GetClient() if err != nil { return nil, trace.Wrap(err) } servicedReq := services.ChangePasswordReq{ User: ctx.GetUser(), OldPassword: req.OldPassword, NewPassword: req.NewPassword, SecondFactorToken: req.SecondFactorToken, U2FSignResponse: req.U2FSignResponse, } err = clt.ChangePassword(servicedReq) if err != nil { return nil, trace.Wrap(err) } return ok(), nil }
[ "func", "(", "h", "*", "Handler", ")", "changePassword", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ",", "p", "httprouter", ".", "Params", ",", "ctx", "*", "SessionContext", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "var", "req", "*", "changePasswordReq", "\n", "if", "err", ":=", "httplib", ".", "ReadJSON", "(", "r", ",", "&", "req", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "clt", ",", "err", ":=", "ctx", ".", "GetClient", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "servicedReq", ":=", "services", ".", "ChangePasswordReq", "{", "User", ":", "ctx", ".", "GetUser", "(", ")", ",", "OldPassword", ":", "req", ".", "OldPassword", ",", "NewPassword", ":", "req", ".", "NewPassword", ",", "SecondFactorToken", ":", "req", ".", "SecondFactorToken", ",", "U2FSignResponse", ":", "req", ".", "U2FSignResponse", ",", "}", "\n\n", "err", "=", "clt", ".", "ChangePassword", "(", "servicedReq", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "return", "ok", "(", ")", ",", "nil", "\n", "}" ]
// changePassword updates users password based on the old password
[ "changePassword", "updates", "users", "password", "based", "on", "the", "old", "password" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/password.go#L45-L70
train
gravitational/teleport
lib/web/password.go
u2fChangePasswordRequest
func (h *Handler) u2fChangePasswordRequest(w http.ResponseWriter, r *http.Request, _ httprouter.Params, ctx *SessionContext) (interface{}, error) { var req *client.U2fSignRequestReq if err := httplib.ReadJSON(r, &req); err != nil { return nil, trace.Wrap(err) } clt, err := ctx.GetClient() if err != nil { return nil, trace.Wrap(err) } u2fReq, err := clt.GetU2FSignRequest(ctx.GetUser(), []byte(req.Pass)) if err != nil && trace.IsAccessDenied(err) { // logout in case of access denied logoutErr := h.logout(w, ctx) if logoutErr != nil { return nil, trace.Wrap(logoutErr) } } if err != nil { return nil, trace.Wrap(err) } return u2fReq, nil }
go
func (h *Handler) u2fChangePasswordRequest(w http.ResponseWriter, r *http.Request, _ httprouter.Params, ctx *SessionContext) (interface{}, error) { var req *client.U2fSignRequestReq if err := httplib.ReadJSON(r, &req); err != nil { return nil, trace.Wrap(err) } clt, err := ctx.GetClient() if err != nil { return nil, trace.Wrap(err) } u2fReq, err := clt.GetU2FSignRequest(ctx.GetUser(), []byte(req.Pass)) if err != nil && trace.IsAccessDenied(err) { // logout in case of access denied logoutErr := h.logout(w, ctx) if logoutErr != nil { return nil, trace.Wrap(logoutErr) } } if err != nil { return nil, trace.Wrap(err) } return u2fReq, nil }
[ "func", "(", "h", "*", "Handler", ")", "u2fChangePasswordRequest", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ",", "_", "httprouter", ".", "Params", ",", "ctx", "*", "SessionContext", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "var", "req", "*", "client", ".", "U2fSignRequestReq", "\n", "if", "err", ":=", "httplib", ".", "ReadJSON", "(", "r", ",", "&", "req", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "clt", ",", "err", ":=", "ctx", ".", "GetClient", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "u2fReq", ",", "err", ":=", "clt", ".", "GetU2FSignRequest", "(", "ctx", ".", "GetUser", "(", ")", ",", "[", "]", "byte", "(", "req", ".", "Pass", ")", ")", "\n", "if", "err", "!=", "nil", "&&", "trace", ".", "IsAccessDenied", "(", "err", ")", "{", "// logout in case of access denied", "logoutErr", ":=", "h", ".", "logout", "(", "w", ",", "ctx", ")", "\n", "if", "logoutErr", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "logoutErr", ")", "\n", "}", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "return", "u2fReq", ",", "nil", "\n", "}" ]
// u2fChangePasswordRequest is called to get U2F challedge for changing a user password
[ "u2fChangePasswordRequest", "is", "called", "to", "get", "U2F", "challedge", "for", "changing", "a", "user", "password" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/password.go#L73-L98
train
gravitational/teleport
lib/web/static.go
NewStaticFileSystem
func NewStaticFileSystem(debugMode bool) (http.FileSystem, error) { if debugMode { assetsToCheck := []string{"index.html", "/app"} if debugAssetsPath == "" { exePath, err := osext.ExecutableFolder() if err != nil { return nil, trace.Wrap(err) } debugAssetsPath = path.Join(exePath, "../web/dist") } for _, af := range assetsToCheck { _, err := os.Stat(filepath.Join(debugAssetsPath, af)) if err != nil { return nil, trace.Wrap(err) } } log.Infof("[Web] Using filesystem for serving web assets: %s", debugAssetsPath) return http.Dir(debugAssetsPath), nil } // otherwise, lets use the zip archive attached to the executable: return loadZippedExeAssets() }
go
func NewStaticFileSystem(debugMode bool) (http.FileSystem, error) { if debugMode { assetsToCheck := []string{"index.html", "/app"} if debugAssetsPath == "" { exePath, err := osext.ExecutableFolder() if err != nil { return nil, trace.Wrap(err) } debugAssetsPath = path.Join(exePath, "../web/dist") } for _, af := range assetsToCheck { _, err := os.Stat(filepath.Join(debugAssetsPath, af)) if err != nil { return nil, trace.Wrap(err) } } log.Infof("[Web] Using filesystem for serving web assets: %s", debugAssetsPath) return http.Dir(debugAssetsPath), nil } // otherwise, lets use the zip archive attached to the executable: return loadZippedExeAssets() }
[ "func", "NewStaticFileSystem", "(", "debugMode", "bool", ")", "(", "http", ".", "FileSystem", ",", "error", ")", "{", "if", "debugMode", "{", "assetsToCheck", ":=", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", "}", "\n\n", "if", "debugAssetsPath", "==", "\"", "\"", "{", "exePath", ",", "err", ":=", "osext", ".", "ExecutableFolder", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "debugAssetsPath", "=", "path", ".", "Join", "(", "exePath", ",", "\"", "\"", ")", "\n", "}", "\n\n", "for", "_", ",", "af", ":=", "range", "assetsToCheck", "{", "_", ",", "err", ":=", "os", ".", "Stat", "(", "filepath", ".", "Join", "(", "debugAssetsPath", ",", "af", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "}", "\n", "log", ".", "Infof", "(", "\"", "\"", ",", "debugAssetsPath", ")", "\n", "return", "http", ".", "Dir", "(", "debugAssetsPath", ")", ",", "nil", "\n", "}", "\n\n", "// otherwise, lets use the zip archive attached to the executable:", "return", "loadZippedExeAssets", "(", ")", "\n", "}" ]
// NewStaticFileSystem returns the initialized implementation of http.FileSystem // interface which can be used to serve Teleport Proxy Web UI // // If 'debugMode' is true, it will load the web assets from the same git repo // directory where the executable is, otherwise it will load them from the embedded // zip archive. //
[ "NewStaticFileSystem", "returns", "the", "initialized", "implementation", "of", "http", ".", "FileSystem", "interface", "which", "can", "be", "used", "to", "serve", "Teleport", "Proxy", "Web", "UI", "If", "debugMode", "is", "true", "it", "will", "load", "the", "web", "assets", "from", "the", "same", "git", "repo", "directory", "where", "the", "executable", "is", "otherwise", "it", "will", "load", "them", "from", "the", "embedded", "zip", "archive", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/static.go#L53-L77
train
gravitational/teleport
lib/web/static.go
isDebugMode
func isDebugMode() bool { v, _ := strconv.ParseBool(os.Getenv(teleport.DebugEnvVar)) return v }
go
func isDebugMode() bool { v, _ := strconv.ParseBool(os.Getenv(teleport.DebugEnvVar)) return v }
[ "func", "isDebugMode", "(", ")", "bool", "{", "v", ",", "_", ":=", "strconv", ".", "ParseBool", "(", "os", ".", "Getenv", "(", "teleport", ".", "DebugEnvVar", ")", ")", "\n", "return", "v", "\n", "}" ]
// isDebugMode determines if teleport is running in a "debug" mode. // It looks at DEBUG environment variable
[ "isDebugMode", "determines", "if", "teleport", "is", "running", "in", "a", "debug", "mode", ".", "It", "looks", "at", "DEBUG", "environment", "variable" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/static.go#L81-L84
train
gravitational/teleport
lib/web/static.go
loadZippedExeAssets
func loadZippedExeAssets() (ResourceMap, error) { // open ourselves (teleport binary) for reading: // NOTE: the file stays open to serve future Read() requests myExe, err := osext.Executable() if err != nil { return nil, trace.Wrap(err) } return readZipArchive(myExe) }
go
func loadZippedExeAssets() (ResourceMap, error) { // open ourselves (teleport binary) for reading: // NOTE: the file stays open to serve future Read() requests myExe, err := osext.Executable() if err != nil { return nil, trace.Wrap(err) } return readZipArchive(myExe) }
[ "func", "loadZippedExeAssets", "(", ")", "(", "ResourceMap", ",", "error", ")", "{", "// open ourselves (teleport binary) for reading:", "// NOTE: the file stays open to serve future Read() requests", "myExe", ",", "err", ":=", "osext", ".", "Executable", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "readZipArchive", "(", "myExe", ")", "\n", "}" ]
// LoadWebResources returns a filesystem implementation compatible // with http.Serve. // // The "filesystem" is served from a zip file attached at the end of // the executable //
[ "LoadWebResources", "returns", "a", "filesystem", "implementation", "compatible", "with", "http", ".", "Serve", ".", "The", "filesystem", "is", "served", "from", "a", "zip", "file", "attached", "at", "the", "end", "of", "the", "executable" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/static.go#L92-L100
train
gravitational/teleport
lib/auth/register.go
LocalRegister
func LocalRegister(id IdentityID, authServer *AuthServer, additionalPrincipals, dnsNames []string, remoteAddr string) (*Identity, error) { // If local registration is happening and no remote address was passed in // (which means no advertise IP was set), use localhost. if remoteAddr == "" { remoteAddr = defaults.Localhost } keys, err := authServer.GenerateServerKeys(GenerateServerKeysRequest{ HostID: id.HostUUID, NodeName: id.NodeName, Roles: teleport.Roles{id.Role}, AdditionalPrincipals: additionalPrincipals, RemoteAddr: remoteAddr, DNSNames: dnsNames, NoCache: true, }) if err != nil { return nil, trace.Wrap(err) } identity, err := ReadIdentityFromKeyPair(keys) if err != nil { return nil, trace.Wrap(err) } return identity, nil }
go
func LocalRegister(id IdentityID, authServer *AuthServer, additionalPrincipals, dnsNames []string, remoteAddr string) (*Identity, error) { // If local registration is happening and no remote address was passed in // (which means no advertise IP was set), use localhost. if remoteAddr == "" { remoteAddr = defaults.Localhost } keys, err := authServer.GenerateServerKeys(GenerateServerKeysRequest{ HostID: id.HostUUID, NodeName: id.NodeName, Roles: teleport.Roles{id.Role}, AdditionalPrincipals: additionalPrincipals, RemoteAddr: remoteAddr, DNSNames: dnsNames, NoCache: true, }) if err != nil { return nil, trace.Wrap(err) } identity, err := ReadIdentityFromKeyPair(keys) if err != nil { return nil, trace.Wrap(err) } return identity, nil }
[ "func", "LocalRegister", "(", "id", "IdentityID", ",", "authServer", "*", "AuthServer", ",", "additionalPrincipals", ",", "dnsNames", "[", "]", "string", ",", "remoteAddr", "string", ")", "(", "*", "Identity", ",", "error", ")", "{", "// If local registration is happening and no remote address was passed in", "// (which means no advertise IP was set), use localhost.", "if", "remoteAddr", "==", "\"", "\"", "{", "remoteAddr", "=", "defaults", ".", "Localhost", "\n", "}", "\n", "keys", ",", "err", ":=", "authServer", ".", "GenerateServerKeys", "(", "GenerateServerKeysRequest", "{", "HostID", ":", "id", ".", "HostUUID", ",", "NodeName", ":", "id", ".", "NodeName", ",", "Roles", ":", "teleport", ".", "Roles", "{", "id", ".", "Role", "}", ",", "AdditionalPrincipals", ":", "additionalPrincipals", ",", "RemoteAddr", ":", "remoteAddr", ",", "DNSNames", ":", "dnsNames", ",", "NoCache", ":", "true", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "identity", ",", "err", ":=", "ReadIdentityFromKeyPair", "(", "keys", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "return", "identity", ",", "nil", "\n", "}" ]
// LocalRegister is used to generate host keys when a node or proxy is running // within the same process as the Auth Server and as such, does not need to // use provisioning tokens.
[ "LocalRegister", "is", "used", "to", "generate", "host", "keys", "when", "a", "node", "or", "proxy", "is", "running", "within", "the", "same", "process", "as", "the", "Auth", "Server", "and", "as", "such", "does", "not", "need", "to", "use", "provisioning", "tokens", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/register.go#L37-L62
train
gravitational/teleport
lib/auth/register.go
Register
func Register(params RegisterParams) (*Identity, error) { // Read in the token. The token can either be passed in or come from a file // on disk. token, err := readToken(params.Token) if err != nil { return nil, trace.Wrap(err) } // Attempt to register through the auth server, if it fails, try and // register through the proxy server. ident, err := registerThroughAuth(token, params) if err != nil { // If no params client was set this is a proxy and fail right away. if params.CredsClient == nil { log.Debugf("Missing client, failing with error from Auth Server: %v.", err) return nil, trace.Wrap(err) } ident, er := registerThroughProxy(token, params) if er != nil { return nil, trace.NewAggregate(err, er) } log.Debugf("Successfully registered through proxy server.") return ident, nil } log.Debugf("Successfully registered through auth server.") return ident, nil }
go
func Register(params RegisterParams) (*Identity, error) { // Read in the token. The token can either be passed in or come from a file // on disk. token, err := readToken(params.Token) if err != nil { return nil, trace.Wrap(err) } // Attempt to register through the auth server, if it fails, try and // register through the proxy server. ident, err := registerThroughAuth(token, params) if err != nil { // If no params client was set this is a proxy and fail right away. if params.CredsClient == nil { log.Debugf("Missing client, failing with error from Auth Server: %v.", err) return nil, trace.Wrap(err) } ident, er := registerThroughProxy(token, params) if er != nil { return nil, trace.NewAggregate(err, er) } log.Debugf("Successfully registered through proxy server.") return ident, nil } log.Debugf("Successfully registered through auth server.") return ident, nil }
[ "func", "Register", "(", "params", "RegisterParams", ")", "(", "*", "Identity", ",", "error", ")", "{", "// Read in the token. The token can either be passed in or come from a file", "// on disk.", "token", ",", "err", ":=", "readToken", "(", "params", ".", "Token", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "// Attempt to register through the auth server, if it fails, try and", "// register through the proxy server.", "ident", ",", "err", ":=", "registerThroughAuth", "(", "token", ",", "params", ")", "\n", "if", "err", "!=", "nil", "{", "// If no params client was set this is a proxy and fail right away.", "if", "params", ".", "CredsClient", "==", "nil", "{", "log", ".", "Debugf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "ident", ",", "er", ":=", "registerThroughProxy", "(", "token", ",", "params", ")", "\n", "if", "er", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "NewAggregate", "(", "err", ",", "er", ")", "\n", "}", "\n\n", "log", ".", "Debugf", "(", "\"", "\"", ")", "\n", "return", "ident", ",", "nil", "\n", "}", "\n\n", "log", ".", "Debugf", "(", "\"", "\"", ")", "\n", "return", "ident", ",", "nil", "\n", "}" ]
// Register is used to generate host keys when a node or proxy are running on // different hosts than the auth server. This method requires provisioning // tokens to prove a valid auth server was used to issue the joining request // as well as a method for the node to validate the auth server.
[ "Register", "is", "used", "to", "generate", "host", "keys", "when", "a", "node", "or", "proxy", "are", "running", "on", "different", "hosts", "than", "the", "auth", "server", ".", "This", "method", "requires", "provisioning", "tokens", "to", "prove", "a", "valid", "auth", "server", "was", "used", "to", "issue", "the", "joining", "request", "as", "well", "as", "a", "method", "for", "the", "node", "to", "validate", "the", "auth", "server", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/register.go#L108-L137
train
gravitational/teleport
lib/auth/register.go
registerThroughProxy
func registerThroughProxy(token string, params RegisterParams) (*Identity, error) { log.Debugf("Attempting to register through proxy server.") keys, err := params.CredsClient.HostCredentials(context.Background(), RegisterUsingTokenRequest{ Token: token, HostID: params.ID.HostUUID, NodeName: params.ID.NodeName, Role: params.ID.Role, AdditionalPrincipals: params.AdditionalPrincipals, DNSNames: params.DNSNames, PublicTLSKey: params.PublicTLSKey, PublicSSHKey: params.PublicSSHKey, }) if err != nil { return nil, trace.Wrap(err) } keys.Key = params.PrivateKey return ReadIdentityFromKeyPair(keys) }
go
func registerThroughProxy(token string, params RegisterParams) (*Identity, error) { log.Debugf("Attempting to register through proxy server.") keys, err := params.CredsClient.HostCredentials(context.Background(), RegisterUsingTokenRequest{ Token: token, HostID: params.ID.HostUUID, NodeName: params.ID.NodeName, Role: params.ID.Role, AdditionalPrincipals: params.AdditionalPrincipals, DNSNames: params.DNSNames, PublicTLSKey: params.PublicTLSKey, PublicSSHKey: params.PublicSSHKey, }) if err != nil { return nil, trace.Wrap(err) } keys.Key = params.PrivateKey return ReadIdentityFromKeyPair(keys) }
[ "func", "registerThroughProxy", "(", "token", "string", ",", "params", "RegisterParams", ")", "(", "*", "Identity", ",", "error", ")", "{", "log", ".", "Debugf", "(", "\"", "\"", ")", "\n\n", "keys", ",", "err", ":=", "params", ".", "CredsClient", ".", "HostCredentials", "(", "context", ".", "Background", "(", ")", ",", "RegisterUsingTokenRequest", "{", "Token", ":", "token", ",", "HostID", ":", "params", ".", "ID", ".", "HostUUID", ",", "NodeName", ":", "params", ".", "ID", ".", "NodeName", ",", "Role", ":", "params", ".", "ID", ".", "Role", ",", "AdditionalPrincipals", ":", "params", ".", "AdditionalPrincipals", ",", "DNSNames", ":", "params", ".", "DNSNames", ",", "PublicTLSKey", ":", "params", ".", "PublicTLSKey", ",", "PublicSSHKey", ":", "params", ".", "PublicSSHKey", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "keys", ".", "Key", "=", "params", ".", "PrivateKey", "\n\n", "return", "ReadIdentityFromKeyPair", "(", "keys", ")", "\n", "}" ]
// registerThroughProxy is used to register through the proxy server.
[ "registerThroughProxy", "is", "used", "to", "register", "through", "the", "proxy", "server", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/register.go#L140-L160
train
gravitational/teleport
lib/auth/register.go
registerThroughAuth
func registerThroughAuth(token string, params RegisterParams) (*Identity, error) { log.Debugf("Attempting to register through auth server.") var client *Client var err error // Build a client to the Auth Server. If a CA pin is specified require the // Auth Server is validated. Otherwise attempt to use the CA file on disk // but if it's not available connect without validating the Auth Server CA. switch { case params.CAPin != "": client, err = pinRegisterClient(params) default: client, err = insecureRegisterClient(params) } if err != nil { return nil, trace.Wrap(err) } defer client.Close() // Get the SSH and X509 certificates for a node. keys, err := client.RegisterUsingToken(RegisterUsingTokenRequest{ Token: token, HostID: params.ID.HostUUID, NodeName: params.ID.NodeName, Role: params.ID.Role, AdditionalPrincipals: params.AdditionalPrincipals, DNSNames: params.DNSNames, PublicTLSKey: params.PublicTLSKey, PublicSSHKey: params.PublicSSHKey, }) if err != nil { return nil, trace.Wrap(err) } keys.Key = params.PrivateKey return ReadIdentityFromKeyPair(keys) }
go
func registerThroughAuth(token string, params RegisterParams) (*Identity, error) { log.Debugf("Attempting to register through auth server.") var client *Client var err error // Build a client to the Auth Server. If a CA pin is specified require the // Auth Server is validated. Otherwise attempt to use the CA file on disk // but if it's not available connect without validating the Auth Server CA. switch { case params.CAPin != "": client, err = pinRegisterClient(params) default: client, err = insecureRegisterClient(params) } if err != nil { return nil, trace.Wrap(err) } defer client.Close() // Get the SSH and X509 certificates for a node. keys, err := client.RegisterUsingToken(RegisterUsingTokenRequest{ Token: token, HostID: params.ID.HostUUID, NodeName: params.ID.NodeName, Role: params.ID.Role, AdditionalPrincipals: params.AdditionalPrincipals, DNSNames: params.DNSNames, PublicTLSKey: params.PublicTLSKey, PublicSSHKey: params.PublicSSHKey, }) if err != nil { return nil, trace.Wrap(err) } keys.Key = params.PrivateKey return ReadIdentityFromKeyPair(keys) }
[ "func", "registerThroughAuth", "(", "token", "string", ",", "params", "RegisterParams", ")", "(", "*", "Identity", ",", "error", ")", "{", "log", ".", "Debugf", "(", "\"", "\"", ")", "\n\n", "var", "client", "*", "Client", "\n", "var", "err", "error", "\n\n", "// Build a client to the Auth Server. If a CA pin is specified require the", "// Auth Server is validated. Otherwise attempt to use the CA file on disk", "// but if it's not available connect without validating the Auth Server CA.", "switch", "{", "case", "params", ".", "CAPin", "!=", "\"", "\"", ":", "client", ",", "err", "=", "pinRegisterClient", "(", "params", ")", "\n", "default", ":", "client", ",", "err", "=", "insecureRegisterClient", "(", "params", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "defer", "client", ".", "Close", "(", ")", "\n\n", "// Get the SSH and X509 certificates for a node.", "keys", ",", "err", ":=", "client", ".", "RegisterUsingToken", "(", "RegisterUsingTokenRequest", "{", "Token", ":", "token", ",", "HostID", ":", "params", ".", "ID", ".", "HostUUID", ",", "NodeName", ":", "params", ".", "ID", ".", "NodeName", ",", "Role", ":", "params", ".", "ID", ".", "Role", ",", "AdditionalPrincipals", ":", "params", ".", "AdditionalPrincipals", ",", "DNSNames", ":", "params", ".", "DNSNames", ",", "PublicTLSKey", ":", "params", ".", "PublicTLSKey", ",", "PublicSSHKey", ":", "params", ".", "PublicSSHKey", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "keys", ".", "Key", "=", "params", ".", "PrivateKey", "\n\n", "return", "ReadIdentityFromKeyPair", "(", "keys", ")", "\n", "}" ]
// registerThroughAuth is used to register through the auth server.
[ "registerThroughAuth", "is", "used", "to", "register", "through", "the", "auth", "server", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/register.go#L163-L200
train
gravitational/teleport
lib/auth/register.go
insecureRegisterClient
func insecureRegisterClient(params RegisterParams) (*Client, error) { tlsConfig := utils.TLSConfig(params.CipherSuites) cert, err := readCA(params) if err != nil && !trace.IsNotFound(err) { return nil, trace.Wrap(err) } // If no CA was found, then create a insecure connection to the Auth Server, // otherwise use the CA on disk to validate the Auth Server. if trace.IsNotFound(err) { tlsConfig.InsecureSkipVerify = true log.Warnf("Joining cluster without validating the identity of the Auth " + "Server. This may open you up to a Man-In-The-Middle (MITM) attack if an " + "attacker can gain privileged network access. To remedy this, use the CA pin " + "value provided when join token was generated to validate the identity of " + "the Auth Server.") } else { certPool := x509.NewCertPool() certPool.AddCert(cert) tlsConfig.RootCAs = certPool log.Infof("Joining remote cluster %v, validating connection with certificate on disk.", cert.Subject.CommonName) } client, err := NewTLSClient(ClientConfig{Addrs: params.Servers, TLS: tlsConfig}) if err != nil { return nil, trace.Wrap(err) } return client, nil }
go
func insecureRegisterClient(params RegisterParams) (*Client, error) { tlsConfig := utils.TLSConfig(params.CipherSuites) cert, err := readCA(params) if err != nil && !trace.IsNotFound(err) { return nil, trace.Wrap(err) } // If no CA was found, then create a insecure connection to the Auth Server, // otherwise use the CA on disk to validate the Auth Server. if trace.IsNotFound(err) { tlsConfig.InsecureSkipVerify = true log.Warnf("Joining cluster without validating the identity of the Auth " + "Server. This may open you up to a Man-In-The-Middle (MITM) attack if an " + "attacker can gain privileged network access. To remedy this, use the CA pin " + "value provided when join token was generated to validate the identity of " + "the Auth Server.") } else { certPool := x509.NewCertPool() certPool.AddCert(cert) tlsConfig.RootCAs = certPool log.Infof("Joining remote cluster %v, validating connection with certificate on disk.", cert.Subject.CommonName) } client, err := NewTLSClient(ClientConfig{Addrs: params.Servers, TLS: tlsConfig}) if err != nil { return nil, trace.Wrap(err) } return client, nil }
[ "func", "insecureRegisterClient", "(", "params", "RegisterParams", ")", "(", "*", "Client", ",", "error", ")", "{", "tlsConfig", ":=", "utils", ".", "TLSConfig", "(", "params", ".", "CipherSuites", ")", "\n\n", "cert", ",", "err", ":=", "readCA", "(", "params", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "trace", ".", "IsNotFound", "(", "err", ")", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "// If no CA was found, then create a insecure connection to the Auth Server,", "// otherwise use the CA on disk to validate the Auth Server.", "if", "trace", ".", "IsNotFound", "(", "err", ")", "{", "tlsConfig", ".", "InsecureSkipVerify", "=", "true", "\n\n", "log", ".", "Warnf", "(", "\"", "\"", "+", "\"", "\"", "+", "\"", "\"", "+", "\"", "\"", "+", "\"", "\"", ")", "\n", "}", "else", "{", "certPool", ":=", "x509", ".", "NewCertPool", "(", ")", "\n", "certPool", ".", "AddCert", "(", "cert", ")", "\n", "tlsConfig", ".", "RootCAs", "=", "certPool", "\n\n", "log", ".", "Infof", "(", "\"", "\"", ",", "cert", ".", "Subject", ".", "CommonName", ")", "\n", "}", "\n\n", "client", ",", "err", ":=", "NewTLSClient", "(", "ClientConfig", "{", "Addrs", ":", "params", ".", "Servers", ",", "TLS", ":", "tlsConfig", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "return", "client", ",", "nil", "\n", "}" ]
// insecureRegisterClient attempts to connects to the Auth Server using the // CA on disk. If no CA is found on disk, Teleport will not verify the Auth // Server it is connecting to.
[ "insecureRegisterClient", "attempts", "to", "connects", "to", "the", "Auth", "Server", "using", "the", "CA", "on", "disk", ".", "If", "no", "CA", "is", "found", "on", "disk", "Teleport", "will", "not", "verify", "the", "Auth", "Server", "it", "is", "connecting", "to", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/register.go#L205-L237
train
gravitational/teleport
lib/auth/register.go
readCA
func readCA(params RegisterParams) (*x509.Certificate, error) { certBytes, err := utils.ReadPath(params.CAPath) if err != nil { return nil, trace.Wrap(err) } cert, err := tlsca.ParseCertificatePEM(certBytes) if err != nil { return nil, trace.Wrap(err, "failed to parse certificate at %v", params.CAPath) } return cert, nil }
go
func readCA(params RegisterParams) (*x509.Certificate, error) { certBytes, err := utils.ReadPath(params.CAPath) if err != nil { return nil, trace.Wrap(err) } cert, err := tlsca.ParseCertificatePEM(certBytes) if err != nil { return nil, trace.Wrap(err, "failed to parse certificate at %v", params.CAPath) } return cert, nil }
[ "func", "readCA", "(", "params", "RegisterParams", ")", "(", "*", "x509", ".", "Certificate", ",", "error", ")", "{", "certBytes", ",", "err", ":=", "utils", ".", "ReadPath", "(", "params", ".", "CAPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "cert", ",", "err", ":=", "tlsca", ".", "ParseCertificatePEM", "(", "certBytes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ",", "\"", "\"", ",", "params", ".", "CAPath", ")", "\n", "}", "\n", "return", "cert", ",", "nil", "\n", "}" ]
// readCA will read in CA that will be used to validate the certificate that // the Auth Server presents.
[ "readCA", "will", "read", "in", "CA", "that", "will", "be", "used", "to", "validate", "the", "certificate", "that", "the", "Auth", "Server", "presents", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/register.go#L241-L251
train
gravitational/teleport
lib/auth/register.go
pinRegisterClient
func pinRegisterClient(params RegisterParams) (*Client, error) { // Build a insecure client to the Auth Server. This is safe because even if // an attacker were to MITM this connection the CA pin will not match below. tlsConfig := utils.TLSConfig(params.CipherSuites) tlsConfig.InsecureSkipVerify = true client, err := NewTLSClient(ClientConfig{Addrs: params.Servers, TLS: tlsConfig}) if err != nil { return nil, trace.Wrap(err) } defer client.Close() // Fetch the root CA from the Auth Server. The NOP role has access to the // GetClusterCACert endpoint. localCA, err := client.GetClusterCACert() if err != nil { return nil, trace.Wrap(err) } tlsCA, err := tlsca.ParseCertificatePEM(localCA.TLSCA) if err != nil { return nil, trace.Wrap(err) } // Check that the SPKI pin matches the CA we fetched over a insecure // connection. This makes sure the CA fetched over a insecure connection is // in-fact the expected CA. err = utils.CheckSPKI(params.CAPin, tlsCA) if err != nil { return nil, trace.Wrap(err) } log.Infof("Joining remote cluster %v with CA pin.", tlsCA.Subject.CommonName) // Create another client, but this time with the CA provided to validate // that the Auth Server was issued a certificate by the same CA. tlsConfig = utils.TLSConfig(params.CipherSuites) certPool := x509.NewCertPool() certPool.AddCert(tlsCA) tlsConfig.RootCAs = certPool client, err = NewTLSClient(ClientConfig{Addrs: params.Servers, TLS: tlsConfig}) if err != nil { return nil, trace.Wrap(err) } return client, nil }
go
func pinRegisterClient(params RegisterParams) (*Client, error) { // Build a insecure client to the Auth Server. This is safe because even if // an attacker were to MITM this connection the CA pin will not match below. tlsConfig := utils.TLSConfig(params.CipherSuites) tlsConfig.InsecureSkipVerify = true client, err := NewTLSClient(ClientConfig{Addrs: params.Servers, TLS: tlsConfig}) if err != nil { return nil, trace.Wrap(err) } defer client.Close() // Fetch the root CA from the Auth Server. The NOP role has access to the // GetClusterCACert endpoint. localCA, err := client.GetClusterCACert() if err != nil { return nil, trace.Wrap(err) } tlsCA, err := tlsca.ParseCertificatePEM(localCA.TLSCA) if err != nil { return nil, trace.Wrap(err) } // Check that the SPKI pin matches the CA we fetched over a insecure // connection. This makes sure the CA fetched over a insecure connection is // in-fact the expected CA. err = utils.CheckSPKI(params.CAPin, tlsCA) if err != nil { return nil, trace.Wrap(err) } log.Infof("Joining remote cluster %v with CA pin.", tlsCA.Subject.CommonName) // Create another client, but this time with the CA provided to validate // that the Auth Server was issued a certificate by the same CA. tlsConfig = utils.TLSConfig(params.CipherSuites) certPool := x509.NewCertPool() certPool.AddCert(tlsCA) tlsConfig.RootCAs = certPool client, err = NewTLSClient(ClientConfig{Addrs: params.Servers, TLS: tlsConfig}) if err != nil { return nil, trace.Wrap(err) } return client, nil }
[ "func", "pinRegisterClient", "(", "params", "RegisterParams", ")", "(", "*", "Client", ",", "error", ")", "{", "// Build a insecure client to the Auth Server. This is safe because even if", "// an attacker were to MITM this connection the CA pin will not match below.", "tlsConfig", ":=", "utils", ".", "TLSConfig", "(", "params", ".", "CipherSuites", ")", "\n", "tlsConfig", ".", "InsecureSkipVerify", "=", "true", "\n", "client", ",", "err", ":=", "NewTLSClient", "(", "ClientConfig", "{", "Addrs", ":", "params", ".", "Servers", ",", "TLS", ":", "tlsConfig", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "defer", "client", ".", "Close", "(", ")", "\n\n", "// Fetch the root CA from the Auth Server. The NOP role has access to the", "// GetClusterCACert endpoint.", "localCA", ",", "err", ":=", "client", ".", "GetClusterCACert", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "tlsCA", ",", "err", ":=", "tlsca", ".", "ParseCertificatePEM", "(", "localCA", ".", "TLSCA", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "// Check that the SPKI pin matches the CA we fetched over a insecure", "// connection. This makes sure the CA fetched over a insecure connection is", "// in-fact the expected CA.", "err", "=", "utils", ".", "CheckSPKI", "(", "params", ".", "CAPin", ",", "tlsCA", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "log", ".", "Infof", "(", "\"", "\"", ",", "tlsCA", ".", "Subject", ".", "CommonName", ")", "\n\n", "// Create another client, but this time with the CA provided to validate", "// that the Auth Server was issued a certificate by the same CA.", "tlsConfig", "=", "utils", ".", "TLSConfig", "(", "params", ".", "CipherSuites", ")", "\n", "certPool", ":=", "x509", ".", "NewCertPool", "(", ")", "\n", "certPool", ".", "AddCert", "(", "tlsCA", ")", "\n", "tlsConfig", ".", "RootCAs", "=", "certPool", "\n\n", "client", ",", "err", "=", "NewTLSClient", "(", "ClientConfig", "{", "Addrs", ":", "params", ".", "Servers", ",", "TLS", ":", "tlsConfig", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "return", "client", ",", "nil", "\n", "}" ]
// pinRegisterClient first connects to the Auth Server using a insecure // connection to fetch the root CA. If the root CA matches the provided CA // pin, a connection will be re-established and the root CA will be used to // validate the certificate presented. If both conditions hold true, then we // know we are connecting to the expected Auth Server.
[ "pinRegisterClient", "first", "connects", "to", "the", "Auth", "Server", "using", "a", "insecure", "connection", "to", "fetch", "the", "root", "CA", ".", "If", "the", "root", "CA", "matches", "the", "provided", "CA", "pin", "a", "connection", "will", "be", "re", "-", "established", "and", "the", "root", "CA", "will", "be", "used", "to", "validate", "the", "certificate", "presented", ".", "If", "both", "conditions", "hold", "true", "then", "we", "know", "we", "are", "connecting", "to", "the", "expected", "Auth", "Server", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/register.go#L258-L303
train
gravitational/teleport
lib/auth/register.go
ReRegister
func ReRegister(params ReRegisterParams) (*Identity, error) { hostID, err := params.ID.HostID() if err != nil { return nil, trace.Wrap(err) } keys, err := params.Client.GenerateServerKeys(GenerateServerKeysRequest{ HostID: hostID, NodeName: params.ID.NodeName, Roles: teleport.Roles{params.ID.Role}, AdditionalPrincipals: params.AdditionalPrincipals, DNSNames: params.DNSNames, PublicTLSKey: params.PublicTLSKey, PublicSSHKey: params.PublicSSHKey, Rotation: &params.Rotation, }) if err != nil { return nil, trace.Wrap(err) } keys.Key = params.PrivateKey return ReadIdentityFromKeyPair(keys) }
go
func ReRegister(params ReRegisterParams) (*Identity, error) { hostID, err := params.ID.HostID() if err != nil { return nil, trace.Wrap(err) } keys, err := params.Client.GenerateServerKeys(GenerateServerKeysRequest{ HostID: hostID, NodeName: params.ID.NodeName, Roles: teleport.Roles{params.ID.Role}, AdditionalPrincipals: params.AdditionalPrincipals, DNSNames: params.DNSNames, PublicTLSKey: params.PublicTLSKey, PublicSSHKey: params.PublicSSHKey, Rotation: &params.Rotation, }) if err != nil { return nil, trace.Wrap(err) } keys.Key = params.PrivateKey return ReadIdentityFromKeyPair(keys) }
[ "func", "ReRegister", "(", "params", "ReRegisterParams", ")", "(", "*", "Identity", ",", "error", ")", "{", "hostID", ",", "err", ":=", "params", ".", "ID", ".", "HostID", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "keys", ",", "err", ":=", "params", ".", "Client", ".", "GenerateServerKeys", "(", "GenerateServerKeysRequest", "{", "HostID", ":", "hostID", ",", "NodeName", ":", "params", ".", "ID", ".", "NodeName", ",", "Roles", ":", "teleport", ".", "Roles", "{", "params", ".", "ID", ".", "Role", "}", ",", "AdditionalPrincipals", ":", "params", ".", "AdditionalPrincipals", ",", "DNSNames", ":", "params", ".", "DNSNames", ",", "PublicTLSKey", ":", "params", ".", "PublicTLSKey", ",", "PublicSSHKey", ":", "params", ".", "PublicSSHKey", ",", "Rotation", ":", "&", "params", ".", "Rotation", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "keys", ".", "Key", "=", "params", ".", "PrivateKey", "\n\n", "return", "ReadIdentityFromKeyPair", "(", "keys", ")", "\n", "}" ]
// ReRegister renews the certificates and private keys based on the client's existing identity.
[ "ReRegister", "renews", "the", "certificates", "and", "private", "keys", "based", "on", "the", "client", "s", "existing", "identity", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/register.go#L327-L348
train
gravitational/teleport
lib/config/fileconf.go
ReadFromFile
func ReadFromFile(filePath string) (*FileConfig, error) { f, err := os.Open(filePath) if err != nil { return nil, trace.Wrap(err, fmt.Sprintf("failed to open file: %v", filePath)) } defer f.Close() return ReadConfig(f) }
go
func ReadFromFile(filePath string) (*FileConfig, error) { f, err := os.Open(filePath) if err != nil { return nil, trace.Wrap(err, fmt.Sprintf("failed to open file: %v", filePath)) } defer f.Close() return ReadConfig(f) }
[ "func", "ReadFromFile", "(", "filePath", "string", ")", "(", "*", "FileConfig", ",", "error", ")", "{", "f", ",", "err", ":=", "os", ".", "Open", "(", "filePath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "filePath", ")", ")", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n", "return", "ReadConfig", "(", "f", ")", "\n", "}" ]
// ReadFromFile reads Teleport configuration from a file. Currently only YAML // format is supported
[ "ReadFromFile", "reads", "Teleport", "configuration", "from", "a", "file", ".", "Currently", "only", "YAML", "format", "is", "supported" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/fileconf.go#L170-L177
train
gravitational/teleport
lib/config/fileconf.go
ReadFromString
func ReadFromString(configString string) (*FileConfig, error) { data, err := base64.StdEncoding.DecodeString(configString) if err != nil { return nil, trace.BadParameter( "confiugraion should be base64 encoded: %v", err) } return ReadConfig(bytes.NewBuffer(data)) }
go
func ReadFromString(configString string) (*FileConfig, error) { data, err := base64.StdEncoding.DecodeString(configString) if err != nil { return nil, trace.BadParameter( "confiugraion should be base64 encoded: %v", err) } return ReadConfig(bytes.NewBuffer(data)) }
[ "func", "ReadFromString", "(", "configString", "string", ")", "(", "*", "FileConfig", ",", "error", ")", "{", "data", ",", "err", ":=", "base64", ".", "StdEncoding", ".", "DecodeString", "(", "configString", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "ReadConfig", "(", "bytes", ".", "NewBuffer", "(", "data", ")", ")", "\n", "}" ]
// ReadFromString reads values from base64 encoded byte string
[ "ReadFromString", "reads", "values", "from", "base64", "encoded", "byte", "string" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/fileconf.go#L180-L187
train
gravitational/teleport
lib/config/fileconf.go
ReadConfig
func ReadConfig(reader io.Reader) (*FileConfig, error) { // read & parse YAML config: bytes, err := ioutil.ReadAll(reader) if err != nil { return nil, trace.Wrap(err, "failed reading Teleport configuration") } var fc FileConfig if err = yaml.Unmarshal(bytes, &fc); err != nil { return nil, trace.BadParameter("failed to parse Teleport configuration: %v", err) } // don't start Teleport with invalid ciphers, kex algorithms, or mac algorithms. err = fc.Check() if err != nil { return nil, trace.BadParameter("failed to parse Teleport configuration: %v", err) } // now check for unknown (misspelled) config keys: var validateKeys func(m YAMLMap) error validateKeys = func(m YAMLMap) error { var recursive, ok bool var key string for k, v := range m { if key, ok = k.(string); ok { if recursive, ok = validKeys[key]; !ok { return trace.BadParameter("unrecognized configuration key: '%v'", key) } if recursive { if m2, ok := v.(YAMLMap); ok { if err := validateKeys(m2); err != nil { return err } } } } } return nil } // validate configuration keys: var tmp YAMLMap if err = yaml.Unmarshal(bytes, &tmp); err != nil { return nil, trace.BadParameter("error parsing YAML config") } if err = validateKeys(tmp); err != nil { return nil, trace.Wrap(err) } return &fc, nil }
go
func ReadConfig(reader io.Reader) (*FileConfig, error) { // read & parse YAML config: bytes, err := ioutil.ReadAll(reader) if err != nil { return nil, trace.Wrap(err, "failed reading Teleport configuration") } var fc FileConfig if err = yaml.Unmarshal(bytes, &fc); err != nil { return nil, trace.BadParameter("failed to parse Teleport configuration: %v", err) } // don't start Teleport with invalid ciphers, kex algorithms, or mac algorithms. err = fc.Check() if err != nil { return nil, trace.BadParameter("failed to parse Teleport configuration: %v", err) } // now check for unknown (misspelled) config keys: var validateKeys func(m YAMLMap) error validateKeys = func(m YAMLMap) error { var recursive, ok bool var key string for k, v := range m { if key, ok = k.(string); ok { if recursive, ok = validKeys[key]; !ok { return trace.BadParameter("unrecognized configuration key: '%v'", key) } if recursive { if m2, ok := v.(YAMLMap); ok { if err := validateKeys(m2); err != nil { return err } } } } } return nil } // validate configuration keys: var tmp YAMLMap if err = yaml.Unmarshal(bytes, &tmp); err != nil { return nil, trace.BadParameter("error parsing YAML config") } if err = validateKeys(tmp); err != nil { return nil, trace.Wrap(err) } return &fc, nil }
[ "func", "ReadConfig", "(", "reader", "io", ".", "Reader", ")", "(", "*", "FileConfig", ",", "error", ")", "{", "// read & parse YAML config:", "bytes", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "reader", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "var", "fc", "FileConfig", "\n", "if", "err", "=", "yaml", ".", "Unmarshal", "(", "bytes", ",", "&", "fc", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "// don't start Teleport with invalid ciphers, kex algorithms, or mac algorithms.", "err", "=", "fc", ".", "Check", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "// now check for unknown (misspelled) config keys:", "var", "validateKeys", "func", "(", "m", "YAMLMap", ")", "error", "\n", "validateKeys", "=", "func", "(", "m", "YAMLMap", ")", "error", "{", "var", "recursive", ",", "ok", "bool", "\n", "var", "key", "string", "\n", "for", "k", ",", "v", ":=", "range", "m", "{", "if", "key", ",", "ok", "=", "k", ".", "(", "string", ")", ";", "ok", "{", "if", "recursive", ",", "ok", "=", "validKeys", "[", "key", "]", ";", "!", "ok", "{", "return", "trace", ".", "BadParameter", "(", "\"", "\"", ",", "key", ")", "\n", "}", "\n", "if", "recursive", "{", "if", "m2", ",", "ok", ":=", "v", ".", "(", "YAMLMap", ")", ";", "ok", "{", "if", "err", ":=", "validateKeys", "(", "m2", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "// validate configuration keys:", "var", "tmp", "YAMLMap", "\n", "if", "err", "=", "yaml", ".", "Unmarshal", "(", "bytes", ",", "&", "tmp", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "err", "=", "validateKeys", "(", "tmp", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "&", "fc", ",", "nil", "\n", "}" ]
// ReadConfig reads Teleport configuration from reader in YAML format
[ "ReadConfig", "reads", "Teleport", "configuration", "from", "reader", "in", "YAML", "format" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/fileconf.go#L190-L235
train
gravitational/teleport
lib/config/fileconf.go
MakeSampleFileConfig
func MakeSampleFileConfig() (fc *FileConfig) { conf := service.MakeDefaultConfig() // sample global config: var g Global g.NodeName = conf.Hostname g.AuthToken = "cluster-join-token" g.Logger.Output = "stderr" g.Logger.Severity = "INFO" g.AuthServers = []string{defaults.AuthListenAddr().Addr} g.Limits.MaxConnections = defaults.LimiterMaxConnections g.Limits.MaxUsers = defaults.LimiterMaxConcurrentUsers g.DataDir = defaults.DataDir g.PIDFile = "/var/run/teleport.pid" // sample SSH config: var s SSH s.EnabledFlag = "yes" s.ListenAddress = conf.SSH.Addr.Addr s.Commands = []CommandLabel{ { Name: "hostname", Command: []string{"/usr/bin/hostname"}, Period: time.Minute, }, { Name: "arch", Command: []string{"/usr/bin/uname", "-p"}, Period: time.Hour, }, } s.Labels = map[string]string{ "db_type": "postgres", "db_role": "master", } // sample Auth config: var a Auth a.ListenAddress = conf.Auth.SSHAddr.Addr a.EnabledFlag = "yes" a.StaticTokens = []StaticToken{"proxy,node:cluster-join-token"} // sample proxy config: var p Proxy p.EnabledFlag = "yes" p.ListenAddress = conf.Proxy.SSHAddr.Addr p.WebAddr = conf.Proxy.WebAddr.Addr p.TunAddr = conf.Proxy.ReverseTunnelListenAddr.Addr p.CertFile = "/var/lib/teleport/webproxy_cert.pem" p.KeyFile = "/var/lib/teleport/webproxy_key.pem" fc = &FileConfig{ Global: g, Proxy: p, SSH: s, Auth: a, } return fc }
go
func MakeSampleFileConfig() (fc *FileConfig) { conf := service.MakeDefaultConfig() // sample global config: var g Global g.NodeName = conf.Hostname g.AuthToken = "cluster-join-token" g.Logger.Output = "stderr" g.Logger.Severity = "INFO" g.AuthServers = []string{defaults.AuthListenAddr().Addr} g.Limits.MaxConnections = defaults.LimiterMaxConnections g.Limits.MaxUsers = defaults.LimiterMaxConcurrentUsers g.DataDir = defaults.DataDir g.PIDFile = "/var/run/teleport.pid" // sample SSH config: var s SSH s.EnabledFlag = "yes" s.ListenAddress = conf.SSH.Addr.Addr s.Commands = []CommandLabel{ { Name: "hostname", Command: []string{"/usr/bin/hostname"}, Period: time.Minute, }, { Name: "arch", Command: []string{"/usr/bin/uname", "-p"}, Period: time.Hour, }, } s.Labels = map[string]string{ "db_type": "postgres", "db_role": "master", } // sample Auth config: var a Auth a.ListenAddress = conf.Auth.SSHAddr.Addr a.EnabledFlag = "yes" a.StaticTokens = []StaticToken{"proxy,node:cluster-join-token"} // sample proxy config: var p Proxy p.EnabledFlag = "yes" p.ListenAddress = conf.Proxy.SSHAddr.Addr p.WebAddr = conf.Proxy.WebAddr.Addr p.TunAddr = conf.Proxy.ReverseTunnelListenAddr.Addr p.CertFile = "/var/lib/teleport/webproxy_cert.pem" p.KeyFile = "/var/lib/teleport/webproxy_key.pem" fc = &FileConfig{ Global: g, Proxy: p, SSH: s, Auth: a, } return fc }
[ "func", "MakeSampleFileConfig", "(", ")", "(", "fc", "*", "FileConfig", ")", "{", "conf", ":=", "service", ".", "MakeDefaultConfig", "(", ")", "\n\n", "// sample global config:", "var", "g", "Global", "\n", "g", ".", "NodeName", "=", "conf", ".", "Hostname", "\n", "g", ".", "AuthToken", "=", "\"", "\"", "\n", "g", ".", "Logger", ".", "Output", "=", "\"", "\"", "\n", "g", ".", "Logger", ".", "Severity", "=", "\"", "\"", "\n", "g", ".", "AuthServers", "=", "[", "]", "string", "{", "defaults", ".", "AuthListenAddr", "(", ")", ".", "Addr", "}", "\n", "g", ".", "Limits", ".", "MaxConnections", "=", "defaults", ".", "LimiterMaxConnections", "\n", "g", ".", "Limits", ".", "MaxUsers", "=", "defaults", ".", "LimiterMaxConcurrentUsers", "\n", "g", ".", "DataDir", "=", "defaults", ".", "DataDir", "\n", "g", ".", "PIDFile", "=", "\"", "\"", "\n\n", "// sample SSH config:", "var", "s", "SSH", "\n", "s", ".", "EnabledFlag", "=", "\"", "\"", "\n", "s", ".", "ListenAddress", "=", "conf", ".", "SSH", ".", "Addr", ".", "Addr", "\n", "s", ".", "Commands", "=", "[", "]", "CommandLabel", "{", "{", "Name", ":", "\"", "\"", ",", "Command", ":", "[", "]", "string", "{", "\"", "\"", "}", ",", "Period", ":", "time", ".", "Minute", ",", "}", ",", "{", "Name", ":", "\"", "\"", ",", "Command", ":", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", "}", ",", "Period", ":", "time", ".", "Hour", ",", "}", ",", "}", "\n", "s", ".", "Labels", "=", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "\"", "\"", ",", "}", "\n\n", "// sample Auth config:", "var", "a", "Auth", "\n", "a", ".", "ListenAddress", "=", "conf", ".", "Auth", ".", "SSHAddr", ".", "Addr", "\n", "a", ".", "EnabledFlag", "=", "\"", "\"", "\n", "a", ".", "StaticTokens", "=", "[", "]", "StaticToken", "{", "\"", "\"", "}", "\n\n", "// sample proxy config:", "var", "p", "Proxy", "\n", "p", ".", "EnabledFlag", "=", "\"", "\"", "\n", "p", ".", "ListenAddress", "=", "conf", ".", "Proxy", ".", "SSHAddr", ".", "Addr", "\n", "p", ".", "WebAddr", "=", "conf", ".", "Proxy", ".", "WebAddr", ".", "Addr", "\n", "p", ".", "TunAddr", "=", "conf", ".", "Proxy", ".", "ReverseTunnelListenAddr", ".", "Addr", "\n", "p", ".", "CertFile", "=", "\"", "\"", "\n", "p", ".", "KeyFile", "=", "\"", "\"", "\n\n", "fc", "=", "&", "FileConfig", "{", "Global", ":", "g", ",", "Proxy", ":", "p", ",", "SSH", ":", "s", ",", "Auth", ":", "a", ",", "}", "\n", "return", "fc", "\n", "}" ]
// MakeSampleFileConfig returns a sample config structure populated by defaults, // useful to generate sample configuration files
[ "MakeSampleFileConfig", "returns", "a", "sample", "config", "structure", "populated", "by", "defaults", "useful", "to", "generate", "sample", "configuration", "files" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/fileconf.go#L239-L297
train
gravitational/teleport
lib/config/fileconf.go
DebugDumpToYAML
func (conf *FileConfig) DebugDumpToYAML() string { bytes, err := yaml.Marshal(&conf) if err != nil { panic(err) } return string(bytes) }
go
func (conf *FileConfig) DebugDumpToYAML() string { bytes, err := yaml.Marshal(&conf) if err != nil { panic(err) } return string(bytes) }
[ "func", "(", "conf", "*", "FileConfig", ")", "DebugDumpToYAML", "(", ")", "string", "{", "bytes", ",", "err", ":=", "yaml", ".", "Marshal", "(", "&", "conf", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "string", "(", "bytes", ")", "\n", "}" ]
// DebugDumpToYAML allows for quick YAML dumping of the config
[ "DebugDumpToYAML", "allows", "for", "quick", "YAML", "dumping", "of", "the", "config" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/fileconf.go#L300-L306
train
gravitational/teleport
lib/config/fileconf.go
Parse
func (c *CachePolicy) Parse() (*service.CachePolicy, error) { out := service.CachePolicy{ Enabled: c.Enabled(), NeverExpires: c.NeverExpires(), } if out.NeverExpires { return &out, nil } var err error if c.TTL != "" { out.TTL, err = time.ParseDuration(c.TTL) if err != nil { return nil, trace.BadParameter("cache.ttl invalid duration: %v, accepted format '10h'", c.TTL) } } return &out, nil }
go
func (c *CachePolicy) Parse() (*service.CachePolicy, error) { out := service.CachePolicy{ Enabled: c.Enabled(), NeverExpires: c.NeverExpires(), } if out.NeverExpires { return &out, nil } var err error if c.TTL != "" { out.TTL, err = time.ParseDuration(c.TTL) if err != nil { return nil, trace.BadParameter("cache.ttl invalid duration: %v, accepted format '10h'", c.TTL) } } return &out, nil }
[ "func", "(", "c", "*", "CachePolicy", ")", "Parse", "(", ")", "(", "*", "service", ".", "CachePolicy", ",", "error", ")", "{", "out", ":=", "service", ".", "CachePolicy", "{", "Enabled", ":", "c", ".", "Enabled", "(", ")", ",", "NeverExpires", ":", "c", ".", "NeverExpires", "(", ")", ",", "}", "\n", "if", "out", ".", "NeverExpires", "{", "return", "&", "out", ",", "nil", "\n", "}", "\n", "var", "err", "error", "\n", "if", "c", ".", "TTL", "!=", "\"", "\"", "{", "out", ".", "TTL", ",", "err", "=", "time", ".", "ParseDuration", "(", "c", ".", "TTL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ",", "c", ".", "TTL", ")", "\n", "}", "\n", "}", "\n", "return", "&", "out", ",", "nil", "\n", "}" ]
// Parse parses cache policy from Teleport config
[ "Parse", "parses", "cache", "policy", "from", "Teleport", "config" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/fileconf.go#L425-L441
train
gravitational/teleport
lib/config/fileconf.go
Parse
func (p *PAM) Parse() *pam.Config { serviceName := p.ServiceName if serviceName == "" { serviceName = defaults.ServiceName } enabled, _ := utils.ParseBool(p.Enabled) return &pam.Config{ Enabled: enabled, ServiceName: serviceName, } }
go
func (p *PAM) Parse() *pam.Config { serviceName := p.ServiceName if serviceName == "" { serviceName = defaults.ServiceName } enabled, _ := utils.ParseBool(p.Enabled) return &pam.Config{ Enabled: enabled, ServiceName: serviceName, } }
[ "func", "(", "p", "*", "PAM", ")", "Parse", "(", ")", "*", "pam", ".", "Config", "{", "serviceName", ":=", "p", ".", "ServiceName", "\n", "if", "serviceName", "==", "\"", "\"", "{", "serviceName", "=", "defaults", ".", "ServiceName", "\n", "}", "\n", "enabled", ",", "_", ":=", "utils", ".", "ParseBool", "(", "p", ".", "Enabled", ")", "\n", "return", "&", "pam", ".", "Config", "{", "Enabled", ":", "enabled", ",", "ServiceName", ":", "serviceName", ",", "}", "\n", "}" ]
// Parse returns a parsed pam.Config.
[ "Parse", "returns", "a", "parsed", "pam", ".", "Config", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/fileconf.go#L710-L720
train
gravitational/teleport
lib/config/fileconf.go
ConvertAndValidate
func (t *ReverseTunnel) ConvertAndValidate() (services.ReverseTunnel, error) { for i := range t.Addresses { addr, err := utils.ParseHostPortAddr(t.Addresses[i], defaults.SSHProxyTunnelListenPort) if err != nil { return nil, trace.Wrap(err, "Invalid address for tunnel %v", t.DomainName) } t.Addresses[i] = addr.String() } out := services.NewReverseTunnel(t.DomainName, t.Addresses) if err := out.Check(); err != nil { return nil, trace.Wrap(err) } return out, nil }
go
func (t *ReverseTunnel) ConvertAndValidate() (services.ReverseTunnel, error) { for i := range t.Addresses { addr, err := utils.ParseHostPortAddr(t.Addresses[i], defaults.SSHProxyTunnelListenPort) if err != nil { return nil, trace.Wrap(err, "Invalid address for tunnel %v", t.DomainName) } t.Addresses[i] = addr.String() } out := services.NewReverseTunnel(t.DomainName, t.Addresses) if err := out.Check(); err != nil { return nil, trace.Wrap(err) } return out, nil }
[ "func", "(", "t", "*", "ReverseTunnel", ")", "ConvertAndValidate", "(", ")", "(", "services", ".", "ReverseTunnel", ",", "error", ")", "{", "for", "i", ":=", "range", "t", ".", "Addresses", "{", "addr", ",", "err", ":=", "utils", ".", "ParseHostPortAddr", "(", "t", ".", "Addresses", "[", "i", "]", ",", "defaults", ".", "SSHProxyTunnelListenPort", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ",", "\"", "\"", ",", "t", ".", "DomainName", ")", "\n", "}", "\n", "t", ".", "Addresses", "[", "i", "]", "=", "addr", ".", "String", "(", ")", "\n", "}", "\n\n", "out", ":=", "services", ".", "NewReverseTunnel", "(", "t", ".", "DomainName", ",", "t", ".", "Addresses", ")", "\n", "if", "err", ":=", "out", ".", "Check", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "out", ",", "nil", "\n", "}" ]
// ConvertAndValidate returns validated services.ReverseTunnel or nil and error otherwize
[ "ConvertAndValidate", "returns", "validated", "services", ".", "ReverseTunnel", "or", "nil", "and", "error", "otherwize" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/fileconf.go#L778-L792
train
gravitational/teleport
lib/config/fileconf.go
Parse
func (a *Authority) Parse() (services.CertAuthority, services.Role, error) { ca := &services.CertAuthorityV1{ AllowedLogins: a.AllowedLogins, DomainName: a.DomainName, Type: a.Type, } for _, path := range a.CheckingKeyFiles { keyBytes, err := utils.ReadPath(path) if err != nil { return nil, nil, trace.Wrap(err) } ca.CheckingKeys = append(ca.CheckingKeys, keyBytes) } for _, val := range a.CheckingKeys { ca.CheckingKeys = append(ca.CheckingKeys, []byte(val)) } for _, path := range a.SigningKeyFiles { keyBytes, err := utils.ReadPath(path) if err != nil { return nil, nil, trace.Wrap(err) } ca.SigningKeys = append(ca.SigningKeys, keyBytes) } for _, val := range a.SigningKeys { ca.SigningKeys = append(ca.SigningKeys, []byte(val)) } new, role := services.ConvertV1CertAuthority(ca) return new, role, nil }
go
func (a *Authority) Parse() (services.CertAuthority, services.Role, error) { ca := &services.CertAuthorityV1{ AllowedLogins: a.AllowedLogins, DomainName: a.DomainName, Type: a.Type, } for _, path := range a.CheckingKeyFiles { keyBytes, err := utils.ReadPath(path) if err != nil { return nil, nil, trace.Wrap(err) } ca.CheckingKeys = append(ca.CheckingKeys, keyBytes) } for _, val := range a.CheckingKeys { ca.CheckingKeys = append(ca.CheckingKeys, []byte(val)) } for _, path := range a.SigningKeyFiles { keyBytes, err := utils.ReadPath(path) if err != nil { return nil, nil, trace.Wrap(err) } ca.SigningKeys = append(ca.SigningKeys, keyBytes) } for _, val := range a.SigningKeys { ca.SigningKeys = append(ca.SigningKeys, []byte(val)) } new, role := services.ConvertV1CertAuthority(ca) return new, role, nil }
[ "func", "(", "a", "*", "Authority", ")", "Parse", "(", ")", "(", "services", ".", "CertAuthority", ",", "services", ".", "Role", ",", "error", ")", "{", "ca", ":=", "&", "services", ".", "CertAuthorityV1", "{", "AllowedLogins", ":", "a", ".", "AllowedLogins", ",", "DomainName", ":", "a", ".", "DomainName", ",", "Type", ":", "a", ".", "Type", ",", "}", "\n\n", "for", "_", ",", "path", ":=", "range", "a", ".", "CheckingKeyFiles", "{", "keyBytes", ",", "err", ":=", "utils", ".", "ReadPath", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "ca", ".", "CheckingKeys", "=", "append", "(", "ca", ".", "CheckingKeys", ",", "keyBytes", ")", "\n", "}", "\n\n", "for", "_", ",", "val", ":=", "range", "a", ".", "CheckingKeys", "{", "ca", ".", "CheckingKeys", "=", "append", "(", "ca", ".", "CheckingKeys", ",", "[", "]", "byte", "(", "val", ")", ")", "\n", "}", "\n\n", "for", "_", ",", "path", ":=", "range", "a", ".", "SigningKeyFiles", "{", "keyBytes", ",", "err", ":=", "utils", ".", "ReadPath", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "ca", ".", "SigningKeys", "=", "append", "(", "ca", ".", "SigningKeys", ",", "keyBytes", ")", "\n", "}", "\n\n", "for", "_", ",", "val", ":=", "range", "a", ".", "SigningKeys", "{", "ca", ".", "SigningKeys", "=", "append", "(", "ca", ".", "SigningKeys", ",", "[", "]", "byte", "(", "val", ")", ")", "\n", "}", "\n\n", "new", ",", "role", ":=", "services", ".", "ConvertV1CertAuthority", "(", "ca", ")", "\n", "return", "new", ",", "role", ",", "nil", "\n", "}" ]
// Parse reads values and returns parsed CertAuthority
[ "Parse", "reads", "values", "and", "returns", "parsed", "CertAuthority" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/fileconf.go#L818-L851
train
gravitational/teleport
lib/config/fileconf.go
Parse
func (o *OIDCConnector) Parse() (services.OIDCConnector, error) { if o.Display == "" { o.Display = o.ID } var mappings []services.ClaimMapping for _, c := range o.ClaimsToRoles { var roles []string if len(c.Roles) > 0 { roles = append(roles, c.Roles...) } mappings = append(mappings, services.ClaimMapping{ Claim: c.Claim, Value: c.Value, Roles: roles, RoleTemplate: c.RoleTemplate, }) } other := &services.OIDCConnectorV1{ ID: o.ID, Display: o.Display, IssuerURL: o.IssuerURL, ClientID: o.ClientID, ClientSecret: o.ClientSecret, RedirectURL: o.RedirectURL, Scope: o.Scope, ClaimsToRoles: mappings, } v2 := other.V2() v2.SetACR(o.ACR) v2.SetProvider(o.Provider) if err := v2.Check(); err != nil { return nil, trace.Wrap(err) } return v2, nil }
go
func (o *OIDCConnector) Parse() (services.OIDCConnector, error) { if o.Display == "" { o.Display = o.ID } var mappings []services.ClaimMapping for _, c := range o.ClaimsToRoles { var roles []string if len(c.Roles) > 0 { roles = append(roles, c.Roles...) } mappings = append(mappings, services.ClaimMapping{ Claim: c.Claim, Value: c.Value, Roles: roles, RoleTemplate: c.RoleTemplate, }) } other := &services.OIDCConnectorV1{ ID: o.ID, Display: o.Display, IssuerURL: o.IssuerURL, ClientID: o.ClientID, ClientSecret: o.ClientSecret, RedirectURL: o.RedirectURL, Scope: o.Scope, ClaimsToRoles: mappings, } v2 := other.V2() v2.SetACR(o.ACR) v2.SetProvider(o.Provider) if err := v2.Check(); err != nil { return nil, trace.Wrap(err) } return v2, nil }
[ "func", "(", "o", "*", "OIDCConnector", ")", "Parse", "(", ")", "(", "services", ".", "OIDCConnector", ",", "error", ")", "{", "if", "o", ".", "Display", "==", "\"", "\"", "{", "o", ".", "Display", "=", "o", ".", "ID", "\n", "}", "\n\n", "var", "mappings", "[", "]", "services", ".", "ClaimMapping", "\n", "for", "_", ",", "c", ":=", "range", "o", ".", "ClaimsToRoles", "{", "var", "roles", "[", "]", "string", "\n", "if", "len", "(", "c", ".", "Roles", ")", ">", "0", "{", "roles", "=", "append", "(", "roles", ",", "c", ".", "Roles", "...", ")", "\n", "}", "\n\n", "mappings", "=", "append", "(", "mappings", ",", "services", ".", "ClaimMapping", "{", "Claim", ":", "c", ".", "Claim", ",", "Value", ":", "c", ".", "Value", ",", "Roles", ":", "roles", ",", "RoleTemplate", ":", "c", ".", "RoleTemplate", ",", "}", ")", "\n", "}", "\n\n", "other", ":=", "&", "services", ".", "OIDCConnectorV1", "{", "ID", ":", "o", ".", "ID", ",", "Display", ":", "o", ".", "Display", ",", "IssuerURL", ":", "o", ".", "IssuerURL", ",", "ClientID", ":", "o", ".", "ClientID", ",", "ClientSecret", ":", "o", ".", "ClientSecret", ",", "RedirectURL", ":", "o", ".", "RedirectURL", ",", "Scope", ":", "o", ".", "Scope", ",", "ClaimsToRoles", ":", "mappings", ",", "}", "\n", "v2", ":=", "other", ".", "V2", "(", ")", "\n", "v2", ".", "SetACR", "(", "o", ".", "ACR", ")", "\n", "v2", ".", "SetProvider", "(", "o", ".", "Provider", ")", "\n", "if", "err", ":=", "v2", ".", "Check", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "v2", ",", "nil", "\n", "}" ]
// Parse parses config struct into services connector and checks if it's valid
[ "Parse", "parses", "config", "struct", "into", "services", "connector", "and", "checks", "if", "it", "s", "valid" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/fileconf.go#L898-L935
train
gravitational/teleport
lib/config/fileconf.go
Parse
func (u *U2F) Parse() (*services.U2F, error) { // If no appID specified, default to hostname appID := u.AppID if appID == "" { hostname, err := os.Hostname() if err != nil { return nil, trace.Wrap(err, "failed to automatically determine U2F AppID from hostname") } appID = fmt.Sprintf("https://%s:%d", strings.ToLower(hostname), defaults.HTTPListenPort) } // If no facets specified, default to AppID facets := u.Facets if len(facets) == 0 { facets = []string{appID} } return &services.U2F{ AppID: appID, Facets: facets, }, nil }
go
func (u *U2F) Parse() (*services.U2F, error) { // If no appID specified, default to hostname appID := u.AppID if appID == "" { hostname, err := os.Hostname() if err != nil { return nil, trace.Wrap(err, "failed to automatically determine U2F AppID from hostname") } appID = fmt.Sprintf("https://%s:%d", strings.ToLower(hostname), defaults.HTTPListenPort) } // If no facets specified, default to AppID facets := u.Facets if len(facets) == 0 { facets = []string{appID} } return &services.U2F{ AppID: appID, Facets: facets, }, nil }
[ "func", "(", "u", "*", "U2F", ")", "Parse", "(", ")", "(", "*", "services", ".", "U2F", ",", "error", ")", "{", "// If no appID specified, default to hostname", "appID", ":=", "u", ".", "AppID", "\n", "if", "appID", "==", "\"", "\"", "{", "hostname", ",", "err", ":=", "os", ".", "Hostname", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "appID", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "strings", ".", "ToLower", "(", "hostname", ")", ",", "defaults", ".", "HTTPListenPort", ")", "\n", "}", "\n\n", "// If no facets specified, default to AppID", "facets", ":=", "u", ".", "Facets", "\n", "if", "len", "(", "facets", ")", "==", "0", "{", "facets", "=", "[", "]", "string", "{", "appID", "}", "\n", "}", "\n\n", "return", "&", "services", ".", "U2F", "{", "AppID", ":", "appID", ",", "Facets", ":", "facets", ",", "}", ",", "nil", "\n", "}" ]
// Parse parses values in the U2F configuration section and validates its content.
[ "Parse", "parses", "values", "in", "the", "U2F", "configuration", "section", "and", "validates", "its", "content", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/fileconf.go#L943-L964
train