auth

package
v0.9.1 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2026 License: MIT Imports: 19 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

Index

Constants

View Source
const MaxRotationGraceSeconds = 7 * 24 * 60 * 60

MaxRotationGraceSeconds caps how long a caller can keep the old key alive during rotation. Seven days matches the longest grace window Stripe offers in its dashboard "roll key" flow — long enough for a scheduled deploy cadence, short enough that a forgotten rotation still self-heals.

Variables

View Source
var ErrInvalidKey = errors.New("invalid api key")

ErrInvalidKey marks a DEFINITIVE credential rejection — bad format, no matching key, hash mismatch, or expiry. Middlewares map it (and only it) to the generic 401. Any other ValidateKey error means the verdict never happened (store/DB failure) and must surface as a retryable 5xx: during a DB outage a 401 tells every integrator their key went bad and to start rotating credentials, which is a lie about the key (#560). A fleet-wide 503 reveals nothing about any individual key, so ADR-026's anti-enumeration stance is preserved.

Functions

func CustomerActorID

func CustomerActorID(ctx context.Context) string

CustomerActorID returns the customer ID a portal-session middleware stamped into ctx, or "" when the request isn't customer-authed. audit.Logger consults this to tag rows with actor_type='customer' when the request originated from the customer-portal surface, so the operator Activity feed renders "by customer" instead of the misleading 'system' fallback.

func HasPermission

func HasPermission(keyType KeyType, perm Permission) bool

func KeyID

func KeyID(ctx context.Context) string

func KeyPrefix

func KeyPrefix(kt KeyType, livemode bool) string

KeyPrefix returns the full "hc_{type}_{mode}_" prefix used on new keys. Stripe-style: hc_secret_live_..., hc_secret_test_..., etc. A visible mode infix lets operators spot "test key in prod config" misrouting without decoding the key.

func LivemodeFromRawKey

func LivemodeFromRawKey(raw string) (live, ok bool)

LivemodeFromRawKey peeks at a raw API key's prefix to recover the mode it was minted for, without touching the DB. Returns ok=false for strings that don't look like Hardcount API keys so callers can skip the check silently.

func LivemodeFromRequest

func LivemodeFromRequest(r *http.Request) (live, ok bool)

LivemodeFromRequest extracts the mode from whichever auth header the request carries (Authorization: Bearer or X-API-Key), if any. Returns ok=false when the request has no API key or the key prefix is unrecognised.

func Middleware

func Middleware(svc *Service) func(http.Handler) http.Handler

Middleware validates API key credentials and injects tenant context.

func Require

func Require(perm Permission) func(http.Handler) http.Handler

Require returns middleware that checks if the authenticated key has a specific permission. Use this 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 based on HTTP method: GET/HEAD/OPTIONS check `read`, POST/PUT/PATCH/ DELETE check `write`. Closes the gap where a single Require() in front of a chi.Mount applies one permission to a subrouter that mixes reads and writes — left unguarded, a key with read access could write on every endpoint inside the subtree.

Usage:

r.With(auth.RequireMethod(auth.PermCustomerRead, auth.PermCustomerWrite)).
    Mount("/customers", customerH.Routes())

func RequireSession

func RequireSession() func(http.Handler) http.Handler

RequireSession gates a subtree to dashboard-session principals only. Used for surfaces that are inherently a human act (team membership): API keys are machine credentials with no user identity to attribute the action to, so they get a 403 with a pointer at the dashboard.

func TenantID

func TenantID(ctx context.Context) string

func TestTenantIDKey

func TestTenantIDKey() contextKey

TestTenantIDKey returns the context key for tenant ID (for use in tests).

func UserID

func UserID(ctx context.Context) string

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

func WithCustomerActor(ctx context.Context, customerID string) context.Context

WithCustomerActor stamps a customer ID as the request's actor so downstream services (chiefly the audit logger) record who acted.

It is LIVE, and load-bearing. An earlier version of this comment said it was "currently unused after the customer-portal removal — retained for a future surface", which was false and dangerous in a specific way: it invited a cleanup pass to delete the ONE mechanism that attributes an action to a customer rather than to "system". It is 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, and audit.ResolveActor reads it to emit actor_type='customer'.

func WithKeyID

func WithKeyID(ctx context.Context, id string) context.Context

WithKeyID is the setter counterpart to KeyID. Used by adapters outside the auth package (currently `internal/session`) that resolve a credential to a key context themselves.

func WithKeyType

func WithKeyType(ctx context.Context, kt KeyType) context.Context

WithKeyType lets adapters declare the principal type so auth.Require keeps working off a single ctx key. Called by `internal/session` when a session resolves to its parent key's type.

func WithTenantID

func WithTenantID(ctx context.Context, tenantID string) context.Context

WithTenantID returns a derived context carrying tenantID. Middleware uses this indirectly via its own WithValue call; background workers (reconciler, billing engine charge loop) use this explicitly to seed the tenant ctx before calling Stripe-resolver-backed clients so per-tenant credentials can be looked up.

func WithUserID

func WithUserID(ctx context.Context, id string) context.Context

WithUserID is the setter counterpart to UserID. Called by the session middleware when a cookie resolves to a user-bound session.

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. Declared here so the package stays decoupled from internal/audit and can be tested with a fake. Production wires *audit.Logger via SetAuditLogger in router.go.

type CreateKeyInput

type CreateKeyInput struct {
	Name      string     `json:"name"`
	KeyType   KeyType    `json:"key_type"`
	ExpiresAt *time.Time `json:"expires_at,omitempty"`
}

type CreateKeyResult

type CreateKeyResult struct {
	Key    domain.APIKey `json:"key"`
	RawKey string        `json:"raw_key"`
}

CreateKeyResult contains the key record + raw key (shown once).

type Handler

type Handler struct {
	// contains filtered or unexported fields
}

func NewHandler

func NewHandler(svc *Service) *Handler

func (*Handler) Routes

func (h *Handler) Routes() chi.Router

func (*Handler) SetAuditLogger

func (h *Handler) SetAuditLogger(a AuditWriter)

SetAuditLogger wires the audit logger so API key lifecycle changes (create / revoke / rotate) write audit_log rows. Without this, security-critical key mutations are invisible to the operator's Audit Log page — a SOC2 / forensics blocker.

type KeyType

type KeyType string

KeyType determines the prefix and permission set for an API key.

const (
	KeyTypePlatform KeyType = "platform" // hc_platform_ — tenant management
	KeyTypeSecret   KeyType = "secret"   // hc_secret_   — full tenant access
	KeyTypeSession  KeyType = "session"  // dashboard cookie session — role-scoped access
)

func GetKeyType

func GetKeyType(ctx context.Context) KeyType

func (KeyType) TypePrefix

func (kt KeyType) TypePrefix() string

TypePrefix returns the type-only prefix (e.g. "hc_secret_"). Used when parsing a raw key to identify its type before the mode infix.

type ListFilter

type ListFilter struct {
	TenantID string
	Role     string
	Limit    int
	Offset   int
}

type Permission

type Permission string

Permission represents a specific API operation scope.

const (
	PermTenantRead  Permission = "tenant:read"
	PermTenantWrite Permission = "tenant:write"

	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"

	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; platform keys do not.
	PermTestClockWrite Permission = "testclock:write"
)

func AllPermissions

func AllPermissions(keyType KeyType) []Permission

type PostgresStore

type PostgresStore struct {
	// contains filtered or unexported fields
}

func NewPostgresStore

func NewPostgresStore(db *postgres.DB) *PostgresStore

func (*PostgresStore) Create

func (s *PostgresStore) Create(ctx context.Context, key domain.APIKey) (domain.APIKey, error)

func (*PostgresStore) Get

func (s *PostgresStore) Get(ctx context.Context, tenantID, id string) (domain.APIKey, error)

func (*PostgresStore) GetByPrefix

func (s *PostgresStore) GetByPrefix(ctx context.Context, prefix string) (domain.APIKey, error)

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

func (s *PostgresStore) Revoke(ctx context.Context, tenantID, id string) (domain.APIKey, error)

Revoke flips revoked_at on the target key. Idempotent: revoking an already-revoked or expired key returns ErrNotFound (the UPDATE matches zero rows). Caller decides how to surface that.

Pre-ADR-011 included a last-active-secret/platform safeguard that refused to leave the tenant with zero active manage-keys-capable credentials — necessary when the API key was the dashboard sign-in credential. With user accounts (ADR-011), revoking all API keys no longer locks the tenant out: the operator still signs in via email + password and creates new keys.

func (*PostgresStore) ScheduleExpiry

func (s *PostgresStore) ScheduleExpiry(ctx context.Context, tenantID, id string, expiresAt time.Time) (domain.APIKey, error)

func (*PostgresStore) TouchLastUsed

func (s *PostgresStore) TouchLastUsed(ctx context.Context, id string, usedAt time.Time) error

type RotateKeyInput

type RotateKeyInput struct {
	ExpiresInSeconds int64 `json:"expires_in_seconds,omitempty"`
}

RotateKeyInput parameterises rotation. ExpiresInSeconds=0 revokes the old key immediately on rotation; a positive value keeps it valid for that many seconds past now, giving 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 — shown once, never persisted or returned on any subsequent fetch. OldKey's ExpiresAt (grace window) or RevokedAt (immediate) reflects which path the caller took.

type Service

type Service struct {
	// contains filtered or unexported fields
}

func NewService

func NewService(store Store) *Service

func (*Service) CreateKey

func (s *Service) CreateKey(ctx context.Context, tenantID string, input CreateKeyInput) (CreateKeyResult, error)

func (*Service) ListKeys

func (s *Service) ListKeys(ctx context.Context, filter ListFilter) ([]domain.APIKey, int, error)

func (*Service) RevokeKey

func (s *Service) RevokeKey(ctx context.Context, tenantID, id string) (domain.APIKey, error)

func (*Service) RotateKey

func (s *Service) RotateKey(ctx context.Context, tenantID, id string, input RotateKeyInput) (RotateKeyResult, error)

RotateKey issues a replacement key for `id`, preserving its name, type, livemode, and any configured expires_at. The old key is either revoked immediately (grace=0) or scheduled to expire after input.ExpiresInSeconds seconds; callers trading zero-downtime deploys for slightly wider blast radius pick a non-zero grace.

func (*Service) ValidateKey

func (s *Service) ValidateKey(ctx context.Context, rawKey string) (domain.APIKey, error)

ValidateKey looks up a key by prefix, verifies hash, checks expiry.

Accepts three prefix forms, in priority order:

  1. "hc_{type}_live_..." (new, post-FEAT-8)
  2. "hc_{type}_test_..." (new, post-FEAT-8)
  3. "hc_{type}_..." (legacy, pre-FEAT-8 — treated as live)

Backward compat for (3) keeps existing production keys working through the cutover. 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 non-revoked key without revoking it.
	// Used by rotation when a grace period is requested — ValidateKey rejects
	// expired keys the same way it rejects revoked ones, but leaving
	// revoked_at unset keeps the key visible to GetByPrefix through the
	// grace window so in-flight requests 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
}

Jump to

Keyboard shortcuts

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