repo
stringlengths
5
67
sha
stringlengths
40
40
path
stringlengths
4
234
url
stringlengths
85
339
language
stringclasses
6 values
split
stringclasses
3 values
doc
stringlengths
3
51.2k
sign
stringlengths
5
8.01k
problem
stringlengths
13
51.2k
output
stringlengths
0
3.87M
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/service/supervisor.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/supervisor.go#L313-L354
go
train
// BroadcastEvent generates event and broadcasts it to all // subscribed parties.
func (s *LocalSupervisor) BroadcastEvent(event Event)
// BroadcastEvent generates event and broadcasts it to all // subscribed parties. func (s *LocalSupervisor) BroadcastEvent(event Event)
{ s.Lock() defer s.Unlock() switch event.Name { case TeleportExitEvent: s.signalExit() case TeleportReloadEvent: s.signalReload() } s.events[event.Name] = event // Log all events other than recovered events to prevent the logs from // being flooded. if event.String() != TeleportOKEvent { log.WithFields(logrus.Fields{"event": event.String(), trace.Component: teleport.Component(teleport.ComponentProcess, s.id)}).Debugf("Broadcasting event.") } go func() { select { case s.eventsC <- event: case <-s.closeContext.Done(): return } }() for _, m := range s.eventMappings { if m.matches(event.Name, s.events) { mappedEvent := Event{Name: m.Out} s.events[mappedEvent.Name] = mappedEvent go func(e Event) { select { case s.eventsC <- e: case <-s.closeContext.Done(): return } }(mappedEvent) log.WithFields(logrus.Fields{"in": event.String(), "out": m.String(), trace.Component: teleport.Component(teleport.ComponentProcess, s.id)}).Debugf("Broadcasting mapped event.") } } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/service/supervisor.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/supervisor.go#L359-L364
go
train
// RegisterEventMapping registers event mapping - // when the sequence in the event mapping triggers, the // outbound event will be generated.
func (s *LocalSupervisor) RegisterEventMapping(m EventMapping)
// RegisterEventMapping registers event mapping - // when the sequence in the event mapping triggers, the // outbound event will be generated. func (s *LocalSupervisor) RegisterEventMapping(m EventMapping)
{ s.Lock() defer s.Unlock() s.eventMappings = append(s.eventMappings, m) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/service/supervisor.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/supervisor.go#L368-L379
go
train
// WaitForEvent waits for event to be broadcasted, if the event // was already broadcasted, eventC will receive current event immediately.
func (s *LocalSupervisor) WaitForEvent(ctx context.Context, name string, eventC chan Event)
// WaitForEvent waits for event to be broadcasted, if the event // was already broadcasted, eventC will receive current event immediately. func (s *LocalSupervisor) WaitForEvent(ctx context.Context, name string, eventC chan Event)
{ s.Lock() defer s.Unlock() waiter := &waiter{eventC: eventC, context: ctx} event, ok := s.events[name] if ok { go s.notifyWaiter(waiter, event) return } s.eventWaiters[name] = append(s.eventWaiters[name], waiter) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tsh/tsh.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tsh/tsh.go#L180-L348
go
train
// Run executes TSH client. same as main() but easier to test
func Run(args []string, underTest bool)
// Run executes TSH client. same as main() but easier to test func Run(args []string, underTest bool)
{ var cf CLIConf cf.IsUnderTest = underTest utils.InitLogger(utils.LoggingForCLI, logrus.WarnLevel) // configure CLI argument parser: app := utils.InitCLIParser("tsh", "TSH: Teleport SSH client").Interspersed(false) app.Flag("login", "Remote host login").Short('l').Envar("TELEPORT_LOGIN").StringVar(&cf.NodeLogin) localUser, _ := client.Username() app.Flag("proxy", "SSH proxy address").Envar("TELEPORT_PROXY").StringVar(&cf.Proxy) app.Flag("nocache", "do not cache cluster discovery locally").Hidden().BoolVar(&cf.NoCache) app.Flag("user", fmt.Sprintf("SSH proxy user [%s]", localUser)).Envar("TELEPORT_USER").StringVar(&cf.Username) app.Flag("option", "").Short('o').Hidden().AllowDuplicate().PreAction(func(ctx *kingpin.ParseContext) error { return trace.BadParameter("invalid flag, perhaps you want to use this flag as tsh ssh -o?") }).String() app.Flag("ttl", "Minutes to live for a SSH session").Int32Var(&cf.MinsToLive) app.Flag("identity", "Identity file").Short('i').StringVar(&cf.IdentityFileIn) app.Flag("compat", "OpenSSH compatibility flag").Hidden().StringVar(&cf.Compatibility) app.Flag("cert-format", "SSH certificate format").StringVar(&cf.CertificateFormat) app.Flag("insecure", "Do not verify server's certificate and host name. Use only in test environments").Default("false").BoolVar(&cf.InsecureSkipVerify) app.Flag("auth", "Specify the type of authentication connector to use.").StringVar(&cf.AuthConnector) app.Flag("namespace", "Namespace of the cluster").Default(defaults.Namespace).Hidden().StringVar(&cf.Namespace) app.Flag("gops", "Start gops endpoint on a given address").Hidden().BoolVar(&cf.Gops) app.Flag("gops-addr", "Specify gops addr to listen on").Hidden().StringVar(&cf.GopsAddr) app.Flag("skip-version-check", "Skip version checking between server and client.").BoolVar(&cf.SkipVersionCheck) debugMode := app.Flag("debug", "Verbose logging to stdout").Short('d').Bool() app.HelpFlag.Short('h') ver := app.Command("version", "Print the version") // ssh ssh := app.Command("ssh", "Run shell or execute a command on a remote SSH node") ssh.Arg("[user@]host", "Remote hostname and the login to use").Required().StringVar(&cf.UserHost) ssh.Arg("command", "Command to execute on a remote host").StringsVar(&cf.RemoteCommand) ssh.Flag("port", "SSH port on a remote host").Short('p').Int32Var(&cf.NodePort) ssh.Flag("forward-agent", "Forward agent to target node").Short('A').BoolVar(&cf.ForwardAgent) ssh.Flag("forward", "Forward localhost connections to remote server").Short('L').StringsVar(&cf.LocalForwardPorts) ssh.Flag("dynamic-forward", "Forward localhost connections to remote server using SOCKS5").Short('D').StringsVar(&cf.DynamicForwardedPorts) ssh.Flag("local", "Execute command on localhost after connecting to SSH node").Default("false").BoolVar(&cf.LocalExec) ssh.Flag("tty", "Allocate TTY").Short('t').BoolVar(&cf.Interactive) ssh.Flag("cluster", clusterHelp).Envar(clusterEnvVar).StringVar(&cf.SiteName) ssh.Flag("option", "OpenSSH options in the format used in the configuration file").Short('o').AllowDuplicate().StringsVar(&cf.Options) // join join := app.Command("join", "Join the active SSH session") join.Flag("cluster", clusterHelp).Envar(clusterEnvVar).StringVar(&cf.SiteName) join.Arg("session-id", "ID of the session to join").Required().StringVar(&cf.SessionID) // play play := app.Command("play", "Replay the recorded SSH session") play.Flag("cluster", clusterHelp).Envar(clusterEnvVar).StringVar(&cf.SiteName) play.Arg("session-id", "ID of the session to play").Required().StringVar(&cf.SessionID) // scp scp := app.Command("scp", "Secure file copy") scp.Flag("cluster", clusterHelp).Envar(clusterEnvVar).StringVar(&cf.SiteName) scp.Arg("from, to", "Source and destination to copy").Required().StringsVar(&cf.CopySpec) scp.Flag("recursive", "Recursive copy of subdirectories").Short('r').BoolVar(&cf.RecursiveCopy) scp.Flag("port", "Port to connect to on the remote host").Short('P').Int32Var(&cf.NodePort) scp.Flag("quiet", "Quiet mode").Short('q').BoolVar(&cf.Quiet) // ls ls := app.Command("ls", "List remote SSH nodes") ls.Flag("cluster", clusterHelp).Envar(clusterEnvVar).StringVar(&cf.SiteName) ls.Arg("labels", "List of labels to filter node list").StringVar(&cf.UserHost) ls.Flag("verbose", clusterHelp).Short('v').BoolVar(&cf.Verbose) // clusters clusters := app.Command("clusters", "List available Teleport clusters") clusters.Flag("quiet", "Quiet mode").Short('q').BoolVar(&cf.Quiet) // login logs in with remote proxy and obtains a "session certificate" which gets // stored in ~/.tsh directory login := app.Command("login", "Log in to a cluster and retrieve the session certificate") login.Flag("bind-addr", "Address in the form of host:port to bind to for login command webhook").Envar(bindAddrEnvVar).StringVar(&cf.BindAddr) login.Flag("out", "Identity output").Short('o').AllowDuplicate().StringVar(&cf.IdentityFileOut) login.Flag("format", fmt.Sprintf("Identity format [%s] or %s (for OpenSSH compatibility)", client.DefaultIdentityFormat, client.IdentityFormatOpenSSH)).Default(string(client.DefaultIdentityFormat)).StringVar((*string)(&cf.IdentityFormat)) login.Arg("cluster", clusterHelp).StringVar(&cf.SiteName) login.Alias(loginUsageFooter) // logout deletes obtained session certificates in ~/.tsh logout := app.Command("logout", "Delete a cluster certificate") // bench bench := app.Command("bench", "Run shell or execute a command on a remote SSH node").Hidden() bench.Flag("cluster", clusterHelp).Envar(clusterEnvVar).StringVar(&cf.SiteName) bench.Arg("[user@]host", "Remote hostname and the login to use").Required().StringVar(&cf.UserHost) bench.Arg("command", "Command to execute on a remote host").Required().StringsVar(&cf.RemoteCommand) bench.Flag("port", "SSH port on a remote host").Short('p').Int32Var(&cf.NodePort) bench.Flag("threads", "Concurrent threads to run").Default("10").IntVar(&cf.BenchThreads) bench.Flag("duration", "Test duration").Default("1s").DurationVar(&cf.BenchDuration) bench.Flag("rate", "Requests per second rate").Default("10").IntVar(&cf.BenchRate) bench.Flag("interactive", "Create interactive SSH session").BoolVar(&cf.BenchInteractive) // show key show := app.Command("show", "Read an identity from file and print to stdout").Hidden() show.Arg("identity_file", "The file containing a public key or a certificate").Required().StringVar(&cf.IdentityFileIn) // The status command shows which proxy the user is logged into and metadata // about the certificate. status := app.Command("status", "Display the list of proxy servers and retrieved certificates") // On Windows, hide the "ssh", "join", "play", "scp", and "bench" commands // because they all use a terminal. if runtime.GOOS == teleport.WindowsOS { ssh.Hidden() join.Hidden() play.Hidden() scp.Hidden() bench.Hidden() } // parse CLI commands+flags: command, err := app.Parse(args) if err != nil { utils.FatalError(err) } // apply -d flag: if *debugMode { utils.InitLogger(utils.LoggingForCLI, logrus.DebugLevel) } ctx, cancel := context.WithCancel(context.Background()) go func() { exitSignals := make(chan os.Signal, 1) signal.Notify(exitSignals, syscall.SIGTERM, syscall.SIGINT) select { case sig := <-exitSignals: log.Debugf("signal: %v", sig) cancel() } }() cf.Context = ctx if cf.Gops { log.Debugf("Starting gops agent.") err = gops.Listen(&gops.Options{Addr: cf.GopsAddr}) if err != nil { log.Warningf("Failed to start gops agent %v.", err) } } switch command { case ver.FullCommand(): utils.PrintVersion() case ssh.FullCommand(): onSSH(&cf) case bench.FullCommand(): onBenchmark(&cf) case join.FullCommand(): onJoin(&cf) case scp.FullCommand(): onSCP(&cf) case play.FullCommand(): onPlay(&cf) case ls.FullCommand(): onListNodes(&cf) case clusters.FullCommand(): onListClusters(&cf) case login.FullCommand(): onLogin(&cf) case logout.FullCommand(): refuseArgs(logout.FullCommand(), args) onLogout(&cf) case show.FullCommand(): onShow(&cf) case status.FullCommand(): onStatus(&cf) } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tsh/tsh.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tsh/tsh.go#L351-L359
go
train
// onPlay replays a session with a given ID
func onPlay(cf *CLIConf)
// onPlay replays a session with a given ID func onPlay(cf *CLIConf)
{ tc, err := makeClient(cf, true) if err != nil { utils.FatalError(err) } if err := tc.Play(context.TODO(), cf.Namespace, cf.SessionID); err != nil { utils.FatalError(err) } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tsh/tsh.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tsh/tsh.go#L362-L460
go
train
// onLogin logs in with remote proxy and gets signed certificates
func onLogin(cf *CLIConf)
// onLogin logs in with remote proxy and gets signed certificates func onLogin(cf *CLIConf)
{ var ( err error tc *client.TeleportClient key *client.Key ) if cf.IdentityFileIn != "" { utils.FatalError(trace.BadParameter("-i flag cannot be used here")) } if cf.IdentityFormat != client.IdentityFormatOpenSSH && cf.IdentityFormat != client.IdentityFormatFile { utils.FatalError(trace.BadParameter("invalid identity format: %s", cf.IdentityFormat)) } // Get the status of the active profile ~/.tsh/profile as well as the status // of any other proxies the user is logged into. profile, profiles, err := client.Status("", cf.Proxy) if err != nil { if !trace.IsNotFound(err) { utils.FatalError(err) } } // make the teleport client and retrieve the certificate from the proxy: tc, err = makeClient(cf, true) if err != nil { utils.FatalError(err) } // client is already logged in and profile is not expired if profile != nil && !profile.IsExpired(clockwork.NewRealClock()) { switch { // in case if nothing is specified, print current status case cf.Proxy == "" && cf.SiteName == "": printProfiles(profile, profiles) return // in case if parameters match, print current status case host(cf.Proxy) == host(profile.ProxyURL.Host) && cf.SiteName == profile.Cluster: printProfiles(profile, profiles) return // proxy is unspecified or the same as the currently provided proxy, // but cluster is specified, treat this as selecting a new cluster // for the same proxy case (cf.Proxy == "" || host(cf.Proxy) == host(profile.ProxyURL.Host)) && cf.SiteName != "": tc.SaveProfile("", "") if err := kubeclient.UpdateKubeconfig(tc); err != nil { utils.FatalError(err) } onStatus(cf) return // otherwise just passthrough to standard login default: } } if cf.Username == "" { cf.Username = tc.Username } // -i flag specified? save the retreived cert into an identity file makeIdentityFile := (cf.IdentityFileOut != "") activateKey := !makeIdentityFile key, err = tc.Login(cf.Context, activateKey) if err != nil { utils.FatalError(err) } if makeIdentityFile { if err := setupNoninteractiveClient(tc, key); err != nil { utils.FatalError(err) } authorities, err := tc.GetTrustedCA(cf.Context, key.ClusterName) if err != nil { utils.FatalError(err) } client.MakeIdentityFile(cf.IdentityFileOut, key, cf.IdentityFormat, authorities) fmt.Printf("\nThe certificate has been written to %s\n", cf.IdentityFileOut) return } // If the proxy is advertising that it supports Kubernetes, update kubeconfig. if tc.KubeProxyAddr != "" { if err := kubeclient.UpdateKubeconfig(tc); err != nil { utils.FatalError(err) } } // Regular login without -i flag. tc.SaveProfile(key.ProxyHost, "") // Print status to show information of the logged in user. Update the // command line flag (used to print status) for the proxy to make sure any // advertised settings are picked up. webProxyHost, _ := tc.WebProxyHostPort() cf.Proxy = webProxyHost onStatus(cf) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tsh/tsh.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tsh/tsh.go#L464-L495
go
train
// setupNoninteractiveClient sets up existing client to use // non-interactive authentication methods
func setupNoninteractiveClient(tc *client.TeleportClient, key *client.Key) error
// setupNoninteractiveClient sets up existing client to use // non-interactive authentication methods func setupNoninteractiveClient(tc *client.TeleportClient, key *client.Key) error
{ certUsername, err := key.CertUsername() if err != nil { return trace.Wrap(err) } tc.Username = certUsername // Extract and set the HostLogin to be the first principal. It doesn't // matter what the value is, but some valid principal has to be set // otherwise the certificate won't be validated. certPrincipals, err := key.CertPrincipals() if err != nil { return trace.Wrap(err) } if len(certPrincipals) == 0 { return trace.BadParameter("no principals found") } tc.HostLogin = certPrincipals[0] identityAuth, err := authFromIdentity(key) if err != nil { return trace.Wrap(err) } tc.TLS, err = key.ClientTLSConfig() if err != nil { return trace.Wrap(err) } tc.AuthMethods = []ssh.AuthMethod{identityAuth} tc.Interactive = false tc.SkipLocalAuth = true return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tsh/tsh.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tsh/tsh.go#L498-L586
go
train
// onLogout deletes a "session certificate" from ~/.tsh for a given proxy
func onLogout(cf *CLIConf)
// onLogout deletes a "session certificate" from ~/.tsh for a given proxy func onLogout(cf *CLIConf)
{ // Extract all clusters the user is currently logged into. active, available, err := client.Status("", "") if err != nil { utils.FatalError(err) return } profiles := append([]*client.ProfileStatus{}, available...) if active != nil { profiles = append(profiles, active) } // Extract the proxy name. proxyHost, _, err := net.SplitHostPort(cf.Proxy) if err != nil { proxyHost = cf.Proxy } switch { // Proxy and username for key to remove. case proxyHost != "" && cf.Username != "": tc, err := makeClient(cf, true) if err != nil { utils.FatalError(err) return } // Remove keys for this user from disk and running agent. err = tc.Logout() if err != nil { if trace.IsNotFound(err) { fmt.Printf("User %v already logged out from %v.\n", cf.Username, proxyHost) os.Exit(1) } utils.FatalError(err) return } // Get the address of the active Kubernetes proxy to find AuthInfos, // Clusters, and Contexts in kubeconfig. clusterName, _ := tc.KubeProxyHostPort() if tc.SiteName != "" { clusterName = fmt.Sprintf("%v.%v", tc.SiteName, clusterName) } // Remove Teleport related entries from kubeconfig. log.Debugf("Removing Teleport related entries for '%v' from kubeconfig.", clusterName) err = kubeclient.RemoveKubeconifg(tc, clusterName) if err != nil { utils.FatalError(err) return } fmt.Printf("Logged out %v from %v.\n", cf.Username, proxyHost) // Remove all keys. case proxyHost == "" && cf.Username == "": // The makeClient function requires a proxy. However this value is not used // because the user will be logged out from all proxies. Pass a dummy value // to allow creation of the TeleportClient. cf.Proxy = "dummy:1234" tc, err := makeClient(cf, true) if err != nil { utils.FatalError(err) return } // Remove Teleport related entries from kubeconfig for all clusters. for _, profile := range profiles { log.Debugf("Removing Teleport related entries for '%v' from kubeconfig.", profile.Cluster) err = kubeclient.RemoveKubeconifg(tc, profile.Cluster) if err != nil { utils.FatalError(err) return } } // Remove all keys from disk and the running agent. err = tc.LogoutAll() if err != nil { utils.FatalError(err) return } fmt.Printf("Logged out all users from all proxies.\n") default: fmt.Printf("Specify --proxy and --user to remove keys for specific user ") fmt.Printf("from a proxy or neither to log out all users from all proxies.\n") } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tsh/tsh.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tsh/tsh.go#L589-L637
go
train
// onListNodes executes 'tsh ls' command.
func onListNodes(cf *CLIConf)
// onListNodes executes 'tsh ls' command. func onListNodes(cf *CLIConf)
{ tc, err := makeClient(cf, true) if err != nil { utils.FatalError(err) } // Get list of all nodes in backend and sort by "Node Name". var nodes []services.Server err = client.RetryWithRelogin(cf.Context, tc, func() error { nodes, err = tc.ListNodes(cf.Context) return err }) if err != nil { utils.FatalError(err) } sort.Slice(nodes, func(i, j int) bool { return nodes[i].GetHostname() < nodes[j].GetHostname() }) switch cf.Verbose { // In verbose mode, print everything on a single line and include the Node // ID (UUID). Useful for machines that need to parse the output of "tsh ls". case true: t := asciitable.MakeTable([]string{"Node Name", "Node ID", "Address", "Labels"}) for _, n := range nodes { t.AddRow([]string{ n.GetHostname(), n.GetName(), n.GetAddr(), n.LabelsString(), }) } fmt.Println(t.AsBuffer().String()) // In normal mode chunk the labels and print two per line and allow multiple // lines per node. case false: t := asciitable.MakeTable([]string{"Node Name", "Address", "Labels"}) for _, n := range nodes { labelChunks := chunkLabels(n.GetAllLabels(), 2) for i, v := range labelChunks { var hostname string var addr string if i == 0 { hostname = n.GetHostname() addr = n.GetAddr() } t.AddRow([]string{hostname, addr, strings.Join(v, ", ")}) } } fmt.Println(t.AsBuffer().String()) } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tsh/tsh.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tsh/tsh.go#L641-L657
go
train
// chunkLabels breaks labels into sized chunks. Used to improve readability // of "tsh ls".
func chunkLabels(labels map[string]string, chunkSize int) [][]string
// chunkLabels breaks labels into sized chunks. Used to improve readability // of "tsh ls". func chunkLabels(labels map[string]string, chunkSize int) [][]string
{ // First sort labels so they always occur in the same order. sorted := make([]string, 0, len(labels)) for k, v := range labels { sorted = append(sorted, fmt.Sprintf("%v=%v", k, v)) } sort.Slice(sorted, func(i, j int) bool { return sorted[i] < sorted[j] }) // Then chunk labels into sized chunks. var chunks [][]string for chunkSize < len(sorted) { sorted, chunks = sorted[chunkSize:], append(chunks, sorted[0:chunkSize:chunkSize]) } chunks = append(chunks, sorted) return chunks }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tsh/tsh.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tsh/tsh.go#L660-L692
go
train
// onListClusters executes 'tsh clusters' command
func onListClusters(cf *CLIConf)
// onListClusters executes 'tsh clusters' command func onListClusters(cf *CLIConf)
{ tc, err := makeClient(cf, true) if err != nil { utils.FatalError(err) } proxyClient, err := tc.ConnectToProxy(cf.Context) if err != nil { utils.FatalError(err) } defer proxyClient.Close() var sites []services.Site err = client.RetryWithRelogin(cf.Context, tc, func() error { sites, err = proxyClient.GetSites() return err }) if err != nil { utils.FatalError(err) } var t asciitable.Table if cf.Quiet { t = asciitable.MakeHeadlessTable(2) } else { t = asciitable.MakeTable([]string{"Cluster Name", "Status"}) } if len(sites) == 0 { return } for _, site := range sites { t.AddRow([]string{site.Name, site.Status}) } fmt.Println(t.AsBuffer().String()) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tsh/tsh.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tsh/tsh.go#L695-L714
go
train
// onSSH executes 'tsh ssh' command
func onSSH(cf *CLIConf)
// onSSH executes 'tsh ssh' command func onSSH(cf *CLIConf)
{ tc, err := makeClient(cf, false) if err != nil { utils.FatalError(err) } tc.Stdin = os.Stdin err = client.RetryWithRelogin(cf.Context, tc, func() error { return tc.SSH(cf.Context, cf.RemoteCommand, cf.LocalExec) }) if err != nil { // exit with the same exit status as the failed command: if tc.ExitStatus != 0 { fmt.Fprintln(os.Stderr, utils.UserMessageFromError(err)) os.Exit(tc.ExitStatus) } else { utils.FatalError(err) } } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tsh/tsh.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tsh/tsh.go#L717-L747
go
train
// onBenchmark executes benchmark
func onBenchmark(cf *CLIConf)
// onBenchmark executes benchmark func onBenchmark(cf *CLIConf)
{ tc, err := makeClient(cf, false) if err != nil { utils.FatalError(err) } result, err := tc.Benchmark(cf.Context, client.Benchmark{ Command: cf.RemoteCommand, Threads: cf.BenchThreads, Duration: cf.BenchDuration, Rate: cf.BenchRate, }) if err != nil { fmt.Fprintln(os.Stderr, utils.UserMessageFromError(err)) os.Exit(255) } fmt.Printf("\n") fmt.Printf("* Requests originated: %v\n", result.RequestsOriginated) fmt.Printf("* Requests failed: %v\n", result.RequestsFailed) if result.LastError != nil { fmt.Printf("* Last error: %v\n", result.LastError) } fmt.Printf("\nHistogram\n\n") t := asciitable.MakeTable([]string{"Percentile", "Duration"}) for _, quantile := range []float64{25, 50, 75, 90, 95, 99, 100} { t.AddRow([]string{fmt.Sprintf("%v", quantile), fmt.Sprintf("%v ms", result.Histogram.ValueAtQuantile(quantile)), }) } io.Copy(os.Stdout, t.AsBuffer()) fmt.Printf("\n") }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tsh/tsh.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tsh/tsh.go#L750-L765
go
train
// onJoin executes 'ssh join' command
func onJoin(cf *CLIConf)
// onJoin executes 'ssh join' command func onJoin(cf *CLIConf)
{ tc, err := makeClient(cf, true) if err != nil { utils.FatalError(err) } sid, err := session.ParseID(cf.SessionID) if err != nil { utils.FatalError(fmt.Errorf("'%v' is not a valid session ID (must be GUID)", cf.SessionID)) } err = client.RetryWithRelogin(cf.Context, tc, func() error { return tc.Join(context.TODO(), cf.Namespace, *sid, nil) }) if err != nil { utils.FatalError(err) } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tsh/tsh.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tsh/tsh.go#L768-L785
go
train
// onSCP executes 'tsh scp' command
func onSCP(cf *CLIConf)
// onSCP executes 'tsh scp' command func onSCP(cf *CLIConf)
{ tc, err := makeClient(cf, false) if err != nil { utils.FatalError(err) } err = client.RetryWithRelogin(cf.Context, tc, func() error { return tc.SCP(context.TODO(), cf.CopySpec, int(cf.NodePort), cf.RecursiveCopy, cf.Quiet) }) if err != nil { // exit with the same exit status as the failed command: if tc.ExitStatus != 0 { fmt.Fprintln(os.Stderr, utils.UserMessageFromError(err)) os.Exit(tc.ExitStatus) } else { utils.FatalError(err) } } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tsh/tsh.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tsh/tsh.go#L789-L951
go
train
// makeClient takes the command-line configuration and constructs & returns // a fully configured TeleportClient object
func makeClient(cf *CLIConf, useProfileLogin bool) (tc *client.TeleportClient, err error)
// makeClient takes the command-line configuration and constructs & returns // a fully configured TeleportClient object func makeClient(cf *CLIConf, useProfileLogin bool) (tc *client.TeleportClient, err error)
{ // Parse OpenSSH style options. options, err := parseOptions(cf.Options) if err != nil { return nil, trace.Wrap(err) } // apply defaults if cf.MinsToLive == 0 { cf.MinsToLive = int32(defaults.CertDuration / time.Minute) } // split login & host hostLogin := cf.NodeLogin var labels map[string]string if cf.UserHost != "" { parts := strings.Split(cf.UserHost, "@") if len(parts) > 1 { hostLogin = parts[0] cf.UserHost = parts[1] } // see if remote host is specified as a set of labels if strings.Contains(cf.UserHost, "=") { labels, err = client.ParseLabelSpec(cf.UserHost) if err != nil { return nil, err } } } fPorts, err := client.ParsePortForwardSpec(cf.LocalForwardPorts) if err != nil { return nil, err } dPorts, err := client.ParseDynamicPortForwardSpec(cf.DynamicForwardedPorts) if err != nil { return nil, err } // 1: start with the defaults c := client.MakeDefaultConfig() // Look if a user identity was given via -i flag if cf.IdentityFileIn != "" { // Ignore local authentication methods when identity file is provided c.SkipLocalAuth = true var ( key *client.Key identityAuth ssh.AuthMethod expiryDate time.Time hostAuthFunc ssh.HostKeyCallback ) // read the ID file and create an "auth method" from it: key, hostAuthFunc, err = loadIdentity(cf.IdentityFileIn) if err != nil { return nil, trace.Wrap(err) } if hostAuthFunc != nil { c.HostKeyCallback = hostAuthFunc } else { return nil, trace.BadParameter("missing trusted certificate authorities in the identity, upgrade to newer version of tctl, export identity and try again") } certUsername, err := key.CertUsername() if err != nil { return nil, trace.Wrap(err) } log.Debugf("Extracted username %q from the identity file %v.", certUsername, cf.IdentityFileIn) c.Username = certUsername identityAuth, err = authFromIdentity(key) if err != nil { return nil, trace.Wrap(err) } c.AuthMethods = []ssh.AuthMethod{identityAuth} // check the expiration date expiryDate, _ = key.CertValidBefore() if expiryDate.Before(time.Now()) { fmt.Fprintf(os.Stderr, "WARNING: the certificate has expired on %v\n", expiryDate) } } else { // load profile. if no --proxy is given use ~/.tsh/profile symlink otherwise // fetch profile for exact proxy we are trying to connect to. err = c.LoadProfile("", cf.Proxy) if err != nil { fmt.Printf("WARNING: Failed to load tsh profile for %q: %v\n", cf.Proxy, err) } } // 3: override with the CLI flags if cf.Namespace != "" { c.Namespace = cf.Namespace } if cf.Username != "" { c.Username = cf.Username } // if proxy is set, and proxy is not equal to profile's // loaded addresses, override the values if cf.Proxy != "" && c.WebProxyAddr == "" { err = c.ParseProxyHost(cf.Proxy) if err != nil { return nil, trace.Wrap(err) } } if len(fPorts) > 0 { c.LocalForwardPorts = fPorts } if len(dPorts) > 0 { c.DynamicForwardedPorts = dPorts } if cf.SiteName != "" { c.SiteName = cf.SiteName } // if host logins stored in profiles must be ignored... if !useProfileLogin { c.HostLogin = "" } if hostLogin != "" { c.HostLogin = hostLogin } c.Host = cf.UserHost c.HostPort = int(cf.NodePort) c.Labels = labels c.KeyTTL = time.Minute * time.Duration(cf.MinsToLive) c.InsecureSkipVerify = cf.InsecureSkipVerify // If a TTY was requested, make sure to allocate it. Note this applies to // "exec" command because a shell always has a TTY allocated. if cf.Interactive || options.RequestTTY { c.Interactive = true } if !cf.NoCache { c.CachePolicy = &client.CachePolicy{} } // check version compatibility of the server and client c.CheckVersions = !cf.SkipVersionCheck // parse compatibility parameter certificateFormat, err := parseCertificateCompatibilityFlag(cf.Compatibility, cf.CertificateFormat) if err != nil { return nil, trace.Wrap(err) } c.CertificateFormat = certificateFormat // copy the authentication connector over if cf.AuthConnector != "" { c.AuthConnector = cf.AuthConnector } // If agent forwarding was specified on the command line enable it. if cf.ForwardAgent || options.ForwardAgent { c.ForwardAgent = true } // If the caller does not want to check host keys, pass in a insecure host // key checker. if options.StrictHostKeyChecking == false { c.HostKeyCallback = client.InsecureSkipHostKeyChecking } c.BindAddr = cf.BindAddr return client.NewClient(c) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tsh/tsh.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tsh/tsh.go#L972-L981
go
train
// refuseArgs helper makes sure that 'args' (list of CLI arguments) // does not contain anything other than command
func refuseArgs(command string, args []string)
// refuseArgs helper makes sure that 'args' (list of CLI arguments) // does not contain anything other than command func refuseArgs(command string, args []string)
{ for _, arg := range args { if arg == command || strings.HasPrefix(arg, "-") { continue } else { utils.FatalError(trace.BadParameter("unexpected argument: %s", arg)) } } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tsh/tsh.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tsh/tsh.go#L991-L1088
go
train
// loadIdentity loads the private key + certificate from a file // Returns: // - client key: user's private key+cert // - host auth callback: function to validate the host (may be null) // - error, if somthing happens when reading the identityf file // // If the "host auth callback" is not returned, user will be prompted to // trust the proxy server.
func loadIdentity(idFn string) (*client.Key, ssh.HostKeyCallback, error)
// loadIdentity loads the private key + certificate from a file // Returns: // - client key: user's private key+cert // - host auth callback: function to validate the host (may be null) // - error, if somthing happens when reading the identityf file // // If the "host auth callback" is not returned, user will be prompted to // trust the proxy server. func loadIdentity(idFn string) (*client.Key, ssh.HostKeyCallback, error)
{ log.Infof("Reading identity file: %v", idFn) f, err := os.Open(idFn) if err != nil { return nil, nil, trace.Wrap(err) } defer f.Close() var ( keyBuf bytes.Buffer state int // 0: not found, 1: found beginning, 2: found ending cert []byte caCerts [][]byte ) // read the identity file line by line: scanner := bufio.NewScanner(f) for scanner.Scan() { line := strings.TrimSpace(scanner.Text()) if state != 1 { if strings.HasPrefix(line, "ssh") { cert = []byte(line) continue } if strings.HasPrefix(line, "@cert-authority") { caCerts = append(caCerts, []byte(line)) continue } } if state == 0 && strings.HasPrefix(line, "-----BEGIN") { state = 1 keyBuf.WriteString(line) keyBuf.WriteRune('\n') continue } if state == 1 { keyBuf.WriteString(line) if strings.HasPrefix(line, "-----END") { state = 2 } else { keyBuf.WriteRune('\n') } } } // did not find the certificate in the file? look in a separate file with // -cert.pub prefix if len(cert) == 0 { certFn := idFn + "-cert.pub" log.Infof("Certificate not found in %s. Looking in %s.", idFn, certFn) cert, err = ioutil.ReadFile(certFn) if err != nil { return nil, nil, trace.Wrap(err) } } // validate both by parsing them: privKey, err := ssh.ParseRawPrivateKey(keyBuf.Bytes()) if err != nil { return nil, nil, trace.BadParameter("invalid identity: %s. %v", idFn, err) } signer, err := ssh.NewSignerFromKey(privKey) if err != nil { return nil, nil, trace.Wrap(err) } var hostAuthFunc ssh.HostKeyCallback = nil // validate CA (cluster) cert if len(caCerts) > 0 { var trustedKeys []ssh.PublicKey for _, caCert := range caCerts { _, _, publicKey, _, _, err := ssh.ParseKnownHosts(caCert) if err != nil { return nil, nil, trace.BadParameter("CA cert parsing error: %v. cert line :%v", err.Error(), string(caCert)) } trustedKeys = append(trustedKeys, publicKey) } // found CA cert in the indentity file? construct the host key checking function // and return it: hostAuthFunc = func(host string, a net.Addr, hostKey ssh.PublicKey) error { clusterCert, ok := hostKey.(*ssh.Certificate) if ok { hostKey = clusterCert.SignatureKey } for _, trustedKey := range trustedKeys { if sshutils.KeysEqual(trustedKey, hostKey) { return nil } } err = trace.AccessDenied("host %v is untrusted", host) log.Error(err) return err } } return &client.Key{ Priv: keyBuf.Bytes(), Pub: signer.PublicKey().Marshal(), Cert: cert, }, hostAuthFunc, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tsh/tsh.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tsh/tsh.go#L1091-L1097
go
train
// authFromIdentity returns a standard ssh.Authmethod for a given identity file
func authFromIdentity(k *client.Key) (ssh.AuthMethod, error)
// authFromIdentity returns a standard ssh.Authmethod for a given identity file func authFromIdentity(k *client.Key) (ssh.AuthMethod, error)
{ signer, err := sshutils.NewSigner(k.Priv, k.Cert) if err != nil { return nil, trace.Wrap(err) } return client.NewAuthMethodForCert(signer), nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tsh/tsh.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tsh/tsh.go#L1100-L1124
go
train
// onShow reads an identity file (a public SSH key or a cert) and dumps it to stdout
func onShow(cf *CLIConf)
// onShow reads an identity file (a public SSH key or a cert) and dumps it to stdout func onShow(cf *CLIConf)
{ key, _, err := loadIdentity(cf.IdentityFileIn) // unmarshal certificate bytes into a ssh.PublicKey cert, _, _, _, err := ssh.ParseAuthorizedKey(key.Cert) if err != nil { utils.FatalError(err) } // unmarshal private key bytes into a *rsa.PrivateKey priv, err := ssh.ParseRawPrivateKey(key.Priv) if err != nil { utils.FatalError(err) } pub, err := ssh.ParsePublicKey(key.Pub) if err != nil { utils.FatalError(err) } fmt.Printf("Cert: %#v\nPriv: %#v\nPub: %#v\n", cert, priv, pub) fmt.Printf("Fingerprint: %s\n", ssh.FingerprintSHA256(pub)) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tsh/tsh.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tsh/tsh.go#L1127-L1149
go
train
// printStatus prints the status of the profile.
func printStatus(p *client.ProfileStatus, isActive bool)
// printStatus prints the status of the profile. func printStatus(p *client.ProfileStatus, isActive bool)
{ var prefix string if isActive { prefix = "> " } else { prefix = " " } duration := p.ValidUntil.Sub(time.Now()) humanDuration := "EXPIRED" if duration.Nanoseconds() > 0 { humanDuration = fmt.Sprintf("valid for %v", duration.Round(time.Minute)) } fmt.Printf("%vProfile URL: %v\n", prefix, p.ProxyURL.String()) fmt.Printf(" Logged in as: %v\n", p.Username) if p.Cluster != "" { fmt.Printf(" Cluster: %v\n", p.Cluster) } fmt.Printf(" Roles: %v*\n", strings.Join(p.Roles, ", ")) fmt.Printf(" Logins: %v\n", strings.Join(p.Logins, ", ")) fmt.Printf(" Valid until: %v [%v]\n", p.ValidUntil, humanDuration) fmt.Printf(" Extensions: %v\n\n", strings.Join(p.Extensions, ", ")) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tsh/tsh.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tsh/tsh.go#L1153-L1165
go
train
// onStatus command shows which proxy the user is logged into and metadata // about the certificate.
func onStatus(cf *CLIConf)
// onStatus command shows which proxy the user is logged into and metadata // about the certificate. func onStatus(cf *CLIConf)
{ // Get the status of the active profile ~/.tsh/profile as well as the status // of any other proxies the user is logged into. profile, profiles, err := client.Status("", cf.Proxy) if err != nil { if trace.IsNotFound(err) { fmt.Printf("Not logged in.\n") return } utils.FatalError(err) } printProfiles(profile, profiles) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tsh/tsh.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tsh/tsh.go#L1189-L1195
go
train
// host is a utility function that extracts // host from the host:port pair, in case of any error // returns the original value
func host(in string) string
// host is a utility function that extracts // host from the host:port pair, in case of any error // returns the original value func host(in string) string
{ out, err := utils.Host(in) if err != nil { return in } return out }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/user.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/user.go#L74-L87
go
train
// NewUser creates new empty user
func NewUser(name string) (User, error)
// NewUser creates new empty user func NewUser(name string) (User, error)
{ u := &UserV2{ Kind: KindUser, Version: V2, Metadata: Metadata{ Name: name, Namespace: defaults.Namespace, }, } if err := u.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } return u, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/user.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/user.go#L91-L93
go
train
// IsSameProvider returns true if the provided connector has the // same ID/type as this one
func (r *ConnectorRef) IsSameProvider(other *ConnectorRef) bool
// IsSameProvider returns true if the provided connector has the // same ID/type as this one func (r *ConnectorRef) IsSameProvider(other *ConnectorRef) bool
{ return other != nil && other.Type == r.Type && other.ID == r.ID }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/user.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/user.go#L123-L132
go
train
// String returns human readable information about the user
func (c CreatedBy) String() string
// String returns human readable information about the user func (c CreatedBy) String() string
{ if c.User.Name == "" { return "system" } if c.Connector != nil { return fmt.Sprintf("%v connector %v for user %v at %v", c.Connector.Type, c.Connector.ID, c.Connector.Identity, utils.HumanTimeFormat(c.Time)) } return fmt.Sprintf("%v at %v", c.User.Name, c.Time) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/user.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/user.go#L154-L159
go
train
// Check checks parameters
func (la *LoginAttempt) Check() error
// Check checks parameters func (la *LoginAttempt) Check() error
{ if la.Time.IsZero() { return trace.BadParameter("missing parameter time") } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/user.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/user.go#L197-L199
go
train
// SetExpiry sets expiry time for the object
func (u *UserV2) SetExpiry(expires time.Time)
// SetExpiry sets expiry time for the object func (u *UserV2) SetExpiry(expires time.Time)
{ u.Metadata.SetExpiry(expires) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/user.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/user.go#L202-L204
go
train
// SetTTL sets Expires header using realtime clock
func (u *UserV2) SetTTL(clock clockwork.Clock, ttl time.Duration)
// SetTTL sets Expires header using realtime clock func (u *UserV2) SetTTL(clock clockwork.Clock, ttl time.Duration)
{ u.Metadata.SetTTL(clock, ttl) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/user.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/user.go#L217-L221
go
train
// WebSessionInfo returns web session information about user
func (u *UserV2) WebSessionInfo(allowedLogins []string) interface{}
// WebSessionInfo returns web session information about user func (u *UserV2) WebSessionInfo(allowedLogins []string) interface{}
{ out := u.V1() out.AllowedLogins = allowedLogins return *out }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/user.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/user.go#L229-L231
go
train
// SetTraits sets the trait map for this user used to populate role variables.
func (u *UserV2) SetTraits(traits map[string][]string)
// SetTraits sets the trait map for this user used to populate role variables. func (u *UserV2) SetTraits(traits map[string][]string)
{ u.Spec.Traits = traits }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/user.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/user.go#L234-L246
go
train
// CheckAndSetDefaults checks and set default values for any missing fields.
func (u *UserV2) CheckAndSetDefaults() error
// CheckAndSetDefaults checks and set default values for any missing fields. func (u *UserV2) CheckAndSetDefaults() error
{ err := u.Metadata.CheckAndSetDefaults() if err != nil { return trace.Wrap(err) } err = u.Check() if err != nil { return trace.Wrap(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/user.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/user.go#L249-L257
go
train
// V1 converts UserV2 to UserV1 format
func (u *UserV2) V1() *UserV1
// V1 converts UserV2 to UserV1 format func (u *UserV2) V1() *UserV1
{ return &UserV1{ Name: u.Metadata.Name, OIDCIdentities: u.Spec.OIDCIdentities, Status: u.Spec.Status, Expires: u.Spec.Expires, CreatedBy: u.Spec.CreatedBy, } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/user.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/user.go#L316-L348
go
train
// Equals checks if user equals to another
func (u *UserV2) Equals(other User) bool
// Equals checks if user equals to another func (u *UserV2) Equals(other User) bool
{ if u.Metadata.Name != other.GetName() { return false } otherIdentities := other.GetOIDCIdentities() if len(u.Spec.OIDCIdentities) != len(otherIdentities) { return false } for i := range u.Spec.OIDCIdentities { if !u.Spec.OIDCIdentities[i].Equals(&otherIdentities[i]) { return false } } otherSAMLIdentities := other.GetSAMLIdentities() if len(u.Spec.SAMLIdentities) != len(otherSAMLIdentities) { return false } for i := range u.Spec.SAMLIdentities { if !u.Spec.SAMLIdentities[i].Equals(&otherSAMLIdentities[i]) { return false } } otherGithubIdentities := other.GetGithubIdentities() if len(u.Spec.GithubIdentities) != len(otherGithubIdentities) { return false } for i := range u.Spec.GithubIdentities { if !u.Spec.GithubIdentities[i].Equals(&otherGithubIdentities[i]) { return false } } return true }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/user.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/user.go#L352-L357
go
train
// Expiry returns expiry time for temporary users. Prefer expires from // metadata, if it does not exist, fall back to expires in spec.
func (u *UserV2) Expiry() time.Time
// Expiry returns expiry time for temporary users. Prefer expires from // metadata, if it does not exist, fall back to expires in spec. func (u *UserV2) Expiry() time.Time
{ if u.Metadata.Expires != nil && !u.Metadata.Expires.IsZero() { return *u.Metadata.Expires } return u.Spec.Expires }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/user.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/user.go#L360-L362
go
train
// SetRoles sets a list of roles for user
func (u *UserV2) SetRoles(roles []string)
// SetRoles sets a list of roles for user func (u *UserV2) SetRoles(roles []string)
{ u.Spec.Roles = utils.Deduplicate(roles) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/user.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/user.go#L390-L397
go
train
// AddRole adds a role to user's role list
func (u *UserV2) AddRole(name string)
// AddRole adds a role to user's role list func (u *UserV2) AddRole(name string)
{ for _, r := range u.Spec.Roles { if r == name { return } } u.Spec.Roles = append(u.Spec.Roles, name) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/user.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/user.go#L410-L426
go
train
// Check checks validity of all parameters
func (u *UserV2) Check() error
// Check checks validity of all parameters func (u *UserV2) Check() error
{ if u.Kind == "" { return trace.BadParameter("user kind is not set") } if u.Version == "" { return trace.BadParameter("user version is not set") } if u.Metadata.Name == "" { return trace.BadParameter("user name cannot be empty") } for _, id := range u.Spec.OIDCIdentities { if err := id.Check(); err != nil { return trace.Wrap(err) } } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/user.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/user.go#L459-L475
go
train
// Check checks validity of all parameters
func (u *UserV1) Check() error
// Check checks validity of all parameters func (u *UserV1) Check() error
{ if u.Name == "" { return trace.BadParameter("user name cannot be empty") } for _, login := range u.AllowedLogins { _, _, err := parse.IsRoleVariable(login) if err == nil { return trace.BadParameter("role variables not allowed in allowed logins") } } for _, id := range u.OIDCIdentities { if err := id.Check(); err != nil { return trace.Wrap(err) } } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/user.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/user.go#L483-L503
go
train
//V2 converts UserV1 to UserV2 format
func (u *UserV1) V2() *UserV2
//V2 converts UserV1 to UserV2 format func (u *UserV1) V2() *UserV2
{ return &UserV2{ Kind: KindUser, Version: V2, Metadata: Metadata{ Name: u.Name, Namespace: defaults.Namespace, }, Spec: UserSpecV2{ OIDCIdentities: u.OIDCIdentities, Status: u.Status, Expires: u.Expires, CreatedBy: u.CreatedBy, Roles: u.Roles, Traits: map[string][]string{ teleport.TraitLogins: u.AllowedLogins, teleport.TraitKubeGroups: u.KubeGroups, }, }, } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/user.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/user.go#L536-L544
go
train
// GetRoleSchema returns role schema with optionally injected // schema for extensions
func GetUserSchema(extensionSchema string) string
// GetRoleSchema returns role schema with optionally injected // schema for extensions func GetUserSchema(extensionSchema string) string
{ var userSchema string if extensionSchema == "" { userSchema = fmt.Sprintf(UserSpecV2SchemaTemplate, ExternalIdentitySchema, ExternalIdentitySchema, ExternalIdentitySchema, LoginStatusSchema, CreatedBySchema, ``) } else { userSchema = fmt.Sprintf(UserSpecV2SchemaTemplate, ExternalIdentitySchema, ExternalIdentitySchema, ExternalIdentitySchema, LoginStatusSchema, CreatedBySchema, ", "+extensionSchema) } return fmt.Sprintf(V2SchemaTemplate, MetadataSchema, userSchema, DefaultDefinitions) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/user.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/user.go#L549-L595
go
train
// UnmarshalUser unmarshals user from JSON
func (*TeleportUserMarshaler) UnmarshalUser(bytes []byte, opts ...MarshalOption) (User, error)
// UnmarshalUser unmarshals user from JSON func (*TeleportUserMarshaler) UnmarshalUser(bytes []byte, opts ...MarshalOption) (User, error)
{ var h ResourceHeader err := json.Unmarshal(bytes, &h) if err != nil { return nil, trace.Wrap(err) } cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } switch h.Version { case "": var u UserV1 err := json.Unmarshal(bytes, &u) if err != nil { return nil, trace.Wrap(err) } return u.V2(), nil case V2: var u UserV2 if cfg.SkipValidation { if err := utils.FastUnmarshal(bytes, &u); err != nil { return nil, trace.BadParameter(err.Error()) } } else { if err := utils.UnmarshalWithSchema(GetUserSchema(""), &u, bytes); err != nil { return nil, trace.BadParameter(err.Error()) } } if err := u.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } if cfg.ID != 0 { u.SetResourceID(cfg.ID) } if !cfg.Expires.IsZero() { u.SetExpiry(cfg.Expires) } return &u, nil } return nil, trace.BadParameter("user resource version %v is not supported", h.Version) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/user.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/user.go#L603-L640
go
train
// MarshalUser marshalls user into JSON
func (*TeleportUserMarshaler) MarshalUser(u User, opts ...MarshalOption) ([]byte, error)
// MarshalUser marshalls user into JSON func (*TeleportUserMarshaler) MarshalUser(u User, opts ...MarshalOption) ([]byte, error)
{ cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } type userv1 interface { V1() *UserV1 } type userv2 interface { V2() *UserV2 } version := cfg.GetVersion() switch version { case V1: v, ok := u.(userv1) if !ok { return nil, trace.BadParameter("don't know how to marshal %v", V1) } return json.Marshal(v.V1()) case V2: v, ok := u.(userv2) if !ok { return nil, trace.BadParameter("don't know how to marshal %v", V2) } v2 := v.V2() if !cfg.PreserveResourceID { // avoid modifying the original object // to prevent unexpected data races copy := *v2 copy.SetResourceID(0) v2 = &copy } return utils.FastMarshal(v2) default: return nil, trace.BadParameter("version %v is not supported", version) } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/wrap.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/wrap.go#L47-L51
go
train
// GetReadError returns error to be returned by // read backend operations
func (s *Wrapper) GetReadError() error
// GetReadError returns error to be returned by // read backend operations func (s *Wrapper) GetReadError() error
{ s.RLock() defer s.RUnlock() return s.readErr }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/wrap.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/wrap.go#L54-L58
go
train
// SetReadError sets error to be returned by read backend operations
func (s *Wrapper) SetReadError(err error)
// SetReadError sets error to be returned by read backend operations func (s *Wrapper) SetReadError(err error)
{ s.Lock() defer s.Unlock() s.readErr = err }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/wrap.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/wrap.go#L67-L72
go
train
// GetRange returns query range
func (s *Wrapper) GetRange(ctx context.Context, startKey []byte, endKey []byte, limit int) (*GetResult, error)
// GetRange returns query range func (s *Wrapper) GetRange(ctx context.Context, startKey []byte, endKey []byte, limit int) (*GetResult, error)
{ if err := s.GetReadError(); err != nil { return nil, trace.Wrap(err) } return s.backend.GetRange(ctx, startKey, endKey, limit) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/wrap.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/wrap.go#L86-L88
go
train
// Update updates value in the backend
func (s *Wrapper) Update(ctx context.Context, i Item) (*Lease, error)
// Update updates value in the backend func (s *Wrapper) Update(ctx context.Context, i Item) (*Lease, error)
{ return s.backend.Update(ctx, i) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/wrap.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/wrap.go#L91-L96
go
train
// Get returns a single item or not found error
func (s *Wrapper) Get(ctx context.Context, key []byte) (*Item, error)
// Get returns a single item or not found error func (s *Wrapper) Get(ctx context.Context, key []byte) (*Item, error)
{ if err := s.GetReadError(); err != nil { return nil, trace.Wrap(err) } return s.backend.Get(ctx, key) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/wrap.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/wrap.go#L100-L102
go
train
// CompareAndSwap compares item with existing item // and replaces is with replaceWith item
func (s *Wrapper) CompareAndSwap(ctx context.Context, expected Item, replaceWith Item) (*Lease, error)
// CompareAndSwap compares item with existing item // and replaces is with replaceWith item func (s *Wrapper) CompareAndSwap(ctx context.Context, expected Item, replaceWith Item) (*Lease, error)
{ return s.backend.CompareAndSwap(ctx, expected, replaceWith) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/wrap.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/wrap.go#L105-L107
go
train
// Delete deletes item by key
func (s *Wrapper) Delete(ctx context.Context, key []byte) error
// Delete deletes item by key func (s *Wrapper) Delete(ctx context.Context, key []byte) error
{ return s.backend.Delete(ctx, key) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/wrap.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/wrap.go#L110-L112
go
train
// DeleteRange deletes range of items
func (s *Wrapper) DeleteRange(ctx context.Context, startKey []byte, endKey []byte) error
// DeleteRange deletes range of items func (s *Wrapper) DeleteRange(ctx context.Context, startKey []byte, endKey []byte) error
{ return s.backend.DeleteRange(ctx, startKey, endKey) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/wrap.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/wrap.go#L118-L120
go
train
// KeepAlive keeps object from expiring, updates lease on the existing object, // expires contains the new expiry to set on the lease, // some backends may ignore expires based on the implementation // in case if the lease managed server side
func (s *Wrapper) KeepAlive(ctx context.Context, lease Lease, expires time.Time) error
// KeepAlive keeps object from expiring, updates lease on the existing object, // expires contains the new expiry to set on the lease, // some backends may ignore expires based on the implementation // in case if the lease managed server side func (s *Wrapper) KeepAlive(ctx context.Context, lease Lease, expires time.Time) error
{ return s.backend.KeepAlive(ctx, lease, expires) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/wrap.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/wrap.go#L123-L128
go
train
// NewWatcher returns a new event watcher
func (s *Wrapper) NewWatcher(ctx context.Context, watch Watch) (Watcher, error)
// NewWatcher returns a new event watcher func (s *Wrapper) NewWatcher(ctx context.Context, watch Watch) (Watcher, error)
{ if err := s.GetReadError(); err != nil { return nil, trace.Wrap(err) } return s.backend.NewWatcher(ctx, watch) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/users.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L54-L57
go
train
// DeleteAllUsers deletes all users
func (s *IdentityService) DeleteAllUsers() error
// DeleteAllUsers deletes all users func (s *IdentityService) DeleteAllUsers() error
{ startKey := backend.Key(webPrefix, usersPrefix) return s.DeleteRange(context.TODO(), startKey, backend.RangeEnd(startKey)) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/users.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L60-L79
go
train
// GetUsers returns a list of users registered with the local auth server
func (s *IdentityService) GetUsers() ([]services.User, error)
// GetUsers returns a list of users registered with the local auth server func (s *IdentityService) GetUsers() ([]services.User, error)
{ startKey := backend.Key(webPrefix, usersPrefix) result, err := s.GetRange(context.TODO(), startKey, backend.RangeEnd(startKey), backend.NoLimit) if err != nil { return nil, trace.Wrap(err) } var out []services.User for _, item := range result.Items { if !bytes.HasSuffix(item.Key, []byte(paramsPrefix)) { continue } u, err := services.GetUserMarshaler().UnmarshalUser( item.Value, services.WithResourceID(item.ID), services.WithExpires(item.Expires)) if err != nil { return nil, trace.Wrap(err) } out = append(out, u) } return out, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/users.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L82-L100
go
train
// CreateUser creates user if it does not exist
func (s *IdentityService) CreateUser(user services.User) error
// CreateUser creates user if it does not exist func (s *IdentityService) CreateUser(user services.User) error
{ if err := user.Check(); err != nil { return trace.Wrap(err) } value, err := services.GetUserMarshaler().MarshalUser(user) if err != nil { return trace.Wrap(err) } item := backend.Item{ Key: backend.Key(webPrefix, usersPrefix, user.GetName(), paramsPrefix), Value: value, Expires: user.Expiry(), } _, err = s.Create(context.TODO(), item) if err != nil { return trace.Wrap(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/users.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L125-L139
go
train
// GetUser returns a user by name
func (s *IdentityService) GetUser(user string) (services.User, error)
// GetUser returns a user by name func (s *IdentityService) GetUser(user string) (services.User, error)
{ if user == "" { return nil, trace.BadParameter("missing user name") } item, err := s.Get(context.TODO(), backend.Key(webPrefix, usersPrefix, user, paramsPrefix)) if err != nil { return nil, trace.NotFound("user %q is not found", user) } u, err := services.GetUserMarshaler().UnmarshalUser( item.Value, services.WithResourceID(item.ID), services.WithExpires(item.Expires)) if err != nil { return nil, trace.Wrap(err) } return u, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/users.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L143-L156
go
train
// GetUserByOIDCIdentity returns a user by it's specified OIDC Identity, returns first // user specified with this identity
func (s *IdentityService) GetUserByOIDCIdentity(id services.ExternalIdentity) (services.User, error)
// GetUserByOIDCIdentity returns a user by it's specified OIDC Identity, returns first // user specified with this identity func (s *IdentityService) GetUserByOIDCIdentity(id services.ExternalIdentity) (services.User, error)
{ users, err := s.GetUsers() if err != nil { return nil, trace.Wrap(err) } for _, u := range users { for _, uid := range u.GetOIDCIdentities() { if uid.Equals(&id) { return u, nil } } } return nil, trace.NotFound("user with identity %q not found", &id) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/users.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L192-L200
go
train
// DeleteUser deletes a user with all the keys from the backend
func (s *IdentityService) DeleteUser(user string) error
// DeleteUser deletes a user with all the keys from the backend func (s *IdentityService) DeleteUser(user string) error
{ _, err := s.GetUser(user) if err != nil { return trace.Wrap(err) } startKey := backend.Key(webPrefix, usersPrefix, user) err = s.DeleteRange(context.TODO(), startKey, backend.RangeEnd(startKey)) return trace.Wrap(err) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/users.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L203-L227
go
train
// UpsertPasswordHash upserts user password hash
func (s *IdentityService) UpsertPasswordHash(username string, hash []byte) error
// UpsertPasswordHash upserts user password hash func (s *IdentityService) UpsertPasswordHash(username string, hash []byte) error
{ userPrototype, err := services.NewUser(username) if err != nil { return trace.Wrap(err) } user, err := services.GetUserMarshaler().GenerateUser(userPrototype) if err != nil { return trace.Wrap(err) } err = s.CreateUser(user) if err != nil { if !trace.IsAlreadyExists(err) { return trace.Wrap(err) } } item := backend.Item{ Key: backend.Key(webPrefix, usersPrefix, username, pwdPrefix), Value: hash, } _, err = s.Put(context.TODO(), item) if err != nil { return trace.Wrap(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/users.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L246-L266
go
train
// UpsertHOTP upserts HOTP state for user // Deprecated: HOTP use is deprecated, use UpsertTOTP instead.
func (s *IdentityService) UpsertHOTP(user string, otp *hotp.HOTP) error
// UpsertHOTP upserts HOTP state for user // Deprecated: HOTP use is deprecated, use UpsertTOTP instead. func (s *IdentityService) UpsertHOTP(user string, otp *hotp.HOTP) error
{ if user == "" { return trace.BadParameter("missing user name") } bytes, err := hotp.Marshal(otp) if err != nil { return trace.Wrap(err) } item := backend.Item{ Key: backend.Key(webPrefix, usersPrefix, user, hotpPrefix), Value: bytes, } _, err = s.Put(context.TODO(), item) if err != nil { return trace.Wrap(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/users.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L270-L289
go
train
// GetHOTP gets HOTP token state for a user // Deprecated: HOTP use is deprecated, use GetTOTP instead.
func (s *IdentityService) GetHOTP(user string) (*hotp.HOTP, error)
// GetHOTP gets HOTP token state for a user // Deprecated: HOTP use is deprecated, use GetTOTP instead. func (s *IdentityService) GetHOTP(user string) (*hotp.HOTP, error)
{ if user == "" { return nil, trace.BadParameter("missing user name") } item, err := s.Get(context.TODO(), backend.Key(webPrefix, usersPrefix, user, hotpPrefix)) if err != nil { if trace.IsNotFound(err) { return nil, trace.NotFound("user %q is not found", user) } return nil, trace.Wrap(err) } otp, err := hotp.Unmarshal(item.Value) if err != nil { return nil, trace.Wrap(err) } return otp, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/users.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L292-L308
go
train
// UpsertTOTP upserts TOTP secret key for a user that can be used to generate and validate tokens.
func (s *IdentityService) UpsertTOTP(user string, secretKey string) error
// UpsertTOTP upserts TOTP secret key for a user that can be used to generate and validate tokens. func (s *IdentityService) UpsertTOTP(user string, secretKey string) error
{ if user == "" { return trace.BadParameter("missing user name") } item := backend.Item{ Key: backend.Key(webPrefix, usersPrefix, user, totpPrefix), Value: []byte(secretKey), } _, err := s.Put(context.TODO(), item) if err != nil { return trace.Wrap(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/users.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L311-L325
go
train
// GetTOTP returns the secret key used by the TOTP algorithm to validate tokens
func (s *IdentityService) GetTOTP(user string) (string, error)
// GetTOTP returns the secret key used by the TOTP algorithm to validate tokens func (s *IdentityService) GetTOTP(user string) (string, error)
{ if user == "" { return "", trace.BadParameter("missing user name") } item, err := s.Get(context.TODO(), backend.Key(webPrefix, usersPrefix, user, totpPrefix)) if err != nil { if trace.IsNotFound(err) { return "", trace.NotFound("user %q is not found", user) } return "", trace.Wrap(err) } return string(item.Value), nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/users.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L329-L343
go
train
// UpsertUsedTOTPToken upserts a TOTP token to the backend so it can't be used again // during the 30 second window it's valid.
func (s *IdentityService) UpsertUsedTOTPToken(user string, otpToken string) error
// UpsertUsedTOTPToken upserts a TOTP token to the backend so it can't be used again // during the 30 second window it's valid. func (s *IdentityService) UpsertUsedTOTPToken(user string, otpToken string) error
{ if user == "" { return trace.BadParameter("missing user name") } item := backend.Item{ Key: backend.Key(webPrefix, usersPrefix, user, usedTOTPPrefix), Value: []byte(otpToken), Expires: s.Clock().Now().UTC().Add(usedTOTPTTL), } _, err := s.Put(context.TODO(), item) if err != nil { return trace.Wrap(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/users.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L363-L368
go
train
// DeleteUsedTOTPToken removes the used token from the backend. This should only // be used during tests.
func (s *IdentityService) DeleteUsedTOTPToken(user string) error
// DeleteUsedTOTPToken removes the used token from the backend. This should only // be used during tests. func (s *IdentityService) DeleteUsedTOTPToken(user string) error
{ if user == "" { return trace.BadParameter("missing user name") } return s.Delete(context.TODO(), backend.Key(webPrefix, usersPrefix, user, usedTOTPPrefix)) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/users.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L373-L388
go
train
// UpsertWebSession updates or inserts a web session for a user and session id // the session will be created with bearer token expiry time TTL, because // it is expected to be extended by the client before then
func (s *IdentityService) UpsertWebSession(user, sid string, session services.WebSession) error
// UpsertWebSession updates or inserts a web session for a user and session id // the session will be created with bearer token expiry time TTL, because // it is expected to be extended by the client before then func (s *IdentityService) UpsertWebSession(user, sid string, session services.WebSession) error
{ session.SetUser(user) session.SetName(sid) value, err := services.GetWebSessionMarshaler().MarshalWebSession(session) if err != nil { return trace.Wrap(err) } sessionMetadata := session.GetMetadata() item := backend.Item{ Key: backend.Key(webPrefix, usersPrefix, user, sessionsPrefix, sid), Value: value, Expires: backend.EarliestExpiry(session.GetBearerTokenExpiryTime(), sessionMetadata.Expiry()), } _, err = s.Put(context.TODO(), item) return trace.Wrap(err) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/users.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L391-L406
go
train
// AddUserLoginAttempt logs user login attempt
func (s *IdentityService) AddUserLoginAttempt(user string, attempt services.LoginAttempt, ttl time.Duration) error
// AddUserLoginAttempt logs user login attempt func (s *IdentityService) AddUserLoginAttempt(user string, attempt services.LoginAttempt, ttl time.Duration) error
{ if err := attempt.Check(); err != nil { return trace.Wrap(err) } value, err := json.Marshal(attempt) if err != nil { return trace.Wrap(err) } item := backend.Item{ Key: backend.Key(webPrefix, usersPrefix, user, attemptsPrefix, uuid.New()), Value: value, Expires: backend.Expiry(s.Clock(), ttl), } _, err = s.Put(context.TODO(), item) return trace.Wrap(err) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/users.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L409-L425
go
train
// GetUserLoginAttempts returns user login attempts
func (s *IdentityService) GetUserLoginAttempts(user string) ([]services.LoginAttempt, error)
// GetUserLoginAttempts returns user login attempts func (s *IdentityService) GetUserLoginAttempts(user string) ([]services.LoginAttempt, error)
{ startKey := backend.Key(webPrefix, usersPrefix, user, attemptsPrefix) result, err := s.GetRange(context.TODO(), startKey, backend.RangeEnd(startKey), backend.NoLimit) if err != nil { return nil, trace.Wrap(err) } out := make([]services.LoginAttempt, len(result.Items)) for i, item := range result.Items { var a services.LoginAttempt if err := json.Unmarshal(item.Value, &a); err != nil { return nil, trace.Wrap(err) } out[i] = a } sort.Sort(services.SortedLoginAttempts(out)) return out, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/users.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L429-L439
go
train
// DeleteUserLoginAttempts removes all login attempts of a user. Should be // called after successful login.
func (s *IdentityService) DeleteUserLoginAttempts(user string) error
// DeleteUserLoginAttempts removes all login attempts of a user. Should be // called after successful login. func (s *IdentityService) DeleteUserLoginAttempts(user string) error
{ if user == "" { return trace.BadParameter("missing username") } startKey := backend.Key(webPrefix, usersPrefix, user, attemptsPrefix) err := s.DeleteRange(context.TODO(), startKey, backend.RangeEnd(startKey)) if err != nil { return trace.Wrap(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/users.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L442-L462
go
train
// GetWebSession returns a web session state for a given user and session id
func (s *IdentityService) GetWebSession(user, sid string) (services.WebSession, error)
// GetWebSession returns a web session state for a given user and session id func (s *IdentityService) GetWebSession(user, sid string) (services.WebSession, error)
{ if user == "" { return nil, trace.BadParameter("missing username") } if sid == "" { return nil, trace.BadParameter("missing session id") } item, err := s.Get(context.TODO(), backend.Key(webPrefix, usersPrefix, user, sessionsPrefix, sid)) if err != nil { return nil, trace.Wrap(err) } session, err := services.GetWebSessionMarshaler().UnmarshalWebSession(item.Value) if err != nil { return nil, trace.Wrap(err) } // this is for backwards compatibility to ensure we // always have these values session.SetUser(user) session.SetName(sid) return session, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/users.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L465-L474
go
train
// DeleteWebSession deletes web session from the storage
func (s *IdentityService) DeleteWebSession(user, sid string) error
// DeleteWebSession deletes web session from the storage func (s *IdentityService) DeleteWebSession(user, sid string) error
{ if user == "" { return trace.BadParameter("missing username") } if sid == "" { return trace.BadParameter("missing session id") } err := s.Delete(context.TODO(), backend.Key(webPrefix, usersPrefix, user, sessionsPrefix, sid)) return trace.Wrap(err) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/users.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L477-L496
go
train
// UpsertPassword upserts new password hash into a backend.
func (s *IdentityService) UpsertPassword(user string, password []byte) error
// UpsertPassword upserts new password hash into a backend. func (s *IdentityService) UpsertPassword(user string, password []byte) error
{ if user == "" { return trace.BadParameter("missing username") } err := services.VerifyPassword(password) if err != nil { return trace.Wrap(err) } hash, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost) if err != nil { return trace.Wrap(err) } err = s.UpsertPasswordHash(user, hash) if err != nil { return trace.Wrap(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/users.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L499-L519
go
train
// UpsertSignupToken upserts signup token - one time token that lets user to create a user account
func (s *IdentityService) UpsertSignupToken(token string, tokenData services.SignupToken, ttl time.Duration) error
// UpsertSignupToken upserts signup token - one time token that lets user to create a user account func (s *IdentityService) UpsertSignupToken(token string, tokenData services.SignupToken, ttl time.Duration) error
{ if ttl < time.Second || ttl > defaults.MaxSignupTokenTTL { ttl = defaults.MaxSignupTokenTTL } tokenData.Expires = time.Now().UTC().Add(ttl) value, err := json.Marshal(tokenData) if err != nil { return trace.Wrap(err) } item := backend.Item{ Key: backend.Key(userTokensPrefix, token), Value: value, Expires: tokenData.Expires, } _, err = s.Put(context.TODO(), item) if err != nil { return trace.Wrap(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/users.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L522-L536
go
train
// GetSignupToken returns signup token data
func (s *IdentityService) GetSignupToken(token string) (*services.SignupToken, error)
// GetSignupToken returns signup token data func (s *IdentityService) GetSignupToken(token string) (*services.SignupToken, error)
{ if token == "" { return nil, trace.BadParameter("missing token") } item, err := s.Get(context.TODO(), backend.Key(userTokensPrefix, token)) if err != nil { return nil, trace.Wrap(err) } var signupToken services.SignupToken err = json.Unmarshal(item.Value, &signupToken) if err != nil { return nil, trace.Wrap(err) } return &signupToken, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/users.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L539-L555
go
train
// GetSignupTokens returns all non-expired user tokens
func (s *IdentityService) GetSignupTokens() ([]services.SignupToken, error)
// GetSignupTokens returns all non-expired user tokens func (s *IdentityService) GetSignupTokens() ([]services.SignupToken, error)
{ startKey := backend.Key(userTokensPrefix) result, err := s.GetRange(context.TODO(), startKey, backend.RangeEnd(startKey), backend.NoLimit) if err != nil { return nil, trace.Wrap(err) } tokens := make([]services.SignupToken, len(result.Items)) for i, item := range result.Items { var signupToken services.SignupToken err = json.Unmarshal(item.Value, &signupToken) if err != nil { return nil, trace.Wrap(err) } tokens[i] = signupToken } return tokens, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/users.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L558-L564
go
train
// DeleteSignupToken deletes signup token from the storage
func (s *IdentityService) DeleteSignupToken(token string) error
// DeleteSignupToken deletes signup token from the storage func (s *IdentityService) DeleteSignupToken(token string) error
{ if token == "" { return trace.BadParameter("missing parameter token") } err := s.Delete(context.TODO(), backend.Key(userTokensPrefix, token)) return trace.Wrap(err) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/users.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L746-L765
go
train
// UpsertOIDCConnector upserts OIDC Connector
func (s *IdentityService) UpsertOIDCConnector(connector services.OIDCConnector) error
// UpsertOIDCConnector upserts OIDC Connector func (s *IdentityService) UpsertOIDCConnector(connector services.OIDCConnector) error
{ if err := connector.Check(); err != nil { return trace.Wrap(err) } value, err := services.GetOIDCConnectorMarshaler().MarshalOIDCConnector(connector) if err != nil { return trace.Wrap(err) } item := backend.Item{ Key: backend.Key(webPrefix, connectorsPrefix, oidcPrefix, connectorsPrefix, connector.GetName()), Value: value, Expires: connector.Expiry(), ID: connector.GetResourceID(), } _, err = s.Put(context.TODO(), item) if err != nil { return trace.Wrap(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/users.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L778-L798
go
train
// GetOIDCConnector returns OIDC connector data, parameter 'withSecrets' // includes or excludes client secret from return results
func (s *IdentityService) GetOIDCConnector(name string, withSecrets bool) (services.OIDCConnector, error)
// GetOIDCConnector returns OIDC connector data, parameter 'withSecrets' // includes or excludes client secret from return results func (s *IdentityService) GetOIDCConnector(name string, withSecrets bool) (services.OIDCConnector, error)
{ if name == "" { return nil, trace.BadParameter("missing parameter name") } item, err := s.Get(context.TODO(), backend.Key(webPrefix, connectorsPrefix, oidcPrefix, connectorsPrefix, name)) if err != nil { if trace.IsNotFound(err) { return nil, trace.NotFound("OpenID connector '%v' is not configured", name) } return nil, trace.Wrap(err) } conn, err := services.GetOIDCConnectorMarshaler().UnmarshalOIDCConnector(item.Value, services.WithExpires(item.Expires)) if err != nil { return nil, trace.Wrap(err) } if !withSecrets { conn.SetClientSecret("") } return conn, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/users.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L801-L820
go
train
// GetOIDCConnectors returns registered connectors, withSecrets adds or removes client secret from return results
func (s *IdentityService) GetOIDCConnectors(withSecrets bool) ([]services.OIDCConnector, error)
// GetOIDCConnectors returns registered connectors, withSecrets adds or removes client secret from return results func (s *IdentityService) GetOIDCConnectors(withSecrets bool) ([]services.OIDCConnector, error)
{ startKey := backend.Key(webPrefix, connectorsPrefix, oidcPrefix, connectorsPrefix) result, err := s.GetRange(context.TODO(), startKey, backend.RangeEnd(startKey), backend.NoLimit) if err != nil { return nil, trace.Wrap(err) } connectors := make([]services.OIDCConnector, len(result.Items)) for i, item := range result.Items { conn, err := services.GetOIDCConnectorMarshaler().UnmarshalOIDCConnector( item.Value, services.WithExpires(item.Expires)) if err != nil { return nil, trace.Wrap(err) } if !withSecrets { conn.SetClientSecret("") } connectors[i] = conn } return connectors, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/users.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L823-L841
go
train
// CreateOIDCAuthRequest creates new auth request
func (s *IdentityService) CreateOIDCAuthRequest(req services.OIDCAuthRequest, ttl time.Duration) error
// CreateOIDCAuthRequest creates new auth request func (s *IdentityService) CreateOIDCAuthRequest(req services.OIDCAuthRequest, ttl time.Duration) error
{ if err := req.Check(); err != nil { return trace.Wrap(err) } value, err := json.Marshal(req) if err != nil { return trace.Wrap(err) } item := backend.Item{ Key: backend.Key(webPrefix, connectorsPrefix, oidcPrefix, requestsPrefix, req.StateToken), Value: value, Expires: backend.Expiry(s.Clock(), ttl), } _, err = s.Create(context.TODO(), item) if err != nil { return trace.Wrap(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/users.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L860-L878
go
train
// CreateSAMLConnector creates SAML Connector
func (s *IdentityService) CreateSAMLConnector(connector services.SAMLConnector) error
// CreateSAMLConnector creates SAML Connector func (s *IdentityService) CreateSAMLConnector(connector services.SAMLConnector) error
{ if err := connector.CheckAndSetDefaults(); err != nil { return trace.Wrap(err) } value, err := services.GetSAMLConnectorMarshaler().MarshalSAMLConnector(connector) if err != nil { return trace.Wrap(err) } item := backend.Item{ Key: backend.Key(webPrefix, connectorsPrefix, samlPrefix, connectorsPrefix, connector.GetName()), Value: value, Expires: connector.Expiry(), } _, err = s.Create(context.TODO(), item) if err != nil { return trace.Wrap(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/users.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L902-L908
go
train
// DeleteSAMLConnector deletes SAML Connector by name
func (s *IdentityService) DeleteSAMLConnector(name string) error
// DeleteSAMLConnector deletes SAML Connector by name func (s *IdentityService) DeleteSAMLConnector(name string) error
{ if name == "" { return trace.BadParameter("missing parameter name") } err := s.Delete(context.TODO(), backend.Key(webPrefix, connectorsPrefix, samlPrefix, connectorsPrefix, name)) return trace.Wrap(err) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/users.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L912-L936
go
train
// GetSAMLConnector returns SAML connector data, // withSecrets includes or excludes secrets from return results
func (s *IdentityService) GetSAMLConnector(name string, withSecrets bool) (services.SAMLConnector, error)
// GetSAMLConnector returns SAML connector data, // withSecrets includes or excludes secrets from return results func (s *IdentityService) GetSAMLConnector(name string, withSecrets bool) (services.SAMLConnector, error)
{ if name == "" { return nil, trace.BadParameter("missing parameter name") } item, err := s.Get(context.TODO(), backend.Key(webPrefix, connectorsPrefix, samlPrefix, connectorsPrefix, name)) if err != nil { if trace.IsNotFound(err) { return nil, trace.NotFound("SAML connector %q is not configured", name) } return nil, trace.Wrap(err) } conn, err := services.GetSAMLConnectorMarshaler().UnmarshalSAMLConnector( item.Value, services.WithExpires(item.Expires)) if err != nil { return nil, trace.Wrap(err) } if !withSecrets { keyPair := conn.GetSigningKeyPair() if keyPair != nil { keyPair.PrivateKey = "" conn.SetSigningKeyPair(keyPair) } } return conn, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/users.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L940-L963
go
train
// GetSAMLConnectors returns registered connectors // withSecrets includes or excludes private key values from return results
func (s *IdentityService) GetSAMLConnectors(withSecrets bool) ([]services.SAMLConnector, error)
// GetSAMLConnectors returns registered connectors // withSecrets includes or excludes private key values from return results func (s *IdentityService) GetSAMLConnectors(withSecrets bool) ([]services.SAMLConnector, error)
{ startKey := backend.Key(webPrefix, connectorsPrefix, samlPrefix, connectorsPrefix) result, err := s.GetRange(context.TODO(), startKey, backend.RangeEnd(startKey), backend.NoLimit) if err != nil { return nil, trace.Wrap(err) } connectors := make([]services.SAMLConnector, len(result.Items)) for i, item := range result.Items { conn, err := services.GetSAMLConnectorMarshaler().UnmarshalSAMLConnector( item.Value, services.WithExpires(item.Expires)) if err != nil { return nil, trace.Wrap(err) } if !withSecrets { keyPair := conn.GetSigningKeyPair() if keyPair != nil { keyPair.PrivateKey = "" conn.SetSigningKeyPair(keyPair) } } connectors[i] = conn } return connectors, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/users.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L966-L984
go
train
// CreateSAMLAuthRequest creates new auth request
func (s *IdentityService) CreateSAMLAuthRequest(req services.SAMLAuthRequest, ttl time.Duration) error
// CreateSAMLAuthRequest creates new auth request func (s *IdentityService) CreateSAMLAuthRequest(req services.SAMLAuthRequest, ttl time.Duration) error
{ if err := req.Check(); err != nil { return trace.Wrap(err) } value, err := json.Marshal(req) if err != nil { return trace.Wrap(err) } item := backend.Item{ Key: backend.Key(webPrefix, connectorsPrefix, samlPrefix, requestsPrefix, req.ID), Value: value, Expires: backend.Expiry(s.Clock(), ttl), } _, err = s.Create(context.TODO(), item) if err != nil { return trace.Wrap(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/users.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L987-L1000
go
train
// GetSAMLAuthRequest returns SAML auth request if found
func (s *IdentityService) GetSAMLAuthRequest(id string) (*services.SAMLAuthRequest, error)
// GetSAMLAuthRequest returns SAML auth request if found func (s *IdentityService) GetSAMLAuthRequest(id string) (*services.SAMLAuthRequest, error)
{ if id == "" { return nil, trace.BadParameter("missing parameter id") } item, err := s.Get(context.TODO(), backend.Key(webPrefix, connectorsPrefix, samlPrefix, requestsPrefix, id)) if err != nil { return nil, trace.Wrap(err) } var req services.SAMLAuthRequest if err := json.Unmarshal(item.Value, &req); err != nil { return nil, trace.Wrap(err) } return &req, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/users.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L1003-L1021
go
train
// CreateGithubConnector creates a new Github connector
func (s *IdentityService) CreateGithubConnector(connector services.GithubConnector) error
// CreateGithubConnector creates a new Github connector func (s *IdentityService) CreateGithubConnector(connector services.GithubConnector) error
{ if err := connector.CheckAndSetDefaults(); err != nil { return trace.Wrap(err) } value, err := services.GetGithubConnectorMarshaler().Marshal(connector) if err != nil { return trace.Wrap(err) } item := backend.Item{ Key: backend.Key(webPrefix, connectorsPrefix, githubPrefix, connectorsPrefix, connector.GetName()), Value: value, Expires: connector.Expiry(), } _, err = s.Create(context.TODO(), item) if err != nil { return trace.Wrap(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/users.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L1046-L1064
go
train
// GetGithubConnectors returns all configured Github connectors
func (s *IdentityService) GetGithubConnectors(withSecrets bool) ([]services.GithubConnector, error)
// GetGithubConnectors returns all configured Github connectors func (s *IdentityService) GetGithubConnectors(withSecrets bool) ([]services.GithubConnector, error)
{ startKey := backend.Key(webPrefix, connectorsPrefix, githubPrefix, connectorsPrefix) result, err := s.GetRange(context.TODO(), startKey, backend.RangeEnd(startKey), backend.NoLimit) if err != nil { return nil, trace.Wrap(err) } connectors := make([]services.GithubConnector, len(result.Items)) for i, item := range result.Items { connector, err := services.GetGithubConnectorMarshaler().Unmarshal(item.Value) if err != nil { return nil, trace.Wrap(err) } if !withSecrets { connector.SetClientSecret("") } connectors[i] = connector } return connectors, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/users.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L1067-L1086
go
train
// GetGithubConnectot returns a particular Github connector
func (s *IdentityService) GetGithubConnector(name string, withSecrets bool) (services.GithubConnector, error)
// GetGithubConnectot returns a particular Github connector func (s *IdentityService) GetGithubConnector(name string, withSecrets bool) (services.GithubConnector, error)
{ if name == "" { return nil, trace.BadParameter("missing parameter name") } item, err := s.Get(context.TODO(), backend.Key(webPrefix, connectorsPrefix, githubPrefix, connectorsPrefix, name)) if err != nil { if trace.IsNotFound(err) { return nil, trace.NotFound("github connector %q is not configured", name) } return nil, trace.Wrap(err) } connector, err := services.GetGithubConnectorMarshaler().Unmarshal(item.Value) if err != nil { return nil, trace.Wrap(err) } if !withSecrets { connector.SetClientSecret("") } return connector, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/users.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L1089-L1094
go
train
// DeleteGithubConnector deletes the specified connector
func (s *IdentityService) DeleteGithubConnector(name string) error
// DeleteGithubConnector deletes the specified connector func (s *IdentityService) DeleteGithubConnector(name string) error
{ if name == "" { return trace.BadParameter("missing parameter name") } return trace.Wrap(s.Delete(context.TODO(), backend.Key(webPrefix, connectorsPrefix, githubPrefix, connectorsPrefix, name))) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/users.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L1097-L1116
go
train
// CreateGithubAuthRequest creates a new auth request for Github OAuth2 flow
func (s *IdentityService) CreateGithubAuthRequest(req services.GithubAuthRequest) error
// CreateGithubAuthRequest creates a new auth request for Github OAuth2 flow func (s *IdentityService) CreateGithubAuthRequest(req services.GithubAuthRequest) error
{ err := req.Check() if err != nil { return trace.Wrap(err) } value, err := json.Marshal(req) if err != nil { return trace.Wrap(err) } item := backend.Item{ Key: backend.Key(webPrefix, connectorsPrefix, githubPrefix, requestsPrefix, req.StateToken), Value: value, Expires: req.Expiry(), } _, err = s.Create(context.TODO(), item) if err != nil { return trace.Wrap(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/users.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/users.go#L1119-L1133
go
train
// GetGithubAuthRequest retrieves Github auth request by the token
func (s *IdentityService) GetGithubAuthRequest(stateToken string) (*services.GithubAuthRequest, error)
// GetGithubAuthRequest retrieves Github auth request by the token func (s *IdentityService) GetGithubAuthRequest(stateToken string) (*services.GithubAuthRequest, error)
{ if stateToken == "" { return nil, trace.BadParameter("missing parameter stateToken") } item, err := s.Get(context.TODO(), backend.Key(webPrefix, connectorsPrefix, githubPrefix, requestsPrefix, stateToken)) if err != nil { return nil, trace.Wrap(err) } var req services.GithubAuthRequest err = json.Unmarshal(item.Value, &req) if err != nil { return nil, trace.Wrap(err) } return &req, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/server.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/server.go#L81-L87
go
train
// ServersToV1 converts list of servers to slice of V1 style ones
func ServersToV1(in []Server) []ServerV1
// ServersToV1 converts list of servers to slice of V1 style ones func ServersToV1(in []Server) []ServerV1
{ out := make([]ServerV1, len(in)) for i := range in { out[i] = *(in[i].V1()) } return out }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/server.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/server.go#L162-L164
go
train
// SetExpiry sets expiry time for the object
func (s *ServerV2) SetExpiry(expires time.Time)
// SetExpiry sets expiry time for the object func (s *ServerV2) SetExpiry(expires time.Time)
{ s.Metadata.SetExpiry(expires) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/server.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/server.go#L172-L174
go
train
// SetTTL sets Expires header using realtime clock
func (s *ServerV2) SetTTL(clock clockwork.Clock, ttl time.Duration)
// SetTTL sets Expires header using realtime clock func (s *ServerV2) SetTTL(clock clockwork.Clock, ttl time.Duration)
{ s.Metadata.SetTTL(clock, ttl) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/server.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/server.go#L232-L242
go
train
// GetCmdLabels returns command labels
func (s *ServerV2) GetCmdLabels() map[string]CommandLabel
// GetCmdLabels returns command labels func (s *ServerV2) GetCmdLabels() map[string]CommandLabel
{ if s.Spec.CmdLabels == nil { return nil } out := make(map[string]CommandLabel, len(s.Spec.CmdLabels)) for key := range s.Spec.CmdLabels { val := s.Spec.CmdLabels[key] out[key] = &val } return out }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/server.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/server.go#L255-L264
go
train
// GetAllLabels returns the full key:value map of both static labels and // "command labels"
func (s *ServerV2) GetAllLabels() map[string]string
// GetAllLabels returns the full key:value map of both static labels and // "command labels" func (s *ServerV2) GetAllLabels() map[string]string
{ lmap := make(map[string]string) for key, value := range s.Metadata.Labels { lmap[key] = value } for key, cmd := range s.Spec.CmdLabels { lmap[key] = cmd.Result } return lmap }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/server.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/server.go#L270-L280
go
train
// MatchAgainst takes a map of labels and returns True if this server // has ALL of them // // Any server matches against an empty label set
func (s *ServerV2) MatchAgainst(labels map[string]string) bool
// MatchAgainst takes a map of labels and returns True if this server // has ALL of them // // Any server matches against an empty label set func (s *ServerV2) MatchAgainst(labels map[string]string) bool
{ if labels != nil { myLabels := s.GetAllLabels() for key, value := range labels { if myLabels[key] != value { return false } } } return true }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/server.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/server.go#L283-L293
go
train
// LabelsString returns a comma separated string with all node's labels
func (s *ServerV2) LabelsString() string
// LabelsString returns a comma separated string with all node's labels func (s *ServerV2) LabelsString() string
{ labels := []string{} for key, val := range s.Metadata.Labels { labels = append(labels, fmt.Sprintf("%s=%s", key, val)) } for key, val := range s.Spec.CmdLabels { labels = append(labels, fmt.Sprintf("%s=%s", key, val.Result)) } sort.Strings(labels) return strings.Join(labels, ",") }