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 "":
var p ProvisionTokenV1
err := utils.FastUnmarshal(data, &p)
if err != nil {
return nil, trace.Wrap(err)
}
v2 := p.V2()
if cfg.ID != 0 {
v2.SetResourceID(cfg.ID)
}
return v2, nil
case V2:
var p ProvisionTokenV2
if cfg.SkipValidation {
if err := utils.FastUnmarshal(data, &p); err != nil {
return nil, trace.BadParameter(err.Error())
}
} else {
if err := utils.UnmarshalWithSchema(GetProvisionTokenSchema(), &p, data); err != nil {
return nil, trace.BadParameter(err.Error())
}
}
if err := p.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
if cfg.ID != 0 {
p.SetResourceID(cfg.ID)
}
return &p, nil
}
return nil, trace.BadParameter("server resource version %v is not supported", h.Version)
} |
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("don't know how to marshal %v", V1)
}
return utils.FastMarshal(v.V1())
case V2:
v, ok := t.(token2)
if !ok {
return nil, trace.BadParameter("don't know how to marshal %v", V2)
}
return utils.FastMarshal(v.V2())
default:
return nil, trace.BadParameter("version %v is not supported", version)
}
} |
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 := ssh.NewClientConn(pconn, addr, config)
if err != nil {
return nil, trace.Wrap(err)
}
if config.Timeout > 0 {
pconn.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#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.Debugf("Found proxy %q in environment, returning proxy dialer.", proxyAddr)
return proxyDial{proxyHost: proxyAddr}
} |
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)
}
if err = cfg.Validate(); err != nil {
return nil, trace.Wrap(err)
}
buf, err := backend.NewCircularBuffer(ctx, cfg.BufferSize)
if err != nil {
return nil, trace.Wrap(err)
}
closeCtx, cancel := context.WithCancel(ctx)
watchStarted, signalWatchStart := context.WithCancel(ctx)
b := &EtcdBackend{
Entry: log.WithFields(log.Fields{trace.Component: GetName()}),
cfg: cfg,
nodes: cfg.Nodes,
cancelC: make(chan bool, 1),
stopC: make(chan bool, 1),
clock: clockwork.NewRealClock(),
cancel: cancel,
ctx: closeCtx,
watchStarted: watchStarted,
signalWatchStart: signalWatchStart,
buf: buf,
}
if err = b.reconnect(); err != nil {
return nil, trace.Wrap(err)
}
// Wrap backend in a input sanitizer and return it.
return b, nil
} |
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.TLSCertFile == "" {
return trace.BadParameter(`etcd: missing "tls_cert_file" setting`)
}
if cfg.TLSCAFile == "" {
return trace.BadParameter(`etcd: missing "tls_ca_file" setting`)
}
}
if cfg.BufferSize == 0 {
cfg.BufferSize = backend.DefaultBufferSize
}
if cfg.DialTimeout == 0 {
cfg.DialTimeout = defaults.DefaultDialTimeout
}
return nil
} |
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, clientv3.WithLimit(int64(limit)))
}
start := b.clock.Now()
re, err := b.client.Get(ctx, prependPrefix(startKey), opts...)
batchReadLatencies.Observe(time.Since(start).Seconds())
batchReadRequests.Inc()
if err := convertErr(err); err != nil {
return nil, trace.Wrap(err)
}
items := make([]backend.Item, 0, len(re.Kvs))
for _, kv := range re.Kvs {
value, err := unmarshal(kv.Value)
if err != nil {
return nil, trace.Wrap(err)
}
items = append(items, backend.Item{
Key: trimPrefix(kv.Key),
Value: value,
ID: kv.ModRevision,
LeaseID: kv.Lease,
})
}
sort.Sort(backend.Items(items))
return &backend.GetResult{Items: items}, nil
} |
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)), "=", 0)).
Then(clientv3.OpPut(prependPrefix(item.Key), base64.StdEncoding.EncodeToString(item.Value), opts...)).
Commit()
txLatencies.Observe(time.Since(start).Seconds())
txRequests.Inc()
if err != nil {
return nil, trace.Wrap(convertErr(err))
}
if !re.Succeeded {
return nil, trace.AlreadyExists("%q already exists", string(item.Key))
}
return &lease, nil
} |
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")
}
var opts []clientv3.OpOption
var lease backend.Lease
if !replaceWith.Expires.IsZero() {
if err := b.setupLease(ctx, replaceWith, &lease, &opts); err != nil {
return nil, trace.Wrap(err)
}
}
encodedPrev := base64.StdEncoding.EncodeToString(expected.Value)
start := b.clock.Now()
re, err := b.client.Txn(ctx).
If(clientv3.Compare(clientv3.Value(prependPrefix(expected.Key)), "=", encodedPrev)).
Then(clientv3.OpPut(prependPrefix(expected.Key), base64.StdEncoding.EncodeToString(replaceWith.Value), opts...)).
Commit()
txLatencies.Observe(time.Since(start).Seconds())
txRequests.Inc()
if err != nil {
err = convertErr(err)
if trace.IsNotFound(err) {
return nil, trace.CompareFailed(err.Error())
}
}
if !re.Succeeded {
return nil, trace.CompareFailed("key %q did not match expected value", string(expected.Key))
}
return &lease, nil
} |
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),
opts...)
writeLatencies.Observe(time.Since(start).Seconds())
writeRequests.Inc()
if err != nil {
return nil, convertErr(err)
}
return &lease, nil
} |
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.Key))
}
// instead of keep-alive on the old lease, setup a new lease
// because we would like the event to be generated
// which does not happen in case of lease keep-alive
var opts []clientv3.OpOption
var newLease backend.Lease
if err := b.setupLease(ctx, backend.Item{Expires: expires}, &newLease, &opts); err != nil {
return trace.Wrap(err)
}
opts = append(opts, clientv3.WithIgnoreValue())
kv := re.Kvs[0]
_, err = b.client.Put(ctx, string(kv.Key), "", opts...)
return convertErr(err)
} |
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(err)
}
return &backend.Item{Key: key, Value: bytes, ID: kv.ModRevision, LeaseID: kv.Lease}, nil
} |
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(time.Since(start).Seconds())
writeRequests.Inc()
if err != nil {
return trace.Wrap(convertErr(err))
}
return nil
} |
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.exportPrivateKeys)
a.authExport.Flag("fingerprint", "filter authority by fingerprint").StringVar(&a.exportAuthorityFingerprint)
a.authExport.Flag("compat", "export cerfiticates compatible with specific version of Teleport").StringVar(&a.compatVersion)
a.authExport.Flag("type", "certificate type: 'user', 'host' or 'tls'").StringVar(&a.authType)
a.authGenerate = auth.Command("gen", "Generate a new SSH keypair").Hidden()
a.authGenerate.Flag("pub-key", "path to the public key").Required().StringVar(&a.genPubPath)
a.authGenerate.Flag("priv-key", "path to the private key").Required().StringVar(&a.genPrivPath)
a.authSign = auth.Command("sign", "Create an identity file(s) for a given user")
a.authSign.Flag("user", "Teleport user name").StringVar(&a.genUser)
a.authSign.Flag("host", "Teleport host name").StringVar(&a.genHost)
a.authSign.Flag("out", "identity output").Short('o').StringVar(&a.output)
a.authSign.Flag("format", fmt.Sprintf("identity format: %q (default) or %q", client.IdentityFormatFile, client.IdentityFormatOpenSSH)).Default(string(client.DefaultIdentityFormat)).StringVar((*string)(&a.outputFormat))
a.authSign.Flag("ttl", "TTL (time to live) for the generated certificate").Default(fmt.Sprintf("%v", defaults.CertDuration)).DurationVar(&a.genTTL)
a.authSign.Flag("compat", "OpenSSH compatibility flag").StringVar(&a.compatibility)
a.authRotate = auth.Command("rotate", "Rotate certificate authorities in the cluster")
a.authRotate.Flag("grace-period", "Grace period keeps previous certificate authorities signatures valid, if set to 0 will force users to relogin and nodes to re-register.").Default(fmt.Sprintf("%v", defaults.RotationGracePeriod)).DurationVar(&a.rotateGracePeriod)
a.authRotate.Flag("manual", "Activate manual rotation , set rotation phases manually").BoolVar(&a.rotateManualMode)
a.authRotate.Flag("type", "Certificate authority to rotate, rotates both host and user CA by default").StringVar(&a.rotateType)
a.authRotate.Flag("phase", fmt.Sprintf("Target rotation phase to set, used in manual rotation, one of: %v", strings.Join(services.RotatePhases, ", "))).StringVar(&a.rotateTargetPhase)
} |
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
}
return true, trace.Wrap(err)
} |
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: clusterName},
a.exportPrivateKeys)
if err != nil {
return trace.Wrap(err)
}
if len(certAuthority.GetTLSKeyPairs()) != 1 {
return trace.BadParameter("expected one TLS key pair, got %v", len(certAuthority.GetTLSKeyPairs()))
}
keyPair := certAuthority.GetTLSKeyPairs()[0]
if a.exportPrivateKeys {
fmt.Println(string(keyPair.Key))
}
fmt.Println(string(keyPair.Cert))
return nil
}
// if no --type flag is given, export all types
if a.authType == "" {
typesToExport = []services.CertAuthType{services.HostCA, services.UserCA}
} else {
authType := services.CertAuthType(a.authType)
if err := authType.Check(); err != nil {
return trace.Wrap(err)
}
typesToExport = []services.CertAuthType{authType}
}
localAuthName, err := client.GetDomainName()
if err != nil {
return trace.Wrap(err)
}
// fetch authorities via auth API (and only take local CAs, ignoring
// trusted ones)
var authorities []services.CertAuthority
for _, at := range typesToExport {
cas, err := client.GetCertAuthorities(at, a.exportPrivateKeys)
if err != nil {
return trace.Wrap(err)
}
for _, ca := range cas {
if ca.GetClusterName() == localAuthName {
authorities = append(authorities, ca)
}
}
}
// print:
for _, ca := range authorities {
if a.exportPrivateKeys {
for _, key := range ca.GetSigningKeys() {
fingerprint, err := sshutils.PrivateKeyFingerprint(key)
if err != nil {
return trace.Wrap(err)
}
if a.exportAuthorityFingerprint != "" && fingerprint != a.exportAuthorityFingerprint {
continue
}
os.Stdout.Write(key)
fmt.Fprintf(os.Stdout, "\n")
}
} else {
for _, keyBytes := range ca.GetCheckingKeys() {
fingerprint, err := sshutils.AuthorizedKeyFingerprint(keyBytes)
if err != nil {
return trace.Wrap(err)
}
if a.exportAuthorityFingerprint != "" && fingerprint != a.exportAuthorityFingerprint {
continue
}
// export certificates in the old 1.0 format where host and user
// certificate authorities were exported in the known_hosts format.
if a.compatVersion == "1.0" {
castr, err := hostCAFormat(ca, keyBytes, client)
if err != nil {
return trace.Wrap(err)
}
fmt.Println(castr)
continue
}
// export certificate authority in user or host ca format
var castr string
switch ca.GetType() {
case services.UserCA:
castr, err = userCAFormat(ca, keyBytes)
case services.HostCA:
castr, err = hostCAFormat(ca, keyBytes, client)
default:
return trace.BadParameter("unknown user type: %q", ca.GetType())
}
if err != nil {
return trace.Wrap(err)
}
// print the export friendly string
fmt.Println(castr)
}
}
}
return nil
} |
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 trace.Wrap(err)
}
err = ioutil.WriteFile(a.genPrivPath, privBytes, 0600)
if err != nil {
return trace.Wrap(err)
}
fmt.Printf("wrote public key to: %v and private key to: %v\n", a.genPubPath, a.genPrivPath)
return nil
} |
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); err != nil {
return err
}
if a.rotateTargetPhase != "" {
fmt.Printf("Updated rotation phase to %q. To check status use 'tctl status'\n", a.rotateTargetPhase)
} else {
fmt.Printf("Initiated certificate authority rotation. To check status use 'tctl status'\n")
}
return nil
} |
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-authority AAA... type=user&clustername=cluster-a
//
// URL encoding is used to pass the CA type and cluster name into the comment field. | 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-authority AAA... type=user&clustername=cluster-a
//
// URL encoding is used to pass the CA type and cluster name into the comment field.
func userCAFormat(ca services.CertAuthority, keyBytes []byte) (string, error) | {
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-rsa AAA... type=host
//
// URL encoding is used to pass the CA type and allowed logins into the comment field. | 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-rsa AAA... type=host
//
// URL encoding is used to pass the CA type and allowed logins into the comment field.
func hostCAFormat(ca services.CertAuthority, keyBytes []byte, client auth.ClientI) (string, error) | {
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, config.MaxConnections)
if err != nil {
return nil, trace.Wrap(err)
}
return &limiter, nil
} |
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",
token, numberOfConnections, l.maxConnections)
}
l.connections[token] = numberOfConnections + 1
return nil
} |
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] = numberOfConnections - 1
}
}
} |
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: []certificates.KeyUsage{
certificates.UsageDigitalSignature,
certificates.UsageKeyEncipherment,
certificates.UsageClientAuth,
},
},
})
if err != nil {
return nil, trace.Wrap(err)
}
// Delete CSR as it seems to be hanging forever if not deleted manually.
defer func() {
if err := requests.Delete(id, &metav1.DeleteOptions{}); err != nil {
log.Warningf("Failed to delete CSR: %v.", err)
}
}()
csr.Status.Conditions = append(csr.Status.Conditions, certificates.CertificateSigningRequestCondition{
Type: certificates.CertificateApproved,
Reason: "TeleportApprove",
Message: "This CSR was approved by Teleport.",
LastUpdateTime: metav1.Now(),
})
result, err := requests.UpdateApproval(csr)
if err != nil {
return nil, trace.Wrap(err)
}
if result.Status.Certificate != nil {
log.Debugf("Received certificate right after approval, returning.")
return result.Status.Certificate, nil
}
ctx, cancel := context.WithTimeout(context.TODO(), defaults.CSRSignTimeout)
defer cancel()
watchForCert := func() ([]byte, error) {
watcher, err := requests.Watch(metav1.ListOptions{
TypeMeta: metav1.TypeMeta{
Kind: teleport.KubeKindCSR,
},
FieldSelector: fields.Set{teleport.KubeMetadataNameSelector: id}.String(),
Watch: true,
})
if err != nil {
return nil, trace.Wrap(err)
}
cert, err := waitForCSR(ctx, watcher.ResultChan())
watcher.Stop()
if err == nil {
return cert, nil
}
return nil, trace.Wrap(err)
}
// this could be infinite loop, but is limited to certain number
// of iterations just in case.
for i := 0; i < int(defaults.CSRSignTimeout/time.Second); i++ {
cert, err := watchForCert()
if err == nil {
return cert, nil
}
if !trace.IsRetryError(err) {
return nil, trace.Wrap(err)
}
select {
case <-time.After(time.Second):
log.Debugf("Retry after network error: %v.", err)
case <-ctx.Done():
return nil, trace.BadParameter(timeoutCSRMessage)
}
}
return nil, trace.BadParameter(timeoutCSRMessage)
} |
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 secondFactor {
case teleport.OFF:
return s.CheckPasswordWOToken(userID, req.OldPassword)
case teleport.OTP:
return s.CheckPassword(userID, req.OldPassword, req.SecondFactorToken)
case teleport.U2F:
if req.U2FSignResponse == nil {
return trace.BadParameter("missing U2F sign response")
}
return s.CheckU2FSignResponse(userID, req.U2FSignResponse)
}
return trace.BadParameter("unsupported second factor method: %q", secondFactor)
}
err = s.WithUserLock(userID, fn)
if err != nil {
return trace.Wrap(err)
}
return trace.Wrap(s.UpsertPassword(userID, req.NewPassword))
} |
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 found, using fake hash to mitigate timing attacks.", user)
hash = fakePasswordHash
}
if err = bcrypt.CompareHashAndPassword(hash, password); err != nil {
log.Debugf("Password for %q does not match", user)
return trace.BadParameter(errMsg)
}
return nil
} |
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.HOTPFirstTokensRange) {
return trace.BadParameter("bad one time token")
}
// we need to upsert the hotp state again because the
// counter was incremented
if err := s.UpsertHOTP(user, otp); err != nil {
return trace.Wrap(err)
}
case teleport.TOTP:
otpSecret, err := s.GetTOTP(user)
if err != nil {
return trace.Wrap(err)
}
// get the previously used token to mitigate token replay attacks
usedToken, err := s.GetUsedTOTPToken(user)
if err != nil {
return trace.Wrap(err)
}
// we use a constant time compare function to mitigate timing attacks
if subtle.ConstantTimeCompare([]byte(otpToken), []byte(usedToken)) == 1 {
return trace.BadParameter("previously used totp token")
}
// we use totp.ValidateCustom over totp.Validate so we can use
// a fake clock in tests to get reliable results
valid, err := totp.ValidateCustom(otpToken, otpSecret, s.clock.Now(), totp.ValidateOpts{
Period: teleport.TOTPValidityPeriod,
Skew: teleport.TOTPSkew,
Digits: otp.DigitsSix,
Algorithm: otp.AlgorithmSHA1,
})
if err != nil {
log.Errorf("unable to validate token: %v", err)
return trace.BadParameter("unable to validate token")
}
if !valid {
return trace.BadParameter("invalid totp token")
}
// if we have a valid token, update the previously used token
err = s.UpsertUsedTOTPToken(user, otpToken)
if err != nil {
return trace.Wrap(err)
}
}
return nil
} |
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)
if err != nil {
return "", nil, trace.Wrap(err)
}
return otpURL, otpQR, nil
} |
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 type,
// it returns empty values for unrecognized values to
// pass static rule checks.
"system.catype": func() (interface{}, error) {
resource, err := ctx.GetResource()
if err != nil {
if trace.IsNotFound(err) {
return "", nil
}
return nil, trace.Wrap(err)
}
ca, ok := resource.(CertAuthority)
if !ok {
return "", nil
}
return string(ca.GetType()), nil
},
},
GetIdentifier: ctx.GetIdentifier,
GetProperty: GetStringMapValue,
})
} |
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 {
// to return nil with a proper type
var n []string
return n, nil
}
return m[key], nil
case map[string]string:
if len(m) == 0 {
return "", nil
}
return m[key], nil
default:
_, ok := mapVal.(map[string][]string)
return nil, trace.BadParameter("type %T is not supported, but %v %#v", m, ok, mapVal)
}
} |
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 {
resource = ctx.Resource
}
return predicate.GetFieldByTag(resource, "json", fields[1:])
default:
return nil, trace.NotFound("%v is not defined", strings.Join(fields, "."))
}
} |
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)
}
ciphertext, err := json.Marshal(&sealedData{
Ciphertext: aesgcm.Seal(nil, nonce, plaintext, nil),
Nonce: nonce,
})
if err != nil {
return nil, trace.Wrap(err)
}
return ciphertext, nil
} |
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(nil, data.Nonce, data.Ciphertext, nil)
if err != nil {
return nil, trace.Wrap(err)
}
return plaintext, nil
} |
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,
Clock: cfg.Clock,
})
if err != nil {
return nil, trace.Wrap(err)
}
return &Forwarder{
ForwarderConfig: cfg,
sessionLogger: diskLogger,
}, nil
} |
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(),
},
}
return l.PostSessionSlice(SessionSlice{
Namespace: l.Namespace,
SessionID: string(l.SessionID),
Version: V3,
Chunks: chunks,
})
} |
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)
}
// no chunks to post (all chunks are print events)
if len(chunksWithoutPrintEvents) == 0 {
return nil
}
slice.Chunks = chunksWithoutPrintEvents
slice.Version = V3
err = l.ForwardTo.PostSessionSlice(slice)
return 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, sid session.ID, offsetBytes, maxBytes int) ([]byte, error) | {
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 string, sid session.ID, after int, includePrintEvents bool) ([]EventFields, error) | {
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 always
// show up sorted by date (newest first) | 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 always
// show up sorted by date (newest first)
func (l *Forwarder) SearchEvents(fromUTC, toUTC time.Time, query string, limit int) ([]EventFields, error) | {
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 !utils.IsDir(path) {
return nil, trace.BadParameter("%v is not a valid directory", path)
}
path, err := filepath.Abs(filepath.Join(path, keysBoltFile))
if err != nil {
return nil, trace.Wrap(err)
}
db, err := bolt.Open(path, openFileMode, &bolt.Options{Timeout: openTimeout})
if err != nil {
if err == bolt.ErrTimeout {
return nil, trace.Errorf("Local storage is locked. Another instance is running? (%v)", path)
}
return nil, trace.Wrap(err)
}
// Wrap the backend in a input sanitizer and return it.
return &BoltBackend{
locks: make(map[string]time.Time),
clock: clockwork.NewRealClock(),
db: db,
}, nil
} |
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 := range rootBuckets {
f := &fetcher{
bucket: bucket,
}
err := b.db.View(f.fetch)
if err != nil {
return nil, trace.Wrap(boltErr(err))
}
for _, p := range f.paths {
item, err := b.getItem(p.bucket, p.key)
if err != nil {
continue
}
items = append(items, *item)
}
}
return items, nil
} |
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 interface since the Bolt backend is slated for removal
// in 2.7.0 anyway.
items := make([]legacy.Item, 0, len(keys))
for _, e := range keys {
val, err := b.GetVal(path, e)
if err != nil {
continue
}
items = append(items, legacy.Item{
Key: e,
Value: val,
})
}
return items, nil
} |
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 []byte, prevData []byte, ttl time.Duration) error | {
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.Update(func(tx *bolt.Tx) error {
bkt, err := GetBucket(tx, bucket)
if err != nil {
if trace.IsNotFound(err) {
return trace.CompareFailed("key %q is not found", key)
}
return trace.Wrap(err)
}
currentData := bkt.Get([]byte(key))
if currentData == nil {
_, err := GetBucket(tx, append(bucket, key))
if err == nil {
return trace.BadParameter("key %q is a bucket", key)
}
return trace.CompareFailed("%v %v is not found", bucket, key)
}
var currentVal kv
if err := json.Unmarshal(currentData, ¤tVal); err != nil {
return trace.Wrap(err)
}
if bytes.Compare(prevData, currentVal.Value) != 0 {
return trace.CompareFailed("%q is not matching expected value", key)
}
return boltErr(bkt.Put([]byte(key), newEncodedData))
})
return trace.Wrap(err)
} |
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.Get("Content-Length")
fileSize, err := strconv.ParseInt(contentLength, 10, 0)
if err != nil {
return nil, trace.BadParameter("failed to parse Content-Length header: %q", contentLength)
}
fs := &httpFileSystem{
reader: req.HTTPRequest.Body,
fileName: req.FileName,
fileSize: fileSize,
}
flags := Flags{
// scp treats it as a list of files to upload
Target: []string{req.FileName},
}
cfg := Config{
Flags: flags,
FileSystem: fs,
User: req.User,
ProgressWriter: req.Progress,
RemoteLocation: req.RemoteLocation,
AuditLog: req.AuditLog,
}
cmd, err := CreateUploadCommand(cfg)
if err != nil {
return nil, trace.Wrap(err)
}
return cmd, nil
} |
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{
writer: req.HTTPResponse,
},
}
cmd, err := CreateDownloadCommand(cfg)
if err != nil {
return nil, trace.Wrap(err)
}
return cmd, nil
} |
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(filename)
header.Set("Content-Disposition", fmt.Sprintf(`attachment;filename="%v"`, filename))
return &nopWriteCloser{Writer: l.writer}, nil
} |
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 = teleport.ComponentMemory
}
return nil
} |
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(log.Fields{
trace.Component: teleport.ComponentMemory,
}),
Config: cfg,
tree: btree.New(cfg.BTreeDegree),
heap: newMinHeap(),
cancel: cancel,
ctx: ctx,
buf: buf,
}
return m, nil
} |
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,
})
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#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{
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#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.generateID()
}
m.processEvent(event)
if !m.EventsOff {
m.buf.Push(event)
}
}
return nil
} |
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: backend.Item{
Key: key,
},
}
m.processEvent(event)
if !m.EventsOff {
m.buf.Push(event)
}
return nil
} |
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.processEvent(backend.Event{
Type: backend.OpDelete,
Item: item,
})
}
return nil
} |
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, endKey, limit)
return &re, nil
} |
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 = expires
event := backend.Event{
Type: backend.OpPut,
Item: item,
}
m.processEvent(event)
if !m.EventsOff {
m.buf.Push(event)
}
return nil
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.