Documentation
¶
Overview ¶
Package auth issues API keys and decides who may do what. Service manages the keys, and Handler serves their routes. Caller is who a request acts as, a dashboard session or a key, and RequirePermission refuses a caller what its route does not let it do.
Index ¶
- Variables
- func CustomerActorID(ctx context.Context) string
- func RequirePermission(table AccessTable, unrouted http.Handler) func(http.Handler) http.Handler
- func TenantID(ctx context.Context) string
- func WithCaller(ctx context.Context, c Caller) context.Context
- func WithCustomerActor(ctx context.Context, customerID string) context.Context
- func WithTenantID(ctx context.Context, tenantID string) context.Context
- func WithUserID(ctx context.Context, id string) context.Context
- type Access
- type AccessTable
- type AuditWriter
- type Caller
- type CreateKeyInput
- type CreateKeyResult
- type Handler
- type KeyType
- type ListFilter
- type Permission
- type PermissionRequired
- type RotateKeyInput
- type RotateKeyResult
- type Service
- func (s *Service) CreateKey(ctx context.Context, tenantID string, input CreateKeyInput) (CreateKeyResult, error)
- func (s *Service) CreateKeyTx(ctx context.Context, tx *sql.Tx, 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)
Constants ¶
This section is empty.
Variables ¶
var ErrInvalidKey = errors.New("invalid api key")
ErrInvalidKey is ValidateKey's verdict that a string is not a usable key: the only ValidateKey error that may answer 401. Any other is a store failure that says nothing about the key (ADR-026).
Functions ¶
func CustomerActorID ¶
CustomerActorID returns the customer WithCustomerActor put on ctx, or "" when none.
func RequirePermission ¶ added in v0.10.0
RequirePermission returns middleware that answers 403 unless the caller has the Access the request's route needs, and 500 for a route whose Access names no caller. unrouted answers a request no route serves (its 404 or 405), so the next handler runs only for a route the table lists and the caller may call.
func WithCaller ¶ added in v0.10.0
WithCaller returns ctx with c as its whole caller, replacing any caller ctx held. session.Authenticate sets it for each authenticated request.
func WithCustomerActor ¶
WithCustomerActor returns ctx with customerID as the actor, for work a customer did: on a public page, or in the Stripe event such a page caused. audit.ResolveActor then names the customer (actor_type 'customer') ahead of any caller.
func WithTenantID ¶
WithTenantID returns ctx with tenantID as the caller's tenant; the rest of the caller is kept. A background job, or a public route that finds the tenant itself, sets it before calling code that needs the tenant, such as the per-tenant Stripe client.
func WithUserID ¶
WithUserID returns ctx with id as the caller's user. The account routes outside authentication (route_table.go's outsideAuth entries) set it, so their audit row names the user. Each calls it on a context with no caller, so the result is that user's session (IsSession).
Types ¶
type Access ¶ added in v0.10.0
type Access struct {
Perm Permission
Session string
Any bool
}
Access is who may call a route: a caller holding Perm, only a dashboard session (Session is the task its 403 names), or any caller (Any). The zero Access names no caller: a fault in the table, answered 500.
type AccessTable ¶ added in v0.10.0
AccessTable gives the Access of a request's route, and false for a request no route serves.
type AuditWriter ¶
type AuditWriter interface {
LogInTxFields(ctx context.Context, tx *sql.Tx, action, resourceType, resourceID, resourceLabel string, metadata map[string]any) error
}
AuditWriter writes an audit row on the caller's transaction, so the change and its row commit or roll back together. *audit.Logger implements it; auth cannot import audit, which imports auth.
type Caller ¶ added in v0.10.0
type Caller struct {
TenantID string
UserID string // set for a session
KeyID string // set for a key
KeyType KeyType // the key's type; "" for a session
}
Caller is who a request acts as: a dashboard user's session, or an API key. Never both a UserID and a KeyID: session.Authenticate sets one or the other. WithUserID names a user only on the account routes (sign-in and sign-out, the mode switch, invitations, password reset), where authentication does not run and there is no caller yet. A background job, a webhook or a public page carries only a tenant (WithTenantID), or no caller.
func CallerOf ¶ added in v0.10.0
CallerOf returns the caller in ctx, or the zero Caller when there is none.
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 is a new key and its raw value. No later answer can show the raw value: the table holds only its hash, and the routes that answer with it are withShowOnce (internal/api/route_table.go), so the idempotency layer keeps no copy.
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.
type KeyType ¶
type KeyType string
KeyType is an API key's type, which sets the key's permissions (hasPermission).
type ListFilter ¶
ListFilter selects a page of a tenant's keys.
type Permission ¶
type Permission string
Permission is what a route requires of its caller (RequirePermission).
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 Permission = "usage:ingest" PermInvoiceRead Permission = "invoice:read" PermInvoiceWrite Permission = "invoice:write" PermDunningRead Permission = "dunning:read" PermDunningWrite Permission = "dunning:write" // apikey:read and apikey:write gate more than API keys: the access values // in internal/api/route_table.go say what each guards. PermAPIKeyRead Permission = "apikey:read" PermAPIKeyWrite Permission = "apikey:write" )
func (Permission) Writes ¶ added in v0.11.0
func (p Permission) Writes() bool
Writes reports whether p is a write permission: one that lets its holder change an account's data. usage:ingest is not one; it sends usage and reads a customer's live credit balance.
type PermissionRequired ¶ added in v0.10.0
type PermissionRequired struct {
// contains filtered or unexported fields
}
PermissionRequired checks the route's Access. RequirePermission makes it; its doc has the rule.
func (PermissionRequired) ServeHTTP ¶ added in v0.10.0
func (c PermissionRequired) ServeHTTP(w http.ResponseWriter, r *http.Request)
type RotateKeyInput ¶
type RotateKeyInput struct {
ExpiresInSeconds int64 `json:"expires_in_seconds,omitempty"`
}
RotateKeyInput is the request to rotate a key. ExpiresInSeconds is the old key's grace (RotateKey).
type RotateKeyResult ¶
type RotateKeyResult struct {
OldKey domain.APIKey `json:"old_key"`
NewKey domain.APIKey `json:"new_key"`
RawKey string `json:"raw_key"`
}
RotateKeyResult is the old key as it now stands, the new key, and the new key's raw value.
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service creates, lists, validates, rotates and revokes API keys. A change to a key (create, revoke, rotate) and its audit row commit in one transaction, or neither does.
func NewService ¶
func NewService(db *postgres.DB, audit AuditWriter) *Service
NewService returns a Service on db that writes each key change's audit row with audit. It panics on a nil audit: a key change with no audit row would be invisible on the operator's Audit Log page.
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. checkCreateInput says what it refuses.
func (*Service) CreateKeyTx ¶ added in v0.10.0
func (s *Service) CreateKeyTx(ctx context.Context, tx *sql.Tx, tenantID string, input CreateKeyInput) (CreateKeyResult, error)
CreateKeyTx is CreateKey on the caller's transaction, for account setup (tenant.RunBootstrap). The caller gives the mode twice:
- tx has app.tenant_id set to tenantID and app.livemode set: the row and its audit row take their mode from tx;
- ctx carries the same mode (postgres.WithLivemode): the key's prefix takes it from ctx.
api_keys_prefix_shape_check refuses a key where the two differ.
func (*Service) ListKeys ¶
ListKeys returns one page of filter's keys in the mode ctx carries, newest first, and how many keys there are.
func (*Service) RevokeKey ¶
RevokeKey revokes the tenant's key with id, in the mode ctx carries, and returns the revoked key. A key that is not found, or already revoked, returns errs.ErrNotFound. A caller may revoke the key it calls with, and the last key: an operator can still sign in and make a new one (ADR-011).
func (*Service) RotateKey ¶
func (s *Service) RotateKey(ctx context.Context, tenantID, id string, input RotateKeyInput) (RotateKeyResult, error)
RotateKey replaces the tenant's key with id, in the mode ctx carries, with a new key of the same name, type, mode and expires_at. A grace of 0 revokes the old key; a grace of up to maxRotationGrace sets it to expire that many seconds from now, or at its own expires_at if that is sooner (scheduleExpiry, in postgres.go, does it in SQL). A grace out of range returns a validation error, a key not found errs.ErrNotFound, and a key that is not active errs.ErrInvalidState.
func (*Service) ValidateKey ¶
ValidateKey returns the active key rawKey is. It returns ErrInvalidKey when rawKey does not have a key's shape (lookupPrefix), matches no stored key, or names a key that is not active (statusAt). It writes the key's last_used_at as lastUsedDebounce allows; a failed write is logged and does not refuse the key.