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 Ansib...
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.Gi...
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 { ...
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...
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.NewPublic...
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...
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(e...
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 emp...
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 emp...
{ // 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 []str...
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.Op...
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.Sess...
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 "", ...
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: ...
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....
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 t...
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 == ni...
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 := filepa...
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.Sca...
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")...
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,...
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) } ...
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...
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,...
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(c...
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....
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 er...
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 == mappi...
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.CheckAndSetDefa...
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 = &cop...
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 := b...
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), ...
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.UnmarshalP...
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(defa...
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 } // c...
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, De...
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, tra...
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 ...
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...
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...
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/er...
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,...
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) } // ...
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 prepare...
{ 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 { ...
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(inputW...
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, trac...
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.Clo...
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 =...
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 IdentityFo...
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").St...
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 ...
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...
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() ...
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) }