auth

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: May 16, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Overview

Package auth provides per-route HTTP middleware for verifying caller identity against the paper-board identity gRPC AuthService.

Usage (Option C — separate config wiring from per-route factories):

cfg := auth.New(auth.WithClient(grpcConn))
router.Use(cfg.Require(auth.JWT, auth.APIKey))
adminRoutes.Use(cfg.RequireRole(auth.Owner))

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrMissingHeader is returned when the Authorization header is absent.
	ErrMissingHeader = errors.New("auth: missing Authorization header")
	// ErrInvalidScheme is returned when the Authorization header does not use Bearer scheme.
	ErrInvalidScheme = errors.New("auth: invalid scheme")
	// ErrUnauthenticated is returned when the credential is invalid or expired.
	ErrUnauthenticated = errors.New("auth: unauthenticated")
	// ErrKeyRetired is returned when the JWT signing key has been retired.
	ErrKeyRetired = errors.New("auth: signing key retired")
	// ErrWrongEnvironment is returned when credential env does not match route expectation.
	ErrWrongEnvironment = errors.New("auth: wrong environment")
	// ErrInsufficientRole is returned when the caller's role does not meet the route requirement (HTTP 403).
	ErrInsufficientRole = errors.New("auth: insufficient role")
)

Sentinel errors for callers to use with errors.Is. All map to HTTP 401 except ErrInsufficientRole (403).

Functions

func WithContext

func WithContext(ctx context.Context, a AuthCtx) context.Context

WithContext returns a new context carrying the AuthCtx.

Types

type AuthCtx

type AuthCtx struct {
	UserID    uuid.UUID
	OrgID     uuid.UUID
	Mode      AuthMode
	AuthKeyID *uuid.UUID // present when Mode=JWT (the signing key kid parsed as UUID)
	APIKeyID  *uuid.UUID // present when Mode=APIKey
	Method    string     // raw method string from identity (e.g. "jwt", "api_key")
	Env       Env
	Role      Role
}

AuthCtx is the verified caller identity injected into request context after Require succeeds.

func FromContext

func FromContext(ctx context.Context) (AuthCtx, bool)

FromContext extracts the AuthCtx from a request context. The bool reports presence.

type AuthMode

type AuthMode int

AuthMode identifies the credential format expected by a route.

const (
	// JWT indicates Bearer token authentication.
	JWT AuthMode = 1
	// APIKey indicates API key authentication (pbk_(live|test)_* format).
	APIKey AuthMode = 2
)

type Config

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

Config holds the shared dependencies for the auth middleware factories. Create with New; then call Require / RequireRole on routes.

func New

func New(opts ...Option) *Config

New constructs a Config from the supplied options. WithClient is required unless WithKeystore is supplied (e.g. in tests).

func (*Config) Require

func (cfg *Config) Require(modes ...AuthMode) func(http.Handler) http.Handler

Require returns middleware that accepts only requests carrying one of the listed AuthModes. Modes are an OR set — order is irrelevant. The verified AuthCtx is injected into the request context for downstream handlers.

Respond policy:

missing header     → 401
non-Bearer scheme  → 401
mode not accepted  → 401
verify failure     → 401 (or 403 for ErrInsufficientRole)

func (*Config) RequireRole

func (cfg *Config) RequireRole(roles ...Role) func(http.Handler) http.Handler

RequireRole returns middleware that gates routes by role. Must run AFTER Require in the chain (depends on AuthCtx already in context). Roles are an OR set — any one of the listed roles passes.

type Env

type Env string

Env identifies the credential environment.

const (
	// EnvLive is the production credential environment.
	EnvLive Env = "live"
	// EnvTest is the sandbox credential environment.
	EnvTest Env = "test"
)

type Keystore

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

Keystore caches GetPublicKey responses with TTL. Concurrent-safe.

func NewKeystore

func NewKeystore(client identityv1.AuthServiceClient) *Keystore

NewKeystore returns a Keystore with the given client and default 5min TTL.

func NewKeystoreWithTTL

func NewKeystoreWithTTL(client identityv1.AuthServiceClient, ttl time.Duration) *Keystore

NewKeystoreWithTTL returns a Keystore with a custom TTL.

func (*Keystore) Get

func (k *Keystore) Get(ctx context.Context, kid string) ([]byte, string, error)

Get returns the cached public key for kid, fetching from identity on miss or expiry.

func (*Keystore) Refresh

func (k *Keystore) Refresh(ctx context.Context, kid string) ([]byte, string, error)

Refresh forces a re-fetch from identity, bypassing the TTL.

type Option

type Option func(*Config)

Option mutates Config during construction.

func WithClient

func WithClient(c identityv1.AuthServiceClient) Option

WithClient injects the identity gRPC client. Required for non-mock usage.

func WithKeystore

func WithKeystore(s *Keystore) Option

WithKeystore injects a custom Keystore (defaults to a fresh in-memory one built from WithClient).

func WithKeystoreTTL

func WithKeystoreTTL(d time.Duration) Option

WithKeystoreTTL overrides the default 5min Keystore TTL. Ignored if WithKeystore is also supplied.

type Role

type Role int

Role is the org-scoped membership level returned by identity.

const (
	// Owner has full administrative access within an org.
	Owner Role = 1
	// Member has standard access within an org.
	Member Role = 2
)

Directories

Path Synopsis
Package mock provides test doubles for the identity gRPC AuthService.
Package mock provides test doubles for the identity gRPC AuthService.

Jump to

Keyboard shortcuts

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