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
integration/helpers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L1152-L1156
go
train
// Count returns the number of connections that have been proxied.
func (p *proxyServer) Count() int
// Count returns the number of connections that have been proxied. func (p *proxyServer) Count() int
{ p.Lock() defer p.Unlock() return p.count }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
integration/helpers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L1246-L1302
go
train
// externalSSHCommand runs an external SSH command (if an external ssh binary // exists) with the passed in parameters.
func externalSSHCommand(o commandOptions) (*exec.Cmd, error)
// externalSSHCommand runs an external SSH command (if an external ssh binary // exists) with the passed in parameters. func externalSSHCommand(o commandOptions) (*exec.Cmd, error)
{ var execArgs []string // Don't check the host certificate as part of the testing an external SSH // client, this is done elsewhere. execArgs = append(execArgs, "-oStrictHostKeyChecking=no") execArgs = append(execArgs, "-oUserKnownHostsFile=/dev/null") // ControlMaster is often used by applications like Ansible. if o.controlPath != "" { execArgs = append(execArgs, "-oControlMaster=auto") execArgs = append(execArgs, "-oControlPersist=1s") execArgs = append(execArgs, "-oConnectTimeout=2") execArgs = append(execArgs, fmt.Sprintf("-oControlPath=%v", o.controlPath)) } // The -tt flag is used to force PTY allocation. It's often used by // applications like Ansible. if o.forcePTY { execArgs = append(execArgs, "-tt") } // Connect to node on the passed in port. execArgs = append(execArgs, fmt.Sprintf("-p %v", o.nodePort)) // Build proxy command. proxyCommand := []string{"ssh"} proxyCommand = append(proxyCommand, "-oStrictHostKeyChecking=no") proxyCommand = append(proxyCommand, "-oUserKnownHostsFile=/dev/null") if o.forwardAgent { proxyCommand = append(proxyCommand, "-oForwardAgent=yes") } proxyCommand = append(proxyCommand, fmt.Sprintf("-p %v", o.proxyPort)) proxyCommand = append(proxyCommand, `%r@localhost -s proxy:%h:%p`) // Add in ProxyCommand option, needed for all Teleport connections. execArgs = append(execArgs, fmt.Sprintf("-oProxyCommand=%v", strings.Join(proxyCommand, " "))) // Add in the host to connect to and the command to run when connected. execArgs = append(execArgs, Host) execArgs = append(execArgs, o.command) // Find the OpenSSH binary. sshpath, err := exec.LookPath("ssh") if err != nil { return nil, trace.Wrap(err) } // Create an exec.Command and tell it where to find the SSH agent. cmd, err := exec.Command(sshpath, execArgs...), nil if err != nil { return nil, trace.Wrap(err) } cmd.Env = []string{fmt.Sprintf("SSH_AUTH_SOCK=%v", o.socketPath)} return cmd, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
integration/helpers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L1307-L1353
go
train
// createAgent creates a SSH agent with the passed in private key and // certificate that can be used in tests. This is useful so tests don't // clobber your system agent.
func createAgent(me *user.User, privateKeyByte []byte, certificateBytes []byte) (*teleagent.AgentServer, string, string, error)
// createAgent creates a SSH agent with the passed in private key and // certificate that can be used in tests. This is useful so tests don't // clobber your system agent. func createAgent(me *user.User, privateKeyByte []byte, certificateBytes []byte) (*teleagent.AgentServer, string, string, error)
{ // create a path to the unix socket sockDir, err := ioutil.TempDir("", "int-test") if err != nil { return nil, "", "", trace.Wrap(err) } sockPath := filepath.Join(sockDir, "agent.sock") uid, err := strconv.Atoi(me.Uid) if err != nil { return nil, "", "", trace.Wrap(err) } gid, err := strconv.Atoi(me.Gid) if err != nil { return nil, "", "", trace.Wrap(err) } // transform the key and certificate bytes into something the agent can understand publicKey, _, _, _, err := ssh.ParseAuthorizedKey(certificateBytes) if err != nil { return nil, "", "", trace.Wrap(err) } privateKey, err := ssh.ParseRawPrivateKey(privateKeyByte) if err != nil { return nil, "", "", trace.Wrap(err) } agentKey := agent.AddedKey{ PrivateKey: privateKey, Certificate: publicKey.(*ssh.Certificate), Comment: "", LifetimeSecs: 0, ConfirmBeforeUse: false, } // create a (unstarted) agent and add the key to it teleAgent := teleagent.NewServer() teleAgent.Add(agentKey) // start the SSH agent err = teleAgent.ListenUnixSocket(sockPath, uid, gid, 0600) if err != nil { return nil, "", "", trace.Wrap(err) } go teleAgent.Serve() return teleAgent, sockDir, sockPath, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
integration/helpers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L1371-L1385
go
train
// createWebClient builds a *client.WebClient that is used to simulate // browser requests.
func createWebClient(cluster *TeleInstance, opts ...roundtrip.ClientParam) (*client.WebClient, error)
// createWebClient builds a *client.WebClient that is used to simulate // browser requests. func createWebClient(cluster *TeleInstance, opts ...roundtrip.ClientParam) (*client.WebClient, error)
{ // Craft URL to Web UI. u := &url.URL{ Scheme: "https", Host: cluster.Config.Proxy.WebAddr.Addr, } opts = append(opts, roundtrip.HTTPClient(client.NewInsecureWebClient())) wc, err := client.NewWebClient(u.String(), opts...) if err != nil { return nil, trace.Wrap(err) } return wc, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/native/native.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/native/native.go#L70-L75
go
train
// SetClock sets the clock to use for key generation.
func SetClock(clock clockwork.Clock) KeygenOption
// SetClock sets the clock to use for key generation. func SetClock(clock clockwork.Clock) KeygenOption
{ return func(k *Keygen) error { k.clock = clock return nil } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/native/native.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/native/native.go#L79-L84
go
train
// PrecomputeKeys sets up a number of private keys to pre-compute // in background, 0 disables the process
func PrecomputeKeys(count int) KeygenOption
// PrecomputeKeys sets up a number of private keys to pre-compute // in background, 0 disables the process func PrecomputeKeys(count int) KeygenOption
{ return func(k *Keygen) error { k.precomputeCount = count return nil } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/native/native.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/native/native.go#L87-L110
go
train
// New returns a new key generator.
func New(ctx context.Context, opts ...KeygenOption) (*Keygen, error)
// New returns a new key generator. func New(ctx context.Context, opts ...KeygenOption) (*Keygen, error)
{ ctx, cancel := context.WithCancel(ctx) k := &Keygen{ ctx: ctx, cancel: cancel, precomputeCount: PrecomputedNum, clock: clockwork.NewRealClock(), } for _, opt := range opts { if err := opt(k); err != nil { return nil, trace.Wrap(err) } } if k.precomputeCount > 0 { log.Debugf("SSH cert authority is going to pre-compute %v keys.", k.precomputeCount) k.keysCh = make(chan keyPair, k.precomputeCount) go k.precomputeKeys() } else { log.Debugf("SSH cert authority started with no keys pre-compute.") } return k, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/native/native.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/native/native.go#L118-L125
go
train
// GetNewKeyPairFromPool returns precomputed key pair from the pool.
func (k *Keygen) GetNewKeyPairFromPool() ([]byte, []byte, error)
// GetNewKeyPairFromPool returns precomputed key pair from the pool. func (k *Keygen) GetNewKeyPairFromPool() ([]byte, []byte, error)
{ select { case key := <-k.keysCh: return key.privPem, key.pubBytes, nil default: return GenerateKeyPair("") } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/native/native.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/native/native.go#L128-L148
go
train
// precomputeKeys continues loops forever trying to compute cache key pairs.
func (k *Keygen) precomputeKeys()
// precomputeKeys continues loops forever trying to compute cache key pairs. func (k *Keygen) precomputeKeys()
{ for { privPem, pubBytes, err := GenerateKeyPair("") if err != nil { log.Errorf("Unable to generate key pair: %v.", err) continue } key := keyPair{ privPem: privPem, pubBytes: pubBytes, } select { case <-k.ctx.Done(): log.Infof("Stopping key precomputation routine.") return case k.keysCh <- key: continue } } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/native/native.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/native/native.go#L152-L171
go
train
// GenerateKeyPair returns fresh priv/pub keypair, takes about 300ms to // execute.
func GenerateKeyPair(passphrase string) ([]byte, []byte, error)
// GenerateKeyPair returns fresh priv/pub keypair, takes about 300ms to // execute. func GenerateKeyPair(passphrase string) ([]byte, []byte, error)
{ priv, err := rsa.GenerateKey(rand.Reader, teleport.RSAKeySize) if err != nil { return nil, nil, err } privDer := x509.MarshalPKCS1PrivateKey(priv) privBlock := pem.Block{ Type: "RSA PRIVATE KEY", Headers: nil, Bytes: privDer, } privPem := pem.EncodeToMemory(&privBlock) pub, err := ssh.NewPublicKey(&priv.PublicKey) if err != nil { return nil, nil, err } pubBytes := ssh.MarshalAuthorizedKey(pub) return privPem, pubBytes, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/native/native.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/native/native.go#L175-L177
go
train
// GenerateKeyPair returns fresh priv/pub keypair, takes about 300ms to // execute.
func (k *Keygen) GenerateKeyPair(passphrase string) ([]byte, []byte, error)
// GenerateKeyPair returns fresh priv/pub keypair, takes about 300ms to // execute. func (k *Keygen) GenerateKeyPair(passphrase string) ([]byte, []byte, error)
{ return GenerateKeyPair(passphrase) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/native/native.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/native/native.go#L181-L231
go
train
// GenerateHostCert generates a host certificate with the passed in parameters. // The private key of the CA to sign the certificate must be provided.
func (k *Keygen) GenerateHostCert(c services.HostCertParams) ([]byte, error)
// GenerateHostCert generates a host certificate with the passed in parameters. // The private key of the CA to sign the certificate must be provided. func (k *Keygen) GenerateHostCert(c services.HostCertParams) ([]byte, error)
{ if err := c.Check(); err != nil { return nil, trace.Wrap(err) } pubKey, _, _, _, err := ssh.ParseAuthorizedKey(c.PublicHostKey) if err != nil { return nil, trace.Wrap(err) } signer, err := ssh.ParsePrivateKey(c.PrivateCASigningKey) if err != nil { return nil, trace.Wrap(err) } // Build a valid list of principals from the HostID and NodeName and then // add in any additional principals passed in. principals := BuildPrincipals(c.HostID, c.NodeName, c.ClusterName, c.Roles) principals = append(principals, c.Principals...) if len(principals) == 0 { return nil, trace.BadParameter("no principals provided: %v, %v, %v", c.HostID, c.NodeName, c.Principals) } principals = utils.Deduplicate(principals) // create certificate validBefore := uint64(ssh.CertTimeInfinity) if c.TTL != 0 { b := k.clock.Now().UTC().Add(c.TTL) validBefore = uint64(b.Unix()) } cert := &ssh.Certificate{ ValidPrincipals: principals, Key: pubKey, ValidAfter: uint64(k.clock.Now().UTC().Add(-1 * time.Minute).Unix()), ValidBefore: validBefore, CertType: ssh.HostCert, } cert.Permissions.Extensions = make(map[string]string) cert.Permissions.Extensions[utils.CertExtensionRole] = c.Roles.String() cert.Permissions.Extensions[utils.CertExtensionAuthority] = string(c.ClusterName) // sign host certificate with private signing key of certificate authority if err := cert.SignCert(rand.Reader, signer); err != nil { return nil, trace.Wrap(err) } log.Debugf("Generated SSH host certificate for role %v with principals: %v.", c.Roles, principals) return ssh.MarshalAuthorizedKey(cert), nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/native/native.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/native/native.go#L235-L292
go
train
// GenerateUserCert generates a host certificate with the passed in parameters. // The private key of the CA to sign the certificate must be provided.
func (k *Keygen) GenerateUserCert(c services.UserCertParams) ([]byte, error)
// GenerateUserCert generates a host certificate with the passed in parameters. // The private key of the CA to sign the certificate must be provided. func (k *Keygen) GenerateUserCert(c services.UserCertParams) ([]byte, error)
{ if c.TTL < defaults.MinCertDuration { return nil, trace.BadParameter("wrong certificate TTL") } if len(c.AllowedLogins) == 0 { return nil, trace.BadParameter("allowedLogins: need allowed OS logins") } pubKey, _, _, _, err := ssh.ParseAuthorizedKey(c.PublicUserKey) if err != nil { return nil, trace.Wrap(err) } validBefore := uint64(ssh.CertTimeInfinity) if c.TTL != 0 { b := k.clock.Now().UTC().Add(c.TTL) validBefore = uint64(b.Unix()) log.Debugf("generated user key for %v with expiry on (%v) %v", c.AllowedLogins, validBefore, b) } cert := &ssh.Certificate{ // we have to use key id to identify teleport user KeyId: c.Username, ValidPrincipals: c.AllowedLogins, Key: pubKey, ValidAfter: uint64(k.clock.Now().UTC().Add(-1 * time.Minute).Unix()), ValidBefore: validBefore, CertType: ssh.UserCert, } cert.Permissions.Extensions = map[string]string{ teleport.CertExtensionPermitPTY: "", teleport.CertExtensionPermitPortForwarding: "", } if c.PermitAgentForwarding { cert.Permissions.Extensions[teleport.CertExtensionPermitAgentForwarding] = "" } if !c.PermitPortForwarding { delete(cert.Permissions.Extensions, teleport.CertExtensionPermitPortForwarding) } if len(c.Roles) != 0 { // only add roles to the certificate extensions if the standard format was // requested. we allow the option to omit this to support older versions of // OpenSSH due to a bug in <= OpenSSH 7.1 // https://bugzilla.mindrot.org/show_bug.cgi?id=2387 if c.CertificateFormat == teleport.CertificateFormatStandard { roles, err := services.MarshalCertRoles(c.Roles) if err != nil { return nil, trace.Wrap(err) } cert.Permissions.Extensions[teleport.CertExtensionTeleportRoles] = roles } } signer, err := ssh.ParsePrivateKey(c.PrivateCASigningKey) if err != nil { return nil, trace.Wrap(err) } if err := cert.SignCert(rand.Reader, signer); err != nil { return nil, trace.Wrap(err) } return ssh.MarshalAuthorizedKey(cert), nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/native/native.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/native/native.go#L299-L324
go
train
// BuildPrincipals takes a hostID, nodeName, clusterName, and role and builds a list of // principals to insert into a certificate. This function is backward compatible with // older clients which means: // * If RoleAdmin is in the list of roles, only a single principal is returned: hostID // * If nodename is empty, it is not included in the list of principals.
func BuildPrincipals(hostID string, nodeName string, clusterName string, roles teleport.Roles) []string
// BuildPrincipals takes a hostID, nodeName, clusterName, and role and builds a list of // principals to insert into a certificate. This function is backward compatible with // older clients which means: // * If RoleAdmin is in the list of roles, only a single principal is returned: hostID // * If nodename is empty, it is not included in the list of principals. func BuildPrincipals(hostID string, nodeName string, clusterName string, roles teleport.Roles) []string
{ // TODO(russjones): This should probably be clusterName, but we need to // verify changing this won't break older clients. if roles.Include(teleport.RoleAdmin) { return []string{hostID} } // if no hostID was passed it, the user might be specifying an exact list of principals if hostID == "" { return []string{} } // always include the hostID, this is what teleport uses internally to find nodes principals := []string{ fmt.Sprintf("%v.%v", hostID, clusterName), } // nodeName is the DNS name, this is for OpenSSH interoperability if nodeName != "" { principals = append(principals, fmt.Sprintf("%s.%s", nodeName, clusterName)) principals = append(principals, nodeName) } // deduplicate (in-case hostID and nodeName are the same) and return return utils.Deduplicate(principals) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/s3sessions/s3handler.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/s3sessions/s3handler.go#L52-L73
go
train
// CheckAndSetDefaults checks and sets defaults
func (s *Config) CheckAndSetDefaults() error
// CheckAndSetDefaults checks and sets defaults func (s *Config) CheckAndSetDefaults() error
{ if s.Bucket == "" { return trace.BadParameter("missing parameter Bucket") } if s.Session == nil { // create an AWS session using default SDK behavior, i.e. it will interpret // the environment and ~/.aws directory just like an AWS CLI tool would: sess, err := awssession.NewSessionWithOptions(awssession.Options{ SharedConfigState: awssession.SharedConfigEnable, }) if err != nil { return trace.Wrap(err) } // override the default environment (region + credentials) with the values // from the YAML file: if s.Region != "" { sess.Config.Region = aws.String(s.Region) } s.Session = sess } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/s3sessions/s3handler.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/s3sessions/s3handler.go#L76-L97
go
train
// NewHandler returns new S3 uploader
func NewHandler(cfg Config) (*Handler, error)
// NewHandler returns new S3 uploader func NewHandler(cfg Config) (*Handler, error)
{ if err := cfg.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } h := &Handler{ Entry: log.WithFields(log.Fields{ trace.Component: teleport.Component(teleport.SchemeS3), }), Config: cfg, uploader: s3manager.NewUploader(cfg.Session), downloader: s3manager.NewDownloader(cfg.Session), client: s3.New(cfg.Session), } start := time.Now() h.Infof("Setting up bucket %q, sessions path %q in region %q.", h.Bucket, h.Path, h.Region) if err := h.ensureBucket(); err != nil { return nil, trace.Wrap(err) } h.WithFields(log.Fields{"duration": time.Now().Sub(start)}).Infof("Setup bucket %q completed.", h.Bucket) return h, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/s3sessions/s3handler.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/s3sessions/s3handler.go#L117-L129
go
train
// Upload uploads object to S3 bucket, reads the contents of the object from reader // and returns the target S3 bucket path in case of successful upload.
func (l *Handler) Upload(ctx context.Context, sessionID session.ID, reader io.Reader) (string, error)
// Upload uploads object to S3 bucket, reads the contents of the object from reader // and returns the target S3 bucket path in case of successful upload. func (l *Handler) Upload(ctx context.Context, sessionID session.ID, reader io.Reader) (string, error)
{ path := l.path(sessionID) _, err := l.uploader.UploadWithContext(ctx, &s3manager.UploadInput{ Bucket: aws.String(l.Bucket), Key: aws.String(path), Body: reader, ServerSideEncryption: aws.String(s3.ServerSideEncryptionAwsKms), }) if err != nil { return "", ConvertS3Error(err) } return fmt.Sprintf("%v://%v/%v", teleport.SchemeS3, l.Bucket, path), nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/s3sessions/s3handler.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/s3sessions/s3handler.go#L133-L145
go
train
// Download downloads recorded session from S3 bucket and writes the results into writer // return trace.NotFound error is object is not found
func (l *Handler) Download(ctx context.Context, sessionID session.ID, writer io.WriterAt) error
// Download downloads recorded session from S3 bucket and writes the results into writer // return trace.NotFound error is object is not found func (l *Handler) Download(ctx context.Context, sessionID session.ID, writer io.WriterAt) error
{ written, err := l.downloader.DownloadWithContext(ctx, writer, &s3.GetObjectInput{ Bucket: aws.String(l.Bucket), Key: aws.String(l.path(sessionID)), }) if err != nil { return ConvertS3Error(err) } if written == 0 { return trace.NotFound("recording for %v is not found", sessionID) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/s3sessions/s3handler.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/s3sessions/s3handler.go#L148-L170
go
train
// delete bucket deletes bucket and all it's contents and is used in tests
func (h *Handler) deleteBucket() error
// delete bucket deletes bucket and all it's contents and is used in tests func (h *Handler) deleteBucket() error
{ // first, list and delete all the objects in the bucket out, err := h.client.ListObjectVersions(&s3.ListObjectVersionsInput{ Bucket: aws.String(h.Bucket), }) if err != nil { return ConvertS3Error(err) } for _, ver := range out.Versions { _, err := h.client.DeleteObject(&s3.DeleteObjectInput{ Bucket: aws.String(h.Bucket), Key: ver.Key, VersionId: ver.VersionId, }) if err != nil { return ConvertS3Error(err) } } _, err = h.client.DeleteBucket(&s3.DeleteBucketInput{ Bucket: aws.String(h.Bucket), }) return ConvertS3Error(err) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/s3sessions/s3handler.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/s3sessions/s3handler.go#L180-L233
go
train
// ensureBucket makes sure bucket exists, and if it does not, creates it
func (h *Handler) ensureBucket() error
// ensureBucket makes sure bucket exists, and if it does not, creates it func (h *Handler) ensureBucket() error
{ _, err := h.client.HeadBucket(&s3.HeadBucketInput{ Bucket: aws.String(h.Bucket), }) err = ConvertS3Error(err) // assumes that bucket is administered by other entity if err == nil { return nil } if !trace.IsNotFound(err) { return trace.Wrap(err) } input := &s3.CreateBucketInput{ Bucket: aws.String(h.Bucket), ACL: aws.String("private"), } _, err = h.client.CreateBucket(input) err = ConvertS3Error(err, "bucket %v already exists", aws.String(h.Bucket)) if err != nil { if !trace.IsAlreadyExists(err) { return trace.Wrap(err) } // if this client has not created the bucket, don't reconfigure it return nil } // turn on versioning ver := &s3.PutBucketVersioningInput{ Bucket: aws.String(h.Bucket), VersioningConfiguration: &s3.VersioningConfiguration{ Status: aws.String("Enabled"), }, } _, err = h.client.PutBucketVersioning(ver) err = ConvertS3Error(err, "failed to set versioning state for bucket %q", h.Bucket) if err != nil { return trace.Wrap(err) } _, err = h.client.PutBucketEncryption(&s3.PutBucketEncryptionInput{ Bucket: aws.String(h.Bucket), ServerSideEncryptionConfiguration: &s3.ServerSideEncryptionConfiguration{ Rules: []*s3.ServerSideEncryptionRule{&s3.ServerSideEncryptionRule{ ApplyServerSideEncryptionByDefault: &s3.ServerSideEncryptionByDefault{ SSEAlgorithm: aws.String(s3.ServerSideEncryptionAwsKms), }, }}, }, }) err = ConvertS3Error(err, "failed to set versioning state for bucket %q", h.Bucket) if err != nil { return trace.Wrap(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/s3sessions/s3handler.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/s3sessions/s3handler.go#L236-L251
go
train
// ConvertS3Error wraps S3 error and returns trace equivalent
func ConvertS3Error(err error, args ...interface{}) error
// ConvertS3Error wraps S3 error and returns trace equivalent func ConvertS3Error(err error, args ...interface{}) error
{ if err == nil { return nil } if aerr, ok := err.(awserr.Error); ok { switch aerr.Code() { case s3.ErrCodeNoSuchKey, s3.ErrCodeNoSuchBucket, s3.ErrCodeNoSuchUpload, "NotFound": return trace.NotFound(aerr.Error(), args...) case s3.ErrCodeBucketAlreadyExists, s3.ErrCodeBucketAlreadyOwnedByYou: return trace.AlreadyExists(aerr.Error(), args...) default: return trace.BadParameter(aerr.Error(), args...) } } return err }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
roles.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/roles.go#L61-L71
go
train
// NewRoles return a list of roles from slice of strings
func NewRoles(in []string) (Roles, error)
// NewRoles return a list of roles from slice of strings func NewRoles(in []string) (Roles, error)
{ var roles Roles for _, val := range in { role := Role(val) if err := role.Check(); err != nil { return nil, trace.Wrap(err) } roles = append(roles, role) } return roles, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
roles.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/roles.go#L75-L84
go
train
// ParseRoles takes a comma-separated list of roles and returns a slice // of roles, or an error if parsing failed
func ParseRoles(str string) (roles Roles, err error)
// ParseRoles takes a comma-separated list of roles and returns a slice // of roles, or an error if parsing failed func ParseRoles(str string) (roles Roles, err error)
{ for _, s := range strings.Split(str, ",") { r := Role(strings.Title(strings.ToLower(strings.TrimSpace(s)))) if err = r.Check(); err != nil { return nil, trace.Wrap(err) } roles = append(roles, r) } return roles, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
roles.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/roles.go#L87-L94
go
train
// Includes returns 'true' if a given list of roles includes a given role
func (roles Roles) Include(role Role) bool
// Includes returns 'true' if a given list of roles includes a given role func (roles Roles) Include(role Role) bool
{ for _, r := range roles { if r == role { return true } } return false }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
roles.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/roles.go#L97-L103
go
train
// Slice returns roles as string slice
func (roles Roles) StringSlice() []string
// Slice returns roles as string slice func (roles Roles) StringSlice() []string
{ s := make([]string, 0) for _, r := range roles { s = append(s, r.String()) } return s }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
roles.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/roles.go#L106-L116
go
train
// Equals compares two sets of roles
func (roles Roles) Equals(other Roles) bool
// Equals compares two sets of roles func (roles Roles) Equals(other Roles) bool
{ if len(roles) != len(other) { return false } for _, r := range roles { if !other.Include(r) { return false } } return true }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
roles.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/roles.go#L119-L126
go
train
// Check returns an error if the role set is incorrect (contains unknown roles)
func (roles Roles) Check() (err error)
// Check returns an error if the role set is incorrect (contains unknown roles) func (roles Roles) Check() (err error)
{ for _, role := range roles { if err = role.Check(); err != nil { return trace.Wrap(err) } } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
roles.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/roles.go#L134-L141
go
train
// Set sets the value of the role from string, used to integrate with CLI tools
func (r *Role) Set(v string) error
// Set sets the value of the role from string, used to integrate with CLI tools func (r *Role) Set(v string) error
{ val := Role(strings.Title(v)) if err := val.Check(); err != nil { return trace.Wrap(err) } *r = val return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
roles.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/roles.go#L144-L153
go
train
// String returns debug-friendly representation of this role.
func (r *Role) String() string
// String returns debug-friendly representation of this role. func (r *Role) String() string
{ switch string(*r) { case string(RoleSignup): return "User signup" case string(RoleTrustedCluster), string(LegacyClusterTokenType): return "trusted_cluster" default: return fmt.Sprintf("%v", string(*r)) } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
roles.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/roles.go#L157-L166
go
train
// Check checks if this a a valid role value, returns nil // if it's ok, false otherwise
func (r *Role) Check() error
// Check checks if this a a valid role value, returns nil // if it's ok, false otherwise func (r *Role) Check() error
{ switch *r { case RoleAuth, RoleWeb, RoleNode, RoleAdmin, RoleProvisionToken, RoleTrustedCluster, LegacyClusterTokenType, RoleSignup, RoleProxy, RoleNop: return nil } return trace.BadParameter("role %v is not registered", *r) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/lite/lite.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/lite/lite.go#L94-L117
go
train
// CheckAndSetDefaults is a helper returns an error if the supplied configuration // is not enough to connect to sqlite
func (cfg *Config) CheckAndSetDefaults() error
// CheckAndSetDefaults is a helper returns an error if the supplied configuration // is not enough to connect to sqlite func (cfg *Config) CheckAndSetDefaults() error
{ if cfg.Path == "" && !cfg.Memory { return trace.BadParameter("specify directory path to the database using 'path' parameter") } if cfg.BufferSize == 0 { cfg.BufferSize = backend.DefaultBufferSize } if cfg.PollStreamPeriod == 0 { cfg.PollStreamPeriod = backend.DefaultPollStreamPeriod } if cfg.Clock == nil { cfg.Clock = clockwork.NewRealClock() } if cfg.Sync == "" { cfg.Sync = syncOFF } if cfg.BusyTimeout == 0 { cfg.BusyTimeout = busyTimeout } if cfg.MemoryName == "" { cfg.MemoryName = defaultDBFile } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/lite/lite.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/lite/lite.go#L120-L127
go
train
// New returns a new instance of sqlite backend
func New(ctx context.Context, params backend.Params) (*LiteBackend, error)
// New returns a new instance of sqlite backend func New(ctx context.Context, params backend.Params) (*LiteBackend, error)
{ var cfg *Config err := utils.ObjectToStruct(params, &cfg) if err != nil { return nil, trace.BadParameter("SQLite configuration is invalid: %v", err) } return NewWithConfig(ctx, *cfg) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/lite/lite.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/lite/lite.go#L131-L179
go
train
// NewWithConfig returns a new instance of lite backend using // configuration struct as a parameter
func NewWithConfig(ctx context.Context, cfg Config) (*LiteBackend, error)
// NewWithConfig returns a new instance of lite backend using // configuration struct as a parameter func NewWithConfig(ctx context.Context, cfg Config) (*LiteBackend, error)
{ if err := cfg.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } var connectorURL string if !cfg.Memory { // Ensure that the path to the root directory exists. err := os.MkdirAll(cfg.Path, defaultDirMode) if err != nil { return nil, trace.ConvertSystemError(err) } fullPath := filepath.Join(cfg.Path, defaultDBFile) connectorURL = fmt.Sprintf("file:%v?_busy_timeout=%v&_sync=%v", fullPath, cfg.BusyTimeout, cfg.Sync) } else { connectorURL = fmt.Sprintf("file:%v?mode=memory", cfg.MemoryName) } db, err := sql.Open(BackendName, connectorURL) if err != nil { return nil, trace.Wrap(err, "error opening URI: %v", connectorURL) } // serialize access to sqlite to avoid database is locked errors db.SetMaxOpenConns(1) buf, err := backend.NewCircularBuffer(ctx, cfg.BufferSize) if err != nil { return nil, trace.Wrap(err) } closeCtx, cancel := context.WithCancel(ctx) watchStarted, signalWatchStart := context.WithCancel(ctx) l := &LiteBackend{ Config: cfg, db: db, Entry: log.WithFields(log.Fields{trace.Component: BackendName}), clock: cfg.Clock, buf: buf, ctx: closeCtx, cancel: cancel, watchStarted: watchStarted, signalWatchStart: signalWatchStart, } l.Debugf("Connected to: %v, poll stream period: %v", connectorURL, cfg.PollStreamPeriod) if err := l.createSchema(); err != nil { return nil, trace.Wrap(err, "error creating schema: %v", connectorURL) } if err := l.showPragmas(); err != nil { l.Warningf("Failed to show pragma settings: %v.", err) } go l.runPeriodicOperations() return l, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/lite/lite.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/lite/lite.go#L205-L220
go
train
// showPragmas is used to debug SQLite database connection // parameters, when called, logs some key PRAGMA values
func (l *LiteBackend) showPragmas() error
// showPragmas is used to debug SQLite database connection // parameters, when called, logs some key PRAGMA values func (l *LiteBackend) showPragmas() error
{ return l.inTransaction(l.ctx, func(tx *sql.Tx) error { row := tx.QueryRowContext(l.ctx, "PRAGMA synchronous;") var syncValue string if err := row.Scan(&syncValue); err != nil { return trace.Wrap(err) } var timeoutValue string row = tx.QueryRowContext(l.ctx, "PRAGMA busy_timeout;") if err := row.Scan(&timeoutValue); err != nil { return trace.Wrap(err) } l.Debugf("Synchronous: %v, busy timeout: %v", syncValue, timeoutValue) return nil }) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/lite/lite.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/lite/lite.go#L311-L365
go
train
// CompareAndSwap compares item with existing item // and replaces is with replaceWith item
func (l *LiteBackend) CompareAndSwap(ctx context.Context, expected backend.Item, replaceWith backend.Item) (*backend.Lease, error)
// CompareAndSwap compares item with existing item // and replaces is with replaceWith item func (l *LiteBackend) CompareAndSwap(ctx context.Context, expected backend.Item, replaceWith backend.Item) (*backend.Lease, error)
{ if len(expected.Key) == 0 { return nil, trace.BadParameter("missing parameter Key") } if len(replaceWith.Key) == 0 { return nil, trace.BadParameter("missing parameter Key") } if bytes.Compare(expected.Key, replaceWith.Key) != 0 { return nil, trace.BadParameter("expected and replaceWith keys should match") } now := l.clock.Now().UTC() err := l.inTransaction(ctx, func(tx *sql.Tx) error { q, err := tx.PrepareContext(ctx, "SELECT value FROM kv WHERE key = ? AND (expires IS NULL OR expires > ?) LIMIT 1") if err != nil { return trace.Wrap(err) } row := q.QueryRowContext(ctx, string(expected.Key), now) var value []byte if err := row.Scan(&value); err != nil { if err == sql.ErrNoRows { return trace.CompareFailed("key %v is not found", string(expected.Key)) } return trace.Wrap(err) } if bytes.Compare(value, expected.Value) != 0 { return trace.CompareFailed("current value does not match expected for %v", string(expected.Key)) } created := l.clock.Now().UTC() stmt, err := tx.PrepareContext(ctx, "UPDATE kv SET value = ?, expires = ?, modified = ? WHERE key = ?") if err != nil { return trace.Wrap(err) } _, err = stmt.ExecContext(ctx, replaceWith.Value, expires(replaceWith.Expires), id(created), string(replaceWith.Key)) if err != nil { return trace.Wrap(err) } if !l.EventsOff { stmt, err = tx.PrepareContext(ctx, "INSERT INTO events(type, created, kv_key, kv_modified, kv_expires, kv_value) values(?, ?, ?, ?, ?, ?)") if err != nil { return trace.Wrap(err) } if _, err := stmt.ExecContext(ctx, backend.OpPut, created, string(replaceWith.Key), id(created), expires(replaceWith.Expires), replaceWith.Value); err != nil { return trace.Wrap(err) } } return nil }) if err != nil { return nil, trace.Wrap(err) } return l.newLease(replaceWith), nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/lite/lite.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/lite/lite.go#L374-L406
go
train
// Put puts value into backend (creates if it does not // exists, updates it otherwise)
func (l *LiteBackend) Put(ctx context.Context, i backend.Item) (*backend.Lease, error)
// Put puts value into backend (creates if it does not // exists, updates it otherwise) func (l *LiteBackend) Put(ctx context.Context, i backend.Item) (*backend.Lease, error)
{ if i.Key == nil { return nil, trace.BadParameter("missing parameter key") } err := l.inTransaction(ctx, func(tx *sql.Tx) error { created := l.clock.Now().UTC() recordID := i.ID if !l.Mirror { recordID = id(created) } if !l.EventsOff { stmt, err := tx.PrepareContext(ctx, "INSERT INTO events(type, created, kv_key, kv_modified, kv_expires, kv_value) values(?, ?, ?, ?, ?, ?)") if err != nil { return trace.Wrap(err) } if _, err := stmt.ExecContext(ctx, backend.OpPut, created, string(i.Key), recordID, expires(i.Expires), i.Value); err != nil { return trace.Wrap(err) } } stmt, err := tx.PrepareContext(ctx, "INSERT OR REPLACE INTO kv(key, modified, expires, value) values(?, ?, ?, ?)") if err != nil { return trace.Wrap(err) } if _, err := stmt.ExecContext(ctx, string(i.Key), recordID, expires(i.Expires), i.Value); err != nil { return trace.Wrap(err) } return nil }) if err != nil { return nil, trace.Wrap(err) } return l.newLease(i), nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/lite/lite.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/lite/lite.go#L413-L429
go
train
// Imported returns true if backend already imported data from another backend
func (l *LiteBackend) Imported(ctx context.Context) (imported bool, err error)
// Imported returns true if backend already imported data from another backend func (l *LiteBackend) Imported(ctx context.Context) (imported bool, err error)
{ err = l.inTransaction(ctx, func(tx *sql.Tx) error { q, err := tx.PrepareContext(ctx, "SELECT imported from meta LIMIT 1") if err != nil { return trace.Wrap(err) } row := q.QueryRowContext(ctx) if err := row.Scan(&imported); err != nil { if err != sql.ErrNoRows { return trace.Wrap(err) } } return nil }) return imported, err }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/lite/lite.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/lite/lite.go#L433-L474
go
train
// Import imports elements, makes sure elements are imported only once // returns trace.AlreadyExists if elements have been imported
func (l *LiteBackend) Import(ctx context.Context, items []backend.Item) error
// Import imports elements, makes sure elements are imported only once // returns trace.AlreadyExists if elements have been imported func (l *LiteBackend) Import(ctx context.Context, items []backend.Item) error
{ for i := range items { if items[i].Key == nil { return trace.BadParameter("missing parameter key in item %v", i) } } err := l.inTransaction(ctx, func(tx *sql.Tx) error { q, err := tx.PrepareContext(ctx, "SELECT imported from meta LIMIT 1") if err != nil { return trace.Wrap(err) } var imported bool row := q.QueryRowContext(ctx) if err := row.Scan(&imported); err != nil { if err != sql.ErrNoRows { return trace.Wrap(err) } } if imported { return trace.AlreadyExists("database has been already imported") } if err := l.putRangeInTransaction(ctx, tx, items, true); err != nil { return trace.Wrap(err) } stmt, err := tx.PrepareContext(ctx, "INSERT INTO meta(version, imported) values(?, ?)") if err != nil { return trace.Wrap(err) } if _, err := stmt.ExecContext(ctx, schemaVersion, true); err != nil { return trace.Wrap(err) } return nil }) if err != nil { return trace.Wrap(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/lite/lite.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/lite/lite.go#L478-L491
go
train
// PutRange puts range of items into backend (creates if items doe not // exists, updates it otherwise)
func (l *LiteBackend) PutRange(ctx context.Context, items []backend.Item) error
// PutRange puts range of items into backend (creates if items doe not // exists, updates it otherwise) func (l *LiteBackend) PutRange(ctx context.Context, items []backend.Item) error
{ for i := range items { if items[i].Key == nil { return trace.BadParameter("missing parameter key in item %v", i) } } err := l.inTransaction(ctx, func(tx *sql.Tx) error { return l.putRangeInTransaction(ctx, tx, items, false) }) if err != nil { return trace.Wrap(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/lite/lite.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/lite/lite.go#L564-L576
go
train
// Get returns a single item or not found error
func (l *LiteBackend) Get(ctx context.Context, key []byte) (*backend.Item, error)
// Get returns a single item or not found error func (l *LiteBackend) Get(ctx context.Context, key []byte) (*backend.Item, error)
{ if len(key) == 0 { return nil, trace.BadParameter("missing parameter key") } var item backend.Item err := l.inTransaction(ctx, func(tx *sql.Tx) error { return l.getInTransaction(ctx, key, tx, &item) }) if err != nil { return nil, trace.Wrap(err) } return &item, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/lite/lite.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/lite/lite.go#L579-L596
go
train
// getInTransaction returns an item, works in transaction
func (l *LiteBackend) getInTransaction(ctx context.Context, key []byte, tx *sql.Tx, item *backend.Item) error
// getInTransaction returns an item, works in transaction func (l *LiteBackend) getInTransaction(ctx context.Context, key []byte, tx *sql.Tx, item *backend.Item) error
{ now := l.clock.Now().UTC() q, err := tx.PrepareContext(ctx, "SELECT key, value, expires, modified FROM kv WHERE key = ? AND (expires IS NULL OR expires > ?) LIMIT 1") if err != nil { return trace.Wrap(err) } row := q.QueryRowContext(ctx, string(key), now) var expires NullTime if err := row.Scan(&item.Key, &item.Value, &expires, &item.ID); err != nil { if err == sql.ErrNoRows { return trace.NotFound("key %v is not found", string(key)) } return trace.Wrap(err) } item.Expires = expires.Time return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/lite/lite.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/lite/lite.go#L599-L638
go
train
// GetRange returns query range
func (l *LiteBackend) GetRange(ctx context.Context, startKey []byte, endKey []byte, limit int) (*backend.GetResult, error)
// GetRange returns query range func (l *LiteBackend) GetRange(ctx context.Context, startKey []byte, endKey []byte, limit int) (*backend.GetResult, error)
{ if len(startKey) == 0 { return nil, trace.BadParameter("missing parameter startKey") } if len(endKey) == 0 { return nil, trace.BadParameter("missing parameter endKey") } if limit <= 0 { limit = backend.DefaultLargeLimit } var result backend.GetResult now := l.clock.Now().UTC() err := l.inTransaction(ctx, func(tx *sql.Tx) error { q, err := tx.PrepareContext(ctx, "SELECT key, value, expires, modified FROM kv WHERE (key >= ? and key <= ?) AND (expires is NULL or expires > ?) ORDER BY key LIMIT ?") if err != nil { return trace.Wrap(err) } rows, err := q.QueryContext(ctx, string(startKey), string(endKey), now, limit) if err != nil { return trace.Wrap(err) } defer rows.Close() for rows.Next() { var i backend.Item var expires NullTime if err := rows.Scan(&i.Key, &i.Value, &expires, &i.ID); err != nil { return trace.Wrap(err) } i.Expires = expires.Time result.Items = append(result.Items, i) } return nil }) if err != nil { return nil, trace.Wrap(err) } return &result, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/lite/lite.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/lite/lite.go#L641-L679
go
train
// KeepAlive updates TTL on the lease
func (l *LiteBackend) KeepAlive(ctx context.Context, lease backend.Lease, expires time.Time) error
// KeepAlive updates TTL on the lease func (l *LiteBackend) KeepAlive(ctx context.Context, lease backend.Lease, expires time.Time) error
{ if len(lease.Key) == 0 { return trace.BadParameter("lease key is not specified") } now := l.clock.Now().UTC() return l.inTransaction(ctx, func(tx *sql.Tx) error { var item backend.Item err := l.getInTransaction(ctx, lease.Key, tx, &item) if err != nil { return trace.Wrap(err) } created := l.clock.Now().UTC() if !l.EventsOff { stmt, err := tx.PrepareContext(ctx, "INSERT INTO events(type, created, kv_key, kv_modified, kv_expires, kv_value) values(?, ?, ?, ?, ?, ?)") if err != nil { return trace.Wrap(err) } if _, err := stmt.ExecContext(ctx, backend.OpPut, created, string(item.Key), id(created), expires.UTC(), item.Value); err != nil { return trace.Wrap(err) } } stmt, err := tx.PrepareContext(ctx, "UPDATE kv SET expires = ?, modified = ? WHERE key = ?") if err != nil { return trace.Wrap(err) } result, err := stmt.ExecContext(ctx, expires.UTC(), id(now), string(lease.Key)) if err != nil { return trace.Wrap(err) } rows, err := result.RowsAffected() if err != nil { return trace.Wrap(err) } if rows == 0 { return trace.NotFound("key %v is not found", string(lease.Key)) } return nil }) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/lite/lite.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/lite/lite.go#L712-L719
go
train
// Delete deletes item by key, returns NotFound error // if item does not exist
func (l *LiteBackend) Delete(ctx context.Context, key []byte) error
// Delete deletes item by key, returns NotFound error // if item does not exist func (l *LiteBackend) Delete(ctx context.Context, key []byte) error
{ if len(key) == 0 { return trace.BadParameter("missing parameter key") } return l.inTransaction(ctx, func(tx *sql.Tx) error { return l.deleteInTransaction(ctx, key, tx) }) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/lite/lite.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/lite/lite.go#L723-L758
go
train
// DeleteRange deletes range of items with keys between startKey and endKey // Note that elements deleted by range do not produce any events
func (l *LiteBackend) DeleteRange(ctx context.Context, startKey, endKey []byte) error
// DeleteRange deletes range of items with keys between startKey and endKey // Note that elements deleted by range do not produce any events func (l *LiteBackend) DeleteRange(ctx context.Context, startKey, endKey []byte) error
{ if len(startKey) == 0 { return trace.BadParameter("missing parameter startKey") } if len(endKey) == 0 { return trace.BadParameter("missing parameter endKey") } return l.inTransaction(ctx, func(tx *sql.Tx) error { q, err := tx.PrepareContext(ctx, "SELECT key FROM kv WHERE key >= ? and key <= ?") if err != nil { return trace.Wrap(err) } rows, err := q.QueryContext(ctx, string(startKey), string(endKey)) if err != nil { return trace.Wrap(err) } defer rows.Close() var keys [][]byte for rows.Next() { var key []byte if err := rows.Scan(&key); err != nil { return trace.Wrap(err) } keys = append(keys, key) } for i := range keys { if err := l.deleteInTransaction(l.ctx, keys[i], tx); err != nil { return trace.Wrap(err) } } return nil }) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/lite/lite.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/lite/lite.go#L761-L771
go
train
// NewWatcher returns a new event watcher
func (l *LiteBackend) NewWatcher(ctx context.Context, watch backend.Watch) (backend.Watcher, error)
// NewWatcher returns a new event watcher func (l *LiteBackend) NewWatcher(ctx context.Context, watch backend.Watch) (backend.Watcher, error)
{ if l.EventsOff { return nil, trace.BadParameter("events are turned off for this backend") } select { case <-l.watchStarted.Done(): case <-ctx.Done(): return nil, trace.ConnectionProblem(ctx.Err(), "context is closing") } return l.buf.NewWatcher(ctx, watch) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/lite/lite.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/lite/lite.go#L931-L934
go
train
// Scan implements the Scanner interface.
func (nt *NullTime) Scan(value interface{}) error
// Scan implements the Scanner interface. func (nt *NullTime) Scan(value interface{}) error
{ nt.Time, nt.Valid = value.(time.Time) return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/modules/modules.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/modules/modules.go#L85-L93
go
train
// PrintVersion prints the Teleport version.
func (p *defaultModules) PrintVersion()
// PrintVersion prints the Teleport version. func (p *defaultModules) PrintVersion()
{ var buf bytes.Buffer buf.WriteString(fmt.Sprintf("Teleport v%s ", teleport.Version)) buf.WriteString(fmt.Sprintf("git:%s ", teleport.Gitref)) buf.WriteString(runtime.Version()) fmt.Println(buf.String()) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/modules/modules.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/modules/modules.go#L108-L113
go
train
// TraitsFromLogins returns traits for external user based on the logins // extracted from the connector // // By default logins are treated as allowed logins user traits.
func (p *defaultModules) TraitsFromLogins(logins []string, kubeGroups []string) map[string][]string
// TraitsFromLogins returns traits for external user based on the logins // extracted from the connector // // By default logins are treated as allowed logins user traits. func (p *defaultModules) TraitsFromLogins(logins []string, kubeGroups []string) map[string][]string
{ return map[string][]string{ teleport.TraitLogins: logins, teleport.TraitKubeGroups: kubeGroups, } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/github.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/github.go#L63-L73
go
train
// NewGithubConnector creates a new Github connector from name and spec
func NewGithubConnector(name string, spec GithubConnectorSpecV3) GithubConnector
// NewGithubConnector creates a new Github connector from name and spec func NewGithubConnector(name string, spec GithubConnectorSpecV3) GithubConnector
{ return &GithubConnectorV3{ Kind: KindGithubConnector, Version: V3, Metadata: Metadata{ Name: name, Namespace: defaults.Namespace, }, Spec: spec, } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/github.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/github.go#L169-L171
go
train
// SetExpiry sets the connector expiration time
func (c *GithubConnectorV3) SetExpiry(expires time.Time)
// SetExpiry sets the connector expiration time func (c *GithubConnectorV3) SetExpiry(expires time.Time)
{ c.Metadata.SetExpiry(expires) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/github.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/github.go#L174-L176
go
train
// SetTTL sets the connector TTL
func (c *GithubConnectorV3) SetTTL(clock clockwork.Clock, ttl time.Duration)
// SetTTL sets the connector TTL func (c *GithubConnectorV3) SetTTL(clock clockwork.Clock, ttl time.Duration)
{ c.Metadata.SetTTL(clock, ttl) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/github.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/github.go#L243-L260
go
train
// MapClaims returns a list of logins based on the provided claims, // returns a list of logins and list of kubernetes groups
func (c *GithubConnectorV3) MapClaims(claims GithubClaims) ([]string, []string)
// MapClaims returns a list of logins based on the provided claims, // returns a list of logins and list of kubernetes groups func (c *GithubConnectorV3) MapClaims(claims GithubClaims) ([]string, []string)
{ var logins, kubeGroups []string for _, mapping := range c.GetTeamsToLogins() { teams, ok := claims.OrganizationToTeams[mapping.Organization] if !ok { // the user does not belong to this organization continue } for _, team := range teams { // see if the user belongs to this team if team == mapping.Team { logins = append(logins, mapping.Logins...) kubeGroups = append(kubeGroups, mapping.KubeGroups...) } } } return utils.Deduplicate(logins), utils.Deduplicate(kubeGroups) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/github.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/github.go#L295-L313
go
train
// UnmarshalGithubConnector unmarshals Github connector from JSON
func (*TeleportGithubConnectorMarshaler) Unmarshal(bytes []byte) (GithubConnector, error)
// UnmarshalGithubConnector unmarshals Github connector from JSON func (*TeleportGithubConnectorMarshaler) Unmarshal(bytes []byte) (GithubConnector, error)
{ var h ResourceHeader if err := json.Unmarshal(bytes, &h); err != nil { return nil, trace.Wrap(err) } switch h.Version { case V3: var c GithubConnectorV3 if err := utils.UnmarshalWithSchema(GetGithubConnectorSchema(), &c, bytes); err != nil { return nil, trace.Wrap(err) } if err := c.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } return &c, nil } return nil, trace.BadParameter( "Github connector resource version %q is not supported", h.Version) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/github.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/github.go#L316-L334
go
train
// MarshalGithubConnector marshals Github connector to JSON
func (*TeleportGithubConnectorMarshaler) Marshal(c GithubConnector, opts ...MarshalOption) ([]byte, error)
// MarshalGithubConnector marshals Github connector to JSON func (*TeleportGithubConnectorMarshaler) Marshal(c GithubConnector, opts ...MarshalOption) ([]byte, error)
{ cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } switch resource := c.(type) { case *GithubConnectorV3: if !cfg.PreserveResourceID { // avoid modifying the original object // to prevent unexpected data races copy := *resource copy.SetResourceID(0) resource = &copy } return utils.FastMarshal(resource) default: return nil, trace.BadParameter("unrecognized resource version %T", c) } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/provisioning.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/provisioning.go#L41-L63
go
train
// UpsertToken adds provisioning tokens for the auth server
func (s *ProvisioningService) UpsertToken(p services.ProvisionToken) error
// UpsertToken adds provisioning tokens for the auth server func (s *ProvisioningService) UpsertToken(p services.ProvisionToken) error
{ if err := p.CheckAndSetDefaults(); err != nil { return trace.Wrap(err) } if p.Expiry().IsZero() || p.Expiry().Sub(s.Clock().Now().UTC()) < time.Second { p.SetTTL(s.Clock(), defaults.ProvisioningTokenTTL) } data, err := services.MarshalProvisionToken(p) if err != nil { return trace.Wrap(err) } item := backend.Item{ Key: backend.Key(tokensPrefix, p.GetName()), Value: data, Expires: p.Expiry(), ID: p.GetResourceID(), } _, err = s.Put(context.TODO(), item) if err != nil { return trace.Wrap(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/provisioning.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/provisioning.go#L66-L69
go
train
// DeleteAllTokens deletes all provisioning tokens
func (s *ProvisioningService) DeleteAllTokens() error
// DeleteAllTokens deletes all provisioning tokens func (s *ProvisioningService) DeleteAllTokens() error
{ startKey := backend.Key(tokensPrefix) return s.DeleteRange(context.TODO(), startKey, backend.RangeEnd(startKey)) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/provisioning.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/provisioning.go#L72-L82
go
train
// GetToken finds and returns token by ID
func (s *ProvisioningService) GetToken(token string) (services.ProvisionToken, error)
// GetToken finds and returns token by ID func (s *ProvisioningService) GetToken(token string) (services.ProvisionToken, error)
{ if token == "" { return nil, trace.BadParameter("missing parameter token") } item, err := s.Get(context.TODO(), backend.Key(tokensPrefix, token)) if err != nil { return nil, trace.Wrap(err) } return services.UnmarshalProvisionToken(item.Value, services.SkipValidation(), services.WithResourceID(item.ID), services.WithExpires(item.Expires)) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/provisioning.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/provisioning.go#L93-L110
go
train
// GetTokens returns all active (non-expired) provisioning tokens
func (s *ProvisioningService) GetTokens(opts ...services.MarshalOption) ([]services.ProvisionToken, error)
// GetTokens returns all active (non-expired) provisioning tokens func (s *ProvisioningService) GetTokens(opts ...services.MarshalOption) ([]services.ProvisionToken, error)
{ startKey := backend.Key(tokensPrefix) result, err := s.GetRange(context.TODO(), startKey, backend.RangeEnd(startKey), backend.NoLimit) if err != nil { return nil, trace.Wrap(err) } tokens := make([]services.ProvisionToken, len(result.Items)) for i, item := range result.Items { t, err := services.UnmarshalProvisionToken(item.Value, services.AddOptions(opts, services.SkipValidation(), services.WithResourceID(item.ID), services.WithExpires(item.Expires))...) if err != nil { return nil, trace.Wrap(err) } tokens[i] = t } return tokens, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/clusterconfig.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/clusterconfig.go#L97-L112
go
train
// NewClusterConfig is a convenience wrapper to create a ClusterConfig resource.
func NewClusterConfig(spec ClusterConfigSpecV3) (ClusterConfig, error)
// NewClusterConfig is a convenience wrapper to create a ClusterConfig resource. func NewClusterConfig(spec ClusterConfigSpecV3) (ClusterConfig, error)
{ cc := ClusterConfigV3{ Kind: KindClusterConfig, Version: V3, Metadata: Metadata{ Name: MetaNameClusterConfig, Namespace: defaults.Namespace, }, Spec: spec, } if err := cc.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } return &cc, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/clusterconfig.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/clusterconfig.go#L116-L131
go
train
// DefaultClusterConfig is used as the default cluster configuration when // one is not specified (record at node).
func DefaultClusterConfig() ClusterConfig
// DefaultClusterConfig is used as the default cluster configuration when // one is not specified (record at node). func DefaultClusterConfig() ClusterConfig
{ return &ClusterConfigV3{ Kind: KindClusterConfig, Version: V3, Metadata: Metadata{ Name: MetaNameClusterConfig, Namespace: defaults.Namespace, }, Spec: ClusterConfigSpecV3{ SessionRecording: RecordAtNode, ProxyChecksHostKeys: HostKeyCheckYes, KeepAliveInterval: NewDuration(defaults.KeepAliveInterval), KeepAliveCountMax: int64(defaults.KeepAliveCountMax), }, } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/clusterconfig.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/clusterconfig.go#L140-L149
go
train
// AuditConfigFromObject returns audit config from interface object
func AuditConfigFromObject(in interface{}) (*AuditConfig, error)
// AuditConfigFromObject returns audit config from interface object func AuditConfigFromObject(in interface{}) (*AuditConfig, error)
{ var cfg AuditConfig if in == nil { return &cfg, nil } if err := utils.ObjectToStruct(in, &cfg); err != nil { return nil, trace.Wrap(err) } return &cfg, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/clusterconfig.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/clusterconfig.go#L219-L221
go
train
// SetExpiry sets expiry time for the object
func (c *ClusterConfigV3) SetExpiry(expires time.Time)
// SetExpiry sets expiry time for the object func (c *ClusterConfigV3) SetExpiry(expires time.Time)
{ c.Metadata.SetExpiry(expires) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/clusterconfig.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/clusterconfig.go#L279-L281
go
train
// SetClientIdleTimeout sets client idle timeout setting
func (c *ClusterConfigV3) SetClientIdleTimeout(d time.Duration)
// SetClientIdleTimeout sets client idle timeout setting func (c *ClusterConfigV3) SetClientIdleTimeout(d time.Duration)
{ c.Spec.ClientIdleTimeout = Duration(d) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/clusterconfig.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/clusterconfig.go#L289-L291
go
train
// SetDisconnectExpiredCert sets disconnect client with expired certificate setting
func (c *ClusterConfigV3) SetDisconnectExpiredCert(b bool)
// SetDisconnectExpiredCert sets disconnect client with expired certificate setting func (c *ClusterConfigV3) SetDisconnectExpiredCert(b bool)
{ c.Spec.DisconnectExpiredCert = NewBool(b) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/clusterconfig.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/clusterconfig.go#L299-L301
go
train
// SetKeepAliveInterval sets the keep-alive interval.
func (c *ClusterConfigV3) SetKeepAliveInterval(t time.Duration)
// SetKeepAliveInterval sets the keep-alive interval. func (c *ClusterConfigV3) SetKeepAliveInterval(t time.Duration)
{ c.Spec.KeepAliveInterval = Duration(t) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/clusterconfig.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/clusterconfig.go#L316-L354
go
train
// CheckAndSetDefaults checks validity of all parameters and sets defaults.
func (c *ClusterConfigV3) CheckAndSetDefaults() error
// CheckAndSetDefaults checks validity of all parameters and sets defaults. func (c *ClusterConfigV3) CheckAndSetDefaults() error
{ // make sure we have defaults for all metadata fields err := c.Metadata.CheckAndSetDefaults() if err != nil { return trace.Wrap(err) } if c.Spec.SessionRecording == "" { c.Spec.SessionRecording = RecordAtNode } if c.Spec.ProxyChecksHostKeys == "" { c.Spec.ProxyChecksHostKeys = HostKeyCheckYes } // check if the recording type is valid all := []string{RecordAtNode, RecordAtProxy, RecordOff} ok := utils.SliceContainsStr(all, c.Spec.SessionRecording) if !ok { return trace.BadParameter("session_recording must either be: %v", strings.Join(all, ",")) } // check if host key checking mode is valid all = []string{HostKeyCheckYes, HostKeyCheckNo} ok = utils.SliceContainsStr(all, c.Spec.ProxyChecksHostKeys) if !ok { return trace.BadParameter("proxy_checks_host_keys must be one of: %v", strings.Join(all, ",")) } // Set the keep-alive interval and max missed keep-alives before the // client is disconnected. if c.Spec.KeepAliveInterval.Duration() == 0 { c.Spec.KeepAliveInterval = NewDuration(defaults.KeepAliveInterval) } if c.Spec.KeepAliveCountMax == 0 { c.Spec.KeepAliveCountMax = int64(defaults.KeepAliveCountMax) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/clusterconfig.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/clusterconfig.go#L363-L366
go
train
// String represents a human readable version of the cluster name.
func (c *ClusterConfigV3) String() string
// String represents a human readable version of the cluster name. func (c *ClusterConfigV3) String() string
{ return fmt.Sprintf("ClusterConfig(SessionRecording=%v, ClusterID=%v, ProxyChecksHostKeys=%v)", c.Spec.SessionRecording, c.Spec.ClusterID, c.Spec.ProxyChecksHostKeys) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/clusterconfig.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/clusterconfig.go#L427-L435
go
train
// GetClusterConfigSchema returns the schema with optionally injected // schema for extensions.
func GetClusterConfigSchema(extensionSchema string) string
// GetClusterConfigSchema returns the schema with optionally injected // schema for extensions. func GetClusterConfigSchema(extensionSchema string) string
{ var clusterConfigSchema string if clusterConfigSchema == "" { clusterConfigSchema = fmt.Sprintf(ClusterConfigSpecSchemaTemplate, "") } else { clusterConfigSchema = fmt.Sprintf(ClusterConfigSpecSchemaTemplate, ","+extensionSchema) } return fmt.Sprintf(V2SchemaTemplate, MetadataSchema, clusterConfigSchema, DefaultDefinitions) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/clusterconfig.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/clusterconfig.go#L464-L499
go
train
// Unmarshal unmarshals ClusterConfig from JSON.
func (t *TeleportClusterConfigMarshaler) Unmarshal(bytes []byte, opts ...MarshalOption) (ClusterConfig, error)
// Unmarshal unmarshals ClusterConfig from JSON. func (t *TeleportClusterConfigMarshaler) Unmarshal(bytes []byte, opts ...MarshalOption) (ClusterConfig, error)
{ var clusterConfig ClusterConfigV3 if len(bytes) == 0 { return nil, trace.BadParameter("missing resource data") } cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } if cfg.SkipValidation { if err := utils.FastUnmarshal(bytes, &clusterConfig); err != nil { return nil, trace.BadParameter(err.Error()) } } else { err = utils.UnmarshalWithSchema(GetClusterConfigSchema(""), &clusterConfig, bytes) if err != nil { return nil, trace.BadParameter(err.Error()) } } err = clusterConfig.CheckAndSetDefaults() if err != nil { return nil, trace.Wrap(err) } if cfg.ID != 0 { clusterConfig.SetResourceID(cfg.ID) } if !cfg.Expires.IsZero() { clusterConfig.SetExpiry(cfg.Expires) } return &clusterConfig, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/clusterconfig.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/clusterconfig.go#L502-L520
go
train
// Marshal marshals ClusterConfig to JSON.
func (t *TeleportClusterConfigMarshaler) Marshal(c ClusterConfig, opts ...MarshalOption) ([]byte, error)
// Marshal marshals ClusterConfig to JSON. func (t *TeleportClusterConfigMarshaler) Marshal(c ClusterConfig, opts ...MarshalOption) ([]byte, error)
{ cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } switch resource := c.(type) { case *ClusterConfigV3: if !cfg.PreserveResourceID { // avoid modifying the original object // to prevent unexpected data races copy := *resource copy.SetResourceID(0) resource = &copy } return utils.FastMarshal(resource) default: return nil, trace.BadParameter("unrecognized resource version %T", c) } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/ver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/ver.go#L30-L51
go
train
// CheckVersions compares client and server versions and makes sure that the // client version is greater than or equal to the minimum version supported // by the server.
func CheckVersions(clientVersion string, minClientVersion string) error
// CheckVersions compares client and server versions and makes sure that the // client version is greater than or equal to the minimum version supported // by the server. func CheckVersions(clientVersion string, minClientVersion string) error
{ clientSemver, err := semver.NewVersion(clientVersion) if err != nil { return trace.Wrap(err, "unsupported version format, need semver format: %q, e.g 1.0.0", clientVersion) } minClientSemver, err := semver.NewVersion(minClientVersion) if err != nil { return trace.Wrap(err, "unsupported version format, need semver format: %q, e.g 1.0.0", minClientVersion) } if clientSemver.Compare(*minClientSemver) < 0 { errorMessage := fmt.Sprintf("minimum client version supported by the server "+ "is %v. Please upgrade the client, downgrade the server, or use the "+ "--skip-version-check flag to by-pass this check.", minClientVersion) return trace.BadParameter(errorMessage) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/exec.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/exec.go#L78-L104
go
train
// NewExecRequest creates a new local or remote Exec.
func NewExecRequest(ctx *ServerContext, command string) (Exec, error)
// NewExecRequest creates a new local or remote Exec. func NewExecRequest(ctx *ServerContext, command string) (Exec, error)
{ // It doesn't matter what mode the cluster is in, if this is a Teleport node // return a local *localExec. if ctx.srv.Component() == teleport.ComponentNode { return &localExec{ Ctx: ctx, Command: command, }, nil } // When in recording mode, return an *remoteExec which will execute the // command on a remote host. This is used by in-memory forwarding nodes. if ctx.ClusterConfig.GetSessionRecording() == services.RecordAtProxy { return &remoteExec{ ctx: ctx, command: command, session: ctx.RemoteSession, }, nil } // Otherwise return a *localExec which will execute locally on the server. // used by the regular Teleport nodes. return &localExec{ Ctx: ctx, Command: command, }, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/exec.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/exec.go#L131-L172
go
train
// Start launches the given command returns (nil, nil) if successful. // ExecResult is only used to communicate an error while launching.
func (e *localExec) Start(channel ssh.Channel) (*ExecResult, error)
// Start launches the given command returns (nil, nil) if successful. // ExecResult is only used to communicate an error while launching. func (e *localExec) Start(channel ssh.Channel) (*ExecResult, error)
{ var err error // parse the command to see if the user is trying to run scp err = e.transformSecureCopy() if err != nil { return nil, trace.Wrap(err) } // transforms the Command string into *exec.Cmd e.Cmd, err = prepareCommand(e.Ctx) if err != nil { return nil, trace.Wrap(err) } // hook up stdout/err the channel so the user can interact with the command e.Cmd.Stderr = channel.Stderr() e.Cmd.Stdout = channel inputWriter, err := e.Cmd.StdinPipe() if err != nil { return nil, trace.Wrap(err) } go func() { // copy from the channel (client) into stdin of the process io.Copy(inputWriter, channel) inputWriter.Close() }() if err := e.Cmd.Start(); err != nil { e.Ctx.Warningf("%v start failure err: %v", e, err) execResult, err := collectLocalStatus(e.Cmd, trace.ConvertSystemError(err)) // emit the result of execution to the audit log emitExecAuditEvent(e.Ctx, e.GetCommand(), execResult, err) return execResult, trace.Wrap(err) } e.Ctx.Infof("[LOCAL EXEC] Started command: %q", e.Command) return nil, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/exec.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/exec.go#L175-L188
go
train
// Wait will block while the command executes.
func (e *localExec) Wait() (*ExecResult, error)
// Wait will block while the command executes. func (e *localExec) Wait() (*ExecResult, error)
{ if e.Cmd.Process == nil { e.Ctx.Errorf("no process") } // wait for the command to complete, then figure out if the command // successfully exited or if it exited in failure execResult, err := collectLocalStatus(e.Cmd, e.Cmd.Wait()) // emit the result of execution to the audit log emitExecAuditEvent(e.Ctx, e.GetCommand(), execResult, err) return execResult, trace.Wrap(err) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/exec.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/exec.go#L196-L228
go
train
// prepareInteractiveCommand configures exec.Cmd object for launching an // interactive command (or a shell).
func prepareInteractiveCommand(ctx *ServerContext) (*exec.Cmd, error)
// prepareInteractiveCommand configures exec.Cmd object for launching an // interactive command (or a shell). func prepareInteractiveCommand(ctx *ServerContext) (*exec.Cmd, error)
{ var ( err error runShell bool ) // determine shell for the given OS user: if ctx.ExecRequest.GetCommand() == "" { runShell = true cmdName, err := shell.GetLoginShell(ctx.Identity.Login) ctx.ExecRequest.SetCommand(cmdName) if err != nil { log.Error(err) return nil, trace.Wrap(err) } // in test mode short-circuit to /bin/sh if ctx.IsTestStub { ctx.ExecRequest.SetCommand("/bin/sh") } } c, err := prepareCommand(ctx) if err != nil { return nil, trace.Wrap(err) } // this configures shell to run in 'login' mode. from openssh source: // "If we have no command, execute the shell. In this case, the shell // name to be passed in argv[0] is preceded by '-' to indicate that // this is a login shell." // https://github.com/openssh/openssh-portable/blob/master/session.c if runShell { c.Args = []string{"-" + filepath.Base(ctx.ExecRequest.GetCommand())} } return c, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/exec.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/exec.go#L266-L387
go
train
// prepareCommand configures exec.Cmd for executing a given command within an SSH // session. // // 'cmd' is the string passed as parameter to 'ssh' command, like "ls -l /" // // If 'cmd' does not have any spaces in it, it gets executed directly, otherwise // it is passed to user's shell for interpretation
func prepareCommand(ctx *ServerContext) (*exec.Cmd, error)
// prepareCommand configures exec.Cmd for executing a given command within an SSH // session. // // 'cmd' is the string passed as parameter to 'ssh' command, like "ls -l /" // // If 'cmd' does not have any spaces in it, it gets executed directly, otherwise // it is passed to user's shell for interpretation func prepareCommand(ctx *ServerContext) (*exec.Cmd, error)
{ osUserName := ctx.Identity.Login // configure UID & GID of the requested OS user: osUser, err := user.Lookup(osUserName) if err != nil { return nil, trace.Wrap(err) } uid, err := strconv.Atoi(osUser.Uid) if err != nil { return nil, trace.Wrap(err) } gid, err := strconv.Atoi(osUser.Gid) if err != nil { return nil, trace.Wrap(err) } // get user's shell: shell, err := shell.GetLoginShell(ctx.Identity.Login) if err != nil { log.Warn(err) } if ctx.IsTestStub { shell = "/bin/sh" } // by default, execute command using user's shell like openssh does: // https://github.com/openssh/openssh-portable/blob/master/session.c c := exec.Command(shell, "-c", ctx.ExecRequest.GetCommand()) clusterName, err := ctx.srv.GetAccessPoint().GetClusterName() if err != nil { return nil, trace.Wrap(err) } c.Env = []string{ "LANG=en_US.UTF-8", getDefaultEnvPath(osUser.Uid, defaultLoginDefsPath), "HOME=" + osUser.HomeDir, "USER=" + osUserName, "SHELL=" + shell, teleport.SSHTeleportUser + "=" + ctx.Identity.TeleportUser, teleport.SSHSessionWebproxyAddr + "=" + ctx.ProxyPublicAddress(), teleport.SSHTeleportHostUUID + "=" + ctx.srv.ID(), teleport.SSHTeleportClusterName + "=" + clusterName.GetClusterName(), } c.Dir = osUser.HomeDir c.SysProcAttr = &syscall.SysProcAttr{} // execute the command under requested user's UID:GID me, err := user.Current() if err != nil { return nil, trace.Wrap(err) } if me.Uid != osUser.Uid || me.Gid != osUser.Gid { userGroups, err := osUser.GroupIds() if err != nil { return nil, trace.Wrap(err) } groups := make([]uint32, 0) for _, sgid := range userGroups { igid, err := strconv.Atoi(sgid) if err != nil { log.Warnf("Cannot interpret user group: '%v'", sgid) } else { groups = append(groups, uint32(igid)) } } if len(groups) == 0 { groups = append(groups, uint32(gid)) } c.SysProcAttr.Credential = &syscall.Credential{ Uid: uint32(uid), Gid: uint32(gid), Groups: groups, } c.SysProcAttr.Setsid = true } // apply environment variables passed from the client for n, v := range ctx.env { c.Env = append(c.Env, fmt.Sprintf("%s=%s", n, v)) } // if a terminal was allocated, apply terminal type variable if ctx.session != nil { c.Env = append(c.Env, fmt.Sprintf("TERM=%v", ctx.session.term.GetTermType())) } // apply SSH_xx environment variables remoteHost, remotePort, err := net.SplitHostPort(ctx.Conn.RemoteAddr().String()) if err != nil { log.Warn(err) } else { localHost, localPort, err := net.SplitHostPort(ctx.Conn.LocalAddr().String()) if err != nil { log.Warn(err) } else { c.Env = append(c.Env, fmt.Sprintf("SSH_CLIENT=%s %s %s", remoteHost, remotePort, localPort), fmt.Sprintf("SSH_CONNECTION=%s %s %s %s", remoteHost, remotePort, localHost, localPort)) } } if ctx.session != nil { if ctx.session.term != nil { c.Env = append(c.Env, fmt.Sprintf("SSH_TTY=%s", ctx.session.term.TTY().Name())) } if ctx.session.id != "" { c.Env = append(c.Env, fmt.Sprintf("%s=%s", teleport.SSHSessionID, ctx.session.id)) } } // if the server allows reading in of ~/.tsh/environment read it in // and pass environment variables along to new session if ctx.srv.PermitUserEnvironment() { filename := filepath.Join(osUser.HomeDir, ".tsh", "environment") userEnvs, err := utils.ReadEnvironmentFile(filename) if err != nil { return nil, trace.Wrap(err) } c.Env = append(c.Env, userEnvs...) } return c, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/exec.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/exec.go#L423-L444
go
train
// Start launches the given command returns (nil, nil) if successful. // ExecResult is only used to communicate an error while launching.
func (r *remoteExec) Start(ch ssh.Channel) (*ExecResult, error)
// Start launches the given command returns (nil, nil) if successful. // ExecResult is only used to communicate an error while launching. func (r *remoteExec) Start(ch ssh.Channel) (*ExecResult, error)
{ // hook up stdout/err the channel so the user can interact with the command r.session.Stdout = ch r.session.Stderr = ch.Stderr() inputWriter, err := r.session.StdinPipe() if err != nil { return nil, trace.Wrap(err) } go func() { // copy from the channel (client) into stdin of the process io.Copy(inputWriter, ch) inputWriter.Close() }() err = r.session.Start(r.command) if err != nil { return nil, trace.Wrap(err) } return nil, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/exec.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/exec.go#L448-L457
go
train
// Wait will block while the command executes then return the result as well // as emit an event to the Audit Log.
func (r *remoteExec) Wait() (*ExecResult, error)
// Wait will block while the command executes then return the result as well // as emit an event to the Audit Log. func (r *remoteExec) Wait() (*ExecResult, error)
{ // block until the command is finished and then figure out if the command // successfully exited or if it exited in failure execResult, err := r.collectRemoteStatus(r.session.Wait()) // emit the result of execution to the audit log emitExecAuditEvent(r.ctx, r.command, execResult, err) return execResult, trace.Wrap(err) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/exec.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/exec.go#L549-L599
go
train
// getDefaultEnvPath returns the default value of PATH environment variable for // new logins (prior to shell) based on login.defs. Returns a strings which // looks like "PATH=/usr/bin:/bin"
func getDefaultEnvPath(uid string, loginDefsPath string) string
// getDefaultEnvPath returns the default value of PATH environment variable for // new logins (prior to shell) based on login.defs. Returns a strings which // looks like "PATH=/usr/bin:/bin" func getDefaultEnvPath(uid string, loginDefsPath string) string
{ envPath := defaultEnvPath envSuPath := defaultEnvPath // open file, if it doesn't exist return a default path and move on f, err := os.Open(loginDefsPath) if err != nil { log.Infof("Unable to open %q: %v: returning default path: %q", loginDefsPath, err, defaultEnvPath) return defaultEnvPath } defer f.Close() // read path to login.defs file /etc/login.defs line by line: scanner := bufio.NewScanner(f) for scanner.Scan() { line := strings.TrimSpace(scanner.Text()) // skip comments and empty lines: if line == "" || line[0] == '#' { continue } // look for a line that starts with ENV_SUPATH or ENV_PATH fields := strings.Fields(line) if len(fields) > 1 { if fields[0] == "ENV_PATH" { envPath = fields[1] } if fields[0] == "ENV_SUPATH" { envSuPath = fields[1] } } } // if any error occurs while reading the file, return the default value err = scanner.Err() if err != nil { log.Warnf("Unable to read %q: %v: returning default path: %q", loginDefsPath, err, defaultEnvPath) return defaultEnvPath } // if requesting path for uid 0 and no ENV_SUPATH is given, fallback to // ENV_PATH first, then the default path. if uid == "0" { if envSuPath == defaultEnvPath { return envPath } return envSuPath } return envPath }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/exec.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/exec.go#L602-L631
go
train
// parseSecureCopy will parse a command and return if it's secure copy or not.
func parseSecureCopy(path string) (string, string, bool, error)
// parseSecureCopy will parse a command and return if it's secure copy or not. func parseSecureCopy(path string) (string, string, bool, error)
{ parts := strings.Fields(path) if len(parts) == 0 { return "", "", false, trace.BadParameter("no executable found") } // Look for the -t flag, it indicates that an upload occurred. The other // flags do no matter for now. action := events.SCPActionDownload if utils.SliceContainsStr(parts, "-t") { action = events.SCPActionUpload } // Exract the name of the Teleport executable on disk. teleportPath, err := os.Executable() if err != nil { return "", "", false, trace.Wrap(err) } _, teleportBinary := filepath.Split(teleportPath) // Extract the name of the executable that was run. The command was secure // copy if the executable was "scp" or "teleport". _, executable := filepath.Split(parts[0]) switch executable { case teleport.SCP, teleportBinary: return parts[len(parts)-1], action, true, nil default: return "", "", false, nil } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/identity.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/identity.go#L33-L43
go
train
// NewKey generates a new unsigned key. Such key must be signed by a // Teleport CA (auth server) before it becomes useful.
func NewKey() (key *Key, err error)
// NewKey generates a new unsigned key. Such key must be signed by a // Teleport CA (auth server) before it becomes useful. func NewKey() (key *Key, err error)
{ priv, pub, err := native.GenerateKeyPair("") if err != nil { return nil, trace.Wrap(err) } return &Key{ Priv: priv, Pub: pub, }, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/identity.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/identity.go#L62-L127
go
train
// MakeIdentityFile takes a username + their credentials and saves them to disk // in a specified format
func MakeIdentityFile(filePath string, key *Key, format IdentityFileFormat, certAuthorities []services.CertAuthority) (err error)
// MakeIdentityFile takes a username + their credentials and saves them to disk // in a specified format func MakeIdentityFile(filePath string, key *Key, format IdentityFileFormat, certAuthorities []services.CertAuthority) (err error)
{ const ( // the files and the dir will be created with these permissions: fileMode = 0600 dirMode = 0700 ) if filePath == "" { return trace.BadParameter("identity location is not specified") } var output io.Writer = os.Stdout switch format { // dump user identity into a single file: case IdentityFormatFile: f, err := os.OpenFile(filePath, os.O_CREATE|os.O_WRONLY, fileMode) if err != nil { return trace.Wrap(err) } output = f defer f.Close() // write key: if _, err = output.Write(key.Priv); err != nil { return trace.Wrap(err) } // append cert: if _, err = output.Write(key.Cert); err != nil { return trace.Wrap(err) } // append trusted host certificate authorities for _, ca := range certAuthorities { for _, publicKey := range ca.GetCheckingKeys() { data, err := sshutils.MarshalAuthorizedHostsFormat(ca.GetClusterName(), publicKey, nil) if err != nil { return trace.Wrap(err) } if _, err = output.Write([]byte(data)); err != nil { return trace.Wrap(err) } if _, err = output.Write([]byte("\n")); err != nil { return trace.Wrap(err) } } } // dump user identity into separate files: case IdentityFormatOpenSSH: keyPath := filePath certPath := keyPath + "-cert.pub" err = ioutil.WriteFile(certPath, key.Cert, fileMode) if err != nil { return trace.Wrap(err) } err = ioutil.WriteFile(keyPath, key.Priv, fileMode) if err != nil { return trace.Wrap(err) } default: return trace.BadParameter("unsupported identity format: %q, use either %q or %q", format, IdentityFormatFile, IdentityFormatOpenSSH) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/filesessions/fileuploader.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/filesessions/fileuploader.go#L41-L49
go
train
// CheckAndSetDefaults checks and sets default values of file handler config
func (s *Config) CheckAndSetDefaults() error
// CheckAndSetDefaults checks and sets default values of file handler config func (s *Config) CheckAndSetDefaults() error
{ if s.Directory == "" { return trace.BadParameter("missing parameter Directory") } if !utils.IsDir(s.Directory) { return trace.BadParameter("path %q does not exist or is not a directory", s.Directory) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/filesessions/fileuploader.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/filesessions/fileuploader.go#L52-L64
go
train
// NewHandler returns new file sessions handler
func NewHandler(cfg Config) (*Handler, error)
// NewHandler returns new file sessions handler func NewHandler(cfg Config) (*Handler, error)
{ if err := cfg.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } h := &Handler{ Entry: log.WithFields(log.Fields{ trace.Component: teleport.Component(teleport.SchemeFile), }), Config: cfg, } return h, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/filesessions/fileuploader.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/filesessions/fileuploader.go#L82-L95
go
train
// Download downloads session recording from storage, in case of file handler reads the // file from local directory
func (l *Handler) Download(ctx context.Context, sessionID session.ID, writer io.WriterAt) error
// Download downloads session recording from storage, in case of file handler reads the // file from local directory func (l *Handler) Download(ctx context.Context, sessionID session.ID, writer io.WriterAt) error
{ path := l.path(sessionID) _, err := os.Stat(filepath.Dir(path)) f, err := os.Open(path) if err != nil { return trace.ConvertSystemError(err) } defer f.Close() _, err = io.Copy(writer.(io.Writer), f) if err != nil { return trace.Wrap(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/filesessions/fileuploader.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/filesessions/fileuploader.go#L99-L111
go
train
// Upload uploads session recording to file storage, in case of file handler, // writes the file to local directory
func (l *Handler) Upload(ctx context.Context, sessionID session.ID, reader io.Reader) (string, error)
// Upload uploads session recording to file storage, in case of file handler, // writes the file to local directory func (l *Handler) Upload(ctx context.Context, sessionID session.ID, reader io.Reader) (string, error)
{ path := l.path(sessionID) f, err := os.Create(path) if err != nil { return "", trace.ConvertSystemError(err) } defer f.Close() _, err = io.Copy(f, reader) if err != nil { return "", trace.Wrap(err) } return fmt.Sprintf("%v://%v", teleport.SchemeFile, path), nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/token_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/token_command.go#L68-L88
go
train
// Initialize allows TokenCommand to plug itself into the CLI parser
func (c *TokenCommand) Initialize(app *kingpin.Application, config *service.Config)
// Initialize allows TokenCommand to plug itself into the CLI parser func (c *TokenCommand) Initialize(app *kingpin.Application, config *service.Config)
{ c.config = config tokens := app.Command("tokens", "List or revoke invitation tokens") // tctl tokens add ..." c.tokenAdd = tokens.Command("add", "Create a invitation token") c.tokenAdd.Flag("type", "Type of token to add").Required().StringVar(&c.tokenType) c.tokenAdd.Flag("value", "Value of token to add").StringVar(&c.value) c.tokenAdd.Flag("ttl", fmt.Sprintf("Set expiration time for token, default is %v hour, maximum is %v hours", int(defaults.SignupTokenTTL/time.Hour), int(defaults.MaxSignupTokenTTL/time.Hour))). Default(fmt.Sprintf("%v", defaults.SignupTokenTTL)).DurationVar(&c.ttl) // "tctl tokens rm ..." c.tokenDel = tokens.Command("rm", "Delete/revoke an invitation token").Alias("del") c.tokenDel.Arg("token", "Token to delete").StringVar(&c.value) // "tctl tokens ls" c.tokenList = tokens.Command("ls", "List node and user invitation tokens") c.tokenList.Flag("format", "Output format, 'text' or 'json'").Hidden().Default(teleport.Text).StringVar(&c.format) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/token_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/token_command.go#L91-L103
go
train
// TryRun takes the CLI command as an argument (like "nodes ls") and executes it.
func (c *TokenCommand) TryRun(cmd string, client auth.ClientI) (match bool, err error)
// TryRun takes the CLI command as an argument (like "nodes ls") and executes it. func (c *TokenCommand) TryRun(cmd string, client auth.ClientI) (match bool, err error)
{ switch cmd { case c.tokenAdd.FullCommand(): err = c.Add(client) case c.tokenDel.FullCommand(): err = c.Del(client) case c.tokenList.FullCommand(): err = c.List(client) default: return false, nil } return true, trace.Wrap(err) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/token_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/token_command.go#L106-L158
go
train
// Add is called to execute "tokens add ..." command.
func (c *TokenCommand) Add(client auth.ClientI) error
// Add is called to execute "tokens add ..." command. func (c *TokenCommand) Add(client auth.ClientI) error
{ // Parse string to see if it's a type of role that Teleport supports. roles, err := teleport.ParseRoles(c.tokenType) if err != nil { return trace.Wrap(err) } // Generate token. token, err := client.GenerateToken(auth.GenerateTokenRequest{ Roles: roles, TTL: c.ttl, Token: c.value, }) if err != nil { return trace.Wrap(err) } // Calculate the CA pin for this cluster. The CA pin is used by the client // to verify the identity of the Auth Server. caPin, err := calculateCAPin(client) if err != nil { return trace.Wrap(err) } // Get list of auth servers. Used to print friendly signup message. authServers, err := client.GetAuthServers() if err != nil { return trace.Wrap(err) } if len(authServers) == 0 { return trace.Errorf("this cluster has no auth servers") } // Print signup message. switch { case roles.Include(teleport.RoleTrustedCluster), roles.Include(teleport.LegacyClusterTokenType): fmt.Printf(trustedClusterMessage, token, int(c.ttl.Minutes())) default: fmt.Printf(nodeMessage, token, int(c.ttl.Minutes()), strings.ToLower(roles.String()), token, caPin, authServers[0].GetAddr(), int(c.ttl.Minutes()), authServers[0].GetAddr()) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/token_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/token_command.go#L161-L170
go
train
// Del is called to execute "tokens del ..." command.
func (c *TokenCommand) Del(client auth.ClientI) error
// Del is called to execute "tokens del ..." command. func (c *TokenCommand) Del(client auth.ClientI) error
{ if c.value == "" { return trace.Errorf("Need an argument: token") } if err := client.DeleteToken(c.value); err != nil { return trace.Wrap(err) } fmt.Printf("Token %s has been deleted\n", c.value) return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/token_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/token_command.go#L173-L207
go
train
// List is called to execute "tokens ls" command.
func (c *TokenCommand) List(client auth.ClientI) error
// List is called to execute "tokens ls" command. func (c *TokenCommand) List(client auth.ClientI) error
{ tokens, err := client.GetTokens() if err != nil { return trace.Wrap(err) } if len(tokens) == 0 { fmt.Println("No active tokens found.") return nil } // Sort by expire time. sort.Slice(tokens, func(i, j int) bool { return tokens[i].Expiry().Unix() < tokens[j].Expiry().Unix() }) if c.format == teleport.Text { tokensView := func() string { table := asciitable.MakeTable([]string{"Token", "Type", "Expiry Time (UTC)"}) for _, t := range tokens { expiry := "never" if t.Expiry().Unix() > 0 { expiry = t.Expiry().Format(time.RFC822) } table.AddRow([]string{t.GetName(), t.GetRoles().String(), expiry}) } return table.AsBuffer().String() } fmt.Printf(tokensView()) } else { data, err := json.MarshalIndent(tokens, "", " ") if err != nil { return trace.Wrap(err, "failed to marshal tokens") } fmt.Printf(string(data)) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/token_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/token_command.go#L210-L221
go
train
// calculateCAPin returns the SPKI pin for the local cluster.
func calculateCAPin(client auth.ClientI) (string, error)
// calculateCAPin returns the SPKI pin for the local cluster. func calculateCAPin(client auth.ClientI) (string, error)
{ localCA, err := client.GetClusterCACert() if err != nil { return "", trace.Wrap(err) } tlsCA, err := tlsca.ParseCertificatePEM(localCA.TLSCA) if err != nil { return "", trace.Wrap(err) } return utils.CalculateSPKI(tlsCA), nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/kube.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/kube.go#L40-L45
go
train
// CheckAndSetDefaults checks and sets defaults
func (a *KubeCSR) CheckAndSetDefaults() error
// CheckAndSetDefaults checks and sets defaults func (a *KubeCSR) CheckAndSetDefaults() error
{ if len(a.CSR) == 0 { return trace.BadParameter("missing parameter 'csr'") } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/kube.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/kube.go#L61-L148
go
train
// ProcessKubeCSR processes CSR request against Kubernetes CA, returns // signed certificate if sucessful.
func (s *AuthServer) ProcessKubeCSR(req KubeCSR) (*KubeCSRResponse, error)
// ProcessKubeCSR processes CSR request against Kubernetes CA, returns // signed certificate if sucessful. func (s *AuthServer) ProcessKubeCSR(req KubeCSR) (*KubeCSRResponse, error)
{ if !modules.GetModules().SupportsKubernetes() { return nil, trace.AccessDenied( "this teleport cluster does not support kubernetes, please contact system administrator for support") } if err := req.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } clusterName, err := s.GetClusterName() if err != nil { return nil, trace.Wrap(err) } // Certificate for remote cluster is a user certificate // with special provisions. log.Debugf("Generating certificate to access remote Kubernetes clusters.") hostCA, err := s.GetCertAuthority(services.CertAuthID{ Type: services.HostCA, DomainName: req.ClusterName, }, false) if err != nil { return nil, trace.Wrap(err) } user, err := s.GetUser(req.Username) if err != nil { return nil, trace.Wrap(err) } roles, err := services.FetchRoles(user.GetRoles(), s, user.GetTraits()) if err != nil { return nil, trace.Wrap(err) } ttl := roles.AdjustSessionTTL(defaults.CertDuration) // extract and encode the kubernetes groups of the authenticated // user in the newly issued certificate kubernetesGroups, err := roles.CheckKubeGroups(0) if err != nil { return nil, trace.Wrap(err) } csr, err := tlsca.ParseCertificateRequestPEM(req.CSR) if err != nil { return nil, trace.Wrap(err) } userCA, err := s.Trust.GetCertAuthority(services.CertAuthID{ Type: services.UserCA, DomainName: clusterName.GetClusterName(), }, true) if err != nil { return nil, trace.Wrap(err) } // generate TLS certificate tlsAuthority, err := userCA.TLSCA() if err != nil { return nil, trace.Wrap(err) } identity := tlsca.Identity{ Username: user.GetName(), Groups: roles.RoleNames(), // Generate a certificate restricted for // use against a kubernetes endpoint, and not the API server endpoint // otherwise proxies can generate certs for any user. Usage: []string{teleport.UsageKubeOnly}, KubernetesGroups: kubernetesGroups, } certRequest := tlsca.CertificateRequest{ Clock: s.clock, PublicKey: csr.PublicKey, Subject: identity.Subject(), NotAfter: s.clock.Now().UTC().Add(ttl), } tlsCert, err := tlsAuthority.GenerateCertificate(certRequest) if err != nil { return nil, trace.Wrap(err) } re := &KubeCSRResponse{Cert: tlsCert} for _, keyPair := range hostCA.GetTLSKeyPairs() { re.CertAuthorities = append(re.CertAuthorities, keyPair.Cert) } return re, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/sanitize.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/sanitize.go#L40-L42
go
train
// isKeySafe checks if the passed in key conforms to whitelist
func isKeySafe(s []byte) bool
// isKeySafe checks if the passed in key conforms to whitelist func isKeySafe(s []byte) bool
{ return whitelistPattern.Match(s) && !blacklistPattern.Match(s) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/sanitize.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/sanitize.go#L64-L69
go
train
// GetRange returns query range
func (s *Sanitizer) GetRange(ctx context.Context, startKey []byte, endKey []byte, limit int) (*GetResult, error)
// GetRange returns query range func (s *Sanitizer) GetRange(ctx context.Context, startKey []byte, endKey []byte, limit int) (*GetResult, error)
{ if !isKeySafe(startKey) { return nil, trace.BadParameter(errorMessage) } return s.backend.GetRange(ctx, startKey, endKey, limit) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/sanitize.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/sanitize.go#L72-L77
go
train
// Create creates item if it does not exist
func (s *Sanitizer) Create(ctx context.Context, i Item) (*Lease, error)
// Create creates item if it does not exist func (s *Sanitizer) Create(ctx context.Context, i Item) (*Lease, error)
{ if !isKeySafe(i.Key) { return nil, trace.BadParameter(errorMessage) } return s.backend.Create(ctx, i) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/sanitize.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/sanitize.go#L99-L104
go
train
// Get returns a single item or not found error
func (s *Sanitizer) Get(ctx context.Context, key []byte) (*Item, error)
// Get returns a single item or not found error func (s *Sanitizer) Get(ctx context.Context, key []byte) (*Item, error)
{ if !isKeySafe(key) { return nil, trace.BadParameter(errorMessage) } return s.backend.Get(ctx, key) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/sanitize.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/sanitize.go#L108-L114
go
train
// CompareAndSwap compares item with existing item // and replaces is with replaceWith item
func (s *Sanitizer) CompareAndSwap(ctx context.Context, expected Item, replaceWith Item) (*Lease, error)
// CompareAndSwap compares item with existing item // and replaces is with replaceWith item func (s *Sanitizer) CompareAndSwap(ctx context.Context, expected Item, replaceWith Item) (*Lease, error)
{ if !isKeySafe(expected.Key) { return nil, trace.BadParameter(errorMessage) } return s.backend.CompareAndSwap(ctx, expected, replaceWith) }