repo stringlengths 5 67 | sha stringlengths 40 40 | path stringlengths 4 234 | url stringlengths 85 339 | language stringclasses 6
values | split stringclasses 3
values | doc stringlengths 3 51.2k | sign stringlengths 5 8.01k | problem stringlengths 13 51.2k | output stringlengths 0 3.87M |
|---|---|---|---|---|---|---|---|---|---|
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/provisioning.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/provisioning.go#L256-L263 | go | train | // String returns the human readable representation of a provisioning token. | func (p ProvisionTokenV1) String() string | // String returns the human readable representation of a provisioning token.
func (p ProvisionTokenV1) String() string | {
expires := "never"
if p.Expires.Unix() != 0 {
expires = p.Expires.String()
}
return fmt.Sprintf("ProvisionToken(Roles=%v, Expires=%v)",
p.Roles, expires)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/provisioning.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/provisioning.go#L281-L329 | go | train | // UnmarshalProvisionToken unmarshals provision token from JSON or YAML,
// sets defaults and checks the schema | func UnmarshalProvisionToken(data []byte, opts ...MarshalOption) (ProvisionToken, error) | // UnmarshalProvisionToken unmarshals provision token from JSON or YAML,
// sets defaults and checks the schema
func UnmarshalProvisionToken(data []byte, opts ...MarshalOption) (ProvisionToken, error) | {
if len(data) == 0 {
return nil, trace.BadParameter("missing provision token data")
}
cfg, err := collectOptions(opts)
if err != nil {
return nil, trace.Wrap(err)
}
var h ResourceHeader
err = utils.FastUnmarshal(data, &h)
if err != nil {
return nil, trace.Wrap(err)
}
switch h.Version {
case "":
... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/provisioning.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/provisioning.go#L332-L360 | go | train | // MarshalProvisionToken marshals provisioning token into JSON. | func MarshalProvisionToken(t ProvisionToken, opts ...MarshalOption) ([]byte, error) | // MarshalProvisionToken marshals provisioning token into JSON.
func MarshalProvisionToken(t ProvisionToken, opts ...MarshalOption) ([]byte, error) | {
cfg, err := collectOptions(opts)
if err != nil {
return nil, trace.Wrap(err)
}
type token1 interface {
V1() *ProvisionTokenV1
}
type token2 interface {
V2() *ProvisionTokenV2
}
version := cfg.GetVersion()
switch version {
case V1:
v, ok := t.(token1)
if !ok {
return nil, trace.BadParameter("do... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/proxy/proxy.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/proxy/proxy.go#L41-L53 | go | train | // NewClientConnWithDeadline establishes new client connection with specified deadline | func NewClientConnWithDeadline(conn net.Conn, addr string, config *ssh.ClientConfig) (*ssh.Client, error) | // NewClientConnWithDeadline establishes new client connection with specified deadline
func NewClientConnWithDeadline(conn net.Conn, addr string, config *ssh.ClientConfig) (*ssh.Client, error) | {
if config.Timeout > 0 {
conn.SetReadDeadline(time.Now().Add(config.Timeout))
}
c, chans, reqs, err := ssh.NewClientConn(conn, addr, config)
if err != nil {
return nil, err
}
if config.Timeout > 0 {
conn.SetReadDeadline(time.Time{})
}
return ssh.NewClient(c, chans, reqs), nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/proxy/proxy.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/proxy/proxy.go#L58-L64 | go | train | // DialWithDeadline works around the case when net.DialWithTimeout
// succeeds, but key exchange hangs. Setting deadline on connection
// prevents this case from happening | func DialWithDeadline(network string, addr string, config *ssh.ClientConfig) (*ssh.Client, error) | // DialWithDeadline works around the case when net.DialWithTimeout
// succeeds, but key exchange hangs. Setting deadline on connection
// prevents this case from happening
func DialWithDeadline(network string, addr string, config *ssh.ClientConfig) (*ssh.Client, error) | {
conn, err := net.DialTimeout(network, addr, config.Timeout)
if err != nil {
return nil, err
}
return NewClientConnWithDeadline(conn, addr, config)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/proxy/proxy.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/proxy/proxy.go#L78-L80 | go | train | // Dial calls ssh.Dial directly. | func (d directDial) Dial(network string, addr string, config *ssh.ClientConfig) (*ssh.Client, error) | // Dial calls ssh.Dial directly.
func (d directDial) Dial(network string, addr string, config *ssh.ClientConfig) (*ssh.Client, error) | {
return DialWithDeadline(network, addr, config)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/proxy/proxy.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/proxy/proxy.go#L83-L85 | go | train | // DialTimeout acts like Dial but takes a timeout. | func (d directDial) DialTimeout(network, address string, timeout time.Duration) (net.Conn, error) | // DialTimeout acts like Dial but takes a timeout.
func (d directDial) DialTimeout(network, address string, timeout time.Duration) (net.Conn, error) | {
return net.DialTimeout(network, address, timeout)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/proxy/proxy.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/proxy/proxy.go#L92-L101 | go | train | // DialTimeout acts like Dial but takes a timeout. | func (d proxyDial) DialTimeout(network, address string, timeout time.Duration) (net.Conn, error) | // DialTimeout acts like Dial but takes a timeout.
func (d proxyDial) DialTimeout(network, address string, timeout time.Duration) (net.Conn, error) | {
// Build a proxy connection first.
ctx := context.Background()
if timeout > 0 {
timeoutCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
ctx = timeoutCtx
}
return dialProxy(ctx, d.proxyHost, address)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/proxy/proxy.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/proxy/proxy.go#L105-L123 | go | train | // Dial first connects to a proxy, then uses the connection to establish a new
// SSH connection. | func (d proxyDial) Dial(network string, addr string, config *ssh.ClientConfig) (*ssh.Client, error) | // Dial first connects to a proxy, then uses the connection to establish a new
// SSH connection.
func (d proxyDial) Dial(network string, addr string, config *ssh.ClientConfig) (*ssh.Client, error) | {
// Build a proxy connection first.
pconn, err := dialProxy(context.Background(), d.proxyHost, addr)
if err != nil {
return nil, trace.Wrap(err)
}
if config.Timeout > 0 {
pconn.SetReadDeadline(time.Now().Add(config.Timeout))
}
// Do the same as ssh.Dial but pass in proxy connection.
c, chans, reqs, err :=... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/proxy/proxy.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/proxy/proxy.go#L129-L141 | go | train | // DialerFromEnvironment returns a Dial function. If the https_proxy or http_proxy
// environment variable are set, it returns a function that will dial through
// said proxy server. If neither variable is set, it will connect to the SSH
// server directly. | func DialerFromEnvironment(addr string) Dialer | // DialerFromEnvironment returns a Dial function. If the https_proxy or http_proxy
// environment variable are set, it returns a function that will dial through
// said proxy server. If neither variable is set, it will connect to the SSH
// server directly.
func DialerFromEnvironment(addr string) Dialer | {
// Try and get proxy addr from the environment.
proxyAddr := getProxyAddress(addr)
// If no proxy settings are in environment return regular ssh dialer,
// otherwise return a proxy dialer.
if proxyAddr == "" {
log.Debugf("No proxy set in environment, returning direct dialer.")
return directDial{}
}
log.D... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/proxy/proxy.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/proxy/proxy.go#L222-L232 | go | train | // parse will extract the host:port of the proxy to dial to. If the
// value is not prefixed by "http", then it will prepend "http" and try. | func parse(addr string) (string, error) | // parse will extract the host:port of the proxy to dial to. If the
// value is not prefixed by "http", then it will prepend "http" and try.
func parse(addr string) (string, error) | {
proxyurl, err := url.Parse(addr)
if err != nil || !strings.HasPrefix(proxyurl.Scheme, "http") {
proxyurl, err = url.Parse("http://" + addr)
if err != nil {
return "", trace.Wrap(err)
}
}
return proxyurl.Host, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/proxy/proxy.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/proxy/proxy.go#L245-L250 | go | train | // Read first reads from the *bufio.Reader any data that has already been
// buffered. Once all buffered data has been read, reads go to the net.Conn. | func (bc *bufferedConn) Read(b []byte) (n int, err error) | // Read first reads from the *bufio.Reader any data that has already been
// buffered. Once all buffered data has been read, reads go to the net.Conn.
func (bc *bufferedConn) Read(b []byte) (n int, err error) | {
if bc.reader.Buffered() > 0 {
return bc.reader.Read(b)
}
return bc.Conn.Read(b)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/etcdbk/etcd.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/etcdbk/etcd.go#L168-L207 | go | train | // New returns new instance of Etcd-powered backend | func New(ctx context.Context, params backend.Params) (*EtcdBackend, error) | // New returns new instance of Etcd-powered backend
func New(ctx context.Context, params backend.Params) (*EtcdBackend, error) | {
var err error
if params == nil {
return nil, trace.BadParameter("missing etcd configuration")
}
// convert generic backend parameters structure to etcd config:
var cfg *Config
if err = utils.ObjectToStruct(params, &cfg); err != nil {
return nil, trace.BadParameter("invalid etcd configuration: %v", err)
}... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/etcdbk/etcd.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/etcdbk/etcd.go#L210-L235 | go | train | // Validate checks if all the parameters are present/valid | func (cfg *Config) Validate() error | // Validate checks if all the parameters are present/valid
func (cfg *Config) Validate() error | {
if len(cfg.Key) == 0 {
return trace.BadParameter(`etcd: missing "prefix" setting`)
}
if len(cfg.Nodes) == 0 {
return trace.BadParameter(`etcd: missing "peers" setting`)
}
if cfg.Insecure == false {
if cfg.TLSKeyFile == "" {
return trace.BadParameter(`etcd: missing "tls_key_file" setting`)
}
if cfg.... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/etcdbk/etcd.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/etcdbk/etcd.go#L328-L335 | go | train | // NewWatcher returns a new event watcher | func (b *EtcdBackend) NewWatcher(ctx context.Context, watch backend.Watch) (backend.Watcher, error) | // NewWatcher returns a new event watcher
func (b *EtcdBackend) NewWatcher(ctx context.Context, watch backend.Watch) (backend.Watcher, error) | {
select {
case <-b.watchStarted.Done():
case <-ctx.Done():
return nil, trace.ConnectionProblem(ctx.Err(), "context is closing")
}
return b.buf.NewWatcher(ctx, watch)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/etcdbk/etcd.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/etcdbk/etcd.go#L338-L371 | go | train | // GetRange returns query range | func (b *EtcdBackend) GetRange(ctx context.Context, startKey, endKey []byte, limit int) (*backend.GetResult, error) | // GetRange returns query range
func (b *EtcdBackend) GetRange(ctx context.Context, startKey, 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")
}
opts := []clientv3.OpOption{clientv3.WithSerializable(), clientv3.WithRange(prependPrefix(endKey))}
if limit > 0 {
opts = append(opts, ... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/etcdbk/etcd.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/etcdbk/etcd.go#L374-L396 | go | train | // Create creates item if it does not exist | func (b *EtcdBackend) Create(ctx context.Context, item backend.Item) (*backend.Lease, error) | // Create creates item if it does not exist
func (b *EtcdBackend) Create(ctx context.Context, item backend.Item) (*backend.Lease, error) | {
var opts []clientv3.OpOption
var lease backend.Lease
if !item.Expires.IsZero() {
if err := b.setupLease(ctx, item, &lease, &opts); err != nil {
return nil, trace.Wrap(err)
}
}
start := b.clock.Now()
re, err := b.client.Txn(ctx).
If(clientv3.Compare(clientv3.CreateRevision(prependPrefix(item.Key)), "="... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/etcdbk/etcd.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/etcdbk/etcd.go#L425-L460 | go | train | // CompareAndSwap compares item with existing item
// and replaces is with replaceWith item | func (b *EtcdBackend) 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 (b *EtcdBackend) 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/etcdbk/etcd.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/etcdbk/etcd.go#L464-L484 | go | train | // Put puts value into backend (creates if it does not
// exists, updates it otherwise) | func (b *EtcdBackend) Put(ctx context.Context, item backend.Item) (*backend.Lease, error) | // Put puts value into backend (creates if it does not
// exists, updates it otherwise)
func (b *EtcdBackend) Put(ctx context.Context, item backend.Item) (*backend.Lease, error) | {
var opts []clientv3.OpOption
var lease backend.Lease
if !item.Expires.IsZero() {
if err := b.setupLease(ctx, item, &lease, &opts); err != nil {
return nil, trace.Wrap(err)
}
}
start := b.clock.Now()
_, err := b.client.Put(
ctx,
prependPrefix(item.Key),
base64.StdEncoding.EncodeToString(item.Value)... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/etcdbk/etcd.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/etcdbk/etcd.go#L487-L510 | go | train | // KeepAlive updates TTL on the lease ID | func (b *EtcdBackend) KeepAlive(ctx context.Context, lease backend.Lease, expires time.Time) error | // KeepAlive updates TTL on the lease ID
func (b *EtcdBackend) KeepAlive(ctx context.Context, lease backend.Lease, expires time.Time) error | {
if lease.ID == 0 {
return trace.BadParameter("lease is not specified")
}
re, err := b.client.Get(ctx, prependPrefix(lease.Key), clientv3.WithSerializable(), clientv3.WithKeysOnly())
if err != nil {
return convertErr(err)
}
if len(re.Kvs) == 0 {
return trace.NotFound("item %q is not found", string(lease.K... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/etcdbk/etcd.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/etcdbk/etcd.go#L513-L527 | go | train | // Get returns a single item or not found error | func (b *EtcdBackend) Get(ctx context.Context, key []byte) (*backend.Item, error) | // Get returns a single item or not found error
func (b *EtcdBackend) Get(ctx context.Context, key []byte) (*backend.Item, error) | {
re, err := b.client.Get(ctx, prependPrefix(key), clientv3.WithSerializable())
if err != nil {
return nil, convertErr(err)
}
if len(re.Kvs) == 0 {
return nil, trace.NotFound("item %q is not found", string(key))
}
kv := re.Kvs[0]
bytes, err := unmarshal(kv.Value)
if err != nil {
return nil, trace.Wrap(er... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/etcdbk/etcd.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/etcdbk/etcd.go#L530-L542 | go | train | // Delete deletes item by key | func (b *EtcdBackend) Delete(ctx context.Context, key []byte) error | // Delete deletes item by key
func (b *EtcdBackend) Delete(ctx context.Context, key []byte) error | {
start := b.clock.Now()
re, err := b.client.Delete(ctx, prependPrefix(key))
writeLatencies.Observe(time.Since(start).Seconds())
writeRequests.Inc()
if err != nil {
return trace.Wrap(convertErr(err))
}
if re.Deleted == 0 {
return trace.NotFound("%q is not found", key)
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/etcdbk/etcd.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/etcdbk/etcd.go#L545-L560 | go | train | // DeleteRange deletes range of items with keys between startKey and endKey | func (b *EtcdBackend) DeleteRange(ctx context.Context, startKey, endKey []byte) error | // DeleteRange deletes range of items with keys between startKey and endKey
func (b *EtcdBackend) 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")
}
start := b.clock.Now()
_, err := b.client.Delete(ctx, prependPrefix(startKey), clientv3.WithRange(prependPrefix(endKey)))
writeLatencies.Observe(t... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/etcdbk/etcd.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/etcdbk/etcd.go#L606-L612 | go | train | // seconds converts duration to seconds, rounds up to 1 second | func seconds(ttl time.Duration) int64 | // seconds converts duration to seconds, rounds up to 1 second
func seconds(ttl time.Duration) int64 | {
i := int64(ttl / time.Second)
if i <= 0 {
i = 1
}
return i
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | tool/tctl/common/auth_command.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/auth_command.go#L53-L81 | go | train | // Initialize allows TokenCommand to plug itself into the CLI parser | func (a *AuthCommand) Initialize(app *kingpin.Application, config *service.Config) | // Initialize allows TokenCommand to plug itself into the CLI parser
func (a *AuthCommand) Initialize(app *kingpin.Application, config *service.Config) | {
a.config = config
// operations with authorities
auth := app.Command("auth", "Operations with user and host certificate authorities (CAs)").Hidden()
a.authExport = auth.Command("export", "Export public cluster (CA) keys to stdout")
a.authExport.Flag("keys", "if set, will print private keys").BoolVar(&a.exportP... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | tool/tctl/common/auth_command.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/auth_command.go#L85-L99 | go | train | // TryRun takes the CLI command as an argument (like "auth gen") and executes it
// or returns match=false if 'cmd' does not belong to it | func (a *AuthCommand) TryRun(cmd string, client auth.ClientI) (match bool, err error) | // TryRun takes the CLI command as an argument (like "auth gen") and executes it
// or returns match=false if 'cmd' does not belong to it
func (a *AuthCommand) TryRun(cmd string, client auth.ClientI) (match bool, err error) | {
switch cmd {
case a.authGenerate.FullCommand():
err = a.GenerateKeys()
case a.authExport.FullCommand():
err = a.ExportAuthorities(client)
case a.authSign.FullCommand():
err = a.GenerateAndSignKeys(client)
case a.authRotate.FullCommand():
err = a.RotateCertAuthority(client)
default:
return false, nil
... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | tool/tctl/common/auth_command.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/auth_command.go#L104-L216 | go | train | // ExportAuthorities outputs the list of authorities in OpenSSH compatible formats
// If --type flag is given, only prints keys for CAs of this type, otherwise
// prints all keys | func (a *AuthCommand) ExportAuthorities(client auth.ClientI) error | // ExportAuthorities outputs the list of authorities in OpenSSH compatible formats
// If --type flag is given, only prints keys for CAs of this type, otherwise
// prints all keys
func (a *AuthCommand) ExportAuthorities(client auth.ClientI) error | {
var typesToExport []services.CertAuthType
// this means to export TLS authority
if a.authType == "tls" {
clusterName, err := client.GetDomainName()
if err != nil {
return trace.Wrap(err)
}
certAuthority, err := client.GetCertAuthority(
services.CertAuthID{Type: services.HostCA, DomainName: clusterN... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | tool/tctl/common/auth_command.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/auth_command.go#L219-L241 | go | train | // GenerateKeys generates a new keypair | func (a *AuthCommand) GenerateKeys() error | // GenerateKeys generates a new keypair
func (a *AuthCommand) GenerateKeys() error | {
keygen, err := native.New(context.TODO(), native.PrecomputeKeys(0))
if err != nil {
return trace.Wrap(err)
}
defer keygen.Close()
privBytes, pubBytes, err := keygen.GenerateKeyPair("")
if err != nil {
return trace.Wrap(err)
}
err = ioutil.WriteFile(a.genPubPath, pubBytes, 0600)
if err != nil {
return ... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | tool/tctl/common/auth_command.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/auth_command.go#L244-L253 | go | train | // GenerateAndSignKeys generates a new keypair and signs it for role | func (a *AuthCommand) GenerateAndSignKeys(clusterApi auth.ClientI) error | // GenerateAndSignKeys generates a new keypair and signs it for role
func (a *AuthCommand) GenerateAndSignKeys(clusterApi auth.ClientI) error | {
switch {
case a.genUser != "" && a.genHost == "":
return a.generateUserKeys(clusterApi)
case a.genUser == "" && a.genHost != "":
return a.generateHostKeys(clusterApi)
default:
return trace.BadParameter("--user or --host must be specified")
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | tool/tctl/common/auth_command.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/auth_command.go#L256-L277 | go | train | // RotateCertAuthority starts or restarts certificate authority rotation process | func (a *AuthCommand) RotateCertAuthority(client auth.ClientI) error | // RotateCertAuthority starts or restarts certificate authority rotation process
func (a *AuthCommand) RotateCertAuthority(client auth.ClientI) error | {
req := auth.RotateRequest{
Type: services.CertAuthType(a.rotateType),
GracePeriod: &a.rotateGracePeriod,
TargetPhase: a.rotateTargetPhase,
}
if a.rotateManualMode {
req.Mode = services.RotationModeManual
} else {
req.Mode = services.RotationModeAuto
}
if err := client.RotateCertAuthority(req);... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | tool/tctl/common/auth_command.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/auth_command.go#L370-L372 | go | train | // userCAFormat returns the certificate authority public key exported as a single
// line that can be placed in ~/.ssh/authorized_keys file. The format adheres to the
// man sshd (8) authorized_keys format, a space-separated list of: options, keytype,
// base64-encoded key, comment.
// For example:
//
// cert-author... | func userCAFormat(ca services.CertAuthority, keyBytes []byte) (string, error) | // userCAFormat returns the certificate authority public key exported as a single
// line that can be placed in ~/.ssh/authorized_keys file. The format adheres to the
// man sshd (8) authorized_keys format, a space-separated list of: options, keytype,
// base64-encoded key, comment.
// For example:
//
// cert-author... | {
return sshutils.MarshalAuthorizedKeysFormat(ca.GetClusterName(), keyBytes)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | tool/tctl/common/auth_command.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/auth_command.go#L382-L389 | go | train | // hostCAFormat returns the certificate authority public key exported as a single line
// that can be placed in ~/.ssh/authorized_hosts. The format adheres to the man sshd (8)
// authorized_hosts format, a space-separated list of: marker, hosts, key, and comment.
// For example:
//
// @cert-authority *.cluster-a ssh... | func hostCAFormat(ca services.CertAuthority, keyBytes []byte, client auth.ClientI) (string, error) | // hostCAFormat returns the certificate authority public key exported as a single line
// that can be placed in ~/.ssh/authorized_hosts. The format adheres to the man sshd (8)
// authorized_hosts format, a space-separated list of: marker, hosts, key, and comment.
// For example:
//
// @cert-authority *.cluster-a ssh... | {
roles, err := services.FetchRoles(ca.GetRoles(), client, nil)
if err != nil {
return "", trace.Wrap(err)
}
allowedLogins, _ := roles.CheckLoginDuration(defaults.MinCertDuration + time.Second)
return sshutils.MarshalAuthorizedHostsFormat(ca.GetClusterName(), keyBytes, allowedLogins)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/legacy/legacy.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/legacy.go#L96-L104 | go | train | // CollectOptions collects all options from functional
// arg and returns config | func CollectOptions(opts []OpOption) (*OpConfig, error) | // CollectOptions collects all options from functional
// arg and returns config
func CollectOptions(opts []OpOption) (*OpConfig, error) | {
cfg := OpConfig{}
for _, o := range opts {
if err := o(&cfg); err != nil {
return nil, trace.Wrap(err)
}
}
return &cfg, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/legacy/legacy.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/legacy.go#L131-L133 | go | train | // Less is part of sort.Interface. | func (it Items) Less(i, j int) bool | // Less is part of sort.Interface.
func (it Items) Less(i, j int) bool | {
return it[i].Key < it[j].Key
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/legacy/legacy.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/legacy.go#L160-L165 | go | train | // ValidateLockTTL helper allows all backends to validate lock TTL parameter | func ValidateLockTTL(ttl time.Duration) error | // ValidateLockTTL helper allows all backends to validate lock TTL parameter
func ValidateLockTTL(ttl time.Duration) error | {
if ttl == Forever || ttl > MaxLockDuration {
return trace.BadParameter("locks cannot exceed %v", MaxLockDuration)
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/legacy/legacy.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/legacy.go#L180-L189 | go | train | // TTL converts time to TTL from current time supplied
// by provider, if t is zero, returns forever | func TTL(clock clockwork.Clock, t time.Time) time.Duration | // TTL converts time to TTL from current time supplied
// by provider, if t is zero, returns forever
func TTL(clock clockwork.Clock, t time.Time) time.Duration | {
if t.IsZero() {
return Forever
}
diff := t.UTC().Sub(clock.Now().UTC())
if diff < 0 {
return Forever
}
return diff
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/legacy/legacy.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/legacy.go#L193-L200 | go | train | // AnyTTL returns TTL if any of the suplied times pass expiry time
// otherwise returns forever | func AnyTTL(clock clockwork.Clock, times ...time.Time) time.Duration | // AnyTTL returns TTL if any of the suplied times pass expiry time
// otherwise returns forever
func AnyTTL(clock clockwork.Clock, times ...time.Time) time.Duration | {
for _, t := range times {
if !t.IsZero() {
return TTL(clock, t)
}
}
return Forever
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/limiter/connlimiter.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/limiter/connlimiter.go#L39-L58 | go | train | // NewConnectionsLimiter returns new connection limiter, in case if connection
// limits are not set, they won't be tracked | func NewConnectionsLimiter(config LimiterConfig) (*ConnectionsLimiter, error) | // NewConnectionsLimiter returns new connection limiter, in case if connection
// limits are not set, they won't be tracked
func NewConnectionsLimiter(config LimiterConfig) (*ConnectionsLimiter, error) | {
limiter := ConnectionsLimiter{
Mutex: &sync.Mutex{},
maxConnections: config.MaxConnections,
connections: make(map[string]int64),
}
ipExtractor, err := utils.NewExtractor("client.ip")
if err != nil {
return nil, trace.Wrap(err)
}
limiter.ConnLimiter, err = connlimit.New(
nil, ipExtractor... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/limiter/connlimiter.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/limiter/connlimiter.go#L61-L63 | go | train | // WrapHandle adds connection limiter to the handle | func (l *ConnectionsLimiter) WrapHandle(h http.Handler) | // WrapHandle adds connection limiter to the handle
func (l *ConnectionsLimiter) WrapHandle(h http.Handler) | {
l.ConnLimiter.Wrap(h)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/limiter/connlimiter.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/limiter/connlimiter.go#L66-L86 | go | train | // AcquireConnection acquires connection and bumps counter | func (l *ConnectionsLimiter) AcquireConnection(token string) error | // AcquireConnection acquires connection and bumps counter
func (l *ConnectionsLimiter) AcquireConnection(token string) error | {
l.Lock()
defer l.Unlock()
if l.maxConnections == 0 {
return nil
}
numberOfConnections, exists := l.connections[token]
if !exists {
l.connections[token] = 1
return nil
}
if numberOfConnections >= l.maxConnections {
return trace.LimitExceeded(
"too many connections from %v: %v, max is %v",
toke... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/limiter/connlimiter.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/limiter/connlimiter.go#L89-L108 | go | train | // ReleaseConnection decrements the counter | func (l *ConnectionsLimiter) ReleaseConnection(token string) | // ReleaseConnection decrements the counter
func (l *ConnectionsLimiter) ReleaseConnection(token string) | {
l.Lock()
defer l.Unlock()
if l.maxConnections == 0 {
return
}
numberOfConnections, exists := l.connections[token]
if !exists {
log.Errorf("Trying to set negative number of connections")
} else {
if numberOfConnections <= 1 {
delete(l.connections, token)
} else {
l.connections[token] = numberO... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/kube/authority/authority.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/authority/authority.go#L22-L101 | go | train | // ProcessCSR processes CSR request with local k8s certificate authority
// and returns certificate PEM signed by CA | func ProcessCSR(clt *kubernetes.Clientset, csrPEM []byte) ([]byte, error) | // ProcessCSR processes CSR request with local k8s certificate authority
// and returns certificate PEM signed by CA
func ProcessCSR(clt *kubernetes.Clientset, csrPEM []byte) ([]byte, error) | {
id := "teleport-" + uuid.New()
requests := clt.CertificatesV1beta1().CertificateSigningRequests()
csr, err := requests.Create(&certificates.CertificateSigningRequest{
ObjectMeta: metav1.ObjectMeta{
Name: id,
},
Spec: certificates.CertificateSigningRequestSpec{
Request: csrPEM,
Usages: []certificate... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/time.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/time.go#L11-L22 | go | train | // MinTTL finds min non 0 TTL duration,
// if both durations are 0, fails | func MinTTL(a, b time.Duration) time.Duration | // MinTTL finds min non 0 TTL duration,
// if both durations are 0, fails
func MinTTL(a, b time.Duration) time.Duration | {
if a == 0 {
return b
}
if b == 0 {
return a
}
if a < b {
return a
}
return b
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/time.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/time.go#L26-L32 | go | train | // ToTTL converts expiration time to TTL duration
// relative to current time as provided by clock | func ToTTL(c clockwork.Clock, tm time.Time) time.Duration | // ToTTL converts expiration time to TTL duration
// relative to current time as provided by clock
func ToTTL(c clockwork.Clock, tm time.Time) time.Duration | {
now := c.Now().UTC()
if tm.IsZero() || tm.Before(now) {
return 0
}
return tm.Sub(now)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/time.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/time.go#L35-L46 | go | train | // UTC converts time to UTC timezone | func UTC(t *time.Time) | // UTC converts time to UTC timezone
func UTC(t *time.Time) | {
if t == nil {
return
}
if t.IsZero() {
// to fix issue with timezones for tests
*t = time.Time{}
return
}
*t = t.UTC()
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/password.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/password.go#L21-L58 | go | train | // ChangePassword changes user passsword | func (s *AuthServer) ChangePassword(req services.ChangePasswordReq) error | // ChangePassword changes user passsword
func (s *AuthServer) ChangePassword(req services.ChangePasswordReq) error | {
// validate new password
err := services.VerifyPassword(req.NewPassword)
if err != nil {
return trace.Wrap(err)
}
authPreference, err := s.GetAuthPreference()
if err != nil {
return trace.Wrap(err)
}
userID := req.User
fn := func() error {
secondFactor := authPreference.GetSecondFactor()
switch se... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/password.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/password.go#L62-L85 | go | train | // CheckPasswordWOToken checks just password without checking OTP tokens
// used in case of SSH authentication, when token has been validated. | func (s *AuthServer) CheckPasswordWOToken(user string, password []byte) error | // CheckPasswordWOToken checks just password without checking OTP tokens
// used in case of SSH authentication, when token has been validated.
func (s *AuthServer) CheckPasswordWOToken(user string, password []byte) error | {
const errMsg = "invalid username or password"
err := services.VerifyPassword(password)
if err != nil {
return trace.BadParameter(errMsg)
}
hash, err := s.GetPasswordHash(user)
if err != nil && !trace.IsNotFound(err) {
return trace.Wrap(err)
}
if trace.IsNotFound(err) {
log.Debugf("Username %q not fou... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/password.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/password.go#L88-L96 | go | train | // CheckPassword checks the password and OTP token. Called by tsh or lib/web/*. | func (s *AuthServer) CheckPassword(user string, password []byte, otpToken string) error | // CheckPassword checks the password and OTP token. Called by tsh or lib/web/*.
func (s *AuthServer) CheckPassword(user string, password []byte, otpToken string) error | {
err := s.CheckPasswordWOToken(user, password)
if err != nil {
return trace.Wrap(err)
}
err = s.CheckOTP(user, otpToken)
return trace.Wrap(err)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/password.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/password.go#L100-L166 | go | train | // CheckOTP determines the type of OTP token used (for legacy HOTP support), fetches the
// appropriate type from the backend, and checks if the token is valid. | func (s *AuthServer) CheckOTP(user string, otpToken string) error | // CheckOTP determines the type of OTP token used (for legacy HOTP support), fetches the
// appropriate type from the backend, and checks if the token is valid.
func (s *AuthServer) CheckOTP(user string, otpToken string) error | {
var err error
otpType, err := s.getOTPType(user)
if err != nil {
return trace.Wrap(err)
}
switch otpType {
case teleport.HOTP:
otp, err := s.GetHOTP(user)
if err != nil {
return trace.Wrap(err)
}
// look ahead n tokens to see if we can find a matching token
if !otp.Scan(otpToken, defaults.HOT... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/password.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/password.go#L170-L179 | go | train | // getOTPType returns the type of OTP token used, HOTP or TOTP.
// Deprecated: Remove this method once HOTP support has been removed. | func (s *AuthServer) getOTPType(user string) (string, error) | // getOTPType returns the type of OTP token used, HOTP or TOTP.
// Deprecated: Remove this method once HOTP support has been removed.
func (s *AuthServer) getOTPType(user string) (string, error) | {
_, err := s.GetHOTP(user)
if err != nil {
if trace.IsNotFound(err) {
return teleport.TOTP, nil
}
return "", trace.Wrap(err)
}
return teleport.HOTP, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/password.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/password.go#L182-L200 | go | train | // GetOTPData returns the OTP Key, Key URL, and the QR code. | func (s *AuthServer) GetOTPData(user string) (string, []byte, error) | // GetOTPData returns the OTP Key, Key URL, and the QR code.
func (s *AuthServer) GetOTPData(user string) (string, []byte, error) | {
// get otp key from backend
otpSecret, err := s.GetTOTP(user)
if err != nil {
return "", nil, trace.Wrap(err)
}
// create otp url
params := map[string][]byte{"secret": []byte(otpSecret)}
otpURL := utils.GenerateOTPURL("totp", user, params)
// create the qr code
otpQR, err := utils.GenerateQRCode(otpURL)... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/parser.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/parser.go#L56-L87 | go | train | // NewWhereParser returns standard parser for `where` section in access rules. | func NewWhereParser(ctx RuleContext) (predicate.Parser, error) | // NewWhereParser returns standard parser for `where` section in access rules.
func NewWhereParser(ctx RuleContext) (predicate.Parser, error) | {
return predicate.NewParser(predicate.Def{
Operators: predicate.Operators{
AND: predicate.And,
OR: predicate.Or,
NOT: predicate.Not,
},
Functions: map[string]interface{}{
"equals": predicate.Equals,
"contains": predicate.Contains,
// system.catype is a function that returns cert authority ... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/parser.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/parser.go#L93-L122 | go | train | // GetStringMapValue is a helper function that returns property
// from map[string]string or map[string][]string
// the function returns empty value in case if key not found
// In case if map is nil, returns empty value as well | func GetStringMapValue(mapVal, keyVal interface{}) (interface{}, error) | // GetStringMapValue is a helper function that returns property
// from map[string]string or map[string][]string
// the function returns empty value in case if key not found
// In case if map is nil, returns empty value as well
func GetStringMapValue(mapVal, keyVal interface{}) (interface{}, error) | {
key, ok := keyVal.(string)
if !ok {
return nil, trace.BadParameter("only string keys are supported")
}
switch m := mapVal.(type) {
case map[string][]string:
if len(m) == 0 {
// to return nil with a proper type
var n []string
return n, nil
}
return m[key], nil
case Traits:
if len(m) == 0 {
... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/parser.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/parser.go#L125-L134 | go | train | // NewActionsParser returns standard parser for 'actions' section in access rules | func NewActionsParser(ctx RuleContext) (predicate.Parser, error) | // NewActionsParser returns standard parser for 'actions' section in access rules
func NewActionsParser(ctx RuleContext) (predicate.Parser, error) | {
return predicate.NewParser(predicate.Def{
Operators: predicate.Operators{},
Functions: map[string]interface{}{
"log": NewLogActionFn(ctx),
},
GetIdentifier: ctx.GetIdentifier,
GetProperty: predicate.GetStringMapValue,
})
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/parser.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/parser.go#L137-L144 | go | train | // NewLogActionFn creates logger functions | func NewLogActionFn(ctx RuleContext) interface{} | // NewLogActionFn creates logger functions
func NewLogActionFn(ctx RuleContext) interface{} | {
l := &LogAction{ctx: ctx}
writer, ok := ctx.(io.Writer)
if ok && writer != nil {
l.writer = writer
}
return l.Log
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/parser.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/parser.go#L154-L169 | go | train | // Log logs with specified level and formatting string with arguments | func (l *LogAction) Log(level, format string, args ...interface{}) predicate.BoolPredicate | // Log logs with specified level and formatting string with arguments
func (l *LogAction) Log(level, format string, args ...interface{}) predicate.BoolPredicate | {
return func() bool {
ilevel, err := log.ParseLevel(level)
if err != nil {
ilevel = log.DebugLevel
}
var writer io.Writer
if l.writer != nil {
writer = l.writer
} else {
writer = log.StandardLogger().WriterLevel(ilevel)
}
writer.Write([]byte(fmt.Sprintf(format, args...)))
return true
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/parser.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/parser.go#L181-L183 | go | train | // String returns user friendly representation of this context | func (ctx *Context) String() string | // String returns user friendly representation of this context
func (ctx *Context) String() string | {
return fmt.Sprintf("user %v, resource: %v", ctx.User, ctx.Resource)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/parser.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/parser.go#L194-L199 | go | train | // GetResource returns resource specified in the context,
// returns error if not specified. | func (ctx *Context) GetResource() (Resource, error) | // GetResource returns resource specified in the context,
// returns error if not specified.
func (ctx *Context) GetResource() (Resource, error) | {
if ctx.Resource == nil {
return nil, trace.NotFound("resource is not set in the context")
}
return ctx.Resource, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/parser.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/parser.go#L202-L223 | go | train | // GetIdentifier returns identifier defined in a context | func (ctx *Context) GetIdentifier(fields []string) (interface{}, error) | // GetIdentifier returns identifier defined in a context
func (ctx *Context) GetIdentifier(fields []string) (interface{}, error) | {
switch fields[0] {
case UserIdentifier:
var user User
if ctx.User == nil {
user = emptyUser
} else {
user = ctx.User
}
return predicate.GetFieldByTag(user, teleport.JSON, fields[1:])
case ResourceIdentifier:
var resource Resource
if ctx.Resource == nil {
resource = emptyResource
} else {
... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/parser.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/parser.go#L314-L316 | go | train | // SetExpiry sets expiry time for the object. | func (r *EmptyResource) SetExpiry(expires time.Time) | // SetExpiry sets expiry time for the object.
func (r *EmptyResource) SetExpiry(expires time.Time) | {
r.Metadata.SetExpiry(expires)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/secret/secret.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/secret/secret.go#L43-L51 | go | train | // NewKey generates a new key from a cryptographically secure pseudo-random
// number generator (CSPRNG). | func NewKey() (Key, error) | // NewKey generates a new key from a cryptographically secure pseudo-random
// number generator (CSPRNG).
func NewKey() (Key, error) | {
k := make([]byte, 32)
_, err := io.ReadFull(rand.Reader, k)
if err != nil {
return nil, trace.Wrap(err)
}
return Key(k), nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/secret/secret.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/secret/secret.go#L54-L61 | go | train | // ParseKey reads in an existing hex encoded key. | func ParseKey(k []byte) (Key, error) | // ParseKey reads in an existing hex encoded key.
func ParseKey(k []byte) (Key, error) | {
key, err := hex.DecodeString(string(k))
if err != nil {
return nil, trace.Wrap(err)
}
return Key(key), nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/secret/secret.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/secret/secret.go#L64-L90 | go | train | // Seal will encrypt then authenticate the ciphertext. | func (k Key) Seal(plaintext []byte) ([]byte, error) | // Seal will encrypt then authenticate the ciphertext.
func (k Key) Seal(plaintext []byte) ([]byte, error) | {
block, err := aes.NewCipher([]byte(k))
if err != nil {
return nil, trace.Wrap(err)
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
return nil, trace.Wrap(err)
}
nonce := make([]byte, aesgcm.NonceSize())
_, err = io.ReadFull(rand.Reader, nonce)
if err != nil {
return nil, trace.Wrap(err)
}
c... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/secret/secret.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/secret/secret.go#L93-L117 | go | train | // Open will authenticate then decrypt the ciphertext. | func (k Key) Open(ciphertext []byte) ([]byte, error) | // Open will authenticate then decrypt the ciphertext.
func (k Key) Open(ciphertext []byte) ([]byte, error) | {
var data sealedData
err := json.Unmarshal(ciphertext, &data)
if err != nil {
return nil, trace.Wrap(err)
}
block, err := aes.NewCipher(k)
if err != nil {
return nil, trace.Wrap(err)
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
return nil, trace.Wrap(err)
}
plaintext, err := aesgcm.Open(... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/events/forward.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/forward.go#L54-L68 | go | train | // CheckAndSetDefaults checks and sets default values | func (s *ForwarderConfig) CheckAndSetDefaults() error | // CheckAndSetDefaults checks and sets default values
func (s *ForwarderConfig) CheckAndSetDefaults() error | {
if s.ForwardTo == nil {
return trace.BadParameter("missing parameter bucket")
}
if s.DataDir == "" {
return trace.BadParameter("missing data dir")
}
if s.Clock == nil {
s.Clock = clockwork.NewRealClock()
}
if s.UID == nil {
s.UID = utils.NewRealUID()
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/events/forward.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/forward.go#L71-L90 | go | train | // NewForwarder returns a new instance of session forwarder | func NewForwarder(cfg ForwarderConfig) (*Forwarder, error) | // NewForwarder returns a new instance of session forwarder
func NewForwarder(cfg ForwarderConfig) (*Forwarder, error) | {
if err := cfg.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
diskLogger, err := NewDiskSessionLogger(DiskSessionLoggerConfig{
SessionID: cfg.SessionID,
DataDir: cfg.DataDir,
RecordSessions: cfg.RecordSessions,
Namespace: cfg.Namespace,
ServerID: cfg.ServerID,
... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/events/forward.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/forward.go#L104-L112 | go | train | // Closer releases connection and resources associated with log if any | func (l *Forwarder) Close() error | // Closer releases connection and resources associated with log if any
func (l *Forwarder) Close() error | {
l.Lock()
defer l.Unlock()
if l.isClosed {
return nil
}
l.isClosed = true
return l.sessionLogger.Finalize()
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/events/forward.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/forward.go#L115-L137 | go | train | // EmitAuditEvent emits audit event | func (l *Forwarder) EmitAuditEvent(event Event, fields EventFields) error | // EmitAuditEvent emits audit event
func (l *Forwarder) EmitAuditEvent(event Event, fields EventFields) error | {
err := UpdateEventFields(event, fields, l.Clock, l.UID)
if err != nil {
return trace.Wrap(err)
}
data, err := json.Marshal(fields)
if err != nil {
return trace.Wrap(err)
}
chunks := []*SessionChunk{
{
EventType: event.Name,
Data: data,
Time: time.Now().UTC().UnixNano(),
},
}
retur... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/events/forward.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/forward.go#L140-L161 | go | train | // PostSessionSlice sends chunks of recorded session to the event log | func (l *Forwarder) PostSessionSlice(slice SessionSlice) error | // PostSessionSlice sends chunks of recorded session to the event log
func (l *Forwarder) PostSessionSlice(slice SessionSlice) error | {
// setup slice sets slice version, properly numerates
// all chunks and
chunksWithoutPrintEvents, err := l.setupSlice(&slice)
if err != nil {
return trace.Wrap(err)
}
// log all events and session recording locally
err = l.sessionLogger.PostSessionSlice(slice)
if err != nil {
return trace.Wrap(err)
}
... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/events/forward.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/forward.go#L197-L199 | go | train | // UploadSessionRecording uploads session recording to the audit server | func (l *Forwarder) UploadSessionRecording(r SessionRecording) error | // UploadSessionRecording uploads session recording to the audit server
func (l *Forwarder) UploadSessionRecording(r SessionRecording) error | {
return l.ForwardTo.UploadSessionRecording(r)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/events/forward.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/forward.go#L206-L208 | go | train | // GetSessionChunk returns a reader which can be used to read a byte stream
// of a recorded session starting from 'offsetBytes' (pass 0 to start from the
// beginning) up to maxBytes bytes.
//
// If maxBytes > MaxChunkBytes, it gets rounded down to MaxChunkBytes | func (l *Forwarder) GetSessionChunk(namespace string, sid session.ID, offsetBytes, maxBytes int) ([]byte, error) | // GetSessionChunk returns a reader which can be used to read a byte stream
// of a recorded session starting from 'offsetBytes' (pass 0 to start from the
// beginning) up to maxBytes bytes.
//
// If maxBytes > MaxChunkBytes, it gets rounded down to MaxChunkBytes
func (l *Forwarder) GetSessionChunk(namespace string, si... | {
return l.ForwardTo.GetSessionChunk(namespace, sid, offsetBytes, maxBytes)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/events/forward.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/forward.go#L217-L219 | go | train | // Returns all events that happen during a session sorted by time
// (oldest first).
//
// after tells to use only return events after a specified cursor Id
//
// This function is usually used in conjunction with GetSessionReader to
// replay recorded session streams. | func (l *Forwarder) GetSessionEvents(namespace string, sid session.ID, after int, includePrintEvents bool) ([]EventFields, error) | // Returns all events that happen during a session sorted by time
// (oldest first).
//
// after tells to use only return events after a specified cursor Id
//
// This function is usually used in conjunction with GetSessionReader to
// replay recorded session streams.
func (l *Forwarder) GetSessionEvents(namespace stri... | {
return l.ForwardTo.GetSessionEvents(namespace, sid, after, includePrintEvents)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/events/forward.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/forward.go#L229-L231 | go | train | // SearchEvents is a flexible way to find The format of a query string
// depends on the implementing backend. A recommended format is urlencoded
// (good enough for Lucene/Solr)
//
// Pagination is also defined via backend-specific query format.
//
// The only mandatory requirement is a date range (UTC). Results must... | func (l *Forwarder) SearchEvents(fromUTC, toUTC time.Time, query string, limit int) ([]EventFields, error) | // SearchEvents is a flexible way to find The format of a query string
// depends on the implementing backend. A recommended format is urlencoded
// (good enough for Lucene/Solr)
//
// Pagination is also defined via backend-specific query format.
//
// The only mandatory requirement is a date range (UTC). Results must... | {
return l.ForwardTo.SearchEvents(fromUTC, toUTC, query, limit)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/events/forward.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/forward.go#L235-L237 | go | train | // SearchSessionEvents returns session related events only. This is used to
// find completed session. | func (l *Forwarder) SearchSessionEvents(fromUTC time.Time, toUTC time.Time, limit int) ([]EventFields, error) | // SearchSessionEvents returns session related events only. This is used to
// find completed session.
func (l *Forwarder) SearchSessionEvents(fromUTC time.Time, toUTC time.Time, limit int) ([]EventFields, error) | {
return l.ForwardTo.SearchSessionEvents(fromUTC, toUTC, limit)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/events/forward.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/forward.go#L241-L243 | go | train | // WaitForDelivery waits for resources to be released and outstanding requests to
// complete after calling Close method | func (l *Forwarder) WaitForDelivery(ctx context.Context) error | // WaitForDelivery waits for resources to be released and outstanding requests to
// complete after calling Close method
func (l *Forwarder) WaitForDelivery(ctx context.Context) error | {
return l.ForwardTo.WaitForDelivery(ctx)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/legacy/boltbk/boltbk.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/boltbk/boltbk.go#L66-L81 | go | train | // Exists returns true if backend has been used before | func Exists(path string) (bool, error) | // Exists returns true if backend has been used before
func Exists(path string) (bool, error) | {
path, err := filepath.Abs(filepath.Join(path, keysBoltFile))
if err != nil {
return false, trace.Wrap(err)
}
f, err := os.Open(path)
err = trace.ConvertSystemError(err)
if err != nil {
if trace.IsNotFound(err) {
return false, nil
}
return false, trace.Wrap(err)
}
defer f.Close()
return true, nil
... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/legacy/boltbk/boltbk.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/boltbk/boltbk.go#L85-L117 | go | train | // New initializes and returns a fully created BoltDB backend. It's
// a properly implemented Backend.NewFunc, part of a backend API | func New(params legacy.Params) (*BoltBackend, error) | // New initializes and returns a fully created BoltDB backend. It's
// a properly implemented Backend.NewFunc, part of a backend API
func New(params legacy.Params) (*BoltBackend, error) | {
// look at 'path' parameter, if it's missing use 'data_dir' (default):
path := params.GetString("path")
if len(path) == 0 {
path = params.GetString(teleport.DataDirParameterName)
}
// still nothing? return an error:
if path == "" {
return nil, trace.BadParameter("BoltDB backend: 'path' is not set")
}
if ... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/legacy/boltbk/boltbk.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/boltbk/boltbk.go#L214-L247 | go | train | // Export exports all items from the backend in new backend Items | func (b *BoltBackend) Export() ([]backend.Item, error) | // Export exports all items from the backend in new backend Items
func (b *BoltBackend) Export() ([]backend.Item, error) | {
var rootBuckets [][]string
err := b.db.View(func(tx *bolt.Tx) error {
tx.ForEach(func(name []byte, b *bolt.Bucket) error {
rootBuckets = append(rootBuckets, []string{string(name)})
return nil
})
return nil
})
if err != nil {
return nil, trace.Wrap(err)
}
var items []backend.Item
for _, bucket :... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/legacy/boltbk/boltbk.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/boltbk/boltbk.go#L278-L309 | go | train | // GetItems fetches keys and values and returns them to the caller. | func (b *BoltBackend) GetItems(path []string, opts ...legacy.OpOption) ([]legacy.Item, error) | // GetItems fetches keys and values and returns them to the caller.
func (b *BoltBackend) GetItems(path []string, opts ...legacy.OpOption) ([]legacy.Item, error) | {
cfg, err := legacy.CollectOptions(opts)
if err != nil {
return nil, trace.Wrap(err)
}
if cfg.Recursive {
return b.getItemsRecursive(path)
}
keys, err := b.GetKeys(path)
if err != nil {
return nil, trace.Wrap(err)
}
// This is a very inefficient approach. It's here to satisfy the
// backend.Backend ... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/legacy/boltbk/boltbk.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/boltbk/boltbk.go#L357-L396 | go | train | // CompareAndSwapVal compares and swap values in atomic operation,
// succeeds if prevData matches the value stored in the databases,
// requires prevData as a non-empty value. Returns trace.CompareFailed
// in case if value did not match | func (b *BoltBackend) CompareAndSwapVal(bucket []string, key string, newData []byte, prevData []byte, ttl time.Duration) error | // CompareAndSwapVal compares and swap values in atomic operation,
// succeeds if prevData matches the value stored in the databases,
// requires prevData as a non-empty value. Returns trace.CompareFailed
// in case if value did not match
func (b *BoltBackend) CompareAndSwapVal(bucket []string, key string, newData []by... | {
if len(prevData) == 0 {
return trace.BadParameter("missing prevData parameter, to atomically create item, use CreateVal method")
}
v := &kv{
Created: b.clock.Now().UTC(),
Value: newData,
TTL: ttl,
}
newEncodedData, err := json.Marshal(v)
if err != nil {
return trace.Wrap(err)
}
err = b.db.Upd... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/invite.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/invite.go#L48-L63 | go | train | // NewInviteToken returns a new instance of the invite token | func NewInviteToken(token, signupURL string, expires time.Time) *InviteTokenV3 | // NewInviteToken returns a new instance of the invite token
func NewInviteToken(token, signupURL string, expires time.Time) *InviteTokenV3 | {
tok := InviteTokenV3{
Kind: KindInviteToken,
Version: V3,
Metadata: Metadata{
Name: token,
},
Spec: InviteTokenSpecV3{
URL: signupURL,
},
}
if !expires.IsZero() {
tok.Metadata.SetExpiry(expires)
}
return &tok
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/sshutils/scp/http.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/scp/http.go#L69-L114 | go | train | // CreateHTTPUpload creates HTTP download command | func CreateHTTPUpload(req HTTPTransferRequest) (Command, error) | // CreateHTTPUpload creates HTTP download command
func CreateHTTPUpload(req HTTPTransferRequest) (Command, error) | {
if req.HTTPRequest == nil {
return nil, trace.BadParameter("missing parameter HTTPRequest")
}
if req.FileName == "" {
return nil, trace.BadParameter("missing file name")
}
if req.RemoteLocation == "" {
return nil, trace.BadParameter("missing remote location")
}
contentLength := req.HTTPRequest.Header... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/sshutils/scp/http.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/scp/http.go#L117-L143 | go | train | // CreateHTTPDownload creates HTTP upload command | func CreateHTTPDownload(req HTTPTransferRequest) (Command, error) | // CreateHTTPDownload creates HTTP upload command
func CreateHTTPDownload(req HTTPTransferRequest) (Command, error) | {
_, filename, err := req.parseRemoteLocation()
if err != nil {
return nil, trace.Wrap(err)
}
flags := Flags{
Target: []string{filename},
}
cfg := Config{
Flags: flags,
User: req.User,
ProgressWriter: req.Progress,
RemoteLocation: req.RemoteLocation,
FileSystem: &httpFileSystem... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/sshutils/scp/http.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/scp/http.go#L161-L163 | go | train | // MkDir creates a directory. This method is not implemented as creating directories
// is not supported during HTTP downloads. | func (l *httpFileSystem) MkDir(path string, mode int) error | // MkDir creates a directory. This method is not implemented as creating directories
// is not supported during HTTP downloads.
func (l *httpFileSystem) MkDir(path string, mode int) error | {
return trace.BadParameter("directories are not supported in http file transfer")
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/sshutils/scp/http.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/scp/http.go#L172-L178 | go | train | // OpenFile returns file reader | func (l *httpFileSystem) OpenFile(filePath string) (io.ReadCloser, error) | // OpenFile returns file reader
func (l *httpFileSystem) OpenFile(filePath string) (io.ReadCloser, error) | {
if l.reader == nil {
return nil, trace.BadParameter("missing reader")
}
return l.reader, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/sshutils/scp/http.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/scp/http.go#L182-L195 | go | train | // CreateFile sets proper HTTP headers and returns HTTP writer to stream incoming
// file content | func (l *httpFileSystem) CreateFile(filePath string, length uint64) (io.WriteCloser, error) | // CreateFile sets proper HTTP headers and returns HTTP writer to stream incoming
// file content
func (l *httpFileSystem) CreateFile(filePath string, length uint64) (io.WriteCloser, error) | {
_, filename := filepath.Split(filePath)
contentLength := strconv.FormatUint(length, 10)
header := l.writer.Header()
httplib.SetNoCacheHeaders(header)
httplib.SetNoSniff(header)
header.Set("Content-Length", contentLength)
header.Set("Content-Type", "application/octet-stream")
filename = url.QueryEscape(filen... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/sshutils/scp/http.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/scp/http.go#L198-L204 | go | train | // GetFileInfo returns file information | func (l *httpFileSystem) GetFileInfo(filePath string) (FileInfo, error) | // GetFileInfo returns file information
func (l *httpFileSystem) GetFileInfo(filePath string) (FileInfo, error) | {
return &httpFileInfo{
name: l.fileName,
path: l.fileName,
size: l.fileSize,
}, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/writer.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/writer.go#L37-L49 | go | train | // Write multiplexes the input to multiple sub-writers. If any of the write
// fails, it won't attempt to write to other writers | func (w *BroadcastWriter) Write(p []byte) (n int, err error) | // Write multiplexes the input to multiple sub-writers. If any of the write
// fails, it won't attempt to write to other writers
func (w *BroadcastWriter) Write(p []byte) (n int, err error) | {
for _, writer := range w.writers {
n, err = writer.Write(p)
if err != nil {
return
}
if n != len(p) {
err = io.ErrShortWrite
return
}
}
return len(p), nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/memory/memory.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/memory/memory.go#L63-L80 | go | train | // CheckAndSetDefaults checks and sets default values | func (cfg *Config) CheckAndSetDefaults() error | // CheckAndSetDefaults checks and sets default values
func (cfg *Config) CheckAndSetDefaults() error | {
if cfg.Context == nil {
cfg.Context = context.Background()
}
if cfg.BufferSize == 0 {
cfg.BufferSize = backend.DefaultBufferSize
}
if cfg.BTreeDegree <= 0 {
cfg.BTreeDegree = defaultBTreeDegree
}
if cfg.Clock == nil {
cfg.Clock = clockwork.NewRealClock()
}
if cfg.Component == "" {
cfg.Component = ... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/memory/memory.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/memory/memory.go#L83-L106 | go | train | // New creates a new memory backend | func New(cfg Config) (*Memory, error) | // New creates a new memory backend
func New(cfg Config) (*Memory, error) | {
if err := cfg.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
ctx, cancel := context.WithCancel(cfg.Context)
buf, err := backend.NewCircularBuffer(ctx, cfg.BufferSize)
if err != nil {
cancel()
return nil, trace.Wrap(err)
}
m := &Memory{
Mutex: &sync.Mutex{},
Entry: log.WithFields(l... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/memory/memory.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/memory/memory.go#L128-L134 | go | train | // Close closes memory backend | func (m *Memory) Close() error | // Close closes memory backend
func (m *Memory) Close() error | {
m.cancel()
m.Lock()
defer m.Unlock()
m.buf.Close()
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/memory/memory.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/memory/memory.go#L148-L163 | go | train | // Create creates item if it does not exist | func (m *Memory) Create(ctx context.Context, i backend.Item) (*backend.Lease, error) | // Create creates item if it does not exist
func (m *Memory) Create(ctx context.Context, i backend.Item) (*backend.Lease, error) | {
if len(i.Key) == 0 {
return nil, trace.BadParameter("missing parameter key")
}
m.Lock()
defer m.Unlock()
m.removeExpired()
if m.tree.Get(&btreeItem{Item: i}) != nil {
return nil, trace.AlreadyExists("key %q already exists", string(i.Key))
}
m.processEvent(backend.Event{
Type: backend.OpPut,
Item: i,
... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/memory/memory.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/memory/memory.go#L166-L179 | go | train | // Get returns a single item or not found error | func (m *Memory) Get(ctx context.Context, key []byte) (*backend.Item, error) | // Get returns a single item or not found error
func (m *Memory) Get(ctx context.Context, key []byte) (*backend.Item, error) | {
if len(key) == 0 {
return nil, trace.BadParameter("missing parameter key")
}
m.Lock()
defer m.Unlock()
m.removeExpired()
i := m.tree.Get(&btreeItem{Item: backend.Item{Key: key}})
if i == nil {
return nil, trace.NotFound("key %q is not found", string(key))
}
item := i.(*btreeItem).Item
return &item, nil... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/memory/memory.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/memory/memory.go#L182-L204 | go | train | // Update updates item if it exists, or returns NotFound error | func (m *Memory) Update(ctx context.Context, i backend.Item) (*backend.Lease, error) | // Update updates item if it exists, or returns NotFound error
func (m *Memory) Update(ctx context.Context, i backend.Item) (*backend.Lease, error) | {
if len(i.Key) == 0 {
return nil, trace.BadParameter("missing parameter key")
}
m.Lock()
defer m.Unlock()
m.removeExpired()
if m.tree.Get(&btreeItem{Item: i}) == nil {
return nil, trace.NotFound("key %q is not found", string(i.Key))
}
if !m.Mirror {
i.ID = m.generateID()
}
event := backend.Event{
Ty... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/memory/memory.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/memory/memory.go#L208-L224 | go | train | // Put puts value into backend (creates if it does not
// exists, updates it otherwise) | func (m *Memory) 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 (m *Memory) Put(ctx context.Context, i backend.Item) (*backend.Lease, error) | {
if len(i.Key) == 0 {
return nil, trace.BadParameter("missing parameter key")
}
m.Lock()
defer m.Unlock()
m.removeExpired()
event := backend.Event{
Type: backend.OpPut,
Item: i,
}
m.processEvent(event)
if !m.EventsOff {
m.buf.Push(event)
}
return m.newLease(i), nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/memory/memory.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/memory/memory.go#L228-L251 | go | train | // PutRange puts range of items into backend (creates if items does not
// exists, updates it otherwise) | func (m *Memory) PutRange(ctx context.Context, items []backend.Item) error | // PutRange puts range of items into backend (creates if items does not
// exists, updates it otherwise)
func (m *Memory) 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)
}
}
m.Lock()
defer m.Unlock()
m.removeExpired()
for _, item := range items {
event := backend.Event{
Type: backend.OpPut,
Item: item,
}
if !m.Mirror {
event.Item.ID = m.generat... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/memory/memory.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/memory/memory.go#L255-L276 | go | train | // Delete deletes item by key, returns NotFound error
// if item does not exist | func (m *Memory) Delete(ctx context.Context, key []byte) error | // Delete deletes item by key, returns NotFound error
// if item does not exist
func (m *Memory) Delete(ctx context.Context, key []byte) error | {
if len(key) == 0 {
return trace.BadParameter("missing parameter key")
}
m.Lock()
defer m.Unlock()
m.removeExpired()
if m.tree.Get(&btreeItem{Item: backend.Item{Key: key}}) == nil {
return trace.NotFound("key %q is not found", string(key))
}
event := backend.Event{
Type: backend.OpDelete,
Item: backen... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/memory/memory.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/memory/memory.go#L280-L298 | 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 (m *Memory) 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 (m *Memory) 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")
}
m.Lock()
defer m.Unlock()
m.removeExpired()
re := m.getRange(ctx, startKey, endKey, backend.NoLimit)
for _, item := range re.Items {
m.process... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/memory/memory.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/memory/memory.go#L301-L316 | go | train | // GetRange returns query range | func (m *Memory) GetRange(ctx context.Context, startKey []byte, endKey []byte, limit int) (*backend.GetResult, error) | // GetRange returns query range
func (m *Memory) 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
}
m.Lock()
defer m.Unlock()
m.removeExpired()
re := m.getRange(ctx, startKey, end... |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/memory/memory.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/memory/memory.go#L319-L341 | go | train | // KeepAlive updates TTL on the lease | func (m *Memory) KeepAlive(ctx context.Context, lease backend.Lease, expires time.Time) error | // KeepAlive updates TTL on the lease
func (m *Memory) KeepAlive(ctx context.Context, lease backend.Lease, expires time.Time) error | {
if lease.IsEmpty() {
return trace.BadParameter("lease is empty")
}
m.Lock()
defer m.Unlock()
m.removeExpired()
i := m.tree.Get(&btreeItem{Item: backend.Item{Key: lease.Key}})
if i == nil {
return trace.NotFound("key %q is not found", string(lease.Key))
}
item := i.(*btreeItem).Item
item.Expires = expir... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.