api

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: AGPL-3.0 Imports: 21 Imported by: 0

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

View Source
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
	CodeProviderUnavailable = "provider_unavailable"
	CodeUnavailable         = "unavailable"
	CodeInternal            = "internal_error"
)

Error codes used across the API.

View Source
const Version = "/api/v1"

Version is the URL prefix of the public API.

Variables

View Source
var (
	Public        = Access{Kind: AccessPublic}
	Authenticated = Access{Kind: AccessUser}
	Pending       = Access{Kind: AccessUser, AllowPending: true}
	InstanceAdmin = Access{Kind: AccessInstanceAdmin, HumansOnly: true}
)

Common access requirements.

View Source
var NoContent = &Empty{}

NoContent is returned by operations that answer 204.

Functions

func Delete

func Delete[I, O any](a huma.API, o Op, h func(context.Context, *I) (*O, error))

func Get

func Get[I, O any](a huma.API, o Op, h func(context.Context, *I) (*O, error))

Get, Post, Put, Patch and Delete are shorthands for Register.

func MapError

func MapError(err error, what string) error

MapError turns domain errors into problems: pgx.ErrNoRows becomes 404, authz denials become 403, and anything else passes through unchanged.

func Patch

func Patch[I, O any](a huma.API, o Op, h func(context.Context, *I) (*O, error))

func Post

func Post[I, O any](a huma.API, o Op, h func(context.Context, *I) (*O, error))

func PrincipalFrom

func PrincipalFrom(ctx context.Context) *authz.Principal

PrincipalFrom returns the authenticated caller, or nil on public operations.

func Put

func Put[I, O any](a huma.API, o Op, h func(context.Context, *I) (*O, error))

func Register

func Register[I, O any](a huma.API, o Op, h func(context.Context, *I) (*O, error))

Register adds an operation with a typed handler.

func SchemaNamer

func SchemaNamer() func(t reflect.Type, hint string) string

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

func SessionFrom(ctx context.Context) *store.Session

SessionFrom returns the current session (nil for API keys and public calls).

func UserFrom

func UserFrom(ctx context.Context) *store.User

UserFrom returns the signed-in user (nil for API keys and public calls).

func WithPrincipal

func WithPrincipal(ctx context.Context, p *authz.Principal) context.Context

WithPrincipal stores a principal (used by tests and internal callers).

func WorkspaceFrom

func WorkspaceFrom(ctx context.Context) *store.Workspace

WorkspaceFrom returns the workspace of a workspace operation.

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

func (a *Authenticator) Middleware(hapi huma.API) func(huma.Context, func(huma.Context))

Middleware returns the Huma middleware enforcing each operation's Access.

type Body

type Body[T any] struct {
	Body T
}

Body wraps a JSON response body.

func OK

func OK[T any](v T) *Body[T]

OK wraps v as a response body.

type Empty

type Empty struct{}

Empty is the output of operations without a body.

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

func BadRequest(detail string) *Problem

BadRequest returns a 400 with an explanation.

func Conflict

func Conflict(detail string) *Problem

Conflict returns a 409 with an explanation.

func Err

func Err(status int, code, detail string) *Problem

Err builds a problem with a code.

func Forbidden

func Forbidden(perm authz.Permission, helpers []string) *Problem

Forbidden returns a 403 for a missing permission, naming who can help.

func Invalid

func Invalid(location, message string) *Problem

Invalid returns a 422 for one field: Invalid("body.email", "Use a work email.").

func NotFound

func NotFound(what string) *Problem

NotFound returns a 404 for a named thing ("Campaign").

func (*Problem) WithMeta

func (p *Problem) WithMeta(kv ...any) *Problem

WithMeta adds structured details to a problem.

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.

Jump to

Keyboard shortcuts

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