control

package
v0.10.1 Latest Latest
Warning

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

Go to latest
Published: Oct 5, 2026 License: Apache-2.0 Imports: 72 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package control is the admin-plane HTTP API: /auth/*, CRUD across the catalog and tenancy kinds, /version, /master-key/*, /reload.

Mount(r, deps) wires huma+chi onto an existing chi router and returns the huma.API. main.go constructs Deps and calls Mount.

Index

Constants

This section is empty.

Variables

View Source
var ErrNoSigningKey = errors.New("control: no token signing key")

ErrNoSigningKey means the deployment has no token signing key — tokens cannot be minted until one is configured.

Functions

func AdminTokenMiddleware

func AdminTokenMiddleware(adminToken string) func(http.Handler) http.Handler

AdminTokenMiddleware accepts the request iff it carries a valid bearer admin token in the Authorization header. On success it injects an Actor with AdminToken=true into context so downstream handlers + authz see a valid caller. On absent/mismatched token it does nothing — the next middleware in line (session) may still authenticate.

adminToken is the cleartext token from RELAY_ADMIN_TOKEN. Empty disables the bypass entirely.

func CORS

func CORS(allowedOrigins ...string) func(http.Handler) http.Handler

CORS returns a middleware that handles preflight (OPTIONS) and adds the headers needed for a credentialed browser fetch from one of the allowed origins. Required because the control API is consumed by a frontend on a separate hostname (e.g. https://relay.wyolet.dev).

allowedOrigins is matched exactly against the Origin header — wildcard origins are not allowed when Access-Control-Allow-Credentials is true, per the CORS spec.

func ConfigJSONHandler added in v0.4.1

func ConfigJSONHandler(d Deps) http.HandlerFunc

ConfigJSONHandler serves GET /config.json at the control listener ROOT. The UI fetches ${origin}/config.json at boot — before it knows the /api prefix — so this must stay at root even though the rest of the control API mounts under /api. Static fields are marshalled per request because feature flags (auth:oidc) are settings-driven and may flip at runtime. Mirrors registerConfigJSON's body shaping.

func Mount

func Mount(r chi.Router, d Deps) huma.API

Mount installs the control-plane huma API on r and registers all operations. Returns the huma.API so the caller can attach test-only ops.

Middleware order on r (caller is responsible for wiring these onto the chi router before any operations are matched):

  1. session.Manager.Middleware — loads cookie session, sets Actor in ctx
  2. AdminTokenMiddleware — sets Actor in ctx when bearer matches

Per-operation Middlewares attached by Mount enforce RequireActor on every protected route. Public ops (/auth/login, /version) omit it.

func MountOIDCCallbackRoot added in v0.9.9

func MountOIDCCallbackRoot(r chi.Router, d Deps)

MountOIDCCallbackRoot mounts GET /auth/callback at the listener root — the conventional shape for a registered redirect URI is https://<origin>/auth/callback, not an /api-prefixed path. It runs outside the /api group where Mount installs the session middleware, so it wraps the handler in that middleware itself (Login needs scs context). The /api/auth/oidc/callback mount stays for deployments whose IdP registration predates this path.

func RequireActor

func RequireActor(next http.Handler) http.Handler

RequireActor blocks any request that has no Actor in context. Stacked after AdminTokenMiddleware and the session middleware so either auth path can satisfy it.

Types

type Deps

type Deps struct {
	// Identity is the YAML-backed user store used by /auth/login.
	Identity *identity.Store

	// Users is the DB-backed user store. Login consults it before the YAML
	// fallback; the OIDC callback provisions into it. nil disables both
	// (YAML-only deployments).
	Users *user.Store

	// Sessions is the cookie-backed session manager. Login/Logout write to
	// it; the session middleware (installed by Mount) reads from it.
	Sessions *session.Manager

	// TokenSigner holds the inference-token signing key. nil (or an empty
	// signer) disables minting and revoke-by-token.
	TokenSigner *TokenSigner

	// TokenDenylist is where a revoked token's jti is written for the data
	// plane to read. nil disables per-token revocation (the token-version
	// bump still works).
	TokenDenylist TokenDenylist

	// MintLimiter caps how often one user may mint an inference token.
	// nil leaves minting unmetered.
	MintLimiter MintLimiter

	// RotateTokenKey generates a fresh signing key, installs it on both
	// planes (keeping the outgoing one on the verifier) and records the new
	// ref in the auth:tokens section. Wired by the composition root, which
	// owns the secret store and the master key; nil disables the endpoint.
	RotateTokenKey func(ctx context.Context) error

	// AdminToken is the cleartext break-glass bearer. Empty disables the
	// bypass. Validated by AdminTokenMiddleware; not used directly by
	// handlers.
	AdminToken string

	// Authz is the policy-decision interface. Handlers call
	// d.Authz.Authorize before mutations; RELAY_AUTHZ picks the impl.
	Authz authz.Authorizer

	// License is the gate for licensed features and the backing of the
	// /license endpoints. nil is a community deployment.
	License license.Service

	// Catalog is the in-memory snapshot used for slug→id resolution on
	// reads. Writes go through Stores.
	Catalog *appcatalog.Catalog

	// Stores is the bundle of typed stores used by CRUD writes.
	Stores *appcatalog.Stores

	// CookieSecure controls the Secure attribute on the session cookie.
	// Surfaced here so the OpenAPI doc can reflect deployment posture.
	CookieSecure bool

	// UsageReader serves /usage/* read-side endpoints. nil disables
	// them — useful for deployments where usage events are consumed
	// from a separate store.
	UsageReader usagelog.Reader

	// Audit receives one event per audited admin request. nil disables
	// audit capture entirely (no middleware, no rows).
	Audit *audit.Emitter

	// AuditReader serves GET /audit. nil disables the endpoint.
	AuditReader audit.Reader

	// TrustedProxies is the proxy set the audit middleware honours
	// X-Forwarded-For behind. nil records the peer address.
	TrustedProxies []*net.IPNet

	// PayloadReader serves /payloads/* read-side endpoints (the Logs view).
	// nil disables them — e.g. minimal builds or deployments where captured
	// bodies are consumed from a separate store.
	PayloadReader payloadlog.Reader

	// Selector is the keypool circuit-breaker owner, shared with the data
	// plane. The host-key health endpoint reads per-key breaker state through
	// it. nil disables that endpoint.
	Selector *keypool.Selector

	// HostHealth reads per-host runtime reachability (observed state), shared
	// with the data plane. Overlays host.Status on host reads. nil disables
	// the overlay (Status stays absent → UI shows "unknown").
	HostHealth HostHealthReader

	// PublicURL is the deployment's externally reachable control-plane
	// origin. Exported manifests reference the schema endpoint under it;
	// empty renders the reference relative.
	PublicURL string

	// RuntimeConfig is the public config served at GET /config.json for the
	// embedded admin UI. Zero value is fine (UI falls back to origin defaults).
	RuntimeConfig RuntimeConfig
}

Deps is the typed dependency bundle for the admin plane.

type HostHealthReader added in v0.2.0

type HostHealthReader interface {
	Read(ctx context.Context, hostID string) (host.Status, bool)
	ReadAll(ctx context.Context) map[string]host.Status
}

HostHealthReader reads observed host reachability. Implemented by app/hosthealth.Recorder.

type MintLimiter added in v0.10.0

type MintLimiter interface {
	Reserve(ctx context.Context, scope string, rules []pkgratelimit.Rule) (*pkgratelimit.Reservation, error)
}

MintLimiter meters how often one user may mint a token. Satisfied by *pkg/ratelimit.Limiter; nil leaves minting unmetered.

type RuntimeConfig added in v0.2.0

type RuntimeConfig struct {
	ControlAPIURL   string          `json:"controlApiUrl,omitempty"`
	InferenceAPIURL string          `json:"inferenceApiUrl,omitempty"`
	Mode            string          `json:"mode,omitempty"` // "oss" | "cloud"
	Version         string          `json:"version,omitempty"`
	Features        map[string]bool `json:"features,omitempty"`
	Telemetry       *Telemetry      `json:"telemetry,omitempty"`
	DocsURL         string          `json:"docsUrl,omitempty"`
	SupportURL      string          `json:"supportUrl,omitempty"`
}

RuntimeConfig is the JSON shape the UI reads. Every field is optional and omitempty: an empty controlApiUrl tells the UI to use its own origin; an empty inferenceApiUrl has no safe origin default (UI/data-plane may differ), so the UI prompts rather than guessing. The object is additive — the UI reads keys it knows and ignores the rest.

type Telemetry added in v0.2.0

type Telemetry struct {
	SentryDSN   string `json:"sentryDsn,omitempty"`
	Environment string `json:"environment,omitempty"`
}

Telemetry carries PUBLIC client-side telemetry config only.

type TokenDenylist added in v0.10.0

type TokenDenylist interface {
	Set(ctx context.Context, key string, value []byte, ttl time.Duration) error
}

TokenDenylist writes the per-token revocation entries the data plane's Reserve script reads. Satisfied by kv.Store.

type TokenSigner added in v0.10.0

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

TokenSigner holds the Ed25519 signing key. The composition root swaps the key in when the auth:tokens section changes; an empty signer refuses to mint, which is the posture of a deployment with no master key.

func (*TokenSigner) PublicKey added in v0.10.0

func (s *TokenSigner) PublicKey() ed25519.PublicKey

PublicKey returns the verification half, or nil when no key is installed.

func (*TokenSigner) SetPreviousPublicKey added in v0.10.0

func (s *TokenSigner) SetPreviousPublicKey(pub ed25519.PublicKey)

SetPreviousPublicKey records the key a rotation retired. Call it after SetSeed, which clears it.

func (*TokenSigner) SetSeed added in v0.10.0

func (s *TokenSigner) SetSeed(seed []byte)

SetSeed installs the signing key from its 32-byte seed. A nil seed disables minting.

type UsageFilterInput

type UsageFilterInput struct {
	Since        string   `query:"since" doc:"Relative window (e.g. \"1h\", \"24h\", \"7d\"). Default \"1h\". Ignored when from is set."`
	From         string   `query:"from" doc:"Absolute lower bound (RFC3339). Overrides since."`
	To           string   `query:"to" doc:"Absolute upper bound (RFC3339)."`
	RequestID    string   `query:"request_id" doc:"Exact match on a single request id (deep-link one event)."`
	RelayKeyHash []string `query:"relay_key_hash" doc:"Match any of the given sha256 hashes of the inbound bearer."`
	PolicyID     []string `query:"policy_id" doc:"Match any of the given Policy.metadata.id values."`
	ProjectID    []string `query:"project_id" doc:"Match any of the given Project.metadata.id values."`
	TeamID       []string `query:"team_id" doc:"Match any of the given Team.metadata.id values."`
	PrincipalID  []string `query:"principal_id" doc:"Match any of the given principal ids (ServiceAccount.metadata.id or user id)."`
	ModelID      []string `query:"model_id" doc:"Match any of the given Model.metadata.id values."`
	HostID       []string `query:"host_id" doc:"Match any of the given Host.metadata.id values."`
	Source       []string `query:"source" doc:"Match any of \"pipeline\" | \"proxy\" | \"ws\" | \"batch\"."`
	FinishReason []string `query:"finish_reason" doc:"Match any of \"stop\" | \"length\" | \"tool_calls\" | \"content_filter\" | \"refusal\"."`
	ErrorKind    []string `query:"error_kind" doc:"Match any of the given error_kind values."`
	StatusMin    int      `query:"status_min" doc:"Minimum HTTP status to include."`
	StatusMax    int      `query:"status_max" doc:"Maximum HTTP status to include."`

	HostKeyID      []string `query:"host_key_id" doc:"Match any of the given HostKey.metadata.id values."`
	RequestedModel []string `query:"requested_model" doc:"Match any of the model strings as the caller sent them."`
	Model          []string `query:"model" doc:"Match any of the given model slugs (event-time metadata.name, denormalized)."`
	Host           []string `query:"host" doc:"Match any of the given host slugs (event-time metadata.name, denormalized)."`
	Policy         []string `query:"policy" doc:"Match any of the given policy slugs (event-time metadata.name, denormalized)."`
	Provider       []string `query:"provider" doc:"Match any of the given provider slugs (event-time, denormalized)."`
	Status         []int    `query:"status" doc:"Match any of these exact HTTP status codes."`
	StatusClass    string   `query:"status_class" doc:"Convenience status band: \"2xx\" | \"4xx\" | \"5xx\". Sets status_min/max."`
	Streamed       string   `query:"streamed" enum:"true,false" doc:"true = only streamed responses, false = only non-streamed."`
	Error          string   `query:"error" enum:"true,false" doc:"true = only errors (status>=400 or error_kind set), false = only successes."`
	AttemptsMin    int      `query:"attempts_min" doc:"Minimum upstream try count (failover) — finds retried requests."`
	DurationMsMin  int64    `query:"duration_ms_min" doc:"Minimum total duration in ms (slow-request filter)."`
	DurationMsMax  int64    `query:"duration_ms_max" doc:"Maximum total duration in ms."`
	TTFTMsMin      int64    `query:"ttft_ms_min" doc:"Minimum upstream time-to-first-byte (ms); excludes requests with no upstream timing."`
	TTFTMsMax      int64    `query:"ttft_ms_max" doc:"Maximum upstream time-to-first-byte (ms)."`
	Q              string   `query:"q" doc:"Free-text substring across request_id, model_id, requested_model, source."`
	Tag            []string `` /* 142-byte string literal not displayed */
}

Jump to

Keyboard shortcuts

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