Documentation
¶
Overview ¶
Package auth provides admin and downstream proxy authentication middleware with IP allowlisting and rate limiting.
metapi-go/auth — sensitive-operation re-confirmation (#1034).
A live admin session (or a Bearer master token) authorizes ordinary admin API calls. Destructive/irreversible surfaces additionally require the operator to present the master token again in X-Admin-Confirm-Token, so a walk-away session or a hijacked tab cannot silently exfiltrate backups, downstream keys, or rotate the master token itself. The header value is compared hash-then-constant-time and never logged.
metapi-go/auth — cross-site request guard for cookie-authenticated admin surfaces.
The admin UI authenticates with a SameSite=Strict cookie, which blocks cross-site requests but not same-site ones: a sibling subdomain (or another service on the same host) is "same-site" and can still drive state-changing requests. Browsers send Origin on unsafe requests and Sec-Fetch-Site on all fetch/navigation requests, so comparing them closes the sibling-subdomain and same-host-other-port gaps without affecting non-browser clients (curl/scripts send neither header).
metapi-go/auth — server-side admin sessions (#1034 session model).
The admin UI no longer persists the master token (config.AuthToken) in the browser. Login exchanges the master token for a random session credential carried in an HttpOnly, SameSite=Strict cookie; only the SHA-256 hash of the credential is persisted (admin_sessions, migration sc2_026). Sessions slide on activity and die on logout/revocation/expiry.
The master token itself stays valid as a Bearer API credential (dual-track in AdminAuth) so external scripts/automation keep working; the UI simply never stores it client-side anymore.
GC policy (kept deliberately simple): expired rows are purged lazily on validate and opportunistically on every new login. Session rows are tiny and login is rate-limited, so no scheduler job is warranted.
Index ¶
- Constants
- Variables
- func AdminAuth(sessions *SessionManager) func(http.Handler) http.Handler
- func AdminAuthFromRequest(r *http.Request) *http.Request
- func AdminRateLimit(rps, burst int) func(http.Handler) http.Handler
- func AuthRateLimit(rps, burst int) func(http.Handler) http.Handler
- func CheckDownstreamKeyIP(key *managedKeyView, clientIP string) (bool, string)
- func ClearSessionCookie(w http.ResponseWriter, r *http.Request, secureMode string)
- func ClearUserSessionCookie(w http.ResponseWriter, r *http.Request, secureMode string)
- func ClientIP(r *http.Request) string
- func ConfigureSharedAdmissionFromRedisURL(redisURL string)
- func DirectVideoTaskOwner(pac *ProxyAuthContext) string
- func GetAdminSessionID(ctx context.Context) string
- func GetUserSession(ctx context.Context) *store.UserSession
- func IsAdmin(ctx context.Context) bool
- func OAuthRateLimit(rps, burst int) func(http.Handler) http.Handler
- func ProxyAuth() func(http.Handler) http.Handler
- func ProxyAuthFromRequest(r *http.Request, pac *ProxyAuthContext) *http.Request
- func ProxyRateLimit(rpm int) func(http.Handler) http.Handler
- func ReauthConfirmed(r *http.Request) bool
- func RecordManagedKeyCostUsage(keyID int64, estimatedCost float64)
- func RecordManagedKeyQuotaUsage(keyID int64, reservationID string, tokens *int64, cost *float64)
- func ReleaseManagedKeyQuotaReservation(reservationID string)
- func RequireReauth() func(http.Handler) http.Handler
- func ResetKeyAdmissionForTest()
- func ResolveGatewayUser(ctx context.Context, users GatewayUserReader) (store.GatewayUser, error)
- func SameOriginGuard(allowedOrigins []string) func(http.Handler) http.Handler
- func SessionCookieFromRequest(r *http.Request) string
- func SetSessionCookie(w http.ResponseWriter, r *http.Request, rawToken string, ttl time.Duration, ...)
- func SetUserSessionCookie(w http.ResponseWriter, r *http.Request, raw, secureMode string)
- func UserSameOriginGuard(next http.Handler) http.Handler
- func UserSessionAuth(m *UserSessionManager) func(http.Handler) http.Handler
- func WithAdminAuth(ctx context.Context) context.Context
- func WithAdminSessionID(ctx context.Context, sessionID string) context.Context
- func WithGatewayUserPrincipal(ctx context.Context, principal GatewayUserPrincipal) context.Context
- func WithProxyAuth(ctx context.Context, pac *ProxyAuthContext) context.Context
- func WriteReauthRequired(w http.ResponseWriter)
- type AdmissionDecision
- type CredentialRefKind
- type DownstreamRoutingPolicy
- type DownstreamTokenAuthResult
- type ExcludedCredentialRef
- type GatewayUserPrincipal
- type GatewayUserReader
- type KeyAdmissionLimiter
- func (l *KeyAdmissionLimiter) Allow(ctx context.Context, keyID int64, maxRPM, maxTPM *int64, estimatedTokens int64) AdmissionDecision
- func (l *KeyAdmissionLimiter) SetSharedRPMCounter(c sharedcount.WindowCounter)
- func (l *KeyAdmissionLimiter) SetSharedTPMCounter(c sharedcount.WindowCounter)
- func (l *KeyAdmissionLimiter) Snapshot(keyID int64) (usedRPM, usedTPM int64)
- type ManagedKeyAdmissionBlocker
- type ManagedKeyAdmissionExplanation
- type ManagedKeyContext
- type ManagedKeyIPCheck
- type ManagedKeyQuotaExplanation
- type ManagedKeyRateWindows
- type ManagedKeyWindowUsage
- type ProxyAuthContext
- type ProxyResourceOwner
- type Session
- type SessionManager
- func (sm *SessionManager) ConsumeWSTicket(ticket string) bool
- func (sm *SessionManager) Count(ctx context.Context) int
- func (sm *SessionManager) Create(ctx context.Context, clientIP, userAgent string) (string, *Session, error)
- func (sm *SessionManager) IssueWSTicket() (string, time.Duration)
- func (sm *SessionManager) Revoke(ctx context.Context, rawToken string)
- func (sm *SessionManager) RevokeAll(ctx context.Context)
- func (sm *SessionManager) TTL() time.Duration
- func (sm *SessionManager) Validate(ctx context.Context, rawToken string) *Session
- type UserSessionManager
- func (m *UserSessionManager) Activate(ctx context.Context, username, code, password string) error
- func (m *UserSessionManager) AllowAccount(username string) bool
- func (m *UserSessionManager) ChangePassword(ctx context.Context, userID int64, ...) error
- func (m *UserSessionManager) IssueActivation(ctx context.Context, userID int64) (string, time.Time, error)
- func (m *UserSessionManager) Login(ctx context.Context, username, password string) (string, *store.UserSession, error)
- func (m *UserSessionManager) Revoke(ctx context.Context, raw string) error
Constants ¶
const ( // ErrorCodeAuthSessionExpired: a cookie session was presented but is // unknown/expired (401; the frontend redirects to sign-in). ErrorCodeAuthSessionExpired = "authSessionExpired" // ErrorCodeAuthMissingCredential: no Authorization header and no session // cookie (401). ErrorCodeAuthMissingCredential = "authMissingCredential" // ErrorCodeAuthInvalidToken: Bearer master-token mismatch (403). ErrorCodeAuthInvalidToken = "authInvalidToken" // ErrorCodeAuthIPBlocked: client IP not on the admin allowlist (403). ErrorCodeAuthIPBlocked = "authIpBlocked" )
Machine-readable errorCode values on auth-middleware rejections. Same convention as handler/admin/error_codes.go: stable camelCase, optional and additive — the human-readable "error" stays the display fallback, and the frontend keeps its load-bearing substring match ("invalid token") working. Registered in docs/api.md "errorCode convention and registry".
const ReauthConfirmHeader = "X-Admin-Confirm-Token"
ReauthConfirmHeader carries the master token for sensitive operations.
const SessionCookieName = "metapi_session"
SessionCookieName is the admin session cookie. HttpOnly + SameSite=Strict are always set; Secure follows cookieSecure().
const UserActivationTTL = 30 * time.Minute
const UserSessionCookieName = "metapi_user_session"
const UserSessionIdleTTL = 2 * time.Hour
const UserSessionTTL = 24 * time.Hour
Variables ¶
var EmptyDownstreamRoutingPolicy = DownstreamRoutingPolicy{ SupportedModels: []string{}, AllowedRouteIDs: []int64{}, SiteWeightMultipliers: map[int64]float64{}, ExcludedSiteIDs: []int64{}, ExcludedCredentialRefs: []ExcludedCredentialRef{}, AllowedSiteIDs: []int64{}, AllowedCredentialRefs: []ExcludedCredentialRef{}, }
EmptyDownstreamRoutingPolicy is the zero-value policy used as the default for administrator previews (DenyAllWhenEmpty=false → allow all).
var ErrGatewayUserAccessDenied = errors.New("gateway user access denied")
var ErrUserCredentials = errors.New("invalid user credentials")
var ErrUserPassword = errors.New("password must contain 12 to 72 bytes")
var GlobalKeyAdmission = NewKeyAdmissionLimiter()
GlobalKeyAdmission is the process-wide limiter used by ProxyAuth.
Functions ¶
func AdminAuth ¶
func AdminAuth(sessions *SessionManager) func(http.Handler) http.Handler
AdminAuth returns a chi-compatible middleware that enforces admin authentication using the given configuration. sessions may be nil (tests, DB-less boot): the cookie track then simply never authenticates and the Bearer track keeps working unchanged.
func AdminAuthFromRequest ¶
AdminAuthFromRequest is a convenience helper that stores the admin marker on the request context and returns the modified request.
func AdminRateLimit ¶
AdminRateLimit returns middleware that rate-limits every request by IP using a token bucket with the given sustained rate (req/s) and burst.
Intended for the /api/* route group (all admin endpoints).
func AuthRateLimit ¶ added in v0.16.19
AuthRateLimit returns middleware that rate-limits ONLY /api/auth/* requests by IP (#1034). Login is the single surface that accepts the master token, so it gets a strict bucket regardless of the general admin bucket size. All other paths pass through without consuming tokens.
Intended to be stacked alongside AdminRateLimit so auth endpoints are subject to both the general /api/ cap and this stricter cap.
func CheckDownstreamKeyIP ¶
Semantics (matches admin IP allowlist + New API token IP rules): - Blocklist wins: any match → deny ("ip_blocked"). - Allowlist non-empty: must match → else deny ("ip_not_allowed"). - Both empty: unrestricted → allow.
func ClearSessionCookie ¶ added in v0.16.19
func ClearSessionCookie(w http.ResponseWriter, r *http.Request, secureMode string)
ClearSessionCookie expires the session cookie. Same Path/SameSite/Secure attributes as issuance or the browser ignores the deletion.
func ClearUserSessionCookie ¶ added in v0.27.0
func ClearUserSessionCookie(w http.ResponseWriter, r *http.Request, secureMode string)
func ClientIP ¶ added in v0.26.0
ClientIP returns the normalized client IP used by downstream IP policies. Exported for session loops that authorize beyond the HTTP middleware (the Responses WebSocket transport has no per-message *http.Request), so both paths derive the IP identically.
func ConfigureSharedAdmissionFromRedisURL ¶
func ConfigureSharedAdmissionFromRedisURL(redisURL string)
ConfigureSharedAdmissionFromRedisURL enables Redis-backed RPM+TPM counting when url is non-empty. Both counters share one RedisCounter instance (distinct key namespaces). On parse/dial setup failure, logs and keeps memory-only. Runtime Redis errors fail open.
func DirectVideoTaskOwner ¶ added in v0.24.0
func DirectVideoTaskOwner(pac *ProxyAuthContext) string
DirectVideoTaskOwner stays stable across rotation of the same managed key.
func GetAdminSessionID ¶ added in v0.16.19
GetAdminSessionID returns the session actor id ("" when the request used the Bearer track or no auth at all).
func GetUserSession ¶ added in v0.27.0
func GetUserSession(ctx context.Context) *store.UserSession
func OAuthRateLimit ¶
OAuthRateLimit returns middleware that rate-limits ONLY /api/oauth/* requests by IP. All other paths pass through without consuming tokens.
Intended to be stacked after AdminRateLimit so OAuth endpoints are subject to both the general /api/ cap and this stricter cap.
func ProxyAuth ¶
On successful managed key auth, the middleware runs soft RPM/TPM admission first, then atomically increments used_requests via consumeManagedKeyRequest so a 429 over_rpm/over_tpm never burns max_requests.
func ProxyAuthFromRequest ¶
func ProxyAuthFromRequest(r *http.Request, pac *ProxyAuthContext) *http.Request
ProxyAuthFromRequest stores a ProxyAuthContext on the request context and returns the modified request.
func ProxyRateLimit ¶ added in v0.13.0
ProxyRateLimit returns middleware that enforces a per-IP RPM cap on /v1 proxy routes using a fixed-window counter. rpm<=0 disables the limiter (pass-through).
On limit exceedance it responds with 429 Too Many Requests, a JSON error body, Retry-After, and X-RateLimit-Limit/Remaining/Reset headers.
func ReauthConfirmed ¶ added in v0.26.0
ReauthConfirmed reports whether the request carries the current master token in the confirmation header. It is exported for handlers that gate a single field of an otherwise ordinary request (runtime settings).
func RecordManagedKeyCostUsage ¶
SQL: UPDATE downstream_api_keys SET used_cost = COALESCE(used_cost, 0) + ?, last_used_at = ?, updated_at = ? WHERE id = ?
func RecordManagedKeyQuotaUsage ¶ added in v0.24.0
RecordManagedKeyQuotaUsage records a completed billable attempt independently of proxy-log retention. Missing usage stays NULL so token quotas fail closed. The event ID is generated per completion: caller request IDs are untrusted and cannot be used to deduplicate billing.
When reservationID is non-empty the reservation is removed in the same transaction as the usage insert, so the admission sum never observes a gap between them. A missing reservation (crash cleanup, retry after a released hold) does not suppress the usage row: billing must not depend on admission bookkeeping.
func ReleaseManagedKeyQuotaReservation ¶ added in v0.26.0
func ReleaseManagedKeyQuotaReservation(reservationID string)
ReleaseManagedKeyQuotaReservation drops an admission hold that never reached a billable completion (early handler exit, rejected retry, client cancellation before any usage). It is idempotent and safe after settlement. A failed delete only leaves the hold for the TTL sweep, which over-counts the budget rather than granting it.
func RequireReauth ¶ added in v0.16.19
RequireReauth gates sensitive admin endpoints behind master-token re-confirmation. Non-sensitive paths pass through untouched. Rejection is a machine-readable 403 with reauthRequired=true so the UI can prompt for the token and replay the request once. Sensitive responses (success or rejection) are never cacheable.
func ResetKeyAdmissionForTest ¶
func ResetKeyAdmissionForTest()
ResetKeyAdmissionForTest clears the global limiter state.
func ResolveGatewayUser ¶ added in v0.27.0
func ResolveGatewayUser(ctx context.Context, users GatewayUserReader) (store.GatewayUser, error)
ResolveGatewayUser establishes the current ordinary-user scope. Resource queries still require this user's ID; this does not grant admin authority.
func SameOriginGuard ¶ added in v0.26.0
SameOriginGuard rejects state-changing requests whose declaring origin does not match the request host. allowedOrigins is an explicit list of extra origins (scheme://host[:port]) accepted for deployments that front the API with a different public host; comparison is exact on the serialized origin.
func SessionCookieFromRequest ¶ added in v0.16.19
SessionCookieFromRequest extracts the raw session credential from the request cookie, or "" when absent.
func SetSessionCookie ¶ added in v0.16.19
func SetSessionCookie(w http.ResponseWriter, r *http.Request, rawToken string, ttl time.Duration, secureMode string)
SetSessionCookie writes the session cookie. Max-Age mirrors the sliding TTL; the browser drops the cookie around the same time the server expires the row (the server remains authoritative either way).
func SetUserSessionCookie ¶ added in v0.27.0
func SetUserSessionCookie(w http.ResponseWriter, r *http.Request, raw, secureMode string)
func UserSameOriginGuard ¶ added in v0.27.0
Exact scheme+host+port comparison: an HTTP sibling origin is not HTTPS, even when its hostname matches. Forwarded protocol is trusted only through the existing trusted-proxy boundary. Headerless non-browser clients work.
func UserSessionAuth ¶ added in v0.27.0
func UserSessionAuth(m *UserSessionManager) func(http.Handler) http.Handler
func WithAdminAuth ¶
WithAdminAuth stores an admin auth marker in the context.
func WithAdminSessionID ¶ added in v0.16.19
WithAdminSessionID records the session hash prefix on the request context so the audit middleware can attribute cookie-authenticated writes.
func WithGatewayUserPrincipal ¶ added in v0.27.0
func WithGatewayUserPrincipal(ctx context.Context, principal GatewayUserPrincipal) context.Context
func WithProxyAuth ¶
func WithProxyAuth(ctx context.Context, pac *ProxyAuthContext) context.Context
WithProxyAuth stores a ProxyAuthContext in the context.
func WriteReauthRequired ¶ added in v0.26.0
func WriteReauthRequired(w http.ResponseWriter)
WriteReauthRequired emits the machine-readable rejection shared by the middleware and field-level gates.
Types ¶
type AdmissionDecision ¶
type AdmissionDecision struct {
Allowed bool
Reason string // "" | "over_rpm" | "over_tpm"
RetryAfter time.Duration
UsedRPM int64
UsedTPM int64
}
AdmissionDecision is the result of Allow.
type CredentialRefKind ¶
type CredentialRefKind string
CredentialRefKind distinguishes the two flavours of excluded credential references.
const ( CredentialRefAccountToken CredentialRefKind = "account_token" CredentialRefDefaultApiKey CredentialRefKind = "default_api_key" CredentialRefDirectGrant CredentialRefKind = "direct_grant" )
type DownstreamRoutingPolicy ¶
type DownstreamRoutingPolicy struct {
// nil is the legacy system-Key policy; non-nil is a hard outer-route
// boundary (including empty = deny all), independent of the legacy ORs.
UserRouteIDs *[]int64 `json:"userRouteIds,omitempty"`
AccessPolicy *store.DownstreamAccessPolicy `json:"accessPolicy,omitempty"`
SupportedModels []string `json:"supported_models"`
AllowedRouteIDs []int64 `json:"allowed_route_ids"`
SiteWeightMultipliers map[int64]float64 `json:"site_weight_multipliers"`
// KeyWeight multiplies channel.Weight in weighted selection. 0 = treat as 1.0.
KeyWeight float64 `json:"key_weight"`
ExcludedSiteIDs []int64 `json:"excluded_site_ids"`
ExcludedCredentialRefs []ExcludedCredentialRef `json:"excluded_credential_refs"`
// AllowedSiteIDs / AllowedCredentialRefs are optional allow-lists.
// Empty = unrestricted; non-empty = only listed sites/credentials eligible.
AllowedSiteIDs []int64 `json:"allowed_site_ids"`
AllowedCredentialRefs []ExcludedCredentialRef `json:"allowed_credential_refs"`
DenyAllWhenEmpty bool `json:"deny_all_when_empty"`
}
DownstreamRoutingPolicy holds the routing constraints attached to a downstream API key.
DenyAllWhenEmpty controls the default behaviour when both SupportedModels and AllowedRouteIDs are empty: - true (managed key default): reject all models - false (administrator preview): allow all models
type DownstreamTokenAuthResult ¶
type DownstreamTokenAuthResult struct {
OK bool
Source string // "managed" (when OK)
Token string // normalized token (when OK)
Key *managedKeyView // managed key view (when OK, source="managed")
Policy DownstreamRoutingPolicy // resolved policy (when OK)
StatusCode int // HTTP status (when !OK)
Error string // error message (when !OK)
Reason string // "missing"|"invalid"|"disabled"|"expired"|"over_cost"|"over_requests"|"over_rpm"|"over_tpm"
// QuotaReservationID is the admission hold created for an accessPolicy
// quota window. The completion path settles it; the caller releases it if
// the request ends without billable usage.
QuotaReservationID string
// contains filtered or unexported fields
}
DownstreamTokenAuthResult is the result of authorizing a downstream token. On success (OK=true): Source, Token, Key, and Policy are populated. On failure (OK=false): StatusCode, Error, and Reason are populated.
func AuthorizeDownstreamToken ¶
func AuthorizeDownstreamToken(token string, rt *config.RuntimeSettings) DownstreamTokenAuthResult
AuthorizeDownstreamToken validates a token against downstream_api_keys and enforces its enabled state, expiry and quota. Runtime root tokens are retired. It is the read-only admission variant: quota checks never create a hold.
func ReauthorizeManagedKeyForTurn ¶ added in v0.26.0
func ReauthorizeManagedKeyForTurn(ctx context.Context, token, clientIP string, estimatedTokens int64) DownstreamTokenAuthResult
ReauthorizeManagedKeyForTurn re-runs the managed-key admission chain for one unit of work inside an already established session (a Responses WebSocket message). Long-lived connections otherwise keep the handshake snapshot: a disabled/expired key, a tightened accessPolicy, or an exhausted max_cost/quota/max_requests budget would stay usable until disconnect.
The chain mirrors ProxyAuth exactly: reload by token (enabled, expiry, max_cost, max_requests, accessPolicy/quota), then IP rules, then RPM/TPM admission, then the atomic max_requests consume. A successful result therefore consumed exactly one request slot, reserved its quota slot, and carries the freshly loaded key + policy, which callers must use for the turn. A rejection after the quota reservation keeps the reservation ID so the caller can release it.
estimatedTokens is reserved against maxTPM; when maxTPM is set a minimum of one token is reserved so an unestimable message cannot skip TPM accounting.
type ExcludedCredentialRef ¶
type ExcludedCredentialRef struct {
Kind CredentialRefKind `json:"kind"`
SiteID int64 `json:"siteId"`
AccountID int64 `json:"accountId"`
TokenID *int64 `json:"tokenId,omitempty"` // only account_token
GrantID int64 `json:"grantId,omitempty"` // only direct_grant
}
ExcludedCredentialRef represents a credential that a downstream policy explicitly excludes from routing. The same shape is reused for allow-lists (AllowedCredentialRefs).
- account_token variant: references a specific account's specific token. - default_api_key variant: references a specific account's default API key (no TokenID).
JSON contract: the field tags below MUST match the shape persisted by the admin API into downstream_api_keys.excluded_credential_refs / allowed_credential_refs (camelCase: kind/siteId/accountId/tokenId — see handler/admin normalizeExcludedCredentialRefsInput). A tag mismatch decodes every ID as 0 and silently disables the dimension.
type GatewayUserPrincipal ¶ added in v0.27.0
type GatewayUserPrincipal struct{ UserID int64 }
GatewayUserPrincipal is set after user authentication. Group and enabled state are always loaded from current storage, never supplied by the client.
func GetGatewayUserPrincipal ¶ added in v0.27.0
func GetGatewayUserPrincipal(ctx context.Context) (GatewayUserPrincipal, bool)
type GatewayUserReader ¶ added in v0.27.0
type KeyAdmissionLimiter ¶
type KeyAdmissionLimiter struct {
// contains filtered or unexported fields
}
KeyAdmissionLimiter is an in-process sliding-window RPM/TPM gate for managed downstream keys. Default unlimited when limits are nil/<=0. Multi-instance deployments optionally share RPM/TPM via WindowCounter. Snapshot() remains process-local (known limitation).
Locking model:
- shards[keyID%admissionShards].mu guards the local window data and is only ever held for in-memory work (prune / check / append);
- keyWindow.sharedMu serializes the shared-counter round trips of one key, so an Incr and its compensating Decr can never be reordered by a concurrent request for the same key;
- nesting is always sharedMu -> shard mu, never the reverse (the shard lock is released before sharedMu is taken), so slow Redis I/O blocks neither another key nor a shard, and the two locks cannot deadlock.
func NewKeyAdmissionLimiter ¶
func NewKeyAdmissionLimiter() *KeyAdmissionLimiter
NewKeyAdmissionLimiter creates an empty limiter.
func (*KeyAdmissionLimiter) Allow ¶
func (l *KeyAdmissionLimiter) Allow(ctx context.Context, keyID int64, maxRPM, maxTPM *int64, estimatedTokens int64) AdmissionDecision
Allow checks and records a request against optional RPM/TPM limits. estimatedTokens is reserved against TPM when maxTPM is set; pass 0 to skip TPM accounting. When allowed, the request is recorded immediately (admission reservation).
ctx bounds the shared-counter round trips: a client that goes away cancels its own Redis wait instead of holding the per-key serialization mutex for the full counter timeout. Pass the request context (nil is treated as Background). A cancelled round trip is an error, so it takes the existing fail-open path — the request is already gone, and the window self-heals on expiry.
Shared-counter round trips never run under a shard lock, so a slow or unreachable Redis costs latency only for its own key. Decisions keep the exact order they had under the previous single lock: shared RPM -> local RPM fallback -> shared TPM -> local TPM fallback -> reservation.
func (*KeyAdmissionLimiter) SetSharedRPMCounter ¶
func (l *KeyAdmissionLimiter) SetSharedRPMCounter(c sharedcount.WindowCounter)
SetSharedRPMCounter wires an optional multi-instance window counter. Pass nil to clear (memory-only). Safe to call at process startup.
func (*KeyAdmissionLimiter) SetSharedTPMCounter ¶
func (l *KeyAdmissionLimiter) SetSharedTPMCounter(c sharedcount.WindowCounter)
SetSharedTPMCounter wires an optional multi-instance token counter. Pass nil to clear (memory-only). Safe to call at process startup. May reuse the same WindowCounter instance as SetSharedRPMCounter.
func (*KeyAdmissionLimiter) Snapshot ¶
func (l *KeyAdmissionLimiter) Snapshot(keyID int64) (usedRPM, usedTPM int64)
Snapshot returns current window usage for admin display.
type ManagedKeyAdmissionBlocker ¶ added in v0.24.0
type ManagedKeyAdmissionBlocker struct {
Dimension string `json:"dimension"` // policy|state|expiry|budget|quota|ip|rate
Code string `json:"code"`
Message string `json:"message"`
}
ManagedKeyAdmissionBlocker is one currently-blocking admission dimension. Code matches the live rejection reason of the real chain (snake_case), so a support answer can be traced to the exact production verdict.
type ManagedKeyAdmissionExplanation ¶ added in v0.24.0
type ManagedKeyAdmissionExplanation struct {
Verdict string `json:"verdict"` // allow|deny
Blockers []ManagedKeyAdmissionBlocker `json:"blockers"`
Notes []string `json:"notes"`
IP ManagedKeyIPCheck `json:"ip"`
// Windows are snapshots at evaluation time; they can change on the next
// real request. The rate window is process-local (see Notes).
Cost *ManagedKeyWindowUsage `json:"cost,omitempty"`
Requests *ManagedKeyWindowUsage `json:"requests,omitempty"`
Rate *ManagedKeyRateWindows `json:"rate,omitempty"`
Quota *ManagedKeyQuotaExplanation `json:"quota,omitempty"`
}
ManagedKeyAdmissionExplanation is the full read-only admission answer for one key: every dimension of the real chain evaluated, all current blockers listed (the live chain stops at the first), plus the window numbers behind each budget/quota/rate verdict.
type ManagedKeyContext ¶ added in v0.24.0
type ManagedKeyContext struct {
ID int64
Name string
Enabled bool
ExpiresAt *string
MaxCost *float64
UsedCost float64
MaxRequests *int64
UsedRequests int64
MaxRPM *int64
MaxTPM *int64
// AccessPolicyBlocked mirrors the live chain's first gate: invalid
// persisted JSON or an explicit blockReason. The two stay distinguishable.
AccessPolicyInvalid bool
AccessPolicyBlocked bool
HasQuotaPolicy bool
Policy DownstreamRoutingPolicy
// contains filtered or unexported fields
}
ManagedKeyContext is the read-only managed-key view plus its resolved routing policy (the same derivation the proxy path uses).
func LoadManagedKeyContextByID ¶ added in v0.24.0
func LoadManagedKeyContextByID(db *sqlx.DB, id int64) (*ManagedKeyContext, error)
LoadManagedKeyContextByID returns the read-only context for one managed key, or (nil, nil) when the ID does not exist. The explicit handle keeps the read on the caller's database (tests scope their own; production passes the shared one).
func (*ManagedKeyContext) ExplainAdmission ¶ added in v0.24.0
func (c *ManagedKeyContext) ExplainAdmission(clientIP string) ManagedKeyAdmissionExplanation
ExplainAdmission evaluates every admission dimension in the real chain's order and lists all current blockers. It is read-only by construction: no counter increment, no quota write, no lease, no upstream call.
type ManagedKeyIPCheck ¶ added in v0.24.0
type ManagedKeyIPCheck struct {
Checked bool `json:"checked"`
Allowed bool `json:"allowed"`
Reason string `json:"reason,omitempty"`
}
ManagedKeyIPCheck reports the IP dimension. Checked=false means no client IP was supplied, which is not the same as "allowed".
type ManagedKeyQuotaExplanation ¶ added in v0.24.0
type ManagedKeyQuotaExplanation struct {
WindowStart string `json:"windowStart"`
WindowEnd string `json:"windowEnd"`
RequestsUsed int64 `json:"requestsUsed"`
RequestsMax *int64 `json:"requestsMax,omitempty"`
TokensUsed int64 `json:"tokensUsed"`
TokensMax *int64 `json:"tokensMax,omitempty"`
CostUsed float64 `json:"costUsed"`
CostMax *float64 `json:"costMax,omitempty"`
UnknownTokens int64 `json:"unknownTokens"`
UnknownCost int64 `json:"unknownCost"`
HistoryMissing bool `json:"historyMissing"`
// Blocker is "" when the window currently permits the request; otherwise
// the live chain's reason: over_quota | quota_usage_unknown |
// quota_history_missing | quota_unavailable | access_policy.
Blocker string `json:"blocker"`
Message string `json:"message"`
}
ManagedKeyQuotaExplanation is the read-only quota-window answer for the key-context admission explainer: the same window math as the live gate, but it returns the numbers behind the verdict and records nothing.
func ExplainManagedKeyQuota ¶ added in v0.24.0
func ExplainManagedKeyQuota(db *sqlx.DB, id int64, quota *store.DownstreamQuota) ManagedKeyQuotaExplanation
ExplainManagedKeyQuota evaluates the quota window without recording usage. In-flight reservations count toward the used totals exactly as they do in the live gate, so the numbers describe the budget the next admission sees.
type ManagedKeyRateWindows ¶ added in v0.24.0
type ManagedKeyRateWindows struct {
RPM ManagedKeyWindowUsage `json:"rpm"`
TPM ManagedKeyWindowUsage `json:"tpm"`
Scope string `json:"scope"` // always "processLocal" today
}
ManagedKeyRateWindows carries the sliding-window RPM/TPM snapshot.
type ManagedKeyWindowUsage ¶ added in v0.24.0
ManagedKeyWindowUsage is one used/max pair; Max nil means unlimited.
type ProxyAuthContext ¶
type ProxyAuthContext struct {
OwnerUserID *int64
UserGroupID *int64
Token string // Normalized token string
Source string // "managed" for authenticated requests
KeyID *int64 // Managed key row ID
KeyName string // Managed key name
Policy DownstreamRoutingPolicy // Resolved routing policy
// ProxyURL is an optional per-key egress proxy override from
// downstream_api_keys.proxy_url.
// nil/empty means inherit account → site → system proxy.
// When set, it takes precedence over site/account proxy for that key's
// upstream requests (product intent: multi-tenant key isolation).
ProxyURL *string
// QuotaReservationID is the accessPolicy quota hold created at admission.
// The completion path deletes it together with the usage insert; the
// admission middleware releases it when no billable attempt completes.
QuotaReservationID string
}
ProxyAuthContext holds the result of a successful downstream token authorization. It is stored in the request context by ProxyAuth middleware.
func GetProxyAuth ¶
func GetProxyAuth(ctx context.Context) *ProxyAuthContext
GetProxyAuth retrieves the ProxyAuthContext from the context. Returns nil if not present.
type ProxyResourceOwner ¶
type ProxyResourceOwner struct {
OwnerType string // "managed_key"; historical records may use "global_proxy_token"
OwnerID string // managed key ID, or historical owner reference
}
ProxyResourceOwner identifies the downstream principal that owns a proxy resource (log entry, file, etc.).
func GetProxyResourceOwner ¶
func GetProxyResourceOwner(auth *ProxyAuthContext) *ProxyResourceOwner
GetProxyResourceOwner derives a ProxyResourceOwner from a ProxyAuthContext. Returns nil if auth is nil.
type Session ¶ added in v0.16.19
type Session struct {
// TokenHash is the SHA-256 hex of the session credential; the raw
// credential never exists server-side after issuance. Doubles as the
// stable, non-reversible audit actor id.
TokenHash string
CreatedAt time.Time
LastSeenAt time.Time
ExpiresAt time.Time
ClientIP string
UserAgent string
}
Session is one admin_sessions row (timestamps parsed to time.Time).
type SessionManager ¶ added in v0.16.19
type SessionManager struct {
// contains filtered or unexported fields
}
SessionManager owns server-side admin session lifecycle (create / validate / revoke) plus one-time WebSocket tickets. A nil *SessionManager is valid and fails closed (no sessions, no tickets) so tests and DB-less boots keep working without special casing.
func NewSessionManager ¶ added in v0.16.19
func NewSessionManager(db *store.DB, ttl time.Duration) *SessionManager
NewSessionManager builds a session manager over the store. db == nil returns nil (callers must treat a nil manager as "sessions unavailable"). ttl <= 0 falls back to 12h so a misconfig can never mint eternal sessions.
func (*SessionManager) ConsumeWSTicket ¶ added in v0.16.19
func (sm *SessionManager) ConsumeWSTicket(ticket string) bool
ConsumeWSTicket redeems a ticket exactly once. Unknown, expired, or already-consumed tickets return false.
func (*SessionManager) Count ¶ added in v0.16.19
func (sm *SessionManager) Count(ctx context.Context) int
Count returns the number of live (unexpired) sessions; used by tests and future diagnostics surfaces.
func (*SessionManager) Create ¶ added in v0.16.19
func (sm *SessionManager) Create(ctx context.Context, clientIP, userAgent string) (string, *Session, error)
Create issues a new session and returns the raw cookie credential (shown to the client exactly once, inside Set-Cookie). Expired rows are purged on the same statement budget (lazy GC, see package doc).
func (*SessionManager) IssueWSTicket ¶ added in v0.16.19
func (sm *SessionManager) IssueWSTicket() (string, time.Duration)
IssueWSTicket mints a one-time ticket for the realtime ops WebSocket.
func (*SessionManager) Revoke ¶ added in v0.16.19
func (sm *SessionManager) Revoke(ctx context.Context, rawToken string)
Revoke deletes the session behind a raw cookie credential (logout). Unknown tokens are a no-op so logout stays idempotent.
func (*SessionManager) RevokeAll ¶ added in v0.16.19
func (sm *SessionManager) RevokeAll(ctx context.Context)
RevokeAll invalidates every session (master token rotation). Sessions minted from the old token must not survive the rotation.
func (*SessionManager) TTL ¶ added in v0.16.19
func (sm *SessionManager) TTL() time.Duration
TTL returns the sliding session lifetime.
func (*SessionManager) Validate ¶ added in v0.16.19
func (sm *SessionManager) Validate(ctx context.Context, rawToken string) *Session
Validate resolves a raw cookie credential to a live session. Expired or unknown credentials return nil (the caller answers 401). A live session is slid forward (last_seen_at + expires_at) on every validation — admin traffic is rate-limited, so the per-request UPDATE is cheap enough and keeps the semantics trivial.
type UserSessionManager ¶ added in v0.27.0
type UserSessionManager struct {
// contains filtered or unexported fields
}
UserSessionManager has no administrator capabilities. Random credentials carry 256 bits; only their SHA-256 digests persist. Passwords use bcrypt12.
func NewUserSessionManager ¶ added in v0.27.0
func NewUserSessionManager(db *store.DB) *UserSessionManager
func (*UserSessionManager) Activate ¶ added in v0.27.0
func (m *UserSessionManager) Activate(ctx context.Context, username, code, password string) error
func (*UserSessionManager) AllowAccount ¶ added in v0.27.0
func (m *UserSessionManager) AllowAccount(username string) bool
AllowAccount bounds slow-hash work per canonical username as well as the router's per-IP bucket. Unknown names follow the same bucket and response.
func (*UserSessionManager) ChangePassword ¶ added in v0.27.0
func (*UserSessionManager) IssueActivation ¶ added in v0.27.0
func (*UserSessionManager) Login ¶ added in v0.27.0
func (m *UserSessionManager) Login(ctx context.Context, username, password string) (string, *store.UserSession, error)