web

package
v1.3.3-0...-f31c912 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 9, 2024 License: AGPL-3.0 Imports: 146 Imported by: 59

Documentation

Overview

Package web implements web proxy handler that provides web interface to view and connect to teleport nodes

Package web implements web proxy handler that provides web interface to view and connect to teleport nodes

Index

Constants

View Source
const (
	EnvelopeTypeStdout = "stdout"
)
View Source
const (
	// OIDCJWKWURI is the relative path where the OIDC IdP JWKS is located
	OIDCJWKWURI = "/.well-known/jwks-oidc"
)
View Source
const (
	// SNISuffix is the server name suffix used during SNI to specify the
	// target desktop to connect to. The client (proxy_service) will use SNI
	// like "${UUID}.desktop.teleport.cluster.local" to pass the UUID of the
	// desktop.
	// This is a copy of the same constant in `lib/srv/desktop/desktop.go` to
	// prevent depending on `lib/srv` in `lib/web`.
	SNISuffix = ".desktop." + constants.APIDomain
)
View Source
const (
	// SSOLoginFailureMessage is a generic error message to avoid disclosing sensitive SSO failure messages.
	SSOLoginFailureMessage = "Failed to login. Please check Teleport's log for more details."
)

Variables

View Source
var (
	ErrInvalidLengthEnvelope        = fmt.Errorf("proto: negative length found during unmarshaling")
	ErrIntOverflowEnvelope          = fmt.Errorf("proto: integer overflow")
	ErrUnexpectedEndOfGroupEnvelope = fmt.Errorf("proto: unexpected end of group")
)

Functions

func CheckResourceUpsert

func CheckResourceUpsert(ctx context.Context, httpMethod string, params httprouter.Params, payloadResourceName string, get getResource) error

CheckResourceUpsert checks if the resource can be created or updated, depending on the http method.

func ConstructSSHResponse added in v1.0.0

func ConstructSSHResponse(response AuthParams) (*url.URL, error)

ConstructSSHResponse creates a special SSH response for SSH login method that encodes everything using the client's secret key

func CreateResource

func CreateResource[T types.Resource](r *http.Request, kind string, unmarshalFn unmarshalFunc[T], createFn func(ctx context.Context, r T) (T, error)) (*ui.ResourceItem, error)

CreateResource is a helper function for POST requests from the UI to create a new resource. It will validate the request contains the appropriate items, that the resource attempting to be created is valid. If all validations are satisfied then the creation is attempted. If the resource already exists a trace.AlreadyExists error is returned.

func ExtractResourceAndValidate

func ExtractResourceAndValidate(yaml string) (*services.UnknownResource, error)

ExtractResourceAndValidate extracts resource information from given string and validates basic fields.

func NewXForwardedForMiddleware

func NewXForwardedForMiddleware(next http.Handler) http.Handler

NewXForwardedForMiddleware is an HTTP middleware that overwrites client source address if X-Forwarded-For is set.

Both hijacked conn and request context are updated. The hijacked conn can be used for ALPN connection upgrades or Websocket connections.

func OK

func OK() interface{}

OK is a response that indicates request was successful.

func RedirectURLWithError

func RedirectURLWithError(clientRedirectURL string, errReply error) (*url.URL, error)

RedirectURLWithError adds an err query parameter to the given redirect URL with the given errReply message and returns the new URL. If the given URL cannot be parsed, an error is returned with a nil URL. It is used to return an error back to the original URL in an SSO callback when validation fails.

func SSOSetWebSessionAndRedirectURL

func SSOSetWebSessionAndRedirectURL(w http.ResponseWriter, r *http.Request, response *SSOCallbackResponse, verifyCSRF bool) error

SSOSetWebSessionAndRedirectURL validates the CSRF token in the response against that in the request, validates that the callback URL in the response can be parsed, and sets a session cookie with the username and session name from the response. On success, nil is returned. If the validation fails, an error is returned.

func UpdateResource

func UpdateResource[T types.Resource](r *http.Request, params httprouter.Params, kind string, unmarshalFn unmarshalFunc[T], updateFn func(ctx context.Context, r T) (T, error)) (*ui.ResourceItem, error)

UpdateResource is a helper function for PUT requests from the UI to update an existing resource. It will validate the request contains the appropriate items, that the resource attempting to be updated is valid. If all validations are satisfied then the update is attempted. If the resource does not exist a trace.NotFound error is returned.

Types

type APIHandler

type APIHandler struct {
	// contains filtered or unexported fields
}

func NewHandler added in v1.0.0

func NewHandler(cfg Config, opts ...HandlerOption) (*APIHandler, error)

NewHandler returns a new instance of web proxy handler

func (*APIHandler) Close

func (h *APIHandler) Close() error

func (*APIHandler) HandleConnection

func (h *APIHandler) HandleConnection(ctx context.Context, conn net.Conn) error

HandleConnection handles connections from plain TCP applications.

func (*APIHandler) ServeHTTP

