auth

package
v0.6.1 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: Apache-2.0 Imports: 27 Imported by: 0 modules, 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 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

View Source
const (
	CookieAdminSession = "runkite_admin_session"
	HeaderCSRF         = "X-CSRF-Token"
	AdminSessionTTL    = 12 * time.Hour
)
View Source
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.

View Source
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.

View Source
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.

View Source
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.

View Source
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.

View Source
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

This section is empty.

Functions

func AgentRunPermission

func AgentRunPermission(agentID string) string

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 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 SessionIDFromRequest

func SessionIDFromRequest(r *http.Request) string

SessionIDFromRequest reads the admin session cookie.

func SetSessionCookie

func SetSessionCookie(w http.ResponseWriter, r *http.Request, sessionID string, ttl time.Duration)

SetSessionCookie writes the httpOnly session cookie.

func SimulationRequested

func SimulationRequested(raw string) bool

SimulationRequested reports whether a header value asks for fixture replay.

func ValidRunID

func ValidRunID(id string) bool

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.

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
}

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

Create handles POST /admin-api/session.

func (*AdminSessionHandlers) Delete

Delete handles DELETE /admin-api/session (logout). Middleware already authenticated the session cookie + CSRF before this runs.

func (*AdminSessionHandlers) Status

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 (*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) Delete

func (s *AdminSessionStore) Delete(id string) error

Delete removes a session (logout). Idempotent.

func (*AdminSessionStore) Get

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 {
	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"`
}

AuthResult is the output of a successful authentication.

func FromContext

func FromContext(ctx context.Context) *AuthResult

FromContext extracts AuthResult from request context.

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 {
	Message string
}

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 {
	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
	// 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 RunBinding

type RunBinding struct {
	RunID      string
	Generation int64
	TenantID   string
	AgentID    string
	ThreadID   string
	User       *transport.UserContext
}

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) 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) 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.

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.

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).

Jump to

Keyboard shortcuts

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