Documentation
¶
Overview ¶
Package api holds the Huma (OpenAPI 3.1) setup shared by every domain: operation helpers that declare the required permission, the middleware that authenticates users, API keys and MCP agents and authorizes them with internal/authz, and RFC 9457 error helpers.
Domain packages register their operations with Register* helpers and read the caller with PrincipalFrom. This package never imports domain packages.
Index ¶
- Constants
- Variables
- func Delete[I, O any](a huma.API, o Op, h func(context.Context, *I) (*O, error))
- func Get[I, O any](a huma.API, o Op, h func(context.Context, *I) (*O, error))
- func MapError(err error, what string) error
- func Patch[I, O any](a huma.API, o Op, h func(context.Context, *I) (*O, error))
- func Post[I, O any](a huma.API, o Op, h func(context.Context, *I) (*O, error))
- func PrincipalFrom(ctx context.Context) *authz.Principal
- func Put[I, O any](a huma.API, o Op, h func(context.Context, *I) (*O, error))
- func Register[I, O any](a huma.API, o Op, h func(context.Context, *I) (*O, error))
- func SchemaNamer() func(t reflect.Type, hint string) string
- func SessionFrom(ctx context.Context) *store.Session
- func UserFrom(ctx context.Context) *store.User
- func WithPrincipal(ctx context.Context, p *authz.Principal) context.Context
- func WorkspaceFrom(ctx context.Context) *store.Workspace
- type Access
- type AccessKind
- type Authenticator
- type Body
- type Empty
- type Op
- type Page
- type PageInput
- type Policy
- type Problem
- type WorkspaceInput
Constants ¶
const ( CodeUnauthenticated = "unauthenticated" CodeSessionExpired = "session_expired" CodePasswordChange = "password_change_required" CodeTwoFactorSetup = "two_factor_setup_required" CodePermissionDenied = "permission_denied" CodeEscalation = "escalation_denied" CodeNotFound = "not_found" CodeConflict = "conflict" CodeValidation = "validation_failed" CodeRateLimited = "rate_limited" CodeLocked = "locked" CodeInstanceNotSetUp = "instance_not_set_up" CodeHumansOnly = "humans_only" CodeWorkspaceNotFound = "workspace_not_found" CodeLastOwner = "last_owner" CodeInvalidCredentials = "invalid_credentials" //nolint:gosec // an error code, not a credential )
Error codes used across the API.
const Version = "/api/v1"
Version is the URL prefix of the public API.
Variables ¶
var ( Public = Access{Kind: AccessPublic} Authenticated = Access{Kind: AccessUser} Pending = Access{Kind: AccessUser, AllowPending: true} InstanceAdmin = Access{Kind: AccessInstanceAdmin, HumansOnly: true} )
Common access requirements.
var NoContent = &Empty{}
NoContent is returned by operations that answer 204.
Functions ¶
func MapError ¶
MapError turns domain errors into problems: pgx.ErrNoRows becomes 404, authz denials become 403, and anything else passes through unchanged.
func PrincipalFrom ¶
PrincipalFrom returns the authenticated caller, or nil on public operations.
func SchemaNamer ¶
SchemaNamer names API schemas after their Go type, like Huma's default namer, and keeps names unique across domains: when a second, different type asks for a name already taken (FieldOption in two packages), it gets its package name as a prefix (AutomationsFieldOption) instead of Huma panicking at startup. Domains should still pick distinct type names.
func SessionFrom ¶
SessionFrom returns the current session (nil for API keys and public calls).
func WithPrincipal ¶
WithPrincipal stores a principal (used by tests and internal callers).
Types ¶
type Access ¶
type Access struct {
Kind AccessKind
Permission authz.Permission
// AllowPending lets users with a temporary password or missing required
// two-factor call the operation (the setup and account endpoints).
AllowPending bool
// HumansOnly rejects API keys and agents (account security, approvals).
HumansOnly bool
}
Access is the requirement attached to an operation.
func Workspace ¶
func Workspace(perm authz.Permission) Access
Workspace requires perm in the workspace from the {workspace} path parameter.
func WorkspaceHuman ¶
func WorkspaceHuman(perm authz.Permission) Access
WorkspaceHuman is Workspace but rejects API keys and agents.
type AccessKind ¶
type AccessKind string
AccessKind says who may call an operation.
const ( // AccessPublic needs no authentication (sign-in, public pages, webhooks). AccessPublic AccessKind = "public" // AccessUser needs a signed-in person (account, workspace list). AccessUser AccessKind = "user" // AccessInstanceAdmin needs an instance admin. AccessInstanceAdmin AccessKind = "instance_admin" // AccessWorkspace needs a member, API key or agent holding Permission in // the workspace named by the {workspace} path parameter. AccessWorkspace AccessKind = "workspace" )
type Authenticator ¶
type Authenticator struct {
Q *store.Queries
Audit *audit.Logger
Log *slog.Logger
CookieName string
Policy func(context.Context) (Policy, error)
Now func() time.Time
// OnKeyRejected, when set, records a call refused because its key was
// revoked or expired (reason "revoked" or "expired"), so Settings › Keys
// can show what still uses it.
OnKeyRejected func(ctx context.Context, keyID uuid.UUID, reason string)
}
Authenticator resolves and authorizes callers for every operation.
func (*Authenticator) Middleware ¶
Middleware returns the Huma middleware enforcing each operation's Access.
type Op ¶
type Op struct {
ID string
Method string
Path string
Summary string
Description string
Tags []string
Access Access
// Status overrides the default success status (200, or 204 without a body).
Status int
// MaxBodyBytes overrides Huma's default 1 MiB request limit.
MaxBodyBytes int64
}
Op describes an operation. Path is relative to /api/v1 and workspace operations start with "/workspaces/{workspace}".
type Page ¶
type Page[T any] struct { Items []T `json:"items"` NextCursor string `json:"nextCursor,omitempty" doc:"Pass as ?cursor= to fetch the next page"` Total *int64 `json:"total,omitempty"` }
Page is the envelope of cursor-paginated lists.
type PageInput ¶
type PageInput struct {
Cursor string `query:"cursor" doc:"Opaque cursor from a previous page"`
Limit int `query:"limit" default:"50" minimum:"1" maximum:"500"`
}
PageInput is embedded by inputs of paginated lists.
type Policy ¶
type Policy struct {
SessionIdle time.Duration
TwoFAEnforcement string // off | sensitive | everyone
}
Policy is the part of the instance authentication policy the middleware needs.
type Problem ¶
type Problem struct {
huma.ErrorModel
Code string `json:"code,omitempty" doc:"Stable error code, e.g. permission_denied"`
Permission string `json:"permission,omitempty" doc:"The missing permission key"`
Helpers []string `json:"helpers,omitempty" doc:"Members who hold the missing permission"`
// Meta carries structured details for specific codes, e.g. lockedUntil
// and attemptsLeft for sign-in errors.
Meta map[string]any `json:"meta,omitempty"`
}
Problem is ReputeCast's RFC 9457 error body: Huma's model plus a stable machine-readable code and, for permission errors, who can help.
func BadRequest ¶
BadRequest returns a 400 with an explanation.
func Forbidden ¶
func Forbidden(perm authz.Permission, helpers []string) *Problem
Forbidden returns a 403 for a missing permission, naming who can help.
type WorkspaceInput ¶
type WorkspaceInput struct {
Workspace string `path:"workspace" doc:"Workspace slug" example:"acme-newsletter" pattern:"^[a-z0-9][a-z0-9-]{1,62}$"`
}
WorkspaceInput is embedded by inputs of workspace operations.