Documentation
¶
Index ¶
- Constants
- Variables
- func CompactCacheObject(in any) (any, error)
- func GroupNamespace(groupID string) string
- func LogReportFailure(log logr.Logger) func(error)
- func ParseAccessKey(data []byte) (ed25519.PublicKey, bool)
- func PolicyAllows(rules []laboratoryv1alpha1.LabGroupAccessRule, client, lab string) bool
- func ReportName(instance string) string
- func RunLifecycle(ctx context.Context, server *http.Server, handler *Handler, ...) error
- func UseGroupReader(r client.Reader)
- type AccessGroup
- type AccessReader
- func (a *AccessReader) Allowed(ctx context.Context, namespace, member, labName string) bool
- func (a *AccessReader) Device(ctx context.Context, namespace, device, code string) (DeviceInfo, error)
- func (a *AccessReader) Group(ctx context.Context, id string) (AccessGroup, error)
- func (a *AccessReader) Route(ctx context.Context, task, namespace string) (AccessRoute, error)
- func (a *AccessReader) Tenant(id string) (string, bool)
- type AccessRoute
- type Attribution
- type Authorizer
- type BackendResolver
- type DeviceInfo
- type DeviceLookup
- type EmbedMatcher
- type GroupTenant
- type Handler
- func (h *Handler) CheckLive() int
- func (h *Handler) RunLiveCheck(ctx context.Context, interval time.Duration)
- func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (h *Handler) Shutdown(ctx context.Context) error
- func (h *Handler) Throttle() *bandwidth.Throttle[string]
- func (h *Handler) WithAccessLog(log logr.Logger, slow time.Duration) *Handler
- func (h *Handler) WithAccessReader(a *AccessReader) *Handler
- func (h *Handler) WithAccounting(meter *Meter, attribute Attribution) *Handler
- func (h *Handler) WithActivity(hub *activity.Hub) *Handler
- func (h *Handler) WithAuthRateLimit(rate float64, burst int) *Handler
- func (h *Handler) WithAuthorizer(authorize Authorizer) *Handler
- func (h *Handler) WithGrantMaxTTL(d time.Duration) *Handler
- func (h *Handler) WithGroupTenant(g GroupTenant) *Handler
- func (h *Handler) WithLiveCaps(c LiveCaps) *Handler
- func (h *Handler) WithLiveMaxLifetime(d time.Duration) *Handler
- func (h *Handler) WithPlatformOrigins(m *EmbedMatcher) *Handler
- func (h *Handler) WithReportPreparation(prepare func(context.Context, string) error) *Handler
- func (h *Handler) WithTerminal(c TerminalConfig) *Handler
- type KeyLookup
- type LiveCaps
- type Meter
- func (m *Meter) Begin(namespace, client, lab string, start time.Time) *RequestMeter
- func (m *Meter) Ledger(namespace string) ([]Touch, bool)
- func (m *Meter) MarkPartial()
- func (m *Meter) Record(namespace, client, lab string, start time.Time, responded bool, ...)
- func (m *Meter) Restore(namespace string, rows []Touch, truncated, partial bool) error
- func (m *Meter) RetireNamespaces(active map[string]bool)
- func (m *Meter) Snapshot(namespace string) (rows []Touch, truncated, partial bool)
- type ReportWriter
- func (w *ReportWriter) Prepare(ctx context.Context, namespace string) error
- func (w *ReportWriter) PrepareAll(ctx context.Context) error
- func (w *ReportWriter) Publish(ctx context.Context, namespace string, now time.Time) error
- func (w *ReportWriter) PublishAll(ctx context.Context, now time.Time, onError func(error))
- func (w *ReportWriter) Run(ctx context.Context, every time.Duration, onError func(error))
- type RequestMeter
- type ServiceDirectory
- type TerminalConfig
- type Touch
Constants ¶
const ( // MaxMeterKeys bounds distinct (namespace, user, lab) rows per replica. MaxMeterKeys = 50_000 MaxReportRows = 512 )
const AuthPath = "/_auth"
AuthPath is the path a platform page posts an access grant to: POST https://<device>-<code><kind>.<base>/_auth. The proxy consumes it and never forwards it to a lab.
The request is a form post (application/x-www-form-urlencoded, at most authBodyMax bytes) of the fields
grant the access grant, a JWS of at most grant.MaxLen bytes (see internal/grant) next optional: a root-relative path (with a query) to land on; anything else becomes "/"
The form comes from the platform page, so it is cross-site: the proxy requires the Origin header and matches it against the list of platform origins, which stops an attacker's page from posting its own grant into a victim's browser (login CSRF). On a web host the answer is a 303 to `next` with the grant as a host-only cookie; on a console host it is the console page, with no cookie. A GET (the old link with a token in its URL) consumes nothing and gets the "session over" card, so a link of the old shape fails closed.
const ConsoleSubprotocol = "cib.console.v1"
ConsoleSubprotocol is the first subprotocol of the console WebSocket; the second is the console session token.
const DefaultLiveMaxLifetime = 12 * time.Hour
DefaultLiveMaxLifetime caps how long one request or upgraded (WebSocket) connection may stay open.
const DefaultSlowRequest = 2 * time.Second
DefaultSlowRequest is the upstream latency above which a request is flagged slow in the access log.
const ServiceNameLabel = "kubernetes.io/service-name"
ServiceNameLabel is the label that ties an EndpointSlice to its Service.
Variables ¶
var ErrNoConsole = errors.New("the device has no console")
ErrNoConsole is returned by a DeviceLookup for a device that has no console (or does not exist; the answer is the same).
var ErrRouteNotReady = errors.New("device is not ready")
ErrRouteNotReady says the device exists but has no usable address yet (its pod is starting, was replaced, or the operator has not published the new address): the caller shows the starting page and the client retries. It is never answered by a connection to a guess.
Functions ¶
func CompactCacheObject ¶ added in v1.1.0
CompactCacheObject preserves only what proxy authorization/routing uses. It owns its copy; objects supplied by informer transforms remain untouched.
func GroupNamespace ¶
GroupNamespace is the namespace of a LabGroup the platform calls groupID: the group's custom resource is named after the id (encoded when the id is not a valid name). The namespace is the one in the group's status (a group created before the namespace prefix keeps its old one), else the name a new group gets.
func LogReportFailure ¶
LogReportFailure is the onError of Run: a refusal (Forbidden) or NotFound is how a group namespace looks that the operator has not bound the proxy's role in yet, or that is being deleted. Both pass by themselves, so they are only traced (debug), never an error in the journal.
func ParseAccessKey ¶
ParseAccessKey reads a PKIX PEM Ed25519 public key.
func PolicyAllows ¶
func PolicyAllows(rules []laboratoryv1alpha1.LabGroupAccessRule, client, lab string) bool
PolicyAllows evaluates the group access policy for one client and lab the way the VPN does: a matching deny wins; without a matching allow the pair is denied by default.
func ReportName ¶
ReportName is the LabTrafficReport of one proxy replica.
func RunLifecycle ¶ added in v1.1.0
func RunLifecycle(ctx context.Context, server *http.Server, handler *Handler, reports *ReportWriter, reportEvery, checkEvery time.Duration, serve func() error, onError func(error)) error
RunLifecycle owns report and access workers as well as server shutdown. No final cumulative report is published while request defers can still add data.
func UseGroupReader ¶
UseGroupReader makes GroupNamespace read the LabGroup (from the proxy's cache) to find its namespace.
Types ¶
type AccessGroup ¶ added in v1.1.0
type AccessGroup struct{ Namespace, Tenant string }
type AccessReader ¶ added in v1.1.0
AccessReader uses the proxy's compact informer cache, without a permission TTL. A request reads its group once and its route Service once.
func (*AccessReader) Allowed ¶ added in v1.1.0
func (a *AccessReader) Allowed(ctx context.Context, namespace, member, labName string) bool
func (*AccessReader) Device ¶ added in v1.10.0
func (a *AccessReader) Device(ctx context.Context, namespace, device, code string) (DeviceInfo, error)
Device finds the device of a lab that has a console. A device without one, a missing device and a deleting one are the same answer. Node is empty while the device has no pod placed yet.
func (*AccessReader) Group ¶ added in v1.1.0
func (a *AccessReader) Group(ctx context.Context, id string) (AccessGroup, error)
func (*AccessReader) Route ¶ added in v1.1.0
func (a *AccessReader) Route(ctx context.Context, task, namespace string) (AccessRoute, error)
type AccessRoute ¶ added in v1.1.0
type AccessRoute struct{ URL, Lab, Device string }
AccessRoute is where a web host goes: the upstream, and the lab and device (the Service labels) the host stands for.
type Attribution ¶
Attribution maps (task, groupID) to the lab a request reaches. It fails when the group does not own that lab.
func ServiceAttribution ¶
func ServiceAttribution(reader client.Reader) Attribution
ServiceAttribution attributes a request to a lab through the web Service the operator creates per exposed device. The host label is the Service name; the Service is read (from the cache) in the namespace of the token's own group, so a token only reaches labs its group owns, and its lab label names the lab. Nothing is decoded from the host itself.
type Authorizer ¶
Authorizer decides whether a LabGroupClient of a group may reach a lab. It is
type BackendResolver ¶
BackendResolver maps (task, groupID) to a backend URL string.
type DeviceInfo ¶ added in v1.10.0
DeviceInfo is what the proxy needs to open a console: the lab and device the host names, the node the device runs on and the terminal settings the lab author gave.
type DeviceLookup ¶ added in v1.10.0
type DeviceLookup func(ctx context.Context, namespace, device, code string) (DeviceInfo, error)
DeviceLookup finds the device with a console that a host names, in a group namespace: the device name and base code that names.ParseAccessHost read from the first label of the host.
type EmbedMatcher ¶ added in v1.10.0
type EmbedMatcher struct {
// contains filtered or unexported fields
}
EmbedMatcher is the parsed allow and deny lists. It is built once at start and read-only after that.
func NewEmbedMatcher ¶ added in v1.10.0
func NewEmbedMatcher(allow, deny []string) (*EmbedMatcher, error)
NewEmbedMatcher parses the lists; a malformed entry is an error.
func (*EmbedMatcher) Ancestor ¶ added in v1.10.0
func (m *EmbedMatcher) Ancestor(referer string) string
Ancestor is what `frame-ancestors` gets for a request with this Referer: the Referer's origin when the lists allow it, else 'none'.
type GroupTenant ¶
GroupTenant says which tenant a LabGroup (by the id the platform gave it) belongs to.
func LabGroupTenant ¶
func LabGroupTenant(r client.Reader) GroupTenant
LabGroupTenant tells the tenant of a LabGroup from its tenant label: the group's custom resource is named after the platform's id (encoded when needed). A group created before tenancy has no label and belongs to the default tenant.
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
func NewHandler ¶
func NewHandler(keys KeyLookup, baseDomain, cookieName string, resolver BackendResolver) *Handler
func (*Handler) CheckLive ¶
CheckLive closes every request in flight that must not go on: its deadline passed, the group no longer belongs to the tenant that issued the session, or the group policy no longer lets the client reach the lab. It uses the same checks as a new request, so a lock takes effect on open sessions as soon as the proxy's own copy of the policy does. It returns how many it closed.
func (*Handler) RunLiveCheck ¶
RunLiveCheck calls CheckLive every interval until ctx ends.
func (*Handler) Shutdown ¶ added in v1.1.0
Shutdown stops admissions, cancels HTTP and upgraded connections, and waits for handler defers to settle their meters before the caller publishes.
func (*Handler) Throttle ¶ added in v1.8.0
Throttle is the throttle of the proxy: SetLimits turns the pacing on with the class of the proxy and the ceiling of one participant.
func (*Handler) WithAccessLog ¶ added in v1.7.0
WithAccessLog turns on the access log; slow <= 0 means DefaultSlowRequest.
func (*Handler) WithAccessReader ¶ added in v1.1.0
func (h *Handler) WithAccessReader(a *AccessReader) *Handler
func (*Handler) WithAccounting ¶
func (h *Handler) WithAccounting(meter *Meter, attribute Attribution) *Handler
WithAccounting counts requests of a client per lab device. attribute maps the task host to the lab and device; without it nothing is counted.
func (*Handler) WithActivity ¶ added in v1.10.0
WithActivity keeps the facts of the console sessions in the ring of the hub (nil: activity reports are off).
func (*Handler) WithAuthRateLimit ¶
WithAuthRateLimit limits the handoff path (/_auth). Before anything is verified, an attempt must pass two buckets of its client: the fine one of its address (IPv4 /32, IPv6 /64) and the coarse one of its network (IPv4 /24, IPv6 /48; ten times the rate and burst), whatever the attempt carries (no lab, no cookie in these keys). There is no bucket shared by all clients: what bounds the work garbage can cause is a cap on the verifications in flight (503 when it is full). After a link verifies, the lab, the address and the verified session (group and client of the link) share a bucket of rate per second and burst. Over a bucket the answer is 429. The tables are capped, never evict a drained bucket, and send the keys that do not fit to one shared overflow bucket.
func (*Handler) WithAuthorizer ¶
func (h *Handler) WithAuthorizer(authorize Authorizer) *Handler
WithAuthorizer restricts clients to the labs the group policy allows.
func (*Handler) WithGrantMaxTTL ¶ added in v1.10.0
WithGrantMaxTTL sets the longest accepted grant lifetime (exp - iat).
func (*Handler) WithGroupTenant ¶
func (h *Handler) WithGroupTenant(g GroupTenant) *Handler
WithGroupTenant tells the owner of a group. A grant whose issuer is not the tenant of its group is refused, and so is a session whose tenant no longer owns the group. Without it no grant is accepted.
func (*Handler) WithLiveCaps ¶
WithLiveCaps sets how many requests may be in flight in all, per group and per client of a group.
func (*Handler) WithLiveMaxLifetime ¶
WithLiveMaxLifetime sets the longest a request or upgraded connection may last (zero: the default).
func (*Handler) WithPlatformOrigins ¶ added in v1.10.0
func (h *Handler) WithPlatformOrigins(m *EmbedMatcher) *Handler
WithPlatformOrigins sets the pages that may post a grant: a post whose Origin is not matched is refused. Without it (or with an empty list) every post is refused.
func (*Handler) WithReportPreparation ¶ added in v1.1.0
func (*Handler) WithTerminal ¶ added in v1.10.0
func (h *Handler) WithTerminal(c TerminalConfig) *Handler
WithTerminal switches the console on. It needs the access reader: without it the proxy has no groups to authorize a console by.
type KeyLookup ¶
KeyLookup finds the access public key a tenant registered under a key id.
func SecretKeys ¶
SecretKeys looks the access public key of a tenant up in the Secret tenant-<name>-access-keys of the tenants namespace (one entry per key id, the PEM public key). The reader is a cache that watches that namespace, so a key added by the agent works at once and a removed one stops.
type LiveCaps ¶
type LiveCaps struct {
PerClient, PerGroup, Total int
}
LiveCaps bound the requests in flight: an upgraded (WebSocket) connection or a long download holds a goroutine and buffers for up to LiveMaxLifetime, and one authenticated session could otherwise hold thousands of them. Zero = unlimited.
type Meter ¶
Meter holds only cumulative counters and times. Each namespace has its own index, so publishing one group never scans the traffic of other groups.
func (*Meter) Begin ¶ added in v1.1.0
func (m *Meter) Begin(namespace, client, lab string, start time.Time) *RequestMeter
func (*Meter) MarkPartial ¶ added in v1.1.0
func (m *Meter) MarkPartial()
MarkPartial records an interrupted observation/final drain for every known group.
func (*Meter) Record ¶
func (m *Meter) Record(namespace, client, lab string, start time.Time, responded bool, bytesIn, bytesOut int64)
Record preserves the finished-request API while HTTP wrappers migrate to Begin.
func (*Meter) Restore ¶ added in v1.1.0
Restore folds a successfully loaded durable baseline once. Traffic counted before the API became available remains additive, never replaced by old rows.
func (*Meter) RetireNamespaces ¶ added in v1.1.0
RetireNamespaces reclaims disappeared groups only after their live requests finish; these rows cannot be needed by the final publication of active groups.
type ReportWriter ¶
type ReportWriter struct {
Reader client.Reader
Writer client.Client
Meter *Meter
Instance string
Namespaces func(ctx context.Context) []string
// contains filtered or unexported fields
}
ReportWriter publishes what the Meter counted, one LabTrafficReport per proxy replica in every group namespace, every interval. The covered span advances on each write even when the group saw no request, which is how an idle team proves it was being watched. The agent relays the reports to the platform.
func (*ReportWriter) Prepare ¶ added in v1.1.0
func (w *ReportWriter) Prepare(ctx context.Context, namespace string) error
Prepare restores the previous report before a namespace can admit traffic. Successful preparation is a cheap map lookup; failures remain retryable and cannot publish smaller counters over the durable baseline.
func (*ReportWriter) PrepareAll ¶ added in v1.1.0
func (w *ReportWriter) PrepareAll(ctx context.Context) error
func (*ReportWriter) PublishAll ¶
PublishAll writes the report of every group namespace; a failure of one namespace (for example one that is being deleted) does not stop the others.
type RequestMeter ¶ added in v1.1.0
type RequestMeter struct {
// contains filtered or unexported fields
}
RequestMeter makes a permitted request observable while it is still active. All updates and End share the Meter lock; duplicate completion is harmless.
func (*RequestMeter) AddIn ¶ added in v1.1.0
func (r *RequestMeter) AddIn(n int64)
func (*RequestMeter) AddOut ¶ added in v1.1.0
func (r *RequestMeter) AddOut(n int64)
func (*RequestMeter) End ¶ added in v1.1.0
func (r *RequestMeter) End()
func (*RequestMeter) Incomplete ¶ added in v1.1.0
func (r *RequestMeter) Incomplete()
func (*RequestMeter) Responded ¶ added in v1.1.0
func (r *RequestMeter) Responded(now time.Time)
type ServiceDirectory ¶ added in v1.10.0
ServiceDirectory maps a node to the base URL of the device access service pod on it, e.g. "http://10.0.3.7:8080".
func EndpointDirectory ¶ added in v1.10.0
func EndpointDirectory(r client.Reader, namespace, service string, port int) ServiceDirectory
EndpointDirectory finds the device access service on a node from the EndpointSlices of its headless Service: the ready endpoint whose nodeName is that node. The proxy reads EndpointSlices of the one namespace of the service (an address and a node name, nothing else of a pod), and no pod.
type TerminalConfig ¶ added in v1.10.0
type TerminalConfig struct {
Devices DeviceLookup
Services ServiceDirectory
Log logr.Logger
// PerClient bounds the consoles one client of a group has open through this proxy. 0 is no limit.
PerClient int
// Idle closes a console that no byte crossed for that long; Lifetime closes any console at that age. 0 is no limit.
Idle, Lifetime time.Duration
// OriginScheme is the scheme of the page's origin ("https" unless a test serves it plainly).
OriginScheme string
// Embed decides which sites may show the console page in a frame (see terminal_embed.go); nil means none.
Embed *EmbedMatcher
// Dial opens the stream to a service; nil dials the base URL of the directory over a WebSocket.
Dial func(ctx context.Context, base string) (*websocket.Conn, error)
}
TerminalConfig switches the console on in a Handler.
func DefaultTerminalConfig ¶ added in v1.10.0
func DefaultTerminalConfig() TerminalConfig
DefaultTerminalConfig carries the chart defaults for the limits.