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/srv/authhandlers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/authhandlers.go#L385-L427
go
train
// authorityForCert checks if the certificate was signed by a Teleport // Certificate Authority and returns it.
func (h *AuthHandlers) authorityForCert(caType services.CertAuthType, key ssh.PublicKey) (services.CertAuthority, error)
// authorityForCert checks if the certificate was signed by a Teleport // Certificate Authority and returns it. func (h *AuthHandlers) authorityForCert(caType services.CertAuthType, key ssh.PublicKey) (services.CertAuthority, error)
{ // get all certificate authorities for given type cas, err := h.AccessPoint.GetCertAuthorities(caType, false) if err != nil { h.Warnf("%v", trace.DebugReport(err)) return nil, trace.Wrap(err) } // find the one that signed our certificate var ca services.CertAuthority for i := range cas { checkers, err := cas[i].Checkers() if err != nil { h.Warnf("%v", err) return nil, trace.Wrap(err) } for _, checker := range checkers { // if we have a certificate, compare the certificate signing key against // the ca key. otherwise check the public key that was passed in. this is // due to the differences in how this function is called by the user and // host checkers. switch v := key.(type) { case *ssh.Certificate: if sshutils.KeysEqual(v.SignatureKey, checker) { ca = cas[i] break } default: if sshutils.KeysEqual(key, checker) { ca = cas[i] break } } } } // the certificate was signed by unknown authority if ca == nil { return nil, trace.AccessDenied("the certificate signed by untrusted CA") } return ca, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/authhandlers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/authhandlers.go#L430-L435
go
train
// isProxy returns true if it's a regular SSH proxy.
func (h *AuthHandlers) isProxy() bool
// isProxy returns true if it's a regular SSH proxy. func (h *AuthHandlers) isProxy() bool
{ if h.Component == teleport.ComponentProxy { return true } return false }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/authhandlers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/authhandlers.go#L446-L453
go
train
// extractRolesFromCert extracts roles from certificate metadata extensions.
func extractRolesFromCert(cert *ssh.Certificate) ([]string, error)
// extractRolesFromCert extracts roles from certificate metadata extensions. func extractRolesFromCert(cert *ssh.Certificate) ([]string, error)
{ data, ok := cert.Extensions[teleport.CertExtensionTeleportRoles] if !ok { // it's ok to not have any roles in the metadata return nil, nil } return services.UnmarshalCertRoles(data) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/web/sessions.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/sessions.go#L116-L154
go
train
// GetUserClient will return an auth.ClientI with the role of the user at // the requested site. If the site is local a client with the users local role // is returned. If the site is remote a client with the users remote role is // returned.
func (c *SessionContext) GetUserClient(site reversetunnel.RemoteSite) (auth.ClientI, error)
// GetUserClient will return an auth.ClientI with the role of the user at // the requested site. If the site is local a client with the users local role // is returned. If the site is remote a client with the users remote role is // returned. func (c *SessionContext) GetUserClient(site reversetunnel.RemoteSite) (auth.ClientI, error)
{ // get the name of the current cluster clt, err := c.GetClient() if err != nil { return nil, trace.Wrap(err) } cn, err := clt.GetClusterName() if err != nil { return nil, trace.Wrap(err) } // if we're trying to access the local cluster, pass back the local client. if cn.GetClusterName() == site.GetName() { return clt, nil } // look to see if we already have a connection to this cluster remoteClt, ok := c.getRemoteClient(site.GetName()) if !ok { rClt, rConn, err := c.newRemoteClient(site) if err != nil { return nil, trace.Wrap(err) } // add a closer for the underlying connection if rConn != nil { c.AddClosers(rConn) } // we'll save the remote client in our session context so we don't have to // build a new connection next time. all remote clients will be closed when // the session context is closed. c.addRemoteClient(site.GetName(), rClt) return rClt, nil } return remoteClt, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/web/sessions.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/sessions.go#L158-L164
go
train
// newRemoteClient returns a client to a remote cluster with the role of // the logged in user.
func (c *SessionContext) newRemoteClient(cluster reversetunnel.RemoteSite) (auth.ClientI, net.Conn, error)
// newRemoteClient returns a client to a remote cluster with the role of // the logged in user. func (c *SessionContext) newRemoteClient(cluster reversetunnel.RemoteSite) (auth.ClientI, net.Conn, error)
{ clt, err := c.tryRemoteTLSClient(cluster) if err != nil { return nil, nil, trace.Wrap(err) } return clt, nil, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/web/sessions.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/sessions.go#L167-L171
go
train
// clusterDialer returns DialContext function using cluster's dial function
func clusterDialer(remoteCluster reversetunnel.RemoteSite) auth.DialContext
// clusterDialer returns DialContext function using cluster's dial function func clusterDialer(remoteCluster reversetunnel.RemoteSite) auth.DialContext
{ return func(in context.Context, network, _ string) (net.Conn, error) { return remoteCluster.DialAuthServer() } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/web/sessions.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/sessions.go#L175-L185
go
train
// tryRemoteTLSClient tries creating TLS client and using it (the client may not be available // due to older clusters), returns client if it is working properly
func (c *SessionContext) tryRemoteTLSClient(cluster reversetunnel.RemoteSite) (auth.ClientI, error)
// tryRemoteTLSClient tries creating TLS client and using it (the client may not be available // due to older clusters), returns client if it is working properly func (c *SessionContext) tryRemoteTLSClient(cluster reversetunnel.RemoteSite) (auth.ClientI, error)
{ clt, err := c.newRemoteTLSClient(cluster) if err != nil { return nil, trace.Wrap(err) } _, err = clt.GetDomainName() if err != nil { return clt, trace.Wrap(err) } return clt, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/web/sessions.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/sessions.go#L189-L223
go
train
// ClientTLSConfig returns client TLS authentication associated // with the web session context
func (c *SessionContext) ClientTLSConfig(clusterName ...string) (*tls.Config, error)
// ClientTLSConfig returns client TLS authentication associated // with the web session context func (c *SessionContext) ClientTLSConfig(clusterName ...string) (*tls.Config, error)
{ var certPool *x509.CertPool if len(clusterName) == 0 { certAuthorities, err := c.parent.proxyClient.GetCertAuthorities(services.HostCA, false) if err != nil { return nil, trace.Wrap(err) } certPool, err = services.CertPoolFromCertAuthorities(certAuthorities) if err != nil { return nil, trace.Wrap(err) } } else { certAuthority, err := c.parent.proxyClient.GetCertAuthority(services.CertAuthID{ Type: services.HostCA, DomainName: clusterName[0], }, false) if err != nil { return nil, trace.Wrap(err) } certPool, err = services.CertPool(certAuthority) if err != nil { return nil, trace.Wrap(err) } } tlsConfig := utils.TLSConfig(c.parent.cipherSuites) tlsCert, err := tls.X509KeyPair(c.sess.GetTLSCert(), c.sess.GetPriv()) if err != nil { return nil, trace.Wrap(err, "failed to parse TLS cert and key") } tlsConfig.Certificates = []tls.Certificate{tlsCert} tlsConfig.RootCAs = certPool tlsConfig.ServerName = auth.EncodeClusterName(c.parent.clusterName) return tlsConfig, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/web/sessions.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/sessions.go#L245-L251
go
train
// ExtendWebSession creates a new web session for this user // based on the previous session
func (c *SessionContext) ExtendWebSession() (services.WebSession, error)
// ExtendWebSession creates a new web session for this user // based on the previous session func (c *SessionContext) ExtendWebSession() (services.WebSession, error)
{ sess, err := c.clt.ExtendWebSession(c.user, c.sess.GetName()) if err != nil { return nil, trace.Wrap(err) } return sess, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/web/sessions.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/sessions.go#L255-L281
go
train
// GetAgent returns agent that can be used to answer challenges // for the web to ssh connection as well as certificate
func (c *SessionContext) GetAgent() (agent.Agent, *ssh.Certificate, error)
// GetAgent returns agent that can be used to answer challenges // for the web to ssh connection as well as certificate func (c *SessionContext) GetAgent() (agent.Agent, *ssh.Certificate, error)
{ pub, _, _, _, err := ssh.ParseAuthorizedKey(c.sess.GetPub()) if err != nil { return nil, nil, trace.Wrap(err) } cert, ok := pub.(*ssh.Certificate) if !ok { return nil, nil, trace.BadParameter("expected certificate, got %T", pub) } if len(cert.ValidPrincipals) == 0 { return nil, nil, trace.BadParameter("expected at least valid principal in certificate") } privateKey, err := ssh.ParseRawPrivateKey(c.sess.GetPriv()) if err != nil { return nil, nil, trace.Wrap(err, "failed to parse SSH private key") } keyring := agent.NewKeyring() err = keyring.Add(agent.AddedKey{ PrivateKey: privateKey, Certificate: cert, }) if err != nil { return nil, nil, trace.Wrap(err) } return keyring, cert, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/web/sessions.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/sessions.go#L284-L294
go
train
// Close cleans up connections associated with requests
func (c *SessionContext) Close() error
// Close cleans up connections associated with requests func (c *SessionContext) Close() error
{ closers := c.TransferClosers() for _, closer := range closers { c.Debugf("Closing %v.", closer) closer.Close() } if c.clt != nil { return trace.Wrap(c.clt.Close()) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/web/sessions.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/sessions.go#L297-L317
go
train
// newSessionCache returns new instance of the session cache
func newSessionCache(proxyClient auth.ClientI, servers []utils.NetAddr, cipherSuites []uint16) (*sessionCache, error)
// newSessionCache returns new instance of the session cache func newSessionCache(proxyClient auth.ClientI, servers []utils.NetAddr, cipherSuites []uint16) (*sessionCache, error)
{ clusterName, err := proxyClient.GetClusterName() if err != nil { return nil, trace.Wrap(err) } m, err := ttlmap.New(1024, ttlmap.CallOnExpire(closeContext)) if err != nil { return nil, trace.Wrap(err) } cache := &sessionCache{ clusterName: clusterName.GetClusterName(), proxyClient: proxyClient, contexts: m, authServers: servers, closer: utils.NewCloseBroadcaster(), cipherSuites: cipherSuites, } // periodically close expired and unused sessions go cache.expireSessions() return cache, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/web/sessions.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/sessions.go#L341-L353
go
train
// closeContext is called when session context expires from // cache and will clean up connections
func closeContext(key string, val interface{})
// closeContext is called when session context expires from // cache and will clean up connections func closeContext(key string, val interface{})
{ go func() { log.Infof("[WEB] closing context %v", key) ctx, ok := val.(*SessionContext) if !ok { log.Warningf("warning, not valid value type %T", val) return } if err := ctx.Close(); err != nil { log.Infof("failed to close context: %v", err) } }() }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/github.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/github.go#L40-L62
go
train
// CreateGithubAuthRequest creates a new request for Github OAuth2 flow
func (s *AuthServer) CreateGithubAuthRequest(req services.GithubAuthRequest) (*services.GithubAuthRequest, error)
// CreateGithubAuthRequest creates a new request for Github OAuth2 flow func (s *AuthServer) CreateGithubAuthRequest(req services.GithubAuthRequest) (*services.GithubAuthRequest, error)
{ connector, err := s.Identity.GetGithubConnector(req.ConnectorID, true) if err != nil { return nil, trace.Wrap(err) } client, err := s.getGithubOAuth2Client(connector) if err != nil { return nil, trace.Wrap(err) } req.StateToken, err = utils.CryptoRandomHex(TokenLenBytes) if err != nil { return nil, trace.Wrap(err) } req.RedirectURL = client.AuthCodeURL(req.StateToken, "", "") log.WithFields(logrus.Fields{trace.Component: "github"}).Debugf( "Redirect URL: %v.", req.RedirectURL) req.SetTTL(s.GetClock(), defaults.GithubAuthRequestTTL) err = s.Identity.CreateGithubAuthRequest(req) if err != nil { return nil, trace.Wrap(err) } return &req, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/github.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/github.go#L84-L100
go
train
// ValidateGithubAuthCallback validates Github auth callback redirect
func (a *AuthServer) ValidateGithubAuthCallback(q url.Values) (*GithubAuthResponse, error)
// ValidateGithubAuthCallback validates Github auth callback redirect func (a *AuthServer) ValidateGithubAuthCallback(q url.Values) (*GithubAuthResponse, error)
{ re, err := a.validateGithubAuthCallback(q) if err != nil { a.EmitAuditEvent(events.UserSSOLoginFailure, events.EventFields{ events.LoginMethod: events.LoginMethodGithub, events.AuthAttemptSuccess: false, events.AuthAttemptErr: err.Error(), }) } else { a.EmitAuditEvent(events.UserSSOLogin, events.EventFields{ events.EventUser: re.Username, events.AuthAttemptSuccess: true, events.LoginMethod: events.LoginMethodGithub, }) } return re, err }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/github.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/github.go#L103-L213
go
train
// ValidateGithubAuthCallback validates Github auth callback redirect
func (s *AuthServer) validateGithubAuthCallback(q url.Values) (*GithubAuthResponse, error)
// ValidateGithubAuthCallback validates Github auth callback redirect func (s *AuthServer) validateGithubAuthCallback(q url.Values) (*GithubAuthResponse, error)
{ logger := log.WithFields(logrus.Fields{trace.Component: "github"}) error := q.Get("error") if error != "" { return nil, trace.OAuth2(oauth2.ErrorInvalidRequest, error, q) } code := q.Get("code") if code == "" { return nil, trace.OAuth2(oauth2.ErrorInvalidRequest, "code query param must be set", q) } stateToken := q.Get("state") if stateToken == "" { return nil, trace.OAuth2(oauth2.ErrorInvalidRequest, "missing state query param", q) } req, err := s.Identity.GetGithubAuthRequest(stateToken) if err != nil { return nil, trace.Wrap(err) } connector, err := s.Identity.GetGithubConnector(req.ConnectorID, true) if err != nil { return nil, trace.Wrap(err) } if len(connector.GetTeamsToLogins()) == 0 { logger.Warnf("Github connector %q has empty teams_to_logins mapping, cannot populate claims.", connector.GetName()) return nil, trace.BadParameter( "connector %q has empty teams_to_logins mapping", connector.GetName()) } client, err := s.getGithubOAuth2Client(connector) if err != nil { return nil, trace.Wrap(err) } // exchange the authorization code received by the callback for an access token token, err := client.RequestToken(oauth2.GrantTypeAuthCode, code) if err != nil { return nil, trace.Wrap(err) } logger.Debugf("Obtained OAuth2 token: Type=%v Expires=%v Scope=%v.", token.TokenType, token.Expires, token.Scope) // Github does not support OIDC so user claims have to be populated // by making requests to Github API using the access token claims, err := populateGithubClaims(&githubAPIClient{ token: token.AccessToken, authServer: s, }) if err != nil { return nil, trace.Wrap(err) } // Calculate (figure out name, roles, traits, session TTL) of user and // create the user in the backend. params, err := s.calculateGithubUser(connector, claims, req) if err != nil { return nil, trace.Wrap(err) } user, err := s.createGithubUser(params) if err != nil { return nil, trace.Wrap(err) } // Auth was successful, return session, certificate, etc. to caller. response := &GithubAuthResponse{ Req: *req, Identity: services.ExternalIdentity{ ConnectorID: params.connectorName, Username: params.username, }, Username: user.GetName(), } response.Username = user.GetName() // If the request is coming from a browser, create a web session. if req.CreateWebSession { session, err := s.createWebSession(user, params.sessionTTL) if err != nil { return nil, trace.Wrap(err) } response.Session = session } // If a public key was provided, sign it and return a certificate. if len(req.PublicKey) != 0 { sshCert, tlsCert, err := s.createSessionCert(user, params.sessionTTL, req.PublicKey, req.Compatibility) if err != nil { return nil, trace.Wrap(err) } clusterName, err := s.GetClusterName() if err != nil { return nil, trace.Wrap(err) } response.Cert = sshCert response.TLSCert = tlsCert // Return the host CA for this cluster only. authority, err := s.GetCertAuthority(services.CertAuthID{ Type: services.HostCA, DomainName: clusterName.GetClusterName(), }, false) if err != nil { return nil, trace.Wrap(err) } response.HostSigners = append(response.HostSigners, authority) } return response, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/github.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/github.go#L366-L395
go
train
// populateGithubClaims retrieves information about user and its team // memberships by calling Github API using the access token
func populateGithubClaims(client githubAPIClientI) (*services.GithubClaims, error)
// populateGithubClaims retrieves information about user and its team // memberships by calling Github API using the access token func populateGithubClaims(client githubAPIClientI) (*services.GithubClaims, error)
{ // find out the username user, err := client.getUser() if err != nil { return nil, trace.Wrap(err, "failed to query Github user info") } // build team memberships teams, err := client.getTeams() if err != nil { return nil, trace.Wrap(err, "failed to query Github user teams") } log.Debugf("Retrieved %v teams for GitHub user %v.", len(teams), user.Login) orgToTeams := make(map[string][]string) for _, team := range teams { orgToTeams[team.Org.Login] = append( orgToTeams[team.Org.Login], team.Slug) } if len(orgToTeams) == 0 { return nil, trace.AccessDenied( "list of user teams is empty, did you grant access?") } claims := &services.GithubClaims{ Username: user.Login, OrganizationToTeams: orgToTeams, } log.WithFields(logrus.Fields{trace.Component: "github"}).Debugf( "Claims: %#v.", claims) return claims, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/github.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/github.go#L450-L462
go
train
// getEmails retrieves a list of emails for authenticated user
func (c *githubAPIClient) getUser() (*userResponse, error)
// getEmails retrieves a list of emails for authenticated user func (c *githubAPIClient) getUser() (*userResponse, error)
{ // Ignore pagination links, we should never get more than a single user here. bytes, _, err := c.get("/user") if err != nil { return nil, trace.Wrap(err) } var user userResponse err = json.Unmarshal(bytes, &user) if err != nil { return nil, trace.Wrap(err) } return &user, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/github.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/github.go#L481-L540
go
train
// getTeams retrieves a list of teams authenticated user belongs to.
func (c *githubAPIClient) getTeams() ([]teamResponse, error)
// getTeams retrieves a list of teams authenticated user belongs to. func (c *githubAPIClient) getTeams() ([]teamResponse, error)
{ var result []teamResponse bytes, nextPage, err := c.get("/user/teams") if err != nil { return nil, trace.Wrap(err) } // Extract the first page of results and append them to the full result set. var teams []teamResponse err = json.Unmarshal(bytes, &teams) if err != nil { return nil, trace.Wrap(err) } result = append(result, teams...) // If the response returned a next page link, continue following the next // page links until all teams have been retrieved. var count int for nextPage != "" { // To prevent this from looping forever, don't fetch more than a set number // of pages, print an error when it does happen, and return the results up // to that point. if count > MaxPages { warningMessage := "Truncating list of teams used to populate claims: " + "hit maximum number pages that can be fetched from GitHub." // Print warning to Teleport logs as well as the Audit Log. log.Warnf(warningMessage) c.authServer.EmitAuditEvent(events.UserSSOLoginFailure, events.EventFields{ events.LoginMethod: events.LoginMethodGithub, events.AuthAttemptMessage: warningMessage, }) return result, nil } u, err := url.Parse(nextPage) if err != nil { return nil, trace.Wrap(err) } bytes, nextPage, err = c.get(u.RequestURI()) if err != nil { return nil, trace.Wrap(err) } err = json.Unmarshal(bytes, &teams) if err != nil { return nil, trace.Wrap(err) } // Append this page of teams to full result set. result = append(result, teams...) count = count + 1 } return result, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/github.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/github.go#L543-L568
go
train
// get makes a GET request to the provided URL using the client's token for auth
func (c *githubAPIClient) get(url string) ([]byte, string, error)
// get makes a GET request to the provided URL using the client's token for auth func (c *githubAPIClient) get(url string) ([]byte, string, error)
{ request, err := http.NewRequest("GET", fmt.Sprintf("%v%v", GithubAPIURL, url), nil) if err != nil { return nil, "", trace.Wrap(err) } request.Header.Set("Authorization", fmt.Sprintf("token %v", c.token)) response, err := http.DefaultClient.Do(request) if err != nil { return nil, "", trace.Wrap(err) } defer response.Body.Close() bytes, err := ioutil.ReadAll(response.Body) if err != nil { return nil, "", trace.Wrap(err) } if response.StatusCode != 200 { return nil, "", trace.AccessDenied("bad response: %v %v", response.StatusCode, string(bytes)) } // Parse web links header to extract any pagination links. This is used to // return the next link which can be used in a loop to pull back all data. wls := utils.ParseWebLinks(response) return bytes, wls.NextPage, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/forward/sshserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/forward/sshserver.go#L162-L189
go
train
// CheckDefaults makes sure all required parameters are passed in.
func (s *ServerConfig) CheckDefaults() error
// CheckDefaults makes sure all required parameters are passed in. func (s *ServerConfig) CheckDefaults() error
{ if s.AuthClient == nil { return trace.BadParameter("auth client required") } if s.DataDir == "" { return trace.BadParameter("missing parameter DataDir") } if s.UserAgent == nil { return trace.BadParameter("user agent required to connect to remote host") } if s.TargetConn == nil { return trace.BadParameter("connection to target connection required") } if s.SrcAddr == nil { return trace.BadParameter("source address required to identify client") } if s.DstAddr == nil { return trace.BadParameter("destination address required to connect to remote host") } if s.HostCertificate == nil { return trace.BadParameter("host certificate required to act on behalf of remote host") } if s.Clock == nil { s.Clock = clockwork.NewRealClock() } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/forward/sshserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/forward/sshserver.go#L192-L262
go
train
// New creates a new unstarted Server.
func New(c ServerConfig) (*Server, error)
// New creates a new unstarted Server. func New(c ServerConfig) (*Server, error)
{ // Check and make sure we everything we need to build a forwarding node. err := c.CheckDefaults() if err != nil { return nil, trace.Wrap(err) } // Build a pipe connection to hook up the client and the server. we save both // here and will pass them along to the context when we create it so they // can be closed by the context. serverConn, clientConn := utils.DualPipeNetConn(c.SrcAddr, c.DstAddr) if err != nil { return nil, trace.Wrap(err) } s := &Server{ log: logrus.WithFields(logrus.Fields{ trace.Component: teleport.ComponentForwardingNode, trace.ComponentFields: map[string]string{ "src-addr": c.SrcAddr.String(), "dst-addr": c.DstAddr.String(), }, }), id: uuid.New(), targetConn: c.TargetConn, serverConn: utils.NewTrackingConn(serverConn), clientConn: clientConn, userAgent: c.UserAgent, hostCertificate: c.HostCertificate, authClient: c.AuthClient, auditLog: c.AuthClient, authService: c.AuthClient, sessionServer: c.AuthClient, dataDir: c.DataDir, clock: c.Clock, } // Set the ciphers, KEX, and MACs that the in-memory server will send to the // client in its SSH_MSG_KEXINIT. s.ciphers = c.Ciphers s.kexAlgorithms = c.KEXAlgorithms s.macAlgorithms = c.MACAlgorithms s.sessionRegistry, err = srv.NewSessionRegistry(s) if err != nil { return nil, trace.Wrap(err) } // Common auth handlers. s.authHandlers = &srv.AuthHandlers{ Entry: logrus.WithFields(logrus.Fields{ trace.Component: teleport.ComponentForwardingNode, trace.ComponentFields: logrus.Fields{}, }), Server: s, Component: teleport.ComponentForwardingNode, AuditLog: c.AuthClient, AccessPoint: c.AuthClient, } // Common term handlers. s.termHandlers = &srv.TermHandlers{ SessionRegistry: s.sessionRegistry, } // Create a close context that is used internally to signal when the server // is closing and for any blocking goroutines to unblock. s.closeContext, s.closeCancel = context.WithCancel(context.Background()) return s, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/forward/sshserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/forward/sshserver.go#L291-L300
go
train
// EmitAuditEvent sends an event to the Audit Log.
func (s *Server) EmitAuditEvent(event events.Event, fields events.EventFields)
// EmitAuditEvent sends an event to the Audit Log. func (s *Server) EmitAuditEvent(event events.Event, fields events.EventFields)
{ auditLog := s.GetAuditLog() if auditLog != nil { if err := auditLog.EmitAuditEvent(event, fields); err != nil { s.log.Error(err) } } else { s.log.Warn("SSH server has no audit log") } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/forward/sshserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/forward/sshserver.go#L330-L342
go
train
// GetInfo returns a services.Server that represents this server.
func (s *Server) GetInfo() services.Server
// GetInfo returns a services.Server that represents this server. func (s *Server) GetInfo() services.Server
{ return &services.ServerV2{ Kind: services.KindNode, Version: services.V2, Metadata: services.Metadata{ Name: s.ID(), Namespace: s.GetNamespace(), }, Spec: services.ServerSpecV2{ Addr: s.AdvertiseAddr(), }, } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/forward/sshserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/forward/sshserver.go#L436-L463
go
train
// Close will close all underlying connections that the forwarding server holds.
func (s *Server) Close() error
// Close will close all underlying connections that the forwarding server holds. func (s *Server) Close() error
{ conns := []io.Closer{ s.sconn, s.clientConn, s.serverConn, s.targetConn, s.remoteClient, } var errs []error for _, c := range conns { if c == nil { continue } err := c.Close() if err != nil { errs = append(errs, err) } } // Signal to waiting goroutines that the server is closing (for example, // the keep alive loop). s.closeCancel() return trace.NewAggregate(errs...) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/forward/sshserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/forward/sshserver.go#L467-L497
go
train
// newRemoteSession will create and return a *ssh.Client and *ssh.Session // with a remote host.
func (s *Server) newRemoteClient(systemLogin string) (*ssh.Client, error)
// newRemoteSession will create and return a *ssh.Client and *ssh.Session // with a remote host. func (s *Server) newRemoteClient(systemLogin string) (*ssh.Client, error)
{ // the proxy will use the agent that has been forwarded to it as the auth // method when connecting to the remote host if s.userAgent == nil { return nil, trace.AccessDenied("agent must be forwarded to proxy") } authMethod := ssh.PublicKeysCallback(s.userAgent.Signers) clientConfig := &ssh.ClientConfig{ User: systemLogin, Auth: []ssh.AuthMethod{ authMethod, }, HostKeyCallback: s.authHandlers.HostKeyAuth, Timeout: defaults.DefaultDialTimeout, } // Ciphers, KEX, and MACs preferences are honored by both the in-memory // server as well as the client in the connection to the target node. clientConfig.Ciphers = s.ciphers clientConfig.KeyExchanges = s.kexAlgorithms clientConfig.MACs = s.macAlgorithms dstAddr := s.targetConn.RemoteAddr().String() client, err := proxy.NewClientConnWithDeadline(s.targetConn, dstAddr, clientConfig) if err != nil { return nil, trace.Wrap(err) } return client, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/forward/sshserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/forward/sshserver.go#L585-L644
go
train
// handleDirectTCPIPRequest handles port forwarding requests.
func (s *Server) handleDirectTCPIPRequest(ch ssh.Channel, req *sshutils.DirectTCPIPReq)
// handleDirectTCPIPRequest handles port forwarding requests. func (s *Server) handleDirectTCPIPRequest(ch ssh.Channel, req *sshutils.DirectTCPIPReq)
{ srcAddr := fmt.Sprintf("%v:%d", req.Orig, req.OrigPort) dstAddr := fmt.Sprintf("%v:%d", req.Host, req.Port) // Create context for this channel. This context will be closed when // forwarding is complete. ctx, err := srv.NewServerContext(s, s.sconn, s.identityContext) if err != nil { ctx.Errorf("Unable to create connection context: %v.", err) ch.Stderr().Write([]byte("Unable to create connection context.")) return } ctx.Connection = s.serverConn ctx.RemoteClient = s.remoteClient defer ctx.Close() // Check if the role allows port forwarding for this user. err = s.authHandlers.CheckPortForward(dstAddr, ctx) if err != nil { ch.Stderr().Write([]byte(err.Error())) return } s.log.Debugf("Opening direct-tcpip channel from %v to %v in context %v.", srcAddr, dstAddr, ctx.ID()) defer s.log.Debugf("Completing direct-tcpip request from %v to %v in context %v.", srcAddr, dstAddr, ctx.ID()) // Create "direct-tcpip" channel from the remote host to the target host. conn, err := s.remoteClient.Dial("tcp", dstAddr) if err != nil { ctx.Infof("Failed to connect to: %v: %v", dstAddr, err) return } defer conn.Close() // Emit a port forwarding audit event. s.EmitAuditEvent(events.PortForward, events.EventFields{ events.PortForwardAddr: dstAddr, events.PortForwardSuccess: true, events.EventLogin: s.identityContext.Login, events.EventUser: s.identityContext.TeleportUser, events.LocalAddr: s.sconn.LocalAddr().String(), events.RemoteAddr: s.sconn.RemoteAddr().String(), }) wg := &sync.WaitGroup{} wg.Add(1) go func() { defer wg.Done() io.Copy(ch, conn) ch.Close() }() wg.Add(1) go func() { defer wg.Done() io.Copy(conn, ch) conn.Close() }() wg.Wait() }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/forward/sshserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/forward/sshserver.go#L649-L724
go
train
// handleSessionRequests handles out of band session requests once the session // channel has been created this function's loop handles all the "exec", // "subsystem" and "shell" requests.
func (s *Server) handleSessionRequests(ch ssh.Channel, in <-chan *ssh.Request)
// handleSessionRequests handles out of band session requests once the session // channel has been created this function's loop handles all the "exec", // "subsystem" and "shell" requests. func (s *Server) handleSessionRequests(ch ssh.Channel, in <-chan *ssh.Request)
{ // Create context for this channel. This context will be closed when the // session request is complete. // There is no need for the forwarding server to initiate disconnects, // based on teleport business logic, because this logic is already // done on the server's terminating side. ctx, err := srv.NewServerContext(s, s.sconn, s.identityContext) if err != nil { ctx.Errorf("Unable to create connection context: %v.", err) ch.Stderr().Write([]byte("Unable to create connection context.")) return } ctx.Connection = s.serverConn ctx.RemoteClient = s.remoteClient ctx.AddCloser(ch) defer ctx.Close() // Create a "session" channel on the remote host. remoteSession, err := s.remoteClient.NewSession() if err != nil { ch.Stderr().Write([]byte(err.Error())) return } ctx.RemoteSession = remoteSession s.log.Debugf("Opening session request to %v in context %v.", s.sconn.RemoteAddr(), ctx.ID()) defer s.log.Debugf("Closing session request to %v in context %v.", s.sconn.RemoteAddr(), ctx.ID()) for { // Update the context with the session ID. err := ctx.CreateOrJoinSession(s.sessionRegistry) if err != nil { errorMessage := fmt.Sprintf("unable to update context: %v", err) ctx.Errorf("%v", errorMessage) // Write the error to channel and close it. ch.Stderr().Write([]byte(errorMessage)) _, err := ch.SendRequest("exit-status", false, ssh.Marshal(struct{ C uint32 }{C: teleport.RemoteCommandFailure})) if err != nil { ctx.Errorf("Failed to send exit status %v", errorMessage) } return } select { case result := <-ctx.SubsystemResultCh: // Subsystem has finished executing, close the channel and session. ctx.Debugf("Subsystem execution result: %v", result.Err) return case req := <-in: if req == nil { // The client has closed or dropped the connection. ctx.Debugf("Client %v disconnected", s.sconn.RemoteAddr()) return } if err := s.dispatch(ch, req, ctx); err != nil { s.replyError(ch, req, err) return } if req.WantReply { req.Reply(true, nil) } case result := <-ctx.ExecResultCh: ctx.Debugf("Exec request (%q) complete: %v", result.Command, result.Code) // The exec process has finished and delivered the execution result, send // the result back to the client, and close the session and channel. _, err := ch.SendRequest("exit-status", false, ssh.Marshal(struct{ C uint32 }{C: uint32(result.Code)})) if err != nil { ctx.Infof("Failed to send exit status for %v: %v", result.Command, err) } return } } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/service/cfg.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/cfg.go#L177-L183
go
train
// ApplyToken assigns a given token to all internal services but only if token // is not an empty string. // // Returns 'true' if token was modified
func (cfg *Config) ApplyToken(token string) bool
// ApplyToken assigns a given token to all internal services but only if token // is not an empty string. // // Returns 'true' if token was modified func (cfg *Config) ApplyToken(token string) bool
{ if token != "" { cfg.Token = token return true } return false }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/service/cfg.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/cfg.go#L186-L195
go
train
// RoleConfig is a config for particular Teleport role
func (cfg *Config) RoleConfig() RoleConfig
// RoleConfig is a config for particular Teleport role func (cfg *Config) RoleConfig() RoleConfig
{ return RoleConfig{ DataDir: cfg.DataDir, HostUUID: cfg.HostUUID, HostName: cfg.Hostname, AuthServers: cfg.AuthServers, Auth: cfg.Auth, Console: cfg.Console, } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/service/cfg.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/cfg.go#L199-L209
go
train
// DebugDumpToYAML is useful for debugging: it dumps the Config structure into // a string
func (cfg *Config) DebugDumpToYAML() string
// DebugDumpToYAML is useful for debugging: it dumps the Config structure into // a string func (cfg *Config) DebugDumpToYAML() string
{ shallow := *cfg // do not copy sensitive data to stdout shallow.Identities = nil shallow.Auth.Authorities = nil out, err := yaml.Marshal(shallow) if err != nil { return err.Error() } return string(out) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/service/cfg.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/cfg.go#L227-L232
go
train
// GetRecentTTL either returns TTL that was set, // or default recent TTL value
func (c *CachePolicy) GetRecentTTL() time.Duration
// GetRecentTTL either returns TTL that was set, // or default recent TTL value func (c *CachePolicy) GetRecentTTL() time.Duration
{ if c.RecentTTL == nil { return defaults.RecentCacheTTL } return *c.RecentTTL }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/service/cfg.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/cfg.go#L235-L252
go
train
// String returns human-friendly representation of the policy
func (c CachePolicy) String() string
// String returns human-friendly representation of the policy func (c CachePolicy) String() string
{ if !c.Enabled { return "no cache policy" } recentCachePolicy := "" if c.GetRecentTTL() == 0 { recentCachePolicy = "will not cache frequently accessed items" } else { recentCachePolicy = fmt.Sprintf("will cache frequently accessed items for %v", c.GetRecentTTL()) } if c.NeverExpires { return fmt.Sprintf("cache that will not expire in case if connection to database is lost, %v", recentCachePolicy) } if c.TTL == 0 { return fmt.Sprintf("cache that will expire after connection to database is lost after %v, %v", defaults.CacheTTL, recentCachePolicy) } return fmt.Sprintf("cache that will expire after connection to database is lost after %v, %v", c.TTL, recentCachePolicy) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/service/cfg.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/cfg.go#L412-L475
go
train
// ApplyDefaults applies default values to the existing config structure
func ApplyDefaults(cfg *Config)
// ApplyDefaults applies default values to the existing config structure func ApplyDefaults(cfg *Config)
{ // Get defaults for Cipher, Kex algorithms, and MAC algorithms from // golang.org/x/crypto/ssh default config. var sc ssh.Config sc.SetDefaults() // Remove insecure and (borderline insecure) cryptographic primitives from // default configuration. These can still be added back in file configuration by // users, but not supported by default by Teleport. See #1856 for more // details. kex := utils.RemoveFromSlice(sc.KeyExchanges, defaults.DiffieHellmanGroup1SHA1, defaults.DiffieHellmanGroup14SHA1) macs := utils.RemoveFromSlice(sc.MACs, defaults.HMACSHA1, defaults.HMACSHA196) hostname, err := os.Hostname() if err != nil { hostname = "localhost" log.Errorf("Failed to determine hostname: %v.", err) } // global defaults cfg.Hostname = hostname cfg.DataDir = defaults.DataDir cfg.Console = os.Stdout cfg.CipherSuites = utils.DefaultCipherSuites() cfg.Ciphers = sc.Ciphers cfg.KEXAlgorithms = kex cfg.MACAlgorithms = macs // defaults for the auth service: cfg.Auth.Enabled = true cfg.Auth.SSHAddr = *defaults.AuthListenAddr() cfg.Auth.StorageConfig.Type = dir.GetName() cfg.Auth.StorageConfig.Params = backend.Params{defaults.BackendPath: filepath.Join(cfg.DataDir, defaults.BackendDir)} cfg.Auth.StaticTokens = services.DefaultStaticTokens() cfg.Auth.ClusterConfig = services.DefaultClusterConfig() defaults.ConfigureLimiter(&cfg.Auth.Limiter) // set new style default auth preferences ap := &services.AuthPreferenceV2{} ap.CheckAndSetDefaults() cfg.Auth.Preference = ap cfg.Auth.LicenseFile = filepath.Join(cfg.DataDir, defaults.LicenseFile) // defaults for the SSH proxy service: cfg.Proxy.Enabled = true cfg.Proxy.SSHAddr = *defaults.ProxyListenAddr() cfg.Proxy.WebAddr = *defaults.ProxyWebListenAddr() cfg.Proxy.ReverseTunnelListenAddr = *defaults.ReverseTunnellListenAddr() defaults.ConfigureLimiter(&cfg.Proxy.Limiter) // defaults for the Kubernetes proxy service cfg.Proxy.Kube.Enabled = false cfg.Proxy.Kube.ListenAddr = *defaults.KubeProxyListenAddr() // defaults for the SSH service: cfg.SSH.Enabled = true cfg.SSH.Addr = *defaults.SSHServerListenAddr() cfg.SSH.Shell = defaults.DefaultShell defaults.ConfigureLimiter(&cfg.SSH.Limiter) cfg.SSH.PAM = &pam.Config{Enabled: false} }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/keepalive.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/keepalive.go#L59-L102
go
train
// StartKeepAliveLoop starts the keep-alive loop.
func StartKeepAliveLoop(p KeepAliveParams)
// StartKeepAliveLoop starts the keep-alive loop. func StartKeepAliveLoop(p KeepAliveParams)
{ var missedCount int64 log := logrus.WithFields(logrus.Fields{ trace.Component: teleport.ComponentKeepAlive, }) log.Debugf("Starting keep-alive loop with with interval %v and max count %v.", p.Interval, p.MaxCount) tickerCh := time.NewTicker(p.Interval) defer tickerCh.Stop() for { select { case <-tickerCh.C: var sentCount int // Send a keep alive message on all connections and make sure a response // was received on all. for _, conn := range p.Conns { ok := sendKeepAliveWithTimeout(conn, defaults.ReadHeadersTimeout, p.CloseContext) if ok { sentCount += 1 } } if sentCount == len(p.Conns) { missedCount = 0 continue } // If enough keep-alives are missed, the connection is dead, call cancel // and notify the server to disconnect and cleanup. missedCount = missedCount + 1 if missedCount > p.MaxCount { log.Infof("Missed %v keep-alive messages, closing connection.", missedCount) p.CloseCancel() return } // If an external caller closed the context (connection is done) then no // more need to wait around for keep-alives. case <-p.CloseContext.Done(): return } } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/keepalive.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/keepalive.go#L107-L127
go
train
// sendKeepAliveWithTimeout sends a [email protected] message to the remote // client. A manual timeout is needed here because SendRequest will wait for a // response forever.
func sendKeepAliveWithTimeout(conn RequestSender, timeout time.Duration, closeContext context.Context) bool
// sendKeepAliveWithTimeout sends a [email protected] message to the remote // client. A manual timeout is needed here because SendRequest will wait for a // response forever. func sendKeepAliveWithTimeout(conn RequestSender, timeout time.Duration, closeContext context.Context) bool
{ errorCh := make(chan error, 1) go func() { // SendRequest will unblock when connection or channel is closed. _, _, err := conn.SendRequest(teleport.KeepAliveReqType, true, nil) errorCh <- err }() select { case err := <-errorCh: if err != nil { return false } return true case <-time.After(timeout): return false case <-closeContext.Done(): return false } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/namespace.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/namespace.go#L31-L41
go
train
// Check checks validity of all parameters and sets defaults
func (n *Namespace) CheckAndSetDefaults() error
// Check checks validity of all parameters and sets defaults func (n *Namespace) CheckAndSetDefaults() error
{ if err := n.Metadata.CheckAndSetDefaults(); err != nil { return trace.Wrap(err) } isValid := IsValidNamespace(n.Metadata.Name) if !isValid { return trace.BadParameter("namespace %q is invalid", n.Metadata.Name) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/namespace.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/namespace.go#L89-L91
go
train
// SetExpiry sets expiry time for the object
func (n *Namespace) SetExpiry(expires time.Time)
// SetExpiry sets expiry time for the object func (n *Namespace) SetExpiry(expires time.Time)
{ n.Metadata.SetExpiry(expires) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/namespace.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/namespace.go#L94-L96
go
train
// SetTTL sets Expires header using realtime clock
func (n *Namespace) SetTTL(clock clockwork.Clock, ttl time.Duration)
// SetTTL sets Expires header using realtime clock func (n *Namespace) SetTTL(clock clockwork.Clock, ttl time.Duration)
{ n.Metadata.SetTTL(clock, ttl) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/namespace.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/namespace.go#L128-L141
go
train
// MarshalNamespace marshals namespace to JSON
func MarshalNamespace(resource Namespace, opts ...MarshalOption) ([]byte, error)
// MarshalNamespace marshals namespace to JSON func MarshalNamespace(resource Namespace, opts ...MarshalOption) ([]byte, error)
{ cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } if !cfg.PreserveResourceID { // avoid modifying the original object // to prevent unexpected data races copy := resource copy.SetResourceID(0) resource = copy } return utils.FastMarshal(resource) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/namespace.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/namespace.go#L145-L174
go
train
// UnmarshalNamespace unmarshals role from JSON or YAML, // sets defaults and checks the schema
func UnmarshalNamespace(data []byte, opts ...MarshalOption) (*Namespace, error)
// UnmarshalNamespace unmarshals role from JSON or YAML, // sets defaults and checks the schema func UnmarshalNamespace(data []byte, opts ...MarshalOption) (*Namespace, error)
{ if len(data) == 0 { return nil, trace.BadParameter("missing namespace data") } cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } // always skip schema validation on namespaces unmarshal // the namespace is always created by teleport now var namespace Namespace if err := utils.FastUnmarshal(data, &namespace); err != nil { return nil, trace.BadParameter(err.Error()) } if err := namespace.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } if cfg.ID != 0 { namespace.Metadata.ID = cfg.ID } if !cfg.Expires.IsZero() { namespace.Metadata.Expires = &cfg.Expires } return &namespace, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/namespace.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/namespace.go#L185-L187
go
train
// Less compares roles by name
func (s SortedNamespaces) Less(i, j int) bool
// Less compares roles by name func (s SortedNamespaces) Less(i, j int) bool
{ return s[i].Metadata.Name < s[j].Metadata.Name }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/namespace.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/namespace.go#L190-L192
go
train
// Swap swaps two roles in a list
func (s SortedNamespaces) Swap(i, j int)
// Swap swaps two roles in a list func (s SortedNamespaces) Swap(i, j int)
{ s[i], s[j] = s[j], s[i] }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/top_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/top_command.go#L55-L60
go
train
// Initialize allows TopCommand to plug itself into the CLI parser.
func (c *TopCommand) Initialize(app *kingpin.Application, config *service.Config)
// Initialize allows TopCommand to plug itself into the CLI parser. func (c *TopCommand) Initialize(app *kingpin.Application, config *service.Config)
{ c.config = config c.top = app.Command("top", "Report diagnostic information") c.diagURL = c.top.Arg("diag-addr", "Diagnostic HTTP URL").Default("http://127.0.0.1:3434").String() c.refreshPeriod = c.top.Arg("refresh", "Refresh period").Default("5s").Duration() }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/top_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/top_command.go#L63-L79
go
train
// TryRun takes the CLI command as an argument (like "nodes ls") and executes it.
func (c *TopCommand) TryRun(cmd string, client auth.ClientI) (match bool, err error)
// TryRun takes the CLI command as an argument (like "nodes ls") and executes it. func (c *TopCommand) TryRun(cmd string, client auth.ClientI) (match bool, err error)
{ switch cmd { case c.top.FullCommand(): diagClient, err := roundtrip.NewClient(*c.diagURL, "") if err != nil { return true, trace.Wrap(err) } err = c.Top(diagClient) if trace.IsConnectionProblem(err) { return true, trace.ConnectionProblem(err, "[CLIENT] Could not connect to metrics service at %v. Is teleport is running with --diag-addr=%v?", *c.diagURL, *c.diagURL) } return true, trace.Wrap(err) default: return false, nil } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/top_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/top_command.go#L82-L133
go
train
// Top is called to execute "status" CLI command.
func (c *TopCommand) Top(client *roundtrip.Client) error
// Top is called to execute "status" CLI command. func (c *TopCommand) Top(client *roundtrip.Client) error
{ if err := ui.Init(); err != nil { return trace.Wrap(err) } defer ui.Close() ctx, cancel := context.WithCancel(context.TODO()) defer cancel() uiEvents := ui.PollEvents() ticker := time.NewTicker(*c.refreshPeriod) defer ticker.Stop() // fetch and render first time var prev *Report re, err := c.fetchAndGenerateReport(ctx, client, nil) if err != nil { return trace.Wrap(err) } lastTab := "" if err := c.render(ctx, *re, lastTab); err != nil { return trace.Wrap(err) } for { select { case e := <-uiEvents: switch e.ID { // event string/identifier case "q", "<C-c>": // press 'q' or 'C-c' to quit return nil } if e.ID == "1" || e.ID == "2" || e.ID == "3" { lastTab = e.ID } // render previously fetched data on the resize event if re != nil { if err := c.render(ctx, *re, lastTab); err != nil { return trace.Wrap(err) } } case <-ticker.C: // fetch data and re-render on ticker prev = re re, err = c.fetchAndGenerateReport(ctx, client, prev) if err != nil { return trace.Wrap(err) } if err := c.render(ctx, *re, lastTab); err != nil { return trace.Wrap(err) } } } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/top_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/top_command.go#L393-L405
go
train
// SortedTopRequests returns top requests sorted either // by frequency if frequency is present, or by count otherwise
func (b *BackendStats) SortedTopRequests() []Request
// SortedTopRequests returns top requests sorted either // by frequency if frequency is present, or by count otherwise func (b *BackendStats) SortedTopRequests() []Request
{ out := make([]Request, 0, len(b.TopRequests)) for _, req := range b.TopRequests { out = append(out, req) } sort.Slice(out, func(i, j int) bool { if out[i].GetFreq() == out[j].GetFreq() { return out[i].Count > out[j].Count } return out[i].GetFreq() > out[j].GetFreq() }) return out }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/top_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/top_command.go#L487-L493
go
train
// SetFreq sets counter frequency based on the previous value // and the time period
func (c *Counter) SetFreq(prevCount Counter, period time.Duration)
// SetFreq sets counter frequency based on the previous value // and the time period func (c *Counter) SetFreq(prevCount Counter, period time.Duration)
{ if period == 0 { return } freq := float64(c.Count-prevCount.Count) / float64(period/time.Second) c.Freq = &freq }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/top_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/top_command.go#L521-L543
go
train
// AsPercentiles interprets historgram as a bucket of percentiles // and returns calculated percentiles
func (h Histogram) AsPercentiles() []Percentile
// AsPercentiles interprets historgram as a bucket of percentiles // and returns calculated percentiles func (h Histogram) AsPercentiles() []Percentile
{ if h.Count == 0 { return nil } var percentiles []Percentile for _, bucket := range h.Buckets { if bucket.Count == 0 { continue } if bucket.Count == h.Count || math.IsInf(bucket.UpperBound, 0) { percentiles = append(percentiles, Percentile{ Percentile: 100, Value: time.Duration(bucket.UpperBound * float64(time.Second)), }) return percentiles } percentiles = append(percentiles, Percentile{ Percentile: 100 * (float64(bucket.Count) / float64(h.Count)), Value: time.Duration(bucket.UpperBound * float64(time.Second)), }) } return percentiles }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/top_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/top_command.go#L636-L643
go
train
// matchesLabelValue returns true if a list of label pairs // matches required name/value pair, used to slice vectors by component
func matchesLabelValue(labels []*dto.LabelPair, name, value string) bool
// matchesLabelValue returns true if a list of label pairs // matches required name/value pair, used to slice vectors by component func matchesLabelValue(labels []*dto.LabelPair, name, value string) bool
{ for _, label := range labels { if label.GetName() == name { return label.GetValue() == value } } return false }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/fixtures/fixtures.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/fixtures/fixtures.go#L13-L15
go
train
// ExpectNotFound expects not found error
func ExpectNotFound(c *check.C, err error)
// ExpectNotFound expects not found error func ExpectNotFound(c *check.C, err error)
{ c.Assert(trace.IsNotFound(err), check.Equals, true, check.Commentf("expected NotFound, got %T %v at %v", trace.Unwrap(err), err, string(debug.Stack()))) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/fixtures/fixtures.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/fixtures/fixtures.go#L18-L20
go
train
// ExpectBadParameter expects bad parameter error
func ExpectBadParameter(c *check.C, err error)
// ExpectBadParameter expects bad parameter error func ExpectBadParameter(c *check.C, err error)
{ c.Assert(trace.IsBadParameter(err), check.Equals, true, check.Commentf("expected BadParameter, got %T %v at %v", trace.Unwrap(err), err, string(debug.Stack()))) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/fixtures/fixtures.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/fixtures/fixtures.go#L23-L25
go
train
// ExpectCompareFailed expects compare failed error
func ExpectCompareFailed(c *check.C, err error)
// ExpectCompareFailed expects compare failed error func ExpectCompareFailed(c *check.C, err error)
{ c.Assert(trace.IsCompareFailed(err), check.Equals, true, check.Commentf("expected CompareFailed, got %T %v at %v", trace.Unwrap(err), err, string(debug.Stack()))) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/fixtures/fixtures.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/fixtures/fixtures.go#L28-L30
go
train
// ExpectAccessDenied expects error to be access denied
func ExpectAccessDenied(c *check.C, err error)
// ExpectAccessDenied expects error to be access denied func ExpectAccessDenied(c *check.C, err error)
{ c.Assert(trace.IsAccessDenied(err), check.Equals, true, check.Commentf("expected AccessDenied, got %T %v at %v", trace.Unwrap(err), err, string(debug.Stack()))) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/fixtures/fixtures.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/fixtures/fixtures.go#L33-L35
go
train
// ExpectAlreadyExists expects already exists error
func ExpectAlreadyExists(c *check.C, err error)
// ExpectAlreadyExists expects already exists error func ExpectAlreadyExists(c *check.C, err error)
{ c.Assert(trace.IsAlreadyExists(err), check.Equals, true, check.Commentf("expected AlreadyExists, got %T %v at %v", trace.Unwrap(err), err, string(debug.Stack()))) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/fixtures/fixtures.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/fixtures/fixtures.go#L38-L40
go
train
// ExpectConnectionProblem expects connection problem error
func ExpectConnectionProblem(c *check.C, err error)
// ExpectConnectionProblem expects connection problem error func ExpectConnectionProblem(c *check.C, err error)
{ c.Assert(trace.IsConnectionProblem(err), check.Equals, true, check.Commentf("expected ConnectionProblem, got %T %v at %v", trace.Unwrap(err), err, string(debug.Stack()))) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/fixtures/fixtures.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/fixtures/fixtures.go#L43-L47
go
train
// DeepCompare uses gocheck DeepEquals but provides nice diff if things are not equal
func DeepCompare(c *check.C, a, b interface{})
// DeepCompare uses gocheck DeepEquals but provides nice diff if things are not equal func DeepCompare(c *check.C, a, b interface{})
{ d := &spew.ConfigState{Indent: " ", DisableMethods: true, DisablePointerMethods: true, DisablePointerAddresses: true} c.Assert(a, check.DeepEquals, b, check.Commentf("%v\nStack:\n%v\n", diff.Diff(d.Sdump(a), d.Sdump(b)), string(debug.Stack()))) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/sshutils/req.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/req.go#L72-L99
go
train
// TerminalModes converts encoded terminal modes into a ssh.TerminalModes map. // The encoding is described in: https://tools.ietf.org/html/rfc4254#section-8 // // All 'encoded terminal modes' (as passed in a pty request) are encoded // into a byte stream. It is intended that the coding be portable // across different environments. The stream consists of opcode- // argument pairs wherein the opcode is a byte value. Opcodes 1 to 159 // have a single uint32 argument. Opcodes 160 to 255 are not yet // defined, and cause parsing to stop (they should only be used after // any other data). The stream is terminated by opcode TTY_OP_END // (0x00). // // In practice, this means encoded terminal modes get translated like below: // // 0x80 0x00 0x00 0x38 0x40 0x81 0x00 0x00 0x38 0x40 0x35 0x00 0x00 0x00 0x00 0x00 // |___|__________________| |___|__________________| |___|__________________| |__| // 0x80: 0x3840 0x81: 0x3840 0x35: 0x00 0x00 // ssh.TTY_OP_ISPEED: 14400 ssh.TTY_OP_OSPEED: 14400 ssh.ECHO:0 //
func (p *PTYReqParams) TerminalModes() (ssh.TerminalModes, error)
// TerminalModes converts encoded terminal modes into a ssh.TerminalModes map. // The encoding is described in: https://tools.ietf.org/html/rfc4254#section-8 // // All 'encoded terminal modes' (as passed in a pty request) are encoded // into a byte stream. It is intended that the coding be portable // across different environments. The stream consists of opcode- // argument pairs wherein the opcode is a byte value. Opcodes 1 to 159 // have a single uint32 argument. Opcodes 160 to 255 are not yet // defined, and cause parsing to stop (they should only be used after // any other data). The stream is terminated by opcode TTY_OP_END // (0x00). // // In practice, this means encoded terminal modes get translated like below: // // 0x80 0x00 0x00 0x38 0x40 0x81 0x00 0x00 0x38 0x40 0x35 0x00 0x00 0x00 0x00 0x00 // |___|__________________| |___|__________________| |___|__________________| |__| // 0x80: 0x3840 0x81: 0x3840 0x35: 0x00 0x00 // ssh.TTY_OP_ISPEED: 14400 ssh.TTY_OP_OSPEED: 14400 ssh.ECHO:0 // func (p *PTYReqParams) TerminalModes() (ssh.TerminalModes, error)
{ terminalModes := ssh.TerminalModes{} if len(p.Modes) == 1 && p.Modes[0] == 0 { return terminalModes, nil } chunkSize := 5 for i := 0; i < len(p.Modes); i = i + chunkSize { // the first byte of the chunk is the key key := uint8(p.Modes[i]) // a key with value 0 means is the termination of the stream if key == 0 { break } // the remaining 4 bytes of the chunk are the value if i+chunkSize > len(p.Modes) { return nil, trace.BadParameter("invalid terminal modes encoding") } value := binary.BigEndian.Uint32([]byte(p.Modes[i+1 : i+chunkSize])) terminalModes[key] = value } return terminalModes, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/sshutils/req.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/req.go#L102-L111
go
train
// Check validates PTY parameters.
func (p *PTYReqParams) Check() error
// Check validates PTY parameters. func (p *PTYReqParams) Check() error
{ if p.W > maxSize || p.W < minSize { return trace.BadParameter("bad width: %v", p.W) } if p.H > maxSize || p.H < minSize { return trace.BadParameter("bad height: %v", p.H) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/sshutils/req.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/req.go#L115-L124
go
train
// CheckAndSetDefaults validates PTY parameters and ensures parameters // are within default values.
func (p *PTYReqParams) CheckAndSetDefaults() error
// CheckAndSetDefaults validates PTY parameters and ensures parameters // are within default values. func (p *PTYReqParams) CheckAndSetDefaults() error
{ if p.W > maxSize || p.W < minSize { p.W = teleport.DefaultTerminalWidth } if p.H > maxSize || p.H < minSize { p.H = teleport.DefaultTerminalHeight } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/kube/proxy/portforward.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/portforward.go#L101-L132
go
train
// httpStreamReceived is the httpstream.NewStreamHandler for port // forward streams. It checks each stream's port and stream type headers, // rejecting any streams that with missing or invalid values. Each valid // stream is sent to the streams channel.
func httpStreamReceived(ctx context.Context, streams chan httpstream.Stream) func(httpstream.Stream, <-chan struct{}) error
// httpStreamReceived is the httpstream.NewStreamHandler for port // forward streams. It checks each stream's port and stream type headers, // rejecting any streams that with missing or invalid values. Each valid // stream is sent to the streams channel. func httpStreamReceived(ctx context.Context, streams chan httpstream.Stream) func(httpstream.Stream, <-chan struct{}) error
{ return func(stream httpstream.Stream, replySent <-chan struct{}) error { // make sure it has a valid port header portString := stream.Headers().Get(PortHeader) if len(portString) == 0 { return trace.BadParameter("%q header is required", PortHeader) } port, err := strconv.ParseUint(portString, 10, 16) if err != nil { return trace.BadParameter("unable to parse %q as a port: %v", portString, err) } if port < 1 { return trace.BadParameter("port %q must be > 0", portString) } // make sure it has a valid stream type header streamType := stream.Headers().Get(StreamType) if len(streamType) == 0 { return trace.BadParameter("%q header is required", StreamType) } if streamType != StreamTypeError && streamType != StreamTypeData { return trace.BadParameter("invalid stream type %q", streamType) } select { case streams <- stream: return nil case <-ctx.Done(): return trace.BadParameter("request has been cancelled") } } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/kube/proxy/portforward.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/portforward.go#L242-L257
go
train
// getStreamPair returns a httpStreamPair for requestID. This creates a // new pair if one does not yet exist for the requestID. The returned bool is // true if the pair was created.
func (h *portForwardProxy) getStreamPair(requestID string) (*httpStreamPair, bool)
// getStreamPair returns a httpStreamPair for requestID. This creates a // new pair if one does not yet exist for the requestID. The returned bool is // true if the pair was created. func (h *portForwardProxy) getStreamPair(requestID string) (*httpStreamPair, bool)
{ h.streamPairsLock.Lock() defer h.streamPairsLock.Unlock() if p, ok := h.streamPairs[requestID]; ok { log.Infof("(conn=%p, request=%s) found existing stream pair", h.sourceConn, requestID) return p, false } log.Infof("(conn=%p, request=%s) creating new stream pair", h.sourceConn, requestID) p := newPortForwardPair(requestID) h.streamPairs[requestID] = p return p, true }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/kube/proxy/portforward.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/portforward.go#L262-L271
go
train
// monitorStreamPair waits for the pair to receive both its error and data // streams, or for the timeout to expire (whichever happens first), and then // removes the pair.
func (h *portForwardProxy) monitorStreamPair(p *httpStreamPair, timeout <-chan time.Time)
// monitorStreamPair waits for the pair to receive both its error and data // streams, or for the timeout to expire (whichever happens first), and then // removes the pair. func (h *portForwardProxy) monitorStreamPair(p *httpStreamPair, timeout <-chan time.Time)
{ select { case <-timeout: err := fmt.Errorf("(conn=%v, request=%s) timed out waiting for streams", h.sourceConn, p.requestID) p.printError(err.Error()) case <-p.complete: log.Infof("(conn=%v, request=%s) successfully received error and data streams", h.sourceConn, p.requestID) } h.removeStreamPair(p.requestID) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/kube/proxy/portforward.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/portforward.go#L284-L289
go
train
// removeStreamPair removes the stream pair identified by requestID from streamPairs.
func (h *portForwardProxy) removeStreamPair(requestID string)
// removeStreamPair removes the stream pair identified by requestID from streamPairs. func (h *portForwardProxy) removeStreamPair(requestID string)
{ h.streamPairsLock.Lock() defer h.streamPairsLock.Unlock() delete(h.streamPairs, requestID) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/kube/proxy/portforward.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/portforward.go#L292-L298
go
train
// requestID returns the request id for stream.
func (h *portForwardProxy) requestID(stream httpstream.Stream) (string, error)
// requestID returns the request id for stream. func (h *portForwardProxy) requestID(stream httpstream.Stream) (string, error)
{ requestID := stream.Headers().Get(PortForwardRequestIDHeader) if len(requestID) == 0 { return "", trace.BadParameter("port forwarding is not supported") } return requestID, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/kube/proxy/portforward.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/portforward.go#L303-L334
go
train
// run is the main loop for the portForwardProxy. It processes new // streams, invoking portForward for each complete stream pair. The loop exits // when the httpstream.Connection is closed.
func (h *portForwardProxy) run()
// run is the main loop for the portForwardProxy. It processes new // streams, invoking portForward for each complete stream pair. The loop exits // when the httpstream.Connection is closed. func (h *portForwardProxy) run()
{ h.Debugf("Waiting for port forward streams.") for { select { case <-h.context.Done(): h.Debugf("Context is closing, returning.") return case <-h.sourceConn.CloseChan(): h.Debugf("Upgraded connection closed.") return case stream := <-h.streamChan: requestID, err := h.requestID(stream) if err != nil { h.Warningf("Failed to parse request id: %v.", err) return } streamType := stream.Headers().Get(StreamType) h.Debugf("Received new stream %v of type %v.", requestID, streamType) p, created := h.getStreamPair(requestID) if created { go h.monitorStreamPair(p, time.After(h.streamCreationTimeout)) } if complete, err := p.add(stream); err != nil { msg := fmt.Sprintf("error processing stream for request %s: %v", requestID, err) p.printError(msg) } else if complete { go h.portForward(p) } } } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/kube/proxy/portforward.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/portforward.go#L338-L353
go
train
// portForward invokes the portForwardProxy's forwarder.PortForward // function for the given stream pair.
func (h *portForwardProxy) portForward(p *httpStreamPair)
// portForward invokes the portForwardProxy's forwarder.PortForward // function for the given stream pair. func (h *portForwardProxy) portForward(p *httpStreamPair)
{ defer p.dataStream.Close() defer p.errorStream.Close() portString := p.dataStream.Headers().Get(PortHeader) port, _ := strconv.ParseInt(portString, 10, 32) h.Debugf("Forwrarding port %v -> %v.", p.requestID, portString) err := h.forwardStreamPair(p, port) h.Debugf("Completed forwrarding port %v -> %v.", p.requestID, portString) if err != nil { msg := fmt.Errorf("error forwarding port %d to pod %s: %v", port, h.podName, err) fmt.Fprint(p.errorStream, msg.Error()) } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/kube/proxy/portforward.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/portforward.go#L377-L399
go
train
// add adds the stream to the httpStreamPair. If the pair already // contains a stream for the new stream's type, an error is returned. add // returns true if both the data and error streams for this pair have been // received.
func (p *httpStreamPair) add(stream httpstream.Stream) (bool, error)
// add adds the stream to the httpStreamPair. If the pair already // contains a stream for the new stream's type, an error is returned. add // returns true if both the data and error streams for this pair have been // received. func (p *httpStreamPair) add(stream httpstream.Stream) (bool, error)
{ p.lock.Lock() defer p.lock.Unlock() switch stream.Headers().Get(StreamType) { case StreamTypeError: if p.errorStream != nil { return false, trace.BadParameter("error stream already assigned") } p.errorStream = stream case StreamTypeData: if p.dataStream != nil { return false, trace.BadParameter("data stream already assigned") } p.dataStream = stream } complete := p.errorStream != nil && p.dataStream != nil if complete { close(p.complete) } return complete, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/replace.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/replace.go#L30-L47
go
train
// ReplaceRegexp replaces value in string, accepts regular expression and simplified // wildcard syntax, it has several important differeneces with standard lib // regexp replacer: // * Wildcard globs '*' are treated as regular expression .* expression // * Expression is treated as regular expression if it starts with ^ and ends with $ // * Full match is expected, partial replacements ignored // * If there is no match, returns not found error
func ReplaceRegexp(expression string, replaceWith string, input string) (string, error)
// ReplaceRegexp replaces value in string, accepts regular expression and simplified // wildcard syntax, it has several important differeneces with standard lib // regexp replacer: // * Wildcard globs '*' are treated as regular expression .* expression // * Expression is treated as regular expression if it starts with ^ and ends with $ // * Full match is expected, partial replacements ignored // * If there is no match, returns not found error func ReplaceRegexp(expression string, replaceWith string, input string) (string, error)
{ if !strings.HasPrefix(expression, "^") || !strings.HasSuffix(expression, "$") { // replace glob-style wildcards with regexp wildcards // for plain strings, and quote all characters that could // be interpreted in regular expression expression = "^" + GlobToRegexp(expression) + "$" } expr, err := regexp.Compile(expression) if err != nil { return "", trace.BadParameter(err.Error()) } // if there is no match, return NotFound error index := expr.FindAllStringIndex(input, -1) if len(index) == 0 { return "", trace.NotFound("no match found") } return expr.ReplaceAllString(input, replaceWith), nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/replace.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/replace.go#L51-L74
go
train
// SliceMatchesRegex checks if input matches any of the expressions. The // match is always evaluated as a regex either an exact match or regexp.
func SliceMatchesRegex(input string, expressions []string) (bool, error)
// SliceMatchesRegex checks if input matches any of the expressions. The // match is always evaluated as a regex either an exact match or regexp. func SliceMatchesRegex(input string, expressions []string) (bool, error)
{ for _, expression := range expressions { if !strings.HasPrefix(expression, "^") || !strings.HasSuffix(expression, "$") { // replace glob-style wildcards with regexp wildcards // for plain strings, and quote all characters that could // be interpreted in regular expression expression = "^" + GlobToRegexp(expression) + "$" } expr, err := regexp.Compile(expression) if err != nil { return false, trace.BadParameter(err.Error()) } // Since the expression is always surrounded by ^ and $ this is an exact // match for either a a plain string (for example ^hello$) or for a regexp // (for example ^hel*o$). if expr.MatchString(input) { return true, nil } } return false, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/state.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/state.go#L44-L61
go
train
// NewProcessStorage returns a new instance of the process storage.
func NewProcessStorage(ctx context.Context, path string) (*ProcessStorage, error)
// NewProcessStorage returns a new instance of the process storage. func NewProcessStorage(ctx context.Context, path string) (*ProcessStorage, error)
{ if path == "" { return nil, trace.BadParameter("missing parameter path") } litebk, err := lite.NewWithConfig(ctx, lite.Config{Path: path, EventsOff: true}) if err != nil { return nil, trace.Wrap(err) } // Import storage data err = legacy.Import(ctx, litebk, func() (legacy.Exporter, error) { return dir.New(legacy.Params{"path": path}) }) if err != nil { return nil, trace.Wrap(err) } return &ProcessStorage{Backend: litebk}, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/state.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/state.go#L84-L94
go
train
// GetState reads rotation state from disk.
func (p *ProcessStorage) GetState(role teleport.Role) (*StateV2, error)
// GetState reads rotation state from disk. func (p *ProcessStorage) GetState(role teleport.Role) (*StateV2, error)
{ item, err := p.Get(context.TODO(), backend.Key(statesPrefix, strings.ToLower(role.String()), stateName)) if err != nil { return nil, trace.Wrap(err) } var res StateV2 if err := utils.UnmarshalWithSchema(GetStateSchema(), &res, item.Value); err != nil { return nil, trace.BadParameter(err.Error()) } return &res, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/state.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/state.go#L97-L114
go
train
// CreateState creates process state if it does not exist yet.
func (p *ProcessStorage) CreateState(role teleport.Role, state StateV2) error
// CreateState creates process state if it does not exist yet. func (p *ProcessStorage) CreateState(role teleport.Role, state StateV2) error
{ if err := state.CheckAndSetDefaults(); err != nil { return trace.Wrap(err) } value, err := json.Marshal(state) if err != nil { return trace.Wrap(err) } item := backend.Item{ Key: backend.Key(statesPrefix, strings.ToLower(role.String()), stateName), Value: value, } _, err = p.Create(context.TODO(), item) if err != nil { return trace.Wrap(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/state.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/state.go#L137-L156
go
train
// ReadIdentity reads identity using identity name and role.
func (p *ProcessStorage) ReadIdentity(name string, role teleport.Role) (*Identity, error)
// ReadIdentity reads identity using identity name and role. func (p *ProcessStorage) ReadIdentity(name string, role teleport.Role) (*Identity, error)
{ if name == "" { return nil, trace.BadParameter("missing parameter name") } item, err := p.Get(context.TODO(), backend.Key(idsPrefix, strings.ToLower(role.String()), name)) if err != nil { return nil, trace.Wrap(err) } var res IdentityV2 if err := utils.UnmarshalWithSchema(GetIdentitySchema(), &res, item.Value); err != nil { return nil, trace.BadParameter(err.Error()) } return ReadIdentityFromKeyPair(&PackedKeys{ Key: res.Spec.Key, Cert: res.Spec.SSHCert, TLSCert: res.Spec.TLSCert, TLSCACerts: res.Spec.TLSCACerts, SSHCACerts: res.Spec.SSHCACerts, }) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/state.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/state.go#L159-L189
go
train
// WriteIdentity writes identity to the backend.
func (p *ProcessStorage) WriteIdentity(name string, id Identity) error
// WriteIdentity writes identity to the backend. func (p *ProcessStorage) WriteIdentity(name string, id Identity) error
{ res := IdentityV2{ ResourceHeader: services.ResourceHeader{ Kind: services.KindIdentity, Version: services.V2, Metadata: services.Metadata{ Name: name, }, }, Spec: IdentitySpecV2{ Key: id.KeyBytes, SSHCert: id.CertBytes, TLSCert: id.TLSCertBytes, TLSCACerts: id.TLSCACertsBytes, SSHCACerts: id.SSHCACertBytes, }, } if err := res.CheckAndSetDefaults(); err != nil { return trace.Wrap(err) } value, err := json.Marshal(res) if err != nil { return trace.Wrap(err) } item := backend.Item{ Key: backend.Key(idsPrefix, strings.ToLower(id.ID.Role.String()), name), Value: value, } _, err = p.Put(context.TODO(), item) return trace.Wrap(err) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/state.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/state.go#L200-L211
go
train
// CheckAndSetDefaults checks and sets defaults values.
func (s *StateV2) CheckAndSetDefaults() error
// CheckAndSetDefaults checks and sets defaults values. func (s *StateV2) CheckAndSetDefaults() error
{ s.Kind = services.KindState s.Version = services.V2 // for state resource name does not matter if s.Metadata.Name == "" { s.Metadata.Name = stateName } if err := s.Metadata.CheckAndSetDefaults(); err != nil { return trace.Wrap(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/state.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/state.go#L228-L250
go
train
// CheckAndSetDefaults checks and sets defaults values.
func (s *IdentityV2) CheckAndSetDefaults() error
// CheckAndSetDefaults checks and sets defaults values. func (s *IdentityV2) CheckAndSetDefaults() error
{ s.Kind = services.KindIdentity s.Version = services.V2 if err := s.Metadata.CheckAndSetDefaults(); err != nil { return trace.Wrap(err) } if len(s.Spec.Key) == 0 { return trace.BadParameter("missing parameter Key") } if len(s.Spec.SSHCert) == 0 { return trace.BadParameter("missing parameter SSHCert") } if len(s.Spec.TLSCert) == 0 { return trace.BadParameter("missing parameter TLSCert") } if len(s.Spec.TLSCACerts) == 0 { return trace.BadParameter("missing parameter TLSCACerts") } if len(s.Spec.SSHCACerts) == 0 { return trace.BadParameter("missing parameter SSH CA bytes") } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/state.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/state.go#L289-L291
go
train
// GetIdentitySchema returns JSON Schema for cert authorities.
func GetIdentitySchema() string
// GetIdentitySchema returns JSON Schema for cert authorities. func GetIdentitySchema() string
{ return fmt.Sprintf(services.V2SchemaTemplate, services.MetadataSchema, IdentitySpecV2Schema, services.DefaultDefinitions) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/state.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/state.go#L304-L306
go
train
// GetStateSchema returns JSON Schema for cert authorities.
func GetStateSchema() string
// GetStateSchema returns JSON Schema for cert authorities. func GetStateSchema() string
{ return fmt.Sprintf(services.V2SchemaTemplate, services.MetadataSchema, fmt.Sprintf(StateSpecV2Schema, services.RotationSchema), services.DefaultDefinitions) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/api.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/api.go#L251-L257
go
train
// String returns a string representation of an event structure
func (f EventFields) AsString() string
// String returns a string representation of an event structure func (f EventFields) AsString() string
{ return fmt.Sprintf("%s: login=%s, id=%v, bytes=%v", f.GetString(EventType), f.GetString(EventLogin), f.GetInt(EventCursor), f.GetInt(SessionPrintEventBytes)) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/api.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/api.go#L280-L287
go
train
// GetString returns a string representation of a logged field
func (f EventFields) GetString(key string) string
// GetString returns a string representation of a logged field func (f EventFields) GetString(key string) string
{ val, found := f[key] if !found { return "" } v, _ := val.(string) return v }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/api.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/api.go#L290-L303
go
train
// GetString returns an int representation of a logged field
func (f EventFields) GetInt(key string) int
// GetString returns an int representation of a logged field func (f EventFields) GetInt(key string) int
{ val, found := f[key] if !found { return 0 } v, ok := val.(int) if !ok { f, ok := val.(float64) if ok { v = int(f) } } return v }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/api.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/api.go#L306-L317
go
train
// GetString returns an int representation of a logged field
func (f EventFields) GetTime(key string) time.Time
// GetString returns an int representation of a logged field func (f EventFields) GetTime(key string) time.Time
{ val, found := f[key] if !found { return time.Time{} } v, ok := val.(time.Time) if !ok { s := f.GetString(key) v, _ = time.Parse(time.RFC3339, s) } return v }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/kube/proxy/remotecommand.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/remotecommand.go#L311-L317
go
train
// waitStreamReply waits until either replySent or stop is closed. If replySent is closed, it sends // an empty struct to the notify channel.
func waitStreamReply(ctx context.Context, replySent <-chan struct{}, notify chan<- struct{})
// waitStreamReply waits until either replySent or stop is closed. If replySent is closed, it sends // an empty struct to the notify channel. func waitStreamReply(ctx context.Context, replySent <-chan struct{}, notify chan<- struct{})
{ select { case <-replySent: notify <- struct{}{} case <-ctx.Done(): } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/fs.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/fs.go#L36-L56
go
train
// EnsureLocalPath makes sure the path exists, or, if omitted results in the subpath in // default gravity config directory, e.g. // // EnsureLocalPath("/custom/myconfig", ".gravity", "config") -> /custom/myconfig // EnsureLocalPath("", ".gravity", "config") -> ${HOME}/.gravity/config // // It also makes sure that base dir exists
func EnsureLocalPath(customPath string, defaultLocalDir, defaultLocalPath string) (string, error)
// EnsureLocalPath makes sure the path exists, or, if omitted results in the subpath in // default gravity config directory, e.g. // // EnsureLocalPath("/custom/myconfig", ".gravity", "config") -> /custom/myconfig // EnsureLocalPath("", ".gravity", "config") -> ${HOME}/.gravity/config // // It also makes sure that base dir exists func EnsureLocalPath(customPath string, defaultLocalDir, defaultLocalPath string) (string, error)
{ if customPath == "" { homeDir := getHomeDir() if homeDir == "" { return "", trace.BadParameter("no path provided and environment variable %v is not not set", teleport.EnvHome) } customPath = filepath.Join(homeDir, defaultLocalDir, defaultLocalPath) } baseDir := filepath.Dir(customPath) _, err := StatDir(baseDir) if err != nil { if trace.IsNotFound(err) { if err := MkdirAll(baseDir, teleport.PrivateDirMode); err != nil { return "", trace.Wrap(err) } } else { return "", trace.Wrap(err) } } return customPath, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/fs.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/fs.go#L59-L65
go
train
// MkdirAll creates directory and subdirectories
func MkdirAll(targetDirectory string, mode os.FileMode) error
// MkdirAll creates directory and subdirectories func MkdirAll(targetDirectory string, mode os.FileMode) error
{ err := os.MkdirAll(targetDirectory, mode) if err != nil { return trace.ConvertSystemError(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/fs.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/fs.go#L74-L76
go
train
// Close removes directory and all it's contents
func (r *RemoveDirCloser) Close() error
// Close removes directory and all it's contents func (r *RemoveDirCloser) Close() error
{ return trace.ConvertSystemError(os.RemoveAll(r.Path)) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/fs.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/fs.go#L79-L85
go
train
// IsFile returns true if a given file path points to an existing file
func IsFile(fp string) bool
// IsFile returns true if a given file path points to an existing file func IsFile(fp string) bool
{ fi, err := os.Stat(fp) if err == nil { return !fi.IsDir() } return false }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/fs.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/fs.go#L88-L94
go
train
// IsDir is a helper function to quickly check if a given path is a valid directory
func IsDir(dirPath string) bool
// IsDir is a helper function to quickly check if a given path is a valid directory func IsDir(dirPath string) bool
{ fi, err := os.Stat(dirPath) if err == nil { return fi.IsDir() } return false }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/fs.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/fs.go#L100-L113
go
train
// ReadAll is similarl to ioutil.ReadAll, except it doesn't use ever-increasing // internal buffer, instead asking for the exact buffer size. // // This is useful when you want to limit the sze of Read/Writes (websockets)
func ReadAll(r io.Reader, bufsize int) (out []byte, err error)
// ReadAll is similarl to ioutil.ReadAll, except it doesn't use ever-increasing // internal buffer, instead asking for the exact buffer size. // // This is useful when you want to limit the sze of Read/Writes (websockets) func ReadAll(r io.Reader, bufsize int) (out []byte, err error)
{ buff := make([]byte, bufsize) n := 0 for err == nil { n, err = r.Read(buff) if n > 0 { out = append(out, buff[:n]...) } } if err == io.EOF { err = nil } return out, err }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/fs.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/fs.go#L117-L127
go
train
// NormalizePath normalises path, evaluating symlinks and converting local // paths to absolute
func NormalizePath(path string) (string, error)
// NormalizePath normalises path, evaluating symlinks and converting local // paths to absolute func NormalizePath(path string) (string, error)
{ s, err := filepath.Abs(path) if err != nil { return "", trace.ConvertSystemError(err) } abs, err := filepath.EvalSymlinks(s) if err != nil { return "", trace.ConvertSystemError(err) } return abs, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/fs.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/fs.go#L130-L147
go
train
// OpenFile opens file and returns file handle
func OpenFile(path string) (*os.File, error)
// OpenFile opens file and returns file handle func OpenFile(path string) (*os.File, error)
{ newPath, err := NormalizePath(path) if err != nil { return nil, trace.Wrap(err) } fi, err := os.Stat(newPath) if err != nil { return nil, trace.ConvertSystemError(err) } if fi.IsDir() { return nil, trace.BadParameter("%v is not a file", path) } f, err := os.Open(newPath) if err != nil { return nil, trace.ConvertSystemError(err) } return f, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/fs.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/fs.go#L150-L159
go
train
// StatDir stats directory, returns error if file exists, but not a directory
func StatDir(path string) (os.FileInfo, error)
// StatDir stats directory, returns error if file exists, but not a directory func StatDir(path string) (os.FileInfo, error)
{ fi, err := os.Stat(path) if err != nil { return nil, trace.ConvertSystemError(err) } if !fi.IsDir() { return nil, trace.BadParameter("%v is not a directory", path) } return fi, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/fs.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/fs.go#L162-L172
go
train
// getHomeDir returns the home directory based off the OS.
func getHomeDir() string
// getHomeDir returns the home directory based off the OS. func getHomeDir() string
{ switch runtime.GOOS { case teleport.LinuxOS: return os.Getenv(teleport.EnvHome) case teleport.DarwinOS: return os.Getenv(teleport.EnvHome) case teleport.WindowsOS: return os.Getenv(teleport.EnvUserProfile) } return "" }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/listener.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/listener.go#L11-L19
go
train
// GetListenerFile returns file associated with listener
func GetListenerFile(listener net.Listener) (*os.File, error)
// GetListenerFile returns file associated with listener func GetListenerFile(listener net.Listener) (*os.File, error)
{ switch t := listener.(type) { case *net.TCPListener: return t.File() case *net.UnixListener: return t.File() } return nil, trace.BadParameter("unsupported listener: %T", listener) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/buf.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/buf.go#L25-L36
go
train
// NewSyncBuffer returns new in memory buffer
func NewSyncBuffer() *SyncBuffer
// NewSyncBuffer returns new in memory buffer func NewSyncBuffer() *SyncBuffer
{ reader, writer := io.Pipe() buf := &bytes.Buffer{} go func() { io.Copy(buf, reader) }() return &SyncBuffer{ reader: reader, writer: writer, buf: buf, } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/buf.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/buf.go#L65-L72
go
train
// Close closes reads and writes on the buffer
func (b *SyncBuffer) Close() error
// Close closes reads and writes on the buffer func (b *SyncBuffer) Close() error
{ err := b.reader.Close() err2 := b.writer.Close() if err != nil { return err } return err2 }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/reversetunnel/agent.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/agent.go#L97-L120
go
train
// CheckAndSetDefaults checks parameters and sets default values
func (a *AgentConfig) CheckAndSetDefaults() error
// CheckAndSetDefaults checks parameters and sets default values func (a *AgentConfig) CheckAndSetDefaults() error
{ if a.Addr.IsEmpty() { return trace.BadParameter("missing parameter Addr") } if a.Context == nil { return trace.BadParameter("missing parameter Context") } if a.Client == nil { return trace.BadParameter("missing parameter Client") } if a.AccessPoint == nil { return trace.BadParameter("missing parameter AccessPoint") } if len(a.Signers) == 0 { return trace.BadParameter("missing parameter Signers") } if len(a.Username) == 0 { return trace.BadParameter("missing parameter Username") } if a.Clock == nil { a.Clock = clockwork.NewRealClock() } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/reversetunnel/agent.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/agent.go#L150-L174
go
train
// NewAgent returns a new reverse tunnel agent
func NewAgent(cfg AgentConfig) (*Agent, error)
// NewAgent returns a new reverse tunnel agent func NewAgent(cfg AgentConfig) (*Agent, error)
{ if err := cfg.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } ctx, cancel := context.WithCancel(cfg.Context) a := &Agent{ AgentConfig: cfg, ctx: ctx, cancel: cancel, authMethods: []ssh.AuthMethod{ssh.PublicKeys(cfg.Signers...)}, } if len(cfg.DiscoverProxies) == 0 { a.state = agentStateConnecting } else { a.state = agentStateDiscovering } a.Entry = log.WithFields(log.Fields{ trace.Component: teleport.ComponentReverseTunnelAgent, trace.ComponentFields: log.Fields{ "target": cfg.Addr.String(), }, }) a.hostKeyCallback = a.checkHostSignature return a, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/reversetunnel/agent.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/agent.go#L230-L237
go
train
// connectedTo returns true if connected services.Server passed in.
func (a *Agent) connectedTo(proxy services.Server) bool
// connectedTo returns true if connected services.Server passed in. func (a *Agent) connectedTo(proxy services.Server) bool
{ principals := a.getPrincipals() proxyID := fmt.Sprintf("%v.%v", proxy.GetName(), a.ClusterName) if _, ok := principals[proxyID]; ok { return true } return false }