api

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: MPL-2.0 Imports: 28 Imported by: 0

Documentation

Overview

Package api is the HTTP contract.

`openapi.yaml` beside this file is the single source of truth for every consumer — the Go server types, the TypeScript client, the oasdiff freeze gate — and it is embedded here so a running server validates traffic against exactly the bytes CI diffed, never against a copy that drifted.

The document is hand-written and reviewed like code: the api-cli-surface ADR's version promise covers behaviour (authorization formula, side effects, idempotency, error semantics), and no schema differ can police that. What CI *can* police is that the document and the Go registries agree — see the cross-check tests beside this file.

Index

Constants

View Source
const (

	// ReauthAccountSecurity is the one reauth class the contract names.
	ReauthAccountSecurity = "account-security"
	// ExtOpenEnum marks an enum declared OPEN: it may gain values additively
	// and every generated consumer must tolerate unknown ones. Open enums
	// deliberately carry no `enum` keyword, so runtime validation tolerates
	// growth rather than rejecting a newer server's response.
	ExtOpenEnum = "x-extensible-enum"
)

Extension keys. Each is cross-checked against a Go registry in CI, so the document cannot describe an authorization posture the code does not have.

View Source
const (
	ArtifactNone                = operation.ArtifactNone
	ArtifactHumanSession        = operation.ArtifactHumanSession
	ArtifactMachineCredential   = operation.ArtifactMachineCredential
	ArtifactDeveloperCredential = operation.ArtifactDeveloperCredential
	ArtifactSCIMCredential      = operation.ArtifactSCIMCredential
	ArtifactInstanceCredential  = operation.ArtifactInstanceCredential
	ArtifactLocal               = operation.ArtifactLocal
)
View Source
const (
	// ReauthRequired: one member, a required string in the schema.
	ReauthRequired = "required"
	// ReauthSelected: two or more optional string members; the service
	// selects which one the account's standing credentials make the proof
	// (a confirmed TOTP code where one stands, else the password) and refuses
	// a request without it.
	ReauthSelected = "selected"
	// ReauthSession: one optional string member, required for every session
	// caller unless a live establish stamp authorizes first local-credential
	// creation. Local host authority, which has no session, is also exempt.
	ReauthSession = "session"
	// ReauthWhenValue: one optional string member, required when the body
	// member `member` carries one of `values`.
	ReauthWhenValue = "when-value"
	// ReauthWhenChanged: one optional string member, required when the body
	// member `member` changes the stored value.
	ReauthWhenChanged = "when-changed"
)

Reauth presence rules: WHEN the proof members must carry a value.

View Source
const DefaultDialect = "https://spec.openapis.org/oas/3.1/dialect/base"

DefaultDialect is the OAS 3.1 default JSON Schema dialect. It is pinned: an alternate dialect changes what every keyword in the document means, and no consumer in the chain negotiates one.

View Source
const PathPrefix = "/api/v1"

PathPrefix is the URL version prefix. A future break gets `/api/v2`; v1 explicitly does not plan one.

View Source
const Revision = 16

Revision is this server's API revision, advertised at `/api/v1/meta`. A client compares an operation's `x-hikyo-min-revision` against it and refuses unsupported verbs naming the server version — a bare version string is not the mechanism, the per-operation registry is.

Revision 2 introduces the definitions Git-flow operations. Every pre-existing operation remains revision 1; clients gate only the new verbs on revision 2. Revision 3 adds environment parameter operations and delivery snapshot revision metadata. Existing operation minimums remain stable for older clients. Revision 4 adds public runtime maintenance status. Revision 5 adds delivery-target condition reporting (report, tombstone, list) and its `/meta` protocol capability. Revision 6 adds SSH user certificates (#155): CAs, profiles, issuance, revocation, the host trust bundle and the KRL. Revision 7 adds transit: managed-key lifecycle and the cryptographic data plane (#156, transit ADR). Revision 7 adds the private PKI (#154): instance CA issuers and certificate profiles, and environment-scoped certificate issuance. Revision 7 adds generic file destinations (#164): file-target operations, the bound client's report and the delivery `target` parameter. Revision 8 adds member access rules: rule list, create and revoke, and the folder-move widening confirmation on key metadata updates and definitions apply. Revision 7 had already shipped in nightlies without them. Revision 9 requires authenticated per-value snapshot receipts when offline disclosures are reconciled. Legacy unsigned records must be regenerated. Revision 10 adds bounded online-only developer credentials. Revision 11 adds social-only credential establishment, password mutation, and the authenticated local-credential inventory. Revision 12 adds manual remote invitations, PAKE redemption, and key-bound directory pairing. Existing operations retain their first-appearance minima. Revision 13 adds instance audit trail query and export. Revision 14 adds the editable org and project identity. Revision 13 had already shipped in v1.0.0 without it. Revision 15 adds per-developer personal values (#1235): the owner's list, set, reveal and delete, the members list and member delete, the delivery overlay fields and developer-credential personal consent. Revision 16 adds the email invitation of an existing account: send, list, revoke, preview and accept (#1207).

View Source
const SCIMBodyBound = 256 << 10

SCIMBodyBound is the largest SCIM request body this server accepts (ops-catalogue SCIM § "Wire request body cap": 256 KiB, fixed). It is declared here, at the FIRST place that materializes one, and re-stated by the protocol package's own check so the two cannot drift apart silently.

Variables

View Source
var ErrNoRoute = errors.New("api: no route in the contract matches this request")

ErrNoRoute reports a request that the contract does not describe. It is a distinct error because the response differs from a malformed request: an undescribed path is a 404, a described path with a bad body is a 400.

View Source
var MLDSA65EnumGrowth = []EnumGrowth{
	{requestEnumAdded, "POST", "/api/v1/instance/pki/issuers", "key_algorithm"},
	{requestEnumAdded, "POST", "/api/v1/instance/pki/issuers/{issuer}/rotate", "key_algorithm"},
	{requestEnumAdded, "POST", "/api/v1/instance/pki/profiles", "policy/key_algorithms/items/"},
	{requestEnumAdded, "PUT", "/api/v1/instance/pki/profiles/{profile}", "policy/key_algorithms/items/"},
	{requestEnumAdded, "POST", environmentPath + "/certificates", "key_algorithm"},
	{requestEnumAdded, "POST", environmentPath + "/transit-keys", "algorithm"},
	{responseEnumAdded, "GET", "/api/v1/instance/pki/profiles", "profiles/items/policy/key_algorithms/items/"},
	{responseEnumAdded, "POST", "/api/v1/instance/pki/profiles", "policy/key_algorithms/items/"},
	{responseEnumAdded, "GET", "/api/v1/instance/pki/profiles/{profile}", "policy/key_algorithms/items/"},
	{responseEnumAdded, "PUT", "/api/v1/instance/pki/profiles/{profile}", "policy/key_algorithms/items/"},
	{responseEnumAdded, "POST", "/api/v1/instance/pki/profiles/{profile}/bindings", "policy/key_algorithms/items/"},
	{responseEnumAdded, "DELETE", "/api/v1/instance/pki/profiles/{profile}/bindings/{binding}", "policy/key_algorithms/items/"},
	{responseEnumAdded, "GET", environmentPath + "/certificate-profiles", "profiles/items/policy/key_algorithms/items/"},
	{responseEnumAdded, "GET", environmentPath + "/transit-keys", "items/items/algorithm"},
	{responseEnumAdded, "POST", environmentPath + "/transit-keys", "algorithm"},
	{responseEnumAdded, "GET", environmentPath + "/transit-keys/{transit_key}", "algorithm"},
	{responseEnumAdded, "PATCH", environmentPath + "/transit-keys/{transit_key}", "algorithm"},
	{responseEnumAdded, "POST", environmentPath + "/transit-keys/{transit_key}/lifecycle", "algorithm"},
	{responseEnumAdded, "POST", environmentPath + "/transit-keys/{transit_key}/rotate", "algorithm"},
	{responseEnumAdded, "POST", environmentPath + "/transit-keys/{transit_key}/trim", "key/algorithm"},
}
View Source
var MLDSA65EnumLocations = []string{
	"/components/schemas/PkiIssuerCreateRequest/properties/key_algorithm/enum",
	"/components/schemas/PkiIssuerRotateRequest/properties/key_algorithm/enum",
	"/components/schemas/PkiPolicy/properties/key_algorithms/items/enum",
	"/components/schemas/CertificateIssueRequest/properties/key_algorithm/enum",
	"/components/schemas/TransitAlgorithm/enum",
}

MLDSA65EnumLocations is the same amendment as MLDSA65EnumGrowth (the api-cli-surface ADR banner of 2026-11-04), in document coordinates: the only enums that may grow, and only by exactly `mldsa65`. Adding to it is an ADR amendment, not a code edit.

View Source
var PermittedChanges = map[string]bool{

	"endpoint-added":                    true,
	"api-operation-id-added":            true,
	"api-tag-added":                     true,
	"response-media-type-added":         true,
	"response-success-status-added":     true,
	"response-non-success-status-added": true,

	"new-optional-request-parameter":        true,
	"new-optional-request-property":         true,
	"new-optional-request-header-parameter": true,
	"request-property-became-optional":      true,
	"request-parameter-became-optional":     true,

	"response-property-added":          true,
	"response-optional-property-added": true,
	"response-required-property-added": true,

	"api-deprecated":                        true,
	"endpoint-deprecated":                   true,
	"api-description-changed":               true,
	"api-summary-changed":                   true,
	"description-changed":                   true,
	"request-property-description-changed":  true,
	"response-property-description-changed": true,
}

PermittedChanges is the fail-closed allowlist: the oasdiff change ids that count as permitted additions under the version promise.

The promise is: new endpoints, new OPTIONAL request fields, new response fields, and growth of enums declared open. Everything else — including anything oasdiff invents in a future release — is refused until reviewed and added here deliberately.

View Source
var SpecYAML []byte

SpecYAML is the contract as authored. Exported so tooling (the oasdiff gate's fixtures, the TypeScript generator's freshness check) reads one copy.

Functions

func AuthorizationOperationAdmitsArtifact

func AuthorizationOperationAdmitsArtifact(id, class string) (admitted, described bool)

AuthorizationOperationAdmitsArtifact reports whether any contract operation mapped to the named authorization operation admits class. The HTTP path uses its exact operation row; this derived view preserves the same contract at in-process chokepoint calls where no request operation exists.

func CheckProfile

func CheckProfile(specYAML []byte) error

CheckProfile reports every profile violation in a document, joined, so one run names all of them rather than one per iteration.

func Doc

func Doc() (*openapi3.T, error)

Doc returns the parsed contract. It fails loudly rather than serving unvalidated traffic: an unparseable embedded document is a build defect.

func IsSCIMWireOperation

func IsSCIMWireOperation(operationID string) bool

IsSCIMWireOperation reports whether a contract operation is one of the identity provider's own protocol endpoints, as opposed to the SCIM ADMINISTRATION surface (which is ordinary domain surface under a human session and is validated pre-auth like everything else).

The two families are told apart by their operation-id shape, which is a convention this function makes load-bearing: wire operations are `scim<Verb>`, administration operations are `<verb>Scim<Noun>`. The contract cross-check test pins that both families are non-empty, so a renamed operation cannot silently move a route from one side to the other.

func Operations

func Operations() (map[string]Operation, error)

Operations returns every operation in the contract, keyed by operationId.

func ValidateResponse

func ValidateResponse(r *http.Request, status int, header http.Header, body []byte) error

ValidateResponse checks a recorded response against the contract. This is the CI wire-response duty: contract tests assert what actually went over the socket, not what a handler intended.

func Warm

func Warm() error

Warm parses and validates the embedded contract. Server boot calls it before opening a listener so no request pays the one-time document load cost.

Types

type EnumGrowth

type EnumGrowth struct {
	ID, Operation, Path, Property string
}

EnumGrowth names one permitted enum-value addition: the oasdiff change id, the operation, the path and the property oasdiff reports. The added value is always mldsa65 and is checked separately.

type GrantOutcome

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

GrantOutcome is the closed result of a grant mutation. Its zero value is invalid so forgotten initialization fails loudly. Callers can obtain valid values only through the constructors below, and JSON decoding rejects every other wire string.

func GrantOutcomeCreated

func GrantOutcomeCreated() GrantOutcome

func GrantOutcomeOriginAdded

func GrantOutcomeOriginAdded() GrantOutcome

func GrantOutcomeUnchanged

func GrantOutcomeUnchanged() GrantOutcome

func ParseGrantOutcome

func ParseGrantOutcome(value string) (GrantOutcome, error)

func (GrantOutcome) MarshalJSON

func (o GrantOutcome) MarshalJSON() ([]byte, error)

func (GrantOutcome) String

func (o GrantOutcome) String() string

func (*GrantOutcome) UnmarshalJSON

func (o *GrantOutcome) UnmarshalJSON(data []byte) error

func (GrantOutcome) Valid

func (o GrantOutcome) Valid() bool

type MatchedRequest

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

MatchedRequest is one request's single resolution through the contract: the route the OpenAPI router matched, its path parameters, and the shared immutable operation row. The mutable kin-openapi values stay attempt-local and never enter a request context.

func MatchRequest

func MatchRequest(r *http.Request) (*MatchedRequest, error)

MatchRequest resolves a request through the embedded contract exactly once. A request the contract does not describe is ErrNoRoute — the caller's 404, distinct from a described route carrying a bad request.

func (*MatchedRequest) Operation

func (m *MatchedRequest) Operation() Operation

Operation returns the shared immutable contract row this request matched. Consumers may hold and read it but must not mutate its slice fields.

func (*MatchedRequest) PathParam

func (m *MatchedRequest) PathParam(name string) string

PathParam returns one path parameter as the contract route matched it, for middleware that answers before the router hands the request to a handler.

func (*MatchedRequest) Validate

func (m *MatchedRequest) Validate() (*ValidatedRequest, error)

Validate checks the matched request against the contract and reports the offending member on failure. The request is validated AS MATCHED: a caller that replaces r.Body on the same *http.Request between MatchRequest and Validate (the SCIM wire body bound does) is honoured; one that swaps in a different request must match again.

Authentication is deliberately NOT evaluated here: the security scheme is satisfied by resolving a session row inside the request's own transaction at the authorization chokepoint, never by a middleware that decides "authenticated" before one exists. The filter is told to accept every security requirement so it validates shape only. Only successful validation returns a value capable of attaching the matched operation to context.

func (*MatchedRequest) ValidateWithoutBody

func (m *MatchedRequest) ValidateWithoutBody() (*ValidatedRequest, error)

ValidateWithoutBody is Validate with the body excluded, for a request whose over-bound body the server refuses UNREAD (the delivery-target report's 413): path, query and headers are still checked, and the returned request carries the operation row, so artifact admission and authorization run on the refusal exactly as on an accepted request. The caller must never read the body from it.

type Operation

type Operation struct {
	ID      string
	Method  string
	Path    string
	Class   string
	AuthzOp string

	MinRevision int
	// Reauth is the x-hikyo-reauth declaration; the zero value (Class "")
	// means the operation is not reauthentication-gated.
	Reauth ReauthGate
	// Secured reports whether the operation inherits the document's session
	// security requirement. An operation that clears it with `security: []`
	// is a pre-authentication path and must be classified as one.
	Secured bool
	// contains filtered or unexported fields
}

Operation is one immutable row of the contract registry, derived from the document rather than restated in Go — one source, no drift. Request accessors share rows without cloning (#514); slice fields stay private so a consumer cannot mutate authorization policy process-wide.

func OperationFromContext

func OperationFromContext(ctx context.Context) (Operation, bool)

OperationFromContext returns the contract row attached at HTTP admission. Absence means an in-process caller rather than an unclassified HTTP route.

func (Operation) AdmitsArtifact

func (o Operation) AdmitsArtifact(class string) bool

AdmitsArtifact reports whether the operation's OpenAPI declaration admits the authenticated artifact class. The declaration is a closed allowlist.

func (Operation) Artifacts

func (o Operation) Artifacts() []string

Artifacts returns a copy of the authenticated artifact allowlist.

func (Operation) Formula

func (o Operation) Formula() []string

Formula returns a copy of the authorization formula declared for this row.

type ReauthGate

type ReauthGate struct {
	Class    string
	Proof    []string
	Presence string
	Member   string
	Values   []string
}

ReauthGate is an operation's x-hikyo-reauth declaration.

type ValidatedRequest

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

ValidatedRequest carries the original request and its shared operation row proven by its validation. Its fields are private, so another package cannot construct an alternate row or attach one to a different request.

func ValidateRequest

func ValidateRequest(r *http.Request) (*ValidatedRequest, error)

ValidateRequest matches and validates once, returning the immutable row that passed validation. Admission uses the two-step form because SCIM body policy must run between matching and shape validation.

func (*ValidatedRequest) Operation

func (v *ValidatedRequest) Operation() Operation

Operation returns the immutable operation row proven by validation.

func (*ValidatedRequest) Request

func (v *ValidatedRequest) Request() *http.Request

Request returns the request that passed validation with its immutable operation row attached. It deliberately accepts no request or context: a caller cannot validate route A and attach that result to request B.

type ValidationError

type ValidationError struct {
	Member string
	Err    error
}

ValidationError wraps a contract violation with the request member that caused it. The member name is safe to return to the caller: request-shape validation happens before any tenant resolution, so it reveals nothing about what exists or who may reach it.

func (*ValidationError) Error

func (e *ValidationError) Error() string

func (*ValidationError) Unwrap

func (e *ValidationError) Unwrap() error

type Violation

type Violation struct {
	ID        string
	Operation string
	Path      string
	Text      string
	Level     string
}

Violation is one refused change.

func CheckFreeze

func CheckFreeze(base, revised []byte) ([]Violation, error)

CheckFreeze diffs revised against base and returns every change that is not a permitted addition, plus any violation of the bound 3.1 profile.

Both halves matter and neither subsumes the other: oasdiff sees structural change but has no opinion about `nullable` or `jsonSchemaDialect`, and CheckProfile sees the profile but has no memory of what the document said yesterday.

Violations have three sources: the oasdiff allowlist, freezeRemovals, and a third, independent layer (freezeContract) that compares the raw documents and refuses every difference but an explicit short list of additions and prose edits. It exists because enumerating oasdiff's blind spots never converged (#1217).

func (Violation) String

func (v Violation) String() string

Directories

Path Synopsis
Package apigen provides primitives to interact with the openapi HTTP API.
Package apigen provides primitives to interact with the openapi HTTP API.

Jump to

Keyboard shortcuts

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