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 DeniedText(l i18n.Lang, perm authz.Permission, helpers []string) string
- func Get[I, O any](a huma.API, o Op, h func(context.Context, *I) (*O, error))
- func LocalizeProblem(hctx huma.Context, _ string, v any) (any, error)
- func MapError(err error, what string) error
- func NoteCall(ctx context.Context, key, value string)
- 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 RequestLang(acceptLanguage string, u *store.User) i18n.Lang
- func RoleArg(key, name string) any
- func RoleName(l i18n.Lang, key, name string) string
- func SchemaNamer() func(t reflect.Type, hint string) string
- func SessionFrom(ctx context.Context) *store.Session
- func UserFrom(ctx context.Context) *store.User
- func WithIntegration(ctx context.Context, k *IntegrationKey) context.Context
- func WithPrincipal(ctx context.Context, p *authz.Principal) context.Context
- func WithReadTimeout(a huma.API, d time.Duration) huma.API
- func WorkspaceFrom(ctx context.Context) *store.Workspace
- type Access
- type AccessKind
- type Authenticator
- type Body
- type Empty
- type IntegrationCall
- type IntegrationKey
- type Integrations
- 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 CodeInternal = "internal_error" // CodeOperatorLocked refuses a change to a setting the server's // configuration pins (http.public_url_locked). CodeOperatorLocked = "operator_locked" )
Error codes used across the API.
const ( CodeKeyRevoked = "key_revoked" CodeKeyExpired = "key_expired" CodeOwnerDeactivated = "owner_deactivated" CodeNotForThisKey = "integration_operation_denied" )
Error codes of calls made with an integration key (the integrations hub shows them in each integration's call log).
const HeaderWorkflow = "X-ReputeCast-Workflow"
HeaderWorkflow names the workflow (a Zap, a Make scenario, an n8n workflow) behind a call: "<name>; id=<id>", the name percent-encoded when it isn't ASCII.
const MaxCallBody = 16 << 10
MaxCallBody is how much of a request and a response the call log keeps.
const UploadReadTimeout = 30 * time.Second
UploadReadTimeout is how long the body of a raw upload (an input with RawBody []byte: an import, a CSV, a DMARC report, a file's chunk) may take to arrive on an API not wrapped by WithReadTimeout. It is http.read_timeout's default. Since v2.40 Huma reads raw bodies with the 5 s deadline it gives JSON ones, unless the operation sets its own.
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 CallingKey = Access{Kind: AccessKey}
CallingKey is for operations about the API key that calls them, in its own workspace. It needs no permission: a key may always describe itself.
var NoContent = &Empty{}
NoContent is returned by operations that answer 204.
Functions ¶
func DeniedText ¶
DeniedText explains a missing permission in a language: "Sending needs a permission you don't have. Ask Marcus Chen or Linh Nguyen." Its words are internal/authz's (authz.DeniedText).
func LocalizeProblem ¶
LocalizeProblem is a Huma transformer that writes access problems in the request's language. English, and problems it doesn't know yet, pass through unchanged.
func MapError ¶
MapError turns domain errors into problems: pgx.ErrNoRows becomes 404, authz denials become 403, and anything else passes through unchanged.
func NoteCall ¶
NoteCall tells the call log something about the current call ("item", "target", "contact"). It does nothing outside integration calls.
func PrincipalFrom ¶
PrincipalFrom returns the authenticated caller, or nil on public operations.
func RequestLang ¶
RequestLang is how a request reads: the Accept-Language header when it names a language ReputeCast has, else the signed-in member's own choice, else English with the ReputeCast standard formats.
func RoleArg ¶
RoleArg is a role's name as an argument of an audit entry's kept line (audit.KeepReason, audit.KeepSummary): a built-in role under its own name is its message, which audit.Render writes in each reader's language; any other name stays as it is.
func RoleName ¶
RoleName writes a role's name in a language: the built-in roles (Owner, Admin, Editor, Viewer, and an agency's client roles) are translated; custom roles, and a built-in role stored under another name, keep the name they were given.
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 WithIntegration ¶
func WithIntegration(ctx context.Context, k *IntegrationKey) context.Context
WithIntegration stores the calling integration (tests and internal callers).
func WithPrincipal ¶
WithPrincipal stores a principal (used by tests and internal callers).
func WithReadTimeout ¶
WithReadTimeout returns a, registering raw uploads with d, the server's read timeout, to read their body.
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
// Integration limits the operation to the keys of one kind of
// integration ("wordpress"), or of any integration ("*").
Integration string
}
Access is the requirement attached to an operation.
func AccessOf ¶
AccessOf returns the access requirement the middleware enforces on an operation, and whether it declares one (an operation that doesn't is public). Tests walk the registered operations with it.
func IntegrationOnly ¶
func IntegrationOnly(kind string, perm authz.Permission) Access
IntegrationOnly is Workspace for the keys of one kind of integration ("wordpress"), or of any integration ("*"): the operations the apps and the WordPress plugin call, which people and other keys don't.
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" // AccessKey needs an API key; the workspace is the key's own, so the // caller needs only the instance URL and the key (integrations' "Test // connection"). AccessKey AccessKind = "key" )
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)
// Integrations knows what integration keys may call and logs their
// calls. Without it integration keys are refused.
Integrations Integrations
// SessionLimit, when set, counts a signed-in browser session's request
// and says whether it may go on, or how long to wait (review 2026-11
// OP-6: a team behind one office NAT no longer shares one budget).
SessionLimit func(session string) (ok bool, wait time.Duration)
// SessionLimitPerMinute is the limit, for the problem's text.
SessionLimitPerMinute int
}
Authenticator resolves and authorizes callers for every operation.
func (*Authenticator) Middleware ¶
Middleware returns the Huma middleware enforcing each operation's Access.
type IntegrationCall ¶
type IntegrationCall struct {
Integration *IntegrationKey
KeyID uuid.UUID
Operation string
Method string
Path string
Status int
At time.Time
Duration time.Duration
// Workflow is the raw X-ReputeCast-Workflow header.
Workflow string
// Request and Response are the first MaxCallBody bytes of each body.
Request []byte
Response []byte
IP *netip.Addr
// UserAgent identifies the app ("ReputeCast-Zapier/1.2.0").
UserAgent string
// Notes are what the operation said about the call (NoteCall).
Notes map[string]string
// Headers are the request headers the call log shows (the workflow and
// the idempotency key); never Authorization.
Headers map[string]string
}
IntegrationCall is one call made with an integration key, for its call log.
type IntegrationKey ¶
type IntegrationKey struct {
ID uuid.UUID
WorkspaceID uuid.UUID
// Kind is the integration ("zapier", "make", "n8n", "wordpress"); Name
// is how people call it ("Zapier").
Kind string
Name string
// Operations are the operation IDs the key may call.
Operations map[string]bool
Disconnected bool
}
IntegrationKey describes the integration an API key belongs to. Such a key works only for the operations of the triggers and actions turned on, even where its permissions would allow more.
func IntegrationFrom ¶
func IntegrationFrom(ctx context.Context) *IntegrationKey
IntegrationFrom returns the integration of the calling key, or nil when the caller isn't an integration key.
func (*IntegrationKey) Allows ¶
func (k *IntegrationKey) Allows(operationID string) bool
Allows reports whether the key may call an operation.
type Integrations ¶
type Integrations interface {
// Key returns the integration of an integration key (its integration_id).
Key(ctx context.Context, integrationID uuid.UUID) (*IntegrationKey, error)
// Record logs a call made with an integration key. It must not fail the call.
Record(ctx context.Context, call IntegrationCall)
}
Integrations connects the authenticator to the integrations hub (internal/integrations), which knows what each integration key may call and keeps their call log.
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.