Documentation
¶
Overview ¶
Package auth provides admin and downstream proxy authentication middleware with IP allowlisting and rate limiting.
Index ¶
- Variables
- func AdminAuth(cfg *config.Config) func(http.Handler) http.Handler
- func AdminAuthFromRequest(r *http.Request) *http.Request
- func AdminRateLimit(rps, burst int) func(http.Handler) http.Handler
- func CheckDownstreamKeyIP(key *managedKeyView, clientIP string) (bool, string)
- func ConfigureSharedAdmissionFromRedisURL(redisURL string)
- func ConsumeManagedKeyRequest(keyID int64) bool
- func IsAdmin(ctx context.Context) bool
- func OAuthRateLimit(rps, burst int) func(http.Handler) http.Handler
- func ProxyAuth(cfg *config.Config) func(http.Handler) http.Handler
- func ProxyAuthFromRequest(r *http.Request, pac *ProxyAuthContext) *http.Request
- func RecordManagedKeyCostUsage(keyID int64, estimatedCost float64)
- func ResetKeyAdmissionForTest()
- func WithAdminAuth(ctx context.Context) context.Context
- func WithProxyAuth(ctx context.Context, pac *ProxyAuthContext) context.Context
- type AdmissionDecision
- type CredentialRefKind
- type DownstreamRoutingPolicy
- type DownstreamTokenAuthResult
- type ExcludedCredentialRef
- type KeyAdmissionLimiter
- func (l *KeyAdmissionLimiter) Allow(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 ProxyAuthContext
- type ProxyResourceOwner
Constants ¶
This section is empty.
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 the global proxy token (DenyAllWhenEmpty=false → allow all).
var GlobalKeyAdmission = NewKeyAdmissionLimiter()
GlobalKeyAdmission is the process-wide limiter used by ProxyAuth.
Functions ¶
func AdminAuth ¶
AdminAuth returns a chi-compatible middleware that enforces admin authentication using the given configuration.
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 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 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 ConsumeManagedKeyRequest ¶
ConsumeManagedKeyRequest atomically reserves one request for a managed key. Used by Responses WebSocket multi-turn billing (WS C2) so each client message is counted once without re-running ProxyAuth middleware on the HTTP bridge. Returns false when the key no longer exists or has reached max_requests.
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 RecordManagedKeyCostUsage ¶
SQL: UPDATE downstream_api_keys SET used_cost = COALESCE(used_cost, 0) + ?, last_used_at = ?, updated_at = ? WHERE id = ?
func ResetKeyAdmissionForTest ¶
func ResetKeyAdmissionForTest()
ResetKeyAdmissionForTest clears the global limiter state.
func WithAdminAuth ¶
WithAdminAuth stores an admin auth marker in the context.
func WithProxyAuth ¶
func WithProxyAuth(ctx context.Context, pac *ProxyAuthContext) context.Context
WithProxyAuth stores a ProxyAuthContext in the context.
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" )
type DownstreamRoutingPolicy ¶
type DownstreamRoutingPolicy struct {
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 (managed) or the global proxy token.
DenyAllWhenEmpty controls the default behaviour when both SupportedModels and AllowedRouteIDs are empty: - true (managed key default): reject all models - false (global token default): allow all models
type DownstreamTokenAuthResult ¶
type DownstreamTokenAuthResult struct {
OK bool
Source string // "managed" | "global" (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"
}
DownstreamTokenAuthResult is the result of authorizing a downstream token. On success (OK=true): Source, Token, Key (maybe nil for global), and Policy are populated. On failure (OK=false): StatusCode, Error, and Reason are populated.
func AuthorizeDownstreamToken ¶
func AuthorizeDownstreamToken(token string, cfg *config.Config) DownstreamTokenAuthResult
Flow (matches TS authorizeDownstreamToken exactly): 1. If token is empty → 401, reason: "missing" 2. Query downstream_api_keys WHERE key = token: a. Found → check enabled/expired/over_cost/over_requests → return managed result b. Not found → continue 3. Check if token == config.ProxyToken: a. Match → return global result b. No match → 403, reason: "invalid"
type ExcludedCredentialRef ¶
type ExcludedCredentialRef struct {
Kind CredentialRefKind `json:"kind"`
SiteID int64 `json:"site_id"`
AccountID int64 `json:"account_id"`
TokenID *int64 `json:"token_id,omitempty"` // only account_token
}
ExcludedCredentialRef represents a credential that a downstream policy explicitly excludes from routing.
- account_token variant: excludes a specific account's specific token. - default_api_key variant: excludes a specific account's default API key (no TokenID).
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).
func NewKeyAdmissionLimiter ¶
func NewKeyAdmissionLimiter() *KeyAdmissionLimiter
NewKeyAdmissionLimiter creates an empty limiter.
func (*KeyAdmissionLimiter) Allow ¶
func (l *KeyAdmissionLimiter) Allow(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).
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 ProxyAuthContext ¶
type ProxyAuthContext struct {
Token string // Normalized token string
Source string // "managed" | "global"
KeyID *int64 // Managed key row ID; nil for global
KeyName string // Managed key name; "global" for global
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
}
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" | "global_proxy_token"
OwnerID string // managed_key: String(keyID) or token fallback; global: "global"
}
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.