func (h *APIHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

Check if this request should be forwarded to an application handler to be handled by the UI and handle the request appropriately.

type AssistUserPreferencesResponse

type AssistUserPreferencesResponse struct {
	PreferredLogins []string                         `json:"preferredLogins"`
	ViewMode        userpreferencesv1.AssistViewMode `json:"viewMode"`
}

AssistUserPreferencesResponse is the JSON response for the assist user preferences.

type AuthParams

type AuthParams struct {
	// Username is authenticated teleport username
	Username string
	// Identity contains validated OIDC identity
	Identity types.ExternalIdentity
	// Web session will be generated by auth server if requested in OIDCAuthRequest
	Session types.WebSession
	// Cert will be generated by certificate authority
	Cert []byte
	// TLSCert is PEM encoded TLS certificate
	TLSCert []byte
	// HostSigners is a list of signing host public keys
	// trusted by proxy, used in console login
	HostSigners []types.CertAuthority
	// ClientRedirectURL is a URL to redirect client to
	ClientRedirectURL string
	// FIPS mode means Teleport started in a FedRAMP/FIPS 140-2 compliant
	// configuration.
	FIPS bool
}

AuthParams are used to construct redirect URL containing auth information back to tsh login

type ClusterClientHandler

type ClusterClientHandler func(http.ResponseWriter, *http.Request, httprouter.Params, *SessionContext, ClusterClientProvider) (interface{}, error)

ClusterClientHandler is an authenticated handler which can get a client for any remote cluster.

type ClusterClientProvider

type ClusterClientProvider interface {
	// UserClientForCluster returns a client to the local or remote cluster
	// identified by clusterName and is authenticated with the identity of the
	// user.
	UserClientForCluster(ctx context.Context, clusterName string) (auth.ClientI, error)
}

ClusterClientProvider is an interface for a type which can provide authenticated clients to remote clusters.

type ClusterHandler

type ClusterHandler func(w http.ResponseWriter, r *http.Request, p httprouter.Params, sctx *SessionContext, site reversetunnelclient.RemoteSite) (interface{}, error)

ClusterHandler is a authenticated handler that is called for some existing remote cluster

type ClusterUserPreferencesResponse

type ClusterUserPreferencesResponse struct {
	PinnedResources []string `json:"pinnedResources"`
}

ClusterUserPreferencesResponse is the JSON response for the user's cluster preferences.

type CommandHandlerConfig

type CommandHandlerConfig struct {
	// SessionCtx is the context for the user's web session.
	SessionCtx *SessionContext
	// UserAuthClient is used to fetch nodes and sessions from the backend via the users' identity.
	UserAuthClient UserAuthClient
	// SessionData is the data to send to the client on the initial session creation.
	SessionData session.Session
	// KeepAliveInterval is the interval for sending ping frames to a web client.
	// This value is pulled from the cluster network config and
	// guaranteed to be set to a nonzero value as it's enforced by the configuration.
	KeepAliveInterval time.Duration
	// ProxyHostPort is the address of the server to connect to.
	ProxyHostPort string
	// InteractiveCommand is a command to execute.
	InteractiveCommand []string
	// Router determines how connections to nodes are created
	Router *proxy.Router
	// TracerProvider is used to create the tracer
	TracerProvider oteltrace.TracerProvider
	// LocalAccessPoint is the subset of the Proxy cache required to
	// look up information from the local cluster. This should not
	// be used for anything that requires RBAC on behalf of the user.
	// Anything requests that should be made on behalf of the user should
	// use [UserAuthClient].
	LocalAccessPoint localAccessPoint
	// contains filtered or unexported fields
}

CommandHandlerConfig is the configuration for the command handler.

func (*CommandHandlerConfig) CheckAndSetDefaults

func (t *CommandHandlerConfig) CheckAndSetDefaults() error

CheckAndSetDefaults checks and sets default values.

type CommandRequest

type CommandRequest struct {
	// Command is the command to be executed on all nodes.
	Command string `json:"command"`
	// Login is a Linux username to connect as.
	Login string `json:"login"`
	// Query is the predicate query to filter nodes where the command will be executed.
	Query string `json:"query"`
	// ConversationID is the conversation context that was used to execute the command.
	ConversationID string `json:"conversation_id"`
	// ExecutionID is a unique ID used to identify the command execution.
	ExecutionID string `json:"execution_id"`
}

CommandRequest is a request to execute a command on all nodes that match the query.

func (*CommandRequest) Check

func (c *CommandRequest) Check() error

Check checks if the request is valid.

type Config added in v1.0.0

type Config struct {
	// PluginRegistry handles plugin registration
	PluginRegistry plugin.Registry
	// Proxy is a reverse tunnel proxy that handles connections
	// to local cluster or remote clusters using unified interface
	Proxy reversetunnelclient.Tunnel
	// AuthServers is a list of auth servers this proxy talks to
	AuthServers utils.NetAddr
	// DomainName is a domain name served by web handler
	DomainName string
	// ProxyClient is a client that authenticated as proxy
	ProxyClient auth.ClientI
	// ProxySSHAddr points to the SSH address of the proxy
	ProxySSHAddr utils.NetAddr
	// ProxyKubeAddr points to the Kube address of the proxy
	ProxyKubeAddr utils.NetAddr
	// ProxyWebAddr points to the web (HTTPS) address of the proxy
	ProxyWebAddr utils.NetAddr
	// ProxyPublicAddr contains web proxy public addresses.
	ProxyPublicAddrs []utils.NetAddr

	// CipherSuites is the list of cipher suites Teleport suppports.
	CipherSuites []uint16

	// FIPS mode means Teleport started in a FedRAMP/FIPS 140-2 compliant
	// configuration.
	FIPS bool

	// AccessPoint holds a cache to the Auth Server.
	AccessPoint auth.ProxyAccessPoint

	// Emitter is event emitter
	Emitter apievents.Emitter

	// HostUUID is the UUID of this process.
	HostUUID string

	// Context is used to signal process exit.
	Context context.Context

	// StaticFS optionally specifies the HTTP file system to use.
	// Enables web UI if set.
	StaticFS http.FileSystem

	// CachedSessionLingeringThreshold specifies the time the session will linger
	// in the cache before getting purged after it has expired.
	// Defaults to cachedSessionLingeringThreshold if unspecified.
	CachedSessionLingeringThreshold *time.Duration

	// ClusterFeatures contains flags for supported/unsupported features.
	ClusterFeatures proto.Features

	// ProxySettings allows fetching the current proxy settings.
	ProxySettings proxySettingsGetter

	// MinimalReverseTunnelRoutesOnly mode handles only the endpoints required for
	// a reverse tunnel agent to establish a connection.
	MinimalReverseTunnelRoutesOnly bool

	// PublicProxyAddr is used to template the public proxy address
	// into the installer script responses
	PublicProxyAddr string

	// ALPNHandler is the ALPN connection handler for handling upgraded ALPN
	// connection through a HTTP upgrade call.
	ALPNHandler ConnectionHandler

	// TraceClient is used to forward spans to the upstream collector for the UI
	TraceClient otlptrace.Client

	// Router is used to route ssh sessions to hosts
	Router *proxy.Router

	// SessionControl is used to determine if users are
	// allowed to spawn new sessions
	SessionControl SessionController

	// PROXYSigner is used to sign PROXY header and securely propagate client IP information
	PROXYSigner multiplexer.PROXYHeaderSigner

	// TracerProvider generates tracers to create spans with
	TracerProvider oteltrace.TracerProvider

	// HealthCheckAppServer is a function that checks if the proxy can handle
	// application requests.
	HealthCheckAppServer healthCheckAppServerFunc

	// UI provides config options for the web UI
	UI webclient.UIConfig

	// OpenAIConfig provides config options for the OpenAI integration.
	OpenAIConfig *openai.ClientConfig

	// NodeWatcher is a services.NodeWatcher used by Assist to lookup nodes from
	// the proxy's cache and get nodes in real time.
	NodeWatcher *services.NodeWatcher

	// PresenceChecker periodically runs the mfa ceremony for moderated
	// sessions.
	PresenceChecker PresenceChecker

	// AccessGraphAddr is the address of the Access Graph service GRPC API
	AccessGraphAddr utils.NetAddr

	// AutomaticUpgradesChannels is a map of all version channels used by the
	// proxy built-in version server to retrieve target versions. This is part
	// of the automatic upgrades.
	AutomaticUpgradesChannels automaticupgrades.Channels
}

Config represents web handler configuration parameters

func (*Config) SetDefaults

func (c *Config) SetDefaults()

SetDefaults ensures proper default values are set if not provided.

type ConnectionHandler

type ConnectionHandler func(ctx context.Context, conn net.Conn) error

ConnectionHandler defines a function for serving incoming connections.

type ContextHandler

type ContextHandler func(w http.ResponseWriter, r *http.Request, p httprouter.Params, ctx *SessionContext) (interface{}, error)

ContextHandler is a handler called with the auth context, what means it is authenticated and ready to work

type CreateAppSessionRequest

type CreateAppSessionRequest resolveAppParams

type CreateAppSessionResponse

type CreateAppSessionResponse struct {
	// CookieValue is the application session cookie value.
	CookieValue string `json:"cookie_value"`
	// SubjectCookieValue is the application session subject cookie token.
	SubjectCookieValue string `json:"subject_cookie_value"`
	// FQDN is application FQDN.
	FQDN string `json:"fqdn"`
}

type CreateBotRequest

type CreateBotRequest struct {
	// BotName is the name of the bot
	BotName string `json:"botName"`
	// Roles are the roles that the bot will be able to impersonate
	Roles []string `json:"roles"`
	// Traits are the traits that will be associated with the bot for the purposes of role
	// templating.
	// Where multiple specified with the same name, these will be merged by the
	// server.
	Traits []*machineidv1.Trait `json:"traits"`
}

type CreateSessionReq

type CreateSessionReq struct {
	// User is the Teleport username.
	User string `json:"user"`
	// Pass is the password.
	Pass string `json:"pass"`
	// SecondFactorToken is the OTP.
	SecondFactorToken string `json:"second_factor_token"`
}

CreateSessionReq is a request to create session from username, password and second factor token.

type CreateSessionResponse added in v1.0.0

type CreateSessionResponse struct {
	// TokenType is token type (bearer)
	TokenType string `json:"type"`
	// Token value
	Token string `json:"token"`
	// TokenExpiresIn sets seconds before this token is not valid
	TokenExpiresIn int `json:"expires_in"`
	// SessionExpires is when this session expires.
	SessionExpires time.Time `json:"sessionExpires,omitempty"`
	// SessionInactiveTimeoutMS specifies how long in milliseconds
	// a user WebUI session can be left idle before being logged out
	// by the server. A zero value means there is no idle timeout set.
	SessionInactiveTimeoutMS int `json:"sessionInactiveTimeout"`
}

CreateSessionResponse returns OAuth compabible data about access token: https://tools.ietf.org/html/rfc6749

func (*CreateSessionResponse) String

func (r *CreateSessionResponse) String() string

String returns text description of this response

type Envelope

type Envelope struct {
	// Version is the version of the protocol.
	Version string `protobuf:"bytes,1,opt,name=Version,proto3" json:"Version,omitempty"`
	// Type is the type of message. For version 1 of the protocol this must
	// not be longer than 1 character.
	Type string `protobuf:"bytes,2,opt,name=Type,proto3" json:"Type,omitempty"`
	// Payload is the actual data to send.
	Payload              string   `protobuf:"bytes,3,opt,name=Payload,proto3" json:"Payload,omitempty"`
	XXX_NoUnkeyedLiteral struct{} `json:"-"`
	XXX_unrecognized     []byte   `json:"-"`
	XXX_sizecache        int32    `json:"-"`
}

Envelope is used to wrap and transend and receive messages between the web client and proxy.

func (*Envelope) Descriptor

func (*Envelope) Descriptor() ([]byte, []int)

func (*Envelope) GetPayload

func (m *Envelope) GetPayload() string

func (*Envelope) GetType

func (m *Envelope) GetType() string

func (*Envelope) GetVersion

func (m *Envelope) GetVersion() string

func (*Envelope) Marshal

func (m *Envelope) Marshal() (dAtA []byte, err error)

func (*Envelope) MarshalTo

func (m *Envelope) MarshalTo(dAtA []byte) (int, error)

func (*Envelope) MarshalToSizedBuffer

func (m *Envelope) MarshalToSizedBuffer(dAtA []byte) (int, error)

func (*Envelope) ProtoMessage

func (*Envelope) ProtoMessage()

func (*Envelope) Reset

func (m *Envelope) Reset()

func (*Envelope) Size

func (m *Envelope) Size() (n int)

func (*Envelope) String

func (m *Envelope) String() string

func (*Envelope) Unmarshal

func (m *Envelope) Unmarshal(dAtA []byte) error

func (*Envelope) XXX_DiscardUnknown

func (m *Envelope) XXX_DiscardUnknown()

func (*Envelope) XXX_Marshal

func (m *Envelope) XXX_Marshal(b []byte, deterministic bool) ([]byte, error)

func (*Envelope) XXX_Merge

func (m *Envelope) XXX_Merge(src proto.Message)

func (*Envelope) XXX_Size

func (m *Envelope) XXX_Size() int

func (*Envelope) XXX_Unmarshal

func (m *Envelope) XXX_Unmarshal(b []byte) error

type GetAppFQDNRequest

type GetAppFQDNRequest resolveAppParams

type GetAppFQDNResponse

type GetAppFQDNResponse struct {
	// FQDN is application FQDN.
	FQDN string `json:"fqdn"`
}

type Handler added in v1.0.0

type Handler struct {
	sync.Mutex
	httprouter.Router

	// ClusterFeatures contain flags for supported and unsupported features.
	ClusterFeatures proto.Features
	// contains filtered or unexported fields
}

Handler is HTTP web proxy handler

func (*Handler) AccessGraphAddr

func (h *Handler) AccessGraphAddr() utils.NetAddr

AccessGraphAddr returns the TAG API address

func (*Handler) AuthenticateRequest added in v1.0.0

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 (*Handler) Close added in v1.0.0

func (h *Handler) Close() error

Close closes associated session cache operations

func (*Handler) GetAccessPoint

func (h *Handler) GetAccessPoint() auth.ProxyAccessPoint

GetAccessPoint returns the caching access point.

func (*Handler) GetProxyClient

func (h *Handler) GetProxyClient() auth.ClientI

GetProxyClient returns authenticated auth server client

func (*Handler) ProxyHostPort

func (h *Handler) ProxyHostPort() string

ProxyHostPort returns the address of the proxy server using --proxy notation, i.e. "localhost:8030,8023"

func (*Handler) ProxyWithRoles

func (h *Handler) ProxyWithRoles(ctx *SessionContext) (reversetunnelclient.Tunnel, error)

ProxyWithRoles returns a reverse tunnel proxy verifying the permissions of the given user.

func (*Handler) PublicProxyAddr

func (h *Handler) PublicProxyAddr() string

PublicProxyAddr returns the publicly advertised proxy address

func (*Handler) String added in v1.0.0

func (h *Handler) String() string

func (*Handler) WithAuth

func (h *Handler) WithAuth(fn ContextHandler) httprouter.Handle

WithAuth ensures that a request is authenticated.

func (*Handler) WithAuthCookieAndCSRF

func (h *Handler) WithAuthCookieAndCSRF(fn ContextHandler) httprouter.Handle

WithAuthCookieAndCSRF ensures that a request is authenticated for plain old non-AJAX requests (does not check the Bearer header). It enforces CSRF checks (except for "safe" methods).

func (*Handler) WithClusterAuth

func (h *Handler) WithClusterAuth(fn ClusterHandler) httprouter.Handle

WithClusterAuth wraps a ClusterHandler to ensure that a request is authenticated to this proxy (the same as WithAuth), as well as to grab the remoteSite (which can represent this local cluster or a remote trusted cluster) as specified by the ":site" url parameter.

func (*Handler) WithClusterClientProvider

func (h *Handler) WithClusterClientProvider(fn ClusterClientHandler) httprouter.Handle

WithClusterClientProvider wraps a ClusterClientHandler to ensure that a request is authenticated to this proxy (the same as WithAuth), and passes a ClusterClientProvider so that the handler can access remote clusters. Use this instead of WithClusterAuth when the remote cluster cannot be encoded in the path or multiple clusters may need to be accessed from a single handler.

func (*Handler) WithHighLimiter

func (h *Handler) WithHighLimiter(fn httplib.HandlerFunc) httprouter.Handle

WithHighLimiter adds high rate IP-based rate limiting to fn. This should only be used on functions which are CPU constrained, and don't use disk or other services. Limits are applied to all requests, authenticated or not.

func (*Handler) WithHighLimiterHandlerFunc

func (h *Handler) WithHighLimiterHandlerFunc(fn httplib.HandlerFunc) httplib.HandlerFunc

WithHighLimiterHandlerFunc adds IP-based rate limiting to a HandlerFunc. This is similar to WithLimiterHandlerFunc but provides a higher rate limit. This should only be used for requests which are only CPU bound (no disk or other resources used).

func (*Handler) WithLimiter

func (h *Handler) WithLimiter(fn httplib.HandlerFunc) httprouter.Handle

WithLimiter adds IP-based rate limiting to fn. Limits are applied to all requests, authenticated or not.

func (*Handler) WithLimiterHandlerFunc

func (h *Handler) WithLimiterHandlerFunc(fn httplib.HandlerFunc) httplib.HandlerFunc

WithLimiterHandlerFunc adds IP-based rate limiting to a HandlerFunc. This should be used when you need to nest this inside another HandlerFunc.

func (*Handler) WithMetaRedirect

func (h *Handler) WithMetaRedirect(fn redirectHandlerFunc) httprouter.Handle

WithMetaRedirect is a handler that redirects to the path specified using HTML rather than HTTP. This is needed for redirects that can have a header size larger than 8kb, which some middlewares will drop. See https://github.com/gravitational/teleport/issues/7467.

func (*Handler) WithProvisionTokenAuth

func (h *Handler) WithProvisionTokenAuth(fn ProvisionTokenHandler) httprouter.Handle

WithProvisionTokenAuth ensures that request is authenticated with a provision token. Provision tokens, when used like this are invalidated as soon as used. Doesn't matter if the underlying response was a success or an error.

func (*Handler) WithRedirect

func (h *Handler) WithRedirect(fn redirectHandlerFunc) httprouter.Handle

WithRedirect is a handler that redirects to the path specified in the returned value.

func (*Handler) WithUnauthenticatedHighLimiter

func (h *Handler) WithUnauthenticatedHighLimiter(fn httplib.HandlerFunc) httprouter.Handle

WithUnauthenticatedHighLimiter adds a conditional IP-based rate limiting that will limit only unauthenticated requests. This is similar to WithUnauthenticatedLimiter, however this one allows a much higher rate limit. This higher rate limit should only be used on endpoints which are only CPU constrained (no file or other resources used).

func (*Handler) WithUnauthenticatedLimiter

func (h *Handler) WithUnauthenticatedLimiter(fn httplib.HandlerFunc) httprouter.Handle

WithUnauthenticatedLimiter adds a conditional IP-based rate limiting that will limit only unauthenticated requests. This is a good default to use as both Cluster and User auth are checked here, but `WithLimiter` can be used if you're certain that no authenticated requests will be made.

type HandlerOption added in v1.0.0

type HandlerOption func(h *Handler) error

HandlerOption is a functional argument - an option that can be passed to NewHandler function

func SetClock

func SetClock(clock clockwork.Clock) HandlerOption

SetClock sets the clock on a handler

func SetSessionStreamPollPeriod added in v1.0.0

func SetSessionStreamPollPeriod(period time.Duration) HandlerOption

SetSessionStreamPollPeriod sets polling period for session streams

type JWKSResponse

type JWKSResponse struct {
	// Keys is a list of public keys in JWK format.
	Keys []jwt.JWK `json:"keys"`
}

type OnboardUserPreferencesResponse

type OnboardUserPreferencesResponse struct {
	PreferredResources []userpreferencesv1.Resource `json:"preferredResources"`
	MarketingParams    preferencesMarketingParams   `json:"marketingParams"`
}

type PresenceChecker

type PresenceChecker = func(ctx context.Context, term io.Writer, maintainer client.PresenceMaintainer, sessionID string, mfaPrompt mfa.Prompt, opts ...client.PresenceOption) error

PresenceChecker is a function that executes an mfa prompt to enforce that a user is present.

type ProvisionTokenHandler

type ProvisionTokenHandler func(w http.ResponseWriter, r *http.Request, p httprouter.Params, site reversetunnelclient.RemoteSite, token types.ProvisionToken) (interface{}, error)

ProvisionTokenHandler is a authenticated handler that is called for some existing Token

type ResourceMap added in v1.2.6

type ResourceMap map[string]*zip.File

func (ResourceMap) Open added in v1.2.6

func (rm ResourceMap) Open(name string) (http.File, error)

type SSHSessionLatencyStats

type SSHSessionLatencyStats struct {
	// WebSocket measures the round trip time for a ping/pong via the websocket
	// established between the client and the Proxy.
	WebSocket int64 `json:"ws"`
	// SSH measures the round trip time for a keepalive@openssh.com request via the
	// connection established between the Proxy and the target host.
	SSH int64 `json:"ssh"`
}

SSHSessionLatencyStats contain latency measurements for both legs of an ssh connection established via the Web UI.

type SSOCallbackResponse

type SSOCallbackResponse struct {
	// CSRFToken is the token provided in the originating SSO login request
	// to be validated against.
	CSRFToken string
	// Username is the authenticated teleport username of the user that has
	// logged in, provided by the SSO provider.
	Username string
	// SessionName is the name of the session generated by auth server if
	// requested in the SSO request.
	SessionName string
	// ClientRedirectURL is the URL to redirect back to on completion of
	// the SSO login process.
	ClientRedirectURL string
}

SSOCallbackResponse holds the parameters for validating and executing an SSO callback URL. See SSOSetWebSessionAndRedirectURL().

type SSORequestParams

type SSORequestParams struct {
	// ClientRedirectURL is the URL specified in the query parameter
	// redirect_url, which will be unescaped here.
	ClientRedirectURL string
	// ConnectorID identifies the SSO connector to use to log in, from
	// the connector_id query parameter.
	ConnectorID string
	// CSRFToken is the token in the CSRF cookie header.
	CSRFToken string
}

SSORequestParams holds parameters parsed out of a HTTP request initiating an SSO login. See ParseSSORequestParams().

func ParseSSORequestParams

func ParseSSORequestParams(r *http.Request) (*SSORequestParams, error)

ParseSSORequestParams extracts the SSO request parameters from an http.Request, returning them in an SSORequestParams struct. If any fields are not present, an error is returned.

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server serves the web api.

func NewServer

func NewServer(cfg ServerConfig) (*Server, error)

NewServer constructs a Server from the provided ServerConfig.

func (*Server) Close

func (s *Server) Close() error

Close immediately closes the http.Server.

func (*Server) HandleConnection

func (s *Server) HandleConnection(ctx context.Context, conn net.Conn) error

HandleConnection handles connections from plain TCP applications.

func (*Server) Serve

func (s *Server) Serve(l net.Listener) error

Serve launches the configured http.Server.

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown initiates graceful shutdown. The underlying http.Server is not shutdown until all active connections are terminated or the context times out. This is required because the http.Server does not attempt to close nor wait for hijacked connections such as WebSockets during Shutdown; which means that any open sessions in the web UI will not prevent the http.Server from shutting down.

type ServerConfig

type ServerConfig struct {
	// Server serves the web api
	Server *http.Server
	// Handler web handler
	Handler *APIHandler
	// Log to write log messages
	Log logrus.FieldLogger
	// ShutdownPollPeriod sets polling period for shutdown
	ShutdownPollPeriod time.Duration
}

ServerConfig provides dependencies required to create a Server.

func (*ServerConfig) CheckAndSetDefaults

func (c *ServerConfig) CheckAndSetDefaults() error

CheckAndSetDefaults validates fields and populates empty fields with default values.

type SessionContext added in v1.0.0

type SessionContext struct {
	// contains filtered or unexported fields
}

SessionContext is a context associated with a user's web session. An instance of the context is created for each web session generated for the user and provides a basic client cache for remote auth server connections.

func NewSessionContext

func NewSessionContext(cfg SessionContextConfig) (*SessionContext, error)

func (*SessionContext) AddClosers added in v1.0.0

func (c *SessionContext) AddClosers(closers ...io.Closer)

AddClosers adds the specified closers to this context

func (*SessionContext) ClientTLSConfig

func (c *SessionContext) ClientTLSConfig(ctx context.Context, clusterName ...string) (*tls.Config, error)

ClientTLSConfig returns client TLS authentication associated with the web session context

func (*SessionContext) Close added in v1.0.0

func (c *SessionContext) Close() error

Close cleans up resources associated with this context and removes it from the user context

func (*SessionContext) GetAgent added in v1.0.0

GetAgent returns agent that can be used to answer challenges for the web to ssh connection as well as certificate

func (*SessionContext) GetClient added in v1.0.0

func (c *SessionContext) GetClient() (auth.ClientI, error)

GetClient returns the client connected to the auth server

func (*SessionContext) GetClientConnection

func (c *SessionContext) GetClientConnection() *grpc.ClientConn

GetClientConnection returns a connection to Auth Service

func (*SessionContext) GetIdentity

func (c *SessionContext) GetIdentity() (*tlsca.Identity, error)

GetIdentity returns identity parsed from the session's TLS certificate.

func (*SessionContext) GetProxyListenerMode

func (c *SessionContext) GetProxyListenerMode(ctx context.Context) (types.ProxyListenerMode, error)

GetProxyListenerMode returns cluster proxy listener mode form cluster networking config.

func (*SessionContext) GetSSHCertificate

func (c *SessionContext) GetSSHCertificate() (*ssh.Certificate, error)

GetSSHCertificate returns the *ssh.Certificate associated with this session.

func (*SessionContext) GetSessionID

func (c *SessionContext) GetSessionID() string

GetSessionID returns the ID of the underlying user web session.

func (*SessionContext) GetUser added in v1.0.0

func (c *SessionContext) GetUser() string

GetUser returns the authenticated teleport user

func (*SessionContext) GetUserAccessChecker

func (c *SessionContext) GetUserAccessChecker() (services.AccessChecker, error)

GetUserAccessChecker returns AccessChecker derived from the SSH certificate associated with this session.

func (*SessionContext) GetUserClient

GetUserClient will return an auth.ClientI with the role of the user at the requested site. If the site is local a client with the users local role is returned. If the site is remote a client with the users remote role is returned.

func (*SessionContext) GetX509Certificate

func (c *SessionContext) GetX509Certificate() (*x509.Certificate, error)

GetX509Certificate returns the *x509.Certificate associated with this session.

func (*SessionContext) Invalidate added in v1.0.0

func (c *SessionContext) Invalidate(ctx context.Context) error

Invalidate invalidates this context by removing the underlying session and closing all underlying closers

func (*SessionContext) NewKubernetesServiceClient

func (c *SessionContext) NewKubernetesServiceClient(ctx context.Context, addr string) (kubeproto.KubeServiceClient, error)

NewKubernetesServiceClient returns a new KubernetesServiceClient.

func (*SessionContext) RemoveCloser

func (c *SessionContext) RemoveCloser(closer io.Closer)

RemoveCloser removes the specified closer from this context

func (*SessionContext) String

func (c *SessionContext) String() string

String returns the text representation of this context

type SessionContextConfig

type SessionContextConfig struct {
	// Log is used to emit logs
	Log *logrus.Entry
	// User is the name of the current user
	User string

	// RootClusterName is the name of the root cluster
	RootClusterName string

	// RootClient holds a connection to the root auth. Note that requests made using this
	// client are made with the identity of the user and are NOT cached.
	RootClient *auth.Client

	// UnsafeCachedAuthClient holds a read-only cache to root auth. Note this access
	// point cache is authenticated with the identity of the node, not of the
	// user. This is why its prefixed with "unsafe".
	//
	// This access point should only be used if the identity of the caller will
	// not affect the result of the RPC. For example, never use it to call
	// "GetNodes".
	UnsafeCachedAuthClient auth.ReadProxyAccessPoint

	Parent *sessionCache
	// Resources is a persistent resource store this context is bound to.
	// The store maintains a list of resources between session renewals
	Resources *sessionResources
	// Session refers the web session created for the user.
	Session types.WebSession
	// contains filtered or unexported fields
}

func (*SessionContextConfig) CheckAndSetDefaults

func (c *SessionContextConfig) CheckAndSetDefaults() error

type SessionController

type SessionController interface {
	// AcquireSessionContext attempts to create a context for the session. If the session is
	// not allowed due to session control an error is returned. The returned
	// context is scoped to the session and will be canceled in the event that session
	// controls terminate the session early.
	AcquireSessionContext(ctx context.Context, sctx *SessionContext, login, localAddr, remoteAddr string) (context.Context, error)
}

SessionController restricts creation of sessions based on cluster session control configuration(locks, connection limits, etc).

type SessionControllerFunc

type SessionControllerFunc func(ctx context.Context, sctx *SessionContext, login, localAddr, remoteAddr string) (context.Context, error)

SessionControllerFunc type is an adapter to allow the use of ordinary functions a SessionController. If f is a function with the appropriate signature, SessionControllerFunc(f) is a SessionController that calls f.

func (SessionControllerFunc) AcquireSessionContext

func (f SessionControllerFunc) AcquireSessionContext(ctx context.Context, sctx *SessionContext, login, localAddr, remoteAddr string) (context.Context, error)

AcquireSessionContext calls f(ctx, sctx, localAddr, remoteAddr).

type TerminalHandler

type TerminalHandler struct {
	// contains filtered or unexported fields
}

TerminalHandler connects together an SSH session with a web-based terminal via a web socket.

func NewTerminal

func NewTerminal(ctx context.Context, cfg TerminalHandlerConfig) (*TerminalHandler, error)

NewTerminal creates a web-based terminal based on WebSockets and returns a new TerminalHandler.

func (*TerminalHandler) Close

func (t *TerminalHandler) Close() error

Close the websocket stream.

func (*TerminalHandler) ServeHTTP

func (t *TerminalHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP builds a connection to the remote node and then pumps back two types of events: raw input/output events for what's happening on the terminal itself and audit log events relevant to this session.

type TerminalHandlerConfig

type TerminalHandlerConfig struct {
	// Term is the initial PTY size.
	Term session.TerminalParams
	// SessionCtx is the context for the users web session.
	SessionCtx *SessionContext
	// UserAuthClient is used to fetch nodes and sessions from the backend.
	UserAuthClient UserAuthClient
	// LocalAccessPoint is the subset of the Proxy cache required to
	// look up information from the local cluster. This should not
	// be used for anything that requires RBAC on behalf of the user.
	// Requests that should be made on behalf of the user should
	// use [UserAuthClient].
	LocalAccessPoint localAccessPoint
	// DisplayLogin is the login name to display in the UI.
	DisplayLogin string
	// SessionData is the data to send to the client on the initial session creation.
	SessionData session.Session
	// KeepAliveInterval is the interval for sending ping frames to web client.
	// This value is pulled from the cluster network config and
	// guaranteed to be set to a nonzero value as it's enforced by the configuration.
	KeepAliveInterval time.Duration
	// ProxyHostPort is the address of the server to connect to.
	ProxyHostPort string
	// ProxyPublicAddr is the public web proxy address.
	ProxyPublicAddr string
	// InteractiveCommand is a command to execute.
	InteractiveCommand []string
	// Router determines how connections to nodes are created
	Router *proxy.Router
	// TracerProvider is used to create the tracer
	TracerProvider oteltrace.TracerProvider
	// PROXYSigner is used to sign PROXY header and securely propagate client IP information
	PROXYSigner multiplexer.PROXYHeaderSigner

	// ParticipantMode is the mode that determines what you can do when you join an active session.
	ParticipantMode types.SessionParticipantMode
	// Tracker is the session tracker of the session being joined. May be nil
	// if the user is not joining a session.
	Tracker types.SessionTracker
	// PresenceChecker used for presence checking.
	PresenceChecker PresenceChecker
	// Clock allows interaction with time.
	Clock clockwork.Clock
	// contains filtered or unexported fields
}

TerminalHandlerConfig contains the configuration options necessary to correctly set up the TerminalHandler

func (*TerminalHandlerConfig) CheckAndSetDefaults

func (t *TerminalHandlerConfig) CheckAndSetDefaults() error

type TerminalRequest

type TerminalRequest struct {
	// Server describes a server to connect to (serverId|hostname[:port]).
	Server string `json:"server_id"`

	// Login is Linux username to connect as.
	Login string `json:"login"`

	// Term is the initial PTY size.
	Term session.TerminalParams `json:"term"`

	// SessionID is a Teleport session ID to join as.
	SessionID session.ID `json:"sid"`

	// ProxyHostPort is the address of the server to connect to.
	ProxyHostPort string `json:"-"`

	// InteractiveCommand is a command to execute
	InteractiveCommand []string `json:"-"`

	// KeepAliveInterval is the interval for sending ping frames to web client.
	// This value is pulled from the cluster network config and
	// guaranteed to be set to a nonzero value as it's enforced by the configuration.
	KeepAliveInterval time.Duration

	// ParticipantMode is the mode that determines what you can do when you join an active session.
	ParticipantMode types.SessionParticipantMode `json:"mode"`
}

TerminalRequest describes a request to create a web-based terminal to a remote SSH server.

type TerminalStream

type TerminalStream struct {
	*WSStream
	// contains filtered or unexported fields
}

TerminalStream manages the [websocket.Conn] to the web UI for a terminal session.

func NewTerminalStream

func NewTerminalStream(ctx context.Context, cfg TerminalStreamConfig) *TerminalStream

NewTerminalStream creates a stream that manages reading and writing data over the provided [websocket.Conn]

type TerminalStreamConfig

type TerminalStreamConfig struct {
	// The websocket to operate over. Required.
	WS WSConn
	// A logger to emit log messages. Optional.
	Logger logrus.FieldLogger
	// A custom set of handlers to process messages received
	// over the websocket. Optional.
	Handlers map[string]WSHandlerFunc
}

TerminalStreamConfig contains dependencies of a TerminalStream.

type UnifiedResourcePreferencesResponse

type UnifiedResourcePreferencesResponse struct {
	DefaultTab     userpreferencesv1.DefaultTab     `json:"defaultTab"`
	ViewMode       userpreferencesv1.ViewMode       `json:"viewMode"`
	LabelsViewMode userpreferencesv1.LabelsViewMode `json:"labelsViewMode"`
}

type UserAuthClient

type UserAuthClient interface {
	GetSessionEvents(namespace string, sid session.ID, after int) ([]events.EventFields, error)
	GetSessionTracker(ctx context.Context, sessionID string) (types.SessionTracker, error)
	IsMFARequired(ctx context.Context, req *authproto.IsMFARequiredRequest) (*authproto.IsMFARequiredResponse, error)
	CreateAuthenticateChallenge(ctx context.Context, req *authproto.CreateAuthenticateChallengeRequest) (*authproto.MFAAuthenticateChallenge, error)
	GenerateUserCerts(ctx context.Context, req authproto.UserCertsRequest) (*authproto.Certs, error)
	MaintainSessionPresence(ctx context.Context) (authproto.AuthService_MaintainSessionPresenceClient, error)
}

UserAuthClient is a subset of the Auth API that performs operations on behalf of the user so that the correct RBAC is applied.

type UserPreferencesResponse

type UserPreferencesResponse struct {
	Assist                     AssistUserPreferencesResponse      `json:"assist"`
	Theme                      userpreferencesv1.Theme            `json:"theme"`
	UnifiedResourcePreferences UnifiedResourcePreferencesResponse `json:"unifiedResourcePreferences"`
	Onboard                    OnboardUserPreferencesResponse     `json:"onboard"`
	ClusterPreferences         ClusterUserPreferencesResponse     `json:"clusterPreferences,omitempty"`
}

UserPreferencesResponse is the JSON response for the user preferences.

type WSConn

type WSConn interface {
	Close() error

	LocalAddr() net.Addr
	RemoteAddr() net.Addr

	WriteControl(messageType int, data []byte, deadline time.Time) error
	WriteMessage(messageType int, data []byte) error
	ReadMessage() (messageType int, p []byte, err error)
	SetReadLimit(limit int64)
	SetReadDeadline(t time.Time) error

	PongHandler() func(appData string) error
	SetPongHandler(h func(appData string) error)
	CloseHandler() func(code int, text string) error
	SetCloseHandler(h func(code int, text string) error)
}

WSConn is a gorilla/websocket minimal interface used by our web implementation. This interface exists to override the default websocket.Conn implementation, currently used by noopCloserWS to prevent WS being closed by wrapping stream.

type WSHandlerFunc

type WSHandlerFunc func(context.Context, Envelope)

WSHandlerFunc specifies a handler that processes received a specific Envelope received via a web socket.

type WSStream

type WSStream struct {
	// contains filtered or unexported fields
}

WSStream handles web socket communication with the frontend.

func NewWStream

func NewWStream(ctx context.Context, ws WSConn, log logrus.FieldLogger, handlers map[string]WSHandlerFunc) *WSStream

func (*WSStream) Close

func (t *WSStream) Close() error

Close sends a close message on the web socket and closes the web socket.

func (*WSStream) Read

func (t *WSStream) Read(out []byte) (int, error)

Read provides data received from [defaults.WebsocketRaw] envelopes. If the previous envelope was not consumed in the last read, any remaining data is returned prior to processing the next envelope.

func (*WSStream) SendCloseMessage

func (t *WSStream) SendCloseMessage(event sessionEndEvent) error

SendCloseMessage sends a close message on the web socket.

func (*WSStream) Write

func (t *WSStream) Write(data []byte) (n int, err error)

Write wraps the data bytes in a raw envelope and sends.

type WebsocketIO

type WebsocketIO struct {
	Conn *websocket.Conn
	// contains filtered or unexported fields
}

func (*WebsocketIO) Close

func (ws *WebsocketIO) Close() error

func (*WebsocketIO) Read

func (ws *WebsocketIO) Read(p []byte) (int, error)

func (*WebsocketIO) Write

func (ws *WebsocketIO) Write(p []byte) (int, error)

Directories

Path Synopsis
Package app connections to applications over a reverse tunnel and forwards HTTP requests to them.
Package app connections to applications over a reverse tunnel and forwards HTTP requests to them.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL