api

package
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2026 License: AGPL-3.0 Imports: 27 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 (
	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).

View Source
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.

View Source
const MaxCallBody = 16 << 10

MaxCallBody is how much of a request and a response the call log keeps.

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 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.

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 DeniedText

func DeniedText(l i18n.Lang, perm authz.Permission, helpers []string) string

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 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 LocalizeProblem

func LocalizeProblem(hctx huma.Context, _ string, v any) (any, error)

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

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 NoteCall

func NoteCall(ctx context.Context, key, value string)

NoteCall tells the call log something about the current call ("item", "target", "contact"). It does nothing outside integration calls.

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 RequestLang

func RequestLang(acceptLanguage string, u *store.User) i18n.Lang

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

func RoleArg(key, name string) any

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

func RoleName(l i18n.Lang, key, name string) string

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

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 WithIntegration

func WithIntegration(ctx context.Context, k *IntegrationKey) context.Context

WithIntegration stores the calling integration (tests and internal callers).

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
	// 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

func AccessOf(op *huma.Operation) (Access, bool)

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

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 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

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"): "Campaign not found." Each kind of thing has its own message in the package's catalog (notFound.campaign), which LocalizeProblem writes in the reader's language; a thing without one reads in English.

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