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/web/apiserver.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/apiserver.go#L1153-L1165 | go | train | // renderUserInvite is called to show user the new user invitation page
//
// GET /v1/webapi/users/invites/:token
//
// Response:
//
// {"invite_token": "token", "user": "alex", qr: "base64-encoded-qr-code image"}
//
// | func (h *Handler) renderUserInvite(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) | // renderUserInvite is called to show user the new user invitation page
//
// GET /v1/webapi/users/invites/:token
//
// Response:
//
// {"invite_token": "token", "user": "alex", qr: "base64-encoded-qr-code image"}
//
//
func (h *Handler) renderUserInvite(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) | {
token := p[0].Value
user, qrCodeBytes, err := h.auth.GetUserInviteInfo(token)
if err != nil {
return nil, trace.Wrap(err)
}
return &renderUserInviteResponse{
InviteToken: token,
User: user,
QR: qrCodeBytes,
}, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/apiserver.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/apiserver.go#L1175-L1183 | go | train | // u2fRegisterRequest is called to get a U2F challenge for registering a U2F key
//
// GET /webapi/u2f/signuptokens/:token
//
// Response:
//
// {"version":"U2F_V2","challenge":"randombase64string","appId":"https://mycorp.com:3080"}
// | func (h *Handler) u2fRegisterRequest(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) | // u2fRegisterRequest is called to get a U2F challenge for registering a U2F key
//
// GET /webapi/u2f/signuptokens/:token
//
// Response:
//
// {"version":"U2F_V2","challenge":"randombase64string","appId":"https://mycorp.com:3080"}
//
func (h *Handler) u2fRegisterRequest(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) | {
token := p[0].Value
u2fRegisterRequest, err := h.auth.GetUserInviteU2FRegisterRequest(token)
if err != nil {
return nil, trace.Wrap(err)
}
return u2fRegisterRequest, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/apiserver.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/apiserver.go#L1195-L1206 | go | train | // u2fSignRequest is called to get a U2F challenge for authenticating
//
// POST /webapi/u2f/signrequest
//
// {"user": "alex", "pass": "abc123"}
//
// Successful response:
//
// {"version":"U2F_V2","challenge":"randombase64string","keyHandle":"longbase64string","appId":"https://mycorp.com:3080"}
// | func (h *Handler) u2fSignRequest(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) | // u2fSignRequest is called to get a U2F challenge for authenticating
//
// POST /webapi/u2f/signrequest
//
// {"user": "alex", "pass": "abc123"}
//
// Successful response:
//
// {"version":"U2F_V2","challenge":"randombase64string","keyHandle":"longbase64string","appId":"https://mycorp.com:3080"}
//
func (h *Handler) u2fSignRequest(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) | {
var req *client.U2fSignRequestReq
if err := httplib.ReadJSON(r, &req); err != nil {
return nil, trace.Wrap(err)
}
u2fSignReq, err := h.auth.GetU2FSignRequest(req.User, req.Pass)
if err != nil {
return nil, trace.AccessDenied("bad auth credentials")
}
return u2fSignReq, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/apiserver.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/apiserver.go#L1224-L1242 | go | train | // createSessionWithU2FSignResponse is called to sign in with a U2F signature
//
// POST /webapi/u2f/session
//
// {"user": "alex", "u2f_sign_response": { "signatureData": "signatureinbase64", "clientData": "verylongbase64string", "challenge": "randombase64string" }}
//
// Successful response:
//
// {"type": "bearer", "token": "bearer token", "user": {"name": "alex", "allowed_logins": ["admin", "bob"]}, "expires_in": 20}
// | func (h *Handler) createSessionWithU2FSignResponse(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) | // createSessionWithU2FSignResponse is called to sign in with a U2F signature
//
// POST /webapi/u2f/session
//
// {"user": "alex", "u2f_sign_response": { "signatureData": "signatureinbase64", "clientData": "verylongbase64string", "challenge": "randombase64string" }}
//
// Successful response:
//
// {"type": "bearer", "token": "bearer token", "user": {"name": "alex", "allowed_logins": ["admin", "bob"]}, "expires_in": 20}
//
func (h *Handler) createSessionWithU2FSignResponse(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) | {
var req *u2fSignResponseReq
if err := httplib.ReadJSON(r, &req); err != nil {
return nil, trace.Wrap(err)
}
sess, err := h.auth.AuthWithU2FSignResponse(req.User, &req.U2FSignResponse)
if err != nil {
return nil, trace.AccessDenied("bad auth credentials")
}
if err := SetSession(w, req.User, sess.GetName()); err != nil {
return nil, trace.Wrap(err)
}
ctx, err := h.auth.ValidateSession(req.User, sess.GetName())
if err != nil {
return nil, trace.AccessDenied("need auth")
}
return NewSessionResponse(ctx)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/apiserver.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/apiserver.go#L1260-L1277 | go | train | // createNewUser creates new user entry based on the invite token
//
// POST /v1/webapi/users
//
// {"invite_token": "unique invite token", "pass": "user password", "second_factor_token": "valid second factor token"}
//
// Successful response: (session cookie is set)
//
// {"type": "bearer", "token": "bearer token", "user": "alex", "expires_in": 20} | func (h *Handler) createNewUser(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) | // createNewUser creates new user entry based on the invite token
//
// POST /v1/webapi/users
//
// {"invite_token": "unique invite token", "pass": "user password", "second_factor_token": "valid second factor token"}
//
// Successful response: (session cookie is set)
//
// {"type": "bearer", "token": "bearer token", "user": "alex", "expires_in": 20}
func (h *Handler) createNewUser(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) | {
var req *createNewUserReq
if err := httplib.ReadJSON(r, &req); err != nil {
return nil, trace.Wrap(err)
}
sess, err := h.auth.CreateNewUser(req.InviteToken, req.Pass, req.SecondFactorToken)
if err != nil {
return nil, trace.Wrap(err)
}
ctx, err := h.auth.ValidateSession(sess.GetUser(), sess.GetName())
if err != nil {
return nil, trace.Wrap(err)
}
if err := SetSession(w, sess.GetUser(), sess.GetName()); err != nil {
return nil, trace.Wrap(err)
}
return NewSessionResponse(ctx)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/apiserver.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/apiserver.go#L1295-L1312 | go | train | // createNewU2FUser creates a new user configured to use U2F as the second factor
//
// POST /webapi/u2f/users
//
// {"invite_token": "unique invite token", "pass": "user password", "u2f_register_response": {"registrationData":"verylongbase64string","clientData":"longbase64string"}}
//
// Successful response: (session cookie is set)
//
// {"type": "bearer", "token": "bearer token", "user": "alex", "expires_in": 20} | func (h *Handler) createNewU2FUser(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) | // createNewU2FUser creates a new user configured to use U2F as the second factor
//
// POST /webapi/u2f/users
//
// {"invite_token": "unique invite token", "pass": "user password", "u2f_register_response": {"registrationData":"verylongbase64string","clientData":"longbase64string"}}
//
// Successful response: (session cookie is set)
//
// {"type": "bearer", "token": "bearer token", "user": "alex", "expires_in": 20}
func (h *Handler) createNewU2FUser(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) | {
var req *createNewU2FUserReq
if err := httplib.ReadJSON(r, &req); err != nil {
return nil, trace.Wrap(err)
}
sess, err := h.auth.CreateNewU2FUser(req.InviteToken, req.Pass, req.U2FRegisterResponse)
if err != nil {
return nil, trace.Wrap(err)
}
ctx, err := h.auth.ValidateSession(sess.GetUser(), sess.GetName())
if err != nil {
return nil, trace.Wrap(err)
}
if err := SetSession(w, sess.GetUser(), sess.GetName()); err != nil {
return nil, trace.Wrap(err)
}
return NewSessionResponse(ctx)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/apiserver.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/apiserver.go#L1322-L1332 | go | train | // getClusters returns a list of clusters
//
// GET /v1/webapi/sites
//
// Successful response:
//
// {"sites": {"name": "localhost", "last_connected": "RFC3339 time", "status": "active"}}
// | func (h *Handler) getClusters(w http.ResponseWriter, r *http.Request, p httprouter.Params, c *SessionContext) (interface{}, error) | // getClusters returns a list of clusters
//
// GET /v1/webapi/sites
//
// Successful response:
//
// {"sites": {"name": "localhost", "last_connected": "RFC3339 time", "status": "active"}}
//
func (h *Handler) getClusters(w http.ResponseWriter, r *http.Request, p httprouter.Params, c *SessionContext) (interface{}, error) | {
resource, err := h.cfg.ProxyClient.GetClusterName()
if err != nil {
return nil, trace.Wrap(err)
}
response := ui.NewAvailableClusters(resource.GetClusterName(),
h.cfg.Proxy.GetSites())
return response, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/apiserver.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/apiserver.go#L1346-L1358 | go | train | /* getSiteNamespaces returns a list of namespaces for a given site
GET /v1/webapi/namespaces/:namespace/sites/:site/nodes
Successful response:
{"namespaces": [{..namespace resource...}]}
*/ | func (h *Handler) getSiteNamespaces(w http.ResponseWriter, r *http.Request, _ httprouter.Params, c *SessionContext, site reversetunnel.RemoteSite) (interface{}, error) | /* getSiteNamespaces returns a list of namespaces for a given site
GET /v1/webapi/namespaces/:namespace/sites/:site/nodes
Successful response:
{"namespaces": [{..namespace resource...}]}
*/
func (h *Handler) getSiteNamespaces(w http.ResponseWriter, r *http.Request, _ httprouter.Params, c *SessionContext, site reversetunnel.RemoteSite) (interface{}, error) | {
clt, err := site.GetClient()
if err != nil {
return nil, trace.Wrap(err)
}
namespaces, err := clt.GetNamespaces()
if err != nil {
return nil, trace.Wrap(err)
}
return getSiteNamespacesResponse{
Namespaces: namespaces,
}, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/apiserver.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/apiserver.go#L1399-L1444 | go | train | // siteNodeConnect connect to the site node
//
// GET /v1/webapi/sites/:site/namespaces/:namespace/connect?access_token=bearer_token¶ms=<urlencoded json-structure>
//
// Due to the nature of websocket we can't POST parameters as is, so we have
// to add query parameters. The params query parameter is a url encodeed JSON strucrture:
//
// {"server_id": "uuid", "login": "admin", "term": {"h": 120, "w": 100}, "sid": "123"}
//
// Session id can be empty
//
// Successful response is a websocket stream that allows read write to the server
// | func (h *Handler) siteNodeConnect(
w http.ResponseWriter,
r *http.Request,
p httprouter.Params,
ctx *SessionContext,
site reversetunnel.RemoteSite) (interface{}, error) | // siteNodeConnect connect to the site node
//
// GET /v1/webapi/sites/:site/namespaces/:namespace/connect?access_token=bearer_token¶ms=<urlencoded json-structure>
//
// Due to the nature of websocket we can't POST parameters as is, so we have
// to add query parameters. The params query parameter is a url encodeed JSON strucrture:
//
// {"server_id": "uuid", "login": "admin", "term": {"h": 120, "w": 100}, "sid": "123"}
//
// Session id can be empty
//
// Successful response is a websocket stream that allows read write to the server
//
func (h *Handler) siteNodeConnect(
w http.ResponseWriter,
r *http.Request,
p httprouter.Params,
ctx *SessionContext,
site reversetunnel.RemoteSite) (interface{}, error) | {
namespace := p.ByName("namespace")
if !services.IsValidNamespace(namespace) {
return nil, trace.BadParameter("invalid namespace %q", namespace)
}
q := r.URL.Query()
params := q.Get("params")
if params == "" {
return nil, trace.BadParameter("missing params")
}
var req *TerminalRequest
if err := json.Unmarshal([]byte(params), &req); err != nil {
return nil, trace.Wrap(err)
}
log.Debugf("[WEB] new terminal request for ns=%s, server=%s, login=%s, sid=%s",
req.Namespace, req.Server, req.Login, req.SessionID)
req.Namespace = namespace
req.ProxyHostPort = h.ProxyHostPort()
req.Cluster = site.GetName()
clt, err := ctx.GetUserClient(site)
if err != nil {
return nil, trace.Wrap(err)
}
term, err := NewTerminal(*req, clt, ctx)
if err != nil {
log.Errorf("[WEB] Unable to create terminal: %v", err)
return nil, trace.Wrap(err)
}
// start the websocket session with a web-based terminal:
log.Infof("[WEB] getting terminal to '%#v'", req)
term.Serve(w, r)
return nil, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/apiserver.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/apiserver.go#L1466-L1482 | go | train | // siteSessionCreate generates a new site session that can be used by UI
//
// POST /v1/webapi/sites/:site/sessions
//
// Request body:
//
// {"session": {"terminal_params": {"w": 100, "h": 100}, "login": "centos"}}
//
// Response body:
//
// {"session": {"id": "session-id", "terminal_params": {"w": 100, "h": 100}, "login": "centos"}}
// | func (h *Handler) siteSessionGenerate(w http.ResponseWriter, r *http.Request, p httprouter.Params, ctx *SessionContext, site reversetunnel.RemoteSite) (interface{}, error) | // siteSessionCreate generates a new site session that can be used by UI
//
// POST /v1/webapi/sites/:site/sessions
//
// Request body:
//
// {"session": {"terminal_params": {"w": 100, "h": 100}, "login": "centos"}}
//
// Response body:
//
// {"session": {"id": "session-id", "terminal_params": {"w": 100, "h": 100}, "login": "centos"}}
//
func (h *Handler) siteSessionGenerate(w http.ResponseWriter, r *http.Request, p httprouter.Params, ctx *SessionContext, site reversetunnel.RemoteSite) (interface{}, error) | {
namespace := p.ByName("namespace")
if !services.IsValidNamespace(namespace) {
return nil, trace.BadParameter("invalid namespace %q", namespace)
}
var req *siteSessionGenerateReq
if err := httplib.ReadJSON(r, &req); err != nil {
return nil, trace.Wrap(err)
}
req.Session.ID = session.NewID()
req.Session.Created = time.Now().UTC()
req.Session.LastActive = time.Now().UTC()
req.Session.Namespace = namespace
log.Infof("Generated session: %#v", req.Session)
return siteSessionGenerateResponse{Session: req.Session}, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/apiserver.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/apiserver.go#L1500-L1516 | go | train | // siteSessionGet gets the list of site sessions filtered by creation time
// and either they're active or not
//
// GET /v1/webapi/sites/:site/namespaces/:namespace/sessions
//
// Response body:
//
// {"sessions": [{"id": "sid", "terminal_params": {"w": 100, "h": 100}, "parties": [], "login": "bob"}, ...] } | func (h *Handler) siteSessionsGet(w http.ResponseWriter, r *http.Request, p httprouter.Params, ctx *SessionContext, site reversetunnel.RemoteSite) (interface{}, error) | // siteSessionGet gets the list of site sessions filtered by creation time
// and either they're active or not
//
// GET /v1/webapi/sites/:site/namespaces/:namespace/sessions
//
// Response body:
//
// {"sessions": [{"id": "sid", "terminal_params": {"w": 100, "h": 100}, "parties": [], "login": "bob"}, ...] }
func (h *Handler) siteSessionsGet(w http.ResponseWriter, r *http.Request, p httprouter.Params, ctx *SessionContext, site reversetunnel.RemoteSite) (interface{}, error) | {
clt, err := ctx.GetUserClient(site)
if err != nil {
return nil, trace.Wrap(err)
}
namespace := p.ByName("namespace")
if !services.IsValidNamespace(namespace) {
return nil, trace.BadParameter("invalid namespace %q", namespace)
}
sessions, err := clt.GetSessions(namespace)
if err != nil {
return nil, trace.Wrap(err)
}
return siteSessionsGetResponse{Sessions: sessions}, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/apiserver.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/apiserver.go#L1526-L1548 | go | train | // siteSessionGet gets the list of site session by id
//
// GET /v1/webapi/sites/:site/namespaces/:namespace/sessions/:sid
//
// Response body:
//
// {"session": {"id": "sid", "terminal_params": {"w": 100, "h": 100}, "parties": [], "login": "bob"}}
// | func (h *Handler) siteSessionGet(w http.ResponseWriter, r *http.Request, p httprouter.Params, ctx *SessionContext, site reversetunnel.RemoteSite) (interface{}, error) | // siteSessionGet gets the list of site session by id
//
// GET /v1/webapi/sites/:site/namespaces/:namespace/sessions/:sid
//
// Response body:
//
// {"session": {"id": "sid", "terminal_params": {"w": 100, "h": 100}, "parties": [], "login": "bob"}}
//
func (h *Handler) siteSessionGet(w http.ResponseWriter, r *http.Request, p httprouter.Params, ctx *SessionContext, site reversetunnel.RemoteSite) (interface{}, error) | {
sessionID, err := session.ParseID(p.ByName("sid"))
if err != nil {
return nil, trace.Wrap(err)
}
log.Infof("web.getSetssion(%v)", sessionID)
clt, err := ctx.GetUserClient(site)
if err != nil {
return nil, trace.Wrap(err)
}
namespace := p.ByName("namespace")
if !services.IsValidNamespace(namespace) {
return nil, trace.BadParameter("invalid namespace %q", namespace)
}
sess, err := clt.GetSession(namespace, *sessionID)
if err != nil {
return nil, trace.Wrap(err)
}
return *sess, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/apiserver.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/apiserver.go#L1563-L1597 | go | train | // clusterSearchSessionEvents allows to search for session events on a cluster
//
// GET /v1/webapi/sites/:site/events
//
// Query parameters:
// "from" : date range from, encoded as RFC3339
// "to" : date range to, encoded as RFC3339
// ... : the rest of the query string is passed to the search back-end as-is,
// the default backend performs exact search: ?key=value means "event
// with a field 'key' with value 'value'
// | func (h *Handler) clusterSearchSessionEvents(w http.ResponseWriter, r *http.Request, p httprouter.Params, ctx *SessionContext, site reversetunnel.RemoteSite) (interface{}, error) | // clusterSearchSessionEvents allows to search for session events on a cluster
//
// GET /v1/webapi/sites/:site/events
//
// Query parameters:
// "from" : date range from, encoded as RFC3339
// "to" : date range to, encoded as RFC3339
// ... : the rest of the query string is passed to the search back-end as-is,
// the default backend performs exact search: ?key=value means "event
// with a field 'key' with value 'value'
//
func (h *Handler) clusterSearchSessionEvents(w http.ResponseWriter, r *http.Request, p httprouter.Params, ctx *SessionContext, site reversetunnel.RemoteSite) (interface{}, error) | {
query := r.URL.Query()
clt, err := ctx.GetUserClient(site)
if err != nil {
log.Error(err)
return nil, trace.Wrap(err)
}
// default values
to := time.Now().In(time.UTC)
from := to.AddDate(0, -1, 0) // one month ago
// parse 'to' and 'from' params:
fromStr := query.Get("from")
if fromStr != "" {
from, err = time.Parse(time.RFC3339, fromStr)
if err != nil {
return nil, trace.BadParameter("from")
}
}
toStr := query.Get("to")
if toStr != "" {
to, err = time.Parse(time.RFC3339, toStr)
if err != nil {
return nil, trace.BadParameter("to")
}
}
el, err := clt.SearchSessionEvents(from, to, defaults.EventsIterationLimit)
if err != nil {
return nil, trace.Wrap(err)
}
return eventsListGetResponse{Events: el}, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/apiserver.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/apiserver.go#L1610-L1637 | go | train | // clusterSearchEvents returns all audit log events matching the provided criteria
//
// GET /v1/webapi/sites/:site/events/search
//
// Query parameters:
// "from" : date range from, encoded as RFC3339
// "to" : date range to, encoded as RFC3339
// "include": optional semicolon-separated list of event names to return e.g.
// include=session.start;session.end, all are returned if empty
// "limit" : optional maximum number of events to return
// | func (h *Handler) clusterSearchEvents(w http.ResponseWriter, r *http.Request, p httprouter.Params, ctx *SessionContext, site reversetunnel.RemoteSite) (interface{}, error) | // clusterSearchEvents returns all audit log events matching the provided criteria
//
// GET /v1/webapi/sites/:site/events/search
//
// Query parameters:
// "from" : date range from, encoded as RFC3339
// "to" : date range to, encoded as RFC3339
// "include": optional semicolon-separated list of event names to return e.g.
// include=session.start;session.end, all are returned if empty
// "limit" : optional maximum number of events to return
//
func (h *Handler) clusterSearchEvents(w http.ResponseWriter, r *http.Request, p httprouter.Params, ctx *SessionContext, site reversetunnel.RemoteSite) (interface{}, error) | {
values := r.URL.Query()
from, err := queryTime(values, "from", time.Now().UTC().AddDate(0, -1, 0))
if err != nil {
return nil, trace.Wrap(err)
}
to, err := queryTime(values, "to", time.Now().UTC())
if err != nil {
return nil, trace.Wrap(err)
}
limit, err := queryLimit(values, "limit", defaults.EventsIterationLimit)
if err != nil {
return nil, trace.Wrap(err)
}
query := url.Values{}
if include := values.Get("include"); include != "" {
query[events.EventType] = strings.Split(include, ";")
}
clt, err := ctx.GetUserClient(site)
if err != nil {
return nil, trace.Wrap(err)
}
fields, err := clt.SearchEvents(from, to, query.Encode(), limit)
if err != nil {
return nil, trace.Wrap(err)
}
return eventsListGetResponse{Events: fields}, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/apiserver.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/apiserver.go#L1643-L1653 | go | train | // queryTime parses the query string parameter with the specified name as a
// RFC3339 time and returns it.
//
// If there's no such parameter, specified default value is returned. | func queryTime(query url.Values, name string, def time.Time) (time.Time, error) | // queryTime parses the query string parameter with the specified name as a
// RFC3339 time and returns it.
//
// If there's no such parameter, specified default value is returned.
func queryTime(query url.Values, name string, def time.Time) (time.Time, error) | {
str := query.Get(name)
if str == "" {
return def, nil
}
parsed, err := time.Parse(time.RFC3339, str)
if err != nil {
return time.Time{}, trace.BadParameter("failed to parse %v as RFC3339 time: %v", name, str)
}
return parsed, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/apiserver.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/apiserver.go#L1659-L1669 | go | train | // queryLimit returns the limit parameter with the specified name from the
// query string.
//
// If there's no such parameter, specified default limit is returned. | func queryLimit(query url.Values, name string, def int) (int, error) | // queryLimit returns the limit parameter with the specified name from the
// query string.
//
// If there's no such parameter, specified default limit is returned.
func queryLimit(query url.Values, name string, def int) (int, error) | {
str := query.Get(name)
if str == "" {
return def, nil
}
limit, err := strconv.Atoi(str)
if err != nil {
return 0, trace.BadParameter("failed to parse %v as limit: %v", name, str)
}
return limit, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/apiserver.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/apiserver.go#L1687-L1778 | go | train | // siteSessionStreamGet returns a byte array from a session's stream
//
// GET /v1/webapi/sites/:site/namespaces/:namespace/sessions/:sid/stream?query
//
// Query parameters:
// "offset" : bytes from the beginning
// "bytes" : number of bytes to read (it won't return more than 512Kb)
//
// Unlike other request handlers, this one does not return JSON.
// It returns the binary stream unencoded, directly in the respose body,
// with Content-Type of application/octet-stream, gzipped with up to 95%
// compression ratio. | func (h *Handler) siteSessionStreamGet(w http.ResponseWriter, r *http.Request, p httprouter.Params) | // siteSessionStreamGet returns a byte array from a session's stream
//
// GET /v1/webapi/sites/:site/namespaces/:namespace/sessions/:sid/stream?query
//
// Query parameters:
// "offset" : bytes from the beginning
// "bytes" : number of bytes to read (it won't return more than 512Kb)
//
// Unlike other request handlers, this one does not return JSON.
// It returns the binary stream unencoded, directly in the respose body,
// with Content-Type of application/octet-stream, gzipped with up to 95%
// compression ratio.
func (h *Handler) siteSessionStreamGet(w http.ResponseWriter, r *http.Request, p httprouter.Params) | {
httplib.SetNoCacheHeaders(w.Header())
logger := log.WithFields(log.Fields{
trace.Component: teleport.ComponentWeb,
})
var site reversetunnel.RemoteSite
onError := func(err error) {
logger.Debugf("Unable to retrieve session chunk: %v.", err)
w.WriteHeader(trace.ErrorToCode(err))
w.Write([]byte(err.Error()))
}
// authenticate first:
ctx, err := h.AuthenticateRequest(w, r, true)
if err != nil {
log.Info(err)
// clear session just in case if the authentication request is not valid
ClearSession(w)
onError(err)
return
}
// get the site interface:
siteName := p.ByName("site")
if siteName == currentSiteShortcut {
sites := h.cfg.Proxy.GetSites()
if len(sites) < 1 {
onError(trace.NotFound("no active sites"))
return
}
siteName = sites[0].GetName()
}
site, err = h.cfg.Proxy.GetSite(siteName)
if err != nil {
onError(err)
return
}
// get the session:
sid, err := session.ParseID(p.ByName("sid"))
if err != nil {
onError(trace.Wrap(err))
return
}
clt, err := ctx.GetUserClient(site)
if err != nil {
onError(trace.Wrap(err))
return
}
// look at 'offset' parameter
query := r.URL.Query()
offset, _ := strconv.Atoi(query.Get("offset"))
if err != nil {
onError(trace.Wrap(err))
return
}
max, err := strconv.Atoi(query.Get("bytes"))
if err != nil || max <= 0 {
max = maxStreamBytes
}
if max > maxStreamBytes {
max = maxStreamBytes
}
namespace := p.ByName("namespace")
if !services.IsValidNamespace(namespace) {
onError(trace.BadParameter("invalid namespace %q", namespace))
return
}
// call the site API to get the chunk:
bytes, err := clt.GetSessionChunk(namespace, *sid, offset, max)
if err != nil {
onError(trace.Wrap(err))
return
}
// see if we can gzip it:
var writer io.Writer = w
for _, acceptedEnc := range strings.Split(r.Header.Get("Accept-Encoding"), ",") {
if strings.TrimSpace(acceptedEnc) == "gzip" {
gzipper := gzip.NewWriter(w)
writer = gzipper
defer gzipper.Close()
w.Header().Set("Content-Encoding", "gzip")
}
}
w.Header().Set("Content-Type", "application/octet-stream")
_, err = writer.Write(bytes)
if err != nil {
onError(trace.Wrap(err))
return
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/apiserver.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/apiserver.go#L1796-L1828 | go | train | // siteSessionEventsGet gets the site session by id
//
// GET /v1/webapi/sites/:site/namespaces/:namespace/sessions/:sid/events?after=N
//
// Query:
// "after" : cursor value of an event to return "newer than" events
// good for repeated polling
//
// Response body (each event is an arbitrary JSON structure)
//
// {"events": [{...}, {...}, ...}
// | func (h *Handler) siteSessionEventsGet(w http.ResponseWriter, r *http.Request, p httprouter.Params, ctx *SessionContext, site reversetunnel.RemoteSite) (interface{}, error) | // siteSessionEventsGet gets the site session by id
//
// GET /v1/webapi/sites/:site/namespaces/:namespace/sessions/:sid/events?after=N
//
// Query:
// "after" : cursor value of an event to return "newer than" events
// good for repeated polling
//
// Response body (each event is an arbitrary JSON structure)
//
// {"events": [{...}, {...}, ...}
//
func (h *Handler) siteSessionEventsGet(w http.ResponseWriter, r *http.Request, p httprouter.Params, ctx *SessionContext, site reversetunnel.RemoteSite) (interface{}, error) | {
logger := log.WithFields(log.Fields{
trace.Component: teleport.ComponentWeb,
})
sessionID, err := session.ParseID(p.ByName("sid"))
if err != nil {
return nil, trace.BadParameter("invalid session ID %q", p.ByName("sid"))
}
clt, err := ctx.GetUserClient(site)
if err != nil {
return nil, trace.Wrap(err)
}
afterN, err := strconv.Atoi(r.URL.Query().Get("after"))
if err != nil {
afterN = 0
}
namespace := p.ByName("namespace")
if !services.IsValidNamespace(namespace) {
return nil, trace.BadParameter("invalid namespace %q", namespace)
}
e, err := clt.GetSessionEvents(namespace, *sessionID, afterN, true)
if err != nil {
logger.Debugf("Unable to find events for session %v: %v.", sessionID, err)
if trace.IsNotFound(err) {
return nil, trace.NotFound("Unable to find events for session %q", sessionID)
}
return nil, trace.Wrap(err)
}
return eventsListGetResponse{Events: e}, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/apiserver.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/apiserver.go#L1832-L1845 | go | train | // hostCredentials sends a registration token and metadata to the Auth Server
// and gets back SSH and TLS certificates. | func (h *Handler) hostCredentials(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) | // hostCredentials sends a registration token and metadata to the Auth Server
// and gets back SSH and TLS certificates.
func (h *Handler) hostCredentials(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) | {
var req auth.RegisterUsingTokenRequest
if err := httplib.ReadJSON(r, &req); err != nil {
return nil, trace.Wrap(err)
}
authClient := h.cfg.ProxyClient
packedKeys, err := authClient.RegisterUsingToken(req)
if err != nil {
return nil, trace.Wrap(err)
}
return packedKeys, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/apiserver.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/apiserver.go#L1858-L1889 | go | train | // createSSHCert is a web call that generates new SSH certificate based
// on user's name, password, 2nd factor token and public key user wishes to sign
//
// POST /v1/webapi/ssh/certs
//
// { "user": "bob", "password": "pass", "otp_token": "tok", "pub_key": "key to sign", "ttl": 1000000000 }
//
// Success response
//
// { "cert": "base64 encoded signed cert", "host_signers": [{"domain_name": "example.com", "checking_keys": ["base64 encoded public signing key"]}] }
// | func (h *Handler) createSSHCert(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) | // createSSHCert is a web call that generates new SSH certificate based
// on user's name, password, 2nd factor token and public key user wishes to sign
//
// POST /v1/webapi/ssh/certs
//
// { "user": "bob", "password": "pass", "otp_token": "tok", "pub_key": "key to sign", "ttl": 1000000000 }
//
// Success response
//
// { "cert": "base64 encoded signed cert", "host_signers": [{"domain_name": "example.com", "checking_keys": ["base64 encoded public signing key"]}] }
//
func (h *Handler) createSSHCert(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) | {
var req *client.CreateSSHCertReq
if err := httplib.ReadJSON(r, &req); err != nil {
return nil, trace.Wrap(err)
}
authClient := h.cfg.ProxyClient
cap, err := authClient.GetAuthPreference()
if err != nil {
return nil, trace.Wrap(err)
}
var cert *auth.SSHLoginResponse
switch cap.GetSecondFactor() {
case teleport.OFF:
cert, err = h.auth.GetCertificateWithoutOTP(*req)
case teleport.OTP, teleport.HOTP, teleport.TOTP:
// convert legacy requests to new parameter here. remove once migration to TOTP is complete.
if req.HOTPToken != "" {
req.OTPToken = req.HOTPToken
}
cert, err = h.auth.GetCertificateWithOTP(*req)
default:
return nil, trace.AccessDenied("unknown second factor type: %q", cap.GetSecondFactor())
}
if err != nil {
return nil, trace.Wrap(err)
}
return cert, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/apiserver.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/apiserver.go#L1902-L1913 | go | train | // createSSHCertWithU2FSignResponse is a web call that generates new SSH certificate based
// on user's name, password, U2F signature and public key user wishes to sign
//
// POST /v1/webapi/u2f/certs
//
// { "user": "bob", "password": "pass", "u2f_sign_response": { "signatureData": "signatureinbase64", "clientData": "verylongbase64string", "challenge": "randombase64string" }, "pub_key": "key to sign", "ttl": 1000000000 }
//
// Success response
//
// { "cert": "base64 encoded signed cert", "host_signers": [{"domain_name": "example.com", "checking_keys": ["base64 encoded public signing key"]}] }
// | func (h *Handler) createSSHCertWithU2FSignResponse(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) | // createSSHCertWithU2FSignResponse is a web call that generates new SSH certificate based
// on user's name, password, U2F signature and public key user wishes to sign
//
// POST /v1/webapi/u2f/certs
//
// { "user": "bob", "password": "pass", "u2f_sign_response": { "signatureData": "signatureinbase64", "clientData": "verylongbase64string", "challenge": "randombase64string" }, "pub_key": "key to sign", "ttl": 1000000000 }
//
// Success response
//
// { "cert": "base64 encoded signed cert", "host_signers": [{"domain_name": "example.com", "checking_keys": ["base64 encoded public signing key"]}] }
//
func (h *Handler) createSSHCertWithU2FSignResponse(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) | {
var req *client.CreateSSHCertWithU2FReq
if err := httplib.ReadJSON(r, &req); err != nil {
return nil, trace.Wrap(err)
}
cert, err := h.auth.GetCertificateWithU2F(*req)
if err != nil {
return nil, trace.Wrap(err)
}
return cert, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/apiserver.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/apiserver.go#L1931-L1958 | go | train | // validateTrustedCluster validates the token for a trusted cluster and returns it's own host and user certificate authority.
//
// POST /webapi/trustedclusters/validate
//
// * Request body:
//
// {
// "token": "foo",
// "certificate_authorities": ["AQ==", "Ag=="]
// }
//
// * Response:
//
// {
// "certificate_authorities": ["AQ==", "Ag=="]
// } | func (h *Handler) validateTrustedCluster(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) | // validateTrustedCluster validates the token for a trusted cluster and returns it's own host and user certificate authority.
//
// POST /webapi/trustedclusters/validate
//
// * Request body:
//
// {
// "token": "foo",
// "certificate_authorities": ["AQ==", "Ag=="]
// }
//
// * Response:
//
// {
// "certificate_authorities": ["AQ==", "Ag=="]
// }
func (h *Handler) validateTrustedCluster(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) | {
var validateRequestRaw auth.ValidateTrustedClusterRequestRaw
if err := httplib.ReadJSON(r, &validateRequestRaw); err != nil {
return nil, trace.Wrap(err)
}
validateRequest, err := validateRequestRaw.ToNative()
if err != nil {
return nil, trace.Wrap(err)
}
validateResponse, err := h.auth.ValidateTrustedCluster(validateRequest)
if err != nil {
if trace.IsAccessDenied(err) {
return nil, trace.AccessDenied("access denied: the cluster token has been rejected")
} else {
log.Error(err)
return nil, trace.Wrap(err)
}
}
validateResponseRaw, err := validateResponse.ToRaw()
if err != nil {
return nil, trace.Wrap(err)
}
return validateResponseRaw, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/apiserver.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/apiserver.go#L1976-L2003 | go | train | // WithClusterAuth ensures that request is authenticated and is issued for existing cluster | func (h *Handler) WithClusterAuth(fn ClusterHandler) httprouter.Handle | // WithClusterAuth ensures that request is authenticated and is issued for existing cluster
func (h *Handler) WithClusterAuth(fn ClusterHandler) httprouter.Handle | {
return httplib.MakeHandler(func(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) {
ctx, err := h.AuthenticateRequest(w, r, true)
if err != nil {
log.Info(err)
// clear session just in case if the authentication request is not valid
ClearSession(w)
return nil, trace.Wrap(err)
}
siteName := p.ByName("site")
if siteName == currentSiteShortcut {
res, err := h.cfg.ProxyClient.GetClusterName()
if err != nil {
log.Warn(err)
return nil, trace.Wrap(err)
}
siteName = res.GetClusterName()
}
site, err := h.cfg.Proxy.GetSite(siteName)
if err != nil {
log.Warn(err)
return nil, trace.Wrap(err)
}
return fn(w, r, p, ctx, site)
})
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/apiserver.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/apiserver.go#L2006-L2014 | go | train | // WithAuth ensures that request is authenticated | func (h *Handler) WithAuth(fn ContextHandler) httprouter.Handle | // WithAuth ensures that request is authenticated
func (h *Handler) WithAuth(fn ContextHandler) httprouter.Handle | {
return httplib.MakeHandler(func(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) {
ctx, err := h.AuthenticateRequest(w, r, true)
if err != nil {
return nil, trace.Wrap(err)
}
return fn(w, r, p, ctx)
})
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/apiserver.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/apiserver.go#L2018-L2054 | go | train | // AuthenticateRequest authenticates request using combination of a session cookie
// and bearer token | func (h *Handler) AuthenticateRequest(w http.ResponseWriter, r *http.Request, checkBearerToken bool) (*SessionContext, error) | // AuthenticateRequest authenticates request using combination of a session cookie
// and bearer token
func (h *Handler) AuthenticateRequest(w http.ResponseWriter, r *http.Request, checkBearerToken bool) (*SessionContext, error) | {
const missingCookieMsg = "missing session cookie"
logger := log.WithFields(log.Fields{
"request": fmt.Sprintf("%v %v", r.Method, r.URL.Path),
})
cookie, err := r.Cookie("session")
if err != nil || (cookie != nil && cookie.Value == "") {
if err != nil {
logger.Warn(err)
}
return nil, trace.AccessDenied(missingCookieMsg)
}
d, err := DecodeCookie(cookie.Value)
if err != nil {
logger.Warningf("failed to decode cookie: %v", err)
return nil, trace.AccessDenied("failed to decode cookie")
}
ctx, err := h.auth.ValidateSession(d.User, d.SID)
if err != nil {
logger.Warningf("invalid session: %v", err)
ClearSession(w)
return nil, trace.AccessDenied("need auth")
}
if checkBearerToken {
creds, err := roundtrip.ParseAuthHeaders(r)
if err != nil {
logger.Warningf("no auth headers %v", err)
return nil, trace.AccessDenied("need auth")
}
if subtle.ConstantTimeCompare([]byte(creds.Password), []byte(ctx.GetWebSession().GetBearerToken())) != 1 {
logger.Warningf("Request failed: bad bearer token.")
return nil, trace.AccessDenied("bad bearer token")
}
}
return ctx, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/apiserver.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/apiserver.go#L2058-L2068 | go | train | // ProxyHostPort returns the address of the proxy server using --proxy
// notation, i.e. "localhost:8030,8023" | func (h *Handler) ProxyHostPort() string | // ProxyHostPort returns the address of the proxy server using --proxy
// notation, i.e. "localhost:8030,8023"
func (h *Handler) ProxyHostPort() string | {
// addr equals to "localhost:8030" at this point
addr := h.cfg.ProxyWebAddr.String()
// add the SSH port number and return
_, sshPort, err := net.SplitHostPort(h.cfg.ProxySSHAddr.String())
if err != nil {
log.Error(err)
sshPort = strconv.Itoa(defaults.SSHProxyListenPort)
}
return fmt.Sprintf("%s,%s", addr, sshPort)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/apiserver.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/apiserver.go#L2080-L2102 | go | train | // CreateSignupLink generates and returns a URL which is given to a new
// user to complete registration with Teleport via Web UI | func CreateSignupLink(client auth.ClientI, token string) (string, string) | // CreateSignupLink generates and returns a URL which is given to a new
// user to complete registration with Teleport via Web UI
func CreateSignupLink(client auth.ClientI, token string) (string, string) | {
proxyHost := "<proxyhost>:3080"
proxies, err := client.GetProxies()
if err != nil {
log.Errorf("Unable to retrieve proxy list: %v", err)
}
if len(proxies) > 0 {
proxyHost = proxies[0].GetPublicAddr()
if proxyHost == "" {
proxyHost = fmt.Sprintf("%v:%v", proxies[0].GetHostname(), defaults.HTTPListenPort)
log.Debugf("public_address not set for proxy, returning proxyHost: %q", proxyHost)
}
}
u := &url.URL{
Scheme: "https",
Host: proxyHost,
Path: "web/newuser/" + token,
}
return u.String(), proxyHost
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/apiserver.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/apiserver.go#L2114-L2141 | go | train | // makeTeleportClientConfig creates default teleport client configuration
// that is used to initiate an SSH terminal session or SCP file transfer | func makeTeleportClientConfig(ctx *SessionContext) (*client.Config, error) | // makeTeleportClientConfig creates default teleport client configuration
// that is used to initiate an SSH terminal session or SCP file transfer
func makeTeleportClientConfig(ctx *SessionContext) (*client.Config, error) | {
agent, cert, err := ctx.GetAgent()
if err != nil {
return nil, trace.BadParameter("failed to get user credentials: %v", err)
}
signers, err := agent.Signers()
if err != nil {
return nil, trace.BadParameter("failed to get user credentials: %v", err)
}
tlsConfig, err := ctx.ClientTLSConfig()
if err != nil {
return nil, trace.BadParameter("failed to get client TLS config: %v", err)
}
config := &client.Config{
Username: ctx.user,
Agent: agent,
SkipLocalAuth: true,
TLS: tlsConfig,
AuthMethods: []ssh.AuthMethod{ssh.PublicKeys(signers...)},
DefaultPrincipal: cert.ValidPrincipals[0],
HostKeyCallback: func(string, net.Addr, ssh.PublicKey) error { return nil },
}
return config, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/client/keyagent.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/keyagent.go#L71-L114 | go | train | // NewLocalAgent reads all Teleport certificates from disk (using FSLocalKeyStore),
// creates a LocalKeyAgent, loads all certificates into it, and returns the agent. | func NewLocalAgent(keyDir string, proxyHost string, username string) (a *LocalKeyAgent, err error) | // NewLocalAgent reads all Teleport certificates from disk (using FSLocalKeyStore),
// creates a LocalKeyAgent, loads all certificates into it, and returns the agent.
func NewLocalAgent(keyDir string, proxyHost string, username string) (a *LocalKeyAgent, err error) | {
keystore, err := NewFSLocalKeyStore(keyDir)
if err != nil {
return nil, trace.Wrap(err)
}
a = &LocalKeyAgent{
log: logrus.WithFields(logrus.Fields{
trace.Component: teleport.ComponentKeyAgent,
}),
Agent: agent.NewKeyring(),
keyStore: keystore,
sshAgent: connectToSSHAgent(),
noHosts: make(map[string]bool),
username: username,
proxyHost: proxyHost,
}
// unload all teleport keys from the agent first to ensure
// we don't leave stale keys in the agent
err = a.UnloadKeys()
if err != nil {
return nil, trace.Wrap(err)
}
// read in key for this user in proxy
key, err := a.GetKey()
if err != nil {
if trace.IsNotFound(err) {
return a, nil
}
return nil, trace.Wrap(err)
}
a.log.Infof("Loading key for %q", username)
// load key into the agent
_, err = a.LoadKey(*key)
if err != nil {
return nil, trace.Wrap(err)
}
return a, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/client/keyagent.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/keyagent.go#L123-L154 | go | train | // LoadKey adds a key into the Teleport ssh agent as well as the system ssh
// agent. | func (a *LocalKeyAgent) LoadKey(key Key) (*agent.AddedKey, error) | // LoadKey adds a key into the Teleport ssh agent as well as the system ssh
// agent.
func (a *LocalKeyAgent) LoadKey(key Key) (*agent.AddedKey, error) | {
agents := []agent.Agent{a.Agent}
if a.sshAgent != nil {
agents = append(agents, a.sshAgent)
}
// convert keys into a format understood by the ssh agent
agentKeys, err := key.AsAgentKeys()
if err != nil {
return nil, trace.Wrap(err)
}
// remove any keys that the user may already have loaded
err = a.UnloadKey()
if err != nil {
return nil, trace.Wrap(err)
}
// iterate over all teleport and system agent and load key
for i, _ := range agents {
for _, agentKey := range agentKeys {
err = agents[i].Add(*agentKey)
if err != nil {
a.log.Warnf("Unable to communicate with agent and add key: %v", err)
}
}
}
// return the first key because it has the embedded private key in it.
// see docs for AsAgentKeys for more details.
return agentKeys[0], nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/client/keyagent.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/keyagent.go#L158-L184 | go | train | // UnloadKey will unload key for user from the teleport ssh agent as well as
// the system agent. | func (a *LocalKeyAgent) UnloadKey() error | // UnloadKey will unload key for user from the teleport ssh agent as well as
// the system agent.
func (a *LocalKeyAgent) UnloadKey() error | {
agents := []agent.Agent{a.Agent}
if a.sshAgent != nil {
agents = append(agents, a.sshAgent)
}
// iterate over all agents we have and unload keys for this user
for i, _ := range agents {
// get a list of all keys in the agent
keyList, err := agents[i].List()
if err != nil {
a.log.Warnf("Unable to communicate with agent and list keys: %v", err)
}
// remove any teleport keys we currently have loaded in the agent for this user
for _, key := range keyList {
if key.Comment == fmt.Sprintf("teleport:%v", a.username) {
err = agents[i].Remove(key)
if err != nil {
a.log.Warnf("Unable to communicate with agent and remove key: %v", err)
}
}
}
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/client/keyagent.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/keyagent.go#L188-L214 | go | train | // UnloadKeys will unload all Teleport keys from the teleport agent as well as
// the system agent. | func (a *LocalKeyAgent) UnloadKeys() error | // UnloadKeys will unload all Teleport keys from the teleport agent as well as
// the system agent.
func (a *LocalKeyAgent) UnloadKeys() error | {
agents := []agent.Agent{a.Agent}
if a.sshAgent != nil {
agents = append(agents, a.sshAgent)
}
// iterate over all agents we have
for i, _ := range agents {
// get a list of all keys in the agent
keyList, err := agents[i].List()
if err != nil {
a.log.Warnf("Unable to communicate with agent and list keys: %v", err)
}
// remove any teleport keys we currently have loaded in the agent
for _, key := range keyList {
if strings.HasPrefix(key.Comment, "teleport:") {
err = agents[i].Remove(key)
if err != nil {
a.log.Warnf("Unable to communicate with agent and remove key: %v", err)
}
}
}
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/client/keyagent.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/keyagent.go#L218-L220 | go | train | // GetKey returns the key for this user in a proxy from the filesystem keystore
// at ~/.tsh. | func (a *LocalKeyAgent) GetKey() (*Key, error) | // GetKey returns the key for this user in a proxy from the filesystem keystore
// at ~/.tsh.
func (a *LocalKeyAgent) GetKey() (*Key, error) | {
return a.keyStore.GetKey(a.proxyHost, a.username)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/client/keyagent.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/keyagent.go#L230-L244 | go | train | // AddHostSignersToCache takes a list of CAs whom we trust. This list is added to a database
// of "seen" CAs.
//
// Every time we connect to a new host, we'll request its certificaate to be signed by one
// of these trusted CAs.
//
// Why do we trust these CAs? Because we received them from a trusted Teleport Proxy.
// Why do we trust the proxy? Because we've connected to it via HTTPS + username + Password + HOTP. | func (a *LocalKeyAgent) AddHostSignersToCache(certAuthorities []auth.TrustedCerts) error | // AddHostSignersToCache takes a list of CAs whom we trust. This list is added to a database
// of "seen" CAs.
//
// Every time we connect to a new host, we'll request its certificaate to be signed by one
// of these trusted CAs.
//
// Why do we trust these CAs? Because we received them from a trusted Teleport Proxy.
// Why do we trust the proxy? Because we've connected to it via HTTPS + username + Password + HOTP.
func (a *LocalKeyAgent) AddHostSignersToCache(certAuthorities []auth.TrustedCerts) error | {
for _, ca := range certAuthorities {
publicKeys, err := ca.SSHCertPublicKeys()
if err != nil {
a.log.Error(err)
return trace.Wrap(err)
}
a.log.Debugf("Adding CA key for %s", ca.ClusterName)
err = a.keyStore.AddKnownHostKeys(ca.ClusterName, publicKeys)
if err != nil {
return trace.Wrap(err)
}
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/client/keyagent.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/keyagent.go#L266-L280 | go | train | // CheckHostSignature checks if the given host key was signed by a Teleport
// certificate authority (CA) or a host certificate the user has seen before. | func (a *LocalKeyAgent) CheckHostSignature(addr string, remote net.Addr, key ssh.PublicKey) error | // CheckHostSignature checks if the given host key was signed by a Teleport
// certificate authority (CA) or a host certificate the user has seen before.
func (a *LocalKeyAgent) CheckHostSignature(addr string, remote net.Addr, key ssh.PublicKey) error | {
certChecker := utils.CertChecker{
CertChecker: ssh.CertChecker{
IsHostAuthority: a.checkHostCertificate,
HostKeyFallback: a.checkHostKey,
},
}
err := certChecker.CheckHostKey(addr, remote, key)
if err != nil {
a.log.Debugf("Host validation failed: %v.", err)
return trace.Wrap(err)
}
a.log.Debugf("Validated host %v.", addr)
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/client/keyagent.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/keyagent.go#L285-L306 | go | train | // checkHostCertificate validates a host certificate. First checks the
// ~/.tsh/known_hosts cache and if not found, prompts the user to accept
// or reject. | func (a *LocalKeyAgent) checkHostCertificate(key ssh.PublicKey, addr string) bool | // checkHostCertificate validates a host certificate. First checks the
// ~/.tsh/known_hosts cache and if not found, prompts the user to accept
// or reject.
func (a *LocalKeyAgent) checkHostCertificate(key ssh.PublicKey, addr string) bool | {
// Check the local cache (where all Teleport CAs are placed upon login) to
// see if any of them match.
keys, err := a.keyStore.GetKnownHostKeys("")
if err != nil {
a.log.Errorf("Unable to fetch certificate authorities: %v.", err)
return false
}
for i := range keys {
if sshutils.KeysEqual(key, keys[i]) {
return true
}
}
// If this certificate was not seen before, prompt the user essentially
// treating it like a key.
err = a.checkHostKey(addr, nil, key)
if err != nil {
return false
}
return true
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/client/keyagent.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/keyagent.go#L311-L340 | go | train | // checkHostKey validates a host key. First checks the
// ~/.tsh/known_hosts cache and if not found, prompts the user to accept
// or reject. | func (a *LocalKeyAgent) checkHostKey(addr string, remote net.Addr, key ssh.PublicKey) error | // checkHostKey validates a host key. First checks the
// ~/.tsh/known_hosts cache and if not found, prompts the user to accept
// or reject.
func (a *LocalKeyAgent) checkHostKey(addr string, remote net.Addr, key ssh.PublicKey) error | {
var err error
// Check if this exact host is in the local cache.
keys, _ := a.keyStore.GetKnownHostKeys(addr)
if len(keys) > 0 && sshutils.KeysEqual(key, keys[0]) {
a.log.Debugf("Verified host %s.", addr)
return nil
}
// If this key was not seen before, prompt the user with a fingerprint.
if a.hostPromptFunc != nil {
err = a.hostPromptFunc(addr, key)
} else {
err = a.defaultHostPromptFunc(addr, key, os.Stdout, os.Stdin)
}
if err != nil {
a.noHosts[addr] = true
return trace.Wrap(err)
}
// If the user trusts the key, store the key in the local known hosts
// cache ~/.tsh/known_hosts.
err = a.keyStore.AddKnownHostKeys(addr, []ssh.PublicKey{key})
if err != nil {
a.log.Warnf("Failed to save the host key: %v.", err)
return trace.Wrap(err)
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/client/keyagent.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/keyagent.go#L343-L366 | go | train | // defaultHostPromptFunc is the default host key/certificates prompt. | func (a *LocalKeyAgent) defaultHostPromptFunc(host string, key ssh.PublicKey, writer io.Writer, reader io.Reader) error | // defaultHostPromptFunc is the default host key/certificates prompt.
func (a *LocalKeyAgent) defaultHostPromptFunc(host string, key ssh.PublicKey, writer io.Writer, reader io.Reader) error | {
var err error
userAnswer := "no"
if !a.noHosts[host] {
fmt.Fprintf(writer, "The authenticity of host '%s' can't be established. "+
"Its public key is:\n%s\nAre you sure you want to continue (yes/no)? ",
host, ssh.MarshalAuthorizedKey(key))
userAnswer, err = bufio.NewReader(reader).ReadString('\n')
if err != nil {
return trace.Wrap(err)
}
userAnswer = strings.TrimSpace(strings.ToLower(userAnswer))
}
ok, err := utils.ParseBool(userAnswer)
if err != nil {
return trace.Wrap(err)
}
if !ok {
return trace.BadParameter("not trusted")
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/client/keyagent.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/keyagent.go#L370-L379 | go | train | // AddKey activates a new signed session key by adding it into the keystore and also
// by loading it into the SSH agent | func (a *LocalKeyAgent) AddKey(key *Key) (*agent.AddedKey, error) | // AddKey activates a new signed session key by adding it into the keystore and also
// by loading it into the SSH agent
func (a *LocalKeyAgent) AddKey(key *Key) (*agent.AddedKey, error) | {
// save it to disk (usually into ~/.tsh)
err := a.keyStore.AddKey(a.proxyHost, a.username, key)
if err != nil {
return nil, trace.Wrap(err)
}
// load key into the teleport agent and system agent
return a.LoadKey(*key)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/client/keyagent.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/keyagent.go#L383-L398 | go | train | // DeleteKey removes the key from the key store as well as unloading the key
// from the agent. | func (a *LocalKeyAgent) DeleteKey() error | // DeleteKey removes the key from the key store as well as unloading the key
// from the agent.
func (a *LocalKeyAgent) DeleteKey() error | {
// remove key from key store
err := a.keyStore.DeleteKey(a.proxyHost, a.username)
if err != nil {
return trace.Wrap(err)
}
// remove any keys that are loaded for this user from the teleport and
// system agents
err = a.UnloadKey()
if err != nil {
return trace.Wrap(err)
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/client/keyagent.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/keyagent.go#L402-L416 | go | train | // DeleteKeys removes all keys from the keystore as well as unloads keys
// from the agent. | func (a *LocalKeyAgent) DeleteKeys() error | // DeleteKeys removes all keys from the keystore as well as unloads keys
// from the agent.
func (a *LocalKeyAgent) DeleteKeys() error | {
// Remove keys from the filesystem.
err := a.keyStore.DeleteKeys()
if err != nil {
return trace.Wrap(err)
}
// Remove all keys from the Teleport and system agents.
err = a.UnloadKeys()
if err != nil {
return trace.Wrap(err)
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/client/keyagent.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/keyagent.go#L422-L443 | go | train | // AuthMethods returns the list of different authentication methods this agent supports
// It returns two:
// 1. First to try is the external SSH agent
// 2. Itself (disk-based local agent) | func (a *LocalKeyAgent) AuthMethods() (m []ssh.AuthMethod) | // AuthMethods returns the list of different authentication methods this agent supports
// It returns two:
// 1. First to try is the external SSH agent
// 2. Itself (disk-based local agent)
func (a *LocalKeyAgent) AuthMethods() (m []ssh.AuthMethod) | {
// combine our certificates with external SSH agent's:
var signers []ssh.Signer
if ourCerts, _ := a.Signers(); ourCerts != nil {
signers = append(signers, ourCerts...)
}
if a.sshAgent != nil {
if sshAgentCerts, _ := a.sshAgent.Signers(); sshAgentCerts != nil {
signers = append(signers, sshAgentCerts...)
}
}
// for every certificate create a new "auth method" and return them
m = make([]ssh.AuthMethod, 0)
for i := range signers {
// filter out non-certificates (like regular public SSH keys stored in the SSH agent):
_, ok := signers[i].PublicKey().(*ssh.Certificate)
if ok {
m = append(m, NewAuthMethodForCert(signers[i]))
}
}
return m
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/fs_unix.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/fs_unix.go#L30-L35 | go | train | // FSWriteLock grabs Flock-style filesystem lock on an open file
// in exclusive mode. | func FSWriteLock(f *os.File) error | // FSWriteLock grabs Flock-style filesystem lock on an open file
// in exclusive mode.
func FSWriteLock(f *os.File) error | {
if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX); err != nil {
return trace.ConvertSystemError(err)
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/fs_unix.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/fs_unix.go#L39-L48 | go | train | // FSTryWriteLock tries to grab write lock, returns CompareFailed
// if lock is already grabbed | func FSTryWriteLock(f *os.File) error | // FSTryWriteLock tries to grab write lock, returns CompareFailed
// if lock is already grabbed
func FSTryWriteLock(f *os.File) error | {
err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
if err != nil {
if err == syscall.EWOULDBLOCK {
return trace.CompareFailed("lock %v is acquired by another process", f.Name())
}
return trace.ConvertSystemError(err)
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/fs_unix.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/fs_unix.go#L52-L57 | go | train | // FSReadLock grabs Flock-style filesystem lock on an open file
// in read (shared) mode | func FSReadLock(f *os.File) error | // FSReadLock grabs Flock-style filesystem lock on an open file
// in read (shared) mode
func FSReadLock(f *os.File) error | {
if err := syscall.Flock(int(f.Fd()), syscall.LOCK_SH); err != nil {
return trace.ConvertSystemError(err)
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/fs_unix.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/fs_unix.go#L60-L65 | go | train | // FSUnlock unlcocks Flock-style filesystem lock | func FSUnlock(f *os.File) error | // FSUnlock unlcocks Flock-style filesystem lock
func FSUnlock(f *os.File) error | {
if err := syscall.Flock(int(f.Fd()), syscall.LOCK_UN); err != nil {
return trace.ConvertSystemError(err)
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/conv.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/conv.go#L53-L62 | go | train | // ObjectToStruct is converts any structure into JSON and then unmarshalls it into
// another structure.
//
// Teleport configuration uses this (strange, at first) trick to convert from one
// struct type to another, if their fields are loosely compatible via their `json` tags
//
// Example: assume you have two structs:
//
// type A struct {
// Name string `json:"name"`
// Age int `json:"age"`
// }
//
// type B struct {
// FullName string `json:"name"`
// }
//
// Now you can convert B to A:
//
// b := &B{ FullName: "Bob Dilan"}
// var a *A
// utils.ObjectToStruct(b, &a)
// fmt.Println(a.Name)
//
// > "Bob Dilan"
// | func ObjectToStruct(in interface{}, out interface{}) error | // ObjectToStruct is converts any structure into JSON and then unmarshalls it into
// another structure.
//
// Teleport configuration uses this (strange, at first) trick to convert from one
// struct type to another, if their fields are loosely compatible via their `json` tags
//
// Example: assume you have two structs:
//
// type A struct {
// Name string `json:"name"`
// Age int `json:"age"`
// }
//
// type B struct {
// FullName string `json:"name"`
// }
//
// Now you can convert B to A:
//
// b := &B{ FullName: "Bob Dilan"}
// var a *A
// utils.ObjectToStruct(b, &a)
// fmt.Println(a.Name)
//
// > "Bob Dilan"
//
func ObjectToStruct(in interface{}, out interface{}) error | {
bytes, err := json.Marshal(in)
if err != nil {
return trace.Wrap(err, fmt.Sprintf("failed to marshal %v, %v", in, err))
}
if err := json.Unmarshal([]byte(bytes), out); err != nil {
return trace.Wrap(err, fmt.Sprintf("failed to unmarshal %v into %T, %v", in, out, err))
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/limiter/ratelimiter.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/limiter/ratelimiter.go#L50-L96 | go | train | // NewRateLimiter returns new request rate controller | func NewRateLimiter(config LimiterConfig) (*RateLimiter, error) | // NewRateLimiter returns new request rate controller
func NewRateLimiter(config LimiterConfig) (*RateLimiter, error) | {
limiter := RateLimiter{
Mutex: &sync.Mutex{},
}
ipExtractor, err := utils.NewExtractor("client.ip")
if err != nil {
return nil, trace.Wrap(err)
}
limiter.rates = ratelimit.NewRateSet()
for _, rate := range config.Rates {
err := limiter.rates.Add(rate.Period, rate.Average, rate.Burst)
if err != nil {
return nil, trace.Wrap(err)
}
}
if len(config.Rates) == 0 {
err := limiter.rates.Add(time.Second, DefaultRate, DefaultRate)
if err != nil {
return nil, trace.Wrap(err)
}
}
if config.Clock == nil {
config.Clock = &timetools.RealTime{}
}
limiter.clock = config.Clock
limiter.TokenLimiter, err = ratelimit.New(nil, ipExtractor,
limiter.rates, ratelimit.Clock(config.Clock))
if err != nil {
return nil, trace.Wrap(err)
}
maxNumberOfUsers := config.MaxNumberOfUsers
if maxNumberOfUsers <= 0 {
maxNumberOfUsers = DefaultMaxNumberOfUsers
}
limiter.rateLimits, err = ttlmap.NewMap(
maxNumberOfUsers, ttlmap.Clock(config.Clock))
if err != nil {
return nil, trace.Wrap(err)
}
return &limiter, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/limiter/ratelimiter.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/limiter/ratelimiter.go#L100-L127 | go | train | // RegisterRequest increases number of requests for the provided token
// Returns error if there are too many requests with the provided token | func (l *RateLimiter) RegisterRequest(token string) error | // RegisterRequest increases number of requests for the provided token
// Returns error if there are too many requests with the provided token
func (l *RateLimiter) RegisterRequest(token string) error | {
l.Lock()
defer l.Unlock()
bucketSetI, exists := l.rateLimits.Get(token)
var bucketSet *ratelimit.TokenBucketSet
if exists {
bucketSet = bucketSetI.(*ratelimit.TokenBucketSet)
bucketSet.Update(l.rates)
} else {
bucketSet = ratelimit.NewTokenBucketSet(l.rates, l.clock)
// We set ttl as 10 times rate period. E.g. if rate is 100 requests/second per client ip
// the counters for this ip will expire after 10 seconds of inactivity
err := l.rateLimits.Set(token, bucketSet, int(bucketSet.GetMaxPeriod()/time.Second)*10+1)
if err != nil {
return trace.Wrap(err)
}
}
delay, err := bucketSet.Consume(1)
if err != nil {
return err
}
if delay > 0 {
return &ratelimit.MaxRateError{}
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/limiter/ratelimiter.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/limiter/ratelimiter.go#L130-L132 | go | train | // Add rate limiter to the handle | func (l *RateLimiter) WrapHandle(h http.Handler) | // Add rate limiter to the handle
func (l *RateLimiter) WrapHandle(h http.Handler) | {
l.TokenLimiter.Wrap(h)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L97-L100 | go | train | // EncodeClusterName encodes cluster name in the SNI hostname | func EncodeClusterName(clusterName string) string | // EncodeClusterName encodes cluster name in the SNI hostname
func EncodeClusterName(clusterName string) string | {
// hex is used to hide "." that will prevent wildcard *. entry to match
return fmt.Sprintf("%v.%v", hex.EncodeToString([]byte(clusterName)), teleport.APIDomain)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L106-L121 | go | train | // DecodeClusterName decodes cluster name, returns NotFound
// if no cluster name is encoded (empty subdomain),
// so servers can detect cases when no server name passed
// returns BadParameter if encoding does not match | func DecodeClusterName(serverName string) (string, error) | // DecodeClusterName decodes cluster name, returns NotFound
// if no cluster name is encoded (empty subdomain),
// so servers can detect cases when no server name passed
// returns BadParameter if encoding does not match
func DecodeClusterName(serverName string) (string, error) | {
if serverName == teleport.APIDomain {
return "", trace.NotFound("no cluster name is encoded")
}
const suffix = "." + teleport.APIDomain
if !strings.HasSuffix(serverName, suffix) {
return "", trace.BadParameter("unrecognized name, expected suffix %v, got %q", teleport.APIDomain, serverName)
}
clusterName := strings.TrimSuffix(serverName, suffix)
decoded, err := hex.DecodeString(clusterName)
if err != nil {
return "", trace.BadParameter("failed to decode cluster name: %v", err)
}
return string(decoded), nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L124-L142 | go | train | // NewAddrDialer returns new dialer from a list of addresses | func NewAddrDialer(addrs []utils.NetAddr) DialContext | // NewAddrDialer returns new dialer from a list of addresses
func NewAddrDialer(addrs []utils.NetAddr) DialContext | {
dialer := net.Dialer{
Timeout: defaults.DefaultDialTimeout,
KeepAlive: defaults.ReverseTunnelAgentHeartbeatPeriod,
}
return func(in context.Context, network, _ string) (net.Conn, error) {
var err error
var conn net.Conn
for _, addr := range addrs {
conn, err = dialer.DialContext(in, network, addr.Addr)
if err == nil {
return conn, nil
}
log.Errorf("Failed to dial auth server %v: %v.", addr.Addr, err)
}
// not wrapping on purpose to preserve the original error
return nil, err
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L146-L156 | go | train | // ClientTimeout sets idle and dial timeouts of the HTTP transport
// used by the client. | func ClientTimeout(timeout time.Duration) roundtrip.ClientParam | // ClientTimeout sets idle and dial timeouts of the HTTP transport
// used by the client.
func ClientTimeout(timeout time.Duration) roundtrip.ClientParam | {
return func(c *roundtrip.Client) error {
transport, ok := (c.HTTPClient().Transport).(*http.Transport)
if !ok {
return nil
}
transport.IdleConnTimeout = timeout
transport.ResponseHeaderTimeout = timeout
return nil
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L175-L206 | go | train | // CheckAndSetDefaults checks and sets default config values | func (c *ClientConfig) CheckAndSetDefaults() error | // CheckAndSetDefaults checks and sets default config values
func (c *ClientConfig) CheckAndSetDefaults() error | {
if len(c.Addrs) == 0 && c.DialContext == nil {
return trace.BadParameter("set parameter Addrs or DialContext")
}
if c.TLS == nil {
return trace.BadParameter("missing parameter TLS")
}
if c.KeepAlivePeriod == 0 {
c.KeepAlivePeriod = defaults.ServerKeepAliveTTL
}
if c.KeepAliveCount == 0 {
c.KeepAliveCount = defaults.KeepAliveCountMax
}
if c.DialContext == nil {
c.DialContext = NewAddrDialer(c.Addrs)
}
if c.TLS.ServerName == "" {
c.TLS.ServerName = teleport.APIDomain
}
// this logic is necessary to force client to always send certificate
// regardless of the server setting, otherwise client may pick
// not to send the client certificate by looking at certificate request
if len(c.TLS.Certificates) != 0 {
cert := c.TLS.Certificates[0]
c.TLS.Certificates = nil
c.TLS.GetClientCertificate = func(_ *tls.CertificateRequestInfo) (*tls.Certificate, error) {
return &cert, nil
}
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L210-L252 | go | train | // NewTLSClient returns a new TLS client that uses mutual TLS authentication
// and dials the remote server using dialer | func NewTLSClient(cfg ClientConfig, params ...roundtrip.ClientParam) (*Client, error) | // NewTLSClient returns a new TLS client that uses mutual TLS authentication
// and dials the remote server using dialer
func NewTLSClient(cfg ClientConfig, params ...roundtrip.ClientParam) (*Client, error) | {
if err := cfg.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
transport := &http.Transport{
// notice that below roundtrip.Client is passed
// teleport.APIEndpoint as an address for the API server, this is
// to make sure client verifies the DNS name of the API server
// custom DialContext overrides this DNS name to the real address
// in addition this dialer tries multiple adresses if provided
DialContext: cfg.DialContext,
ResponseHeaderTimeout: defaults.DefaultDialTimeout,
TLSClientConfig: cfg.TLS,
// Increase the size of the connection pool. This substantially improves the
// performance of Teleport under load as it reduces the number of TLS
// handshakes performed.
MaxIdleConns: defaults.HTTPMaxIdleConns,
MaxIdleConnsPerHost: defaults.HTTPMaxIdleConnsPerHost,
// IdleConnTimeout defines the maximum amount of time before idle connections
// are closed. Leaving this unset will lead to connections open forever and
// will cause memory leaks in a long running process.
IdleConnTimeout: defaults.HTTPIdleTimeout,
}
clientParams := append(
[]roundtrip.ClientParam{
roundtrip.HTTPClient(&http.Client{Transport: transport}),
roundtrip.SanitizerEnabled(true),
},
params...,
)
roundtripClient, err := roundtrip.NewClient("https://"+teleport.APIDomain, CurrentVersion, clientParams...)
if err != nil {
return nil, trace.Wrap(err)
}
return &Client{
ClientConfig: cfg,
Client: *roundtripClient,
transport: transport,
}, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L263-L299 | go | train | // grpc returns grpc client | func (c *Client) grpc() (proto.AuthServiceClient, error) | // grpc returns grpc client
func (c *Client) grpc() (proto.AuthServiceClient, error) | {
// it's ok to lock here, because Dial below is not locking
c.Lock()
defer c.Unlock()
if c.grpcClient != nil {
return c.grpcClient, nil
}
dialer := grpc.WithDialer(func(addr string, timeout time.Duration) (net.Conn, error) {
if c.isClosed() {
return nil, trace.ConnectionProblem(nil, "client is closed")
}
c, err := c.DialContext(context.TODO(), "tcp", addr)
if err != nil {
log.Debugf("Dial to addr %v failed: %v.", addr, err)
}
return c, err
})
tlsConfig := c.TLS.Clone()
tlsConfig.NextProtos = []string{http2.NextProtoTLS}
log.Debugf("GRPC(): keep alive %v count: %v.", c.KeepAlivePeriod, c.KeepAliveCount)
conn, err := grpc.Dial(teleport.APIDomain,
dialer,
grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig)),
grpc.WithKeepaliveParams(keepalive.ClientParameters{
Time: c.KeepAlivePeriod,
Timeout: c.KeepAlivePeriod * time.Duration(c.KeepAliveCount),
}),
)
if err != nil {
return nil, trail.FromGRPC(err)
}
c.conn = conn
c.grpcClient = proto.NewAuthServiceClient(c.conn)
return c.grpcClient, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L312-L315 | go | train | // PutJSON is a generic method that issues http PUT request to the server | func (c *Client) PutJSON(
endpoint string, val interface{}) (*roundtrip.Response, error) | // PutJSON is a generic method that issues http PUT request to the server
func (c *Client) PutJSON(
endpoint string, val interface{}) (*roundtrip.Response, error) | {
return httplib.ConvertResponse(c.Client.PutJSON(context.TODO(), endpoint, val))
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L318-L323 | go | train | // PostForm is a generic method that issues http POST request to the server | func (c *Client) PostForm(
endpoint string,
vals url.Values,
files ...roundtrip.File) (*roundtrip.Response, error) | // PostForm is a generic method that issues http POST request to the server
func (c *Client) PostForm(
endpoint string,
vals url.Values,
files ...roundtrip.File) (*roundtrip.Response, error) | {
return httplib.ConvertResponse(c.Client.PostForm(context.TODO(), endpoint, vals, files...))
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L326-L328 | go | train | // Get issues http GET request to the server | func (c *Client) Get(u string, params url.Values) (*roundtrip.Response, error) | // Get issues http GET request to the server
func (c *Client) Get(u string, params url.Values) (*roundtrip.Response, error) | {
return httplib.ConvertResponse(c.Client.Get(context.TODO(), u, params))
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L331-L333 | go | train | // Delete issues http Delete Request to the server | func (c *Client) Delete(u string) (*roundtrip.Response, error) | // Delete issues http Delete Request to the server
func (c *Client) Delete(u string) (*roundtrip.Response, error) | {
return httplib.ConvertResponse(c.Client.Delete(context.TODO(), u))
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L337-L350 | go | train | // ProcessKubeCSR processes CSR request against Kubernetes CA, returns
// signed certificate if sucessful. | func (c *Client) ProcessKubeCSR(req KubeCSR) (*KubeCSRResponse, error) | // ProcessKubeCSR processes CSR request against Kubernetes CA, returns
// signed certificate if sucessful.
func (c *Client) ProcessKubeCSR(req KubeCSR) (*KubeCSRResponse, error) | {
if err := req.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
out, err := c.PostJSON(c.Endpoint("kube", "csr"), req)
if err != nil {
return nil, trace.Wrap(err)
}
var re KubeCSRResponse
if err := json.Unmarshal(out.Bytes(), &re); err != nil {
return nil, trace.Wrap(err)
}
return &re, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L354-L367 | go | train | // GetSessions returns a list of active sessions in the cluster
// as reported by auth server | func (c *Client) GetSessions(namespace string) ([]session.Session, error) | // GetSessions returns a list of active sessions in the cluster
// as reported by auth server
func (c *Client) GetSessions(namespace string) ([]session.Session, error) | {
if namespace == "" {
return nil, trace.BadParameter(MissingNamespaceError)
}
out, err := c.Get(c.Endpoint("namespaces", namespace, "sessions"), url.Values{})
if err != nil {
return nil, trace.Wrap(err)
}
var sessions []session.Session
if err := json.Unmarshal(out.Bytes(), &sessions); err != nil {
return nil, err
}
return sessions, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L370-L387 | go | train | // GetSession returns a session by ID | func (c *Client) GetSession(namespace string, id session.ID) (*session.Session, error) | // GetSession returns a session by ID
func (c *Client) GetSession(namespace string, id session.ID) (*session.Session, error) | {
if namespace == "" {
return nil, trace.BadParameter(MissingNamespaceError)
}
// saving extra round-trip
if err := id.Check(); err != nil {
return nil, trace.Wrap(err)
}
out, err := c.Get(c.Endpoint("namespaces", namespace, "sessions", string(id)), url.Values{})
if err != nil {
return nil, trace.Wrap(err)
}
var sess *session.Session
if err := json.Unmarshal(out.Bytes(), &sess); err != nil {
return nil, trace.Wrap(err)
}
return sess, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L390-L396 | go | train | // DeleteSession deletes a session by ID | func (c *Client) DeleteSession(namespace, id string) error | // DeleteSession deletes a session by ID
func (c *Client) DeleteSession(namespace, id string) error | {
if namespace == "" {
return trace.BadParameter(MissingNamespaceError)
}
_, err := c.Delete(c.Endpoint("namespaces", namespace, "sessions", id))
return trace.Wrap(err)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L399-L405 | go | train | // CreateSession creates new session | func (c *Client) CreateSession(sess session.Session) error | // CreateSession creates new session
func (c *Client) CreateSession(sess session.Session) error | {
if sess.Namespace == "" {
return trace.BadParameter(MissingNamespaceError)
}
_, err := c.PostJSON(c.Endpoint("namespaces", sess.Namespace, "sessions"), createSessionReq{Session: sess})
return trace.Wrap(err)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L408-L414 | go | train | // UpdateSession updates existing session | func (c *Client) UpdateSession(req session.UpdateRequest) error | // UpdateSession updates existing session
func (c *Client) UpdateSession(req session.UpdateRequest) error | {
if err := req.Check(); err != nil {
return trace.Wrap(err)
}
_, err := c.PutJSON(c.Endpoint("namespaces", req.Namespace, "sessions", string(req.ID)), updateSessionReq{Update: req})
return trace.Wrap(err)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L417-L427 | go | train | // GetDomainName returns local auth domain of the current auth server | func (c *Client) GetDomainName() (string, error) | // GetDomainName returns local auth domain of the current auth server
func (c *Client) GetDomainName() (string, error) | {
out, err := c.Get(c.Endpoint("domain"), url.Values{})
if err != nil {
return "", trace.Wrap(err)
}
var domain string
if err := json.Unmarshal(out.Bytes(), &domain); err != nil {
return "", trace.Wrap(err)
}
return domain, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L430-L440 | go | train | // GetClusterCACert returns the CAs for the local cluster without signing keys. | func (c *Client) GetClusterCACert() (*LocalCAResponse, error) | // GetClusterCACert returns the CAs for the local cluster without signing keys.
func (c *Client) GetClusterCACert() (*LocalCAResponse, error) | {
out, err := c.Get(c.Endpoint("cacert"), url.Values{})
if err != nil {
return nil, trace.Wrap(err)
}
var localCA LocalCAResponse
if err := json.Unmarshal(out.Bytes(), &localCA); err != nil {
return nil, trace.Wrap(err)
}
return &localCA, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L467-L474 | go | train | // RotateCertAuthority starts or restarts certificate authority rotation process. | func (c *Client) RotateCertAuthority(req RotateRequest) error | // RotateCertAuthority starts or restarts certificate authority rotation process.
func (c *Client) RotateCertAuthority(req RotateRequest) error | {
caType := "all"
if req.Type != "" {
caType = string(req.Type)
}
_, err := c.PostJSON(c.Endpoint("authorities", caType, "rotate"), req)
return trace.Wrap(err)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L479-L490 | go | train | // RotateExternalCertAuthority rotates external certificate authority,
// this method is used to update only public keys and certificates of the
// the certificate authorities of trusted clusters. | func (c *Client) RotateExternalCertAuthority(ca services.CertAuthority) error | // RotateExternalCertAuthority rotates external certificate authority,
// this method is used to update only public keys and certificates of the
// the certificate authorities of trusted clusters.
func (c *Client) RotateExternalCertAuthority(ca services.CertAuthority) error | {
if err := ca.Check(); err != nil {
return trace.Wrap(err)
}
data, err := services.GetCertAuthorityMarshaler().MarshalCertAuthority(ca)
if err != nil {
return trace.Wrap(err)
}
_, err = c.PostJSON(c.Endpoint("authorities", string(ca.GetType()), "rotate", "external"),
&rotateExternalCertAuthorityRawReq{CA: data})
return trace.Wrap(err)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L508-L510 | go | train | // CompareAndSwapCertAuthority updates existing cert authority if the existing cert authority
// value matches the value stored in the backend. | func (c *Client) CompareAndSwapCertAuthority(new, existing services.CertAuthority) error | // CompareAndSwapCertAuthority updates existing cert authority if the existing cert authority
// value matches the value stored in the backend.
func (c *Client) CompareAndSwapCertAuthority(new, existing services.CertAuthority) error | {
return trace.BadParameter("this function is not supported on the client")
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L513-L536 | go | train | // GetCertAuthorities returns a list of certificate authorities | func (c *Client) GetCertAuthorities(caType services.CertAuthType, loadKeys bool, opts ...services.MarshalOption) ([]services.CertAuthority, error) | // GetCertAuthorities returns a list of certificate authorities
func (c *Client) GetCertAuthorities(caType services.CertAuthType, loadKeys bool, opts ...services.MarshalOption) ([]services.CertAuthority, error) | {
if err := caType.Check(); err != nil {
return nil, trace.Wrap(err)
}
out, err := c.Get(c.Endpoint("authorities", string(caType)), url.Values{
"load_keys": []string{fmt.Sprintf("%t", loadKeys)},
})
if err != nil {
return nil, trace.Wrap(err)
}
var items []json.RawMessage
if err := json.Unmarshal(out.Bytes(), &items); err != nil {
return nil, err
}
re := make([]services.CertAuthority, len(items))
for i, raw := range items {
ca, err := services.GetCertAuthorityMarshaler().UnmarshalCertAuthority(raw, services.SkipValidation())
if err != nil {
return nil, trace.Wrap(err)
}
re[i] = ca
}
return re, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L540-L552 | go | train | // GetCertAuthority returns certificate authority by given id. Parameter loadSigningKeys
// controls if signing keys are loaded | func (c *Client) GetCertAuthority(id services.CertAuthID, loadSigningKeys bool, opts ...services.MarshalOption) (services.CertAuthority, error) | // GetCertAuthority returns certificate authority by given id. Parameter loadSigningKeys
// controls if signing keys are loaded
func (c *Client) GetCertAuthority(id services.CertAuthID, loadSigningKeys bool, opts ...services.MarshalOption) (services.CertAuthority, error) | {
if err := id.Check(); err != nil {
return nil, trace.Wrap(err)
}
out, err := c.Get(c.Endpoint("authorities", string(id.Type), id.DomainName), url.Values{
"load_keys": []string{fmt.Sprintf("%t", loadSigningKeys)},
})
if err != nil {
return nil, trace.Wrap(err)
}
return services.GetCertAuthorityMarshaler().UnmarshalCertAuthority(
out.Bytes(), services.SkipValidation())
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L555-L561 | go | train | // DeleteCertAuthority deletes cert authority by ID | func (c *Client) DeleteCertAuthority(id services.CertAuthID) error | // DeleteCertAuthority deletes cert authority by ID
func (c *Client) DeleteCertAuthority(id services.CertAuthID) error | {
if err := id.Check(); err != nil {
return trace.Wrap(err)
}
_, err := c.Delete(c.Endpoint("authorities", string(id.Type), id.DomainName))
return trace.Wrap(err)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L583-L593 | go | train | // GenerateToken creates a special provisioning token for a new SSH server
// that is valid for ttl period seconds.
//
// This token is used by SSH server to authenticate with Auth server
// and get signed certificate and private key from the auth server.
//
// If token is not supplied, it will be auto generated and returned.
// If TTL is not supplied, token will be valid until removed. | func (c *Client) GenerateToken(req GenerateTokenRequest) (string, error) | // GenerateToken creates a special provisioning token for a new SSH server
// that is valid for ttl period seconds.
//
// This token is used by SSH server to authenticate with Auth server
// and get signed certificate and private key from the auth server.
//
// If token is not supplied, it will be auto generated and returned.
// If TTL is not supplied, token will be valid until removed.
func (c *Client) GenerateToken(req GenerateTokenRequest) (string, error) | {
out, err := c.PostJSON(c.Endpoint("tokens"), req)
if err != nil {
return "", trace.Wrap(err)
}
var token string
if err := json.Unmarshal(out.Bytes(), &token); err != nil {
return "", trace.Wrap(err)
}
return token, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L597-L610 | go | train | // RegisterUsingToken calls the auth service API to register a new node using a registration token
// which was previously issued via GenerateToken. | func (c *Client) RegisterUsingToken(req RegisterUsingTokenRequest) (*PackedKeys, error) | // RegisterUsingToken calls the auth service API to register a new node using a registration token
// which was previously issued via GenerateToken.
func (c *Client) RegisterUsingToken(req RegisterUsingTokenRequest) (*PackedKeys, error) | {
if err := req.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
out, err := c.PostJSON(c.Endpoint("tokens", "register"), req)
if err != nil {
return nil, trace.Wrap(err)
}
var keys PackedKeys
if err := json.Unmarshal(out.Bytes(), &keys); err != nil {
return nil, trace.Wrap(err)
}
return &keys, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L631-L641 | go | train | // UpsertToken adds provisioning tokens for the auth server | func (c *Client) UpsertToken(tok services.ProvisionToken) error | // UpsertToken adds provisioning tokens for the auth server
func (c *Client) UpsertToken(tok services.ProvisionToken) error | {
_, err := c.PostJSON(c.Endpoint("tokens"), GenerateTokenRequest{
Token: tok.GetName(),
Roles: tok.GetRoles(),
TTL: backend.TTL(clockwork.NewRealClock(), tok.Expiry()),
})
if err != nil {
return trace.Wrap(err)
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L644-L654 | go | train | // GetTokens returns a list of active invitation tokens for nodes and users | func (c *Client) GetTokens(opts ...services.MarshalOption) ([]services.ProvisionToken, error) | // GetTokens returns a list of active invitation tokens for nodes and users
func (c *Client) GetTokens(opts ...services.MarshalOption) ([]services.ProvisionToken, error) | {
out, err := c.Get(c.Endpoint("tokens"), url.Values{})
if err != nil {
return nil, trace.Wrap(err)
}
var tokens []services.ProvisionTokenV1
if err := json.Unmarshal(out.Bytes(), &tokens); err != nil {
return nil, trace.Wrap(err)
}
return services.ProvisionTokensFromV1(tokens), nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L657-L663 | go | train | // GetToken returns provisioning token | func (c *Client) GetToken(token string) (services.ProvisionToken, error) | // GetToken returns provisioning token
func (c *Client) GetToken(token string) (services.ProvisionToken, error) | {
out, err := c.Get(c.Endpoint("tokens", token), url.Values{})
if err != nil {
return nil, trace.Wrap(err)
}
return services.UnmarshalProvisionToken(out.Bytes(), services.SkipValidation())
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L667-L670 | go | train | // DeleteToken deletes a given provisioning token on the auth server (CA). It
// could be a user token or a machine token | func (c *Client) DeleteToken(token string) error | // DeleteToken deletes a given provisioning token on the auth server (CA). It
// could be a user token or a machine token
func (c *Client) DeleteToken(token string) error | {
_, err := c.Delete(c.Endpoint("tokens", token))
return trace.Wrap(err)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L673-L678 | go | train | // RegisterNewAuthServer is used to register new auth server with token | func (c *Client) RegisterNewAuthServer(token string) error | // RegisterNewAuthServer is used to register new auth server with token
func (c *Client) RegisterNewAuthServer(token string) error | {
_, err := c.PostJSON(c.Endpoint("tokens", "register", "auth"), registerNewAuthServerReq{
Token: token,
})
return trace.Wrap(err)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L682-L699 | go | train | // UpsertNode is used by SSH servers to reprt their presence
// to the auth servers in form of hearbeat expiring after ttl period. | func (c *Client) UpsertNode(s services.Server) (*services.KeepAlive, error) | // UpsertNode is used by SSH servers to reprt their presence
// to the auth servers in form of hearbeat expiring after ttl period.
func (c *Client) UpsertNode(s services.Server) (*services.KeepAlive, error) | {
if s.GetNamespace() == "" {
return nil, trace.BadParameter("missing node namespace")
}
protoServer, ok := s.(*services.ServerV2)
if !ok {
return nil, trace.BadParameter("unsupported client")
}
clt, err := c.grpc()
if err != nil {
return nil, trace.Wrap(err)
}
keepAlive, err := clt.UpsertNode(context.TODO(), protoServer)
if err != nil {
return nil, trail.FromGRPC(err)
}
return keepAlive, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L702-L704 | go | train | // KeepAliveNode updates node keep alive information | func (c *Client) KeepAliveNode(ctx context.Context, keepAlive services.KeepAlive) error | // KeepAliveNode updates node keep alive information
func (c *Client) KeepAliveNode(ctx context.Context, keepAlive services.KeepAlive) error | {
return trace.BadParameter("not implemented, use StreamKeepAlives instead")
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L707-L727 | go | train | // NewKeepAliver returns a new instance of keep aliver | func (c *Client) NewKeepAliver(ctx context.Context) (services.KeepAliver, error) | // NewKeepAliver returns a new instance of keep aliver
func (c *Client) NewKeepAliver(ctx context.Context) (services.KeepAliver, error) | {
clt, err := c.grpc()
if err != nil {
return nil, trace.Wrap(err)
}
cancelCtx, cancel := context.WithCancel(ctx)
stream, err := clt.SendKeepAlives(cancelCtx)
if err != nil {
cancel()
return nil, trail.FromGRPC(err)
}
k := &streamKeepAliver{
stream: stream,
ctx: cancelCtx,
cancel: cancel,
keepAlivesC: make(chan services.KeepAlive),
}
go k.forwardKeepAlives()
go k.recv()
return k, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L769-L772 | go | train | // recv is necessary to receive errors from the
// server, otherwise no errors will be propagated | func (k *streamKeepAliver) recv() | // recv is necessary to receive errors from the
// server, otherwise no errors will be propagated
func (k *streamKeepAliver) recv() | {
err := k.stream.RecvMsg(&empty.Empty{})
k.closeWithError(trail.FromGRPC(err))
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L787-L814 | go | train | // NewWatcher returns a new event watcher | func (c *Client) NewWatcher(ctx context.Context, watch services.Watch) (services.Watcher, error) | // NewWatcher returns a new event watcher
func (c *Client) NewWatcher(ctx context.Context, watch services.Watch) (services.Watcher, error) | {
clt, err := c.grpc()
if err != nil {
return nil, trace.Wrap(err)
}
cancelCtx, cancel := context.WithCancel(ctx)
var protoWatch proto.Watch
for _, kind := range watch.Kinds {
protoWatch.Kinds = append(protoWatch.Kinds, proto.WatchKind{
Name: kind.Name,
Kind: kind.Kind,
LoadSecrets: kind.LoadSecrets,
})
}
stream, err := clt.WatchEvents(cancelCtx, &protoWatch)
if err != nil {
cancel()
return nil, trail.FromGRPC(err)
}
w := &streamWatcher{
stream: stream,
ctx: cancelCtx,
cancel: cancel,
eventsC: make(chan services.Event),
}
go w.receiveEvents()
return w, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L873-L888 | go | train | // UpsertNodes bulk inserts nodes. | func (c *Client) UpsertNodes(namespace string, servers []services.Server) error | // UpsertNodes bulk inserts nodes.
func (c *Client) UpsertNodes(namespace string, servers []services.Server) error | {
if namespace == "" {
return trace.BadParameter("missing node namespace")
}
bytes, err := services.GetServerMarshaler().MarshalServers(servers)
if err != nil {
return trace.Wrap(err)
}
args := &upsertNodesReq{
Namespace: namespace,
Nodes: bytes,
}
_, err = c.PutJSON(c.Endpoint("namespaces", namespace, "nodes"), args)
return trace.Wrap(err)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L891-L897 | go | train | // DeleteAllNodes deletes all nodes in a given namespace | func (c *Client) DeleteAllNodes(namespace string) error | // DeleteAllNodes deletes all nodes in a given namespace
func (c *Client) DeleteAllNodes(namespace string) error | {
_, err := c.Delete(c.Endpoint("namespaces", namespace, "nodes"))
if err != nil {
return trace.Wrap(err)
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L900-L912 | go | train | // DeleteNode deletes node in the namespace by name | func (c *Client) DeleteNode(namespace string, name string) error | // DeleteNode deletes node in the namespace by name
func (c *Client) DeleteNode(namespace string, name string) error | {
if namespace == "" {
return trace.BadParameter("missing parameter namespace")
}
if name == "" {
return trace.BadParameter("missing parameter name")
}
_, err := c.Delete(c.Endpoint("namespaces", namespace, "nodes", name))
if err != nil {
return trace.Wrap(err)
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L915-L948 | go | train | // GetNodes returns the list of servers registered in the cluster. | func (c *Client) GetNodes(namespace string, opts ...services.MarshalOption) ([]services.Server, error) | // GetNodes returns the list of servers registered in the cluster.
func (c *Client) GetNodes(namespace string, opts ...services.MarshalOption) ([]services.Server, error) | {
if namespace == "" {
return nil, trace.BadParameter(MissingNamespaceError)
}
cfg, err := services.CollectOptions(opts)
if err != nil {
return nil, trace.Wrap(err)
}
out, err := c.Get(c.Endpoint("namespaces", namespace, "nodes"), url.Values{
"skip_validation": []string{fmt.Sprintf("%t", cfg.SkipValidation)},
})
if err != nil {
return nil, trace.Wrap(err)
}
var items []json.RawMessage
if err := json.Unmarshal(out.Bytes(), &items); err != nil {
return nil, trace.Wrap(err)
}
re := make([]services.Server, len(items))
for i, raw := range items {
s, err := services.GetServerMarshaler().UnmarshalServer(
raw,
services.KindNode,
services.AddOptions(opts, services.SkipValidation())...)
if err != nil {
return nil, trace.Wrap(err)
}
re[i] = s
}
return re, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L952-L962 | go | train | // UpsertReverseTunnel is used by admins to create a new reverse tunnel
// to the remote proxy to bypass firewall restrictions | func (c *Client) UpsertReverseTunnel(tunnel services.ReverseTunnel) error | // UpsertReverseTunnel is used by admins to create a new reverse tunnel
// to the remote proxy to bypass firewall restrictions
func (c *Client) UpsertReverseTunnel(tunnel services.ReverseTunnel) error | {
data, err := services.GetReverseTunnelMarshaler().MarshalReverseTunnel(tunnel)
if err != nil {
return trace.Wrap(err)
}
args := &upsertReverseTunnelRawReq{
ReverseTunnel: data,
}
_, err = c.PostJSON(c.Endpoint("reversetunnels"), args)
return trace.Wrap(err)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L965-L967 | go | train | // GetReverseTunnel returns reverse tunnel by name | func (c *Client) GetReverseTunnel(name string, opts ...services.MarshalOption) (services.ReverseTunnel, error) | // GetReverseTunnel returns reverse tunnel by name
func (c *Client) GetReverseTunnel(name string, opts ...services.MarshalOption) (services.ReverseTunnel, error) | {
return nil, trace.NotImplemented("not implemented")
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L970-L988 | go | train | // GetReverseTunnels returns the list of created reverse tunnels | func (c *Client) GetReverseTunnels(opts ...services.MarshalOption) ([]services.ReverseTunnel, error) | // GetReverseTunnels returns the list of created reverse tunnels
func (c *Client) GetReverseTunnels(opts ...services.MarshalOption) ([]services.ReverseTunnel, error) | {
out, err := c.Get(c.Endpoint("reversetunnels"), url.Values{})
if err != nil {
return nil, trace.Wrap(err)
}
var items []json.RawMessage
if err := json.Unmarshal(out.Bytes(), &items); err != nil {
return nil, trace.Wrap(err)
}
tunnels := make([]services.ReverseTunnel, len(items))
for i, raw := range items {
tunnel, err := services.GetReverseTunnelMarshaler().UnmarshalReverseTunnel(raw, services.SkipValidation())
if err != nil {
return nil, trace.Wrap(err)
}
tunnels[i] = tunnel
}
return tunnels, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L991-L1000 | go | train | // DeleteReverseTunnel deletes reverse tunnel by domain name | func (c *Client) DeleteReverseTunnel(domainName string) error | // DeleteReverseTunnel deletes reverse tunnel by domain name
func (c *Client) DeleteReverseTunnel(domainName string) error | {
// this is to avoid confusing error in case if domain empty for example
// HTTP route will fail producing generic not found error
// instead we catch the error here
if strings.TrimSpace(domainName) == "" {
return trace.BadParameter("empty domain name")
}
_, err := c.Delete(c.Endpoint("reversetunnels", domainName))
return trace.Wrap(err)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L1003-L1013 | go | train | // UpsertTunnelConnection upserts tunnel connection | func (c *Client) UpsertTunnelConnection(conn services.TunnelConnection) error | // UpsertTunnelConnection upserts tunnel connection
func (c *Client) UpsertTunnelConnection(conn services.TunnelConnection) error | {
data, err := services.MarshalTunnelConnection(conn)
if err != nil {
return trace.Wrap(err)
}
args := &upsertTunnelConnectionRawReq{
TunnelConnection: data,
}
_, err = c.PostJSON(c.Endpoint("tunnelconnections"), args)
return trace.Wrap(err)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L1061-L1070 | go | train | // DeleteTunnelConnection deletes tunnel connection by name | func (c *Client) DeleteTunnelConnection(clusterName string, connName string) error | // DeleteTunnelConnection deletes tunnel connection by name
func (c *Client) DeleteTunnelConnection(clusterName string, connName string) error | {
if clusterName == "" {
return trace.BadParameter("missing parameter cluster name")
}
if connName == "" {
return trace.BadParameter("missing parameter connection name")
}
_, err := c.Delete(c.Endpoint("tunnelconnections", clusterName, connName))
return trace.Wrap(err)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L1093-L1095 | go | train | // AddUserLoginAttempt logs user login attempt | func (c *Client) AddUserLoginAttempt(user string, attempt services.LoginAttempt, ttl time.Duration) error | // AddUserLoginAttempt logs user login attempt
func (c *Client) AddUserLoginAttempt(user string, attempt services.LoginAttempt, ttl time.Duration) error | {
panic("not implemented")
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L1103-L1121 | go | train | // GetRemoteClusters returns a list of remote clusters | func (c *Client) GetRemoteClusters(opts ...services.MarshalOption) ([]services.RemoteCluster, error) | // GetRemoteClusters returns a list of remote clusters
func (c *Client) GetRemoteClusters(opts ...services.MarshalOption) ([]services.RemoteCluster, error) | {
out, err := c.Get(c.Endpoint("remoteclusters"), url.Values{})
if err != nil {
return nil, trace.Wrap(err)
}
var items []json.RawMessage
if err := json.Unmarshal(out.Bytes(), &items); err != nil {
return nil, trace.Wrap(err)
}
conns := make([]services.RemoteCluster, len(items))
for i, raw := range items {
conn, err := services.UnmarshalRemoteCluster(raw, services.SkipValidation())
if err != nil {
return nil, trace.Wrap(err)
}
conns[i] = conn
}
return conns, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/clt.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/clt.go#L1124-L1133 | go | train | // GetRemoteCluster returns a remote cluster by name | func (c *Client) GetRemoteCluster(clusterName string) (services.RemoteCluster, error) | // GetRemoteCluster returns a remote cluster by name
func (c *Client) GetRemoteCluster(clusterName string) (services.RemoteCluster, error) | {
if clusterName == "" {
return nil, trace.BadParameter("missing cluster name")
}
out, err := c.Get(c.Endpoint("remoteclusters", clusterName), url.Values{})
if err != nil {
return nil, trace.Wrap(err)
}
return services.UnmarshalRemoteCluster(out.Bytes(), services.SkipValidation())
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.