Documentation
¶
Overview ¶
Package auth issues and validates API keys, decides what each key type may do, and carries the authenticated principal (tenant, key, user and key type) in the request context.
Index ¶
- Constants
- Variables
- func CustomerActorID(ctx context.Context) string
- func HasPermission(keyType KeyType, perm Permission) bool
- func KeyID(ctx context.Context) string
- func KeyPrefix(kt KeyType, livemode bool) string
- func Middleware(svc *Service) func(http.Handler) http.Handler
- func Require(perm Permission) func(http.Handler) http.Handler
- func RequireMethod(read, write Permission) func(http.Handler) http.Handler
- func RequireSession(task string) func(http.Handler) http.Handler
- func TenantID(ctx context.Context) string
- func UserID(ctx context.Context) string
- func WithCustomerActor(ctx context.Context, customerID string) context.Context
- func WithKeyID(ctx context.Context, id string) context.Context
- func WithKeyType(ctx context.Context, kt KeyType) context.Context
- func WithTenantID(ctx context.Context, tenantID string) context.Context
- func WithUserID(ctx context.Context, id string) context.Context
- type AuditWriter
- type CreateKeyInput
- type CreateKeyResult
- type Handler
- type KeyType
- type ListFilter
- type Permission
- type PostgresStore
- func (s *PostgresStore) Create(ctx context.Context, key domain.APIKey) (domain.APIKey, error)
- func (s *PostgresStore) Get(ctx context.Context, tenantID, id string) (domain.APIKey, error)
- func (s *PostgresStore) GetByPrefix(ctx context.Context, prefix string) (domain.APIKey, error)
- func (s *PostgresStore) List(ctx context.Context, filter ListFilter) ([]domain.APIKey, int, error)
- func (s *PostgresStore) Revoke(ctx context.Context, tenantID, id string) (domain.APIKey, error)
- func (s *PostgresStore) ScheduleExpiry(ctx context.Context, tenantID, id string, expiresAt time.Time) (domain.APIKey, error)
- func (s *PostgresStore) TouchLastUsed(ctx context.Context, id string, usedAt time.Time) error
- type RotateKeyInput
- type RotateKeyResult
- type Service
- func (s *Service) CreateKey(ctx context.Context, tenantID string, input CreateKeyInput) (CreateKeyResult, error)
- func (s *Service) ListKeys(ctx context.Context, filter ListFilter) ([]domain.APIKey, int, error)
- func (s *Service) RevokeKey(ctx context.Context, tenantID, id string) (domain.APIKey, error)
- func (s *Service) RotateKey(ctx context.Context, tenantID, id string, input RotateKeyInput) (RotateKeyResult, error)
- func (s *Service) ValidateKey(ctx context.Context, rawKey string) (domain.APIKey, error)
- type Store
Constants ¶
const MaxRotationGraceSeconds = 7 * 24 * 60 * 60
MaxRotationGraceSeconds caps how long a caller can keep the old key alive during a rotation. Seven days matches the longest grace window Stripe offers in its dashboard "roll key" flow. It is long enough for a scheduled deploy cycle, and short enough that a forgotten rotation still ends on its own.
Variables ¶
var ErrInvalidKey = errors.New("invalid api key")
ErrInvalidKey marks a definitive credential rejection: a bad format, no matching key, a hash mismatch or an expired key. Middlewares map it, and only it, to the generic 401. Any other ValidateKey error means no verdict was reached (a store or database failure), and it must surface as a retryable 5xx. During a database outage, a 401 would tell every integrator that their key went bad and to start rotating credentials, which is false about the key (#560). A 503 for every caller reveals nothing about any one key, so ADR-026's rule against key enumeration holds.
var StoredKeyTypes = []KeyType{KeyTypeSecret, KeyTypeIngest}
StoredKeyTypes are the key types api_keys holds: the values api_keys_key_type_check allows. CreateKey issues only these, and ValidateKey reads only their prefixes.
Functions ¶
func CustomerActorID ¶
CustomerActorID returns the customer ID that a portal-session middleware stamped into ctx, or "" when the request is not customer-authenticated. audit.Logger reads it to tag rows with actor_type='customer' when the request came from the customer-portal surface. The operator Activity feed then shows "by customer" instead of the misleading 'system' fallback.
func HasPermission ¶
func HasPermission(keyType KeyType, perm Permission) bool
HasPermission reports whether keyType holds perm. An unknown key type holds no permission.
func KeyID ¶
KeyID returns the ID of the API key that authenticated the request, or "" when no key did.
func KeyPrefix ¶
KeyPrefix returns the full "hc_{type}_{mode}_" prefix used on new keys, in Stripe's style: hc_secret_live_..., hc_secret_test_... and so on. The visible mode infix lets an operator spot a test key in a production config without decoding the key.
func Middleware ¶
Middleware validates the request's API key and puts its tenant context on the request.
func Require ¶
func Require(perm Permission) func(http.Handler) http.Handler
Require returns middleware that checks that the authenticated key has a specific permission. Use it to protect individual route groups.
func RequireMethod ¶
func RequireMethod(read, write Permission) func(http.Handler) http.Handler
RequireMethod returns middleware that picks the permission to enforce from the HTTP method. GET, HEAD and OPTIONS check `read`, and POST, PUT, PATCH and DELETE check `write`. RequireMethod closes a gap: a single Require in front of a chi.Mount applies one permission to a subrouter that mixes reads and writes. Without RequireMethod, a key with read access could write on every endpoint in the subtree.
Usage:
r.With(auth.RequireMethod(auth.PermCustomerRead, auth.PermCustomerWrite)).
Mount("/customers", customerH.Routes())
func RequireSession ¶
RequireSession gates a route or subtree to dashboard-session principals only. Use it for a human act (team membership), where an API key has no user to attribute the action to, and for settings both modes share, which a key, made in one mode, must not change. Any other principal gets a 403 that ends "sign in to the dashboard to <task>".
func UserID ¶
UserID returns the dashboard user id resolved from the cookie session, or "" if the request is on the Bearer (API-key) path. Audit log entries use UserID for cookie-authed requests and KeyID for Bearer-authed requests as the actor identifier.
func WithCustomerActor ¶
WithCustomerActor stamps a customer ID as the request's actor, so downstream services (chiefly the audit logger) record who acted.
It is in use and needed, so do not remove it as unused. It is the one mechanism that attributes an action to a customer rather than to "system", and the whole of ADR-090's customer-actor story. The hosted-invoice Pay click (hostedinvoice/handler.go) and the payment-update link (payment/public_handler.go) both stamp it. audit.ResolveActor reads it to write actor_type='customer'.
func WithKeyID ¶
WithKeyID is the setter counterpart to KeyID. Adapters outside the auth package that resolve a credential to a key context themselves call it (currently `internal/session`).
func WithKeyType ¶
WithKeyType lets adapters declare the principal type, so auth.Require keeps working from a single ctx key. `internal/session` calls it when a session resolves to its parent key's type.
func WithTenantID ¶
WithTenantID returns a derived context carrying tenantID. Middleware sets the same key with its own WithValue call. Background workers (the reconciler, the billing engine's charge loop) call WithTenantID to set the tenant before they call clients backed by the Stripe resolver, so the tenant's own credentials can be looked up.
Types ¶
type AuditWriter ¶
type AuditWriter interface {
Log(ctx context.Context, tenantID, action, resourceType, resourceID, resourceLabel string, metadata map[string]any) error
}
AuditWriter is the narrow audit surface the auth handler uses. It is declared here so the package does not depend on internal/audit and can be tested with a fake. Production wires *audit.Logger with SetAuditLogger in internal/api/router.go.
type CreateKeyInput ¶
type CreateKeyInput struct {
Name string `json:"name"`
KeyType KeyType `json:"key_type"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
}
CreateKeyInput is the request to create a key. An empty KeyType means a secret key.
type CreateKeyResult ¶
CreateKeyResult contains the key record and the raw key, which is shown once.
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler serves the API key routes.
func NewHandler ¶
NewHandler returns a Handler for the keys that svc manages.
func (*Handler) Routes ¶
Routes returns the key routes: POST / creates a key, GET / lists keys, DELETE /{id} revokes one and POST /{id}/rotate rotates one.
func (*Handler) SetAuditLogger ¶
func (h *Handler) SetAuditLogger(a AuditWriter)
SetAuditLogger wires the audit logger, so creating, revoking and rotating an API key writes an audit_log row. Without it, these security-critical key changes do not appear on the operator's Audit Log page, which blocks SOC 2 compliance and forensic work.
type KeyType ¶
type KeyType string
KeyType determines the prefix and permission set for an API key.
func GetKeyType ¶
GetKeyType returns the principal's key type in ctx, or "" when there is none.
func (KeyType) TypePrefix ¶
TypePrefix returns the type-only prefix (e.g. "hc_secret_"). Used when parsing a raw key to identify its type before the mode infix. A type that is never stored (a session) has no prefix, so it returns "".
type ListFilter ¶
ListFilter selects a page of a tenant's keys.
type Permission ¶
type Permission string
Permission represents a specific API operation scope.
const ( PermCustomerRead Permission = "customer:read" PermCustomerWrite Permission = "customer:write" PermPricingRead Permission = "pricing:read" PermPricingWrite Permission = "pricing:write" PermSubscriptionRead Permission = "subscription:read" PermSubscriptionWrite Permission = "subscription:write" PermUsageRead Permission = "usage:read" PermUsageWrite Permission = "usage:write" // PermUsageIngest sends usage events: POST /v1/usage-events, its // /batch, and the LiteLLM callback. It is the only permission an // ingest key holds (ADR-133). Backfill and the held-usage release and // discard need PermUsageWrite. PermUsageIngest Permission = "usage:ingest" PermInvoiceRead Permission = "invoice:read" PermInvoiceWrite Permission = "invoice:write" PermDunningRead Permission = "dunning:read" PermDunningWrite Permission = "dunning:write" PermAPIKeyRead Permission = "apikey:read" PermAPIKeyWrite Permission = "apikey:write" // PermTestClockWrite grants create / advance / delete on test_clocks. // Secret keys and dashboard sessions hold it; ingest keys do not. PermTestClockWrite Permission = "testclock:write" )
type PostgresStore ¶
type PostgresStore struct {
// contains filtered or unexported fields
}
PostgresStore is the Store on the api_keys table.
func NewPostgresStore ¶
func NewPostgresStore(db *postgres.DB) *PostgresStore
NewPostgresStore returns a PostgresStore on db.
func (*PostgresStore) Create ¶
Create inserts key in its own transaction, scoped to key.TenantID, and returns the stored row.
func (*PostgresStore) GetByPrefix ¶
GetByPrefix returns the key that is not revoked and has the given lookup prefix, with its hash and salt, or errs.ErrNotFound.
func (*PostgresStore) List ¶
func (s *PostgresStore) List(ctx context.Context, filter ListFilter) ([]domain.APIKey, int, error)
List returns one page of the tenant's API keys, newest first, and how many keys match.
func (*PostgresStore) Revoke ¶
Revoke sets revoked_at on the target key. It is idempotent: revoking an already-revoked or expired key returns ErrNotFound, because the UPDATE matches zero rows. The caller decides how to report that.
Revoking the tenant's last key is allowed. The operator signs in with email and password (ADR-011), so revoking every API key does not lock the tenant out: the operator can still sign in and create new keys.
func (*PostgresStore) ScheduleExpiry ¶
func (s *PostgresStore) ScheduleExpiry(ctx context.Context, tenantID, id string, expiresAt time.Time) (domain.APIKey, error)
ScheduleExpiry sets expires_at on a key that is not revoked, and returns the updated row or errs.ErrNotFound.
func (*PostgresStore) TouchLastUsed ¶
TouchLastUsed sets the key's last_used_at to usedAt.
type RotateKeyInput ¶
type RotateKeyInput struct {
ExpiresInSeconds int64 `json:"expires_in_seconds,omitempty"`
}
RotateKeyInput sets how a rotation treats the old key. ExpiresInSeconds=0 revokes the old key at once. A positive value keeps it valid for that many seconds past now, which gives deployed clients time to swap credentials without a hard cutover.
type RotateKeyResult ¶
type RotateKeyResult struct {
OldKey domain.APIKey `json:"old_key"`
NewKey domain.APIKey `json:"new_key"`
RawKey string `json:"raw_key"`
}
RotateKeyResult returns both sides of a rotation. RawKey is the new key's plaintext. It is shown once, and never stored or returned on a later fetch. OldKey's ExpiresAt (a grace window) or RevokedAt (immediate) shows which path the caller took.
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service creates, validates, rotates and revokes API keys.
func NewService ¶
NewService returns a Service backed by store.
func (*Service) CreateKey ¶
func (s *Service) CreateKey(ctx context.Context, tenantID string, input CreateKeyInput) (CreateKeyResult, error)
CreateKey mints a key for tenantID, in the mode that ctx carries, and returns it with its raw value. It refuses an empty name, a key type other than secret or ingest, and an expires_at that is not in the future.
func (*Service) ListKeys ¶
ListKeys returns one page of the keys that filter selects, and how many match.
func (*Service) RotateKey ¶
func (s *Service) RotateKey(ctx context.Context, tenantID, id string, input RotateKeyInput) (RotateKeyResult, error)
RotateKey issues a replacement for key `id`, keeping its name, type, livemode and any configured expires_at. The old key is revoked at once (grace 0), or scheduled to expire after input.ExpiresInSeconds seconds. A caller picks a non-zero grace to deploy with no downtime, at the cost of a slightly wider blast radius.
func (*Service) ValidateKey ¶
ValidateKey looks up a key by its prefix, verifies the hash and checks expiry.
It accepts three prefix forms, in priority order:
- "hc_{type}_live_..."
- "hc_{type}_test_..."
- "hc_{type}_..." (the older form with no mode, treated as live)
Form 3 keeps keys issued before the mode infix working. Newly issued keys always use form 1 or 2.
type Store ¶
type Store interface {
Create(ctx context.Context, key domain.APIKey) (domain.APIKey, error)
Get(ctx context.Context, tenantID, id string) (domain.APIKey, error)
GetByPrefix(ctx context.Context, prefix string) (domain.APIKey, error)
Revoke(ctx context.Context, tenantID, id string) (domain.APIKey, error)
// ScheduleExpiry sets expires_at on a key that is not revoked, without
// revoking it. Rotation uses it when a grace period is requested.
// ValidateKey rejects expired keys the same way it rejects revoked ones.
// But with revoked_at unset, GetByPrefix still finds the key through the
// grace window, so requests in flight can still authenticate.
ScheduleExpiry(ctx context.Context, tenantID, id string, expiresAt time.Time) (domain.APIKey, error)
// List returns one page of the keys and how many match.
List(ctx context.Context, filter ListFilter) ([]domain.APIKey, int, error)
TouchLastUsed(ctx context.Context, id string, usedAt time.Time) error
}
Store is the persistence interface for API keys.