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/kube/client/kubeclient.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/client/kubeclient.go#L142-L163 | go | train | // kubeconfigFromEnv extracts location of kubeconfig from the environment. | func kubeconfigFromEnv() string | // kubeconfigFromEnv extracts location of kubeconfig from the environment.
func kubeconfigFromEnv() string | {
kubeconfig := os.Getenv(teleport.EnvKubeConfig)
// The KUBECONFIG environment variable is a list. On Windows it's
// semicolon-delimited. On Linux and macOS it's colon-delimited.
var parts []string
switch runtime.GOOS {
case teleport.WindowsOS:
parts = strings.Split(kubeconfig, ";")
default:
parts = strings.Split(kubeconfig, ":")
}
// Default behavior of kubectl is to return the first file from list.
var configpath string
if len(parts) > 0 {
configpath = parts[0]
}
log.Debugf("Found kubeconfig in environment at '%v'.", configpath)
return configpath
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/events/filelog.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/filelog.go#L60-L86 | go | train | // CheckAndSetDefaults checks and sets config defaults | func (cfg *FileLogConfig) CheckAndSetDefaults() error | // CheckAndSetDefaults checks and sets config defaults
func (cfg *FileLogConfig) CheckAndSetDefaults() error | {
if cfg.Dir == "" {
return trace.BadParameter("missing parameter Dir")
}
if !utils.IsDir(cfg.Dir) {
return trace.BadParameter("path %q does not exist or is not a directory", cfg.Dir)
}
if cfg.SymlinkDir == "" {
cfg.SymlinkDir = cfg.Dir
}
if !utils.IsDir(cfg.SymlinkDir) {
return trace.BadParameter("path %q does not exist or is not a directory", cfg.SymlinkDir)
}
if cfg.RotationPeriod == 0 {
cfg.RotationPeriod = defaults.LogRotationPeriod
}
if cfg.RotationPeriod%(24*time.Hour) != 0 {
return trace.BadParameter("rotation period %v is not a multiple of 24 hours, e.g. '24h' or '48h'", cfg.RotationPeriod)
}
if cfg.Clock == nil {
cfg.Clock = clockwork.NewRealClock()
}
if cfg.UIDGenerator == nil {
cfg.UIDGenerator = utils.NewRealUID()
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/events/filelog.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/filelog.go#L89-L100 | go | train | // NewFileLog returns a new instance of a file log | func NewFileLog(cfg FileLogConfig) (*FileLog, error) | // NewFileLog returns a new instance of a file log
func NewFileLog(cfg FileLogConfig) (*FileLog, error) | {
if err := cfg.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
f := &FileLog{
FileLogConfig: cfg,
Entry: log.WithFields(log.Fields{
trace.Component: teleport.ComponentAuditLog,
}),
}
return f, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/events/filelog.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/filelog.go#L117-L137 | go | train | // EmitAuditEvent adds a new event to the log. Part of auth.IFileLog interface. | func (l *FileLog) EmitAuditEvent(event Event, fields EventFields) error | // EmitAuditEvent adds a new event to the log. Part of auth.IFileLog interface.
func (l *FileLog) EmitAuditEvent(event Event, fields EventFields) error | {
// see if the log needs to be rotated
err := l.rotateLog()
if err != nil {
log.Error(err)
}
err = UpdateEventFields(event, fields, l.Clock, l.UIDGenerator)
if err != nil {
log.Error(err)
}
// line is the text to be logged
line, err := json.Marshal(fields)
if err != nil {
return trace.Wrap(err)
}
// log it to the main log file:
if l.file != nil {
fmt.Fprintln(l.file, string(line))
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/events/filelog.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/filelog.go#L141-L181 | go | train | // SearchEvents finds events. Results show up sorted by date (newest first),
// limit is used when set to value > 0 | func (l *FileLog) SearchEvents(fromUTC, toUTC time.Time, query string, limit int) ([]EventFields, error) | // SearchEvents finds events. Results show up sorted by date (newest first),
// limit is used when set to value > 0
func (l *FileLog) SearchEvents(fromUTC, toUTC time.Time, query string, limit int) ([]EventFields, error) | {
l.Debugf("SearchEvents(%v, %v, query=%v, limit=%v)", fromUTC, toUTC, query, limit)
if limit <= 0 {
limit = defaults.EventsIterationLimit
}
if limit > defaults.EventsMaxIterationLimit {
return nil, trace.BadParameter("limit %v exceeds max iteration limit %v", limit, defaults.MaxIterationLimit)
}
// how many days of logs to search?
days := int(toUTC.Sub(fromUTC).Hours() / 24)
if days < 0 {
return nil, trace.BadParameter("invalid days")
}
queryVals, err := url.ParseQuery(query)
if err != nil {
return nil, trace.BadParameter("invalid query")
}
filtered, err := l.matchingFiles(fromUTC, toUTC)
if err != nil {
return nil, trace.Wrap(err)
}
var total int
// search within each file:
events := make([]EventFields, 0)
for i := range filtered {
found, err := l.findInFile(filtered[i].path, queryVals, &total, limit)
if err != nil {
return nil, trace.Wrap(err)
}
events = append(events, found...)
if limit > 0 && total >= limit {
break
}
}
// sort all accepted files by timestamp or by event index
// in case if events are associated with the same session, to make
// sure that events are not displayed out of order in case of multiple
// auth servers.
sort.Sort(ByTimeAndIndex(events))
return events, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/events/filelog.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/filelog.go#L184-L226 | go | train | // SearchSessionEvents searches for session related events. Used to find completed sessions. | func (l *FileLog) SearchSessionEvents(fromUTC, toUTC time.Time, limit int) ([]EventFields, error) | // SearchSessionEvents searches for session related events. Used to find completed sessions.
func (l *FileLog) SearchSessionEvents(fromUTC, toUTC time.Time, limit int) ([]EventFields, error) | {
l.Debugf("SearchSessionEvents(%v, %v, %v)", fromUTC, toUTC, limit)
// only search for specific event types
query := url.Values{}
query[EventType] = []string{
SessionStartEvent,
SessionEndEvent,
}
// because of the limit and distributed nature of auth server event
// logs, some events can be fetched with session end event and without
// session start event. to fix this, the code below filters out the events without
// start event to guarantee that all events in the range will get fetched
events, err := l.SearchEvents(fromUTC, toUTC, query.Encode(), limit)
if err != nil {
return nil, trace.Wrap(err)
}
// filter out 'session end' events that do not
// have a corresponding 'session start' event
started := make(map[string]struct{}, len(events)/2)
filtered := make([]EventFields, 0, len(events))
for i := range events {
event := events[i]
eventType := event[EventType]
sessionID := event.GetString(SessionEventID)
if sessionID == "" {
continue
}
if eventType == SessionStartEvent {
started[sessionID] = struct{}{}
filtered = append(filtered, event)
}
if eventType == SessionEndEvent {
if _, ok := started[sessionID]; ok {
filtered = append(filtered, event)
}
}
}
return filtered, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/events/filelog.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/filelog.go#L230-L240 | go | train | // Close closes the audit log, which inluces closing all file handles and releasing
// all session loggers | func (l *FileLog) Close() error | // Close closes the audit log, which inluces closing all file handles and releasing
// all session loggers
func (l *FileLog) Close() error | {
l.Lock()
defer l.Unlock()
var err error
if l.file != nil {
err = l.file.Close()
l.file = nil
}
return err
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/events/filelog.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/filelog.go#L292-L342 | go | train | // rotateLog checks if the current log file is older than a given duration,
// and if it is, closes it and opens a new one. | func (l *FileLog) rotateLog() (err error) | // rotateLog checks if the current log file is older than a given duration,
// and if it is, closes it and opens a new one.
func (l *FileLog) rotateLog() (err error) | {
l.Lock()
defer l.Unlock()
// determine the timestamp for the current log file
fileTime := l.Clock.Now().In(time.UTC)
// truncate time to the resolution of one day, cutting at the day end boundary
fileTime = time.Date(fileTime.Year(), fileTime.Month(), fileTime.Day(), 0, 0, 0, 0, time.UTC)
logFilename := filepath.Join(l.Dir,
fileTime.Format(defaults.AuditLogTimeFormat)+LogfileExt)
openLogFile := func() error {
l.file, err = os.OpenFile(logFilename, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0640)
if err != nil {
log.Error(err)
}
l.fileTime = fileTime
return trace.Wrap(err)
}
linkFilename := filepath.Join(l.SymlinkDir, SymlinkFilename)
createSymlink := func() error {
err = trace.ConvertSystemError(os.Remove(linkFilename))
if err != nil {
if !trace.IsNotFound(err) {
return trace.Wrap(err)
}
}
return trace.ConvertSystemError(os.Symlink(logFilename, linkFilename))
}
// need to create a log file?
if l.file == nil {
if err := openLogFile(); err != nil {
return trace.Wrap(err)
}
return trace.Wrap(createSymlink())
}
// time to advance the logfile?
if l.fileTime.Before(fileTime) {
l.file.Close()
if err := openLogFile(); err != nil {
return trace.Wrap(err)
}
return trace.Wrap(createSymlink())
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/events/filelog.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/filelog.go#L346-L398 | go | train | // matchingFiles returns files matching the time restrictions of the query
// across multiple auth servers, returns a list of file names | func (l *FileLog) matchingFiles(fromUTC, toUTC time.Time) ([]eventFile, error) | // matchingFiles returns files matching the time restrictions of the query
// across multiple auth servers, returns a list of file names
func (l *FileLog) matchingFiles(fromUTC, toUTC time.Time) ([]eventFile, error) | {
var dirs []string
var err error
if l.SearchDirs != nil {
dirs, err = l.SearchDirs()
if err != nil {
return nil, trace.Wrap(err)
}
} else {
dirs = []string{l.Dir}
}
var filtered []eventFile
for _, dir := range dirs {
// scan the log directory:
df, err := os.Open(dir)
if err != nil {
return nil, trace.Wrap(err)
}
defer df.Close()
entries, err := df.Readdir(-1)
if err != nil {
return nil, trace.Wrap(err)
}
for i := range entries {
fi := entries[i]
if fi.IsDir() || filepath.Ext(fi.Name()) != LogfileExt {
continue
}
fd, err := parseFileTime(fi.Name())
if err != nil {
l.Warningf("Failed to parse audit log file %q format: %v", fi.Name(), err)
continue
}
// File rounding in current logs is non-deterministic,
// as Round function used in rotateLog can round up to the lowest
// or the highest period. That's why this has to check both
// periods.
// Previous logic used modification time what was flaky
// as it could be changed by migrations or simply moving files
if fd.After(fromUTC.Add(-1*l.RotationPeriod)) && fd.Before(toUTC.Add(l.RotationPeriod)) {
eventFile := eventFile{
FileInfo: fi,
path: filepath.Join(dir, fi.Name()),
}
filtered = append(filtered, eventFile)
}
}
}
// sort all accepted files by date
sort.Sort(byDate(filtered))
return filtered, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/events/filelog.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/filelog.go#L401-L404 | go | train | // parseFileTime parses file's timestamp encoded into filename | func parseFileTime(filename string) (time.Time, error) | // parseFileTime parses file's timestamp encoded into filename
func parseFileTime(filename string) (time.Time, error) | {
base := strings.TrimSuffix(filename, filepath.Ext(filename))
return time.Parse(defaults.AuditLogTimeFormat, base)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/events/filelog.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/filelog.go#L410-L464 | go | train | // findInFile scans a given log file and returns events that fit the criteria
// This simplistic implementation ONLY SEARCHES FOR EVENT TYPE(s)
//
// You can pass multiple types like "event=session.start&event=session.end" | func (l *FileLog) findInFile(fn string, query url.Values, total *int, limit int) ([]EventFields, error) | // findInFile scans a given log file and returns events that fit the criteria
// This simplistic implementation ONLY SEARCHES FOR EVENT TYPE(s)
//
// You can pass multiple types like "event=session.start&event=session.end"
func (l *FileLog) findInFile(fn string, query url.Values, total *int, limit int) ([]EventFields, error) | {
l.Debugf("Called findInFile(%s, %v).", fn, query)
retval := make([]EventFields, 0)
eventFilter, ok := query[EventType]
if !ok && len(query) > 0 {
return nil, nil
}
doFilter := len(eventFilter) > 0
// open the log file:
lf, err := os.OpenFile(fn, os.O_RDONLY, 0)
if err != nil {
return nil, trace.Wrap(err)
}
defer lf.Close()
// for each line...
scanner := bufio.NewScanner(lf)
for lineNo := 0; scanner.Scan(); lineNo++ {
accepted := false
// optimization: to avoid parsing JSON unnecessarily, lets see if we
// can filter out lines that don't even have the requested event type on the line
for i := range eventFilter {
if strings.Contains(scanner.Text(), eventFilter[i]) {
accepted = true
break
}
}
if doFilter && !accepted {
continue
}
// parse JSON on the line and compare event type field to what's
// in the query:
var ef EventFields
if err = json.Unmarshal(scanner.Bytes(), &ef); err != nil {
l.Warnf("invalid JSON in %s line %d", fn, lineNo)
continue
}
for i := range eventFilter {
if ef.GetString(EventType) == eventFilter[i] {
accepted = true
break
}
}
if accepted || !doFilter {
retval = append(retval, ef)
*total += 1
if limit > 0 && *total >= limit {
break
}
}
}
return retval, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/events/filelog.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/filelog.go#L501-L511 | go | train | // getTime converts json time to string | func getTime(v interface{}) time.Time | // getTime converts json time to string
func getTime(v interface{}) time.Time | {
sval, ok := v.(string)
if !ok {
return time.Time{}
}
t, err := time.Parse(time.RFC3339, sval)
if err != nil {
return time.Time{}
}
return t
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/equals.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/equals.go#L33-L43 | go | train | // StringMapsEqual returns true if two strings maps are equal | func StringMapsEqual(a, b map[string]string) bool | // StringMapsEqual returns true if two strings maps are equal
func StringMapsEqual(a, b map[string]string) bool | {
if len(a) != len(b) {
return false
}
for key := range a {
if a[key] != b[key] {
return false
}
}
return true
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/equals.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/equals.go#L59-L69 | go | train | // StringMapSlicesEqual returns true if two maps of string slices are equal | func StringMapSlicesEqual(a, b map[string][]string) bool | // StringMapSlicesEqual returns true if two maps of string slices are equal
func StringMapSlicesEqual(a, b map[string][]string) bool | {
if len(a) != len(b) {
return false
}
for key := range a {
if !StringSlicesEqual(a[key], b[key]) {
return false
}
}
return true
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/saml.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/saml.go#L110-L120 | go | train | // NewSAMLConnector returns a new SAMLConnector based off a name and SAMLConnectorSpecV2. | func NewSAMLConnector(name string, spec SAMLConnectorSpecV2) SAMLConnector | // NewSAMLConnector returns a new SAMLConnector based off a name and SAMLConnectorSpecV2.
func NewSAMLConnector(name string, spec SAMLConnectorSpecV2) SAMLConnector | {
return &SAMLConnectorV2{
Kind: KindSAMLConnector,
Version: V2,
Metadata: Metadata{
Name: name,
Namespace: defaults.Namespace,
},
Spec: spec,
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/saml.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/saml.go#L155-L193 | go | train | // UnmarshalSAMLConnector unmarshals connector from | func (*TeleportSAMLConnectorMarshaler) UnmarshalSAMLConnector(bytes []byte, opts ...MarshalOption) (SAMLConnector, error) | // UnmarshalSAMLConnector unmarshals connector from
func (*TeleportSAMLConnectorMarshaler) UnmarshalSAMLConnector(bytes []byte, opts ...MarshalOption) (SAMLConnector, error) | {
cfg, err := collectOptions(opts)
if err != nil {
return nil, trace.Wrap(err)
}
var h ResourceHeader
err = utils.FastUnmarshal(bytes, &h)
if err != nil {
return nil, trace.Wrap(err)
}
switch h.Version {
case V2:
var c SAMLConnectorV2
if cfg.SkipValidation {
if err := utils.FastUnmarshal(bytes, &c); err != nil {
return nil, trace.BadParameter(err.Error())
}
} else {
if err := utils.UnmarshalWithSchema(GetSAMLConnectorSchema(), &c, bytes); err != nil {
return nil, trace.BadParameter(err.Error())
}
}
if err := c.Metadata.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
if cfg.ID != 0 {
c.SetResourceID(cfg.ID)
}
if !cfg.Expires.IsZero() {
c.SetExpiry(cfg.Expires)
}
return &c, nil
}
return nil, trace.BadParameter("SAML connector resource version %v is not supported", h.Version)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/saml.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/saml.go#L196-L223 | go | train | // MarshalUser marshals SAML connector into JSON | func (*TeleportSAMLConnectorMarshaler) MarshalSAMLConnector(c SAMLConnector, opts ...MarshalOption) ([]byte, error) | // MarshalUser marshals SAML connector into JSON
func (*TeleportSAMLConnectorMarshaler) MarshalSAMLConnector(c SAMLConnector, opts ...MarshalOption) ([]byte, error) | {
cfg, err := collectOptions(opts)
if err != nil {
return nil, trace.Wrap(err)
}
type connv2 interface {
V2() *SAMLConnectorV2
}
version := cfg.GetVersion()
switch version {
case V2:
v, ok := c.(connv2)
if !ok {
return nil, trace.BadParameter("don't know how to marshal %v", V2)
}
v2 := v.V2()
if !cfg.PreserveResourceID {
// avoid modifying the original object
// to prevent unexpected data races
copy := *v2
copy.SetResourceID(0)
v2 = ©
}
return utils.FastMarshal(v2)
default:
return nil, trace.BadParameter("version %v is not supported", version)
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/saml.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/saml.go#L340-L389 | go | train | // Equals returns true if the connectors are identical | func (o *SAMLConnectorV2) Equals(other SAMLConnector) bool | // Equals returns true if the connectors are identical
func (o *SAMLConnectorV2) Equals(other SAMLConnector) bool | {
if o.GetName() != other.GetName() {
return false
}
if o.GetCert() != other.GetCert() {
return false
}
if o.GetAudience() != other.GetAudience() {
return false
}
if o.GetEntityDescriptor() != other.GetEntityDescriptor() {
return false
}
if o.Expiry() != other.Expiry() {
return false
}
if o.GetIssuer() != other.GetIssuer() {
return false
}
if (o.GetSigningKeyPair() == nil && other.GetSigningKeyPair() != nil) || (o.GetSigningKeyPair() != nil && other.GetSigningKeyPair() == nil) {
return false
}
if o.GetSigningKeyPair() != nil {
a, b := o.GetSigningKeyPair(), other.GetSigningKeyPair()
if a.Cert != b.Cert || a.PrivateKey != b.PrivateKey {
return false
}
}
mappings := o.GetAttributesToRoles()
otherMappings := other.GetAttributesToRoles()
if len(mappings) != len(otherMappings) {
return false
}
for i := range mappings {
a, b := mappings[i], otherMappings[i]
if a.Name != b.Name || a.Value != b.Value || !utils.StringSlicesEqual(a.Roles, b.Roles) {
return false
}
if (a.RoleTemplate != nil && b.RoleTemplate == nil) || (a.RoleTemplate == nil && b.RoleTemplate != nil) {
return false
}
if a.RoleTemplate != nil && !a.RoleTemplate.Equals(b.RoleTemplate.V3()) {
return false
}
}
if o.GetSSO() != other.GetSSO() {
return false
}
return true
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/saml.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/saml.go#L407-L409 | go | train | // SetExpiry sets expiry time for the object | func (o *SAMLConnectorV2) SetExpiry(expires time.Time) | // SetExpiry sets expiry time for the object
func (o *SAMLConnectorV2) SetExpiry(expires time.Time) | {
o.Metadata.SetExpiry(expires)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/saml.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/saml.go#L442-L447 | go | train | // Display - Friendly name for this provider. | func (o *SAMLConnectorV2) GetDisplay() string | // Display - Friendly name for this provider.
func (o *SAMLConnectorV2) GetDisplay() string | {
if o.Spec.Display != "" {
return o.Spec.Display
}
return o.GetName()
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/saml.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/saml.go#L470-L476 | go | train | // GetAttributes returns list of attributes expected by mappings | func (o *SAMLConnectorV2) GetAttributes() []string | // GetAttributes returns list of attributes expected by mappings
func (o *SAMLConnectorV2) GetAttributes() []string | {
var out []string
for _, mapping := range o.Spec.AttributesToRoles {
out = append(out, mapping.Name)
}
return utils.Deduplicate(out)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/saml.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/saml.go#L479-L508 | go | train | // MapClaims maps SAML attributes to roles | func (o *SAMLConnectorV2) MapAttributes(assertionInfo saml2.AssertionInfo) []string | // MapClaims maps SAML attributes to roles
func (o *SAMLConnectorV2) MapAttributes(assertionInfo saml2.AssertionInfo) []string | {
var roles []string
for _, mapping := range o.Spec.AttributesToRoles {
for _, attr := range assertionInfo.Values {
if attr.Name != mapping.Name {
continue
}
mappingLoop:
for _, value := range attr.Values {
for _, role := range mapping.Roles {
outRole, err := utils.ReplaceRegexp(mapping.Value, role, value.Value)
switch {
case err != nil:
if !trace.IsNotFound(err) {
log.Debugf("Failed to match expression %v, replace with: %v input: %v, err: %v", mapping.Value, role, value.Value, err)
}
// if value input did not match, no need to apply
// to all roles
continue mappingLoop
case outRole == "":
// skip empty role matches
case outRole != "":
roles = append(roles, outRole)
}
}
}
}
}
return utils.Deduplicate(roles)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/saml.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/saml.go#L515-L527 | go | train | // executeSAMLStringTemplate takes a raw template string and a map of
// assertions to execute a template and generate output. Because the data
// structure used to execute the template is a map, the format of the raw
// string is expected to be {{index . "key"}}. See
// https://golang.org/pkg/text/template/ for more details. | func executeSAMLStringTemplate(raw string, assertion map[string]string) (string, error) | // executeSAMLStringTemplate takes a raw template string and a map of
// assertions to execute a template and generate output. Because the data
// structure used to execute the template is a map, the format of the raw
// string is expected to be {{index . "key"}}. See
// https://golang.org/pkg/text/template/ for more details.
func executeSAMLStringTemplate(raw string, assertion map[string]string) (string, error) | {
tmpl, err := template.New("dynamic-roles").Parse(raw)
if err != nil {
return "", trace.Wrap(err)
}
var buf bytes.Buffer
err = tmpl.Execute(&buf, assertion)
if err != nil {
return "", trace.Wrap(err)
}
return buf.String(), nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/saml.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/saml.go#L534-L552 | go | train | // executeSAMLStringTemplate takes raw template strings and a map of
// assertions to execute templates and generate a slice of output. Because the
// data structure used to execute the template is a map, the format of each raw
// string is expected to be {{index . "key"}}. See
// https://golang.org/pkg/text/template/ for more details. | func executeSAMLSliceTemplate(raw []string, assertion map[string]string) ([]string, error) | // executeSAMLStringTemplate takes raw template strings and a map of
// assertions to execute templates and generate a slice of output. Because the
// data structure used to execute the template is a map, the format of each raw
// string is expected to be {{index . "key"}}. See
// https://golang.org/pkg/text/template/ for more details.
func executeSAMLSliceTemplate(raw []string, assertion map[string]string) ([]string, error) | {
var sl []string
for _, v := range raw {
tmpl, err := template.New("dynamic-roles").Parse(v)
if err != nil {
return nil, trace.Wrap(err)
}
var buf bytes.Buffer
err = tmpl.Execute(&buf, assertion)
if err != nil {
return nil, trace.Wrap(err)
}
sl = append(sl, buf.String())
}
return sl, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/saml.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/saml.go#L555-L696 | go | train | // GetServiceProvider initialises service provider spec from settings | func (o *SAMLConnectorV2) GetServiceProvider(clock clockwork.Clock) (*saml2.SAMLServiceProvider, error) | // GetServiceProvider initialises service provider spec from settings
func (o *SAMLConnectorV2) GetServiceProvider(clock clockwork.Clock) (*saml2.SAMLServiceProvider, error) | {
if o.Metadata.Name == "" {
return nil, trace.BadParameter("ID: missing connector name, name your connector to refer to internally e.g. okta1")
}
if o.Metadata.Name == teleport.Local {
return nil, trace.BadParameter("ID: invalid connector name %v is a reserved name", teleport.Local)
}
if o.Spec.AssertionConsumerService == "" {
return nil, trace.BadParameter("missing acs - assertion consumer service parameter, set service URL that will receive POST requests from SAML")
}
if o.Spec.ServiceProviderIssuer == "" {
o.Spec.ServiceProviderIssuer = o.Spec.AssertionConsumerService
}
if o.Spec.Audience == "" {
o.Spec.Audience = o.Spec.AssertionConsumerService
}
certStore := dsig.MemoryX509CertificateStore{
Roots: []*x509.Certificate{},
}
// if we have a entity descriptor url, fetch it first
if o.Spec.EntityDescriptorURL != "" {
resp, err := http.Get(o.Spec.EntityDescriptorURL)
if err != nil {
return nil, trace.Wrap(err)
}
if resp.StatusCode != http.StatusOK {
return nil, trace.BadParameter("status code %v when fetching from %q", resp.StatusCode, o.Spec.EntityDescriptorURL)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, trace.Wrap(err)
}
o.Spec.EntityDescriptor = string(body)
log.Debugf("[SAML] Successfully fetched entity descriptor from %q", o.Spec.EntityDescriptorURL)
}
if o.Spec.EntityDescriptor != "" {
metadata := &types.EntityDescriptor{}
err := xml.Unmarshal([]byte(o.Spec.EntityDescriptor), metadata)
if err != nil {
return nil, trace.Wrap(err, "failed to parse entity_descriptor")
}
for _, kd := range metadata.IDPSSODescriptor.KeyDescriptors {
certData, err := base64.StdEncoding.DecodeString(strings.TrimSpace(kd.KeyInfo.X509Data.X509Certificate.Data))
if err != nil {
return nil, trace.Wrap(err)
}
cert, err := x509.ParseCertificate(certData)
if err != nil {
return nil, trace.Wrap(err, "failed to parse certificate in metadata")
}
certStore.Roots = append(certStore.Roots, cert)
}
o.Spec.Issuer = metadata.EntityID
o.Spec.SSO = metadata.IDPSSODescriptor.SingleSignOnService.Location
}
if o.Spec.Issuer == "" {
return nil, trace.BadParameter("no issuer or entityID set, either set issuer as a parameter or via entity_descriptor spec")
}
if o.Spec.SSO == "" {
return nil, trace.BadParameter("no SSO set either explicitly or via entity_descriptor spec")
}
if o.Spec.Cert != "" {
cert, err := utils.ParseCertificatePEM([]byte(o.Spec.Cert))
if err != nil {
return nil, trace.Wrap(err)
}
certStore.Roots = append(certStore.Roots, cert)
}
if len(certStore.Roots) == 0 {
return nil, trace.BadParameter(
"no identity provider certificate provided, either set certificate as a parameter or via entity_descriptor")
}
if o.Spec.SigningKeyPair == nil {
keyPEM, certPEM, err := utils.GenerateSelfSignedSigningCert(pkix.Name{
Organization: []string{"Teleport OSS"},
CommonName: "teleport.localhost.localdomain",
}, nil, 10*365*24*time.Hour)
if err != nil {
return nil, trace.Wrap(err)
}
o.Spec.SigningKeyPair = &SigningKeyPair{
PrivateKey: string(keyPEM),
Cert: string(certPEM),
}
}
keyStore, err := utils.ParseSigningKeyStorePEM(o.Spec.SigningKeyPair.PrivateKey, o.Spec.SigningKeyPair.Cert)
if err != nil {
return nil, trace.Wrap(err)
}
// make sure claim mappings have either roles or a role template
for _, v := range o.Spec.AttributesToRoles {
hasRoles := false
if len(v.Roles) > 0 {
hasRoles = true
}
hasRoleTemplate := false
if v.RoleTemplate != nil {
hasRoleTemplate = true
}
// we either need to have roles or role templates not both or neither
// ! ( hasRoles XOR hasRoleTemplate )
if hasRoles == hasRoleTemplate {
return nil, trace.BadParameter("need roles or role template (not both or none)")
}
}
log.Debugf("[SAML] SSO: %v", o.Spec.SSO)
log.Debugf("[SAML] Issuer: %v", o.Spec.Issuer)
log.Debugf("[SAML] ACS: %v", o.Spec.AssertionConsumerService)
sp := &saml2.SAMLServiceProvider{
IdentityProviderSSOURL: o.Spec.SSO,
IdentityProviderIssuer: o.Spec.Issuer,
ServiceProviderIssuer: o.Spec.ServiceProviderIssuer,
AssertionConsumerServiceURL: o.Spec.AssertionConsumerService,
SignAuthnRequests: true,
SignAuthnRequestsCanonicalizer: dsig.MakeC14N11Canonicalizer(),
AudienceURI: o.Spec.Audience,
IDPCertificateStore: &certStore,
SPKeyStore: keyStore,
Clock: dsig.NewFakeClock(clock),
NameIdFormat: "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified",
}
// adfs specific settings
if o.Spec.Provider == teleport.ADFS {
if sp.SignAuthnRequests {
// adfs does not support C14N11, we have to use the C14N10 canonicalizer
sp.SignAuthnRequestsCanonicalizer = dsig.MakeC14N10ExclusiveCanonicalizerWithPrefixList(dsig.DefaultPrefix)
// at a minimum we require password protected transport
sp.RequestedAuthnContext = &saml2.RequestedAuthnContext{
Comparison: "minimum",
Contexts: []string{"urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport"},
}
}
}
return sp, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/saml.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/saml.go#L792-L798 | go | train | // GetAttributeNames returns a list of claim names from the claim values | func GetAttributeNames(attributes map[string]types.Attribute) []string | // GetAttributeNames returns a list of claim names from the claim values
func GetAttributeNames(attributes map[string]types.Attribute) []string | {
var out []string
for _, attr := range attributes {
out = append(out, attr.Name)
}
return out
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/saml.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/saml.go#L853-L865 | go | train | // buildAssertionMap takes an saml2.AssertionInfo and builds a friendly map
// that can be used to access assertion/value pairs. If multiple values are
// returned for an assertion, they are joined into a string by ",". | func buildAssertionMap(assertionInfo saml2.AssertionInfo) map[string]string | // buildAssertionMap takes an saml2.AssertionInfo and builds a friendly map
// that can be used to access assertion/value pairs. If multiple values are
// returned for an assertion, they are joined into a string by ",".
func buildAssertionMap(assertionInfo saml2.AssertionInfo) map[string]string | {
assertionMap := make(map[string]string)
for _, assr := range assertionInfo.Values {
var vals []string
for _, v := range assr.Values {
vals = append(vals, v.Value)
}
assertionMap[assr.Name] = strings.Join(vals, ",")
}
return assertionMap
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/presence.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/presence.go#L159-L167 | go | train | // NewNamespace returns new namespace | func NewNamespace(name string) Namespace | // NewNamespace returns new namespace
func NewNamespace(name string) Namespace | {
return Namespace{
Kind: KindNamespace,
Version: V2,
Metadata: Metadata{
Name: name,
},
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/resource.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/resource.go#L254-L258 | go | train | // AddOptions adds marshal options and returns a new copy | func AddOptions(opts []MarshalOption, add ...MarshalOption) []MarshalOption | // AddOptions adds marshal options and returns a new copy
func AddOptions(opts []MarshalOption, add ...MarshalOption) []MarshalOption | {
out := make([]MarshalOption, len(opts), len(opts)+len(add))
copy(out, opts)
return append(opts, add...)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/resource.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/resource.go#L261-L266 | go | train | // WithResourceID assigns ID to the resource | func WithResourceID(id int64) MarshalOption | // WithResourceID assigns ID to the resource
func WithResourceID(id int64) MarshalOption | {
return func(c *MarshalConfig) error {
c.ID = id
return nil
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/resource.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/resource.go#L269-L274 | go | train | // WithExpires assigns expiry value | func WithExpires(expires time.Time) MarshalOption | // WithExpires assigns expiry value
func WithExpires(expires time.Time) MarshalOption | {
return func(c *MarshalConfig) error {
c.Expires = expires
return nil
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/resource.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/resource.go#L280-L290 | go | train | // WithVersion sets marshal version | func WithVersion(v string) MarshalOption | // WithVersion sets marshal version
func WithVersion(v string) MarshalOption | {
return func(c *MarshalConfig) error {
switch v {
case V1, V2:
c.Version = v
return nil
default:
return trace.BadParameter("version '%v' is not supported", v)
}
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/resource.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/resource.go#L389-L391 | go | train | // SetExpiry sets object expiry | func (h *ResourceHeader) SetExpiry(t time.Time) | // SetExpiry sets object expiry
func (h *ResourceHeader) SetExpiry(t time.Time) | {
h.Metadata.SetExpiry(t)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/resource.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/resource.go#L394-L396 | go | train | // SetTTL sets Expires header using current clock | func (h *ResourceHeader) SetTTL(clock clockwork.Clock, ttl time.Duration) | // SetTTL sets Expires header using current clock
func (h *ResourceHeader) SetTTL(clock clockwork.Clock, ttl time.Duration) | {
h.Metadata.SetTTL(clock, ttl)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/resource.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/resource.go#L419-L428 | go | train | // UnmarshalJSON unmarshals header and captures raw state | func (u *UnknownResource) UnmarshalJSON(raw []byte) error | // UnmarshalJSON unmarshals header and captures raw state
func (u *UnknownResource) UnmarshalJSON(raw []byte) error | {
var h ResourceHeader
if err := json.Unmarshal(raw, &h); err != nil {
return trace.Wrap(err)
}
u.Raw = make([]byte, len(raw))
u.ResourceHeader = h
copy(u.Raw, raw)
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/resource.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/resource.go#L489-L494 | go | train | // Expires returns object expiry setting. | func (m *Metadata) Expiry() time.Time | // Expires returns object expiry setting.
func (m *Metadata) Expiry() time.Time | {
if m.Expires == nil {
return time.Time{}
}
return *m.Expires
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/resource.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/resource.go#L497-L500 | go | train | // SetTTL sets Expires header using realtime clock | func (m *Metadata) SetTTL(clock clockwork.Clock, ttl time.Duration) | // SetTTL sets Expires header using realtime clock
func (m *Metadata) SetTTL(clock clockwork.Clock, ttl time.Duration) | {
expireTime := clock.Now().UTC().Add(ttl)
m.Expires = &expireTime
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/resource.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/resource.go#L503-L517 | go | train | // CheckAndSetDefaults checks validity of all parameters and sets defaults | func (m *Metadata) CheckAndSetDefaults() error | // CheckAndSetDefaults checks validity of all parameters and sets defaults
func (m *Metadata) CheckAndSetDefaults() error | {
if m.Name == "" {
return trace.BadParameter("missing parameter Name")
}
if m.Namespace == "" {
m.Namespace = defaults.Namespace
}
// adjust expires time to utc if it's set
if m.Expires != nil {
utils.UTC(m.Expires)
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/resource.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/resource.go#L520-L557 | go | train | // ParseShortcut parses resource shortcut | func ParseShortcut(in string) (string, error) | // ParseShortcut parses resource shortcut
func ParseShortcut(in string) (string, error) | {
if in == "" {
return "", trace.BadParameter("missing resource name")
}
switch strings.ToLower(in) {
case "role", "roles":
return KindRole, nil
case "namespaces", "ns":
return KindNamespace, nil
case "auth_servers", "auth":
return KindAuthServer, nil
case "proxies":
return KindProxy, nil
case "nodes", "node":
return KindNode, nil
case "oidc":
return KindOIDCConnector, nil
case "saml":
return KindSAMLConnector, nil
case "github":
return KindGithubConnector, nil
case "connectors", "connector":
return KindConnectors, nil
case "user", "users":
return KindUser, nil
case "cert_authorities", "cas":
return KindCertAuthority, nil
case "reverse_tunnels", "rts":
return KindReverseTunnel, nil
case "trusted_cluster", "tc", "cluster", "clusters":
return KindTrustedCluster, nil
case "cluster_authentication_preferences", "cap":
return KindClusterAuthPreference, nil
case "remote_cluster", "remote_clusters", "rc", "rcs":
return KindRemoteCluster, nil
}
return "", trace.BadParameter("unsupported resource: %v", in)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/resource.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/resource.go#L560-L580 | go | train | // ParseRef parses resource reference eg daemonsets/ds1 | func ParseRef(ref string) (*Ref, error) | // ParseRef parses resource reference eg daemonsets/ds1
func ParseRef(ref string) (*Ref, error) | {
if ref == "" {
return nil, trace.BadParameter("missing value")
}
parts := strings.FieldsFunc(ref, isDelimiter)
switch len(parts) {
case 1:
shortcut, err := ParseShortcut(parts[0])
if err != nil {
return nil, trace.Wrap(err)
}
return &Ref{Kind: shortcut}, nil
case 2:
shortcut, err := ParseShortcut(parts[0])
if err != nil {
return nil, trace.Wrap(err)
}
return &Ref{Kind: shortcut, Name: parts[1]}, nil
}
return nil, trace.BadParameter("failed to parse '%v'", ref)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/parse/parse.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/parse/parse.go#L33-L61 | go | train | // IsRoleVariable checks if the passed in string matches the variable pattern
// {{external.foo}} or {{internal.bar}}. If it does, it returns the variable
// prefix and the variable name. In the previous example this would be
// "external" or "internal" for the variable prefix and "foo" or "bar" for the
// variable name. If no variable pattern is found, trace.NotFound is returned. | func IsRoleVariable(variable string) (string, string, error) | // IsRoleVariable checks if the passed in string matches the variable pattern
// {{external.foo}} or {{internal.bar}}. If it does, it returns the variable
// prefix and the variable name. In the previous example this would be
// "external" or "internal" for the variable prefix and "foo" or "bar" for the
// variable name. If no variable pattern is found, trace.NotFound is returned.
func IsRoleVariable(variable string) (string, string, error) | {
// time whitespace around string if it exists
variable = strings.TrimSpace(variable)
// strip {{ and }} from the start and end of the variable
if !strings.HasPrefix(variable, "{{") || !strings.HasSuffix(variable, "}}") {
return "", "", trace.NotFound("no variable found: %v", variable)
}
variable = variable[2 : len(variable)-2]
// parse and get the ast of the expression
expr, err := parser.ParseExpr(variable)
if err != nil {
return "", "", trace.NotFound("no variable found: %v", variable)
}
// walk the ast tree and gather the variable parts
variableParts, err := walk(expr)
if err != nil {
return "", "", trace.NotFound("no variable found: %v", variable)
}
// the variable must have two parts the prefix and the variable name itself
if len(variableParts) != 2 {
return "", "", trace.NotFound("no variable found: %v", variable)
}
return variableParts[0], variableParts[1], nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/parse/parse.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/parse/parse.go#L64-L105 | go | train | // walk will walk the ast tree and gather all the variable parts into a slice and return it. | func walk(node ast.Node) ([]string, error) | // walk will walk the ast tree and gather all the variable parts into a slice and return it.
func walk(node ast.Node) ([]string, error) | {
var l []string
switch n := node.(type) {
case *ast.IndexExpr:
ret, err := walk(n.X)
if err != nil {
return nil, err
}
l = append(l, ret...)
ret, err = walk(n.Index)
if err != nil {
return nil, err
}
l = append(l, ret...)
case *ast.SelectorExpr:
ret, err := walk(n.X)
if err != nil {
return nil, err
}
l = append(l, ret...)
ret, err = walk(n.Sel)
if err != nil {
return nil, err
}
l = append(l, ret...)
case *ast.Ident:
return []string{n.Name}, nil
case *ast.BasicLit:
value, err := strconv.Unquote(n.Value)
if err != nil {
return nil, err
}
return []string{value}, nil
default:
return nil, trace.BadParameter("unknown node type: %T", n)
}
return l, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/linking.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/linking.go#L79-L121 | go | train | // ParseWebLinks partially implements RFC 8288 parsing, enough to support
// GitHub pagination links. See https://tools.ietf.org/html/rfc8288 for more
// details on Web Linking and https://github.com/google/go-github for the API
// client that this function was original extracted from.
//
// Link headers typically look like:
//
// Link: <https://api.github.com/user/teams?page=2>; rel="next",
// <https://api.github.com/user/teams?page=34>; rel="last" | func ParseWebLinks(response *http.Response) WebLinks | // ParseWebLinks partially implements RFC 8288 parsing, enough to support
// GitHub pagination links. See https://tools.ietf.org/html/rfc8288 for more
// details on Web Linking and https://github.com/google/go-github for the API
// client that this function was original extracted from.
//
// Link headers typically look like:
//
// Link: <https://api.github.com/user/teams?page=2>; rel="next",
// <https://api.github.com/user/teams?page=34>; rel="last"
func ParseWebLinks(response *http.Response) WebLinks | {
wls := WebLinks{}
if links, ok := response.Header["Link"]; ok && len(links) > 0 {
for _, lnk := range links {
for _, link := range strings.Split(lnk, ",") {
segments := strings.Split(strings.TrimSpace(link), ";")
// link must at least have href and rel
if len(segments) < 2 {
continue
}
// ensure href is properly formatted
if !strings.HasPrefix(segments[0], "<") || !strings.HasSuffix(segments[0], ">") {
continue
}
// try to pull out page parameter
link, err := url.Parse(segments[0][1 : len(segments[0])-1])
if err != nil {
continue
}
for _, segment := range segments[1:] {
switch strings.TrimSpace(segment) {
case `rel="next"`:
wls.NextPage = link.String()
case `rel="prev"`:
wls.PrevPage = link.String()
case `rel="first"`:
wls.FirstPage = link.String()
case `rel="last"`:
wls.LastPage = link.String()
}
}
}
}
}
return wls
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/events/auditlog.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/auditlog.go#L197-L230 | go | train | // CheckAndSetDefaults checks and sets defaults | func (a *AuditLogConfig) CheckAndSetDefaults() error | // CheckAndSetDefaults checks and sets defaults
func (a *AuditLogConfig) CheckAndSetDefaults() error | {
if a.DataDir == "" {
return trace.BadParameter("missing parameter DataDir")
}
if a.ServerID == "" {
return trace.BadParameter("missing parameter ServerID")
}
if a.Clock == nil {
a.Clock = clockwork.NewRealClock()
}
if a.UIDGenerator == nil {
a.UIDGenerator = utils.NewRealUID()
}
if a.RotationPeriod == 0 {
a.RotationPeriod = defaults.LogRotationPeriod
}
if a.SessionIdlePeriod == 0 {
a.SessionIdlePeriod = defaults.SessionIdlePeriod
}
if a.DirMask == nil {
mask := os.FileMode(teleport.DirMaskSharedGroup)
a.DirMask = &mask
}
if (a.GID != nil && a.UID == nil) || (a.UID != nil && a.GID == nil) {
return trace.BadParameter("if UID or GID is set, both should be specified")
}
if a.PlaybackRecycleTTL == 0 {
a.PlaybackRecycleTTL = defaults.PlaybackRecycleTTL
}
if a.Context == nil {
a.Context = context.Background()
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/events/auditlog.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/auditlog.go#L235-L300 | go | train | // Creates and returns a new Audit Log object whish will store its logfiles in
// a given directory. Session recording can be disabled by setting
// recordSessions to false. | func NewAuditLog(cfg AuditLogConfig) (*AuditLog, error) | // Creates and returns a new Audit Log object whish will store its logfiles in
// a given directory. Session recording can be disabled by setting
// recordSessions to false.
func NewAuditLog(cfg AuditLogConfig) (*AuditLog, error) | {
if err := cfg.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
ctx, cancel := context.WithCancel(cfg.Context)
al := &AuditLog{
playbackDir: filepath.Join(cfg.DataDir, PlaybackDir, SessionLogsDir, defaults.Namespace),
AuditLogConfig: cfg,
Entry: log.WithFields(log.Fields{
trace.Component: teleport.ComponentAuditLog,
}),
activeDownloads: make(map[string]context.Context),
ctx: ctx,
cancel: cancel,
}
// create a directory for audit logs, audit log does not create
// session logs before migrations are run in case if the directory
// has to be moved
auditDir := filepath.Join(cfg.DataDir, cfg.ServerID)
if err := os.MkdirAll(auditDir, *cfg.DirMask); err != nil {
return nil, trace.ConvertSystemError(err)
}
// create a directory for session logs:
sessionDir := filepath.Join(cfg.DataDir, cfg.ServerID, SessionLogsDir, defaults.Namespace)
if err := os.MkdirAll(sessionDir, *cfg.DirMask); err != nil {
return nil, trace.ConvertSystemError(err)
}
// create a directory for uncompressed playbacks
if err := os.MkdirAll(filepath.Join(al.playbackDir), *cfg.DirMask); err != nil {
return nil, trace.ConvertSystemError(err)
}
if cfg.UID != nil && cfg.GID != nil {
err := os.Chown(cfg.DataDir, *cfg.UID, *cfg.GID)
if err != nil {
return nil, trace.ConvertSystemError(err)
}
err = os.Chown(sessionDir, *cfg.UID, *cfg.GID)
if err != nil {
return nil, trace.ConvertSystemError(err)
}
err = os.Chown(al.playbackDir, *cfg.UID, *cfg.GID)
if err != nil {
return nil, trace.ConvertSystemError(err)
}
}
if al.ExternalLog == nil {
var err error
al.localLog, err = NewFileLog(FileLogConfig{
RotationPeriod: al.RotationPeriod,
Dir: auditDir,
SymlinkDir: cfg.DataDir,
Clock: al.Clock,
UIDGenerator: al.UIDGenerator,
SearchDirs: al.auditDirs,
})
if err != nil {
return nil, trace.Wrap(err)
}
}
go al.periodicCleanupPlaybacks()
go al.periodicSpaceMonitor()
return al, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/events/auditlog.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/auditlog.go#L317-L328 | go | train | // CheckAndSetDefaults checks and sets default parameters | func (l *SessionRecording) CheckAndSetDefaults() error | // CheckAndSetDefaults checks and sets default parameters
func (l *SessionRecording) CheckAndSetDefaults() error | {
if l.Recording == nil {
return trace.BadParameter("missing parameter Recording")
}
if l.SessionID.IsZero() {
return trace.BadParameter("missing parameter session ID")
}
if l.Namespace == "" {
l.Namespace = defaults.Namespace
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/events/auditlog.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/auditlog.go#L332-L354 | go | train | // UploadSessionRecording uploads session recording to the audit server
// TODO(klizhentas) add protection against overwrites from different nodes | func (l *AuditLog) UploadSessionRecording(r SessionRecording) error | // UploadSessionRecording uploads session recording to the audit server
// TODO(klizhentas) add protection against overwrites from different nodes
func (l *AuditLog) UploadSessionRecording(r SessionRecording) error | {
if err := r.CheckAndSetDefaults(); err != nil {
return trace.Wrap(err)
}
if l.UploadHandler == nil {
// unpack the tarball locally to sessions directory
err := utils.Extract(r.Recording, filepath.Join(l.DataDir, l.ServerID, SessionLogsDir, r.Namespace))
return trace.Wrap(err)
}
// use upload handler
start := time.Now()
url, err := l.UploadHandler.Upload(context.TODO(), r.SessionID, r.Recording)
if err != nil {
l.WithFields(log.Fields{"duration": time.Now().Sub(start), "session-id": r.SessionID}).Warningf("Session upload failed: %v", trace.DebugReport(err))
return trace.Wrap(err)
}
l.WithFields(log.Fields{"duration": time.Now().Sub(start), "session-id": r.SessionID}).Debugf("Session upload completed.")
return l.EmitAuditEvent(SessionUpload, EventFields{
SessionEventID: string(r.SessionID),
URL: url,
EventIndex: math.MaxInt32,
})
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/events/auditlog.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/auditlog.go#L469-L475 | go | train | // chunkFileNames returns file names of all session chunk files | func (idx *sessionIndex) chunkFileNames() []string | // chunkFileNames returns file names of all session chunk files
func (idx *sessionIndex) chunkFileNames() []string | {
fileNames := make([]string, len(idx.chunks))
for i := 0; i < len(idx.chunks); i++ {
fileNames[i] = idx.chunksFileName(i)
}
return fileNames
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/events/auditlog.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/auditlog.go#L560-L575 | go | train | // createOrGetDownload creates a new download sync entry for a given session,
// if there is no active download in progress, or returns an existing one.
// if the new context has been created, cancel function is returned as a
// second argument. Caller should call this function to signal that download has been
// completed or failed. | func (l *AuditLog) createOrGetDownload(path string) (context.Context, context.CancelFunc) | // createOrGetDownload creates a new download sync entry for a given session,
// if there is no active download in progress, or returns an existing one.
// if the new context has been created, cancel function is returned as a
// second argument. Caller should call this function to signal that download has been
// completed or failed.
func (l *AuditLog) createOrGetDownload(path string) (context.Context, context.CancelFunc) | {
l.Lock()
defer l.Unlock()
ctx, ok := l.activeDownloads[path]
if ok {
return ctx, nil
}
ctx, cancel := context.WithCancel(context.TODO())
l.activeDownloads[path] = ctx
return ctx, func() {
cancel()
l.Lock()
defer l.Unlock()
delete(l.activeDownloads, path)
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/events/auditlog.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/auditlog.go#L646-L668 | go | train | // GetSessionChunk returns a reader which console and web clients request
// to receive a live stream of a given session. The reader allows access to a
// session stream range from offsetBytes to offsetBytes+maxBytes | func (l *AuditLog) GetSessionChunk(namespace string, sid session.ID, offsetBytes, maxBytes int) ([]byte, error) | // GetSessionChunk returns a reader which console and web clients request
// to receive a live stream of a given session. The reader allows access to a
// session stream range from offsetBytes to offsetBytes+maxBytes
func (l *AuditLog) GetSessionChunk(namespace string, sid session.ID, offsetBytes, maxBytes int) ([]byte, error) | {
if l.UploadHandler != nil {
if err := l.downloadSession(namespace, sid); err != nil {
return nil, trace.Wrap(err)
}
}
var data []byte
for {
out, err := l.getSessionChunk(namespace, sid, offsetBytes, maxBytes)
if err != nil {
if err == io.EOF {
return data, nil
}
return nil, trace.Wrap(err)
}
data = append(data, out...)
if len(data) == maxBytes || len(out) == 0 {
return data, nil
}
maxBytes = maxBytes - len(out)
offsetBytes = offsetBytes + len(out)
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/events/auditlog.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/auditlog.go#L797-L841 | go | train | // Returns all events that happen during a session sorted by time
// (oldest first).
//
// Can be filtered by 'after' (cursor value to return events newer than)
//
// This function is usually used in conjunction with GetSessionReader to
// replay recorded session streams. | func (l *AuditLog) GetSessionEvents(namespace string, sid session.ID, afterN int, includePrintEvents bool) ([]EventFields, error) | // Returns all events that happen during a session sorted by time
// (oldest first).
//
// Can be filtered by 'after' (cursor value to return events newer than)
//
// This function is usually used in conjunction with GetSessionReader to
// replay recorded session streams.
func (l *AuditLog) GetSessionEvents(namespace string, sid session.ID, afterN int, includePrintEvents bool) ([]EventFields, error) | {
l.WithFields(log.Fields{"sid": string(sid), "afterN": afterN, "printEvents": includePrintEvents}).Debugf("GetSessionEvents.")
if namespace == "" {
return nil, trace.BadParameter("missing parameter namespace")
}
// Print events are stored in the context of the downloaded session
// so pull them
if !includePrintEvents && l.ExternalLog != nil {
events, err := l.ExternalLog.GetSessionEvents(namespace, sid, afterN, includePrintEvents)
// some loggers (e.g. FileLog) do not support retrieving session only print events,
// in this case rely on local fallback to download the session,
// unpack it and use local search
if !trace.IsNotImplemented(err) {
return events, err
}
}
// If code has to fetch print events (for playback) it has to download
// the playback from external storage first
if l.UploadHandler != nil {
if err := l.downloadSession(namespace, sid); err != nil {
return nil, trace.Wrap(err)
}
}
idx, err := l.readSessionIndex(namespace, sid)
if err != nil {
return nil, trace.Wrap(err)
}
fileIndex, err := idx.eventsFile(afterN)
if err != nil {
return nil, trace.Wrap(err)
}
events := make([]EventFields, 0, 256)
for i := fileIndex; i < len(idx.events); i++ {
skip := 0
if i == fileIndex {
skip = afterN
}
out, err := l.fetchSessionEvents(idx.eventsFileName(i), skip)
if err != nil {
return nil, trace.Wrap(err)
}
events = append(events, out...)
}
return events, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/events/auditlog.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/auditlog.go#L879-L898 | go | train | // EmitAuditEvent adds a new event to the log. If emitting fails, a Prometheus
// counter is incremented. | func (l *AuditLog) EmitAuditEvent(event Event, fields EventFields) error | // EmitAuditEvent adds a new event to the log. If emitting fails, a Prometheus
// counter is incremented.
func (l *AuditLog) EmitAuditEvent(event Event, fields EventFields) error | {
// If an external logger has been set, use it as the emitter, otherwise
// fallback to the local disk based emitter.
var emitAuditEvent func(event Event, fields EventFields) error
if l.ExternalLog != nil {
emitAuditEvent = l.ExternalLog.EmitAuditEvent
} else {
emitAuditEvent = l.localLog.EmitAuditEvent
}
// Emit the event. If it fails for any reason a Prometheus counter is
// incremented.
err := emitAuditEvent(event, fields)
if err != nil {
auditFailedEmit.Inc()
return trace.Wrap(err)
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/events/auditlog.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/auditlog.go#L901-L911 | go | train | // emitEvent emits event for test purposes | func (l *AuditLog) emitEvent(e AuditLogEvent) | // emitEvent emits event for test purposes
func (l *AuditLog) emitEvent(e AuditLogEvent) | {
if l.EventsC == nil {
return
}
select {
case l.EventsC <- &e:
return
default:
l.Warningf("Blocked on the events channel.")
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/events/auditlog.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/auditlog.go#L914-L925 | go | train | // auditDirs returns directories used for audit log storage | func (l *AuditLog) auditDirs() ([]string, error) | // auditDirs returns directories used for audit log storage
func (l *AuditLog) auditDirs() ([]string, error) | {
authServers, err := l.getAuthServers()
if err != nil {
return nil, trace.Wrap(err)
}
var out []string
for _, serverID := range authServers {
out = append(out, filepath.Join(l.DataDir, serverID))
}
return out, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/events/auditlog.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/auditlog.go#L929-L941 | go | train | // SearchEvents finds events. Results show up sorted by date (newest first),
// limit is used when set to value > 0 | func (l *AuditLog) SearchEvents(fromUTC, toUTC time.Time, query string, limit int) ([]EventFields, error) | // SearchEvents finds events. Results show up sorted by date (newest first),
// limit is used when set to value > 0
func (l *AuditLog) SearchEvents(fromUTC, toUTC time.Time, query string, limit int) ([]EventFields, error) | {
l.Debugf("SearchEvents(%v, %v, query=%v, limit=%v)", fromUTC, toUTC, query, limit)
if limit <= 0 {
limit = defaults.EventsIterationLimit
}
if limit > defaults.EventsMaxIterationLimit {
return nil, trace.BadParameter("limit %v exceeds max iteration limit %v", limit, defaults.MaxIterationLimit)
}
if l.ExternalLog != nil {
return l.ExternalLog.SearchEvents(fromUTC, toUTC, query, limit)
}
return l.localLog.SearchEvents(fromUTC, toUTC, query, limit)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/events/auditlog.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/auditlog.go#L944-L951 | go | train | // SearchSessionEvents searches for session related events. Used to find completed sessions. | func (l *AuditLog) SearchSessionEvents(fromUTC, toUTC time.Time, limit int) ([]EventFields, error) | // SearchSessionEvents searches for session related events. Used to find completed sessions.
func (l *AuditLog) SearchSessionEvents(fromUTC, toUTC time.Time, limit int) ([]EventFields, error) | {
l.Debugf("SearchSessionEvents(%v, %v, %v)", fromUTC, toUTC, limit)
if l.ExternalLog != nil {
return l.ExternalLog.SearchSessionEvents(fromUTC, toUTC, limit)
}
return l.localLog.SearchSessionEvents(fromUTC, toUTC, limit)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/events/auditlog.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/auditlog.go#L955-L972 | go | train | // Closes the audit log, which inluces closing all file handles and releasing
// all session loggers | func (l *AuditLog) Close() error | // Closes the audit log, which inluces closing all file handles and releasing
// all session loggers
func (l *AuditLog) Close() error | {
if l.ExternalLog != nil {
if err := l.ExternalLog.Close(); err != nil {
log.Warningf("Close failure: %v", err)
}
}
l.cancel()
l.Lock()
defer l.Unlock()
if l.localLog != nil {
if err := l.localLog.Close(); err != nil {
log.Warningf("Close failure: %v", err)
}
l.localLog = nil
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/events/auditlog.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/auditlog.go#L992-L1019 | go | train | // periodicSpaceMonitor run forever monitoring how much disk space has been
// used on disk. Values are emitted to a Prometheus gauge. | func (l *AuditLog) periodicSpaceMonitor() | // periodicSpaceMonitor run forever monitoring how much disk space has been
// used on disk. Values are emitted to a Prometheus gauge.
func (l *AuditLog) periodicSpaceMonitor() | {
ticker := time.NewTicker(defaults.DiskAlertInterval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
// Find out what percentage of disk space is used. If the syscall fails,
// emit that to prometheus as well.
usedPercent, err := percentUsed(l.DataDir)
if err != nil {
auditFailedDisk.Inc()
log.Warnf("Disk space monitoring failed: %v.", err)
continue
}
// Update prometheus gauge with the percentage disk space used.
auditDiskUsed.Set(usedPercent)
// If used percentage goes above the alerting level, write to logs as well.
if usedPercent > float64(defaults.DiskAlertThreshold) {
log.Warnf("Free disk space for audit log is running low, %v%% of disk used.", usedPercent)
}
case <-l.ctx.Done():
return
}
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/events/auditlog.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/auditlog.go#L1024-L1032 | go | train | // percentUsed returns percentage of disk space used. The percentage of disk
// space used is calculated from (total blocks - free blocks)/total blocks.
// The value is rounded to the nearest whole integer. | func percentUsed(path string) (float64, error) | // percentUsed returns percentage of disk space used. The percentage of disk
// space used is calculated from (total blocks - free blocks)/total blocks.
// The value is rounded to the nearest whole integer.
func percentUsed(path string) (float64, error) | {
var stat syscall.Statfs_t
err := syscall.Statfs(path, &stat)
if err != nil {
return 0, trace.Wrap(err)
}
ratio := float64(stat.Blocks-stat.Bfree) / float64(stat.Blocks)
return math.Round(ratio * 100), nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/legacy/dir/impl.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L77-L111 | go | train | // New creates a new instance of a directory based backend that implements
// backend.Backend. | func New(params legacy.Params) (*Backend, error) | // New creates a new instance of a directory based backend that implements
// backend.Backend.
func New(params legacy.Params) (*Backend, error) | {
rootDir := params.GetString("path")
if rootDir == "" {
rootDir = params.GetString("data_dir")
}
if rootDir == "" {
return nil, trace.BadParameter("filesystem backend: 'path' is not set")
}
// Ensure that the path to the root directory exists.
err := os.MkdirAll(rootDir, defaultDirMode)
if err != nil {
return nil, trace.ConvertSystemError(err)
}
bk := &Backend{
InternalClock: clockwork.NewRealClock(),
rootDir: rootDir,
log: logrus.WithFields(logrus.Fields{
trace.Component: "backend:dir",
trace.ComponentFields: logrus.Fields{
"dir": rootDir,
},
}),
}
// DELETE IN: 2.8.0
// Migrate data to new flat keyspace backend.
err = migrate(rootDir, bk)
if err != nil {
return nil, trace.Wrap(err)
}
return bk, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/legacy/dir/impl.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L119-L133 | go | train | // GetKeys returns a list of keys for a given bucket. | func (bk *Backend) GetKeys(bucket []string) ([]string, error) | // GetKeys returns a list of keys for a given bucket.
func (bk *Backend) GetKeys(bucket []string) ([]string, error) | {
// Get all the key/value pairs for this bucket.
items, err := bk.GetItems(bucket)
if err != nil {
return nil, trace.Wrap(err)
}
// Return only the keys, the keys are already sorted by GetItems.
keys := make([]string, len(items))
for i, e := range items {
keys[i] = e.Key
}
return keys, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/legacy/dir/impl.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L136-L195 | go | train | // Export exports all items from the backend in new backend Items | func (bk *Backend) Export() ([]backend.Item, error) | // Export exports all items from the backend in new backend Items
func (bk *Backend) Export() ([]backend.Item, error) | {
var out []backend.Item
// Get a list of all buckets in the backend.
files, err := ioutil.ReadDir(path.Join(bk.rootDir))
if err != nil {
return nil, trace.ConvertSystemError(err)
}
// Loop over all buckets in the backend.
for _, fi := range files {
// skip sqlite database file - (in general sense,
// dir backend lacked ability to skip files that
// are present in the directory, so this is a necessary
// evil that is going away with dir backend)
if filepath.Base(fi.Name()) == "sqlite.db" {
continue
}
pathToBucket := bk.pathToBucket(fi.Name())
bucketParts, err := decodeBucket(filepath.Base(fi.Name()))
if err != nil {
return nil, trace.Wrap(err)
}
// Open the bucket to work on the items.
b, err := bk.openBucket(pathToBucket, os.O_RDWR)
if err != nil {
return nil, trace.Wrap(err)
}
defer b.Close()
// Loop over all keys, flatten them, and return key and value to caller.
for k, v := range b.items {
// If the bucket item is expired, update the bucket, and don't include
// it in the output.
if bk.isExpired(v) {
b.deleteItem(k)
continue
}
flatKey := make([]string, len(bucketParts))
copy(flatKey, bucketParts)
flatKey = append(flatKey, k)
out = append(out, backend.Item{
Key: backend.Key(flatKey...),
Value: v.Value,
Expires: v.ExpiryTime,
})
}
}
// Sort items and remove any duplicates.
sort.Slice(out, func(i, j int) bool {
return bytes.Compare(out[i].Key, out[j].Key) < 0
})
out = removeBackendDuplicates(out)
return out, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/legacy/dir/impl.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L198-L268 | go | train | // GetItems returns all items (key/value pairs) in a given bucket. | func (bk *Backend) GetItems(bucket []string, opts ...legacy.OpOption) ([]legacy.Item, error) | // GetItems returns all items (key/value pairs) in a given bucket.
func (bk *Backend) GetItems(bucket []string, opts ...legacy.OpOption) ([]legacy.Item, error) | {
var out []legacy.Item
// Get a list of all buckets in the backend.
files, err := ioutil.ReadDir(path.Join(bk.rootDir))
if err != nil {
return nil, trace.ConvertSystemError(err)
}
// Loop over all buckets in the backend.
for _, fi := range files {
pathToBucket := bk.pathToBucket(fi.Name())
bucketPrefix := bk.flatten(bucket)
// Skip over any buckets without a matching prefix.
if !strings.HasPrefix(pathToBucket, bucketPrefix) {
continue
}
// Open the bucket to work on the items.
b, err := bk.openBucket(pathToBucket, os.O_RDWR)
if err != nil {
return nil, trace.Wrap(err)
}
defer b.Close()
// Loop over all keys, flatten them, and return key and value to caller.
for k, v := range b.items {
var key string
// If bucket path on disk and the requested bucket were an exact match,
// return the key as-is.
//
// However, if this was a partial match, for example pathToBucket is
// "/roles/admin/params" but the bucketPrefix is "/roles" then extract
// the first suffix (in this case "admin") and use this as the key. This
// is consistent with our DynamoDB implementation.
if pathToBucket == bucketPrefix {
key = k
} else {
key, err = suffix(pathToBucket, bucketPrefix)
if err != nil {
return nil, trace.Wrap(err)
}
}
// If the bucket item is expired, update the bucket, and don't include
// it in the output.
if bk.isExpired(v) {
b.deleteItem(k)
continue
}
fullPath := filepath.Join(filepath.Base(pathToBucket), k)
out = append(out, legacy.Item{
FullPath: fullPath,
Key: key,
Value: v.Value,
})
}
}
// Sort items and remove any duplicates.
sort.Slice(out, func(i, j int) bool {
return out[i].Key < out[j].Key
})
out = removeDuplicates(out)
return out, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/legacy/dir/impl.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L272-L290 | go | train | // CreateVal creates a key/value pair with the given TTL in the bucket. If
// the key already exists in the bucket, trace.AlreadyExists is returned. | func (bk *Backend) CreateVal(bucket []string, key string, val []byte, ttl time.Duration) error | // CreateVal creates a key/value pair with the given TTL in the bucket. If
// the key already exists in the bucket, trace.AlreadyExists is returned.
func (bk *Backend) CreateVal(bucket []string, key string, val []byte, ttl time.Duration) error | {
// Open the bucket to work on the items.
b, err := bk.openBucket(bk.flatten(bucket), os.O_CREATE|os.O_RDWR)
if err != nil {
return trace.Wrap(err)
}
defer b.Close()
// If the key exists and is not expired, return trace.AlreadyExists.
item, ok := b.getItem(key)
if ok && !bk.isExpired(item) {
return trace.AlreadyExists("key already exists")
}
// Otherwise, update the item in the bucket.
b.updateItem(key, val, ttl)
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/legacy/dir/impl.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L294-L306 | go | train | // UpsertVal inserts (or updates if it already exists) the value for a key
// with the given TTL. | func (bk *Backend) UpsertVal(bucket []string, key string, val []byte, ttl time.Duration) error | // UpsertVal inserts (or updates if it already exists) the value for a key
// with the given TTL.
func (bk *Backend) UpsertVal(bucket []string, key string, val []byte, ttl time.Duration) error | {
// Open the bucket to work on the items.
b, err := bk.openBucket(bk.flatten(bucket), os.O_CREATE|os.O_RDWR)
if err != nil {
return trace.Wrap(err)
}
defer b.Close()
// Update the item in the bucket.
b.updateItem(key, val, ttl)
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/legacy/dir/impl.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L310-L324 | go | train | // UpsertItems inserts (or updates if it already exists) all passed in
// legacy.Items with the given TTL. | func (bk *Backend) UpsertItems(bucket []string, newItems []legacy.Item) error | // UpsertItems inserts (or updates if it already exists) all passed in
// legacy.Items with the given TTL.
func (bk *Backend) UpsertItems(bucket []string, newItems []legacy.Item) error | {
// Open the bucket to work on the items.
b, err := bk.openBucket(bk.flatten(bucket), os.O_CREATE|os.O_RDWR)
if err != nil {
return trace.Wrap(err)
}
defer b.Close()
// Update items in bucket.
for _, e := range newItems {
b.updateItem(e.Key, e.Value, e.TTL)
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/legacy/dir/impl.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L327-L374 | go | train | // GetVal return a value for a given key in the bucket | func (bk *Backend) GetVal(bucket []string, key string) ([]byte, error) | // GetVal return a value for a given key in the bucket
func (bk *Backend) GetVal(bucket []string, key string) ([]byte, error) | {
// Open the bucket to work on the items.
b, err := bk.openBucket(bk.flatten(bucket), os.O_RDWR)
if err != nil {
// GetVal on a bucket needs to return trace.BadParameter. If opening the
// bucket failed a partial match up to a bucket may still exist. To support
// returning trace.BadParameter in this situation, loop over all keys in the
// backend and see if any match the prefix. If any match the prefix return
// trace.BadParameter, otherwise return the original error. This is
// consistent with our DynamoDB implementation.
files, er := ioutil.ReadDir(path.Join(bk.rootDir))
if er != nil {
return nil, trace.ConvertSystemError(er)
}
var matched int
for _, fi := range files {
pathToBucket := bk.pathToBucket(fi.Name())
fullBucket := append(bucket, key)
bucketPrefix := bk.flatten(fullBucket)
// Prefix matched, for example if pathToBucket is "/foo/bar/baz" and
// bucketPrefix is "/foo/bar".
if strings.HasPrefix(pathToBucket, bucketPrefix) {
matched = matched + 1
}
}
if matched > 0 {
return nil, trace.BadParameter("%v is not a valid key", key)
}
return nil, trace.ConvertSystemError(err)
}
defer b.Close()
// If the key does not exist, return trace.NotFound right away.
item, ok := b.getItem(key)
if !ok {
return nil, trace.NotFound("key %q is not found", key)
}
// If the key is expired, remove it from the bucket and write it out and exit.
if bk.isExpired(item) {
b.deleteItem(key)
return nil, trace.NotFound("key %q is not found", key)
}
return item.Value, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/legacy/dir/impl.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L377-L406 | go | train | // CompareAndSwapVal compares and swap values in atomic operation | func (bk *Backend) CompareAndSwapVal(bucket []string, key string, val []byte, prevVal []byte, ttl time.Duration) error | // CompareAndSwapVal compares and swap values in atomic operation
func (bk *Backend) CompareAndSwapVal(bucket []string, key string, val []byte, prevVal []byte, ttl time.Duration) error | {
// Open the bucket to work on the items.
b, err := bk.openBucket(bk.flatten(bucket), os.O_CREATE|os.O_RDWR)
if err != nil {
er := trace.ConvertSystemError(err)
if trace.IsNotFound(er) {
return trace.CompareFailed("%v/%v did not match expected value", bucket, key)
}
return trace.Wrap(er)
}
defer b.Close()
// Read in existing key. If it does not exist, is expired, or does not
// match, return trace.CompareFailed.
oldItem, ok := b.getItem(key)
if !ok {
return trace.CompareFailed("%v/%v did not match expected value", bucket, key)
}
if bk.isExpired(oldItem) {
return trace.CompareFailed("%v/%v did not match expected value", bucket, key)
}
if bytes.Compare(oldItem.Value, prevVal) != 0 {
return trace.CompareFailed("%v/%v did not match expected value", bucket, key)
}
// The compare was successful, update the item.
b.updateItem(key, val, ttl)
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/legacy/dir/impl.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L409-L427 | go | train | // DeleteKey deletes a key in a bucket. | func (bk *Backend) DeleteKey(bucket []string, key string) error | // DeleteKey deletes a key in a bucket.
func (bk *Backend) DeleteKey(bucket []string, key string) error | {
// Open the bucket to work on the items.
b, err := bk.openBucket(bk.flatten(bucket), os.O_RDWR)
if err != nil {
return trace.Wrap(err)
}
defer b.Close()
// If the key doesn't exist, return trace.NotFound.
_, ok := b.getItem(key)
if !ok {
return trace.NotFound("key %v not found", key)
}
// Otherwise, delete key.
b.deleteItem(key)
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/legacy/dir/impl.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L430-L439 | go | train | // DeleteBucket deletes the bucket by a given path. | func (bk *Backend) DeleteBucket(parent []string, bucket string) error | // DeleteBucket deletes the bucket by a given path.
func (bk *Backend) DeleteBucket(parent []string, bucket string) error | {
fullBucket := append(parent, bucket)
err := os.Remove(bk.flatten(fullBucket))
if err != nil {
return trace.ConvertSystemError(err)
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/legacy/dir/impl.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L442-L467 | go | train | // AcquireLock grabs a lock that will be released automatically in TTL. | func (bk *Backend) AcquireLock(token string, ttl time.Duration) (err error) | // AcquireLock grabs a lock that will be released automatically in TTL.
func (bk *Backend) AcquireLock(token string, ttl time.Duration) (err error) | {
bk.log.Debugf("AcquireLock(%s)", token)
if err = legacy.ValidateLockTTL(ttl); err != nil {
return trace.Wrap(err)
}
bucket := []string{locksBucket}
for {
// GetVal will clear TTL on a lock
bk.GetVal(bucket, token)
// CreateVal is atomic:
err = bk.CreateVal(bucket, token, []byte{1}, ttl)
if err == nil {
break // success
}
if trace.IsAlreadyExists(err) { // locked? wait and repeat:
bk.Clock().Sleep(250 * time.Millisecond)
continue
}
return trace.ConvertSystemError(err)
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/legacy/dir/impl.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L470-L479 | go | train | // ReleaseLock forces lock release before TTL. | func (bk *Backend) ReleaseLock(token string) (err error) | // ReleaseLock forces lock release before TTL.
func (bk *Backend) ReleaseLock(token string) (err error) | {
bk.log.Debugf("ReleaseLock(%s)", token)
if err = bk.DeleteKey([]string{locksBucket}, token); err != nil {
if !os.IsNotExist(err) {
return trace.ConvertSystemError(err)
}
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/legacy/dir/impl.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L483-L485 | go | train | // pathToBucket prepends the root directory to the bucket returning the full
// path to the bucket on the filesystem. | func (bk *Backend) pathToBucket(bucket string) string | // pathToBucket prepends the root directory to the bucket returning the full
// path to the bucket on the filesystem.
func (bk *Backend) pathToBucket(bucket string) string | {
return filepath.Join(bk.rootDir, bucket)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/legacy/dir/impl.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L488-L494 | go | train | // decodeBucket decodes bucket into parts of path | func decodeBucket(bucket string) ([]string, error) | // decodeBucket decodes bucket into parts of path
func decodeBucket(bucket string) ([]string, error) | {
decoded, err := url.QueryUnescape(bucket)
if err != nil {
return nil, trace.Wrap(err)
}
return filepath.SplitList(decoded), nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/legacy/dir/impl.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L498-L506 | go | train | // flatten takes a bucket and flattens it (URL encodes) and prepends the root
// directory returning the full path to the bucket on the filesystem. | func (bk *Backend) flatten(bucket []string) string | // flatten takes a bucket and flattens it (URL encodes) and prepends the root
// directory returning the full path to the bucket on the filesystem.
func (bk *Backend) flatten(bucket []string) string | {
// Convert ["foo", "bar"] to "foo/bar"
raw := filepath.Join(bucket...)
// URL encode bucket from "foo/bar" to "foo%2Fbar".
flat := url.QueryEscape(raw)
return filepath.Join(bk.rootDir, flat)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/legacy/dir/impl.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L509-L514 | go | train | // isExpired checks if the bucket item is expired or not. | func (bk *Backend) isExpired(bv bucketItem) bool | // isExpired checks if the bucket item is expired or not.
func (bk *Backend) isExpired(bv bucketItem) bool | {
if bv.ExpiryTime.IsZero() {
return false
}
return bk.Clock().Now().After(bv.ExpiryTime)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/legacy/dir/impl.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L543-L566 | go | train | // openBucket will open a file, lock it, and then read in all the items in
// the bucket. | func (bk *Backend) openBucket(prefix string, openFlag int) (*bucket, error) | // openBucket will open a file, lock it, and then read in all the items in
// the bucket.
func (bk *Backend) openBucket(prefix string, openFlag int) (*bucket, error) | {
// Open bucket with requested flags.
file, err := os.OpenFile(prefix, openFlag, defaultFileMode)
if err != nil {
return nil, trace.ConvertSystemError(err)
}
// Lock the bucket so no one else can access it.
if err := utils.FSWriteLock(file); err != nil {
return nil, trace.Wrap(err)
}
// Read in all items from the bucket.
items, err := readBucket(file)
if err != nil {
return nil, trace.Wrap(err)
}
return &bucket{
backend: bk,
items: items,
file: file,
}, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/legacy/dir/impl.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L591-L613 | go | train | // Close will write out items (if requested), unlock file, and close it. | func (b *bucket) Close() error | // Close will write out items (if requested), unlock file, and close it.
func (b *bucket) Close() error | {
var err error
// If the items were updated, write them out to disk.
if b.itemsUpdated {
err = writeBucket(b.file, b.items)
if err != nil {
b.backend.log.Warnf("Unable to update keys in %v: %v.", b.file.Name(), err)
}
}
err = utils.FSUnlock(b.file)
if err != nil {
b.backend.log.Warnf("Unable to unlock file: %v.", err)
}
err = b.file.Close()
if err != nil {
b.backend.log.Warnf("Unable to close file: %v.", err)
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/legacy/dir/impl.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L617-L639 | go | train | // readBucket will read in the bucket and return a map of keys. The second return
// value returns true to false to indicate if the file was empty or not. | func readBucket(f *os.File) (map[string]bucketItem, error) | // readBucket will read in the bucket and return a map of keys. The second return
// value returns true to false to indicate if the file was empty or not.
func readBucket(f *os.File) (map[string]bucketItem, error) | {
// If the file is empty, return an empty bucket.
ok, err := isEmpty(f)
if err != nil {
return nil, trace.Wrap(err)
}
if ok {
return map[string]bucketItem{}, nil
}
// The file is not empty, read it into a map.
var items map[string]bucketItem
bytes, err := ioutil.ReadAll(f)
if err != nil {
return nil, trace.ConvertSystemError(err)
}
err = utils.FastUnmarshal(bytes, &items)
if err != nil {
return nil, trace.Wrap(err)
}
return items, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/legacy/dir/impl.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L642-L664 | go | train | // writeBucket will truncate the file and write out the items to the file f. | func writeBucket(f *os.File, items map[string]bucketItem) error | // writeBucket will truncate the file and write out the items to the file f.
func writeBucket(f *os.File, items map[string]bucketItem) error | {
// Marshal items to disk format.
bytes, err := json.Marshal(items)
if err != nil {
return trace.Wrap(err)
}
// Truncate the file.
if _, err := f.Seek(0, 0); err != nil {
return trace.ConvertSystemError(err)
}
if err := f.Truncate(0); err != nil {
return trace.ConvertSystemError(err)
}
// Write out the contents to disk.
n, err := f.Write(bytes)
if err == nil && n < len(bytes) {
return trace.Wrap(io.ErrShortWrite)
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/legacy/dir/impl.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L667-L678 | go | train | // isEmpty checks if the file is empty or not. | func isEmpty(f *os.File) (bool, error) | // isEmpty checks if the file is empty or not.
func isEmpty(f *os.File) (bool, error) | {
fi, err := f.Stat()
if err != nil {
return false, trace.Wrap(err)
}
if fi.Size() > 0 {
return false, nil
}
return true, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/legacy/dir/impl.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L683-L704 | go | train | // suffix returns the first bucket after where pathToBucket and bucketPrefix
// differ. For example, if pathToBucket is "/roles/admin/params" and
// bucketPrefix is "/roles", then "admin" is returned. | func suffix(pathToBucket string, bucketPrefix string) (string, error) | // suffix returns the first bucket after where pathToBucket and bucketPrefix
// differ. For example, if pathToBucket is "/roles/admin/params" and
// bucketPrefix is "/roles", then "admin" is returned.
func suffix(pathToBucket string, bucketPrefix string) (string, error) | {
full, err := url.QueryUnescape(pathToBucket)
if err != nil {
return "", trace.Wrap(err)
}
prefix, err := url.QueryUnescape(bucketPrefix)
if err != nil {
return "", trace.Wrap(err)
}
remain := full[len(prefix)+1:]
if remain == "" {
return "", trace.BadParameter("unable to split %v", remain)
}
vals := strings.Split(remain, string(filepath.Separator))
if len(vals) == 0 {
return "", trace.BadParameter("unable to split %v", remain)
}
return vals[0], nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/legacy/dir/impl.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L709-L727 | go | train | // removeDuplicates removes any duplicate items from the passed in slice. This
// is to ensure that partial matches don't result in multiple values returned.
// This is consistent with our DynamoDB implementation. | func removeDuplicates(items []legacy.Item) []legacy.Item | // removeDuplicates removes any duplicate items from the passed in slice. This
// is to ensure that partial matches don't result in multiple values returned.
// This is consistent with our DynamoDB implementation.
func removeDuplicates(items []legacy.Item) []legacy.Item | {
// Use map to record duplicates as we find them.
encountered := map[string]bool{}
result := make([]legacy.Item, 0, len(items))
// Loop over all items, if it has not been seen before, append to result.
for _, e := range items {
_, ok := encountered[e.FullPath]
if !ok {
// Record this element as an encountered element.
encountered[e.FullPath] = true
// Append to result slice.
result = append(result, e)
}
}
return result
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/legacy/dir/impl.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/impl.go#L732-L750 | go | train | // removeDuplicates removes any duplicate items from the passed in slice. This
// is to ensure that partial matches don't result in multiple values returned.
// This is consistent with our DynamoDB implementation. | func removeBackendDuplicates(items []backend.Item) []backend.Item | // removeDuplicates removes any duplicate items from the passed in slice. This
// is to ensure that partial matches don't result in multiple values returned.
// This is consistent with our DynamoDB implementation.
func removeBackendDuplicates(items []backend.Item) []backend.Item | {
// Use map to record duplicates as we find them.
encountered := map[string]bool{}
result := make([]backend.Item, 0, len(items))
// Loop over all items, if it has not been seen before, append to result.
for _, e := range items {
_, ok := encountered[string(e.Key)]
if !ok {
// Record this element as an encountered element.
encountered[string(e.Key)] = true
// Append to result slice.
result = append(result, e)
}
}
return result
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/memory/item.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/memory/item.go#L37-L46 | go | train | // Less is used for Btree operations,
// returns true if item is less than the other one | func (i *btreeItem) Less(iother btree.Item) bool | // Less is used for Btree operations,
// returns true if item is less than the other one
func (i *btreeItem) Less(iother btree.Item) bool | {
switch other := iother.(type) {
case *btreeItem:
return bytes.Compare(i.Key, other.Key) < 0
case *prefixItem:
return !iother.Less(i)
default:
return false
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/memory/item.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/memory/item.go#L55-L61 | go | train | // Less is used for Btree operations | func (p *prefixItem) Less(iother btree.Item) bool | // Less is used for Btree operations
func (p *prefixItem) Less(iother btree.Item) bool | {
other := iother.(*btreeItem)
if bytes.HasPrefix(other.Key, p.prefix) {
return false
}
return true
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/remotecluster.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/remotecluster.go#L50-L59 | go | train | // NewRemoteCluster is a convenience wa to create a RemoteCluster resource. | func NewRemoteCluster(name string) (RemoteCluster, error) | // NewRemoteCluster is a convenience wa to create a RemoteCluster resource.
func NewRemoteCluster(name string) (RemoteCluster, error) | {
return &RemoteClusterV3{
Kind: KindRemoteCluster,
Version: V3,
Metadata: Metadata{
Name: name,
Namespace: defaults.Namespace,
},
}, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/remotecluster.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/remotecluster.go#L128-L130 | go | train | // SetLastHeartbeat sets last heartbeat of the cluster | func (c *RemoteClusterV3) SetLastHeartbeat(t time.Time) | // SetLastHeartbeat sets last heartbeat of the cluster
func (c *RemoteClusterV3) SetLastHeartbeat(t time.Time) | {
c.Status.LastHeartbeat = t
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/remotecluster.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/remotecluster.go#L148-L150 | go | train | // SetExpiry sets expiry time for the object | func (c *RemoteClusterV3) SetExpiry(expires time.Time) | // SetExpiry sets expiry time for the object
func (c *RemoteClusterV3) SetExpiry(expires time.Time) | {
c.Metadata.SetExpiry(expires)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/remotecluster.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/remotecluster.go#L173-L175 | go | train | // String represents a human readable version of remote cluster settings. | func (r *RemoteClusterV3) String() string | // String represents a human readable version of remote cluster settings.
func (r *RemoteClusterV3) String() string | {
return fmt.Sprintf("RemoteCluster(%v, %v)", r.Metadata.Name, r.Status.Connection)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/remotecluster.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/remotecluster.go#L207-L237 | go | train | // UnmarshalRemoteCluster unmarshals remote cluster from JSON or YAML. | func UnmarshalRemoteCluster(bytes []byte, opts ...MarshalOption) (RemoteCluster, error) | // UnmarshalRemoteCluster unmarshals remote cluster from JSON or YAML.
func UnmarshalRemoteCluster(bytes []byte, opts ...MarshalOption) (RemoteCluster, error) | {
cfg, err := collectOptions(opts)
if err != nil {
return nil, trace.Wrap(err)
}
var cluster RemoteClusterV3
if len(bytes) == 0 {
return nil, trace.BadParameter("missing resource data")
}
if cfg.SkipValidation {
err := utils.FastUnmarshal(bytes, &cluster)
if err != nil {
return nil, trace.Wrap(err)
}
} else {
err = utils.UnmarshalWithSchema(GetRemoteClusterSchema(), &cluster, bytes)
if err != nil {
return nil, trace.BadParameter(err.Error())
}
}
err = cluster.CheckAndSetDefaults()
if err != nil {
return nil, trace.Wrap(err)
}
return &cluster, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/remotecluster.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/remotecluster.go#L240-L258 | go | train | // MarshalRemoteCluster marshals remote cluster to JSON. | func MarshalRemoteCluster(c RemoteCluster, opts ...MarshalOption) ([]byte, error) | // MarshalRemoteCluster marshals remote cluster to JSON.
func MarshalRemoteCluster(c RemoteCluster, opts ...MarshalOption) ([]byte, error) | {
cfg, err := collectOptions(opts)
if err != nil {
return nil, trace.Wrap(err)
}
switch resource := c.(type) {
case *RemoteClusterV3:
if !cfg.PreserveResourceID {
// avoid modifying the original object
// to prevent unexpected data races
copy := *resource
copy.SetResourceID(0)
resource = ©
}
return utils.FastMarshal(resource)
default:
return nil, trace.BadParameter("unrecognized resource version %T", c)
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/tlsca/ca.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/tlsca/ca.go#L43-L57 | go | train | // New returns new CA from PEM encoded certificate and private
// key. Private Key is optional, if omitted CA won't be able to
// issue new certificates, only verify them | func New(certPEM, keyPEM []byte) (*CertAuthority, error) | // New returns new CA from PEM encoded certificate and private
// key. Private Key is optional, if omitted CA won't be able to
// issue new certificates, only verify them
func New(certPEM, keyPEM []byte) (*CertAuthority, error) | {
ca := &CertAuthority{}
var err error
ca.Cert, err = ParseCertificatePEM(certPEM)
if err != nil {
return nil, trace.Wrap(err)
}
if len(keyPEM) != 0 {
ca.Signer, err = ParsePrivateKeyPEM(keyPEM)
if err != nil {
return nil, trace.Wrap(err)
}
}
return ca, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/tlsca/ca.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/tlsca/ca.go#L82-L90 | go | train | // CheckAndSetDefaults checks and sets default values | func (i *Identity) CheckAndSetDefaults() error | // CheckAndSetDefaults checks and sets default values
func (i *Identity) CheckAndSetDefaults() error | {
if i.Username == "" {
return trace.BadParameter("missing identity username")
}
if len(i.Groups) == 0 {
return trace.BadParameter("missing identity groups")
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/tlsca/ca.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/tlsca/ca.go#L93-L102 | go | train | // Subject converts identity to X.509 subject name | func (id *Identity) Subject() pkix.Name | // Subject converts identity to X.509 subject name
func (id *Identity) Subject() pkix.Name | {
subject := pkix.Name{
CommonName: id.Username,
}
subject.Organization = append([]string{}, id.Groups...)
subject.OrganizationalUnit = append([]string{}, id.Usage...)
subject.Locality = append([]string{}, id.Principals...)
subject.Province = append([]string{}, id.KubernetesGroups...)
return subject
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/tlsca/ca.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/tlsca/ca.go#L105-L117 | go | train | // FromSubject returns identity from subject name | func FromSubject(subject pkix.Name) (*Identity, error) | // FromSubject returns identity from subject name
func FromSubject(subject pkix.Name) (*Identity, error) | {
i := &Identity{
Username: subject.CommonName,
Groups: subject.Organization,
Usage: subject.OrganizationalUnit,
Principals: subject.Locality,
KubernetesGroups: subject.Province,
}
if err := i.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
return i, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/tlsca/ca.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/tlsca/ca.go#L135-L149 | go | train | // CheckAndSetDefaults checks and sets default values | func (c *CertificateRequest) CheckAndSetDefaults() error | // CheckAndSetDefaults checks and sets default values
func (c *CertificateRequest) CheckAndSetDefaults() error | {
if c.Clock == nil {
return trace.BadParameter("missing parameter Clock")
}
if c.PublicKey == nil {
return trace.BadParameter("missing parameter PublicKey")
}
if c.Subject.CommonName == "" {
return trace.BadParameter("missing parameter Subject.Common name")
}
if c.NotAfter.IsZero() {
return trace.BadParameter("missing parameter NotAfter")
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/tlsca/ca.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/tlsca/ca.go#L152-L200 | go | train | // GenerateCertificate generates certificate from request | func (ca *CertAuthority) GenerateCertificate(req CertificateRequest) ([]byte, error) | // GenerateCertificate generates certificate from request
func (ca *CertAuthority) GenerateCertificate(req CertificateRequest) ([]byte, error) | {
if err := req.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return nil, trace.Wrap(err)
}
log.WithFields(logrus.Fields{
"not_after": req.NotAfter,
"dns_names": req.DNSNames,
"common_name": req.Subject.CommonName,
"org": req.Subject.Organization,
"org_unit": req.Subject.OrganizationalUnit,
"locality": req.Subject.Locality,
}).Infof("Generating TLS certificate %v.", req)
template := &x509.Certificate{
SerialNumber: serialNumber,
Subject: req.Subject,
// NotBefore is one minute in the past to prevent "Not yet valid" errors on
// time skewed clusters.
NotBefore: req.Clock.Now().UTC().Add(-1 * time.Minute),
NotAfter: req.NotAfter,
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
// BasicConstraintsValid is true to not allow any intermediate certs.
BasicConstraintsValid: true,
IsCA: false,
}
// sort out principals into DNS names and IP addresses
for i := range req.DNSNames {
if ip := net.ParseIP(req.DNSNames[i]); ip != nil {
template.IPAddresses = append(template.IPAddresses, ip)
} else {
template.DNSNames = append(template.DNSNames, req.DNSNames[i])
}
}
certBytes, err := x509.CreateCertificate(rand.Reader, template, ca.Cert, req.PublicKey, ca.Signer)
if err != nil {
return nil, trace.Wrap(err)
}
return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certBytes}), nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/srv/termhandlers.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/termhandlers.go#L39-L119 | go | train | // HandleExec handles requests of type "exec" which can execute with or
// without a TTY. Result of execution is propagated back on the ExecResult
// channel of the context. | func (t *TermHandlers) HandleExec(ch ssh.Channel, req *ssh.Request, ctx *ServerContext) error | // HandleExec handles requests of type "exec" which can execute with or
// without a TTY. Result of execution is propagated back on the ExecResult
// channel of the context.
func (t *TermHandlers) HandleExec(ch ssh.Channel, req *ssh.Request, ctx *ServerContext) error | {
execRequest, err := parseExecRequest(req, ctx)
if err != nil {
return trace.Wrap(err)
}
// a terminal has been previously allocate for this command.
// run this inside an interactive session
if ctx.GetTerm() != nil {
return t.SessionRegistry.OpenSession(ch, req, ctx)
}
// If this code is running on a Teleport node and PAM is enabled, then open a
// PAM context.
var pamContext *pam.PAM
if ctx.srv.Component() == teleport.ComponentNode {
conf, err := t.SessionRegistry.srv.GetPAM()
if err != nil {
return trace.Wrap(err)
}
if conf.Enabled == true {
// Note, stdout/stderr is discarded here, otherwise MOTD would be printed to
// the users screen during exec requests.
pamContext, err = pam.Open(&pam.Config{
ServiceName: conf.ServiceName,
Username: ctx.Identity.Login,
Stdin: ch,
Stderr: ioutil.Discard,
Stdout: ioutil.Discard,
})
if err != nil {
return trace.Wrap(err)
}
ctx.Debugf("Opening PAM context for exec request %q.", execRequest.GetCommand())
}
}
// otherwise, regular execution
result, err := execRequest.Start(ch)
if err != nil {
return trace.Wrap(err)
}
// if the program failed to start, we should send that result back
if result != nil {
ctx.Debugf("Exec request (%v) result: %v", execRequest, result)
ctx.SendExecResult(*result)
}
// in case if result is nil and no error, this means that program is
// running in the background
go func() {
result, err = execRequest.Wait()
if err != nil {
ctx.Errorf("Exec request (%v) wait failed: %v", execRequest, err)
}
if result != nil {
ctx.SendExecResult(*result)
}
// If this code is running on a Teleport node and PAM is enabled, close the context.
if ctx.srv.Component() == teleport.ComponentNode {
conf, err := t.SessionRegistry.srv.GetPAM()
if err != nil {
ctx.Errorf("Unable to get PAM configuration from server: %v", err)
return
}
if conf.Enabled == true {
err = pamContext.Close()
if err != nil {
ctx.Errorf("Unable to close PAM context for exec request: %q: %v", execRequest.GetCommand(), err)
return
}
ctx.Debugf("Closing PAM context for exec request: %q.", execRequest.GetCommand())
}
}
}()
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/srv/termhandlers.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/termhandlers.go#L124-L162 | go | train | // HandlePTYReq handles requests of type "pty-req" which allocate a TTY for
// "exec" or "shell" requests. The "pty-req" includes the size of the TTY as
// well as the terminal type requested. | func (t *TermHandlers) HandlePTYReq(ch ssh.Channel, req *ssh.Request, ctx *ServerContext) error | // HandlePTYReq handles requests of type "pty-req" which allocate a TTY for
// "exec" or "shell" requests. The "pty-req" includes the size of the TTY as
// well as the terminal type requested.
func (t *TermHandlers) HandlePTYReq(ch ssh.Channel, req *ssh.Request, ctx *ServerContext) error | {
// parse and extract the requested window size of the pty
ptyRequest, err := parsePTYReq(req)
if err != nil {
return trace.Wrap(err)
}
termModes, err := ptyRequest.TerminalModes()
if err != nil {
return trace.Wrap(err)
}
params, err := rsession.NewTerminalParamsFromUint32(ptyRequest.W, ptyRequest.H)
if err != nil {
return trace.Wrap(err)
}
ctx.Debugf("Requested terminal %q of size %v", ptyRequest.Env, *params)
// get an existing terminal or create a new one
term := ctx.GetTerm()
if term == nil {
// a regular or forwarding terminal will be allocated
term, err = NewTerminal(ctx)
if err != nil {
return trace.Wrap(err)
}
ctx.SetTerm(term)
}
term.SetWinSize(*params)
term.SetTermType(ptyRequest.Env)
term.SetTerminalModes(termModes)
// update the session
if err := t.SessionRegistry.NotifyWinChange(*params, ctx); err != nil {
ctx.Errorf("Unable to update session: %v", err)
}
return nil
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.