Documentation
¶
Overview ¶
Package auth implements authentication middleware for the Agent Protocol API. Auth is opt-in: when no provider is configured (type=none), all requests pass through.
Index ¶
- Constants
- Variables
- func AgentRunPermission(agentID string) string
- func AllowsSimulation(result *AuthResult, strict bool) bool
- func CanRunAgent(result *AuthResult, agentID string) bool
- func ClearSessionCookie(w http.ResponseWriter, r *http.Request)
- func ConfigureWorkloadIdentitiesFromEnv(rt *RunnerTokens) error
- func DelegatedJWTAssertion(result *AuthResult) string
- func HasVerifiedIdentity(result *AuthResult) bool
- func InheritJWTAssertionFromTrustedParent(result *AuthResult, assertion string)
- func MarkIdentityUnverified(result *AuthResult)
- func Middleware(provider Provider, adminProvider Provider, runnerTokens *RunnerTokens, ...) http.Handler
- func MiddlewareWithOpts(provider Provider, adminProvider Provider, runnerTokens *RunnerTokens, ...) http.Handler
- func RequireWorkloadAuthority(ctx context.Context) error
- func RequireWorkloadOwner(ctx context.Context, owner *transport.WorkloadIdentity) error
- func ReviewSessionIDFromRequest(r *http.Request) string
- func SessionIDFromRequest(r *http.Request) string
- func SetSessionCookie(w http.ResponseWriter, r *http.Request, sessionID string, ttl time.Duration)
- func SimulationRequested(raw string) bool
- func ValidRunID(id string) bool
- func WithContext(ctx context.Context, result *AuthResult) context.Context
- func WithRunBinding(ctx context.Context, b *RunBinding) context.Context
- func WorkloadIdentityFromContext(ctx context.Context) *transport.WorkloadIdentity
- type APIKeyEntry
- type APIKeyProvider
- type AdminSession
- type AdminSessionHandlers
- type AdminSessionStore
- func (s *AdminSessionStore) Create(result *AuthResult) (*AdminSession, error)
- func (s *AdminSessionStore) CreateReview(result *AuthResult) (*AdminSession, error)
- func (s *AdminSessionStore) Delete(id string) error
- func (s *AdminSessionStore) Get(id string) *AdminSession
- func (s *AdminSessionStore) TTL() time.Duration
- type AuthResult
- type ErrForbidden
- type ErrUnauthorized
- type InflightLookup
- type JWTConfig
- type JWTProvider
- type MiddlewareOpts
- type NoneProvider
- type Provider
- type RedisClient
- type ReviewCapabilities
- type ReviewSessionCreator
- type ReviewSessionHandlers
- type RunBinding
- type RunnerTokens
- func (rt *RunnerTokens) AllowsAssignment(kind, tenantID, agentID string) bool
- func (rt *RunnerTokens) AllowsPoolAgent(kind, agentID string) bool
- func (rt *RunnerTokens) AllowsTenant(runnerKind, tenantID string) bool
- func (rt *RunnerTokens) AuthenticateWorkloadTLS(ctx context.Context, connection *tls.ConnectionState, kind string) (context.Context, error)
- func (rt *RunnerTokens) ConfigureExecutionPools(pools *execution.Catalog) error
- func (rt *RunnerTokens) ConfigureWorkloadIdentities(allowed map[string][]string, maxTTL time.Duration) error
- func (rt *RunnerTokens) ConfigureWorkloadIdentityPolicy(allowed map[string][]string, deniedKeys []string, maxTTL time.Duration) error
- func (rt *RunnerTokens) Enabled() bool
- func (rt *RunnerTokens) TenantAllowListsComplete() bool
- func (rt *RunnerTokens) Validate(runnerKind, token string) bool
- func (rt *RunnerTokens) WorkloadIdentityEnabled() bool
- type SessionStore
- type WebhookConfig
- type WebhookProvider
Constants ¶
const ( CookieAdminSession = "runkite_admin_session" HeaderCSRF = "X-CSRF-Token" AdminSessionTTL = 12 * time.Hour CookieReviewSession = "runkite_review_session" ReviewSessionTTL = 15 * time.Minute SessionPurposeAdmin = "admin" SessionPurposeReview = "review" )
const ( HeaderRunnerKind = "X-Runner-Kind" HeaderRunnerToken = "X-Runner-Token" // HeaderTenantID is sent by runners on /internal/* that are not // run-bound (schema publish, status, A2A, connector metadata). On // run-bound proxy paths (store/vectors/connector session+MCP), // tenant is derived from the in-flight RunAssignment instead -- see // MiddlewareOpts.Inflight and requiresRunBinding. When // RUNNER_TENANTS_<KIND> is set, the effective tenant (header claim // or assignment) must be on that kind's allow-list. HeaderTenantID = "X-Runkite-Tenant-Id" HeaderTenantIDBase64 = "X-Runkite-Tenant-Id-B64" // HeaderSimulation marks a create-run as fixture replay. The server // sets run metadata.simulation = true only when this is set and the // caller is allowed (see AllowsSimulation). Clients cannot set the // flag through the metadata body. HeaderSimulation = "X-Runkite-Simulation" )
Header names for runner authentication on /internal/* HTTP routes. Mirrors the gRPC metadata keys (runner-kind/runner-token) used by the bridge server's interceptors -- same credential, same trust boundary, just carried over HTTP instead of gRPC metadata.
const ( GovernanceReadPermission = "governance:read" GovernanceApprovePermission = "governance:approve" )
const ( HeaderRunID = "X-Runkite-Run-Id" HeaderRunIDBase64 = "X-Runkite-Run-Id-B64" HeaderGeneration = "X-Runkite-Generation" )
Headers runners must send on run-bound /internal/* proxy paths so the control plane can prove the call belongs to an active dispatch.
const ( ReasonRunnerCredentialsInvalid = "runner_credentials_invalid" ReasonRunnerTenantDenied = "runner_tenant_denied" ReasonRunBindingRequired = "run_binding_required" ReasonRunNotInflight = "run_not_inflight" ReasonRunGenerationMismatch = "run_generation_mismatch" ReasonRunBindingLookupFailed = "run_binding_lookup_failed" ReasonRunThreadMismatch = "run_thread_mismatch" ReasonRunRunnerKindMismatch = "run_runner_kind_mismatch" )
Stable reason_code values for run-binding denials (and related /internal/* auth failures). Clients and SIEM can key off these without parsing free-form message text.
const EnvPrefix = "RUNNER_TOKEN_"
EnvPrefix is the environment variable prefix for runner tokens, e.g. RUNNER_TOKEN_PYTHON_LANGGRAPH for runner_kind "python-langgraph". The value may be a single token or a comma-separated allowlist.
const GovernanceDecidePermission = "governance:decide"
GovernanceDecidePermission is the permission for POST /governance/decide and GET /governance/actions/{id}. It is not implied by "write", "read", or agents:<id>:run. "admin" still implies it, via hasPermission. An empty permission list stays unrestricted when strict mode is off, same as every other client route.
const TenantsEnvPrefix = "RUNNER_TENANTS_"
TenantsEnvPrefix is the allow-list for X-Runkite-Tenant-Id on /internal/*, e.g. RUNNER_TENANTS_PYTHON_LANGGRAPH=acme,beta. Required by serve admission when client auth and RUNNER_TOKEN_* are both set.
Variables ¶
var ErrWorkloadIdentity = errors.New("verified workload identity required")
Functions ¶
func AgentRunPermission ¶
AgentRunPermission builds the agents:<id>:run grant string.
func AllowsSimulation ¶
func AllowsSimulation(result *AuthResult, strict bool) bool
AllowsSimulation is the same rule as Admin: fixture replay is tagged only for callers who could already mutate governance. write and agents:<id>:run are not enough. No auth configured (result nil) and empty permissions with strict=false follow the Admin convention.
func CanRunAgent ¶
func CanRunAgent(result *AuthResult, agentID string) bool
CanRunAgent reports whether the caller may create a run for agentID.
Rules (mirrors authorized()'s empty-list semantics):
- nil result or empty permissions → unrestricted (true)
- "admin" or "write" → any agent
- "agents:<agentID>:run" → that agent only
- otherwise → false
func ClearSessionCookie ¶
func ClearSessionCookie(w http.ResponseWriter, r *http.Request)
ClearSessionCookie expires the session cookie.
func ConfigureWorkloadIdentitiesFromEnv ¶ added in v0.8.0
func ConfigureWorkloadIdentitiesFromEnv(rt *RunnerTokens) error
func DelegatedJWTAssertion ¶ added in v0.8.0
func DelegatedJWTAssertion(result *AuthResult) string
DelegatedJWTAssertion returns only the original credential captured by strict JWT authentication. A copied claim or forwarded header cannot establish it.
func HasVerifiedIdentity ¶ added in v0.7.0
func HasVerifiedIdentity(result *AuthResult) bool
HasVerifiedIdentity distinguishes an authenticated explicit subject from a compatibility display name. Permission checks remain separate.
func InheritJWTAssertionFromTrustedParent ¶ added in v0.8.0
func InheritJWTAssertionFromTrustedParent(result *AuthResult, assertion string)
InheritJWTAssertionFromTrustedParent is only for delegation after the caller has matched the assignment identity to its verified frozen parent manifest. Untrusted on_behalf_of fields must never be passed to this helper.
func MarkIdentityUnverified ¶ added in v0.7.0
func MarkIdentityUnverified(result *AuthResult)
MarkIdentityUnverified only attenuates provenance. Delegation may retain an old display identity without turning it into a verified requester or voter.
func Middleware ¶
func Middleware(provider Provider, adminProvider Provider, runnerTokens *RunnerTokens, next http.Handler) http.Handler
Middleware returns an http.Handler that enforces auth before delegating to next with default (non-strict) permission semantics. See MiddlewareWithOpts.
func MiddlewareWithOpts ¶
func MiddlewareWithOpts(provider Provider, adminProvider Provider, runnerTokens *RunnerTokens, opts MiddlewareOpts, next http.Handler) http.Handler
MiddlewareWithOpts is Middleware plus MiddlewareOpts. client auth (provider), admin auth (adminProvider), and runner auth (runnerTokens) are three separate trust boundaries: provider protects the client-facing Agent Protocol surface, adminProvider is an optional, independent credential accepted ONLY for /admin-api/* (see its own doc comment below for why a deployment would configure one), and runnerTokens protects /internal/* (connector credentials, run status) which client auth always bypasses. Pass nil/disabled for any of the three that aren't configured -- adminProvider and a disabled runnerTokens are both common (local mode, or a deployment happy to gate /admin-api/* via the primary provider's own "admin" permission, the pre-existing behavior).
func RequireWorkloadAuthority ¶ added in v0.8.0
RequireWorkloadAuthority rechecks the immutable deployment policy for every operation. Replacing that policy requires draining/restarting every replica.
func RequireWorkloadOwner ¶ added in v0.8.0
func RequireWorkloadOwner(ctx context.Context, owner *transport.WorkloadIdentity) error
RequireWorkloadOwner checks both the original dispatch expiry and current connection proof. A kind or pool token does not authorize another worker.
func ReviewSessionIDFromRequest ¶ added in v0.7.0
func SessionIDFromRequest ¶
SessionIDFromRequest reads the admin session cookie.
func SetSessionCookie ¶
SetSessionCookie writes the httpOnly session cookie.
func SimulationRequested ¶
SimulationRequested reports whether a header value asks for fixture replay.
func ValidRunID ¶
ValidRunID rejects new identifiers that older helpers would normalize or could not carry safely. Empty selects a generated ID. Unicode is supported through the encoded binding header, without changing the stored identifier.
func WithContext ¶
func WithContext(ctx context.Context, result *AuthResult) context.Context
WithContext attaches AuthResult to context.
func WithRunBinding ¶
func WithRunBinding(ctx context.Context, b *RunBinding) context.Context
WithRunBinding attaches a resolved RunBinding to ctx.
func WorkloadIdentityFromContext ¶ added in v0.8.0
func WorkloadIdentityFromContext(ctx context.Context) *transport.WorkloadIdentity
Types ¶
type APIKeyEntry ¶
type APIKeyEntry struct {
Name string `json:"name"`
Permissions []string `json:"permissions,omitempty"`
// TenantID scopes this key's data for multi-tenancy.
// Empty resolves to tenant.DefaultTenant -- multi-tenancy is opt-in.
TenantID string `json:"tenant_id,omitempty"`
// Extra carries arbitrary per-key metadata into AuthResult.Extra --
// e.g. a downstream service credential or department tag a graph's
// tools need at runtime. Same mechanism/purpose as JWT's
// extra_claims and webhook's passthrough user fields (see jwt.go's
// doc comments); here the deployer just writes the value directly
// in langgraph.json since a static key has no token/claims of its
// own to extract it from.
Extra map[string]interface{} `json:"extra,omitempty"`
}
APIKeyEntry describes a single API key and its permissions.
type APIKeyProvider ¶
type APIKeyProvider struct {
// contains filtered or unexported fields
}
APIKeyProvider authenticates requests using a static key map. Accepts keys via Authorization: Bearer <key> or X-API-Key: <key> header.
func NewAPIKeyProvider ¶
func NewAPIKeyProvider(keys map[string]APIKeyEntry) *APIKeyProvider
NewAPIKeyProvider creates an API key provider from a key→entry map.
func (*APIKeyProvider) Authenticate ¶
func (p *APIKeyProvider) Authenticate(r *http.Request) (*AuthResult, error)
type AdminSession ¶
type AdminSession struct {
ID string
CSRF string
Result AuthResult
Expires time.Time
Purpose string
AbsoluteExpires time.Time
}
AdminSession is one browser login.
type AdminSessionHandlers ¶
type AdminSessionHandlers struct {
Store SessionStore
AdminProvider Provider
Provider Provider
Strict bool
// contains filtered or unexported fields
}
AdminSessionHandlers serves POST/GET/DELETE /admin-api/session. Login authenticates the pasted credential once; the browser never retains the API key/JWT afterward.
func (*AdminSessionHandlers) Create ¶
func (h *AdminSessionHandlers) Create(w http.ResponseWriter, r *http.Request)
Create handles POST /admin-api/session.
func (*AdminSessionHandlers) Delete ¶
func (h *AdminSessionHandlers) Delete(w http.ResponseWriter, r *http.Request)
Delete handles DELETE /admin-api/session (logout). Middleware already authenticated the session cookie + CSRF before this runs.
func (*AdminSessionHandlers) Status ¶
func (h *AdminSessionHandlers) Status(w http.ResponseWriter, r *http.Request)
Status handles GET /admin-api/session -- bootstrap for page refresh and the "is auth configured" probe (no cookie, open deployment).
type AdminSessionStore ¶
type AdminSessionStore struct {
// contains filtered or unexported fields
}
AdminSessionStore is the process-local SessionStore (no Redis).
func NewAdminSessionStore ¶
func NewAdminSessionStore(ttl time.Duration) *AdminSessionStore
NewAdminSessionStore creates an empty memory store. ttl <= 0 uses AdminSessionTTL.
func NewReviewSessionStore ¶ added in v0.7.0
func NewReviewSessionStore(ttl time.Duration) *AdminSessionStore
NewReviewSessionStore keeps review browser credentials separate from Admin.
func (*AdminSessionStore) Create ¶
func (s *AdminSessionStore) Create(result *AuthResult) (*AdminSession, error)
Create mints a session for result and returns the new session (caller sets cookies from ID/CSRF).
func (*AdminSessionStore) CreateReview ¶ added in v0.7.0
func (s *AdminSessionStore) CreateReview(result *AuthResult) (*AdminSession, error)
func (*AdminSessionStore) Delete ¶
func (s *AdminSessionStore) Delete(id string) error
Delete removes a session (logout). Idempotent.
func (*AdminSessionStore) Get ¶
func (s *AdminSessionStore) Get(id string) *AdminSession
Get returns a live session by id, sliding its expiry. nil if missing/expired.
func (*AdminSessionStore) TTL ¶
func (s *AdminSessionStore) TTL() time.Duration
TTL returns the configured sliding session lifetime.
type AuthResult ¶
type AuthResult struct {
Provenance *models.IdentityProvenance `json:"identity_provenance,omitempty"`
Identity string `json:"identity"`
Permissions []string `json:"permissions,omitempty"`
// TenantID scopes this caller's data for multi-tenancy.
// Empty means "no tenant claim configured" -- resolves to
// tenant.DefaultTenant, not an error; multi-tenancy is opt-in.
TenantID string `json:"tenant_id,omitempty"`
// DisplayName and Extra exist for the Factory Graph runtime.user
// passthrough (see internal/transport.UserContext / the Python
// runner's factory_graph.py): JWT (extra_claims/forward_token/
// forward_headers), API-key entry metadata, and webhook user
// fields all populate Extra. Never used for authorization
// decisions in Go -- purely forwarded to the runner.
DisplayName string `json:"display_name,omitempty"`
Extra map[string]interface{} `json:"extra,omitempty"`
// contains filtered or unexported fields
}
AuthResult is the output of a successful authentication.
func FromContext ¶
func FromContext(ctx context.Context) *AuthResult
FromContext extracts AuthResult from request context.
func (AuthResult) MarshalJSON ¶ added in v0.7.0
func (result AuthResult) MarshalJSON() ([]byte, error)
Internal session serialization preserves provider provenance across Redis and process boundaries. Legacy blobs do not establish verified identity.
func (*AuthResult) UnmarshalJSON ¶ added in v0.7.0
func (result *AuthResult) UnmarshalJSON(raw []byte) error
type ErrForbidden ¶
type ErrForbidden struct {
Message string
}
ErrForbidden is returned when the user is authenticated but not allowed.
func (*ErrForbidden) Error ¶
func (e *ErrForbidden) Error() string
type ErrUnauthorized ¶
type ErrUnauthorized struct {
}
ErrUnauthorized is returned when authentication fails.
func (*ErrUnauthorized) Error ¶
func (e *ErrUnauthorized) Error() string
type InflightLookup ¶
type InflightLookup interface {
LookupInflight(ctx context.Context, runID string) (*transport.RunAssignment, error)
}
InflightLookup resolves the currently in-flight RunAssignment for a run id. Satisfied by transport.JobQueue; kept as a narrow interface so auth tests can stub without a full queue.
type JWTConfig ¶
type JWTConfig struct {
// StrictIdentity requires configured issuer/audience and exp/sub claims.
// It also captures bounded nonsecret issuer-asserted delegation provenance.
StrictIdentity bool `json:"strict_identity,omitempty"`
// Test/development escape restricted to a literal loopback JWKS endpoint.
AllowInsecureLoopback bool `json:"allow_insecure_loopback,omitempty"`
JWKSURL string `json:"jwks_url"`
Issuer string `json:"issuer,omitempty"`
Audience string `json:"audience,omitempty"`
// TenantClaim is the JWT claim name to read the caller's tenant ID
// from, for multi-tenancy. Defaults to "tenant_id" if
// unset. A token missing this claim resolves to tenant.DefaultTenant,
// not an auth error -- multi-tenancy is opt-in per deployment.
TenantClaim string `json:"tenant_claim,omitempty"`
// ExtraClaims lists additional JWT claims to surface in
// AuthResult.Extra verbatim by claim name (and, on the Python
// runner, RunnerUser's dict-like/`.to_dict()` access), for
// application code that needs more than identity/permissions/
// tenant_id -- e.g. an `email` claim for per-user notifications, or
// a custom claim a downstream tool needs. Absent means none are
// surfaced (only Identity/Permissions/TenantID, the pre-existing
// behavior, unchanged). A listed claim that's absent from a given
// token is simply omitted from Extra, not an error.
ExtraClaims []string `json:"extra_claims,omitempty"`
// ForwardToken, when true, adds the raw, still-encoded bearer token
// itself to AuthResult.Extra under RawTokenField -- needed when
// downstream code does its own token exchange (e.g. RFC 8693) using
// the SAME credential that authenticated the original request,
// rather than a claim extracted from it. Off by default: forwarding
// a live bearer credential to every consumer of AuthResult (and,
// from there, every runner that receives RunAssignment.User) is a
// meaningfully bigger trust surface than forwarding parsed claims,
// so this opts in explicitly rather than happening automatically
// just because JWT auth is configured.
ForwardToken bool `json:"forward_token,omitempty"`
// RawTokenField names the Extra key the raw token is stored under
// when ForwardToken is true. Defaults to "token". Configurable
// (rather than a fixed name) so an existing deployment's tool code
// that already expects a specific key (e.g. a field named
// "sso_token") can be pointed at unchanged, without runkite
// needing to know that name in advance.
RawTokenField string `json:"raw_token_field,omitempty"`
// ClaimAliases renames ExtraClaims when writing AuthResult.Extra:
// map key = claim name in the JWT, value = Extra key the runner
// should see. Needed when JWT claim casing/naming (e.g. "orgUserId")
// doesn't match what application code already looks up (e.g.
// "org_user_id"). Claims not listed keep their JWT name.
ClaimAliases map[string]string `json:"claim_aliases,omitempty"`
// ForwardHeaders copies selected request headers into
// AuthResult.Extra (map: header name → Extra key). Opt-in so a
// deployment can forward sidecar tokens (e.g. X-HRSystem-Token →
// hr_system_token) without baking header names into runkite.
// Empty/missing header values are omitted, not errors.
ForwardHeaders map[string]string `json:"forward_headers,omitempty"`
// ScopeAsPermissions opts into treating the standard OAuth2 "scope"
// claim as this app's read/write/admin permission list when no
// "permissions" claim is present. Off by default: "scope" is a
// client-consent concept (what the token issuer let the calling
// client app request about the resource owner -- typically
// "openid profile email" from any standard OIDC provider), not an
// app-level authorization signal. Auto-converting it silently
// denied every request from real SSO providers (their scope values
// never happen to be "read"/"write"/"admin"), which is worse than
// just leaving permissions empty -- an empty list already means
// "unrestricted" (see authorized() in auth.go), the correct
// behavior for an IdP that doesn't carry app RBAC in the token at
// all. Set this only for deployments that deliberately mint scope
// values matching this app's permission strings.
ScopeAsPermissions bool `json:"scope_as_permissions,omitempty"`
}
JWTConfig configures the JWT auth provider.
type JWTProvider ¶
type JWTProvider struct {
// contains filtered or unexported fields
}
JWTProvider validates JWTs against a JWKS endpoint.
func NewJWTProvider ¶
func NewJWTProvider(cfg JWTConfig) (*JWTProvider, error)
NewJWTProvider creates a JWT provider that fetches keys from a JWKS URL. The keyfunc library handles caching and automatic refresh.
func (*JWTProvider) Authenticate ¶
func (p *JWTProvider) Authenticate(r *http.Request) (*AuthResult, error)
type MiddlewareOpts ¶
type MiddlewareOpts struct {
// StrictPermissions rejects authenticated callers whose app-level
// permissions list is empty (see authorized). Default false preserves
// the backward-compatible "empty = unrestricted" convention.
StrictPermissions bool
// AdminSessions, when set, accepts the Admin UI httpOnly session
// cookie on /admin-api/* (when no Authorization/X-API-Key header is
// present). Mutating methods require X-CSRF-Token. Bearer auth is
// unchanged for machine clients.
AdminSessions SessionStore
// ReviewSessions uses a separate store and accepts scoped review cookies
// only on the allowlisted /review-api surface.
ReviewSessions SessionStore
// Inflight, when set, enables run-binding on connector session/MCP,
// store, and vector /internal/* paths: callers must present
// X-Runkite-Run-Id + X-Runkite-Generation for an active assignment,
// and tenant/agent are taken from that assignment (runner tenant
// headers are ignored on those paths). Production serve always sets
// this to the job queue; nil keeps the legacy header-only tenant
// model (test helpers that do not wire a queue).
Inflight InflightLookup
}
MiddlewareOpts configures optional authorization behavior for Middleware.
type NoneProvider ¶
type NoneProvider struct{}
NoneProvider is a no-op auth provider that allows all requests as anonymous.
func (*NoneProvider) Authenticate ¶
func (n *NoneProvider) Authenticate(r *http.Request) (*AuthResult, error)
type Provider ¶
type Provider interface {
Authenticate(r *http.Request) (*AuthResult, error)
}
Provider is the interface all auth providers implement.
type RedisClient ¶
type RedisClient interface {
Get(ctx context.Context, key string) *redis.StringCmd
Set(ctx context.Context, key string, value interface{}, expiration time.Duration) *redis.StatusCmd
Del(ctx context.Context, keys ...string) *redis.IntCmd
Eval(ctx context.Context, script string, keys []string, args ...interface{}) *redis.Cmd
}
RedisClient is the subset of go-redis used by redisAdminSessionStore.
type ReviewCapabilities ¶ added in v0.7.0
func ReviewCapabilitiesFromResult ¶ added in v0.7.0
func ReviewCapabilitiesFromResult(result *AuthResult) (ReviewCapabilities, bool)
ReviewCapabilitiesFromResult never inherits default-open client permissions. Scope comes from verified identity claims, not request metadata.
type ReviewSessionCreator ¶ added in v0.7.0
type ReviewSessionCreator interface {
CreateReview(result *AuthResult) (*AdminSession, error)
}
ReviewSessionCreator is optional. A custom store without this attenuation capability cannot create browser review sessions.
type ReviewSessionHandlers ¶ added in v0.7.0
type ReviewSessionHandlers struct {
Store SessionStore
Provider Provider
// contains filtered or unexported fields
}
ReviewSessionHandlers authenticates only through the primary identity provider. Its cookie, CSRF token, storage namespace and authority are separate from Admin.
func (*ReviewSessionHandlers) Create ¶ added in v0.7.0
func (h *ReviewSessionHandlers) Create(w http.ResponseWriter, r *http.Request)
func (*ReviewSessionHandlers) Delete ¶ added in v0.7.0
func (h *ReviewSessionHandlers) Delete(w http.ResponseWriter, r *http.Request)
Delete requires middleware authentication and cookie CSRF for cookie callers.
func (*ReviewSessionHandlers) Status ¶ added in v0.7.0
func (h *ReviewSessionHandlers) Status(w http.ResponseWriter, r *http.Request)
type RunBinding ¶
type RunBinding struct {
RunID string
RunIncarnationID string
Generation int64
TenantID string
AgentID string
ThreadID string
User *transport.UserContext
WorkloadIdentity *transport.WorkloadIdentity
}
RunBinding is the control-plane-derived identity for a run-bound /internal/* call. Tenant/agent/thread come from the assignment, not from runner-supplied headers.
func RunBindingFromContext ¶
func RunBindingFromContext(ctx context.Context) *RunBinding
RunBindingFromContext returns the RunBinding set by middleware, or nil.
type RunnerTokens ¶
type RunnerTokens struct {
// contains filtered or unexported fields
}
RunnerTokens implements two-tier runner authentication: local mode (no tokens configured -- runner trusted implicitly, zero setup) and production mode (one or more shared tokens per runner_kind). A leaked token cannot impersonate a different runner type. Multiple comma-separated values for the same kind form a fleet allowlist: independently revocable credentials and dual-token rotation, not unique-per-pod secrets (K8s Deployments share one Secret across pods of a fleet).
This is a distinct trust boundary from the client-facing Provider/Middleware above: it protects the gRPC bridge (GetJob/StreamEvents/ReportStatus/WatchCancels) and the /internal/* HTTP routes that vend connector credentials and run status -- surfaces the client-facing auth middleware always lets through.
Per-kind tenant allow-lists (RUNNER_TENANTS_*) restrict which X-Runkite-Tenant-Id values a kind token may claim on /internal/*. When unset for a kind, AllowsTenant still accepts any tenant (runtime). With client-facing auth + RUNNER_TOKEN_*, serve admission requires every tokenized kind to have a non-empty list (use "default" for single-tenant). A missing header is treated as "default" for the allow check. Tenant lists are per-kind, not per fleet token.
func LoadRunnerTokensFromEnv ¶
func LoadRunnerTokensFromEnv() *RunnerTokens
LoadRunnerTokensFromEnv scans the process environment for RUNNER_TOKEN_* and optional RUNNER_TENANTS_* variables and builds a RunnerTokens set keyed by runner_kind.
func (*RunnerTokens) AllowsAssignment ¶ added in v0.7.0
func (rt *RunnerTokens) AllowsAssignment(kind, tenantID, agentID string) bool
func (*RunnerTokens) AllowsPoolAgent ¶ added in v0.7.0
func (rt *RunnerTokens) AllowsPoolAgent(kind, agentID string) bool
func (*RunnerTokens) AllowsTenant ¶
func (rt *RunnerTokens) AllowsTenant(runnerKind, tenantID string) bool
AllowsTenant reports whether runnerKind may claim tenantID on /internal/* (via X-Runkite-Tenant-Id). Always true in local mode, when no allow-list is configured for that kind, or when the allow-list is empty. A missing tenantID is treated as tenant.DefaultTenant for the check. Nonempty identities are compared exactly; whitespace is never trimmed from an assignment.
func (*RunnerTokens) AuthenticateWorkloadTLS ¶ added in v0.8.0
func (rt *RunnerTokens) AuthenticateWorkloadTLS(ctx context.Context, connection *tls.ConnectionState, kind string) (context.Context, error)
AuthenticateWorkloadTLS accepts only a certificate verified by this server's TLS handshake. PeerCertificates alone, forwarded headers and certificate CN are deliberately insufficient. The public key is proof of possession from TLS.
func (*RunnerTokens) ConfigureExecutionPools ¶ added in v0.7.0
func (rt *RunnerTokens) ConfigureExecutionPools(pools *execution.Catalog) error
ConfigureExecutionPools requires separate credentials for each pool. A credential reused by another kind would erase the intended fleet boundary.
func (*RunnerTokens) ConfigureWorkloadIdentities ¶ added in v0.8.0
func (rt *RunnerTokens) ConfigureWorkloadIdentities(allowed map[string][]string, maxTTL time.Duration) error
ConfigureWorkloadIdentities enables the strict profile. External issuance owns certificates and keys; this allowlist only authorizes URI SANs for existing runner kinds or execution pools.
func (*RunnerTokens) ConfigureWorkloadIdentityPolicy ¶ added in v0.8.0
func (*RunnerTokens) Enabled ¶
func (rt *RunnerTokens) Enabled() bool
Enabled reports whether production mode is active (any token configured). When false, all runners are trusted implicitly (local mode, zero friction).
func (*RunnerTokens) TenantAllowListsComplete ¶
func (rt *RunnerTokens) TenantAllowListsComplete() bool
TenantAllowListsComplete reports whether every kind that has a runner token also has a non-empty RUNNER_TENANTS_* allow-list. True when runner tokens are disabled (local mode). Used by serve admission so client-facing auth + RUNNER_TOKEN_* cannot start with open tenant claiming on unbound /internal/* routes — set RUNNER_TENANTS_<KIND>=default for single-tenant.
func (*RunnerTokens) Validate ¶
func (rt *RunnerTokens) Validate(runnerKind, token string) bool
Validate checks a runner's claimed kind and token. Always true in local mode. Compares against every allowlisted token for that kind with constant-time equality (OR of matches) so a leaked fleet A token can be revoked without rotating fleet B.
func (*RunnerTokens) WorkloadIdentityEnabled ¶ added in v0.8.0
func (rt *RunnerTokens) WorkloadIdentityEnabled() bool
type SessionStore ¶
type SessionStore interface {
Create(result *AuthResult) (*AdminSession, error)
Get(id string) *AdminSession
Delete(id string) error
TTL() time.Duration
}
SessionStore persists Admin UI browser sessions (memory or Redis).
func NewRedisAdminSessionStore ¶
func NewRedisAdminSessionStore(rdb RedisClient, ttl time.Duration) SessionStore
NewRedisAdminSessionStore shares Admin UI sessions via Redis (auto when REDIS_URL is set). ttl <= 0 uses AdminSessionTTL.
func NewRedisReviewSessionStore ¶ added in v0.7.0
func NewRedisReviewSessionStore(rdb RedisClient, ttl time.Duration) SessionStore
NewRedisReviewSessionStore isolates review credentials from old Admin readers.
type WebhookConfig ¶
type WebhookConfig struct {
URL string `json:"url"`
TimeoutMs int `json:"timeout_ms"`
CacheTTLSeconds int `json:"cache_ttl_seconds"`
// CacheMaxEntries bounds the auth result cache's size -- see
// WebhookProvider's own doc comment for why an unbounded map here
// was a real, not theoretical, memory-growth risk. 0 (the default,
// no config needed for the common case) applies defaultCacheMaxEntries.
CacheMaxEntries int `json:"cache_max_entries,omitempty"`
}
WebhookConfig configures the webhook auth provider.
type WebhookProvider ¶
type WebhookProvider struct {
// contains filtered or unexported fields
}
WebhookProvider delegates auth to an external HTTP sidecar.
func NewWebhookProvider ¶
func NewWebhookProvider(cfg WebhookConfig) *WebhookProvider
NewWebhookProvider creates a webhook auth provider.
func (*WebhookProvider) Authenticate ¶
func (p *WebhookProvider) Authenticate(r *http.Request) (*AuthResult, error)
func (*WebhookProvider) CacheLen ¶
func (p *WebhookProvider) CacheLen() int
CacheLen returns the current number of cached auth results, mainly for tests that need to confirm the size bound actually holds. 0 if caching is disabled (CacheTTLSeconds <= 0).