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/tunnelconn.go
String
func (r *TunnelConnectionV2) String() string { return fmt.Sprintf("TunnelConnection(name=%v, type=%v, cluster=%v, proxy=%v)", r.Metadata.Name, r.Spec.Type, r.Spec.ClusterName, r.Spec.ProxyName) }
go
func (r *TunnelConnectionV2) String() string { return fmt.Sprintf("TunnelConnection(name=%v, type=%v, cluster=%v, proxy=%v)", r.Metadata.Name, r.Spec.Type, r.Spec.ClusterName, r.Spec.ProxyName) }
[ "func", "(", "r", "*", "TunnelConnectionV2", ")", "String", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "r", ".", "Metadata", ".", "Name", ",", "r", ".", "Spec", ".", "Type", ",", "r", ".", "Spec", ".", "ClusterName", ",", "r", ".", "Spec", ".", "ProxyName", ")", "\n", "}" ]
// String returns user-friendly description of this connection
[ "String", "returns", "user", "-", "friendly", "description", "of", "this", "connection" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/tunnelconn.go#L151-L154
train
gravitational/teleport
lib/services/tunnelconn.go
SetLastHeartbeat
func (r *TunnelConnectionV2) SetLastHeartbeat(tm time.Time) { r.Spec.LastHeartbeat = tm }
go
func (r *TunnelConnectionV2) SetLastHeartbeat(tm time.Time) { r.Spec.LastHeartbeat = tm }
[ "func", "(", "r", "*", "TunnelConnectionV2", ")", "SetLastHeartbeat", "(", "tm", "time", ".", "Time", ")", "{", "r", ".", "Spec", ".", "LastHeartbeat", "=", "tm", "\n", "}" ]
// SetLastHeartbeat sets last heartbeat time
[ "SetLastHeartbeat", "sets", "last", "heartbeat", "time" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/tunnelconn.go#L221-L223
train
gravitational/teleport
lib/services/tunnelconn.go
UnmarshalTunnelConnection
func UnmarshalTunnelConnection(data []byte, opts ...MarshalOption) (TunnelConnection, error) { if len(data) == 0 { return nil, trace.BadParameter("missing tunnel connection data") } cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } var h ResourceHeader err = utils.FastUnmarshal(data, &h) if err != nil { return nil, trace.Wrap(err) } switch h.Version { case V2: var r TunnelConnectionV2 if cfg.SkipValidation { if err := utils.FastUnmarshal(data, &r); err != nil { return nil, trace.BadParameter(err.Error()) } } else { if err := utils.UnmarshalWithSchema(GetTunnelConnectionSchema(), &r, data); err != nil { return nil, trace.BadParameter(err.Error()) } } if err := r.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } if cfg.ID != 0 { r.SetResourceID(cfg.ID) } if !cfg.Expires.IsZero() { r.SetExpiry(cfg.Expires) } return &r, nil } return nil, trace.BadParameter("reverse tunnel version %v is not supported", h.Version) }
go
func UnmarshalTunnelConnection(data []byte, opts ...MarshalOption) (TunnelConnection, error) { if len(data) == 0 { return nil, trace.BadParameter("missing tunnel connection data") } cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } var h ResourceHeader err = utils.FastUnmarshal(data, &h) if err != nil { return nil, trace.Wrap(err) } switch h.Version { case V2: var r TunnelConnectionV2 if cfg.SkipValidation { if err := utils.FastUnmarshal(data, &r); err != nil { return nil, trace.BadParameter(err.Error()) } } else { if err := utils.UnmarshalWithSchema(GetTunnelConnectionSchema(), &r, data); err != nil { return nil, trace.BadParameter(err.Error()) } } if err := r.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } if cfg.ID != 0 { r.SetResourceID(cfg.ID) } if !cfg.Expires.IsZero() { r.SetExpiry(cfg.Expires) } return &r, nil } return nil, trace.BadParameter("reverse tunnel version %v is not supported", h.Version) }
[ "func", "UnmarshalTunnelConnection", "(", "data", "[", "]", "byte", ",", "opts", "...", "MarshalOption", ")", "(", "TunnelConnection", ",", "error", ")", "{", "if", "len", "(", "data", ")", "==", "0", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n", "cfg", ",", "err", ":=", "collectOptions", "(", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "var", "h", "ResourceHeader", "\n", "err", "=", "utils", ".", "FastUnmarshal", "(", "data", ",", "&", "h", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "switch", "h", ".", "Version", "{", "case", "V2", ":", "var", "r", "TunnelConnectionV2", "\n\n", "if", "cfg", ".", "SkipValidation", "{", "if", "err", ":=", "utils", ".", "FastUnmarshal", "(", "data", ",", "&", "r", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "}", "else", "{", "if", "err", ":=", "utils", ".", "UnmarshalWithSchema", "(", "GetTunnelConnectionSchema", "(", ")", ",", "&", "r", ",", "data", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "}", "\n\n", "if", "err", ":=", "r", ".", "CheckAndSetDefaults", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "cfg", ".", "ID", "!=", "0", "{", "r", ".", "SetResourceID", "(", "cfg", ".", "ID", ")", "\n", "}", "\n", "if", "!", "cfg", ".", "Expires", ".", "IsZero", "(", ")", "{", "r", ".", "SetExpiry", "(", "cfg", ".", "Expires", ")", "\n", "}", "\n", "return", "&", "r", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ",", "h", ".", "Version", ")", "\n", "}" ]
// UnmarshalTunnelConnection unmarshals reverse tunnel from JSON or YAML, // sets defaults and checks the schema
[ "UnmarshalTunnelConnection", "unmarshals", "reverse", "tunnel", "from", "JSON", "or", "YAML", "sets", "defaults", "and", "checks", "the", "schema" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/tunnelconn.go#L275-L314
train
gravitational/teleport
lib/services/tunnelconn.go
MarshalTunnelConnection
func MarshalTunnelConnection(rt TunnelConnection, opts ...MarshalOption) ([]byte, error) { cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } switch resource := rt.(type) { case *TunnelConnectionV2: if !cfg.PreserveResourceID { // avoid modifying the original object // to prevent unexpected data races copy := *resource copy.SetResourceID(0) resource = &copy } return utils.FastMarshal(resource) default: return nil, trace.BadParameter("unrecognized resource version %T", rt) } }
go
func MarshalTunnelConnection(rt TunnelConnection, opts ...MarshalOption) ([]byte, error) { cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } switch resource := rt.(type) { case *TunnelConnectionV2: if !cfg.PreserveResourceID { // avoid modifying the original object // to prevent unexpected data races copy := *resource copy.SetResourceID(0) resource = &copy } return utils.FastMarshal(resource) default: return nil, trace.BadParameter("unrecognized resource version %T", rt) } }
[ "func", "MarshalTunnelConnection", "(", "rt", "TunnelConnection", ",", "opts", "...", "MarshalOption", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "cfg", ",", "err", ":=", "collectOptions", "(", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "switch", "resource", ":=", "rt", ".", "(", "type", ")", "{", "case", "*", "TunnelConnectionV2", ":", "if", "!", "cfg", ".", "PreserveResourceID", "{", "// avoid modifying the original object", "// to prevent unexpected data races", "copy", ":=", "*", "resource", "\n", "copy", ".", "SetResourceID", "(", "0", ")", "\n", "resource", "=", "&", "copy", "\n", "}", "\n", "return", "utils", ".", "FastMarshal", "(", "resource", ")", "\n", "default", ":", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ",", "rt", ")", "\n", "}", "\n", "}" ]
// MarshalTunnelConnection marshals tunnel connection
[ "MarshalTunnelConnection", "marshals", "tunnel", "connection" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/tunnelconn.go#L317-L335
train
gravitational/teleport
tool/tctl/common/status_command.go
Initialize
func (c *StatusCommand) Initialize(app *kingpin.Application, config *service.Config) { c.config = config c.status = app.Command("status", "Report cluster status") }
go
func (c *StatusCommand) Initialize(app *kingpin.Application, config *service.Config) { c.config = config c.status = app.Command("status", "Report cluster status") }
[ "func", "(", "c", "*", "StatusCommand", ")", "Initialize", "(", "app", "*", "kingpin", ".", "Application", ",", "config", "*", "service", ".", "Config", ")", "{", "c", ".", "config", "=", "config", "\n", "c", ".", "status", "=", "app", ".", "Command", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "}" ]
// Initialize allows StatusCommand to plug itself into the CLI parser.
[ "Initialize", "allows", "StatusCommand", "to", "plug", "itself", "into", "the", "CLI", "parser", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/status_command.go#L41-L44
train
gravitational/teleport
tool/tctl/common/status_command.go
Status
func (c *StatusCommand) Status(client auth.ClientI) error { clusterNameResource, err := client.GetClusterName() if err != nil { return trace.Wrap(err) } clusterName := clusterNameResource.GetClusterName() hostCAs, err := client.GetCertAuthorities(services.HostCA, false) if err != nil { return trace.Wrap(err) } userCAs, err := client.GetCertAuthorities(services.UserCA, false) if err != nil { return trace.Wrap(err) } // Calculate the CA pin for this cluster. The CA pin is used by the client // to verify the identity of the Auth Server. caPin, err := calculateCAPin(client) if err != nil { return trace.Wrap(err) } authorities := append(userCAs, hostCAs...) view := func() string { table := asciitable.MakeHeadlessTable(2) table.AddRow([]string{"Cluster", clusterName}) for _, ca := range authorities { if ca.GetClusterName() != clusterName { continue } info := fmt.Sprintf("%v CA ", strings.Title(string(ca.GetType()))) rotation := ca.GetRotation() if c.config.Debug { table.AddRow([]string{info, fmt.Sprintf("%v, update_servers: %v, complete: %v", rotation.String(), rotation.Schedule.UpdateServers.Format(teleport.HumanDateFormatSeconds), rotation.Schedule.Standby.Format(teleport.HumanDateFormatSeconds), )}) } else { table.AddRow([]string{info, rotation.String()}) } } table.AddRow([]string{"CA pin", caPin}) return table.AsBuffer().String() } fmt.Printf(view()) // in debug mode, output mode of remote certificate authorities if c.config.Debug { view := func() string { table := asciitable.MakeHeadlessTable(2) for _, ca := range authorities { if ca.GetClusterName() == clusterName { continue } info := fmt.Sprintf("Remote %v CA %q", strings.Title(string(ca.GetType())), ca.GetClusterName()) rotation := ca.GetRotation() table.AddRow([]string{info, rotation.String()}) } return "Remote clusters\n\n" + table.AsBuffer().String() } fmt.Printf(view()) } return nil }
go
func (c *StatusCommand) Status(client auth.ClientI) error { clusterNameResource, err := client.GetClusterName() if err != nil { return trace.Wrap(err) } clusterName := clusterNameResource.GetClusterName() hostCAs, err := client.GetCertAuthorities(services.HostCA, false) if err != nil { return trace.Wrap(err) } userCAs, err := client.GetCertAuthorities(services.UserCA, false) if err != nil { return trace.Wrap(err) } // Calculate the CA pin for this cluster. The CA pin is used by the client // to verify the identity of the Auth Server. caPin, err := calculateCAPin(client) if err != nil { return trace.Wrap(err) } authorities := append(userCAs, hostCAs...) view := func() string { table := asciitable.MakeHeadlessTable(2) table.AddRow([]string{"Cluster", clusterName}) for _, ca := range authorities { if ca.GetClusterName() != clusterName { continue } info := fmt.Sprintf("%v CA ", strings.Title(string(ca.GetType()))) rotation := ca.GetRotation() if c.config.Debug { table.AddRow([]string{info, fmt.Sprintf("%v, update_servers: %v, complete: %v", rotation.String(), rotation.Schedule.UpdateServers.Format(teleport.HumanDateFormatSeconds), rotation.Schedule.Standby.Format(teleport.HumanDateFormatSeconds), )}) } else { table.AddRow([]string{info, rotation.String()}) } } table.AddRow([]string{"CA pin", caPin}) return table.AsBuffer().String() } fmt.Printf(view()) // in debug mode, output mode of remote certificate authorities if c.config.Debug { view := func() string { table := asciitable.MakeHeadlessTable(2) for _, ca := range authorities { if ca.GetClusterName() == clusterName { continue } info := fmt.Sprintf("Remote %v CA %q", strings.Title(string(ca.GetType())), ca.GetClusterName()) rotation := ca.GetRotation() table.AddRow([]string{info, rotation.String()}) } return "Remote clusters\n\n" + table.AsBuffer().String() } fmt.Printf(view()) } return nil }
[ "func", "(", "c", "*", "StatusCommand", ")", "Status", "(", "client", "auth", ".", "ClientI", ")", "error", "{", "clusterNameResource", ",", "err", ":=", "client", ".", "GetClusterName", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "clusterName", ":=", "clusterNameResource", ".", "GetClusterName", "(", ")", "\n\n", "hostCAs", ",", "err", ":=", "client", ".", "GetCertAuthorities", "(", "services", ".", "HostCA", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "userCAs", ",", "err", ":=", "client", ".", "GetCertAuthorities", "(", "services", ".", "UserCA", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "// Calculate the CA pin for this cluster. The CA pin is used by the client", "// to verify the identity of the Auth Server.", "caPin", ",", "err", ":=", "calculateCAPin", "(", "client", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "authorities", ":=", "append", "(", "userCAs", ",", "hostCAs", "...", ")", "\n", "view", ":=", "func", "(", ")", "string", "{", "table", ":=", "asciitable", ".", "MakeHeadlessTable", "(", "2", ")", "\n", "table", ".", "AddRow", "(", "[", "]", "string", "{", "\"", "\"", ",", "clusterName", "}", ")", "\n", "for", "_", ",", "ca", ":=", "range", "authorities", "{", "if", "ca", ".", "GetClusterName", "(", ")", "!=", "clusterName", "{", "continue", "\n", "}", "\n", "info", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "strings", ".", "Title", "(", "string", "(", "ca", ".", "GetType", "(", ")", ")", ")", ")", "\n", "rotation", ":=", "ca", ".", "GetRotation", "(", ")", "\n", "if", "c", ".", "config", ".", "Debug", "{", "table", ".", "AddRow", "(", "[", "]", "string", "{", "info", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "rotation", ".", "String", "(", ")", ",", "rotation", ".", "Schedule", ".", "UpdateServers", ".", "Format", "(", "teleport", ".", "HumanDateFormatSeconds", ")", ",", "rotation", ".", "Schedule", ".", "Standby", ".", "Format", "(", "teleport", ".", "HumanDateFormatSeconds", ")", ",", ")", "}", ")", "\n", "}", "else", "{", "table", ".", "AddRow", "(", "[", "]", "string", "{", "info", ",", "rotation", ".", "String", "(", ")", "}", ")", "\n", "}", "\n\n", "}", "\n", "table", ".", "AddRow", "(", "[", "]", "string", "{", "\"", "\"", ",", "caPin", "}", ")", "\n", "return", "table", ".", "AsBuffer", "(", ")", ".", "String", "(", ")", "\n", "}", "\n", "fmt", ".", "Printf", "(", "view", "(", ")", ")", "\n\n", "// in debug mode, output mode of remote certificate authorities", "if", "c", ".", "config", ".", "Debug", "{", "view", ":=", "func", "(", ")", "string", "{", "table", ":=", "asciitable", ".", "MakeHeadlessTable", "(", "2", ")", "\n", "for", "_", ",", "ca", ":=", "range", "authorities", "{", "if", "ca", ".", "GetClusterName", "(", ")", "==", "clusterName", "{", "continue", "\n", "}", "\n", "info", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "strings", ".", "Title", "(", "string", "(", "ca", ".", "GetType", "(", ")", ")", ")", ",", "ca", ".", "GetClusterName", "(", ")", ")", "\n", "rotation", ":=", "ca", ".", "GetRotation", "(", ")", "\n", "table", ".", "AddRow", "(", "[", "]", "string", "{", "info", ",", "rotation", ".", "String", "(", ")", "}", ")", "\n", "}", "\n", "return", "\"", "\\n", "\\n", "\"", "+", "table", ".", "AsBuffer", "(", ")", ".", "String", "(", ")", "\n", "}", "\n", "fmt", ".", "Printf", "(", "view", "(", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Status is called to execute "status" CLI command.
[ "Status", "is", "called", "to", "execute", "status", "CLI", "command", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/status_command.go#L58-L126
train
gravitational/teleport
lib/auth/trustedcluster.go
DeleteTrustedCluster
func (a *AuthServer) DeleteTrustedCluster(name string) error { err := a.DeleteCertAuthority(services.CertAuthID{Type: services.HostCA, DomainName: name}) if err != nil { if !trace.IsNotFound(err) { return trace.Wrap(err) } } err = a.DeleteCertAuthority(services.CertAuthID{Type: services.UserCA, DomainName: name}) if err != nil { if !trace.IsNotFound(err) { return trace.Wrap(err) } } err = a.DeleteReverseTunnel(name) if err != nil { if !trace.IsNotFound(err) { return trace.Wrap(err) } } err = a.Presence.DeleteTrustedCluster(name) if err != nil { return trace.Wrap(err) } return nil }
go
func (a *AuthServer) DeleteTrustedCluster(name string) error { err := a.DeleteCertAuthority(services.CertAuthID{Type: services.HostCA, DomainName: name}) if err != nil { if !trace.IsNotFound(err) { return trace.Wrap(err) } } err = a.DeleteCertAuthority(services.CertAuthID{Type: services.UserCA, DomainName: name}) if err != nil { if !trace.IsNotFound(err) { return trace.Wrap(err) } } err = a.DeleteReverseTunnel(name) if err != nil { if !trace.IsNotFound(err) { return trace.Wrap(err) } } err = a.Presence.DeleteTrustedCluster(name) if err != nil { return trace.Wrap(err) } return nil }
[ "func", "(", "a", "*", "AuthServer", ")", "DeleteTrustedCluster", "(", "name", "string", ")", "error", "{", "err", ":=", "a", ".", "DeleteCertAuthority", "(", "services", ".", "CertAuthID", "{", "Type", ":", "services", ".", "HostCA", ",", "DomainName", ":", "name", "}", ")", "\n", "if", "err", "!=", "nil", "{", "if", "!", "trace", ".", "IsNotFound", "(", "err", ")", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "}", "\n\n", "err", "=", "a", ".", "DeleteCertAuthority", "(", "services", ".", "CertAuthID", "{", "Type", ":", "services", ".", "UserCA", ",", "DomainName", ":", "name", "}", ")", "\n", "if", "err", "!=", "nil", "{", "if", "!", "trace", ".", "IsNotFound", "(", "err", ")", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "}", "\n\n", "err", "=", "a", ".", "DeleteReverseTunnel", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "if", "!", "trace", ".", "IsNotFound", "(", "err", ")", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "}", "\n\n", "err", "=", "a", ".", "Presence", ".", "DeleteTrustedCluster", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// DeleteTrustedCluster removes services.CertAuthority, services.ReverseTunnel, // and services.TrustedCluster resources.
[ "DeleteTrustedCluster", "removes", "services", ".", "CertAuthority", "services", ".", "ReverseTunnel", "and", "services", ".", "TrustedCluster", "resources", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/trustedcluster.go#L171-L199
train
gravitational/teleport
lib/auth/trustedcluster.go
DeleteRemoteCluster
func (a *AuthServer) DeleteRemoteCluster(clusterName string) error { // To make sure remote cluster exists - to protect against random // clusterName requests (e.g. when clusterName is set to local cluster name) _, err := a.Presence.GetRemoteCluster(clusterName) if err != nil { return trace.Wrap(err) } // delete cert authorities associated with the cluster err = a.DeleteCertAuthority(services.CertAuthID{ Type: services.HostCA, DomainName: clusterName, }) if err != nil { // this method could have succeeded on the first call, // but then if the remote cluster resource could not be deleted // it would be impossible to delete the cluster after then if !trace.IsNotFound(err) { return trace.Wrap(err) } } // there should be no User CA in trusted clusters on the main cluster side // per standard automation but clean up just in case err = a.DeleteCertAuthority(services.CertAuthID{ Type: services.UserCA, DomainName: clusterName, }) if err != nil { if !trace.IsNotFound(err) { return trace.Wrap(err) } } return a.Presence.DeleteRemoteCluster(clusterName) }
go
func (a *AuthServer) DeleteRemoteCluster(clusterName string) error { // To make sure remote cluster exists - to protect against random // clusterName requests (e.g. when clusterName is set to local cluster name) _, err := a.Presence.GetRemoteCluster(clusterName) if err != nil { return trace.Wrap(err) } // delete cert authorities associated with the cluster err = a.DeleteCertAuthority(services.CertAuthID{ Type: services.HostCA, DomainName: clusterName, }) if err != nil { // this method could have succeeded on the first call, // but then if the remote cluster resource could not be deleted // it would be impossible to delete the cluster after then if !trace.IsNotFound(err) { return trace.Wrap(err) } } // there should be no User CA in trusted clusters on the main cluster side // per standard automation but clean up just in case err = a.DeleteCertAuthority(services.CertAuthID{ Type: services.UserCA, DomainName: clusterName, }) if err != nil { if !trace.IsNotFound(err) { return trace.Wrap(err) } } return a.Presence.DeleteRemoteCluster(clusterName) }
[ "func", "(", "a", "*", "AuthServer", ")", "DeleteRemoteCluster", "(", "clusterName", "string", ")", "error", "{", "// To make sure remote cluster exists - to protect against random", "// clusterName requests (e.g. when clusterName is set to local cluster name)", "_", ",", "err", ":=", "a", ".", "Presence", ".", "GetRemoteCluster", "(", "clusterName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "// delete cert authorities associated with the cluster", "err", "=", "a", ".", "DeleteCertAuthority", "(", "services", ".", "CertAuthID", "{", "Type", ":", "services", ".", "HostCA", ",", "DomainName", ":", "clusterName", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "// this method could have succeeded on the first call,", "// but then if the remote cluster resource could not be deleted", "// it would be impossible to delete the cluster after then", "if", "!", "trace", ".", "IsNotFound", "(", "err", ")", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "}", "\n", "// there should be no User CA in trusted clusters on the main cluster side", "// per standard automation but clean up just in case", "err", "=", "a", ".", "DeleteCertAuthority", "(", "services", ".", "CertAuthID", "{", "Type", ":", "services", ".", "UserCA", ",", "DomainName", ":", "clusterName", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "if", "!", "trace", ".", "IsNotFound", "(", "err", ")", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "}", "\n", "return", "a", ".", "Presence", ".", "DeleteRemoteCluster", "(", "clusterName", ")", "\n", "}" ]
// DeleteRemoteCluster deletes remote cluster resource, all certificate authorities // associated with it
[ "DeleteRemoteCluster", "deletes", "remote", "cluster", "resource", "all", "certificate", "authorities", "associated", "with", "it" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/trustedcluster.go#L293-L325
train
gravitational/teleport
lib/auth/trustedcluster.go
GetRemoteCluster
func (a *AuthServer) GetRemoteCluster(clusterName string) (services.RemoteCluster, error) { // To make sure remote cluster exists - to protect against random // clusterName requests (e.g. when clusterName is set to local cluster name) remoteCluster, err := a.Presence.GetRemoteCluster(clusterName) if err != nil { return nil, trace.Wrap(err) } if err := a.updateRemoteClusterStatus(remoteCluster); err != nil { return nil, trace.Wrap(err) } return remoteCluster, nil }
go
func (a *AuthServer) GetRemoteCluster(clusterName string) (services.RemoteCluster, error) { // To make sure remote cluster exists - to protect against random // clusterName requests (e.g. when clusterName is set to local cluster name) remoteCluster, err := a.Presence.GetRemoteCluster(clusterName) if err != nil { return nil, trace.Wrap(err) } if err := a.updateRemoteClusterStatus(remoteCluster); err != nil { return nil, trace.Wrap(err) } return remoteCluster, nil }
[ "func", "(", "a", "*", "AuthServer", ")", "GetRemoteCluster", "(", "clusterName", "string", ")", "(", "services", ".", "RemoteCluster", ",", "error", ")", "{", "// To make sure remote cluster exists - to protect against random", "// clusterName requests (e.g. when clusterName is set to local cluster name)", "remoteCluster", ",", "err", ":=", "a", ".", "Presence", ".", "GetRemoteCluster", "(", "clusterName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "err", ":=", "a", ".", "updateRemoteClusterStatus", "(", "remoteCluster", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "remoteCluster", ",", "nil", "\n", "}" ]
// GetRemoteCluster returns remote cluster by name
[ "GetRemoteCluster", "returns", "remote", "cluster", "by", "name" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/trustedcluster.go#L328-L339
train
gravitational/teleport
lib/auth/trustedcluster.go
GetRemoteClusters
func (a *AuthServer) GetRemoteClusters(opts ...services.MarshalOption) ([]services.RemoteCluster, error) { // To make sure remote cluster exists - to protect against random // clusterName requests (e.g. when clusterName is set to local cluster name) remoteClusters, err := a.Presence.GetRemoteClusters(opts...) if err != nil { return nil, trace.Wrap(err) } for i := range remoteClusters { if err := a.updateRemoteClusterStatus(remoteClusters[i]); err != nil { return nil, trace.Wrap(err) } } return remoteClusters, nil }
go
func (a *AuthServer) GetRemoteClusters(opts ...services.MarshalOption) ([]services.RemoteCluster, error) { // To make sure remote cluster exists - to protect against random // clusterName requests (e.g. when clusterName is set to local cluster name) remoteClusters, err := a.Presence.GetRemoteClusters(opts...) if err != nil { return nil, trace.Wrap(err) } for i := range remoteClusters { if err := a.updateRemoteClusterStatus(remoteClusters[i]); err != nil { return nil, trace.Wrap(err) } } return remoteClusters, nil }
[ "func", "(", "a", "*", "AuthServer", ")", "GetRemoteClusters", "(", "opts", "...", "services", ".", "MarshalOption", ")", "(", "[", "]", "services", ".", "RemoteCluster", ",", "error", ")", "{", "// To make sure remote cluster exists - to protect against random", "// clusterName requests (e.g. when clusterName is set to local cluster name)", "remoteClusters", ",", "err", ":=", "a", ".", "Presence", ".", "GetRemoteClusters", "(", "opts", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "for", "i", ":=", "range", "remoteClusters", "{", "if", "err", ":=", "a", ".", "updateRemoteClusterStatus", "(", "remoteClusters", "[", "i", "]", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "}", "\n", "return", "remoteClusters", ",", "nil", "\n", "}" ]
// GetRemoteClusters returns remote clusters with updated statuses
[ "GetRemoteClusters", "returns", "remote", "clusters", "with", "updated", "statuses" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/trustedcluster.go#L357-L370
train
gravitational/teleport
lib/auth/trustedcluster.go
activateCertAuthority
func (a *AuthServer) activateCertAuthority(t services.TrustedCluster) error { err := a.ActivateCertAuthority(services.CertAuthID{Type: services.UserCA, DomainName: t.GetName()}) if err != nil { return trace.Wrap(err) } return trace.Wrap(a.ActivateCertAuthority(services.CertAuthID{Type: services.HostCA, DomainName: t.GetName()})) }
go
func (a *AuthServer) activateCertAuthority(t services.TrustedCluster) error { err := a.ActivateCertAuthority(services.CertAuthID{Type: services.UserCA, DomainName: t.GetName()}) if err != nil { return trace.Wrap(err) } return trace.Wrap(a.ActivateCertAuthority(services.CertAuthID{Type: services.HostCA, DomainName: t.GetName()})) }
[ "func", "(", "a", "*", "AuthServer", ")", "activateCertAuthority", "(", "t", "services", ".", "TrustedCluster", ")", "error", "{", "err", ":=", "a", ".", "ActivateCertAuthority", "(", "services", ".", "CertAuthID", "{", "Type", ":", "services", ".", "UserCA", ",", "DomainName", ":", "t", ".", "GetName", "(", ")", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "return", "trace", ".", "Wrap", "(", "a", ".", "ActivateCertAuthority", "(", "services", ".", "CertAuthID", "{", "Type", ":", "services", ".", "HostCA", ",", "DomainName", ":", "t", ".", "GetName", "(", ")", "}", ")", ")", "\n", "}" ]
// activateCertAuthority will activate both the user and host certificate // authority given in the services.TrustedCluster resource.
[ "activateCertAuthority", "will", "activate", "both", "the", "user", "and", "host", "certificate", "authority", "given", "in", "the", "services", ".", "TrustedCluster", "resource", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/trustedcluster.go#L599-L606
train
gravitational/teleport
lib/auth/trustedcluster.go
createReverseTunnel
func (a *AuthServer) createReverseTunnel(t services.TrustedCluster) error { reverseTunnel := services.NewReverseTunnel( t.GetName(), []string{t.GetReverseTunnelAddress()}, ) return trace.Wrap(a.UpsertReverseTunnel(reverseTunnel)) }
go
func (a *AuthServer) createReverseTunnel(t services.TrustedCluster) error { reverseTunnel := services.NewReverseTunnel( t.GetName(), []string{t.GetReverseTunnelAddress()}, ) return trace.Wrap(a.UpsertReverseTunnel(reverseTunnel)) }
[ "func", "(", "a", "*", "AuthServer", ")", "createReverseTunnel", "(", "t", "services", ".", "TrustedCluster", ")", "error", "{", "reverseTunnel", ":=", "services", ".", "NewReverseTunnel", "(", "t", ".", "GetName", "(", ")", ",", "[", "]", "string", "{", "t", ".", "GetReverseTunnelAddress", "(", ")", "}", ",", ")", "\n", "return", "trace", ".", "Wrap", "(", "a", ".", "UpsertReverseTunnel", "(", "reverseTunnel", ")", ")", "\n", "}" ]
// createReverseTunnel will create a services.ReverseTunnel givenin the // services.TrustedCluster resource.
[ "createReverseTunnel", "will", "create", "a", "services", ".", "ReverseTunnel", "givenin", "the", "services", ".", "TrustedCluster", "resource", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/trustedcluster.go#L621-L627
train
gravitational/teleport
lib/services/local/configuration.go
DeleteClusterName
func (s *ClusterConfigurationService) DeleteClusterName() error { err := s.Delete(context.TODO(), backend.Key(clusterConfigPrefix, namePrefix)) if err != nil { if trace.IsNotFound(err) { return trace.NotFound("cluster configuration not found") } return trace.Wrap(err) } return nil }
go
func (s *ClusterConfigurationService) DeleteClusterName() error { err := s.Delete(context.TODO(), backend.Key(clusterConfigPrefix, namePrefix)) if err != nil { if trace.IsNotFound(err) { return trace.NotFound("cluster configuration not found") } return trace.Wrap(err) } return nil }
[ "func", "(", "s", "*", "ClusterConfigurationService", ")", "DeleteClusterName", "(", ")", "error", "{", "err", ":=", "s", ".", "Delete", "(", "context", ".", "TODO", "(", ")", ",", "backend", ".", "Key", "(", "clusterConfigPrefix", ",", "namePrefix", ")", ")", "\n", "if", "err", "!=", "nil", "{", "if", "trace", ".", "IsNotFound", "(", "err", ")", "{", "return", "trace", ".", "NotFound", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// DeleteClusterName deletes services.ClusterName from the backend.
[ "DeleteClusterName", "deletes", "services", ".", "ClusterName", "from", "the", "backend", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/configuration.go#L54-L63
train
gravitational/teleport
lib/services/local/configuration.go
SetClusterName
func (s *ClusterConfigurationService) SetClusterName(c services.ClusterName) error { value, err := services.GetClusterNameMarshaler().Marshal(c) if err != nil { return trace.Wrap(err) } _, err = s.Create(context.TODO(), backend.Item{ Key: backend.Key(clusterConfigPrefix, namePrefix), Value: value, Expires: c.Expiry(), }) if err != nil { return trace.Wrap(err) } return nil }
go
func (s *ClusterConfigurationService) SetClusterName(c services.ClusterName) error { value, err := services.GetClusterNameMarshaler().Marshal(c) if err != nil { return trace.Wrap(err) } _, err = s.Create(context.TODO(), backend.Item{ Key: backend.Key(clusterConfigPrefix, namePrefix), Value: value, Expires: c.Expiry(), }) if err != nil { return trace.Wrap(err) } return nil }
[ "func", "(", "s", "*", "ClusterConfigurationService", ")", "SetClusterName", "(", "c", "services", ".", "ClusterName", ")", "error", "{", "value", ",", "err", ":=", "services", ".", "GetClusterNameMarshaler", "(", ")", ".", "Marshal", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "_", ",", "err", "=", "s", ".", "Create", "(", "context", ".", "TODO", "(", ")", ",", "backend", ".", "Item", "{", "Key", ":", "backend", ".", "Key", "(", "clusterConfigPrefix", ",", "namePrefix", ")", ",", "Value", ":", "value", ",", "Expires", ":", "c", ".", "Expiry", "(", ")", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// SetClusterName sets the name of the cluster in the backend. SetClusterName // can only be called once on a cluster after which it will return trace.AlreadyExists.
[ "SetClusterName", "sets", "the", "name", "of", "the", "cluster", "in", "the", "backend", ".", "SetClusterName", "can", "only", "be", "called", "once", "on", "a", "cluster", "after", "which", "it", "will", "return", "trace", ".", "AlreadyExists", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/configuration.go#L67-L83
train
gravitational/teleport
lib/services/local/configuration.go
GetAuthPreference
func (s *ClusterConfigurationService) GetAuthPreference() (services.AuthPreference, error) { item, err := s.Get(context.TODO(), backend.Key(authPrefix, preferencePrefix, generalPrefix)) if err != nil { if trace.IsNotFound(err) { return nil, trace.NotFound("authentication preference not found") } return nil, trace.Wrap(err) } return services.GetAuthPreferenceMarshaler().Unmarshal(item.Value, services.WithResourceID(item.ID), services.WithExpires(item.Expires)) }
go
func (s *ClusterConfigurationService) GetAuthPreference() (services.AuthPreference, error) { item, err := s.Get(context.TODO(), backend.Key(authPrefix, preferencePrefix, generalPrefix)) if err != nil { if trace.IsNotFound(err) { return nil, trace.NotFound("authentication preference not found") } return nil, trace.Wrap(err) } return services.GetAuthPreferenceMarshaler().Unmarshal(item.Value, services.WithResourceID(item.ID), services.WithExpires(item.Expires)) }
[ "func", "(", "s", "*", "ClusterConfigurationService", ")", "GetAuthPreference", "(", ")", "(", "services", ".", "AuthPreference", ",", "error", ")", "{", "item", ",", "err", ":=", "s", ".", "Get", "(", "context", ".", "TODO", "(", ")", ",", "backend", ".", "Key", "(", "authPrefix", ",", "preferencePrefix", ",", "generalPrefix", ")", ")", "\n", "if", "err", "!=", "nil", "{", "if", "trace", ".", "IsNotFound", "(", "err", ")", "{", "return", "nil", ",", "trace", ".", "NotFound", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "services", ".", "GetAuthPreferenceMarshaler", "(", ")", ".", "Unmarshal", "(", "item", ".", "Value", ",", "services", ".", "WithResourceID", "(", "item", ".", "ID", ")", ",", "services", ".", "WithExpires", "(", "item", ".", "Expires", ")", ")", "\n", "}" ]
// GetAuthPreference fetches the cluster authentication preferences // from the backend and return them.
[ "GetAuthPreference", "fetches", "the", "cluster", "authentication", "preferences", "from", "the", "backend", "and", "return", "them", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/configuration.go#L151-L161
train
gravitational/teleport
lib/services/local/configuration.go
SetAuthPreference
func (s *ClusterConfigurationService) SetAuthPreference(preferences services.AuthPreference) error { value, err := services.GetAuthPreferenceMarshaler().Marshal(preferences) if err != nil { return trace.Wrap(err) } item := backend.Item{ Key: backend.Key(authPrefix, preferencePrefix, generalPrefix), Value: value, ID: preferences.GetResourceID(), } _, err = s.Put(context.TODO(), item) if err != nil { return trace.Wrap(err) } return nil }
go
func (s *ClusterConfigurationService) SetAuthPreference(preferences services.AuthPreference) error { value, err := services.GetAuthPreferenceMarshaler().Marshal(preferences) if err != nil { return trace.Wrap(err) } item := backend.Item{ Key: backend.Key(authPrefix, preferencePrefix, generalPrefix), Value: value, ID: preferences.GetResourceID(), } _, err = s.Put(context.TODO(), item) if err != nil { return trace.Wrap(err) } return nil }
[ "func", "(", "s", "*", "ClusterConfigurationService", ")", "SetAuthPreference", "(", "preferences", "services", ".", "AuthPreference", ")", "error", "{", "value", ",", "err", ":=", "services", ".", "GetAuthPreferenceMarshaler", "(", ")", ".", "Marshal", "(", "preferences", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "item", ":=", "backend", ".", "Item", "{", "Key", ":", "backend", ".", "Key", "(", "authPrefix", ",", "preferencePrefix", ",", "generalPrefix", ")", ",", "Value", ":", "value", ",", "ID", ":", "preferences", ".", "GetResourceID", "(", ")", ",", "}", "\n\n", "_", ",", "err", "=", "s", ".", "Put", "(", "context", ".", "TODO", "(", ")", ",", "item", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// SetAuthPreference sets the cluster authentication preferences // on the backend.
[ "SetAuthPreference", "sets", "the", "cluster", "authentication", "preferences", "on", "the", "backend", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/configuration.go#L165-L183
train
gravitational/teleport
lib/services/local/configuration.go
DeleteClusterConfig
func (s *ClusterConfigurationService) DeleteClusterConfig() error { err := s.Delete(context.TODO(), backend.Key(clusterConfigPrefix, generalPrefix)) if err != nil { if trace.IsNotFound(err) { return trace.NotFound("cluster configuration not found") } return trace.Wrap(err) } return nil }
go
func (s *ClusterConfigurationService) DeleteClusterConfig() error { err := s.Delete(context.TODO(), backend.Key(clusterConfigPrefix, generalPrefix)) if err != nil { if trace.IsNotFound(err) { return trace.NotFound("cluster configuration not found") } return trace.Wrap(err) } return nil }
[ "func", "(", "s", "*", "ClusterConfigurationService", ")", "DeleteClusterConfig", "(", ")", "error", "{", "err", ":=", "s", ".", "Delete", "(", "context", ".", "TODO", "(", ")", ",", "backend", ".", "Key", "(", "clusterConfigPrefix", ",", "generalPrefix", ")", ")", "\n", "if", "err", "!=", "nil", "{", "if", "trace", ".", "IsNotFound", "(", "err", ")", "{", "return", "trace", ".", "NotFound", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// DeleteClusterConfig deletes services.ClusterConfig from the backend.
[ "DeleteClusterConfig", "deletes", "services", ".", "ClusterConfig", "from", "the", "backend", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/configuration.go#L200-L209
train
gravitational/teleport
lib/services/local/configuration.go
SetClusterConfig
func (s *ClusterConfigurationService) SetClusterConfig(c services.ClusterConfig) error { value, err := services.GetClusterConfigMarshaler().Marshal(c) if err != nil { return trace.Wrap(err) } item := backend.Item{ Key: backend.Key(clusterConfigPrefix, generalPrefix), Value: value, ID: c.GetResourceID(), } _, err = s.Put(context.TODO(), item) if err != nil { return trace.Wrap(err) } return nil }
go
func (s *ClusterConfigurationService) SetClusterConfig(c services.ClusterConfig) error { value, err := services.GetClusterConfigMarshaler().Marshal(c) if err != nil { return trace.Wrap(err) } item := backend.Item{ Key: backend.Key(clusterConfigPrefix, generalPrefix), Value: value, ID: c.GetResourceID(), } _, err = s.Put(context.TODO(), item) if err != nil { return trace.Wrap(err) } return nil }
[ "func", "(", "s", "*", "ClusterConfigurationService", ")", "SetClusterConfig", "(", "c", "services", ".", "ClusterConfig", ")", "error", "{", "value", ",", "err", ":=", "services", ".", "GetClusterConfigMarshaler", "(", ")", ".", "Marshal", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "item", ":=", "backend", ".", "Item", "{", "Key", ":", "backend", ".", "Key", "(", "clusterConfigPrefix", ",", "generalPrefix", ")", ",", "Value", ":", "value", ",", "ID", ":", "c", ".", "GetResourceID", "(", ")", ",", "}", "\n\n", "_", ",", "err", "=", "s", ".", "Put", "(", "context", ".", "TODO", "(", ")", ",", "item", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// SetClusterConfig sets services.ClusterConfig on the backend.
[ "SetClusterConfig", "sets", "services", ".", "ClusterConfig", "on", "the", "backend", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/configuration.go#L212-L230
train
gravitational/teleport
lib/httplib/httpheaders.go
SetNoCacheHeaders
func SetNoCacheHeaders(h http.Header) { h.Set("Cache-Control", "no-cache, no-store, must-revalidate") h.Set("Pragma", "no-cache") h.Set("Expires", "0") }
go
func SetNoCacheHeaders(h http.Header) { h.Set("Cache-Control", "no-cache, no-store, must-revalidate") h.Set("Pragma", "no-cache") h.Set("Expires", "0") }
[ "func", "SetNoCacheHeaders", "(", "h", "http", ".", "Header", ")", "{", "h", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "h", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "h", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "}" ]
// SetNoCacheHeaders tells proxies and browsers do not cache the content
[ "SetNoCacheHeaders", "tells", "proxies", "and", "browsers", "do", "not", "cache", "the", "content" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/httplib/httpheaders.go#L27-L31
train
gravitational/teleport
lib/httplib/httpheaders.go
SetIndexHTMLHeaders
func SetIndexHTMLHeaders(h http.Header) { SetNoCacheHeaders(h) SetSameOriginIFrame(h) SetNoSniff(h) // X-Frame-Options indicates that the page can only be displayed in iframe on the same origin as the page itself h.Set("X-Frame-Options", "SAMEORIGIN") // X-XSS-Protection is a feature of Internet Explorer, Chrome and Safari that stops pages // from loading when they detect reflected cross-site scripting (XSS) attacks. h.Set("X-XSS-Protection", "1; mode=block") // Once a supported browser receives this header that browser will prevent any communications from // being sent over HTTP to the specified domain and will instead send all communications over HTTPS. // It also prevents HTTPS click through prompts on browsers h.Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains") // Prevent web browsers from using content sniffing to discover a file’s MIME type h.Set("X-Content-Type-Options", "nosniff") // Set content policy flags var cspValue = strings.Join([]string{ "script-src 'self'", // 'unsafe-inline' needed for reactjs inline styles "style-src 'self' 'unsafe-inline'", "object-src 'none'", "img-src 'self' data: blob:", }, ";") h.Set("Content-Security-Policy", cspValue) }
go
func SetIndexHTMLHeaders(h http.Header) { SetNoCacheHeaders(h) SetSameOriginIFrame(h) SetNoSniff(h) // X-Frame-Options indicates that the page can only be displayed in iframe on the same origin as the page itself h.Set("X-Frame-Options", "SAMEORIGIN") // X-XSS-Protection is a feature of Internet Explorer, Chrome and Safari that stops pages // from loading when they detect reflected cross-site scripting (XSS) attacks. h.Set("X-XSS-Protection", "1; mode=block") // Once a supported browser receives this header that browser will prevent any communications from // being sent over HTTP to the specified domain and will instead send all communications over HTTPS. // It also prevents HTTPS click through prompts on browsers h.Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains") // Prevent web browsers from using content sniffing to discover a file’s MIME type h.Set("X-Content-Type-Options", "nosniff") // Set content policy flags var cspValue = strings.Join([]string{ "script-src 'self'", // 'unsafe-inline' needed for reactjs inline styles "style-src 'self' 'unsafe-inline'", "object-src 'none'", "img-src 'self' data: blob:", }, ";") h.Set("Content-Security-Policy", cspValue) }
[ "func", "SetIndexHTMLHeaders", "(", "h", "http", ".", "Header", ")", "{", "SetNoCacheHeaders", "(", "h", ")", "\n", "SetSameOriginIFrame", "(", "h", ")", "\n", "SetNoSniff", "(", "h", ")", "\n\n", "// X-Frame-Options indicates that the page can only be displayed in iframe on the same origin as the page itself", "h", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "// X-XSS-Protection is a feature of Internet Explorer, Chrome and Safari that stops pages", "// from loading when they detect reflected cross-site scripting (XSS) attacks.", "h", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "// Once a supported browser receives this header that browser will prevent any communications from", "// being sent over HTTP to the specified domain and will instead send all communications over HTTPS.", "// It also prevents HTTPS click through prompts on browsers", "h", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "// Prevent web browsers from using content sniffing to discover a file’s MIME type", "h", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "// Set content policy flags", "var", "cspValue", "=", "strings", ".", "Join", "(", "[", "]", "string", "{", "\"", "\"", ",", "// 'unsafe-inline' needed for reactjs inline styles", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "}", ",", "\"", "\"", ")", "\n\n", "h", ".", "Set", "(", "\"", "\"", ",", "cspValue", ")", "\n", "}" ]
// SetIndexHTMLHeaders sets security header flags for main index.html page
[ "SetIndexHTMLHeaders", "sets", "security", "header", "flags", "for", "main", "index", ".", "html", "page" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/httplib/httpheaders.go#L40-L70
train
gravitational/teleport
lib/kube/proxy/roundtrip.go
NewSpdyRoundTripperWithDialer
func NewSpdyRoundTripperWithDialer(cfg roundTripperConfig) *SpdyRoundTripper { return &SpdyRoundTripper{tlsConfig: cfg.tlsConfig, followRedirects: cfg.followRedirects, dialWithContext: cfg.dial, ctx: cfg.ctx, authCtx: cfg.authCtx, bearerToken: cfg.bearerToken} }
go
func NewSpdyRoundTripperWithDialer(cfg roundTripperConfig) *SpdyRoundTripper { return &SpdyRoundTripper{tlsConfig: cfg.tlsConfig, followRedirects: cfg.followRedirects, dialWithContext: cfg.dial, ctx: cfg.ctx, authCtx: cfg.authCtx, bearerToken: cfg.bearerToken} }
[ "func", "NewSpdyRoundTripperWithDialer", "(", "cfg", "roundTripperConfig", ")", "*", "SpdyRoundTripper", "{", "return", "&", "SpdyRoundTripper", "{", "tlsConfig", ":", "cfg", ".", "tlsConfig", ",", "followRedirects", ":", "cfg", ".", "followRedirects", ",", "dialWithContext", ":", "cfg", ".", "dial", ",", "ctx", ":", "cfg", ".", "ctx", ",", "authCtx", ":", "cfg", ".", "authCtx", ",", "bearerToken", ":", "cfg", ".", "bearerToken", "}", "\n", "}" ]
// NewSpdyRoundTripperWithDialer creates a new SpdyRoundTripper that will use // the specified tlsConfig. This function is mostly meant for unit tests.
[ "NewSpdyRoundTripperWithDialer", "creates", "a", "new", "SpdyRoundTripper", "that", "will", "use", "the", "specified", "tlsConfig", ".", "This", "function", "is", "mostly", "meant", "for", "unit", "tests", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/roundtrip.go#L99-L101
train
gravitational/teleport
lib/kube/proxy/roundtrip.go
dial
func (s *SpdyRoundTripper) dial(req *http.Request) (net.Conn, error) { return s.dialWithoutProxy(req.URL) }
go
func (s *SpdyRoundTripper) dial(req *http.Request) (net.Conn, error) { return s.dialWithoutProxy(req.URL) }
[ "func", "(", "s", "*", "SpdyRoundTripper", ")", "dial", "(", "req", "*", "http", ".", "Request", ")", "(", "net", ".", "Conn", ",", "error", ")", "{", "return", "s", ".", "dialWithoutProxy", "(", "req", ".", "URL", ")", "\n", "}" ]
// dial dials the host specified by req
[ "dial", "dials", "the", "host", "specified", "by", "req" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/roundtrip.go#L125-L127
train
gravitational/teleport
lib/srv/authhandlers.go
CreateIdentityContext
func (h *AuthHandlers) CreateIdentityContext(sconn *ssh.ServerConn) (IdentityContext, error) { identity := IdentityContext{ TeleportUser: sconn.Permissions.Extensions[utils.CertTeleportUser], Certificate: []byte(sconn.Permissions.Extensions[utils.CertTeleportUserCertificate]), Login: sconn.User(), } clusterName, err := h.AccessPoint.GetClusterName() if err != nil { return IdentityContext{}, trace.Wrap(err) } certificate, err := identity.GetCertificate() if err != nil { return IdentityContext{}, trace.Wrap(err) } if certificate.ValidBefore != 0 { identity.CertValidBefore = time.Unix(int64(certificate.ValidBefore), 0) } certAuthority, err := h.authorityForCert(services.UserCA, certificate.SignatureKey) if err != nil { return IdentityContext{}, trace.Wrap(err) } identity.CertAuthority = certAuthority roleSet, err := h.fetchRoleSet(certificate, certAuthority, identity.TeleportUser, clusterName.GetClusterName()) if err != nil { return IdentityContext{}, trace.Wrap(err) } identity.RoleSet = roleSet return identity, nil }
go
func (h *AuthHandlers) CreateIdentityContext(sconn *ssh.ServerConn) (IdentityContext, error) { identity := IdentityContext{ TeleportUser: sconn.Permissions.Extensions[utils.CertTeleportUser], Certificate: []byte(sconn.Permissions.Extensions[utils.CertTeleportUserCertificate]), Login: sconn.User(), } clusterName, err := h.AccessPoint.GetClusterName() if err != nil { return IdentityContext{}, trace.Wrap(err) } certificate, err := identity.GetCertificate() if err != nil { return IdentityContext{}, trace.Wrap(err) } if certificate.ValidBefore != 0 { identity.CertValidBefore = time.Unix(int64(certificate.ValidBefore), 0) } certAuthority, err := h.authorityForCert(services.UserCA, certificate.SignatureKey) if err != nil { return IdentityContext{}, trace.Wrap(err) } identity.CertAuthority = certAuthority roleSet, err := h.fetchRoleSet(certificate, certAuthority, identity.TeleportUser, clusterName.GetClusterName()) if err != nil { return IdentityContext{}, trace.Wrap(err) } identity.RoleSet = roleSet return identity, nil }
[ "func", "(", "h", "*", "AuthHandlers", ")", "CreateIdentityContext", "(", "sconn", "*", "ssh", ".", "ServerConn", ")", "(", "IdentityContext", ",", "error", ")", "{", "identity", ":=", "IdentityContext", "{", "TeleportUser", ":", "sconn", ".", "Permissions", ".", "Extensions", "[", "utils", ".", "CertTeleportUser", "]", ",", "Certificate", ":", "[", "]", "byte", "(", "sconn", ".", "Permissions", ".", "Extensions", "[", "utils", ".", "CertTeleportUserCertificate", "]", ")", ",", "Login", ":", "sconn", ".", "User", "(", ")", ",", "}", "\n\n", "clusterName", ",", "err", ":=", "h", ".", "AccessPoint", ".", "GetClusterName", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "IdentityContext", "{", "}", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "certificate", ",", "err", ":=", "identity", ".", "GetCertificate", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "IdentityContext", "{", "}", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "certificate", ".", "ValidBefore", "!=", "0", "{", "identity", ".", "CertValidBefore", "=", "time", ".", "Unix", "(", "int64", "(", "certificate", ".", "ValidBefore", ")", ",", "0", ")", "\n", "}", "\n\n", "certAuthority", ",", "err", ":=", "h", ".", "authorityForCert", "(", "services", ".", "UserCA", ",", "certificate", ".", "SignatureKey", ")", "\n", "if", "err", "!=", "nil", "{", "return", "IdentityContext", "{", "}", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "identity", ".", "CertAuthority", "=", "certAuthority", "\n\n", "roleSet", ",", "err", ":=", "h", ".", "fetchRoleSet", "(", "certificate", ",", "certAuthority", ",", "identity", ".", "TeleportUser", ",", "clusterName", ".", "GetClusterName", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "IdentityContext", "{", "}", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "identity", ".", "RoleSet", "=", "roleSet", "\n\n", "return", "identity", ",", "nil", "\n", "}" ]
// BuildIdentityContext returns an IdentityContext populated with information // about the logged in user on the connection.
[ "BuildIdentityContext", "returns", "an", "IdentityContext", "populated", "with", "information", "about", "the", "logged", "in", "user", "on", "the", "connection", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/authhandlers.go#L59-L92
train
gravitational/teleport
lib/srv/authhandlers.go
CheckAgentForward
func (h *AuthHandlers) CheckAgentForward(ctx *ServerContext) error { if err := ctx.Identity.RoleSet.CheckAgentForward(ctx.Identity.Login); err != nil { return trace.Wrap(err) } return nil }
go
func (h *AuthHandlers) CheckAgentForward(ctx *ServerContext) error { if err := ctx.Identity.RoleSet.CheckAgentForward(ctx.Identity.Login); err != nil { return trace.Wrap(err) } return nil }
[ "func", "(", "h", "*", "AuthHandlers", ")", "CheckAgentForward", "(", "ctx", "*", "ServerContext", ")", "error", "{", "if", "err", ":=", "ctx", ".", "Identity", ".", "RoleSet", ".", "CheckAgentForward", "(", "ctx", ".", "Identity", ".", "Login", ")", ";", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// CheckAgentForward checks if agent forwarding is allowed for the users RoleSet.
[ "CheckAgentForward", "checks", "if", "agent", "forwarding", "is", "allowed", "for", "the", "users", "RoleSet", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/authhandlers.go#L95-L101
train
gravitational/teleport
lib/srv/authhandlers.go
CheckPortForward
func (h *AuthHandlers) CheckPortForward(addr string, ctx *ServerContext) error { if ok := ctx.Identity.RoleSet.CanPortForward(); !ok { systemErrorMessage := fmt.Sprintf("port forwarding not allowed by role set: %v", ctx.Identity.RoleSet) userErrorMessage := "port forwarding not allowed" // emit port forward failure event h.AuditLog.EmitAuditEvent(events.PortForwardFailure, events.EventFields{ events.PortForwardAddr: addr, events.PortForwardSuccess: false, events.PortForwardErr: systemErrorMessage, events.EventLogin: ctx.Identity.Login, events.EventUser: ctx.Identity.TeleportUser, events.LocalAddr: ctx.Conn.LocalAddr().String(), events.RemoteAddr: ctx.Conn.RemoteAddr().String(), }) h.Warnf("Port forwarding request denied: %v.", systemErrorMessage) return trace.AccessDenied(userErrorMessage) } return nil }
go
func (h *AuthHandlers) CheckPortForward(addr string, ctx *ServerContext) error { if ok := ctx.Identity.RoleSet.CanPortForward(); !ok { systemErrorMessage := fmt.Sprintf("port forwarding not allowed by role set: %v", ctx.Identity.RoleSet) userErrorMessage := "port forwarding not allowed" // emit port forward failure event h.AuditLog.EmitAuditEvent(events.PortForwardFailure, events.EventFields{ events.PortForwardAddr: addr, events.PortForwardSuccess: false, events.PortForwardErr: systemErrorMessage, events.EventLogin: ctx.Identity.Login, events.EventUser: ctx.Identity.TeleportUser, events.LocalAddr: ctx.Conn.LocalAddr().String(), events.RemoteAddr: ctx.Conn.RemoteAddr().String(), }) h.Warnf("Port forwarding request denied: %v.", systemErrorMessage) return trace.AccessDenied(userErrorMessage) } return nil }
[ "func", "(", "h", "*", "AuthHandlers", ")", "CheckPortForward", "(", "addr", "string", ",", "ctx", "*", "ServerContext", ")", "error", "{", "if", "ok", ":=", "ctx", ".", "Identity", ".", "RoleSet", ".", "CanPortForward", "(", ")", ";", "!", "ok", "{", "systemErrorMessage", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "ctx", ".", "Identity", ".", "RoleSet", ")", "\n", "userErrorMessage", ":=", "\"", "\"", "\n\n", "// emit port forward failure event", "h", ".", "AuditLog", ".", "EmitAuditEvent", "(", "events", ".", "PortForwardFailure", ",", "events", ".", "EventFields", "{", "events", ".", "PortForwardAddr", ":", "addr", ",", "events", ".", "PortForwardSuccess", ":", "false", ",", "events", ".", "PortForwardErr", ":", "systemErrorMessage", ",", "events", ".", "EventLogin", ":", "ctx", ".", "Identity", ".", "Login", ",", "events", ".", "EventUser", ":", "ctx", ".", "Identity", ".", "TeleportUser", ",", "events", ".", "LocalAddr", ":", "ctx", ".", "Conn", ".", "LocalAddr", "(", ")", ".", "String", "(", ")", ",", "events", ".", "RemoteAddr", ":", "ctx", ".", "Conn", ".", "RemoteAddr", "(", ")", ".", "String", "(", ")", ",", "}", ")", "\n", "h", ".", "Warnf", "(", "\"", "\"", ",", "systemErrorMessage", ")", "\n\n", "return", "trace", ".", "AccessDenied", "(", "userErrorMessage", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// CheckPortForward checks if port forwarding is allowed for the users RoleSet.
[ "CheckPortForward", "checks", "if", "port", "forwarding", "is", "allowed", "for", "the", "users", "RoleSet", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/authhandlers.go#L104-L125
train
gravitational/teleport
lib/srv/authhandlers.go
HostKeyAuth
func (h *AuthHandlers) HostKeyAuth(addr string, remote net.Addr, key ssh.PublicKey) error { fingerprint := fmt.Sprintf("%v %v", key.Type(), sshutils.Fingerprint(key)) // update entry to include a fingerprint of the key so admins can track down // the key causing problems h.Entry = log.WithFields(log.Fields{ trace.Component: h.Component, trace.ComponentFields: log.Fields{ "remote": remote.String(), "fingerprint": fingerprint, }, }) // Check if the given host key was signed by a Teleport certificate // authority (CA) or fallback to host key checking if it's allowed. certChecker := utils.CertChecker{ CertChecker: ssh.CertChecker{ IsHostAuthority: h.IsHostAuthority, HostKeyFallback: h.hostKeyCallback, }, } err := certChecker.CheckHostKey(addr, remote, key) if err != nil { return trace.Wrap(err) } return nil }
go
func (h *AuthHandlers) HostKeyAuth(addr string, remote net.Addr, key ssh.PublicKey) error { fingerprint := fmt.Sprintf("%v %v", key.Type(), sshutils.Fingerprint(key)) // update entry to include a fingerprint of the key so admins can track down // the key causing problems h.Entry = log.WithFields(log.Fields{ trace.Component: h.Component, trace.ComponentFields: log.Fields{ "remote": remote.String(), "fingerprint": fingerprint, }, }) // Check if the given host key was signed by a Teleport certificate // authority (CA) or fallback to host key checking if it's allowed. certChecker := utils.CertChecker{ CertChecker: ssh.CertChecker{ IsHostAuthority: h.IsHostAuthority, HostKeyFallback: h.hostKeyCallback, }, } err := certChecker.CheckHostKey(addr, remote, key) if err != nil { return trace.Wrap(err) } return nil }
[ "func", "(", "h", "*", "AuthHandlers", ")", "HostKeyAuth", "(", "addr", "string", ",", "remote", "net", ".", "Addr", ",", "key", "ssh", ".", "PublicKey", ")", "error", "{", "fingerprint", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "key", ".", "Type", "(", ")", ",", "sshutils", ".", "Fingerprint", "(", "key", ")", ")", "\n\n", "// update entry to include a fingerprint of the key so admins can track down", "// the key causing problems", "h", ".", "Entry", "=", "log", ".", "WithFields", "(", "log", ".", "Fields", "{", "trace", ".", "Component", ":", "h", ".", "Component", ",", "trace", ".", "ComponentFields", ":", "log", ".", "Fields", "{", "\"", "\"", ":", "remote", ".", "String", "(", ")", ",", "\"", "\"", ":", "fingerprint", ",", "}", ",", "}", ")", "\n\n", "// Check if the given host key was signed by a Teleport certificate", "// authority (CA) or fallback to host key checking if it's allowed.", "certChecker", ":=", "utils", ".", "CertChecker", "{", "CertChecker", ":", "ssh", ".", "CertChecker", "{", "IsHostAuthority", ":", "h", ".", "IsHostAuthority", ",", "HostKeyFallback", ":", "h", ".", "hostKeyCallback", ",", "}", ",", "}", "\n", "err", ":=", "certChecker", ".", "CheckHostKey", "(", "addr", ",", "remote", ",", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// HostKeyAuth implements host key verification and is called by the client // to validate the certificate presented by the target server. If the target // server presents a SSH certificate, we validate that it was Teleport that // generated the certificate. If the target server presents a public key, if // we are strictly checking keys, we reject the target server. If we are not // we take whatever.
[ "HostKeyAuth", "implements", "host", "key", "verification", "and", "is", "called", "by", "the", "client", "to", "validate", "the", "certificate", "presented", "by", "the", "target", "server", ".", "If", "the", "target", "server", "presents", "a", "SSH", "certificate", "we", "validate", "that", "it", "was", "Teleport", "that", "generated", "the", "certificate", ".", "If", "the", "target", "server", "presents", "a", "public", "key", "if", "we", "are", "strictly", "checking", "keys", "we", "reject", "the", "target", "server", ".", "If", "we", "are", "not", "we", "take", "whatever", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/authhandlers.go#L237-L263
train
gravitational/teleport
lib/srv/authhandlers.go
hostKeyCallback
func (h *AuthHandlers) hostKeyCallback(hostname string, remote net.Addr, key ssh.PublicKey) error { // If strict host key checking is enabled, reject host key fallback. clusterConfig, err := h.AccessPoint.GetClusterConfig() if err != nil { return trace.Wrap(err) } if clusterConfig.GetProxyChecksHostKeys() == services.HostKeyCheckYes { return trace.AccessDenied("remote host presented a public key, expected a host certificate") } // If strict host key checking is not enabled, log that Teleport trusted an // insecure key, but allow the request to go through. h.Warn("Insecure configuration! Strict host key checking disabled, allowing login without checking host key of type %v.", key.Type()) return nil }
go
func (h *AuthHandlers) hostKeyCallback(hostname string, remote net.Addr, key ssh.PublicKey) error { // If strict host key checking is enabled, reject host key fallback. clusterConfig, err := h.AccessPoint.GetClusterConfig() if err != nil { return trace.Wrap(err) } if clusterConfig.GetProxyChecksHostKeys() == services.HostKeyCheckYes { return trace.AccessDenied("remote host presented a public key, expected a host certificate") } // If strict host key checking is not enabled, log that Teleport trusted an // insecure key, but allow the request to go through. h.Warn("Insecure configuration! Strict host key checking disabled, allowing login without checking host key of type %v.", key.Type()) return nil }
[ "func", "(", "h", "*", "AuthHandlers", ")", "hostKeyCallback", "(", "hostname", "string", ",", "remote", "net", ".", "Addr", ",", "key", "ssh", ".", "PublicKey", ")", "error", "{", "// If strict host key checking is enabled, reject host key fallback.", "clusterConfig", ",", "err", ":=", "h", ".", "AccessPoint", ".", "GetClusterConfig", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "clusterConfig", ".", "GetProxyChecksHostKeys", "(", ")", "==", "services", ".", "HostKeyCheckYes", "{", "return", "trace", ".", "AccessDenied", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// If strict host key checking is not enabled, log that Teleport trusted an", "// insecure key, but allow the request to go through.", "h", ".", "Warn", "(", "\"", "\"", ",", "key", ".", "Type", "(", ")", ")", "\n", "return", "nil", "\n", "}" ]
// hostKeyCallback allows connections to hosts that present keys only if // strict host key checking is disabled.
[ "hostKeyCallback", "allows", "connections", "to", "hosts", "that", "present", "keys", "only", "if", "strict", "host", "key", "checking", "is", "disabled", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/authhandlers.go#L267-L281
train
gravitational/teleport
lib/srv/authhandlers.go
IsUserAuthority
func (h *AuthHandlers) IsUserAuthority(cert ssh.PublicKey) bool { if _, err := h.authorityForCert(services.UserCA, cert); err != nil { return false } return true }
go
func (h *AuthHandlers) IsUserAuthority(cert ssh.PublicKey) bool { if _, err := h.authorityForCert(services.UserCA, cert); err != nil { return false } return true }
[ "func", "(", "h", "*", "AuthHandlers", ")", "IsUserAuthority", "(", "cert", "ssh", ".", "PublicKey", ")", "bool", "{", "if", "_", ",", "err", ":=", "h", ".", "authorityForCert", "(", "services", ".", "UserCA", ",", "cert", ")", ";", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n\n", "return", "true", "\n", "}" ]
// IsUserAuthority is called during checking the client key, to see if the // key used to sign the certificate was a Teleport CA.
[ "IsUserAuthority", "is", "called", "during", "checking", "the", "client", "key", "to", "see", "if", "the", "key", "used", "to", "sign", "the", "certificate", "was", "a", "Teleport", "CA", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/authhandlers.go#L285-L291
train
gravitational/teleport
lib/srv/authhandlers.go
IsHostAuthority
func (h *AuthHandlers) IsHostAuthority(cert ssh.PublicKey, address string) bool { if _, err := h.authorityForCert(services.HostCA, cert); err != nil { h.Entry.Debugf("Unable to find SSH host CA: %v.", err) return false } return true }
go
func (h *AuthHandlers) IsHostAuthority(cert ssh.PublicKey, address string) bool { if _, err := h.authorityForCert(services.HostCA, cert); err != nil { h.Entry.Debugf("Unable to find SSH host CA: %v.", err) return false } return true }
[ "func", "(", "h", "*", "AuthHandlers", ")", "IsHostAuthority", "(", "cert", "ssh", ".", "PublicKey", ",", "address", "string", ")", "bool", "{", "if", "_", ",", "err", ":=", "h", ".", "authorityForCert", "(", "services", ".", "HostCA", ",", "cert", ")", ";", "err", "!=", "nil", "{", "h", ".", "Entry", ".", "Debugf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}" ]
// IsHostAuthority is called when checking the host certificate a server // presents. It make sure that the key used to sign the host certificate was a // Teleport CA.
[ "IsHostAuthority", "is", "called", "when", "checking", "the", "host", "certificate", "a", "server", "presents", ".", "It", "make", "sure", "that", "the", "key", "used", "to", "sign", "the", "host", "certificate", "was", "a", "Teleport", "CA", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/authhandlers.go#L296-L302
train
gravitational/teleport
lib/srv/authhandlers.go
fetchRoleSet
func (h *AuthHandlers) fetchRoleSet(cert *ssh.Certificate, ca services.CertAuthority, teleportUser string, clusterName string) (services.RoleSet, error) { // for local users, go and check their individual permissions var roles services.RoleSet if clusterName == ca.GetClusterName() { u, err := h.AccessPoint.GetUser(teleportUser) if err != nil { return nil, trace.Wrap(err) } // Pass along the traits so we get the substituted roles for this user. roles, err = services.FetchRoles(u.GetRoles(), h.AccessPoint, u.GetTraits()) if err != nil { return nil, trace.Wrap(err) } } else { certRoles, err := extractRolesFromCert(cert) if err != nil { return nil, trace.AccessDenied("failed to parse certificate roles") } roleNames, err := ca.CombinedMapping().Map(certRoles) if err != nil { return nil, trace.AccessDenied("failed to map roles") } // pass the principals on the certificate along as the login traits // to the remote cluster. traits := map[string][]string{ teleport.TraitLogins: cert.ValidPrincipals, } roles, err = services.FetchRoles(roleNames, h.AccessPoint, traits) if err != nil { return nil, trace.Wrap(err) } } return roles, nil }
go
func (h *AuthHandlers) fetchRoleSet(cert *ssh.Certificate, ca services.CertAuthority, teleportUser string, clusterName string) (services.RoleSet, error) { // for local users, go and check their individual permissions var roles services.RoleSet if clusterName == ca.GetClusterName() { u, err := h.AccessPoint.GetUser(teleportUser) if err != nil { return nil, trace.Wrap(err) } // Pass along the traits so we get the substituted roles for this user. roles, err = services.FetchRoles(u.GetRoles(), h.AccessPoint, u.GetTraits()) if err != nil { return nil, trace.Wrap(err) } } else { certRoles, err := extractRolesFromCert(cert) if err != nil { return nil, trace.AccessDenied("failed to parse certificate roles") } roleNames, err := ca.CombinedMapping().Map(certRoles) if err != nil { return nil, trace.AccessDenied("failed to map roles") } // pass the principals on the certificate along as the login traits // to the remote cluster. traits := map[string][]string{ teleport.TraitLogins: cert.ValidPrincipals, } roles, err = services.FetchRoles(roleNames, h.AccessPoint, traits) if err != nil { return nil, trace.Wrap(err) } } return roles, nil }
[ "func", "(", "h", "*", "AuthHandlers", ")", "fetchRoleSet", "(", "cert", "*", "ssh", ".", "Certificate", ",", "ca", "services", ".", "CertAuthority", ",", "teleportUser", "string", ",", "clusterName", "string", ")", "(", "services", ".", "RoleSet", ",", "error", ")", "{", "// for local users, go and check their individual permissions", "var", "roles", "services", ".", "RoleSet", "\n", "if", "clusterName", "==", "ca", ".", "GetClusterName", "(", ")", "{", "u", ",", "err", ":=", "h", ".", "AccessPoint", ".", "GetUser", "(", "teleportUser", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "// Pass along the traits so we get the substituted roles for this user.", "roles", ",", "err", "=", "services", ".", "FetchRoles", "(", "u", ".", "GetRoles", "(", ")", ",", "h", ".", "AccessPoint", ",", "u", ".", "GetTraits", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "}", "else", "{", "certRoles", ",", "err", ":=", "extractRolesFromCert", "(", "cert", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "AccessDenied", "(", "\"", "\"", ")", "\n", "}", "\n", "roleNames", ",", "err", ":=", "ca", ".", "CombinedMapping", "(", ")", ".", "Map", "(", "certRoles", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "AccessDenied", "(", "\"", "\"", ")", "\n", "}", "\n", "// pass the principals on the certificate along as the login traits", "// to the remote cluster.", "traits", ":=", "map", "[", "string", "]", "[", "]", "string", "{", "teleport", ".", "TraitLogins", ":", "cert", ".", "ValidPrincipals", ",", "}", "\n", "roles", ",", "err", "=", "services", ".", "FetchRoles", "(", "roleNames", ",", "h", ".", "AccessPoint", ",", "traits", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "}", "\n\n", "return", "roles", ",", "nil", "\n", "}" ]
// fetchRoleSet fetches the services.RoleSet assigned to a Teleport user.
[ "fetchRoleSet", "fetches", "the", "services", ".", "RoleSet", "assigned", "to", "a", "Teleport", "user", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/authhandlers.go#L347-L381
train
gravitational/teleport
lib/srv/authhandlers.go
authorityForCert
func (h *AuthHandlers) authorityForCert(caType services.CertAuthType, key ssh.PublicKey) (services.CertAuthority, error) { // get all certificate authorities for given type cas, err := h.AccessPoint.GetCertAuthorities(caType, false) if err != nil { h.Warnf("%v", trace.DebugReport(err)) return nil, trace.Wrap(err) } // find the one that signed our certificate var ca services.CertAuthority for i := range cas { checkers, err := cas[i].Checkers() if err != nil { h.Warnf("%v", err) return nil, trace.Wrap(err) } for _, checker := range checkers { // if we have a certificate, compare the certificate signing key against // the ca key. otherwise check the public key that was passed in. this is // due to the differences in how this function is called by the user and // host checkers. switch v := key.(type) { case *ssh.Certificate: if sshutils.KeysEqual(v.SignatureKey, checker) { ca = cas[i] break } default: if sshutils.KeysEqual(key, checker) { ca = cas[i] break } } } } // the certificate was signed by unknown authority if ca == nil { return nil, trace.AccessDenied("the certificate signed by untrusted CA") } return ca, nil }
go
func (h *AuthHandlers) authorityForCert(caType services.CertAuthType, key ssh.PublicKey) (services.CertAuthority, error) { // get all certificate authorities for given type cas, err := h.AccessPoint.GetCertAuthorities(caType, false) if err != nil { h.Warnf("%v", trace.DebugReport(err)) return nil, trace.Wrap(err) } // find the one that signed our certificate var ca services.CertAuthority for i := range cas { checkers, err := cas[i].Checkers() if err != nil { h.Warnf("%v", err) return nil, trace.Wrap(err) } for _, checker := range checkers { // if we have a certificate, compare the certificate signing key against // the ca key. otherwise check the public key that was passed in. this is // due to the differences in how this function is called by the user and // host checkers. switch v := key.(type) { case *ssh.Certificate: if sshutils.KeysEqual(v.SignatureKey, checker) { ca = cas[i] break } default: if sshutils.KeysEqual(key, checker) { ca = cas[i] break } } } } // the certificate was signed by unknown authority if ca == nil { return nil, trace.AccessDenied("the certificate signed by untrusted CA") } return ca, nil }
[ "func", "(", "h", "*", "AuthHandlers", ")", "authorityForCert", "(", "caType", "services", ".", "CertAuthType", ",", "key", "ssh", ".", "PublicKey", ")", "(", "services", ".", "CertAuthority", ",", "error", ")", "{", "// get all certificate authorities for given type", "cas", ",", "err", ":=", "h", ".", "AccessPoint", ".", "GetCertAuthorities", "(", "caType", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "h", ".", "Warnf", "(", "\"", "\"", ",", "trace", ".", "DebugReport", "(", "err", ")", ")", "\n", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "// find the one that signed our certificate", "var", "ca", "services", ".", "CertAuthority", "\n", "for", "i", ":=", "range", "cas", "{", "checkers", ",", "err", ":=", "cas", "[", "i", "]", ".", "Checkers", "(", ")", "\n", "if", "err", "!=", "nil", "{", "h", ".", "Warnf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "for", "_", ",", "checker", ":=", "range", "checkers", "{", "// if we have a certificate, compare the certificate signing key against", "// the ca key. otherwise check the public key that was passed in. this is", "// due to the differences in how this function is called by the user and", "// host checkers.", "switch", "v", ":=", "key", ".", "(", "type", ")", "{", "case", "*", "ssh", ".", "Certificate", ":", "if", "sshutils", ".", "KeysEqual", "(", "v", ".", "SignatureKey", ",", "checker", ")", "{", "ca", "=", "cas", "[", "i", "]", "\n", "break", "\n", "}", "\n", "default", ":", "if", "sshutils", ".", "KeysEqual", "(", "key", ",", "checker", ")", "{", "ca", "=", "cas", "[", "i", "]", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// the certificate was signed by unknown authority", "if", "ca", "==", "nil", "{", "return", "nil", ",", "trace", ".", "AccessDenied", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "ca", ",", "nil", "\n", "}" ]
// authorityForCert checks if the certificate was signed by a Teleport // Certificate Authority and returns it.
[ "authorityForCert", "checks", "if", "the", "certificate", "was", "signed", "by", "a", "Teleport", "Certificate", "Authority", "and", "returns", "it", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/authhandlers.go#L385-L427
train
gravitational/teleport
lib/srv/authhandlers.go
isProxy
func (h *AuthHandlers) isProxy() bool { if h.Component == teleport.ComponentProxy { return true } return false }
go
func (h *AuthHandlers) isProxy() bool { if h.Component == teleport.ComponentProxy { return true } return false }
[ "func", "(", "h", "*", "AuthHandlers", ")", "isProxy", "(", ")", "bool", "{", "if", "h", ".", "Component", "==", "teleport", ".", "ComponentProxy", "{", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// isProxy returns true if it's a regular SSH proxy.
[ "isProxy", "returns", "true", "if", "it", "s", "a", "regular", "SSH", "proxy", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/authhandlers.go#L430-L435
train
gravitational/teleport
lib/srv/authhandlers.go
extractRolesFromCert
func extractRolesFromCert(cert *ssh.Certificate) ([]string, error) { data, ok := cert.Extensions[teleport.CertExtensionTeleportRoles] if !ok { // it's ok to not have any roles in the metadata return nil, nil } return services.UnmarshalCertRoles(data) }
go
func extractRolesFromCert(cert *ssh.Certificate) ([]string, error) { data, ok := cert.Extensions[teleport.CertExtensionTeleportRoles] if !ok { // it's ok to not have any roles in the metadata return nil, nil } return services.UnmarshalCertRoles(data) }
[ "func", "extractRolesFromCert", "(", "cert", "*", "ssh", ".", "Certificate", ")", "(", "[", "]", "string", ",", "error", ")", "{", "data", ",", "ok", ":=", "cert", ".", "Extensions", "[", "teleport", ".", "CertExtensionTeleportRoles", "]", "\n", "if", "!", "ok", "{", "// it's ok to not have any roles in the metadata", "return", "nil", ",", "nil", "\n", "}", "\n", "return", "services", ".", "UnmarshalCertRoles", "(", "data", ")", "\n", "}" ]
// extractRolesFromCert extracts roles from certificate metadata extensions.
[ "extractRolesFromCert", "extracts", "roles", "from", "certificate", "metadata", "extensions", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/authhandlers.go#L446-L453
train
gravitational/teleport
lib/web/sessions.go
GetUserClient
func (c *SessionContext) GetUserClient(site reversetunnel.RemoteSite) (auth.ClientI, error) { // get the name of the current cluster clt, err := c.GetClient() if err != nil { return nil, trace.Wrap(err) } cn, err := clt.GetClusterName() if err != nil { return nil, trace.Wrap(err) } // if we're trying to access the local cluster, pass back the local client. if cn.GetClusterName() == site.GetName() { return clt, nil } // look to see if we already have a connection to this cluster remoteClt, ok := c.getRemoteClient(site.GetName()) if !ok { rClt, rConn, err := c.newRemoteClient(site) if err != nil { return nil, trace.Wrap(err) } // add a closer for the underlying connection if rConn != nil { c.AddClosers(rConn) } // we'll save the remote client in our session context so we don't have to // build a new connection next time. all remote clients will be closed when // the session context is closed. c.addRemoteClient(site.GetName(), rClt) return rClt, nil } return remoteClt, nil }
go
func (c *SessionContext) GetUserClient(site reversetunnel.RemoteSite) (auth.ClientI, error) { // get the name of the current cluster clt, err := c.GetClient() if err != nil { return nil, trace.Wrap(err) } cn, err := clt.GetClusterName() if err != nil { return nil, trace.Wrap(err) } // if we're trying to access the local cluster, pass back the local client. if cn.GetClusterName() == site.GetName() { return clt, nil } // look to see if we already have a connection to this cluster remoteClt, ok := c.getRemoteClient(site.GetName()) if !ok { rClt, rConn, err := c.newRemoteClient(site) if err != nil { return nil, trace.Wrap(err) } // add a closer for the underlying connection if rConn != nil { c.AddClosers(rConn) } // we'll save the remote client in our session context so we don't have to // build a new connection next time. all remote clients will be closed when // the session context is closed. c.addRemoteClient(site.GetName(), rClt) return rClt, nil } return remoteClt, nil }
[ "func", "(", "c", "*", "SessionContext", ")", "GetUserClient", "(", "site", "reversetunnel", ".", "RemoteSite", ")", "(", "auth", ".", "ClientI", ",", "error", ")", "{", "// get the name of the current cluster", "clt", ",", "err", ":=", "c", ".", "GetClient", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "cn", ",", "err", ":=", "clt", ".", "GetClusterName", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "// if we're trying to access the local cluster, pass back the local client.", "if", "cn", ".", "GetClusterName", "(", ")", "==", "site", ".", "GetName", "(", ")", "{", "return", "clt", ",", "nil", "\n", "}", "\n\n", "// look to see if we already have a connection to this cluster", "remoteClt", ",", "ok", ":=", "c", ".", "getRemoteClient", "(", "site", ".", "GetName", "(", ")", ")", "\n", "if", "!", "ok", "{", "rClt", ",", "rConn", ",", "err", ":=", "c", ".", "newRemoteClient", "(", "site", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "// add a closer for the underlying connection", "if", "rConn", "!=", "nil", "{", "c", ".", "AddClosers", "(", "rConn", ")", "\n", "}", "\n\n", "// we'll save the remote client in our session context so we don't have to", "// build a new connection next time. all remote clients will be closed when", "// the session context is closed.", "c", ".", "addRemoteClient", "(", "site", ".", "GetName", "(", ")", ",", "rClt", ")", "\n\n", "return", "rClt", ",", "nil", "\n", "}", "\n\n", "return", "remoteClt", ",", "nil", "\n", "}" ]
// GetUserClient will return an auth.ClientI with the role of the user at // the requested site. If the site is local a client with the users local role // is returned. If the site is remote a client with the users remote role is // returned.
[ "GetUserClient", "will", "return", "an", "auth", ".", "ClientI", "with", "the", "role", "of", "the", "user", "at", "the", "requested", "site", ".", "If", "the", "site", "is", "local", "a", "client", "with", "the", "users", "local", "role", "is", "returned", ".", "If", "the", "site", "is", "remote", "a", "client", "with", "the", "users", "remote", "role", "is", "returned", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/sessions.go#L116-L154
train
gravitational/teleport
lib/web/sessions.go
newRemoteClient
func (c *SessionContext) newRemoteClient(cluster reversetunnel.RemoteSite) (auth.ClientI, net.Conn, error) { clt, err := c.tryRemoteTLSClient(cluster) if err != nil { return nil, nil, trace.Wrap(err) } return clt, nil, nil }
go
func (c *SessionContext) newRemoteClient(cluster reversetunnel.RemoteSite) (auth.ClientI, net.Conn, error) { clt, err := c.tryRemoteTLSClient(cluster) if err != nil { return nil, nil, trace.Wrap(err) } return clt, nil, nil }
[ "func", "(", "c", "*", "SessionContext", ")", "newRemoteClient", "(", "cluster", "reversetunnel", ".", "RemoteSite", ")", "(", "auth", ".", "ClientI", ",", "net", ".", "Conn", ",", "error", ")", "{", "clt", ",", "err", ":=", "c", ".", "tryRemoteTLSClient", "(", "cluster", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "clt", ",", "nil", ",", "nil", "\n", "}" ]
// newRemoteClient returns a client to a remote cluster with the role of // the logged in user.
[ "newRemoteClient", "returns", "a", "client", "to", "a", "remote", "cluster", "with", "the", "role", "of", "the", "logged", "in", "user", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/sessions.go#L158-L164
train
gravitational/teleport
lib/web/sessions.go
clusterDialer
func clusterDialer(remoteCluster reversetunnel.RemoteSite) auth.DialContext { return func(in context.Context, network, _ string) (net.Conn, error) { return remoteCluster.DialAuthServer() } }
go
func clusterDialer(remoteCluster reversetunnel.RemoteSite) auth.DialContext { return func(in context.Context, network, _ string) (net.Conn, error) { return remoteCluster.DialAuthServer() } }
[ "func", "clusterDialer", "(", "remoteCluster", "reversetunnel", ".", "RemoteSite", ")", "auth", ".", "DialContext", "{", "return", "func", "(", "in", "context", ".", "Context", ",", "network", ",", "_", "string", ")", "(", "net", ".", "Conn", ",", "error", ")", "{", "return", "remoteCluster", ".", "DialAuthServer", "(", ")", "\n", "}", "\n", "}" ]
// clusterDialer returns DialContext function using cluster's dial function
[ "clusterDialer", "returns", "DialContext", "function", "using", "cluster", "s", "dial", "function" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/sessions.go#L167-L171
train
gravitational/teleport
lib/web/sessions.go
ClientTLSConfig
func (c *SessionContext) ClientTLSConfig(clusterName ...string) (*tls.Config, error) { var certPool *x509.CertPool if len(clusterName) == 0 { certAuthorities, err := c.parent.proxyClient.GetCertAuthorities(services.HostCA, false) if err != nil { return nil, trace.Wrap(err) } certPool, err = services.CertPoolFromCertAuthorities(certAuthorities) if err != nil { return nil, trace.Wrap(err) } } else { certAuthority, err := c.parent.proxyClient.GetCertAuthority(services.CertAuthID{ Type: services.HostCA, DomainName: clusterName[0], }, false) if err != nil { return nil, trace.Wrap(err) } certPool, err = services.CertPool(certAuthority) if err != nil { return nil, trace.Wrap(err) } } tlsConfig := utils.TLSConfig(c.parent.cipherSuites) tlsCert, err := tls.X509KeyPair(c.sess.GetTLSCert(), c.sess.GetPriv()) if err != nil { return nil, trace.Wrap(err, "failed to parse TLS cert and key") } tlsConfig.Certificates = []tls.Certificate{tlsCert} tlsConfig.RootCAs = certPool tlsConfig.ServerName = auth.EncodeClusterName(c.parent.clusterName) return tlsConfig, nil }
go
func (c *SessionContext) ClientTLSConfig(clusterName ...string) (*tls.Config, error) { var certPool *x509.CertPool if len(clusterName) == 0 { certAuthorities, err := c.parent.proxyClient.GetCertAuthorities(services.HostCA, false) if err != nil { return nil, trace.Wrap(err) } certPool, err = services.CertPoolFromCertAuthorities(certAuthorities) if err != nil { return nil, trace.Wrap(err) } } else { certAuthority, err := c.parent.proxyClient.GetCertAuthority(services.CertAuthID{ Type: services.HostCA, DomainName: clusterName[0], }, false) if err != nil { return nil, trace.Wrap(err) } certPool, err = services.CertPool(certAuthority) if err != nil { return nil, trace.Wrap(err) } } tlsConfig := utils.TLSConfig(c.parent.cipherSuites) tlsCert, err := tls.X509KeyPair(c.sess.GetTLSCert(), c.sess.GetPriv()) if err != nil { return nil, trace.Wrap(err, "failed to parse TLS cert and key") } tlsConfig.Certificates = []tls.Certificate{tlsCert} tlsConfig.RootCAs = certPool tlsConfig.ServerName = auth.EncodeClusterName(c.parent.clusterName) return tlsConfig, nil }
[ "func", "(", "c", "*", "SessionContext", ")", "ClientTLSConfig", "(", "clusterName", "...", "string", ")", "(", "*", "tls", ".", "Config", ",", "error", ")", "{", "var", "certPool", "*", "x509", ".", "CertPool", "\n", "if", "len", "(", "clusterName", ")", "==", "0", "{", "certAuthorities", ",", "err", ":=", "c", ".", "parent", ".", "proxyClient", ".", "GetCertAuthorities", "(", "services", ".", "HostCA", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "certPool", ",", "err", "=", "services", ".", "CertPoolFromCertAuthorities", "(", "certAuthorities", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "}", "else", "{", "certAuthority", ",", "err", ":=", "c", ".", "parent", ".", "proxyClient", ".", "GetCertAuthority", "(", "services", ".", "CertAuthID", "{", "Type", ":", "services", ".", "HostCA", ",", "DomainName", ":", "clusterName", "[", "0", "]", ",", "}", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "certPool", ",", "err", "=", "services", ".", "CertPool", "(", "certAuthority", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "}", "\n\n", "tlsConfig", ":=", "utils", ".", "TLSConfig", "(", "c", ".", "parent", ".", "cipherSuites", ")", "\n", "tlsCert", ",", "err", ":=", "tls", ".", "X509KeyPair", "(", "c", ".", "sess", ".", "GetTLSCert", "(", ")", ",", "c", ".", "sess", ".", "GetPriv", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "tlsConfig", ".", "Certificates", "=", "[", "]", "tls", ".", "Certificate", "{", "tlsCert", "}", "\n", "tlsConfig", ".", "RootCAs", "=", "certPool", "\n", "tlsConfig", ".", "ServerName", "=", "auth", ".", "EncodeClusterName", "(", "c", ".", "parent", ".", "clusterName", ")", "\n", "return", "tlsConfig", ",", "nil", "\n", "}" ]
// ClientTLSConfig returns client TLS authentication associated // with the web session context
[ "ClientTLSConfig", "returns", "client", "TLS", "authentication", "associated", "with", "the", "web", "session", "context" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/sessions.go#L189-L223
train
gravitational/teleport
lib/web/sessions.go
ExtendWebSession
func (c *SessionContext) ExtendWebSession() (services.WebSession, error) { sess, err := c.clt.ExtendWebSession(c.user, c.sess.GetName()) if err != nil { return nil, trace.Wrap(err) } return sess, nil }
go
func (c *SessionContext) ExtendWebSession() (services.WebSession, error) { sess, err := c.clt.ExtendWebSession(c.user, c.sess.GetName()) if err != nil { return nil, trace.Wrap(err) } return sess, nil }
[ "func", "(", "c", "*", "SessionContext", ")", "ExtendWebSession", "(", ")", "(", "services", ".", "WebSession", ",", "error", ")", "{", "sess", ",", "err", ":=", "c", ".", "clt", ".", "ExtendWebSession", "(", "c", ".", "user", ",", "c", ".", "sess", ".", "GetName", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "sess", ",", "nil", "\n", "}" ]
// ExtendWebSession creates a new web session for this user // based on the previous session
[ "ExtendWebSession", "creates", "a", "new", "web", "session", "for", "this", "user", "based", "on", "the", "previous", "session" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/sessions.go#L245-L251
train
gravitational/teleport
lib/web/sessions.go
GetAgent
func (c *SessionContext) GetAgent() (agent.Agent, *ssh.Certificate, error) { pub, _, _, _, err := ssh.ParseAuthorizedKey(c.sess.GetPub()) if err != nil { return nil, nil, trace.Wrap(err) } cert, ok := pub.(*ssh.Certificate) if !ok { return nil, nil, trace.BadParameter("expected certificate, got %T", pub) } if len(cert.ValidPrincipals) == 0 { return nil, nil, trace.BadParameter("expected at least valid principal in certificate") } privateKey, err := ssh.ParseRawPrivateKey(c.sess.GetPriv()) if err != nil { return nil, nil, trace.Wrap(err, "failed to parse SSH private key") } keyring := agent.NewKeyring() err = keyring.Add(agent.AddedKey{ PrivateKey: privateKey, Certificate: cert, }) if err != nil { return nil, nil, trace.Wrap(err) } return keyring, cert, nil }
go
func (c *SessionContext) GetAgent() (agent.Agent, *ssh.Certificate, error) { pub, _, _, _, err := ssh.ParseAuthorizedKey(c.sess.GetPub()) if err != nil { return nil, nil, trace.Wrap(err) } cert, ok := pub.(*ssh.Certificate) if !ok { return nil, nil, trace.BadParameter("expected certificate, got %T", pub) } if len(cert.ValidPrincipals) == 0 { return nil, nil, trace.BadParameter("expected at least valid principal in certificate") } privateKey, err := ssh.ParseRawPrivateKey(c.sess.GetPriv()) if err != nil { return nil, nil, trace.Wrap(err, "failed to parse SSH private key") } keyring := agent.NewKeyring() err = keyring.Add(agent.AddedKey{ PrivateKey: privateKey, Certificate: cert, }) if err != nil { return nil, nil, trace.Wrap(err) } return keyring, cert, nil }
[ "func", "(", "c", "*", "SessionContext", ")", "GetAgent", "(", ")", "(", "agent", ".", "Agent", ",", "*", "ssh", ".", "Certificate", ",", "error", ")", "{", "pub", ",", "_", ",", "_", ",", "_", ",", "err", ":=", "ssh", ".", "ParseAuthorizedKey", "(", "c", ".", "sess", ".", "GetPub", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "cert", ",", "ok", ":=", "pub", ".", "(", "*", "ssh", ".", "Certificate", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ",", "pub", ")", "\n", "}", "\n", "if", "len", "(", "cert", ".", "ValidPrincipals", ")", "==", "0", "{", "return", "nil", ",", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n", "privateKey", ",", "err", ":=", "ssh", ".", "ParseRawPrivateKey", "(", "c", ".", "sess", ".", "GetPriv", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "trace", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "keyring", ":=", "agent", ".", "NewKeyring", "(", ")", "\n", "err", "=", "keyring", ".", "Add", "(", "agent", ".", "AddedKey", "{", "PrivateKey", ":", "privateKey", ",", "Certificate", ":", "cert", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "keyring", ",", "cert", ",", "nil", "\n", "}" ]
// GetAgent returns agent that can be used to answer challenges // for the web to ssh connection as well as certificate
[ "GetAgent", "returns", "agent", "that", "can", "be", "used", "to", "answer", "challenges", "for", "the", "web", "to", "ssh", "connection", "as", "well", "as", "certificate" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/sessions.go#L255-L281
train
gravitational/teleport
lib/web/sessions.go
Close
func (c *SessionContext) Close() error { closers := c.TransferClosers() for _, closer := range closers { c.Debugf("Closing %v.", closer) closer.Close() } if c.clt != nil { return trace.Wrap(c.clt.Close()) } return nil }
go
func (c *SessionContext) Close() error { closers := c.TransferClosers() for _, closer := range closers { c.Debugf("Closing %v.", closer) closer.Close() } if c.clt != nil { return trace.Wrap(c.clt.Close()) } return nil }
[ "func", "(", "c", "*", "SessionContext", ")", "Close", "(", ")", "error", "{", "closers", ":=", "c", ".", "TransferClosers", "(", ")", "\n", "for", "_", ",", "closer", ":=", "range", "closers", "{", "c", ".", "Debugf", "(", "\"", "\"", ",", "closer", ")", "\n", "closer", ".", "Close", "(", ")", "\n", "}", "\n", "if", "c", ".", "clt", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "c", ".", "clt", ".", "Close", "(", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Close cleans up connections associated with requests
[ "Close", "cleans", "up", "connections", "associated", "with", "requests" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/sessions.go#L284-L294
train
gravitational/teleport
lib/web/sessions.go
newSessionCache
func newSessionCache(proxyClient auth.ClientI, servers []utils.NetAddr, cipherSuites []uint16) (*sessionCache, error) { clusterName, err := proxyClient.GetClusterName() if err != nil { return nil, trace.Wrap(err) } m, err := ttlmap.New(1024, ttlmap.CallOnExpire(closeContext)) if err != nil { return nil, trace.Wrap(err) } cache := &sessionCache{ clusterName: clusterName.GetClusterName(), proxyClient: proxyClient, contexts: m, authServers: servers, closer: utils.NewCloseBroadcaster(), cipherSuites: cipherSuites, } // periodically close expired and unused sessions go cache.expireSessions() return cache, nil }
go
func newSessionCache(proxyClient auth.ClientI, servers []utils.NetAddr, cipherSuites []uint16) (*sessionCache, error) { clusterName, err := proxyClient.GetClusterName() if err != nil { return nil, trace.Wrap(err) } m, err := ttlmap.New(1024, ttlmap.CallOnExpire(closeContext)) if err != nil { return nil, trace.Wrap(err) } cache := &sessionCache{ clusterName: clusterName.GetClusterName(), proxyClient: proxyClient, contexts: m, authServers: servers, closer: utils.NewCloseBroadcaster(), cipherSuites: cipherSuites, } // periodically close expired and unused sessions go cache.expireSessions() return cache, nil }
[ "func", "newSessionCache", "(", "proxyClient", "auth", ".", "ClientI", ",", "servers", "[", "]", "utils", ".", "NetAddr", ",", "cipherSuites", "[", "]", "uint16", ")", "(", "*", "sessionCache", ",", "error", ")", "{", "clusterName", ",", "err", ":=", "proxyClient", ".", "GetClusterName", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "m", ",", "err", ":=", "ttlmap", ".", "New", "(", "1024", ",", "ttlmap", ".", "CallOnExpire", "(", "closeContext", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "cache", ":=", "&", "sessionCache", "{", "clusterName", ":", "clusterName", ".", "GetClusterName", "(", ")", ",", "proxyClient", ":", "proxyClient", ",", "contexts", ":", "m", ",", "authServers", ":", "servers", ",", "closer", ":", "utils", ".", "NewCloseBroadcaster", "(", ")", ",", "cipherSuites", ":", "cipherSuites", ",", "}", "\n", "// periodically close expired and unused sessions", "go", "cache", ".", "expireSessions", "(", ")", "\n", "return", "cache", ",", "nil", "\n", "}" ]
// newSessionCache returns new instance of the session cache
[ "newSessionCache", "returns", "new", "instance", "of", "the", "session", "cache" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/sessions.go#L297-L317
train
gravitational/teleport
lib/web/sessions.go
closeContext
func closeContext(key string, val interface{}) { go func() { log.Infof("[WEB] closing context %v", key) ctx, ok := val.(*SessionContext) if !ok { log.Warningf("warning, not valid value type %T", val) return } if err := ctx.Close(); err != nil { log.Infof("failed to close context: %v", err) } }() }
go
func closeContext(key string, val interface{}) { go func() { log.Infof("[WEB] closing context %v", key) ctx, ok := val.(*SessionContext) if !ok { log.Warningf("warning, not valid value type %T", val) return } if err := ctx.Close(); err != nil { log.Infof("failed to close context: %v", err) } }() }
[ "func", "closeContext", "(", "key", "string", ",", "val", "interface", "{", "}", ")", "{", "go", "func", "(", ")", "{", "log", ".", "Infof", "(", "\"", "\"", ",", "key", ")", "\n", "ctx", ",", "ok", ":=", "val", ".", "(", "*", "SessionContext", ")", "\n", "if", "!", "ok", "{", "log", ".", "Warningf", "(", "\"", "\"", ",", "val", ")", "\n", "return", "\n", "}", "\n", "if", "err", ":=", "ctx", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "log", ".", "Infof", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "(", ")", "\n", "}" ]
// closeContext is called when session context expires from // cache and will clean up connections
[ "closeContext", "is", "called", "when", "session", "context", "expires", "from", "cache", "and", "will", "clean", "up", "connections" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/sessions.go#L341-L353
train
gravitational/teleport
lib/auth/github.go
populateGithubClaims
func populateGithubClaims(client githubAPIClientI) (*services.GithubClaims, error) { // find out the username user, err := client.getUser() if err != nil { return nil, trace.Wrap(err, "failed to query Github user info") } // build team memberships teams, err := client.getTeams() if err != nil { return nil, trace.Wrap(err, "failed to query Github user teams") } log.Debugf("Retrieved %v teams for GitHub user %v.", len(teams), user.Login) orgToTeams := make(map[string][]string) for _, team := range teams { orgToTeams[team.Org.Login] = append( orgToTeams[team.Org.Login], team.Slug) } if len(orgToTeams) == 0 { return nil, trace.AccessDenied( "list of user teams is empty, did you grant access?") } claims := &services.GithubClaims{ Username: user.Login, OrganizationToTeams: orgToTeams, } log.WithFields(logrus.Fields{trace.Component: "github"}).Debugf( "Claims: %#v.", claims) return claims, nil }
go
func populateGithubClaims(client githubAPIClientI) (*services.GithubClaims, error) { // find out the username user, err := client.getUser() if err != nil { return nil, trace.Wrap(err, "failed to query Github user info") } // build team memberships teams, err := client.getTeams() if err != nil { return nil, trace.Wrap(err, "failed to query Github user teams") } log.Debugf("Retrieved %v teams for GitHub user %v.", len(teams), user.Login) orgToTeams := make(map[string][]string) for _, team := range teams { orgToTeams[team.Org.Login] = append( orgToTeams[team.Org.Login], team.Slug) } if len(orgToTeams) == 0 { return nil, trace.AccessDenied( "list of user teams is empty, did you grant access?") } claims := &services.GithubClaims{ Username: user.Login, OrganizationToTeams: orgToTeams, } log.WithFields(logrus.Fields{trace.Component: "github"}).Debugf( "Claims: %#v.", claims) return claims, nil }
[ "func", "populateGithubClaims", "(", "client", "githubAPIClientI", ")", "(", "*", "services", ".", "GithubClaims", ",", "error", ")", "{", "// find out the username", "user", ",", "err", ":=", "client", ".", "getUser", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "// build team memberships", "teams", ",", "err", ":=", "client", ".", "getTeams", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "log", ".", "Debugf", "(", "\"", "\"", ",", "len", "(", "teams", ")", ",", "user", ".", "Login", ")", "\n\n", "orgToTeams", ":=", "make", "(", "map", "[", "string", "]", "[", "]", "string", ")", "\n", "for", "_", ",", "team", ":=", "range", "teams", "{", "orgToTeams", "[", "team", ".", "Org", ".", "Login", "]", "=", "append", "(", "orgToTeams", "[", "team", ".", "Org", ".", "Login", "]", ",", "team", ".", "Slug", ")", "\n", "}", "\n", "if", "len", "(", "orgToTeams", ")", "==", "0", "{", "return", "nil", ",", "trace", ".", "AccessDenied", "(", "\"", "\"", ")", "\n", "}", "\n", "claims", ":=", "&", "services", ".", "GithubClaims", "{", "Username", ":", "user", ".", "Login", ",", "OrganizationToTeams", ":", "orgToTeams", ",", "}", "\n", "log", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "trace", ".", "Component", ":", "\"", "\"", "}", ")", ".", "Debugf", "(", "\"", "\"", ",", "claims", ")", "\n", "return", "claims", ",", "nil", "\n", "}" ]
// populateGithubClaims retrieves information about user and its team // memberships by calling Github API using the access token
[ "populateGithubClaims", "retrieves", "information", "about", "user", "and", "its", "team", "memberships", "by", "calling", "Github", "API", "using", "the", "access", "token" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/github.go#L366-L395
train
gravitational/teleport
lib/auth/github.go
getUser
func (c *githubAPIClient) getUser() (*userResponse, error) { // Ignore pagination links, we should never get more than a single user here. bytes, _, err := c.get("/user") if err != nil { return nil, trace.Wrap(err) } var user userResponse err = json.Unmarshal(bytes, &user) if err != nil { return nil, trace.Wrap(err) } return &user, nil }
go
func (c *githubAPIClient) getUser() (*userResponse, error) { // Ignore pagination links, we should never get more than a single user here. bytes, _, err := c.get("/user") if err != nil { return nil, trace.Wrap(err) } var user userResponse err = json.Unmarshal(bytes, &user) if err != nil { return nil, trace.Wrap(err) } return &user, nil }
[ "func", "(", "c", "*", "githubAPIClient", ")", "getUser", "(", ")", "(", "*", "userResponse", ",", "error", ")", "{", "// Ignore pagination links, we should never get more than a single user here.", "bytes", ",", "_", ",", "err", ":=", "c", ".", "get", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "var", "user", "userResponse", "\n", "err", "=", "json", ".", "Unmarshal", "(", "bytes", ",", "&", "user", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "&", "user", ",", "nil", "\n", "}" ]
// getEmails retrieves a list of emails for authenticated user
[ "getEmails", "retrieves", "a", "list", "of", "emails", "for", "authenticated", "user" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/github.go#L450-L462
train
gravitational/teleport
lib/auth/github.go
getTeams
func (c *githubAPIClient) getTeams() ([]teamResponse, error) { var result []teamResponse bytes, nextPage, err := c.get("/user/teams") if err != nil { return nil, trace.Wrap(err) } // Extract the first page of results and append them to the full result set. var teams []teamResponse err = json.Unmarshal(bytes, &teams) if err != nil { return nil, trace.Wrap(err) } result = append(result, teams...) // If the response returned a next page link, continue following the next // page links until all teams have been retrieved. var count int for nextPage != "" { // To prevent this from looping forever, don't fetch more than a set number // of pages, print an error when it does happen, and return the results up // to that point. if count > MaxPages { warningMessage := "Truncating list of teams used to populate claims: " + "hit maximum number pages that can be fetched from GitHub." // Print warning to Teleport logs as well as the Audit Log. log.Warnf(warningMessage) c.authServer.EmitAuditEvent(events.UserSSOLoginFailure, events.EventFields{ events.LoginMethod: events.LoginMethodGithub, events.AuthAttemptMessage: warningMessage, }) return result, nil } u, err := url.Parse(nextPage) if err != nil { return nil, trace.Wrap(err) } bytes, nextPage, err = c.get(u.RequestURI()) if err != nil { return nil, trace.Wrap(err) } err = json.Unmarshal(bytes, &teams) if err != nil { return nil, trace.Wrap(err) } // Append this page of teams to full result set. result = append(result, teams...) count = count + 1 } return result, nil }
go
func (c *githubAPIClient) getTeams() ([]teamResponse, error) { var result []teamResponse bytes, nextPage, err := c.get("/user/teams") if err != nil { return nil, trace.Wrap(err) } // Extract the first page of results and append them to the full result set. var teams []teamResponse err = json.Unmarshal(bytes, &teams) if err != nil { return nil, trace.Wrap(err) } result = append(result, teams...) // If the response returned a next page link, continue following the next // page links until all teams have been retrieved. var count int for nextPage != "" { // To prevent this from looping forever, don't fetch more than a set number // of pages, print an error when it does happen, and return the results up // to that point. if count > MaxPages { warningMessage := "Truncating list of teams used to populate claims: " + "hit maximum number pages that can be fetched from GitHub." // Print warning to Teleport logs as well as the Audit Log. log.Warnf(warningMessage) c.authServer.EmitAuditEvent(events.UserSSOLoginFailure, events.EventFields{ events.LoginMethod: events.LoginMethodGithub, events.AuthAttemptMessage: warningMessage, }) return result, nil } u, err := url.Parse(nextPage) if err != nil { return nil, trace.Wrap(err) } bytes, nextPage, err = c.get(u.RequestURI()) if err != nil { return nil, trace.Wrap(err) } err = json.Unmarshal(bytes, &teams) if err != nil { return nil, trace.Wrap(err) } // Append this page of teams to full result set. result = append(result, teams...) count = count + 1 } return result, nil }
[ "func", "(", "c", "*", "githubAPIClient", ")", "getTeams", "(", ")", "(", "[", "]", "teamResponse", ",", "error", ")", "{", "var", "result", "[", "]", "teamResponse", "\n\n", "bytes", ",", "nextPage", ",", "err", ":=", "c", ".", "get", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "// Extract the first page of results and append them to the full result set.", "var", "teams", "[", "]", "teamResponse", "\n", "err", "=", "json", ".", "Unmarshal", "(", "bytes", ",", "&", "teams", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "result", "=", "append", "(", "result", ",", "teams", "...", ")", "\n\n", "// If the response returned a next page link, continue following the next", "// page links until all teams have been retrieved.", "var", "count", "int", "\n", "for", "nextPage", "!=", "\"", "\"", "{", "// To prevent this from looping forever, don't fetch more than a set number", "// of pages, print an error when it does happen, and return the results up", "// to that point.", "if", "count", ">", "MaxPages", "{", "warningMessage", ":=", "\"", "\"", "+", "\"", "\"", "\n\n", "// Print warning to Teleport logs as well as the Audit Log.", "log", ".", "Warnf", "(", "warningMessage", ")", "\n", "c", ".", "authServer", ".", "EmitAuditEvent", "(", "events", ".", "UserSSOLoginFailure", ",", "events", ".", "EventFields", "{", "events", ".", "LoginMethod", ":", "events", ".", "LoginMethodGithub", ",", "events", ".", "AuthAttemptMessage", ":", "warningMessage", ",", "}", ")", "\n\n", "return", "result", ",", "nil", "\n", "}", "\n\n", "u", ",", "err", ":=", "url", ".", "Parse", "(", "nextPage", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "bytes", ",", "nextPage", ",", "err", "=", "c", ".", "get", "(", "u", ".", "RequestURI", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "err", "=", "json", ".", "Unmarshal", "(", "bytes", ",", "&", "teams", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "// Append this page of teams to full result set.", "result", "=", "append", "(", "result", ",", "teams", "...", ")", "\n\n", "count", "=", "count", "+", "1", "\n", "}", "\n\n", "return", "result", ",", "nil", "\n", "}" ]
// getTeams retrieves a list of teams authenticated user belongs to.
[ "getTeams", "retrieves", "a", "list", "of", "teams", "authenticated", "user", "belongs", "to", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/github.go#L481-L540
train
gravitational/teleport
lib/auth/github.go
get
func (c *githubAPIClient) get(url string) ([]byte, string, error) { request, err := http.NewRequest("GET", fmt.Sprintf("%v%v", GithubAPIURL, url), nil) if err != nil { return nil, "", trace.Wrap(err) } request.Header.Set("Authorization", fmt.Sprintf("token %v", c.token)) response, err := http.DefaultClient.Do(request) if err != nil { return nil, "", trace.Wrap(err) } defer response.Body.Close() bytes, err := ioutil.ReadAll(response.Body) if err != nil { return nil, "", trace.Wrap(err) } if response.StatusCode != 200 { return nil, "", trace.AccessDenied("bad response: %v %v", response.StatusCode, string(bytes)) } // Parse web links header to extract any pagination links. This is used to // return the next link which can be used in a loop to pull back all data. wls := utils.ParseWebLinks(response) return bytes, wls.NextPage, nil }
go
func (c *githubAPIClient) get(url string) ([]byte, string, error) { request, err := http.NewRequest("GET", fmt.Sprintf("%v%v", GithubAPIURL, url), nil) if err != nil { return nil, "", trace.Wrap(err) } request.Header.Set("Authorization", fmt.Sprintf("token %v", c.token)) response, err := http.DefaultClient.Do(request) if err != nil { return nil, "", trace.Wrap(err) } defer response.Body.Close() bytes, err := ioutil.ReadAll(response.Body) if err != nil { return nil, "", trace.Wrap(err) } if response.StatusCode != 200 { return nil, "", trace.AccessDenied("bad response: %v %v", response.StatusCode, string(bytes)) } // Parse web links header to extract any pagination links. This is used to // return the next link which can be used in a loop to pull back all data. wls := utils.ParseWebLinks(response) return bytes, wls.NextPage, nil }
[ "func", "(", "c", "*", "githubAPIClient", ")", "get", "(", "url", "string", ")", "(", "[", "]", "byte", ",", "string", ",", "error", ")", "{", "request", ",", "err", ":=", "http", ".", "NewRequest", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "GithubAPIURL", ",", "url", ")", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "\"", "\"", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "request", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "c", ".", "token", ")", ")", "\n", "response", ",", "err", ":=", "http", ".", "DefaultClient", ".", "Do", "(", "request", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "\"", "\"", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "defer", "response", ".", "Body", ".", "Close", "(", ")", "\n", "bytes", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "response", ".", "Body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "\"", "\"", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "response", ".", "StatusCode", "!=", "200", "{", "return", "nil", ",", "\"", "\"", ",", "trace", ".", "AccessDenied", "(", "\"", "\"", ",", "response", ".", "StatusCode", ",", "string", "(", "bytes", ")", ")", "\n", "}", "\n\n", "// Parse web links header to extract any pagination links. This is used to", "// return the next link which can be used in a loop to pull back all data.", "wls", ":=", "utils", ".", "ParseWebLinks", "(", "response", ")", "\n\n", "return", "bytes", ",", "wls", ".", "NextPage", ",", "nil", "\n", "}" ]
// get makes a GET request to the provided URL using the client's token for auth
[ "get", "makes", "a", "GET", "request", "to", "the", "provided", "URL", "using", "the", "client", "s", "token", "for", "auth" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/github.go#L543-L568
train
gravitational/teleport
lib/srv/forward/sshserver.go
CheckDefaults
func (s *ServerConfig) CheckDefaults() error { if s.AuthClient == nil { return trace.BadParameter("auth client required") } if s.DataDir == "" { return trace.BadParameter("missing parameter DataDir") } if s.UserAgent == nil { return trace.BadParameter("user agent required to connect to remote host") } if s.TargetConn == nil { return trace.BadParameter("connection to target connection required") } if s.SrcAddr == nil { return trace.BadParameter("source address required to identify client") } if s.DstAddr == nil { return trace.BadParameter("destination address required to connect to remote host") } if s.HostCertificate == nil { return trace.BadParameter("host certificate required to act on behalf of remote host") } if s.Clock == nil { s.Clock = clockwork.NewRealClock() } return nil }
go
func (s *ServerConfig) CheckDefaults() error { if s.AuthClient == nil { return trace.BadParameter("auth client required") } if s.DataDir == "" { return trace.BadParameter("missing parameter DataDir") } if s.UserAgent == nil { return trace.BadParameter("user agent required to connect to remote host") } if s.TargetConn == nil { return trace.BadParameter("connection to target connection required") } if s.SrcAddr == nil { return trace.BadParameter("source address required to identify client") } if s.DstAddr == nil { return trace.BadParameter("destination address required to connect to remote host") } if s.HostCertificate == nil { return trace.BadParameter("host certificate required to act on behalf of remote host") } if s.Clock == nil { s.Clock = clockwork.NewRealClock() } return nil }
[ "func", "(", "s", "*", "ServerConfig", ")", "CheckDefaults", "(", ")", "error", "{", "if", "s", ".", "AuthClient", "==", "nil", "{", "return", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "s", ".", "DataDir", "==", "\"", "\"", "{", "return", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "s", ".", "UserAgent", "==", "nil", "{", "return", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "s", ".", "TargetConn", "==", "nil", "{", "return", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "s", ".", "SrcAddr", "==", "nil", "{", "return", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "s", ".", "DstAddr", "==", "nil", "{", "return", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "s", ".", "HostCertificate", "==", "nil", "{", "return", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "s", ".", "Clock", "==", "nil", "{", "s", ".", "Clock", "=", "clockwork", ".", "NewRealClock", "(", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// CheckDefaults makes sure all required parameters are passed in.
[ "CheckDefaults", "makes", "sure", "all", "required", "parameters", "are", "passed", "in", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/forward/sshserver.go#L162-L189
train
gravitational/teleport
lib/srv/forward/sshserver.go
New
func New(c ServerConfig) (*Server, error) { // Check and make sure we everything we need to build a forwarding node. err := c.CheckDefaults() if err != nil { return nil, trace.Wrap(err) } // Build a pipe connection to hook up the client and the server. we save both // here and will pass them along to the context when we create it so they // can be closed by the context. serverConn, clientConn := utils.DualPipeNetConn(c.SrcAddr, c.DstAddr) if err != nil { return nil, trace.Wrap(err) } s := &Server{ log: logrus.WithFields(logrus.Fields{ trace.Component: teleport.ComponentForwardingNode, trace.ComponentFields: map[string]string{ "src-addr": c.SrcAddr.String(), "dst-addr": c.DstAddr.String(), }, }), id: uuid.New(), targetConn: c.TargetConn, serverConn: utils.NewTrackingConn(serverConn), clientConn: clientConn, userAgent: c.UserAgent, hostCertificate: c.HostCertificate, authClient: c.AuthClient, auditLog: c.AuthClient, authService: c.AuthClient, sessionServer: c.AuthClient, dataDir: c.DataDir, clock: c.Clock, } // Set the ciphers, KEX, and MACs that the in-memory server will send to the // client in its SSH_MSG_KEXINIT. s.ciphers = c.Ciphers s.kexAlgorithms = c.KEXAlgorithms s.macAlgorithms = c.MACAlgorithms s.sessionRegistry, err = srv.NewSessionRegistry(s) if err != nil { return nil, trace.Wrap(err) } // Common auth handlers. s.authHandlers = &srv.AuthHandlers{ Entry: logrus.WithFields(logrus.Fields{ trace.Component: teleport.ComponentForwardingNode, trace.ComponentFields: logrus.Fields{}, }), Server: s, Component: teleport.ComponentForwardingNode, AuditLog: c.AuthClient, AccessPoint: c.AuthClient, } // Common term handlers. s.termHandlers = &srv.TermHandlers{ SessionRegistry: s.sessionRegistry, } // Create a close context that is used internally to signal when the server // is closing and for any blocking goroutines to unblock. s.closeContext, s.closeCancel = context.WithCancel(context.Background()) return s, nil }
go
func New(c ServerConfig) (*Server, error) { // Check and make sure we everything we need to build a forwarding node. err := c.CheckDefaults() if err != nil { return nil, trace.Wrap(err) } // Build a pipe connection to hook up the client and the server. we save both // here and will pass them along to the context when we create it so they // can be closed by the context. serverConn, clientConn := utils.DualPipeNetConn(c.SrcAddr, c.DstAddr) if err != nil { return nil, trace.Wrap(err) } s := &Server{ log: logrus.WithFields(logrus.Fields{ trace.Component: teleport.ComponentForwardingNode, trace.ComponentFields: map[string]string{ "src-addr": c.SrcAddr.String(), "dst-addr": c.DstAddr.String(), }, }), id: uuid.New(), targetConn: c.TargetConn, serverConn: utils.NewTrackingConn(serverConn), clientConn: clientConn, userAgent: c.UserAgent, hostCertificate: c.HostCertificate, authClient: c.AuthClient, auditLog: c.AuthClient, authService: c.AuthClient, sessionServer: c.AuthClient, dataDir: c.DataDir, clock: c.Clock, } // Set the ciphers, KEX, and MACs that the in-memory server will send to the // client in its SSH_MSG_KEXINIT. s.ciphers = c.Ciphers s.kexAlgorithms = c.KEXAlgorithms s.macAlgorithms = c.MACAlgorithms s.sessionRegistry, err = srv.NewSessionRegistry(s) if err != nil { return nil, trace.Wrap(err) } // Common auth handlers. s.authHandlers = &srv.AuthHandlers{ Entry: logrus.WithFields(logrus.Fields{ trace.Component: teleport.ComponentForwardingNode, trace.ComponentFields: logrus.Fields{}, }), Server: s, Component: teleport.ComponentForwardingNode, AuditLog: c.AuthClient, AccessPoint: c.AuthClient, } // Common term handlers. s.termHandlers = &srv.TermHandlers{ SessionRegistry: s.sessionRegistry, } // Create a close context that is used internally to signal when the server // is closing and for any blocking goroutines to unblock. s.closeContext, s.closeCancel = context.WithCancel(context.Background()) return s, nil }
[ "func", "New", "(", "c", "ServerConfig", ")", "(", "*", "Server", ",", "error", ")", "{", "// Check and make sure we everything we need to build a forwarding node.", "err", ":=", "c", ".", "CheckDefaults", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "// Build a pipe connection to hook up the client and the server. we save both", "// here and will pass them along to the context when we create it so they", "// can be closed by the context.", "serverConn", ",", "clientConn", ":=", "utils", ".", "DualPipeNetConn", "(", "c", ".", "SrcAddr", ",", "c", ".", "DstAddr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "s", ":=", "&", "Server", "{", "log", ":", "logrus", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "trace", ".", "Component", ":", "teleport", ".", "ComponentForwardingNode", ",", "trace", ".", "ComponentFields", ":", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "c", ".", "SrcAddr", ".", "String", "(", ")", ",", "\"", "\"", ":", "c", ".", "DstAddr", ".", "String", "(", ")", ",", "}", ",", "}", ")", ",", "id", ":", "uuid", ".", "New", "(", ")", ",", "targetConn", ":", "c", ".", "TargetConn", ",", "serverConn", ":", "utils", ".", "NewTrackingConn", "(", "serverConn", ")", ",", "clientConn", ":", "clientConn", ",", "userAgent", ":", "c", ".", "UserAgent", ",", "hostCertificate", ":", "c", ".", "HostCertificate", ",", "authClient", ":", "c", ".", "AuthClient", ",", "auditLog", ":", "c", ".", "AuthClient", ",", "authService", ":", "c", ".", "AuthClient", ",", "sessionServer", ":", "c", ".", "AuthClient", ",", "dataDir", ":", "c", ".", "DataDir", ",", "clock", ":", "c", ".", "Clock", ",", "}", "\n\n", "// Set the ciphers, KEX, and MACs that the in-memory server will send to the", "// client in its SSH_MSG_KEXINIT.", "s", ".", "ciphers", "=", "c", ".", "Ciphers", "\n", "s", ".", "kexAlgorithms", "=", "c", ".", "KEXAlgorithms", "\n", "s", ".", "macAlgorithms", "=", "c", ".", "MACAlgorithms", "\n\n", "s", ".", "sessionRegistry", ",", "err", "=", "srv", ".", "NewSessionRegistry", "(", "s", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "// Common auth handlers.", "s", ".", "authHandlers", "=", "&", "srv", ".", "AuthHandlers", "{", "Entry", ":", "logrus", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "trace", ".", "Component", ":", "teleport", ".", "ComponentForwardingNode", ",", "trace", ".", "ComponentFields", ":", "logrus", ".", "Fields", "{", "}", ",", "}", ")", ",", "Server", ":", "s", ",", "Component", ":", "teleport", ".", "ComponentForwardingNode", ",", "AuditLog", ":", "c", ".", "AuthClient", ",", "AccessPoint", ":", "c", ".", "AuthClient", ",", "}", "\n\n", "// Common term handlers.", "s", ".", "termHandlers", "=", "&", "srv", ".", "TermHandlers", "{", "SessionRegistry", ":", "s", ".", "sessionRegistry", ",", "}", "\n\n", "// Create a close context that is used internally to signal when the server", "// is closing and for any blocking goroutines to unblock.", "s", ".", "closeContext", ",", "s", ".", "closeCancel", "=", "context", ".", "WithCancel", "(", "context", ".", "Background", "(", ")", ")", "\n\n", "return", "s", ",", "nil", "\n", "}" ]
// New creates a new unstarted Server.
[ "New", "creates", "a", "new", "unstarted", "Server", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/forward/sshserver.go#L192-L262
train
gravitational/teleport
lib/srv/forward/sshserver.go
EmitAuditEvent
func (s *Server) EmitAuditEvent(event events.Event, fields events.EventFields) { auditLog := s.GetAuditLog() if auditLog != nil { if err := auditLog.EmitAuditEvent(event, fields); err != nil { s.log.Error(err) } } else { s.log.Warn("SSH server has no audit log") } }
go
func (s *Server) EmitAuditEvent(event events.Event, fields events.EventFields) { auditLog := s.GetAuditLog() if auditLog != nil { if err := auditLog.EmitAuditEvent(event, fields); err != nil { s.log.Error(err) } } else { s.log.Warn("SSH server has no audit log") } }
[ "func", "(", "s", "*", "Server", ")", "EmitAuditEvent", "(", "event", "events", ".", "Event", ",", "fields", "events", ".", "EventFields", ")", "{", "auditLog", ":=", "s", ".", "GetAuditLog", "(", ")", "\n", "if", "auditLog", "!=", "nil", "{", "if", "err", ":=", "auditLog", ".", "EmitAuditEvent", "(", "event", ",", "fields", ")", ";", "err", "!=", "nil", "{", "s", ".", "log", ".", "Error", "(", "err", ")", "\n", "}", "\n", "}", "else", "{", "s", ".", "log", ".", "Warn", "(", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// EmitAuditEvent sends an event to the Audit Log.
[ "EmitAuditEvent", "sends", "an", "event", "to", "the", "Audit", "Log", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/forward/sshserver.go#L291-L300
train
gravitational/teleport
lib/srv/forward/sshserver.go
Close
func (s *Server) Close() error { conns := []io.Closer{ s.sconn, s.clientConn, s.serverConn, s.targetConn, s.remoteClient, } var errs []error for _, c := range conns { if c == nil { continue } err := c.Close() if err != nil { errs = append(errs, err) } } // Signal to waiting goroutines that the server is closing (for example, // the keep alive loop). s.closeCancel() return trace.NewAggregate(errs...) }
go
func (s *Server) Close() error { conns := []io.Closer{ s.sconn, s.clientConn, s.serverConn, s.targetConn, s.remoteClient, } var errs []error for _, c := range conns { if c == nil { continue } err := c.Close() if err != nil { errs = append(errs, err) } } // Signal to waiting goroutines that the server is closing (for example, // the keep alive loop). s.closeCancel() return trace.NewAggregate(errs...) }
[ "func", "(", "s", "*", "Server", ")", "Close", "(", ")", "error", "{", "conns", ":=", "[", "]", "io", ".", "Closer", "{", "s", ".", "sconn", ",", "s", ".", "clientConn", ",", "s", ".", "serverConn", ",", "s", ".", "targetConn", ",", "s", ".", "remoteClient", ",", "}", "\n\n", "var", "errs", "[", "]", "error", "\n\n", "for", "_", ",", "c", ":=", "range", "conns", "{", "if", "c", "==", "nil", "{", "continue", "\n", "}", "\n\n", "err", ":=", "c", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "errs", "=", "append", "(", "errs", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "// Signal to waiting goroutines that the server is closing (for example,", "// the keep alive loop).", "s", ".", "closeCancel", "(", ")", "\n\n", "return", "trace", ".", "NewAggregate", "(", "errs", "...", ")", "\n", "}" ]
// Close will close all underlying connections that the forwarding server holds.
[ "Close", "will", "close", "all", "underlying", "connections", "that", "the", "forwarding", "server", "holds", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/forward/sshserver.go#L436-L463
train
gravitational/teleport
lib/service/cfg.go
ApplyToken
func (cfg *Config) ApplyToken(token string) bool { if token != "" { cfg.Token = token return true } return false }
go
func (cfg *Config) ApplyToken(token string) bool { if token != "" { cfg.Token = token return true } return false }
[ "func", "(", "cfg", "*", "Config", ")", "ApplyToken", "(", "token", "string", ")", "bool", "{", "if", "token", "!=", "\"", "\"", "{", "cfg", ".", "Token", "=", "token", "\n", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// ApplyToken assigns a given token to all internal services but only if token // is not an empty string. // // Returns 'true' if token was modified
[ "ApplyToken", "assigns", "a", "given", "token", "to", "all", "internal", "services", "but", "only", "if", "token", "is", "not", "an", "empty", "string", ".", "Returns", "true", "if", "token", "was", "modified" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/cfg.go#L177-L183
train
gravitational/teleport
lib/service/cfg.go
RoleConfig
func (cfg *Config) RoleConfig() RoleConfig { return RoleConfig{ DataDir: cfg.DataDir, HostUUID: cfg.HostUUID, HostName: cfg.Hostname, AuthServers: cfg.AuthServers, Auth: cfg.Auth, Console: cfg.Console, } }
go
func (cfg *Config) RoleConfig() RoleConfig { return RoleConfig{ DataDir: cfg.DataDir, HostUUID: cfg.HostUUID, HostName: cfg.Hostname, AuthServers: cfg.AuthServers, Auth: cfg.Auth, Console: cfg.Console, } }
[ "func", "(", "cfg", "*", "Config", ")", "RoleConfig", "(", ")", "RoleConfig", "{", "return", "RoleConfig", "{", "DataDir", ":", "cfg", ".", "DataDir", ",", "HostUUID", ":", "cfg", ".", "HostUUID", ",", "HostName", ":", "cfg", ".", "Hostname", ",", "AuthServers", ":", "cfg", ".", "AuthServers", ",", "Auth", ":", "cfg", ".", "Auth", ",", "Console", ":", "cfg", ".", "Console", ",", "}", "\n", "}" ]
// RoleConfig is a config for particular Teleport role
[ "RoleConfig", "is", "a", "config", "for", "particular", "Teleport", "role" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/cfg.go#L186-L195
train
gravitational/teleport
lib/service/cfg.go
GetRecentTTL
func (c *CachePolicy) GetRecentTTL() time.Duration { if c.RecentTTL == nil { return defaults.RecentCacheTTL } return *c.RecentTTL }
go
func (c *CachePolicy) GetRecentTTL() time.Duration { if c.RecentTTL == nil { return defaults.RecentCacheTTL } return *c.RecentTTL }
[ "func", "(", "c", "*", "CachePolicy", ")", "GetRecentTTL", "(", ")", "time", ".", "Duration", "{", "if", "c", ".", "RecentTTL", "==", "nil", "{", "return", "defaults", ".", "RecentCacheTTL", "\n", "}", "\n", "return", "*", "c", ".", "RecentTTL", "\n", "}" ]
// GetRecentTTL either returns TTL that was set, // or default recent TTL value
[ "GetRecentTTL", "either", "returns", "TTL", "that", "was", "set", "or", "default", "recent", "TTL", "value" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/cfg.go#L227-L232
train
gravitational/teleport
lib/service/cfg.go
String
func (c CachePolicy) String() string { if !c.Enabled { return "no cache policy" } recentCachePolicy := "" if c.GetRecentTTL() == 0 { recentCachePolicy = "will not cache frequently accessed items" } else { recentCachePolicy = fmt.Sprintf("will cache frequently accessed items for %v", c.GetRecentTTL()) } if c.NeverExpires { return fmt.Sprintf("cache that will not expire in case if connection to database is lost, %v", recentCachePolicy) } if c.TTL == 0 { return fmt.Sprintf("cache that will expire after connection to database is lost after %v, %v", defaults.CacheTTL, recentCachePolicy) } return fmt.Sprintf("cache that will expire after connection to database is lost after %v, %v", c.TTL, recentCachePolicy) }
go
func (c CachePolicy) String() string { if !c.Enabled { return "no cache policy" } recentCachePolicy := "" if c.GetRecentTTL() == 0 { recentCachePolicy = "will not cache frequently accessed items" } else { recentCachePolicy = fmt.Sprintf("will cache frequently accessed items for %v", c.GetRecentTTL()) } if c.NeverExpires { return fmt.Sprintf("cache that will not expire in case if connection to database is lost, %v", recentCachePolicy) } if c.TTL == 0 { return fmt.Sprintf("cache that will expire after connection to database is lost after %v, %v", defaults.CacheTTL, recentCachePolicy) } return fmt.Sprintf("cache that will expire after connection to database is lost after %v, %v", c.TTL, recentCachePolicy) }
[ "func", "(", "c", "CachePolicy", ")", "String", "(", ")", "string", "{", "if", "!", "c", ".", "Enabled", "{", "return", "\"", "\"", "\n", "}", "\n", "recentCachePolicy", ":=", "\"", "\"", "\n", "if", "c", ".", "GetRecentTTL", "(", ")", "==", "0", "{", "recentCachePolicy", "=", "\"", "\"", "\n", "}", "else", "{", "recentCachePolicy", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "c", ".", "GetRecentTTL", "(", ")", ")", "\n", "}", "\n", "if", "c", ".", "NeverExpires", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "recentCachePolicy", ")", "\n", "}", "\n", "if", "c", ".", "TTL", "==", "0", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "defaults", ".", "CacheTTL", ",", "recentCachePolicy", ")", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "c", ".", "TTL", ",", "recentCachePolicy", ")", "\n", "}" ]
// String returns human-friendly representation of the policy
[ "String", "returns", "human", "-", "friendly", "representation", "of", "the", "policy" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/cfg.go#L235-L252
train
gravitational/teleport
lib/service/cfg.go
ApplyDefaults
func ApplyDefaults(cfg *Config) { // Get defaults for Cipher, Kex algorithms, and MAC algorithms from // golang.org/x/crypto/ssh default config. var sc ssh.Config sc.SetDefaults() // Remove insecure and (borderline insecure) cryptographic primitives from // default configuration. These can still be added back in file configuration by // users, but not supported by default by Teleport. See #1856 for more // details. kex := utils.RemoveFromSlice(sc.KeyExchanges, defaults.DiffieHellmanGroup1SHA1, defaults.DiffieHellmanGroup14SHA1) macs := utils.RemoveFromSlice(sc.MACs, defaults.HMACSHA1, defaults.HMACSHA196) hostname, err := os.Hostname() if err != nil { hostname = "localhost" log.Errorf("Failed to determine hostname: %v.", err) } // global defaults cfg.Hostname = hostname cfg.DataDir = defaults.DataDir cfg.Console = os.Stdout cfg.CipherSuites = utils.DefaultCipherSuites() cfg.Ciphers = sc.Ciphers cfg.KEXAlgorithms = kex cfg.MACAlgorithms = macs // defaults for the auth service: cfg.Auth.Enabled = true cfg.Auth.SSHAddr = *defaults.AuthListenAddr() cfg.Auth.StorageConfig.Type = dir.GetName() cfg.Auth.StorageConfig.Params = backend.Params{defaults.BackendPath: filepath.Join(cfg.DataDir, defaults.BackendDir)} cfg.Auth.StaticTokens = services.DefaultStaticTokens() cfg.Auth.ClusterConfig = services.DefaultClusterConfig() defaults.ConfigureLimiter(&cfg.Auth.Limiter) // set new style default auth preferences ap := &services.AuthPreferenceV2{} ap.CheckAndSetDefaults() cfg.Auth.Preference = ap cfg.Auth.LicenseFile = filepath.Join(cfg.DataDir, defaults.LicenseFile) // defaults for the SSH proxy service: cfg.Proxy.Enabled = true cfg.Proxy.SSHAddr = *defaults.ProxyListenAddr() cfg.Proxy.WebAddr = *defaults.ProxyWebListenAddr() cfg.Proxy.ReverseTunnelListenAddr = *defaults.ReverseTunnellListenAddr() defaults.ConfigureLimiter(&cfg.Proxy.Limiter) // defaults for the Kubernetes proxy service cfg.Proxy.Kube.Enabled = false cfg.Proxy.Kube.ListenAddr = *defaults.KubeProxyListenAddr() // defaults for the SSH service: cfg.SSH.Enabled = true cfg.SSH.Addr = *defaults.SSHServerListenAddr() cfg.SSH.Shell = defaults.DefaultShell defaults.ConfigureLimiter(&cfg.SSH.Limiter) cfg.SSH.PAM = &pam.Config{Enabled: false} }
go
func ApplyDefaults(cfg *Config) { // Get defaults for Cipher, Kex algorithms, and MAC algorithms from // golang.org/x/crypto/ssh default config. var sc ssh.Config sc.SetDefaults() // Remove insecure and (borderline insecure) cryptographic primitives from // default configuration. These can still be added back in file configuration by // users, but not supported by default by Teleport. See #1856 for more // details. kex := utils.RemoveFromSlice(sc.KeyExchanges, defaults.DiffieHellmanGroup1SHA1, defaults.DiffieHellmanGroup14SHA1) macs := utils.RemoveFromSlice(sc.MACs, defaults.HMACSHA1, defaults.HMACSHA196) hostname, err := os.Hostname() if err != nil { hostname = "localhost" log.Errorf("Failed to determine hostname: %v.", err) } // global defaults cfg.Hostname = hostname cfg.DataDir = defaults.DataDir cfg.Console = os.Stdout cfg.CipherSuites = utils.DefaultCipherSuites() cfg.Ciphers = sc.Ciphers cfg.KEXAlgorithms = kex cfg.MACAlgorithms = macs // defaults for the auth service: cfg.Auth.Enabled = true cfg.Auth.SSHAddr = *defaults.AuthListenAddr() cfg.Auth.StorageConfig.Type = dir.GetName() cfg.Auth.StorageConfig.Params = backend.Params{defaults.BackendPath: filepath.Join(cfg.DataDir, defaults.BackendDir)} cfg.Auth.StaticTokens = services.DefaultStaticTokens() cfg.Auth.ClusterConfig = services.DefaultClusterConfig() defaults.ConfigureLimiter(&cfg.Auth.Limiter) // set new style default auth preferences ap := &services.AuthPreferenceV2{} ap.CheckAndSetDefaults() cfg.Auth.Preference = ap cfg.Auth.LicenseFile = filepath.Join(cfg.DataDir, defaults.LicenseFile) // defaults for the SSH proxy service: cfg.Proxy.Enabled = true cfg.Proxy.SSHAddr = *defaults.ProxyListenAddr() cfg.Proxy.WebAddr = *defaults.ProxyWebListenAddr() cfg.Proxy.ReverseTunnelListenAddr = *defaults.ReverseTunnellListenAddr() defaults.ConfigureLimiter(&cfg.Proxy.Limiter) // defaults for the Kubernetes proxy service cfg.Proxy.Kube.Enabled = false cfg.Proxy.Kube.ListenAddr = *defaults.KubeProxyListenAddr() // defaults for the SSH service: cfg.SSH.Enabled = true cfg.SSH.Addr = *defaults.SSHServerListenAddr() cfg.SSH.Shell = defaults.DefaultShell defaults.ConfigureLimiter(&cfg.SSH.Limiter) cfg.SSH.PAM = &pam.Config{Enabled: false} }
[ "func", "ApplyDefaults", "(", "cfg", "*", "Config", ")", "{", "// Get defaults for Cipher, Kex algorithms, and MAC algorithms from", "// golang.org/x/crypto/ssh default config.", "var", "sc", "ssh", ".", "Config", "\n", "sc", ".", "SetDefaults", "(", ")", "\n\n", "// Remove insecure and (borderline insecure) cryptographic primitives from", "// default configuration. These can still be added back in file configuration by", "// users, but not supported by default by Teleport. See #1856 for more", "// details.", "kex", ":=", "utils", ".", "RemoveFromSlice", "(", "sc", ".", "KeyExchanges", ",", "defaults", ".", "DiffieHellmanGroup1SHA1", ",", "defaults", ".", "DiffieHellmanGroup14SHA1", ")", "\n", "macs", ":=", "utils", ".", "RemoveFromSlice", "(", "sc", ".", "MACs", ",", "defaults", ".", "HMACSHA1", ",", "defaults", ".", "HMACSHA196", ")", "\n\n", "hostname", ",", "err", ":=", "os", ".", "Hostname", "(", ")", "\n", "if", "err", "!=", "nil", "{", "hostname", "=", "\"", "\"", "\n", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// global defaults", "cfg", ".", "Hostname", "=", "hostname", "\n", "cfg", ".", "DataDir", "=", "defaults", ".", "DataDir", "\n", "cfg", ".", "Console", "=", "os", ".", "Stdout", "\n", "cfg", ".", "CipherSuites", "=", "utils", ".", "DefaultCipherSuites", "(", ")", "\n", "cfg", ".", "Ciphers", "=", "sc", ".", "Ciphers", "\n", "cfg", ".", "KEXAlgorithms", "=", "kex", "\n", "cfg", ".", "MACAlgorithms", "=", "macs", "\n\n", "// defaults for the auth service:", "cfg", ".", "Auth", ".", "Enabled", "=", "true", "\n", "cfg", ".", "Auth", ".", "SSHAddr", "=", "*", "defaults", ".", "AuthListenAddr", "(", ")", "\n", "cfg", ".", "Auth", ".", "StorageConfig", ".", "Type", "=", "dir", ".", "GetName", "(", ")", "\n", "cfg", ".", "Auth", ".", "StorageConfig", ".", "Params", "=", "backend", ".", "Params", "{", "defaults", ".", "BackendPath", ":", "filepath", ".", "Join", "(", "cfg", ".", "DataDir", ",", "defaults", ".", "BackendDir", ")", "}", "\n", "cfg", ".", "Auth", ".", "StaticTokens", "=", "services", ".", "DefaultStaticTokens", "(", ")", "\n", "cfg", ".", "Auth", ".", "ClusterConfig", "=", "services", ".", "DefaultClusterConfig", "(", ")", "\n", "defaults", ".", "ConfigureLimiter", "(", "&", "cfg", ".", "Auth", ".", "Limiter", ")", "\n", "// set new style default auth preferences", "ap", ":=", "&", "services", ".", "AuthPreferenceV2", "{", "}", "\n", "ap", ".", "CheckAndSetDefaults", "(", ")", "\n", "cfg", ".", "Auth", ".", "Preference", "=", "ap", "\n", "cfg", ".", "Auth", ".", "LicenseFile", "=", "filepath", ".", "Join", "(", "cfg", ".", "DataDir", ",", "defaults", ".", "LicenseFile", ")", "\n\n", "// defaults for the SSH proxy service:", "cfg", ".", "Proxy", ".", "Enabled", "=", "true", "\n", "cfg", ".", "Proxy", ".", "SSHAddr", "=", "*", "defaults", ".", "ProxyListenAddr", "(", ")", "\n", "cfg", ".", "Proxy", ".", "WebAddr", "=", "*", "defaults", ".", "ProxyWebListenAddr", "(", ")", "\n", "cfg", ".", "Proxy", ".", "ReverseTunnelListenAddr", "=", "*", "defaults", ".", "ReverseTunnellListenAddr", "(", ")", "\n", "defaults", ".", "ConfigureLimiter", "(", "&", "cfg", ".", "Proxy", ".", "Limiter", ")", "\n\n", "// defaults for the Kubernetes proxy service", "cfg", ".", "Proxy", ".", "Kube", ".", "Enabled", "=", "false", "\n", "cfg", ".", "Proxy", ".", "Kube", ".", "ListenAddr", "=", "*", "defaults", ".", "KubeProxyListenAddr", "(", ")", "\n\n", "// defaults for the SSH service:", "cfg", ".", "SSH", ".", "Enabled", "=", "true", "\n", "cfg", ".", "SSH", ".", "Addr", "=", "*", "defaults", ".", "SSHServerListenAddr", "(", ")", "\n", "cfg", ".", "SSH", ".", "Shell", "=", "defaults", ".", "DefaultShell", "\n", "defaults", ".", "ConfigureLimiter", "(", "&", "cfg", ".", "SSH", ".", "Limiter", ")", "\n", "cfg", ".", "SSH", ".", "PAM", "=", "&", "pam", ".", "Config", "{", "Enabled", ":", "false", "}", "\n", "}" ]
// ApplyDefaults applies default values to the existing config structure
[ "ApplyDefaults", "applies", "default", "values", "to", "the", "existing", "config", "structure" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/cfg.go#L412-L475
train
gravitational/teleport
lib/srv/keepalive.go
StartKeepAliveLoop
func StartKeepAliveLoop(p KeepAliveParams) { var missedCount int64 log := logrus.WithFields(logrus.Fields{ trace.Component: teleport.ComponentKeepAlive, }) log.Debugf("Starting keep-alive loop with with interval %v and max count %v.", p.Interval, p.MaxCount) tickerCh := time.NewTicker(p.Interval) defer tickerCh.Stop() for { select { case <-tickerCh.C: var sentCount int // Send a keep alive message on all connections and make sure a response // was received on all. for _, conn := range p.Conns { ok := sendKeepAliveWithTimeout(conn, defaults.ReadHeadersTimeout, p.CloseContext) if ok { sentCount += 1 } } if sentCount == len(p.Conns) { missedCount = 0 continue } // If enough keep-alives are missed, the connection is dead, call cancel // and notify the server to disconnect and cleanup. missedCount = missedCount + 1 if missedCount > p.MaxCount { log.Infof("Missed %v keep-alive messages, closing connection.", missedCount) p.CloseCancel() return } // If an external caller closed the context (connection is done) then no // more need to wait around for keep-alives. case <-p.CloseContext.Done(): return } } }
go
func StartKeepAliveLoop(p KeepAliveParams) { var missedCount int64 log := logrus.WithFields(logrus.Fields{ trace.Component: teleport.ComponentKeepAlive, }) log.Debugf("Starting keep-alive loop with with interval %v and max count %v.", p.Interval, p.MaxCount) tickerCh := time.NewTicker(p.Interval) defer tickerCh.Stop() for { select { case <-tickerCh.C: var sentCount int // Send a keep alive message on all connections and make sure a response // was received on all. for _, conn := range p.Conns { ok := sendKeepAliveWithTimeout(conn, defaults.ReadHeadersTimeout, p.CloseContext) if ok { sentCount += 1 } } if sentCount == len(p.Conns) { missedCount = 0 continue } // If enough keep-alives are missed, the connection is dead, call cancel // and notify the server to disconnect and cleanup. missedCount = missedCount + 1 if missedCount > p.MaxCount { log.Infof("Missed %v keep-alive messages, closing connection.", missedCount) p.CloseCancel() return } // If an external caller closed the context (connection is done) then no // more need to wait around for keep-alives. case <-p.CloseContext.Done(): return } } }
[ "func", "StartKeepAliveLoop", "(", "p", "KeepAliveParams", ")", "{", "var", "missedCount", "int64", "\n\n", "log", ":=", "logrus", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "trace", ".", "Component", ":", "teleport", ".", "ComponentKeepAlive", ",", "}", ")", "\n", "log", ".", "Debugf", "(", "\"", "\"", ",", "p", ".", "Interval", ",", "p", ".", "MaxCount", ")", "\n\n", "tickerCh", ":=", "time", ".", "NewTicker", "(", "p", ".", "Interval", ")", "\n", "defer", "tickerCh", ".", "Stop", "(", ")", "\n\n", "for", "{", "select", "{", "case", "<-", "tickerCh", ".", "C", ":", "var", "sentCount", "int", "\n\n", "// Send a keep alive message on all connections and make sure a response", "// was received on all.", "for", "_", ",", "conn", ":=", "range", "p", ".", "Conns", "{", "ok", ":=", "sendKeepAliveWithTimeout", "(", "conn", ",", "defaults", ".", "ReadHeadersTimeout", ",", "p", ".", "CloseContext", ")", "\n", "if", "ok", "{", "sentCount", "+=", "1", "\n", "}", "\n", "}", "\n", "if", "sentCount", "==", "len", "(", "p", ".", "Conns", ")", "{", "missedCount", "=", "0", "\n", "continue", "\n", "}", "\n\n", "// If enough keep-alives are missed, the connection is dead, call cancel", "// and notify the server to disconnect and cleanup.", "missedCount", "=", "missedCount", "+", "1", "\n", "if", "missedCount", ">", "p", ".", "MaxCount", "{", "log", ".", "Infof", "(", "\"", "\"", ",", "missedCount", ")", "\n", "p", ".", "CloseCancel", "(", ")", "\n", "return", "\n", "}", "\n", "// If an external caller closed the context (connection is done) then no", "// more need to wait around for keep-alives.", "case", "<-", "p", ".", "CloseContext", ".", "Done", "(", ")", ":", "return", "\n", "}", "\n", "}", "\n", "}" ]
// StartKeepAliveLoop starts the keep-alive loop.
[ "StartKeepAliveLoop", "starts", "the", "keep", "-", "alive", "loop", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/keepalive.go#L59-L102
train
gravitational/teleport
lib/srv/keepalive.go
sendKeepAliveWithTimeout
func sendKeepAliveWithTimeout(conn RequestSender, timeout time.Duration, closeContext context.Context) bool { errorCh := make(chan error, 1) go func() { // SendRequest will unblock when connection or channel is closed. _, _, err := conn.SendRequest(teleport.KeepAliveReqType, true, nil) errorCh <- err }() select { case err := <-errorCh: if err != nil { return false } return true case <-time.After(timeout): return false case <-closeContext.Done(): return false } }
go
func sendKeepAliveWithTimeout(conn RequestSender, timeout time.Duration, closeContext context.Context) bool { errorCh := make(chan error, 1) go func() { // SendRequest will unblock when connection or channel is closed. _, _, err := conn.SendRequest(teleport.KeepAliveReqType, true, nil) errorCh <- err }() select { case err := <-errorCh: if err != nil { return false } return true case <-time.After(timeout): return false case <-closeContext.Done(): return false } }
[ "func", "sendKeepAliveWithTimeout", "(", "conn", "RequestSender", ",", "timeout", "time", ".", "Duration", ",", "closeContext", "context", ".", "Context", ")", "bool", "{", "errorCh", ":=", "make", "(", "chan", "error", ",", "1", ")", "\n\n", "go", "func", "(", ")", "{", "// SendRequest will unblock when connection or channel is closed.", "_", ",", "_", ",", "err", ":=", "conn", ".", "SendRequest", "(", "teleport", ".", "KeepAliveReqType", ",", "true", ",", "nil", ")", "\n", "errorCh", "<-", "err", "\n", "}", "(", ")", "\n\n", "select", "{", "case", "err", ":=", "<-", "errorCh", ":", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "return", "true", "\n", "case", "<-", "time", ".", "After", "(", "timeout", ")", ":", "return", "false", "\n", "case", "<-", "closeContext", ".", "Done", "(", ")", ":", "return", "false", "\n", "}", "\n", "}" ]
// sendKeepAliveWithTimeout sends a [email protected] message to the remote // client. A manual timeout is needed here because SendRequest will wait for a // response forever.
[ "sendKeepAliveWithTimeout", "sends", "a", "keepalive" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/keepalive.go#L107-L127
train
gravitational/teleport
lib/services/namespace.go
MarshalNamespace
func MarshalNamespace(resource Namespace, opts ...MarshalOption) ([]byte, error) { cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } if !cfg.PreserveResourceID { // avoid modifying the original object // to prevent unexpected data races copy := resource copy.SetResourceID(0) resource = copy } return utils.FastMarshal(resource) }
go
func MarshalNamespace(resource Namespace, opts ...MarshalOption) ([]byte, error) { cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } if !cfg.PreserveResourceID { // avoid modifying the original object // to prevent unexpected data races copy := resource copy.SetResourceID(0) resource = copy } return utils.FastMarshal(resource) }
[ "func", "MarshalNamespace", "(", "resource", "Namespace", ",", "opts", "...", "MarshalOption", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "cfg", ",", "err", ":=", "collectOptions", "(", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "!", "cfg", ".", "PreserveResourceID", "{", "// avoid modifying the original object", "// to prevent unexpected data races", "copy", ":=", "resource", "\n", "copy", ".", "SetResourceID", "(", "0", ")", "\n", "resource", "=", "copy", "\n", "}", "\n", "return", "utils", ".", "FastMarshal", "(", "resource", ")", "\n", "}" ]
// MarshalNamespace marshals namespace to JSON
[ "MarshalNamespace", "marshals", "namespace", "to", "JSON" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/namespace.go#L128-L141
train
gravitational/teleport
lib/services/namespace.go
UnmarshalNamespace
func UnmarshalNamespace(data []byte, opts ...MarshalOption) (*Namespace, error) { if len(data) == 0 { return nil, trace.BadParameter("missing namespace data") } cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } // always skip schema validation on namespaces unmarshal // the namespace is always created by teleport now var namespace Namespace if err := utils.FastUnmarshal(data, &namespace); err != nil { return nil, trace.BadParameter(err.Error()) } if err := namespace.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } if cfg.ID != 0 { namespace.Metadata.ID = cfg.ID } if !cfg.Expires.IsZero() { namespace.Metadata.Expires = &cfg.Expires } return &namespace, nil }
go
func UnmarshalNamespace(data []byte, opts ...MarshalOption) (*Namespace, error) { if len(data) == 0 { return nil, trace.BadParameter("missing namespace data") } cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } // always skip schema validation on namespaces unmarshal // the namespace is always created by teleport now var namespace Namespace if err := utils.FastUnmarshal(data, &namespace); err != nil { return nil, trace.BadParameter(err.Error()) } if err := namespace.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } if cfg.ID != 0 { namespace.Metadata.ID = cfg.ID } if !cfg.Expires.IsZero() { namespace.Metadata.Expires = &cfg.Expires } return &namespace, nil }
[ "func", "UnmarshalNamespace", "(", "data", "[", "]", "byte", ",", "opts", "...", "MarshalOption", ")", "(", "*", "Namespace", ",", "error", ")", "{", "if", "len", "(", "data", ")", "==", "0", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n\n", "cfg", ",", "err", ":=", "collectOptions", "(", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "// always skip schema validation on namespaces unmarshal", "// the namespace is always created by teleport now", "var", "namespace", "Namespace", "\n", "if", "err", ":=", "utils", ".", "FastUnmarshal", "(", "data", ",", "&", "namespace", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "if", "err", ":=", "namespace", ".", "CheckAndSetDefaults", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "if", "cfg", ".", "ID", "!=", "0", "{", "namespace", ".", "Metadata", ".", "ID", "=", "cfg", ".", "ID", "\n", "}", "\n", "if", "!", "cfg", ".", "Expires", ".", "IsZero", "(", ")", "{", "namespace", ".", "Metadata", ".", "Expires", "=", "&", "cfg", ".", "Expires", "\n", "}", "\n\n", "return", "&", "namespace", ",", "nil", "\n", "}" ]
// UnmarshalNamespace unmarshals role from JSON or YAML, // sets defaults and checks the schema
[ "UnmarshalNamespace", "unmarshals", "role", "from", "JSON", "or", "YAML", "sets", "defaults", "and", "checks", "the", "schema" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/namespace.go#L145-L174
train
gravitational/teleport
tool/tctl/common/top_command.go
Initialize
func (c *TopCommand) Initialize(app *kingpin.Application, config *service.Config) { c.config = config c.top = app.Command("top", "Report diagnostic information") c.diagURL = c.top.Arg("diag-addr", "Diagnostic HTTP URL").Default("http://127.0.0.1:3434").String() c.refreshPeriod = c.top.Arg("refresh", "Refresh period").Default("5s").Duration() }
go
func (c *TopCommand) Initialize(app *kingpin.Application, config *service.Config) { c.config = config c.top = app.Command("top", "Report diagnostic information") c.diagURL = c.top.Arg("diag-addr", "Diagnostic HTTP URL").Default("http://127.0.0.1:3434").String() c.refreshPeriod = c.top.Arg("refresh", "Refresh period").Default("5s").Duration() }
[ "func", "(", "c", "*", "TopCommand", ")", "Initialize", "(", "app", "*", "kingpin", ".", "Application", ",", "config", "*", "service", ".", "Config", ")", "{", "c", ".", "config", "=", "config", "\n", "c", ".", "top", "=", "app", ".", "Command", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "c", ".", "diagURL", "=", "c", ".", "top", ".", "Arg", "(", "\"", "\"", ",", "\"", "\"", ")", ".", "Default", "(", "\"", "\"", ")", ".", "String", "(", ")", "\n", "c", ".", "refreshPeriod", "=", "c", ".", "top", ".", "Arg", "(", "\"", "\"", ",", "\"", "\"", ")", ".", "Default", "(", "\"", "\"", ")", ".", "Duration", "(", ")", "\n", "}" ]
// Initialize allows TopCommand to plug itself into the CLI parser.
[ "Initialize", "allows", "TopCommand", "to", "plug", "itself", "into", "the", "CLI", "parser", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/top_command.go#L55-L60
train
gravitational/teleport
tool/tctl/common/top_command.go
Top
func (c *TopCommand) Top(client *roundtrip.Client) error { if err := ui.Init(); err != nil { return trace.Wrap(err) } defer ui.Close() ctx, cancel := context.WithCancel(context.TODO()) defer cancel() uiEvents := ui.PollEvents() ticker := time.NewTicker(*c.refreshPeriod) defer ticker.Stop() // fetch and render first time var prev *Report re, err := c.fetchAndGenerateReport(ctx, client, nil) if err != nil { return trace.Wrap(err) } lastTab := "" if err := c.render(ctx, *re, lastTab); err != nil { return trace.Wrap(err) } for { select { case e := <-uiEvents: switch e.ID { // event string/identifier case "q", "<C-c>": // press 'q' or 'C-c' to quit return nil } if e.ID == "1" || e.ID == "2" || e.ID == "3" { lastTab = e.ID } // render previously fetched data on the resize event if re != nil { if err := c.render(ctx, *re, lastTab); err != nil { return trace.Wrap(err) } } case <-ticker.C: // fetch data and re-render on ticker prev = re re, err = c.fetchAndGenerateReport(ctx, client, prev) if err != nil { return trace.Wrap(err) } if err := c.render(ctx, *re, lastTab); err != nil { return trace.Wrap(err) } } } }
go
func (c *TopCommand) Top(client *roundtrip.Client) error { if err := ui.Init(); err != nil { return trace.Wrap(err) } defer ui.Close() ctx, cancel := context.WithCancel(context.TODO()) defer cancel() uiEvents := ui.PollEvents() ticker := time.NewTicker(*c.refreshPeriod) defer ticker.Stop() // fetch and render first time var prev *Report re, err := c.fetchAndGenerateReport(ctx, client, nil) if err != nil { return trace.Wrap(err) } lastTab := "" if err := c.render(ctx, *re, lastTab); err != nil { return trace.Wrap(err) } for { select { case e := <-uiEvents: switch e.ID { // event string/identifier case "q", "<C-c>": // press 'q' or 'C-c' to quit return nil } if e.ID == "1" || e.ID == "2" || e.ID == "3" { lastTab = e.ID } // render previously fetched data on the resize event if re != nil { if err := c.render(ctx, *re, lastTab); err != nil { return trace.Wrap(err) } } case <-ticker.C: // fetch data and re-render on ticker prev = re re, err = c.fetchAndGenerateReport(ctx, client, prev) if err != nil { return trace.Wrap(err) } if err := c.render(ctx, *re, lastTab); err != nil { return trace.Wrap(err) } } } }
[ "func", "(", "c", "*", "TopCommand", ")", "Top", "(", "client", "*", "roundtrip", ".", "Client", ")", "error", "{", "if", "err", ":=", "ui", ".", "Init", "(", ")", ";", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "defer", "ui", ".", "Close", "(", ")", "\n\n", "ctx", ",", "cancel", ":=", "context", ".", "WithCancel", "(", "context", ".", "TODO", "(", ")", ")", "\n", "defer", "cancel", "(", ")", "\n\n", "uiEvents", ":=", "ui", ".", "PollEvents", "(", ")", "\n", "ticker", ":=", "time", ".", "NewTicker", "(", "*", "c", ".", "refreshPeriod", ")", "\n", "defer", "ticker", ".", "Stop", "(", ")", "\n\n", "// fetch and render first time", "var", "prev", "*", "Report", "\n", "re", ",", "err", ":=", "c", ".", "fetchAndGenerateReport", "(", "ctx", ",", "client", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "lastTab", ":=", "\"", "\"", "\n", "if", "err", ":=", "c", ".", "render", "(", "ctx", ",", "*", "re", ",", "lastTab", ")", ";", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "for", "{", "select", "{", "case", "e", ":=", "<-", "uiEvents", ":", "switch", "e", ".", "ID", "{", "// event string/identifier", "case", "\"", "\"", ",", "\"", "\"", ":", "// press 'q' or 'C-c' to quit", "return", "nil", "\n", "}", "\n", "if", "e", ".", "ID", "==", "\"", "\"", "||", "e", ".", "ID", "==", "\"", "\"", "||", "e", ".", "ID", "==", "\"", "\"", "{", "lastTab", "=", "e", ".", "ID", "\n", "}", "\n", "// render previously fetched data on the resize event", "if", "re", "!=", "nil", "{", "if", "err", ":=", "c", ".", "render", "(", "ctx", ",", "*", "re", ",", "lastTab", ")", ";", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "}", "\n", "case", "<-", "ticker", ".", "C", ":", "// fetch data and re-render on ticker", "prev", "=", "re", "\n", "re", ",", "err", "=", "c", ".", "fetchAndGenerateReport", "(", "ctx", ",", "client", ",", "prev", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "if", "err", ":=", "c", ".", "render", "(", "ctx", ",", "*", "re", ",", "lastTab", ")", ";", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// Top is called to execute "status" CLI command.
[ "Top", "is", "called", "to", "execute", "status", "CLI", "command", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/top_command.go#L82-L133
train
gravitational/teleport
tool/tctl/common/top_command.go
SortedTopRequests
func (b *BackendStats) SortedTopRequests() []Request { out := make([]Request, 0, len(b.TopRequests)) for _, req := range b.TopRequests { out = append(out, req) } sort.Slice(out, func(i, j int) bool { if out[i].GetFreq() == out[j].GetFreq() { return out[i].Count > out[j].Count } return out[i].GetFreq() > out[j].GetFreq() }) return out }
go
func (b *BackendStats) SortedTopRequests() []Request { out := make([]Request, 0, len(b.TopRequests)) for _, req := range b.TopRequests { out = append(out, req) } sort.Slice(out, func(i, j int) bool { if out[i].GetFreq() == out[j].GetFreq() { return out[i].Count > out[j].Count } return out[i].GetFreq() > out[j].GetFreq() }) return out }
[ "func", "(", "b", "*", "BackendStats", ")", "SortedTopRequests", "(", ")", "[", "]", "Request", "{", "out", ":=", "make", "(", "[", "]", "Request", ",", "0", ",", "len", "(", "b", ".", "TopRequests", ")", ")", "\n", "for", "_", ",", "req", ":=", "range", "b", ".", "TopRequests", "{", "out", "=", "append", "(", "out", ",", "req", ")", "\n", "}", "\n", "sort", ".", "Slice", "(", "out", ",", "func", "(", "i", ",", "j", "int", ")", "bool", "{", "if", "out", "[", "i", "]", ".", "GetFreq", "(", ")", "==", "out", "[", "j", "]", ".", "GetFreq", "(", ")", "{", "return", "out", "[", "i", "]", ".", "Count", ">", "out", "[", "j", "]", ".", "Count", "\n", "}", "\n", "return", "out", "[", "i", "]", ".", "GetFreq", "(", ")", ">", "out", "[", "j", "]", ".", "GetFreq", "(", ")", "\n", "}", ")", "\n", "return", "out", "\n", "}" ]
// SortedTopRequests returns top requests sorted either // by frequency if frequency is present, or by count otherwise
[ "SortedTopRequests", "returns", "top", "requests", "sorted", "either", "by", "frequency", "if", "frequency", "is", "present", "or", "by", "count", "otherwise" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/top_command.go#L393-L405
train
gravitational/teleport
tool/tctl/common/top_command.go
SetFreq
func (c *Counter) SetFreq(prevCount Counter, period time.Duration) { if period == 0 { return } freq := float64(c.Count-prevCount.Count) / float64(period/time.Second) c.Freq = &freq }
go
func (c *Counter) SetFreq(prevCount Counter, period time.Duration) { if period == 0 { return } freq := float64(c.Count-prevCount.Count) / float64(period/time.Second) c.Freq = &freq }
[ "func", "(", "c", "*", "Counter", ")", "SetFreq", "(", "prevCount", "Counter", ",", "period", "time", ".", "Duration", ")", "{", "if", "period", "==", "0", "{", "return", "\n", "}", "\n", "freq", ":=", "float64", "(", "c", ".", "Count", "-", "prevCount", ".", "Count", ")", "/", "float64", "(", "period", "/", "time", ".", "Second", ")", "\n", "c", ".", "Freq", "=", "&", "freq", "\n", "}" ]
// SetFreq sets counter frequency based on the previous value // and the time period
[ "SetFreq", "sets", "counter", "frequency", "based", "on", "the", "previous", "value", "and", "the", "time", "period" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/top_command.go#L487-L493
train
gravitational/teleport
tool/tctl/common/top_command.go
AsPercentiles
func (h Histogram) AsPercentiles() []Percentile { if h.Count == 0 { return nil } var percentiles []Percentile for _, bucket := range h.Buckets { if bucket.Count == 0 { continue } if bucket.Count == h.Count || math.IsInf(bucket.UpperBound, 0) { percentiles = append(percentiles, Percentile{ Percentile: 100, Value: time.Duration(bucket.UpperBound * float64(time.Second)), }) return percentiles } percentiles = append(percentiles, Percentile{ Percentile: 100 * (float64(bucket.Count) / float64(h.Count)), Value: time.Duration(bucket.UpperBound * float64(time.Second)), }) } return percentiles }
go
func (h Histogram) AsPercentiles() []Percentile { if h.Count == 0 { return nil } var percentiles []Percentile for _, bucket := range h.Buckets { if bucket.Count == 0 { continue } if bucket.Count == h.Count || math.IsInf(bucket.UpperBound, 0) { percentiles = append(percentiles, Percentile{ Percentile: 100, Value: time.Duration(bucket.UpperBound * float64(time.Second)), }) return percentiles } percentiles = append(percentiles, Percentile{ Percentile: 100 * (float64(bucket.Count) / float64(h.Count)), Value: time.Duration(bucket.UpperBound * float64(time.Second)), }) } return percentiles }
[ "func", "(", "h", "Histogram", ")", "AsPercentiles", "(", ")", "[", "]", "Percentile", "{", "if", "h", ".", "Count", "==", "0", "{", "return", "nil", "\n", "}", "\n", "var", "percentiles", "[", "]", "Percentile", "\n", "for", "_", ",", "bucket", ":=", "range", "h", ".", "Buckets", "{", "if", "bucket", ".", "Count", "==", "0", "{", "continue", "\n", "}", "\n", "if", "bucket", ".", "Count", "==", "h", ".", "Count", "||", "math", ".", "IsInf", "(", "bucket", ".", "UpperBound", ",", "0", ")", "{", "percentiles", "=", "append", "(", "percentiles", ",", "Percentile", "{", "Percentile", ":", "100", ",", "Value", ":", "time", ".", "Duration", "(", "bucket", ".", "UpperBound", "*", "float64", "(", "time", ".", "Second", ")", ")", ",", "}", ")", "\n", "return", "percentiles", "\n", "}", "\n", "percentiles", "=", "append", "(", "percentiles", ",", "Percentile", "{", "Percentile", ":", "100", "*", "(", "float64", "(", "bucket", ".", "Count", ")", "/", "float64", "(", "h", ".", "Count", ")", ")", ",", "Value", ":", "time", ".", "Duration", "(", "bucket", ".", "UpperBound", "*", "float64", "(", "time", ".", "Second", ")", ")", ",", "}", ")", "\n", "}", "\n", "return", "percentiles", "\n", "}" ]
// AsPercentiles interprets historgram as a bucket of percentiles // and returns calculated percentiles
[ "AsPercentiles", "interprets", "historgram", "as", "a", "bucket", "of", "percentiles", "and", "returns", "calculated", "percentiles" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/top_command.go#L521-L543
train
gravitational/teleport
lib/fixtures/fixtures.go
ExpectNotFound
func ExpectNotFound(c *check.C, err error) { c.Assert(trace.IsNotFound(err), check.Equals, true, check.Commentf("expected NotFound, got %T %v at %v", trace.Unwrap(err), err, string(debug.Stack()))) }
go
func ExpectNotFound(c *check.C, err error) { c.Assert(trace.IsNotFound(err), check.Equals, true, check.Commentf("expected NotFound, got %T %v at %v", trace.Unwrap(err), err, string(debug.Stack()))) }
[ "func", "ExpectNotFound", "(", "c", "*", "check", ".", "C", ",", "err", "error", ")", "{", "c", ".", "Assert", "(", "trace", ".", "IsNotFound", "(", "err", ")", ",", "check", ".", "Equals", ",", "true", ",", "check", ".", "Commentf", "(", "\"", "\"", ",", "trace", ".", "Unwrap", "(", "err", ")", ",", "err", ",", "string", "(", "debug", ".", "Stack", "(", ")", ")", ")", ")", "\n", "}" ]
// ExpectNotFound expects not found error
[ "ExpectNotFound", "expects", "not", "found", "error" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/fixtures/fixtures.go#L13-L15
train
gravitational/teleport
lib/fixtures/fixtures.go
ExpectBadParameter
func ExpectBadParameter(c *check.C, err error) { c.Assert(trace.IsBadParameter(err), check.Equals, true, check.Commentf("expected BadParameter, got %T %v at %v", trace.Unwrap(err), err, string(debug.Stack()))) }
go
func ExpectBadParameter(c *check.C, err error) { c.Assert(trace.IsBadParameter(err), check.Equals, true, check.Commentf("expected BadParameter, got %T %v at %v", trace.Unwrap(err), err, string(debug.Stack()))) }
[ "func", "ExpectBadParameter", "(", "c", "*", "check", ".", "C", ",", "err", "error", ")", "{", "c", ".", "Assert", "(", "trace", ".", "IsBadParameter", "(", "err", ")", ",", "check", ".", "Equals", ",", "true", ",", "check", ".", "Commentf", "(", "\"", "\"", ",", "trace", ".", "Unwrap", "(", "err", ")", ",", "err", ",", "string", "(", "debug", ".", "Stack", "(", ")", ")", ")", ")", "\n", "}" ]
// ExpectBadParameter expects bad parameter error
[ "ExpectBadParameter", "expects", "bad", "parameter", "error" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/fixtures/fixtures.go#L18-L20
train
gravitational/teleport
lib/fixtures/fixtures.go
ExpectCompareFailed
func ExpectCompareFailed(c *check.C, err error) { c.Assert(trace.IsCompareFailed(err), check.Equals, true, check.Commentf("expected CompareFailed, got %T %v at %v", trace.Unwrap(err), err, string(debug.Stack()))) }
go
func ExpectCompareFailed(c *check.C, err error) { c.Assert(trace.IsCompareFailed(err), check.Equals, true, check.Commentf("expected CompareFailed, got %T %v at %v", trace.Unwrap(err), err, string(debug.Stack()))) }
[ "func", "ExpectCompareFailed", "(", "c", "*", "check", ".", "C", ",", "err", "error", ")", "{", "c", ".", "Assert", "(", "trace", ".", "IsCompareFailed", "(", "err", ")", ",", "check", ".", "Equals", ",", "true", ",", "check", ".", "Commentf", "(", "\"", "\"", ",", "trace", ".", "Unwrap", "(", "err", ")", ",", "err", ",", "string", "(", "debug", ".", "Stack", "(", ")", ")", ")", ")", "\n", "}" ]
// ExpectCompareFailed expects compare failed error
[ "ExpectCompareFailed", "expects", "compare", "failed", "error" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/fixtures/fixtures.go#L23-L25
train
gravitational/teleport
lib/fixtures/fixtures.go
ExpectAccessDenied
func ExpectAccessDenied(c *check.C, err error) { c.Assert(trace.IsAccessDenied(err), check.Equals, true, check.Commentf("expected AccessDenied, got %T %v at %v", trace.Unwrap(err), err, string(debug.Stack()))) }
go
func ExpectAccessDenied(c *check.C, err error) { c.Assert(trace.IsAccessDenied(err), check.Equals, true, check.Commentf("expected AccessDenied, got %T %v at %v", trace.Unwrap(err), err, string(debug.Stack()))) }
[ "func", "ExpectAccessDenied", "(", "c", "*", "check", ".", "C", ",", "err", "error", ")", "{", "c", ".", "Assert", "(", "trace", ".", "IsAccessDenied", "(", "err", ")", ",", "check", ".", "Equals", ",", "true", ",", "check", ".", "Commentf", "(", "\"", "\"", ",", "trace", ".", "Unwrap", "(", "err", ")", ",", "err", ",", "string", "(", "debug", ".", "Stack", "(", ")", ")", ")", ")", "\n", "}" ]
// ExpectAccessDenied expects error to be access denied
[ "ExpectAccessDenied", "expects", "error", "to", "be", "access", "denied" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/fixtures/fixtures.go#L28-L30
train
gravitational/teleport
lib/fixtures/fixtures.go
ExpectAlreadyExists
func ExpectAlreadyExists(c *check.C, err error) { c.Assert(trace.IsAlreadyExists(err), check.Equals, true, check.Commentf("expected AlreadyExists, got %T %v at %v", trace.Unwrap(err), err, string(debug.Stack()))) }
go
func ExpectAlreadyExists(c *check.C, err error) { c.Assert(trace.IsAlreadyExists(err), check.Equals, true, check.Commentf("expected AlreadyExists, got %T %v at %v", trace.Unwrap(err), err, string(debug.Stack()))) }
[ "func", "ExpectAlreadyExists", "(", "c", "*", "check", ".", "C", ",", "err", "error", ")", "{", "c", ".", "Assert", "(", "trace", ".", "IsAlreadyExists", "(", "err", ")", ",", "check", ".", "Equals", ",", "true", ",", "check", ".", "Commentf", "(", "\"", "\"", ",", "trace", ".", "Unwrap", "(", "err", ")", ",", "err", ",", "string", "(", "debug", ".", "Stack", "(", ")", ")", ")", ")", "\n", "}" ]
// ExpectAlreadyExists expects already exists error
[ "ExpectAlreadyExists", "expects", "already", "exists", "error" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/fixtures/fixtures.go#L33-L35
train
gravitational/teleport
lib/fixtures/fixtures.go
ExpectConnectionProblem
func ExpectConnectionProblem(c *check.C, err error) { c.Assert(trace.IsConnectionProblem(err), check.Equals, true, check.Commentf("expected ConnectionProblem, got %T %v at %v", trace.Unwrap(err), err, string(debug.Stack()))) }
go
func ExpectConnectionProblem(c *check.C, err error) { c.Assert(trace.IsConnectionProblem(err), check.Equals, true, check.Commentf("expected ConnectionProblem, got %T %v at %v", trace.Unwrap(err), err, string(debug.Stack()))) }
[ "func", "ExpectConnectionProblem", "(", "c", "*", "check", ".", "C", ",", "err", "error", ")", "{", "c", ".", "Assert", "(", "trace", ".", "IsConnectionProblem", "(", "err", ")", ",", "check", ".", "Equals", ",", "true", ",", "check", ".", "Commentf", "(", "\"", "\"", ",", "trace", ".", "Unwrap", "(", "err", ")", ",", "err", ",", "string", "(", "debug", ".", "Stack", "(", ")", ")", ")", ")", "\n", "}" ]
// ExpectConnectionProblem expects connection problem error
[ "ExpectConnectionProblem", "expects", "connection", "problem", "error" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/fixtures/fixtures.go#L38-L40
train
gravitational/teleport
lib/fixtures/fixtures.go
DeepCompare
func DeepCompare(c *check.C, a, b interface{}) { d := &spew.ConfigState{Indent: " ", DisableMethods: true, DisablePointerMethods: true, DisablePointerAddresses: true} c.Assert(a, check.DeepEquals, b, check.Commentf("%v\nStack:\n%v\n", diff.Diff(d.Sdump(a), d.Sdump(b)), string(debug.Stack()))) }
go
func DeepCompare(c *check.C, a, b interface{}) { d := &spew.ConfigState{Indent: " ", DisableMethods: true, DisablePointerMethods: true, DisablePointerAddresses: true} c.Assert(a, check.DeepEquals, b, check.Commentf("%v\nStack:\n%v\n", diff.Diff(d.Sdump(a), d.Sdump(b)), string(debug.Stack()))) }
[ "func", "DeepCompare", "(", "c", "*", "check", ".", "C", ",", "a", ",", "b", "interface", "{", "}", ")", "{", "d", ":=", "&", "spew", ".", "ConfigState", "{", "Indent", ":", "\"", "\"", ",", "DisableMethods", ":", "true", ",", "DisablePointerMethods", ":", "true", ",", "DisablePointerAddresses", ":", "true", "}", "\n\n", "c", ".", "Assert", "(", "a", ",", "check", ".", "DeepEquals", ",", "b", ",", "check", ".", "Commentf", "(", "\"", "\\n", "\\n", "\\n", "\"", ",", "diff", ".", "Diff", "(", "d", ".", "Sdump", "(", "a", ")", ",", "d", ".", "Sdump", "(", "b", ")", ")", ",", "string", "(", "debug", ".", "Stack", "(", ")", ")", ")", ")", "\n", "}" ]
// DeepCompare uses gocheck DeepEquals but provides nice diff if things are not equal
[ "DeepCompare", "uses", "gocheck", "DeepEquals", "but", "provides", "nice", "diff", "if", "things", "are", "not", "equal" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/fixtures/fixtures.go#L43-L47
train
gravitational/teleport
lib/sshutils/req.go
Check
func (p *PTYReqParams) Check() error { if p.W > maxSize || p.W < minSize { return trace.BadParameter("bad width: %v", p.W) } if p.H > maxSize || p.H < minSize { return trace.BadParameter("bad height: %v", p.H) } return nil }
go
func (p *PTYReqParams) Check() error { if p.W > maxSize || p.W < minSize { return trace.BadParameter("bad width: %v", p.W) } if p.H > maxSize || p.H < minSize { return trace.BadParameter("bad height: %v", p.H) } return nil }
[ "func", "(", "p", "*", "PTYReqParams", ")", "Check", "(", ")", "error", "{", "if", "p", ".", "W", ">", "maxSize", "||", "p", ".", "W", "<", "minSize", "{", "return", "trace", ".", "BadParameter", "(", "\"", "\"", ",", "p", ".", "W", ")", "\n", "}", "\n", "if", "p", ".", "H", ">", "maxSize", "||", "p", ".", "H", "<", "minSize", "{", "return", "trace", ".", "BadParameter", "(", "\"", "\"", ",", "p", ".", "H", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Check validates PTY parameters.
[ "Check", "validates", "PTY", "parameters", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/req.go#L102-L111
train
gravitational/teleport
lib/sshutils/req.go
CheckAndSetDefaults
func (p *PTYReqParams) CheckAndSetDefaults() error { if p.W > maxSize || p.W < minSize { p.W = teleport.DefaultTerminalWidth } if p.H > maxSize || p.H < minSize { p.H = teleport.DefaultTerminalHeight } return nil }
go
func (p *PTYReqParams) CheckAndSetDefaults() error { if p.W > maxSize || p.W < minSize { p.W = teleport.DefaultTerminalWidth } if p.H > maxSize || p.H < minSize { p.H = teleport.DefaultTerminalHeight } return nil }
[ "func", "(", "p", "*", "PTYReqParams", ")", "CheckAndSetDefaults", "(", ")", "error", "{", "if", "p", ".", "W", ">", "maxSize", "||", "p", ".", "W", "<", "minSize", "{", "p", ".", "W", "=", "teleport", ".", "DefaultTerminalWidth", "\n", "}", "\n", "if", "p", ".", "H", ">", "maxSize", "||", "p", ".", "H", "<", "minSize", "{", "p", ".", "H", "=", "teleport", ".", "DefaultTerminalHeight", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// CheckAndSetDefaults validates PTY parameters and ensures parameters // are within default values.
[ "CheckAndSetDefaults", "validates", "PTY", "parameters", "and", "ensures", "parameters", "are", "within", "default", "values", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/req.go#L115-L124
train
gravitational/teleport
lib/kube/proxy/portforward.go
removeStreamPair
func (h *portForwardProxy) removeStreamPair(requestID string) { h.streamPairsLock.Lock() defer h.streamPairsLock.Unlock() delete(h.streamPairs, requestID) }
go
func (h *portForwardProxy) removeStreamPair(requestID string) { h.streamPairsLock.Lock() defer h.streamPairsLock.Unlock() delete(h.streamPairs, requestID) }
[ "func", "(", "h", "*", "portForwardProxy", ")", "removeStreamPair", "(", "requestID", "string", ")", "{", "h", ".", "streamPairsLock", ".", "Lock", "(", ")", "\n", "defer", "h", ".", "streamPairsLock", ".", "Unlock", "(", ")", "\n\n", "delete", "(", "h", ".", "streamPairs", ",", "requestID", ")", "\n", "}" ]
// removeStreamPair removes the stream pair identified by requestID from streamPairs.
[ "removeStreamPair", "removes", "the", "stream", "pair", "identified", "by", "requestID", "from", "streamPairs", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/portforward.go#L284-L289
train
gravitational/teleport
lib/kube/proxy/portforward.go
run
func (h *portForwardProxy) run() { h.Debugf("Waiting for port forward streams.") for { select { case <-h.context.Done(): h.Debugf("Context is closing, returning.") return case <-h.sourceConn.CloseChan(): h.Debugf("Upgraded connection closed.") return case stream := <-h.streamChan: requestID, err := h.requestID(stream) if err != nil { h.Warningf("Failed to parse request id: %v.", err) return } streamType := stream.Headers().Get(StreamType) h.Debugf("Received new stream %v of type %v.", requestID, streamType) p, created := h.getStreamPair(requestID) if created { go h.monitorStreamPair(p, time.After(h.streamCreationTimeout)) } if complete, err := p.add(stream); err != nil { msg := fmt.Sprintf("error processing stream for request %s: %v", requestID, err) p.printError(msg) } else if complete { go h.portForward(p) } } } }
go
func (h *portForwardProxy) run() { h.Debugf("Waiting for port forward streams.") for { select { case <-h.context.Done(): h.Debugf("Context is closing, returning.") return case <-h.sourceConn.CloseChan(): h.Debugf("Upgraded connection closed.") return case stream := <-h.streamChan: requestID, err := h.requestID(stream) if err != nil { h.Warningf("Failed to parse request id: %v.", err) return } streamType := stream.Headers().Get(StreamType) h.Debugf("Received new stream %v of type %v.", requestID, streamType) p, created := h.getStreamPair(requestID) if created { go h.monitorStreamPair(p, time.After(h.streamCreationTimeout)) } if complete, err := p.add(stream); err != nil { msg := fmt.Sprintf("error processing stream for request %s: %v", requestID, err) p.printError(msg) } else if complete { go h.portForward(p) } } } }
[ "func", "(", "h", "*", "portForwardProxy", ")", "run", "(", ")", "{", "h", ".", "Debugf", "(", "\"", "\"", ")", "\n", "for", "{", "select", "{", "case", "<-", "h", ".", "context", ".", "Done", "(", ")", ":", "h", ".", "Debugf", "(", "\"", "\"", ")", "\n", "return", "\n", "case", "<-", "h", ".", "sourceConn", ".", "CloseChan", "(", ")", ":", "h", ".", "Debugf", "(", "\"", "\"", ")", "\n", "return", "\n", "case", "stream", ":=", "<-", "h", ".", "streamChan", ":", "requestID", ",", "err", ":=", "h", ".", "requestID", "(", "stream", ")", "\n", "if", "err", "!=", "nil", "{", "h", ".", "Warningf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "streamType", ":=", "stream", ".", "Headers", "(", ")", ".", "Get", "(", "StreamType", ")", "\n", "h", ".", "Debugf", "(", "\"", "\"", ",", "requestID", ",", "streamType", ")", "\n\n", "p", ",", "created", ":=", "h", ".", "getStreamPair", "(", "requestID", ")", "\n", "if", "created", "{", "go", "h", ".", "monitorStreamPair", "(", "p", ",", "time", ".", "After", "(", "h", ".", "streamCreationTimeout", ")", ")", "\n", "}", "\n", "if", "complete", ",", "err", ":=", "p", ".", "add", "(", "stream", ")", ";", "err", "!=", "nil", "{", "msg", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "requestID", ",", "err", ")", "\n", "p", ".", "printError", "(", "msg", ")", "\n", "}", "else", "if", "complete", "{", "go", "h", ".", "portForward", "(", "p", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// run is the main loop for the portForwardProxy. It processes new // streams, invoking portForward for each complete stream pair. The loop exits // when the httpstream.Connection is closed.
[ "run", "is", "the", "main", "loop", "for", "the", "portForwardProxy", ".", "It", "processes", "new", "streams", "invoking", "portForward", "for", "each", "complete", "stream", "pair", ".", "The", "loop", "exits", "when", "the", "httpstream", ".", "Connection", "is", "closed", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/portforward.go#L303-L334
train
gravitational/teleport
lib/kube/proxy/portforward.go
portForward
func (h *portForwardProxy) portForward(p *httpStreamPair) { defer p.dataStream.Close() defer p.errorStream.Close() portString := p.dataStream.Headers().Get(PortHeader) port, _ := strconv.ParseInt(portString, 10, 32) h.Debugf("Forwrarding port %v -> %v.", p.requestID, portString) err := h.forwardStreamPair(p, port) h.Debugf("Completed forwrarding port %v -> %v.", p.requestID, portString) if err != nil { msg := fmt.Errorf("error forwarding port %d to pod %s: %v", port, h.podName, err) fmt.Fprint(p.errorStream, msg.Error()) } }
go
func (h *portForwardProxy) portForward(p *httpStreamPair) { defer p.dataStream.Close() defer p.errorStream.Close() portString := p.dataStream.Headers().Get(PortHeader) port, _ := strconv.ParseInt(portString, 10, 32) h.Debugf("Forwrarding port %v -> %v.", p.requestID, portString) err := h.forwardStreamPair(p, port) h.Debugf("Completed forwrarding port %v -> %v.", p.requestID, portString) if err != nil { msg := fmt.Errorf("error forwarding port %d to pod %s: %v", port, h.podName, err) fmt.Fprint(p.errorStream, msg.Error()) } }
[ "func", "(", "h", "*", "portForwardProxy", ")", "portForward", "(", "p", "*", "httpStreamPair", ")", "{", "defer", "p", ".", "dataStream", ".", "Close", "(", ")", "\n", "defer", "p", ".", "errorStream", ".", "Close", "(", ")", "\n\n", "portString", ":=", "p", ".", "dataStream", ".", "Headers", "(", ")", ".", "Get", "(", "PortHeader", ")", "\n", "port", ",", "_", ":=", "strconv", ".", "ParseInt", "(", "portString", ",", "10", ",", "32", ")", "\n\n", "h", ".", "Debugf", "(", "\"", "\"", ",", "p", ".", "requestID", ",", "portString", ")", "\n", "err", ":=", "h", ".", "forwardStreamPair", "(", "p", ",", "port", ")", "\n", "h", ".", "Debugf", "(", "\"", "\"", ",", "p", ".", "requestID", ",", "portString", ")", "\n\n", "if", "err", "!=", "nil", "{", "msg", ":=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "port", ",", "h", ".", "podName", ",", "err", ")", "\n", "fmt", ".", "Fprint", "(", "p", ".", "errorStream", ",", "msg", ".", "Error", "(", ")", ")", "\n", "}", "\n", "}" ]
// portForward invokes the portForwardProxy's forwarder.PortForward // function for the given stream pair.
[ "portForward", "invokes", "the", "portForwardProxy", "s", "forwarder", ".", "PortForward", "function", "for", "the", "given", "stream", "pair", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/portforward.go#L338-L353
train
gravitational/teleport
lib/kube/proxy/portforward.go
add
func (p *httpStreamPair) add(stream httpstream.Stream) (bool, error) { p.lock.Lock() defer p.lock.Unlock() switch stream.Headers().Get(StreamType) { case StreamTypeError: if p.errorStream != nil { return false, trace.BadParameter("error stream already assigned") } p.errorStream = stream case StreamTypeData: if p.dataStream != nil { return false, trace.BadParameter("data stream already assigned") } p.dataStream = stream } complete := p.errorStream != nil && p.dataStream != nil if complete { close(p.complete) } return complete, nil }
go
func (p *httpStreamPair) add(stream httpstream.Stream) (bool, error) { p.lock.Lock() defer p.lock.Unlock() switch stream.Headers().Get(StreamType) { case StreamTypeError: if p.errorStream != nil { return false, trace.BadParameter("error stream already assigned") } p.errorStream = stream case StreamTypeData: if p.dataStream != nil { return false, trace.BadParameter("data stream already assigned") } p.dataStream = stream } complete := p.errorStream != nil && p.dataStream != nil if complete { close(p.complete) } return complete, nil }
[ "func", "(", "p", "*", "httpStreamPair", ")", "add", "(", "stream", "httpstream", ".", "Stream", ")", "(", "bool", ",", "error", ")", "{", "p", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "lock", ".", "Unlock", "(", ")", "\n\n", "switch", "stream", ".", "Headers", "(", ")", ".", "Get", "(", "StreamType", ")", "{", "case", "StreamTypeError", ":", "if", "p", ".", "errorStream", "!=", "nil", "{", "return", "false", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n", "p", ".", "errorStream", "=", "stream", "\n", "case", "StreamTypeData", ":", "if", "p", ".", "dataStream", "!=", "nil", "{", "return", "false", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n", "p", ".", "dataStream", "=", "stream", "\n", "}", "\n\n", "complete", ":=", "p", ".", "errorStream", "!=", "nil", "&&", "p", ".", "dataStream", "!=", "nil", "\n", "if", "complete", "{", "close", "(", "p", ".", "complete", ")", "\n", "}", "\n", "return", "complete", ",", "nil", "\n", "}" ]
// add adds the stream to the httpStreamPair. If the pair already // contains a stream for the new stream's type, an error is returned. add // returns true if both the data and error streams for this pair have been // received.
[ "add", "adds", "the", "stream", "to", "the", "httpStreamPair", ".", "If", "the", "pair", "already", "contains", "a", "stream", "for", "the", "new", "stream", "s", "type", "an", "error", "is", "returned", ".", "add", "returns", "true", "if", "both", "the", "data", "and", "error", "streams", "for", "this", "pair", "have", "been", "received", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/portforward.go#L377-L399
train
gravitational/teleport
lib/utils/replace.go
SliceMatchesRegex
func SliceMatchesRegex(input string, expressions []string) (bool, error) { for _, expression := range expressions { if !strings.HasPrefix(expression, "^") || !strings.HasSuffix(expression, "$") { // replace glob-style wildcards with regexp wildcards // for plain strings, and quote all characters that could // be interpreted in regular expression expression = "^" + GlobToRegexp(expression) + "$" } expr, err := regexp.Compile(expression) if err != nil { return false, trace.BadParameter(err.Error()) } // Since the expression is always surrounded by ^ and $ this is an exact // match for either a a plain string (for example ^hello$) or for a regexp // (for example ^hel*o$). if expr.MatchString(input) { return true, nil } } return false, nil }
go
func SliceMatchesRegex(input string, expressions []string) (bool, error) { for _, expression := range expressions { if !strings.HasPrefix(expression, "^") || !strings.HasSuffix(expression, "$") { // replace glob-style wildcards with regexp wildcards // for plain strings, and quote all characters that could // be interpreted in regular expression expression = "^" + GlobToRegexp(expression) + "$" } expr, err := regexp.Compile(expression) if err != nil { return false, trace.BadParameter(err.Error()) } // Since the expression is always surrounded by ^ and $ this is an exact // match for either a a plain string (for example ^hello$) or for a regexp // (for example ^hel*o$). if expr.MatchString(input) { return true, nil } } return false, nil }
[ "func", "SliceMatchesRegex", "(", "input", "string", ",", "expressions", "[", "]", "string", ")", "(", "bool", ",", "error", ")", "{", "for", "_", ",", "expression", ":=", "range", "expressions", "{", "if", "!", "strings", ".", "HasPrefix", "(", "expression", ",", "\"", "\"", ")", "||", "!", "strings", ".", "HasSuffix", "(", "expression", ",", "\"", "\"", ")", "{", "// replace glob-style wildcards with regexp wildcards", "// for plain strings, and quote all characters that could", "// be interpreted in regular expression", "expression", "=", "\"", "\"", "+", "GlobToRegexp", "(", "expression", ")", "+", "\"", "\"", "\n", "}", "\n\n", "expr", ",", "err", ":=", "regexp", ".", "Compile", "(", "expression", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "trace", ".", "BadParameter", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "// Since the expression is always surrounded by ^ and $ this is an exact", "// match for either a a plain string (for example ^hello$) or for a regexp", "// (for example ^hel*o$).", "if", "expr", ".", "MatchString", "(", "input", ")", "{", "return", "true", ",", "nil", "\n", "}", "\n", "}", "\n\n", "return", "false", ",", "nil", "\n", "}" ]
// SliceMatchesRegex checks if input matches any of the expressions. The // match is always evaluated as a regex either an exact match or regexp.
[ "SliceMatchesRegex", "checks", "if", "input", "matches", "any", "of", "the", "expressions", ".", "The", "match", "is", "always", "evaluated", "as", "a", "regex", "either", "an", "exact", "match", "or", "regexp", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/replace.go#L51-L74
train
gravitational/teleport
lib/auth/state.go
NewProcessStorage
func NewProcessStorage(ctx context.Context, path string) (*ProcessStorage, error) { if path == "" { return nil, trace.BadParameter("missing parameter path") } litebk, err := lite.NewWithConfig(ctx, lite.Config{Path: path, EventsOff: true}) if err != nil { return nil, trace.Wrap(err) } // Import storage data err = legacy.Import(ctx, litebk, func() (legacy.Exporter, error) { return dir.New(legacy.Params{"path": path}) }) if err != nil { return nil, trace.Wrap(err) } return &ProcessStorage{Backend: litebk}, nil }
go
func NewProcessStorage(ctx context.Context, path string) (*ProcessStorage, error) { if path == "" { return nil, trace.BadParameter("missing parameter path") } litebk, err := lite.NewWithConfig(ctx, lite.Config{Path: path, EventsOff: true}) if err != nil { return nil, trace.Wrap(err) } // Import storage data err = legacy.Import(ctx, litebk, func() (legacy.Exporter, error) { return dir.New(legacy.Params{"path": path}) }) if err != nil { return nil, trace.Wrap(err) } return &ProcessStorage{Backend: litebk}, nil }
[ "func", "NewProcessStorage", "(", "ctx", "context", ".", "Context", ",", "path", "string", ")", "(", "*", "ProcessStorage", ",", "error", ")", "{", "if", "path", "==", "\"", "\"", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n", "litebk", ",", "err", ":=", "lite", ".", "NewWithConfig", "(", "ctx", ",", "lite", ".", "Config", "{", "Path", ":", "path", ",", "EventsOff", ":", "true", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "// Import storage data", "err", "=", "legacy", ".", "Import", "(", "ctx", ",", "litebk", ",", "func", "(", ")", "(", "legacy", ".", "Exporter", ",", "error", ")", "{", "return", "dir", ".", "New", "(", "legacy", ".", "Params", "{", "\"", "\"", ":", "path", "}", ")", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n\n", "return", "&", "ProcessStorage", "{", "Backend", ":", "litebk", "}", ",", "nil", "\n", "}" ]
// NewProcessStorage returns a new instance of the process storage.
[ "NewProcessStorage", "returns", "a", "new", "instance", "of", "the", "process", "storage", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/state.go#L44-L61
train
gravitational/teleport
lib/auth/state.go
GetState
func (p *ProcessStorage) GetState(role teleport.Role) (*StateV2, error) { item, err := p.Get(context.TODO(), backend.Key(statesPrefix, strings.ToLower(role.String()), stateName)) if err != nil { return nil, trace.Wrap(err) } var res StateV2 if err := utils.UnmarshalWithSchema(GetStateSchema(), &res, item.Value); err != nil { return nil, trace.BadParameter(err.Error()) } return &res, nil }
go
func (p *ProcessStorage) GetState(role teleport.Role) (*StateV2, error) { item, err := p.Get(context.TODO(), backend.Key(statesPrefix, strings.ToLower(role.String()), stateName)) if err != nil { return nil, trace.Wrap(err) } var res StateV2 if err := utils.UnmarshalWithSchema(GetStateSchema(), &res, item.Value); err != nil { return nil, trace.BadParameter(err.Error()) } return &res, nil }
[ "func", "(", "p", "*", "ProcessStorage", ")", "GetState", "(", "role", "teleport", ".", "Role", ")", "(", "*", "StateV2", ",", "error", ")", "{", "item", ",", "err", ":=", "p", ".", "Get", "(", "context", ".", "TODO", "(", ")", ",", "backend", ".", "Key", "(", "statesPrefix", ",", "strings", ".", "ToLower", "(", "role", ".", "String", "(", ")", ")", ",", "stateName", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "var", "res", "StateV2", "\n", "if", "err", ":=", "utils", ".", "UnmarshalWithSchema", "(", "GetStateSchema", "(", ")", ",", "&", "res", ",", "item", ".", "Value", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "return", "&", "res", ",", "nil", "\n", "}" ]
// GetState reads rotation state from disk.
[ "GetState", "reads", "rotation", "state", "from", "disk", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/state.go#L84-L94
train
gravitational/teleport
lib/auth/state.go
CreateState
func (p *ProcessStorage) CreateState(role teleport.Role, state StateV2) error { if err := state.CheckAndSetDefaults(); err != nil { return trace.Wrap(err) } value, err := json.Marshal(state) if err != nil { return trace.Wrap(err) } item := backend.Item{ Key: backend.Key(statesPrefix, strings.ToLower(role.String()), stateName), Value: value, } _, err = p.Create(context.TODO(), item) if err != nil { return trace.Wrap(err) } return nil }
go
func (p *ProcessStorage) CreateState(role teleport.Role, state StateV2) error { if err := state.CheckAndSetDefaults(); err != nil { return trace.Wrap(err) } value, err := json.Marshal(state) if err != nil { return trace.Wrap(err) } item := backend.Item{ Key: backend.Key(statesPrefix, strings.ToLower(role.String()), stateName), Value: value, } _, err = p.Create(context.TODO(), item) if err != nil { return trace.Wrap(err) } return nil }
[ "func", "(", "p", "*", "ProcessStorage", ")", "CreateState", "(", "role", "teleport", ".", "Role", ",", "state", "StateV2", ")", "error", "{", "if", "err", ":=", "state", ".", "CheckAndSetDefaults", "(", ")", ";", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "value", ",", "err", ":=", "json", ".", "Marshal", "(", "state", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "item", ":=", "backend", ".", "Item", "{", "Key", ":", "backend", ".", "Key", "(", "statesPrefix", ",", "strings", ".", "ToLower", "(", "role", ".", "String", "(", ")", ")", ",", "stateName", ")", ",", "Value", ":", "value", ",", "}", "\n", "_", ",", "err", "=", "p", ".", "Create", "(", "context", ".", "TODO", "(", ")", ",", "item", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// CreateState creates process state if it does not exist yet.
[ "CreateState", "creates", "process", "state", "if", "it", "does", "not", "exist", "yet", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/state.go#L97-L114
train
gravitational/teleport
lib/auth/state.go
ReadIdentity
func (p *ProcessStorage) ReadIdentity(name string, role teleport.Role) (*Identity, error) { if name == "" { return nil, trace.BadParameter("missing parameter name") } item, err := p.Get(context.TODO(), backend.Key(idsPrefix, strings.ToLower(role.String()), name)) if err != nil { return nil, trace.Wrap(err) } var res IdentityV2 if err := utils.UnmarshalWithSchema(GetIdentitySchema(), &res, item.Value); err != nil { return nil, trace.BadParameter(err.Error()) } return ReadIdentityFromKeyPair(&PackedKeys{ Key: res.Spec.Key, Cert: res.Spec.SSHCert, TLSCert: res.Spec.TLSCert, TLSCACerts: res.Spec.TLSCACerts, SSHCACerts: res.Spec.SSHCACerts, }) }
go
func (p *ProcessStorage) ReadIdentity(name string, role teleport.Role) (*Identity, error) { if name == "" { return nil, trace.BadParameter("missing parameter name") } item, err := p.Get(context.TODO(), backend.Key(idsPrefix, strings.ToLower(role.String()), name)) if err != nil { return nil, trace.Wrap(err) } var res IdentityV2 if err := utils.UnmarshalWithSchema(GetIdentitySchema(), &res, item.Value); err != nil { return nil, trace.BadParameter(err.Error()) } return ReadIdentityFromKeyPair(&PackedKeys{ Key: res.Spec.Key, Cert: res.Spec.SSHCert, TLSCert: res.Spec.TLSCert, TLSCACerts: res.Spec.TLSCACerts, SSHCACerts: res.Spec.SSHCACerts, }) }
[ "func", "(", "p", "*", "ProcessStorage", ")", "ReadIdentity", "(", "name", "string", ",", "role", "teleport", ".", "Role", ")", "(", "*", "Identity", ",", "error", ")", "{", "if", "name", "==", "\"", "\"", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ")", "\n", "}", "\n", "item", ",", "err", ":=", "p", ".", "Get", "(", "context", ".", "TODO", "(", ")", ",", "backend", ".", "Key", "(", "idsPrefix", ",", "strings", ".", "ToLower", "(", "role", ".", "String", "(", ")", ")", ",", "name", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "var", "res", "IdentityV2", "\n", "if", "err", ":=", "utils", ".", "UnmarshalWithSchema", "(", "GetIdentitySchema", "(", ")", ",", "&", "res", ",", "item", ".", "Value", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "return", "ReadIdentityFromKeyPair", "(", "&", "PackedKeys", "{", "Key", ":", "res", ".", "Spec", ".", "Key", ",", "Cert", ":", "res", ".", "Spec", ".", "SSHCert", ",", "TLSCert", ":", "res", ".", "Spec", ".", "TLSCert", ",", "TLSCACerts", ":", "res", ".", "Spec", ".", "TLSCACerts", ",", "SSHCACerts", ":", "res", ".", "Spec", ".", "SSHCACerts", ",", "}", ")", "\n", "}" ]
// ReadIdentity reads identity using identity name and role.
[ "ReadIdentity", "reads", "identity", "using", "identity", "name", "and", "role", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/state.go#L137-L156
train
gravitational/teleport
lib/auth/state.go
WriteIdentity
func (p *ProcessStorage) WriteIdentity(name string, id Identity) error { res := IdentityV2{ ResourceHeader: services.ResourceHeader{ Kind: services.KindIdentity, Version: services.V2, Metadata: services.Metadata{ Name: name, }, }, Spec: IdentitySpecV2{ Key: id.KeyBytes, SSHCert: id.CertBytes, TLSCert: id.TLSCertBytes, TLSCACerts: id.TLSCACertsBytes, SSHCACerts: id.SSHCACertBytes, }, } if err := res.CheckAndSetDefaults(); err != nil { return trace.Wrap(err) } value, err := json.Marshal(res) if err != nil { return trace.Wrap(err) } item := backend.Item{ Key: backend.Key(idsPrefix, strings.ToLower(id.ID.Role.String()), name), Value: value, } _, err = p.Put(context.TODO(), item) return trace.Wrap(err) }
go
func (p *ProcessStorage) WriteIdentity(name string, id Identity) error { res := IdentityV2{ ResourceHeader: services.ResourceHeader{ Kind: services.KindIdentity, Version: services.V2, Metadata: services.Metadata{ Name: name, }, }, Spec: IdentitySpecV2{ Key: id.KeyBytes, SSHCert: id.CertBytes, TLSCert: id.TLSCertBytes, TLSCACerts: id.TLSCACertsBytes, SSHCACerts: id.SSHCACertBytes, }, } if err := res.CheckAndSetDefaults(); err != nil { return trace.Wrap(err) } value, err := json.Marshal(res) if err != nil { return trace.Wrap(err) } item := backend.Item{ Key: backend.Key(idsPrefix, strings.ToLower(id.ID.Role.String()), name), Value: value, } _, err = p.Put(context.TODO(), item) return trace.Wrap(err) }
[ "func", "(", "p", "*", "ProcessStorage", ")", "WriteIdentity", "(", "name", "string", ",", "id", "Identity", ")", "error", "{", "res", ":=", "IdentityV2", "{", "ResourceHeader", ":", "services", ".", "ResourceHeader", "{", "Kind", ":", "services", ".", "KindIdentity", ",", "Version", ":", "services", ".", "V2", ",", "Metadata", ":", "services", ".", "Metadata", "{", "Name", ":", "name", ",", "}", ",", "}", ",", "Spec", ":", "IdentitySpecV2", "{", "Key", ":", "id", ".", "KeyBytes", ",", "SSHCert", ":", "id", ".", "CertBytes", ",", "TLSCert", ":", "id", ".", "TLSCertBytes", ",", "TLSCACerts", ":", "id", ".", "TLSCACertsBytes", ",", "SSHCACerts", ":", "id", ".", "SSHCACertBytes", ",", "}", ",", "}", "\n", "if", "err", ":=", "res", ".", "CheckAndSetDefaults", "(", ")", ";", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "value", ",", "err", ":=", "json", ".", "Marshal", "(", "res", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "item", ":=", "backend", ".", "Item", "{", "Key", ":", "backend", ".", "Key", "(", "idsPrefix", ",", "strings", ".", "ToLower", "(", "id", ".", "ID", ".", "Role", ".", "String", "(", ")", ")", ",", "name", ")", ",", "Value", ":", "value", ",", "}", "\n", "_", ",", "err", "=", "p", ".", "Put", "(", "context", ".", "TODO", "(", ")", ",", "item", ")", "\n", "return", "trace", ".", "Wrap", "(", "err", ")", "\n", "}" ]
// WriteIdentity writes identity to the backend.
[ "WriteIdentity", "writes", "identity", "to", "the", "backend", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/state.go#L159-L189
train
gravitational/teleport
lib/auth/state.go
GetIdentitySchema
func GetIdentitySchema() string { return fmt.Sprintf(services.V2SchemaTemplate, services.MetadataSchema, IdentitySpecV2Schema, services.DefaultDefinitions) }
go
func GetIdentitySchema() string { return fmt.Sprintf(services.V2SchemaTemplate, services.MetadataSchema, IdentitySpecV2Schema, services.DefaultDefinitions) }
[ "func", "GetIdentitySchema", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "services", ".", "V2SchemaTemplate", ",", "services", ".", "MetadataSchema", ",", "IdentitySpecV2Schema", ",", "services", ".", "DefaultDefinitions", ")", "\n", "}" ]
// GetIdentitySchema returns JSON Schema for cert authorities.
[ "GetIdentitySchema", "returns", "JSON", "Schema", "for", "cert", "authorities", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/state.go#L289-L291
train
gravitational/teleport
lib/auth/state.go
GetStateSchema
func GetStateSchema() string { return fmt.Sprintf(services.V2SchemaTemplate, services.MetadataSchema, fmt.Sprintf(StateSpecV2Schema, services.RotationSchema), services.DefaultDefinitions) }
go
func GetStateSchema() string { return fmt.Sprintf(services.V2SchemaTemplate, services.MetadataSchema, fmt.Sprintf(StateSpecV2Schema, services.RotationSchema), services.DefaultDefinitions) }
[ "func", "GetStateSchema", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "services", ".", "V2SchemaTemplate", ",", "services", ".", "MetadataSchema", ",", "fmt", ".", "Sprintf", "(", "StateSpecV2Schema", ",", "services", ".", "RotationSchema", ")", ",", "services", ".", "DefaultDefinitions", ")", "\n", "}" ]
// GetStateSchema returns JSON Schema for cert authorities.
[ "GetStateSchema", "returns", "JSON", "Schema", "for", "cert", "authorities", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/state.go#L304-L306
train
gravitational/teleport
lib/events/api.go
AsString
func (f EventFields) AsString() string { return fmt.Sprintf("%s: login=%s, id=%v, bytes=%v", f.GetString(EventType), f.GetString(EventLogin), f.GetInt(EventCursor), f.GetInt(SessionPrintEventBytes)) }
go
func (f EventFields) AsString() string { return fmt.Sprintf("%s: login=%s, id=%v, bytes=%v", f.GetString(EventType), f.GetString(EventLogin), f.GetInt(EventCursor), f.GetInt(SessionPrintEventBytes)) }
[ "func", "(", "f", "EventFields", ")", "AsString", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "f", ".", "GetString", "(", "EventType", ")", ",", "f", ".", "GetString", "(", "EventLogin", ")", ",", "f", ".", "GetInt", "(", "EventCursor", ")", ",", "f", ".", "GetInt", "(", "SessionPrintEventBytes", ")", ")", "\n", "}" ]
// String returns a string representation of an event structure
[ "String", "returns", "a", "string", "representation", "of", "an", "event", "structure" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/api.go#L251-L257
train
gravitational/teleport
lib/events/api.go
GetString
func (f EventFields) GetString(key string) string { val, found := f[key] if !found { return "" } v, _ := val.(string) return v }
go
func (f EventFields) GetString(key string) string { val, found := f[key] if !found { return "" } v, _ := val.(string) return v }
[ "func", "(", "f", "EventFields", ")", "GetString", "(", "key", "string", ")", "string", "{", "val", ",", "found", ":=", "f", "[", "key", "]", "\n", "if", "!", "found", "{", "return", "\"", "\"", "\n", "}", "\n", "v", ",", "_", ":=", "val", ".", "(", "string", ")", "\n", "return", "v", "\n", "}" ]
// GetString returns a string representation of a logged field
[ "GetString", "returns", "a", "string", "representation", "of", "a", "logged", "field" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/api.go#L280-L287
train
gravitational/teleport
lib/kube/proxy/remotecommand.go
waitStreamReply
func waitStreamReply(ctx context.Context, replySent <-chan struct{}, notify chan<- struct{}) { select { case <-replySent: notify <- struct{}{} case <-ctx.Done(): } }
go
func waitStreamReply(ctx context.Context, replySent <-chan struct{}, notify chan<- struct{}) { select { case <-replySent: notify <- struct{}{} case <-ctx.Done(): } }
[ "func", "waitStreamReply", "(", "ctx", "context", ".", "Context", ",", "replySent", "<-", "chan", "struct", "{", "}", ",", "notify", "chan", "<-", "struct", "{", "}", ")", "{", "select", "{", "case", "<-", "replySent", ":", "notify", "<-", "struct", "{", "}", "{", "}", "\n", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "}", "\n", "}" ]
// waitStreamReply waits until either replySent or stop is closed. If replySent is closed, it sends // an empty struct to the notify channel.
[ "waitStreamReply", "waits", "until", "either", "replySent", "or", "stop", "is", "closed", ".", "If", "replySent", "is", "closed", "it", "sends", "an", "empty", "struct", "to", "the", "notify", "channel", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/remotecommand.go#L311-L317
train
gravitational/teleport
lib/utils/fs.go
MkdirAll
func MkdirAll(targetDirectory string, mode os.FileMode) error { err := os.MkdirAll(targetDirectory, mode) if err != nil { return trace.ConvertSystemError(err) } return nil }
go
func MkdirAll(targetDirectory string, mode os.FileMode) error { err := os.MkdirAll(targetDirectory, mode) if err != nil { return trace.ConvertSystemError(err) } return nil }
[ "func", "MkdirAll", "(", "targetDirectory", "string", ",", "mode", "os", ".", "FileMode", ")", "error", "{", "err", ":=", "os", ".", "MkdirAll", "(", "targetDirectory", ",", "mode", ")", "\n", "if", "err", "!=", "nil", "{", "return", "trace", ".", "ConvertSystemError", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// MkdirAll creates directory and subdirectories
[ "MkdirAll", "creates", "directory", "and", "subdirectories" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/fs.go#L59-L65
train
gravitational/teleport
lib/utils/fs.go
Close
func (r *RemoveDirCloser) Close() error { return trace.ConvertSystemError(os.RemoveAll(r.Path)) }
go
func (r *RemoveDirCloser) Close() error { return trace.ConvertSystemError(os.RemoveAll(r.Path)) }
[ "func", "(", "r", "*", "RemoveDirCloser", ")", "Close", "(", ")", "error", "{", "return", "trace", ".", "ConvertSystemError", "(", "os", ".", "RemoveAll", "(", "r", ".", "Path", ")", ")", "\n", "}" ]
// Close removes directory and all it's contents
[ "Close", "removes", "directory", "and", "all", "it", "s", "contents" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/fs.go#L74-L76
train
gravitational/teleport
lib/utils/fs.go
IsFile
func IsFile(fp string) bool { fi, err := os.Stat(fp) if err == nil { return !fi.IsDir() } return false }
go
func IsFile(fp string) bool { fi, err := os.Stat(fp) if err == nil { return !fi.IsDir() } return false }
[ "func", "IsFile", "(", "fp", "string", ")", "bool", "{", "fi", ",", "err", ":=", "os", ".", "Stat", "(", "fp", ")", "\n", "if", "err", "==", "nil", "{", "return", "!", "fi", ".", "IsDir", "(", ")", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsFile returns true if a given file path points to an existing file
[ "IsFile", "returns", "true", "if", "a", "given", "file", "path", "points", "to", "an", "existing", "file" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/fs.go#L79-L85
train
gravitational/teleport
lib/utils/fs.go
IsDir
func IsDir(dirPath string) bool { fi, err := os.Stat(dirPath) if err == nil { return fi.IsDir() } return false }
go
func IsDir(dirPath string) bool { fi, err := os.Stat(dirPath) if err == nil { return fi.IsDir() } return false }
[ "func", "IsDir", "(", "dirPath", "string", ")", "bool", "{", "fi", ",", "err", ":=", "os", ".", "Stat", "(", "dirPath", ")", "\n", "if", "err", "==", "nil", "{", "return", "fi", ".", "IsDir", "(", ")", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsDir is a helper function to quickly check if a given path is a valid directory
[ "IsDir", "is", "a", "helper", "function", "to", "quickly", "check", "if", "a", "given", "path", "is", "a", "valid", "directory" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/fs.go#L88-L94
train
gravitational/teleport
lib/utils/fs.go
NormalizePath
func NormalizePath(path string) (string, error) { s, err := filepath.Abs(path) if err != nil { return "", trace.ConvertSystemError(err) } abs, err := filepath.EvalSymlinks(s) if err != nil { return "", trace.ConvertSystemError(err) } return abs, nil }
go
func NormalizePath(path string) (string, error) { s, err := filepath.Abs(path) if err != nil { return "", trace.ConvertSystemError(err) } abs, err := filepath.EvalSymlinks(s) if err != nil { return "", trace.ConvertSystemError(err) } return abs, nil }
[ "func", "NormalizePath", "(", "path", "string", ")", "(", "string", ",", "error", ")", "{", "s", ",", "err", ":=", "filepath", ".", "Abs", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "trace", ".", "ConvertSystemError", "(", "err", ")", "\n", "}", "\n", "abs", ",", "err", ":=", "filepath", ".", "EvalSymlinks", "(", "s", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "trace", ".", "ConvertSystemError", "(", "err", ")", "\n", "}", "\n", "return", "abs", ",", "nil", "\n", "}" ]
// NormalizePath normalises path, evaluating symlinks and converting local // paths to absolute
[ "NormalizePath", "normalises", "path", "evaluating", "symlinks", "and", "converting", "local", "paths", "to", "absolute" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/fs.go#L117-L127
train
gravitational/teleport
lib/utils/fs.go
OpenFile
func OpenFile(path string) (*os.File, error) { newPath, err := NormalizePath(path) if err != nil { return nil, trace.Wrap(err) } fi, err := os.Stat(newPath) if err != nil { return nil, trace.ConvertSystemError(err) } if fi.IsDir() { return nil, trace.BadParameter("%v is not a file", path) } f, err := os.Open(newPath) if err != nil { return nil, trace.ConvertSystemError(err) } return f, nil }
go
func OpenFile(path string) (*os.File, error) { newPath, err := NormalizePath(path) if err != nil { return nil, trace.Wrap(err) } fi, err := os.Stat(newPath) if err != nil { return nil, trace.ConvertSystemError(err) } if fi.IsDir() { return nil, trace.BadParameter("%v is not a file", path) } f, err := os.Open(newPath) if err != nil { return nil, trace.ConvertSystemError(err) } return f, nil }
[ "func", "OpenFile", "(", "path", "string", ")", "(", "*", "os", ".", "File", ",", "error", ")", "{", "newPath", ",", "err", ":=", "NormalizePath", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "fi", ",", "err", ":=", "os", ".", "Stat", "(", "newPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "ConvertSystemError", "(", "err", ")", "\n", "}", "\n", "if", "fi", ".", "IsDir", "(", ")", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ",", "path", ")", "\n", "}", "\n", "f", ",", "err", ":=", "os", ".", "Open", "(", "newPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "ConvertSystemError", "(", "err", ")", "\n", "}", "\n", "return", "f", ",", "nil", "\n", "}" ]
// OpenFile opens file and returns file handle
[ "OpenFile", "opens", "file", "and", "returns", "file", "handle" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/fs.go#L130-L147
train
gravitational/teleport
lib/utils/fs.go
StatDir
func StatDir(path string) (os.FileInfo, error) { fi, err := os.Stat(path) if err != nil { return nil, trace.ConvertSystemError(err) } if !fi.IsDir() { return nil, trace.BadParameter("%v is not a directory", path) } return fi, nil }
go
func StatDir(path string) (os.FileInfo, error) { fi, err := os.Stat(path) if err != nil { return nil, trace.ConvertSystemError(err) } if !fi.IsDir() { return nil, trace.BadParameter("%v is not a directory", path) } return fi, nil }
[ "func", "StatDir", "(", "path", "string", ")", "(", "os", ".", "FileInfo", ",", "error", ")", "{", "fi", ",", "err", ":=", "os", ".", "Stat", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "ConvertSystemError", "(", "err", ")", "\n", "}", "\n", "if", "!", "fi", ".", "IsDir", "(", ")", "{", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ",", "path", ")", "\n", "}", "\n", "return", "fi", ",", "nil", "\n", "}" ]
// StatDir stats directory, returns error if file exists, but not a directory
[ "StatDir", "stats", "directory", "returns", "error", "if", "file", "exists", "but", "not", "a", "directory" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/fs.go#L150-L159
train
gravitational/teleport
lib/utils/fs.go
getHomeDir
func getHomeDir() string { switch runtime.GOOS { case teleport.LinuxOS: return os.Getenv(teleport.EnvHome) case teleport.DarwinOS: return os.Getenv(teleport.EnvHome) case teleport.WindowsOS: return os.Getenv(teleport.EnvUserProfile) } return "" }
go
func getHomeDir() string { switch runtime.GOOS { case teleport.LinuxOS: return os.Getenv(teleport.EnvHome) case teleport.DarwinOS: return os.Getenv(teleport.EnvHome) case teleport.WindowsOS: return os.Getenv(teleport.EnvUserProfile) } return "" }
[ "func", "getHomeDir", "(", ")", "string", "{", "switch", "runtime", ".", "GOOS", "{", "case", "teleport", ".", "LinuxOS", ":", "return", "os", ".", "Getenv", "(", "teleport", ".", "EnvHome", ")", "\n", "case", "teleport", ".", "DarwinOS", ":", "return", "os", ".", "Getenv", "(", "teleport", ".", "EnvHome", ")", "\n", "case", "teleport", ".", "WindowsOS", ":", "return", "os", ".", "Getenv", "(", "teleport", ".", "EnvUserProfile", ")", "\n", "}", "\n", "return", "\"", "\"", "\n", "}" ]
// getHomeDir returns the home directory based off the OS.
[ "getHomeDir", "returns", "the", "home", "directory", "based", "off", "the", "OS", "." ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/fs.go#L162-L172
train
gravitational/teleport
lib/utils/listener.go
GetListenerFile
func GetListenerFile(listener net.Listener) (*os.File, error) { switch t := listener.(type) { case *net.TCPListener: return t.File() case *net.UnixListener: return t.File() } return nil, trace.BadParameter("unsupported listener: %T", listener) }
go
func GetListenerFile(listener net.Listener) (*os.File, error) { switch t := listener.(type) { case *net.TCPListener: return t.File() case *net.UnixListener: return t.File() } return nil, trace.BadParameter("unsupported listener: %T", listener) }
[ "func", "GetListenerFile", "(", "listener", "net", ".", "Listener", ")", "(", "*", "os", ".", "File", ",", "error", ")", "{", "switch", "t", ":=", "listener", ".", "(", "type", ")", "{", "case", "*", "net", ".", "TCPListener", ":", "return", "t", ".", "File", "(", ")", "\n", "case", "*", "net", ".", "UnixListener", ":", "return", "t", ".", "File", "(", ")", "\n", "}", "\n", "return", "nil", ",", "trace", ".", "BadParameter", "(", "\"", "\"", ",", "listener", ")", "\n", "}" ]
// GetListenerFile returns file associated with listener
[ "GetListenerFile", "returns", "file", "associated", "with", "listener" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/listener.go#L11-L19
train
gravitational/teleport
lib/utils/buf.go
NewSyncBuffer
func NewSyncBuffer() *SyncBuffer { reader, writer := io.Pipe() buf := &bytes.Buffer{} go func() { io.Copy(buf, reader) }() return &SyncBuffer{ reader: reader, writer: writer, buf: buf, } }
go
func NewSyncBuffer() *SyncBuffer { reader, writer := io.Pipe() buf := &bytes.Buffer{} go func() { io.Copy(buf, reader) }() return &SyncBuffer{ reader: reader, writer: writer, buf: buf, } }
[ "func", "NewSyncBuffer", "(", ")", "*", "SyncBuffer", "{", "reader", ",", "writer", ":=", "io", ".", "Pipe", "(", ")", "\n", "buf", ":=", "&", "bytes", ".", "Buffer", "{", "}", "\n", "go", "func", "(", ")", "{", "io", ".", "Copy", "(", "buf", ",", "reader", ")", "\n", "}", "(", ")", "\n", "return", "&", "SyncBuffer", "{", "reader", ":", "reader", ",", "writer", ":", "writer", ",", "buf", ":", "buf", ",", "}", "\n", "}" ]
// NewSyncBuffer returns new in memory buffer
[ "NewSyncBuffer", "returns", "new", "in", "memory", "buffer" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/buf.go#L25-L36
train
gravitational/teleport
lib/utils/buf.go
Close
func (b *SyncBuffer) Close() error { err := b.reader.Close() err2 := b.writer.Close() if err != nil { return err } return err2 }
go
func (b *SyncBuffer) Close() error { err := b.reader.Close() err2 := b.writer.Close() if err != nil { return err } return err2 }
[ "func", "(", "b", "*", "SyncBuffer", ")", "Close", "(", ")", "error", "{", "err", ":=", "b", ".", "reader", ".", "Close", "(", ")", "\n", "err2", ":=", "b", ".", "writer", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "err2", "\n", "}" ]
// Close closes reads and writes on the buffer
[ "Close", "closes", "reads", "and", "writes", "on", "the", "buffer" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/buf.go#L65-L72
train
gravitational/teleport
lib/reversetunnel/agent.go
NewAgent
func NewAgent(cfg AgentConfig) (*Agent, error) { if err := cfg.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } ctx, cancel := context.WithCancel(cfg.Context) a := &Agent{ AgentConfig: cfg, ctx: ctx, cancel: cancel, authMethods: []ssh.AuthMethod{ssh.PublicKeys(cfg.Signers...)}, } if len(cfg.DiscoverProxies) == 0 { a.state = agentStateConnecting } else { a.state = agentStateDiscovering } a.Entry = log.WithFields(log.Fields{ trace.Component: teleport.ComponentReverseTunnelAgent, trace.ComponentFields: log.Fields{ "target": cfg.Addr.String(), }, }) a.hostKeyCallback = a.checkHostSignature return a, nil }
go
func NewAgent(cfg AgentConfig) (*Agent, error) { if err := cfg.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } ctx, cancel := context.WithCancel(cfg.Context) a := &Agent{ AgentConfig: cfg, ctx: ctx, cancel: cancel, authMethods: []ssh.AuthMethod{ssh.PublicKeys(cfg.Signers...)}, } if len(cfg.DiscoverProxies) == 0 { a.state = agentStateConnecting } else { a.state = agentStateDiscovering } a.Entry = log.WithFields(log.Fields{ trace.Component: teleport.ComponentReverseTunnelAgent, trace.ComponentFields: log.Fields{ "target": cfg.Addr.String(), }, }) a.hostKeyCallback = a.checkHostSignature return a, nil }
[ "func", "NewAgent", "(", "cfg", "AgentConfig", ")", "(", "*", "Agent", ",", "error", ")", "{", "if", "err", ":=", "cfg", ".", "CheckAndSetDefaults", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "trace", ".", "Wrap", "(", "err", ")", "\n", "}", "\n", "ctx", ",", "cancel", ":=", "context", ".", "WithCancel", "(", "cfg", ".", "Context", ")", "\n", "a", ":=", "&", "Agent", "{", "AgentConfig", ":", "cfg", ",", "ctx", ":", "ctx", ",", "cancel", ":", "cancel", ",", "authMethods", ":", "[", "]", "ssh", ".", "AuthMethod", "{", "ssh", ".", "PublicKeys", "(", "cfg", ".", "Signers", "...", ")", "}", ",", "}", "\n", "if", "len", "(", "cfg", ".", "DiscoverProxies", ")", "==", "0", "{", "a", ".", "state", "=", "agentStateConnecting", "\n", "}", "else", "{", "a", ".", "state", "=", "agentStateDiscovering", "\n", "}", "\n", "a", ".", "Entry", "=", "log", ".", "WithFields", "(", "log", ".", "Fields", "{", "trace", ".", "Component", ":", "teleport", ".", "ComponentReverseTunnelAgent", ",", "trace", ".", "ComponentFields", ":", "log", ".", "Fields", "{", "\"", "\"", ":", "cfg", ".", "Addr", ".", "String", "(", ")", ",", "}", ",", "}", ")", "\n", "a", ".", "hostKeyCallback", "=", "a", ".", "checkHostSignature", "\n", "return", "a", ",", "nil", "\n", "}" ]
// NewAgent returns a new reverse tunnel agent
[ "NewAgent", "returns", "a", "new", "reverse", "tunnel", "agent" ]
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/agent.go#L150-L174
train