Skip to content

feat(apiv2): Huma foundation, wire rules, and OpenAPI contract gates for /api/v2 [api-v2 phase 2] - #936

Merged
Quick104 merged 20 commits into
apiv2from
api-v2/phase-2-foundation
Sep 5, 2026
Merged

Quick104 merged 20 commits into
apiv2from
api-v2/phase-2-foundation

Conversation

@Quick104

@Quick104 Quick104 commented Sep 4, 2026

Copy link
Copy Markdown
Contributor

Problem

Related issue: #135 (phase issue: #882)

Phase 1 (#902) recorded what the legacy native surface is. Nothing yet enforces the ratified /api/v2 contract in code: there is no v2 listener, no framework configuration that encodes the shared wire rules, no proof that the existing auth, profile, admin, demo-mode, and rate-limit gates reach v2 handlers at the same strength as v1, and no deterministic OpenAPI artifact with CI gates that catch a stale spec, an unaccounted route, or a breaking change. Every domain migration in Phase 3 and later would otherwise re-decide these rules per PR.

Base branch: api-v2/phase-1-scenario-catalogs (PR #902) — stacked; merge #902 first. This PR contains no domain migration; GET /api/v2/system/info and GET /api/v2/openapi.json are the only operations.

Approach

Two stages, 15 commits, each stage boundary visible in the history.

Stage A — listener and wire rules (internal/apiv2, internal/api/middleware, internal/routeinventory). One Huma v2 API behind a sealed http.Handler mounted at /api/v2/* inside the existing API-listener middleware stack. Every operation declares a class (public, authenticated, profile_scoped, acting_admin, permission_gated); the existing v1 gates are composed per class in the v1 order (auth, demo mode, rate limit, viewer access, class gate) and fail closed when a dependency is unwired. One error adapter renders every failure, Huma-generated or application-generated, as RFC 9457 Problem Details under project-controlled type URIs. Framework rules encoded with tests: unknown query parameters and body properties rejected, no format fallback, compressed bodies refused before the body is read, per-operation body limits, 405 with computed Allow, RFC 3339 UTC millisecond instants, opaque cursors, a 30 s read deadline as a 408 problem, typed capability state. The request-ID middleware becomes server-generated (a client can no longer choose the ID that reaches logs and the problem instance). The route inventory audits the new listener as a delegation and refuses any structured route registered outside it, including through closures, helpers, aliases, and wrappers.

Stage B — artifact and gates (contracts/api/v2, internal/contractspec, cmd/apiv2-openapi, cmd/apiv2-contract-diff, CI). The OpenAPI 3.1 artifact is generated deterministically from the Go registries, committed, embedded, served byte-for-byte at /api/v2/openapi.json, and digested into system/info. oasdiff v1.30.0 is pinned as a go.mod library with a checksum test; pre-lock breaking changes need an exact approval entry, post-lock they fail with no override. A spec lint rejects duplicate or implicit operation IDs, anonymous schemas, undocumented statuses, missing auth schemes, and free-form responses. Ten contract fixtures (success plus each problem shape) are generated from the running listener and validated against the schema. Metrics and logs are labelled by operation ID, never raw path. The release workflow attaches the artifact and its SHA-256 to each GitHub release. CI runs every gate on pull requests.

One design point worth a look before ratification: the v2 denial translator needs a machine-readable reason from each v1 gate, but the Phase 1 scenario catalogs assert that every v1 error body is exactly {error, message}. Rather than widen the v1 bodies, each gate records its reason out of band through DenialReasonRecorder (internal/api/middleware/auth.go) and the translator switches on that. v1 wire bytes are unchanged.

Deferred, by design

The ratified wire rules that no foundation operation needs are named in the contract's Foundation subsection under "Not yet encoded" and tracked on #882: optimistic concurrency (ETag/If-Match/428/412), idempotency classification, the 202 job shape, the bulk contract, and RFC 9745/8594 deprecation headers. Each lands with the first operation that needs it, before the first Phase 3 domain PR.

Validation

Full CONTRIBUTING gate on a3ac33a (no database, no network beyond pnpm install):

  • make embed-stub, go build ./..., gofmt -l . (empty), go vet ./...: pass.
  • golangci-lint run --new-from-merge-base="origin/main" ./...: 0 issues. make lint-router-recovery: 0 issues.
  • make test-go: all packages ok (158 s).
  • Phase 1 gates still pass: make verify-route-inventory, verify-migration-ledger, verify-scenario-catalogs, verify-offline-routes.
  • New gates: make verify-apiv2-openapi (artifact current; two consecutive generations and a clean git archive generation are byte-identical), make verify-apiv2-contract BASE_REF=3b848dacb (no breaking change; spec lint clean), make verify-apiv2-fixtures (10 fixtures current and schema-valid).
  • Seeded failures each fail with a readable message (verified by the gates review lens): stale Go schema, plain chi route under /api/v2, duplicate operation ID, corrupt fixture, removed required field without approval (exit 3), exact approval accepted, wildcard or prose approval rejected, post-lock marker honours no override.
  • actionlint on release.yml and ci.yml: clean. make verify-settings-bindings-all, verify-playback-fixtures, verify-local-paths: pass.
  • Web: pnpm run lint, format:check, build, make test-web: pass.
  • Middleware parity, reproduced through the production middlewares by the parity lens: locked profile without token on acting_admin and permission_gated -> 403 profile_verification_required; unknown profile on acting_admin -> 404; four demo-mode requests at rps=1 burst=1 -> all 403, none 429; the translator contains no message-substring matching.

Review history

Two blind independent review panels per stage (Fable 5.1, three to four lenses each: parity, route-inventory coexistence, wire-rule tests, gates, fixtures/observability, closure), each followed by a fix round and a re-review of the owning lenses. Stage A closed 18 findings in round 1 (including two blocking authorization-parity defects: acting-admin and permission-gated operations skipped viewer access, and a message-substring denial translator). The final round left no blocking or major finding open.

Risks

  • go.mod gains huma/v2, oasdiff, and kin-openapi as direct dependencies, and bumps golang.org/x/*. go build, go vet, lint and the full test suite pass on the bumped set; go mod tidy is a no-op.
  • The request-ID middleware on the API listener no longer adopts a client-supplied X-Request-Id. v1 sets no request-ID response header today, so no v1 response changes; only log correlation for callers that relied on choosing the ID is affected.
  • Regenerated route-inventory.json and migration.json change every row's middleware_chain count because the analyzer now measures the constructor's own root scope. Dispositions are unchanged; the nine new api_v2 rows are listener_delegation with a null owner.

Checklist

  • I read and can explain the complete diff.
  • This pull request addresses one concern.

AI Disclosure

  • Harness: Claude Code
  • Tool(s): Claude Code (orchestrator session driving implementation and review subagents through the Workflow tool)
  • Model(s): claude-opus-5 (stage A implementation and its first fix round), claude-fable-5-1 (stage B implementation, the final fix round, orchestration, and all review agents)
  • Involvement: Fully AI-generated; maintainer review pending (opened by the orchestrating agent under the maintainer's program instruction)
  • Adversarial review: see "Review history" above; every finding was arbitrated by the orchestrator against the plan and the contract before a fix was briefed.

🤖 Generated with Claude Code

Quick104 and others added 15 commits September 4, 2026 12:52
…dable denial reasons

The v2 listener needs two things from the shared gates that v1 never
exposed. First, a request ID a caller cannot choose: chi's RequestID adopts
a client-supplied X-Request-Id, but the ID reaches logs, the activity log
and the v2 Problem Details `instance`, so it must be a server-side handle.
RequestID mints a random 96-bit ID, stores it under chi's key so
chimw.GetReqID keeps working everywhere, and sets no response header; v2
adds X-Request-ID on its own routes.

Second, a stable reason for each denial. The v2 error adapter re-renders a
v1 gate's refusal as a Problem Details document, and the ratified scenario
catalogs assert the v1 wire body stays exactly {"error","message"}. Each
gate therefore records a machine-readable reason out of band through
DenialReasonRecorder instead of changing its body, and the translator keys
on that reason rather than on message text.

Co-Authored-By: Claude Opus 5 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
… that bypass it

The route inventory must keep proving that no structured v2 route exists
outside the Huma registry once a second native listener is mounted. The
analyzer learns the api_v2 listener and namespace, records the API
listener's /api/v2/* registration as a delegation rather than as leaf rows,
and enforces the consumer rule as identity with the constructor's own root
scope: a RouterConsumer inside a Group, Route or With closure, a helper, a
condition, or a second call is refused, and a sealed listener handler bound
to a local before registration is refused instead of becoming a leaf row.
middleware_chain counts now measure the constructor's own scope, which is
why the regenerated artifacts in the mount commit shift by the root stack.

The ledger builder derives the api_v2 delegation rows as
documented_exclusion/listener_delegation with a null owner, matching the
existing root delegation rows, and the two JSON Schemas admit the new
listener and namespace values.

Co-Authored-By: Claude Opus 5 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
Adds internal/apiv2: one Huma v2 API behind a sealed http.Handler built from
an unexported chi router, exactly like the other listeners, so the route
inventory can audit it. Every stable operation registers when the router is
built and declares a class (public, authenticated, profile_scoped,
acting_admin, permission_gated); the existing internal/api/middleware gates
are composed per class in the v1 order — auth, demo mode, rate limit,
viewer access, class gate — and fail closed when a dependency is unwired.
Register panics on an inert DemoRestricted-on-public declaration, an
unknown permission, and a metadata_curation operation without {id}.

The ratified wire rules live here with tests: RFC 9457 Problem Details for
every failure, Huma-generated or application-generated, under
project-controlled type URIs; a denial translator keyed on the v1 gate's
machine-readable code and recorded reason, with profile_unverified keeping
its own 403 profile_verification_required type because the clients branch
on it; unknown query parameters and unknown body properties rejected; no
format fallback; compressed bodies refused with 415 before the body is
read; a per-operation body limit named in the 413; 405 with Allow computed
from the registry; RFC 3339 UTC millisecond instants; opaque cursors; a
30 s read deadline rendered as a 408 problem; and a typed capability
state model.

GET /api/v2/system/info is the one domain in this stage: unauthenticated,
body-bounded, cache-controlled, always registered, reporting the SHA-256
of the embedded contract artifact. The artifact is a placeholder until
stage B generates it from the registries; contracts/api/v2 now embeds it.
Huma v2 is pinned in go.mod.

Co-Authored-By: Claude Opus 5 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
…tract artifacts

The API listener registers /api/v2/* as a delegation to apiv2.NewHandler
inside its existing root middleware stack, replacing chi's RequestID with
the server-generated one so the same ID reaches v1 logs and the v2
Problem Details instance. v2Dependencies adapts the router's wiring
(auth, viewer access, acting admin, permission gates, settings) into the
listener's dependency set; no global CORS is added.

The route inventory, migration ledger and offline route set are
regenerated: nine api_v2 delegation rows take listener_delegation with a
null owner, the /api/v2/* wildcard is classified non-media, and every
existing row's middleware_chain reflects the analyzer's root-scope count.

Co-Authored-By: Claude Opus 5 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
Adds the Foundation subsection: operation classes and the gate order the
listener composes, the request-ID rule, the 30 s read deadline, the exact
route-inventory consumer rule, the profile_verification_required problem
type, and that the namespace root /api/v2 is outside the v2 surface.

Co-Authored-By: Claude Opus 5 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
The stage A placeholder openapi.json carried no operations, so nothing
proved the served contract matched the registered operations.

cmd/apiv2-openapi now renders contracts/api/v2/openapi.json from the Go
registries alone (apiv2.GenerateOpenAPI): no database, network,
credentials or environment reach it, and the output is canonical JSON
with sorted keys and no servers, examples or timestamps, so two runs
are byte-identical. Register documents each declaration in the
artifact: the bearer security requirement and X-Profile-Id header per
class, x-silo-class/-permission/-demo-restricted extensions, and the
problem statuses the operation's shape implies.

The binary keeps embedding the committed bytes. GET /api/v2/openapi.json
is a regular public operation (getOpenAPIDocument, tag system) that
writes those exact bytes with an ETag equal to the digest
/api/v2/system/info reports and a short public max-age. Make targets
apiv2-openapi and verify-apiv2-openapi generate and byte-compare.

A typed RawHandshake manual registry (internal/apiv2/manual.go) is
added, empty, for the route/spec reconciliation that follows.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Nothing checked that a change to contracts/api/v2/openapi.json was
backward compatible or that the document kept the shape the contract
requires.

internal/contractspec adds both gates. Diff wraps the oasdiff Go module
(github.com/oasdiff/oasdiff v1.30.0, pinned by version in go.mod and
by checksum in go.sum; TestDiffToolIsPinned refuses a replace or a
pseudo-version) and reduces each finding to a rule id, operation and a
SHA-256 fingerprint. Policy applies the pre-lock rule: a breaking
change fails unless contracts/api/v2/breaking-approvals.json carries an
entry with that exact operation id, change id and fingerprint, validated
by breaking-approvals.schema.json and again in Go so prose-only,
wildcard, empty-reason and duplicate entries are refused; a stale
approval is an error too. Once contracts/api/v2/LOCKED exists the
allowlist is ignored and any breaking change fails.

cmd/apiv2-contract-diff runs the policy against the merge-base copy of
the artifact; make verify-apiv2-contract wires the package tests and
the diff together (BASE_REF selects the base).

Lint checks the committed document for duplicate or implicit operation
ids, non-PascalCase or anonymous schemas, undocumented implied statuses,
missing or superfluous security, and free-form objects without the
x-silo-extension-bag marker. TestLintSeededFailures seeds each rule and
TestSeededBreakingChangeIsDetected proves the pinned tool reports the
seeded breaking fixture, so a tool upgrade that stops detecting it
fails here.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
TestRuntimeReconcile compared the router with the in-process registry,
so a stale committed openapi.json or a raw route registered outside Huma
went unnoticed.

reconcileSpec compares the routes the real assembled router serves with
the operations in the COMMITTED contracts/api/v2/openapi.json plus the
typed manual registry of raw handshakes (apiv2.RawHandshake, empty
today), in both directions. TestCommittedArtifactMatchesRouter runs it
on the production wiring and also fails when a fresh generation differs
from the committed bytes; TestReconcileSpecSeeded proves each direction
fires and that one test-only manual entry accounts for a raw route.

The contract's Foundation subsection records the artifact pipeline and
states that the root /health, /ready and unauthenticated /metrics probes
stay out of the artifact by design.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The v1 request logger and metrics middleware keyed every request on its
sanitized raw path, which is a high-cardinality label the v2 contract
forbids and one that never tells an operator which operation failed.

The v2 listener now records each request once, in an outermost observe
middleware, with a stable label set: api_major, operation_id (from the
matched operation, "none" for the router fallbacks), status_class,
error_code (the problem type identifier), auth_class (public, anonymous,
session, api_key, plugin), and a clamped, bounded client name. The same
attributes go to the structured log with the request ID, so the log line,
the X-Request-ID header and the Problem Details instance all name the same
request. Two counters are registered now for release decisions:
streamapp_apiv2_validation_failures_total, incremented on every
validation_failed problem, and streamapp_apiv1_tombstone_requests_total,
incremented by RecordV1Tombstone once the v1 tombstone exists.

The v1 logger and metrics skip the /api/v2/ subtree (apimw.APIv2Prefix,
pinned against apiv2.DelegationPattern) so a v2 request is not recorded
twice under two vocabularies. Nothing v2 logs a URL, query string, body or
credential header; the tests drive a secret-bearing query string and
Authorization/Cookie headers through the production logredact handler and
assert none of it reaches the line.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Clients need example v2 bodies to test against, and a hand-written example
drifts from the server the moment an envelope changes. The fixtures under
contracts/api/v2/fixtures are therefore generated, never edited:
TestContractFixtures in internal/apiv2 drives synthetic requests through
the real v2 router with fixed request ids and fake credentials and writes
what the server answered; without -update-apiv2-fixtures it fails when the
committed tree is stale (make apiv2-fixtures regenerates, make
verify-apiv2-fixtures checks). index.json records each fixture's operation
id, scenario, request, expected status, asserted response headers, media
type and the OpenAPI schema pointer its body satisfies; fixtures.schema.json
is its JSON Schema.

This stage ships the getSystemInfo success and the representative problem
shapes: validation_failed with errors[] (body and unknown query parameter),
406, 415, 413, 404, 401, 403 profile_verification_required, and 429 with
Retry-After. Denial fixtures come from probe operations that exist only in
the test build, so their operation_id is null and the index schema says so.

internal/contractspec.ValidateFixtures validates the index against its
schema and every body against the named component schema of the committed
openapi.json, checks the operation and status are documented, that a
problem body's status equals expected_status, that a 429 records
Retry-After, and that every committed body is indexed; ten seeded failures
prove each rule fires. The local-path leak scan now covers the fixture
tree with the scenario-catalog rules, allowing only the ratified
problem-type origin as a URL host. make apiv2-fixtures-sync vendors the
tree plus a SOURCE file into the sibling Apple and Android checkouts the
way the playback-v3 fixtures are, and make verify-apiv2-fixtures-siblings
reports stale copies.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…iation

The Phase 2 contract gates existed as make targets and tests but nothing
ran them on a pull request, so a stale artifact, an unapproved breaking
change, an invalid fixture or an unaccounted route could merge.

The Go job now runs, next to the Phase 1 gates: make verify-apiv2-openapi
(byte-compare a fresh generation), make verify-apiv2-contract with
BASE_REF read from the PR's base branch through the environment the way
the lint step does (spec lint plus the pinned oasdiff policy), make
verify-apiv2-fixtures (regenerate through the router, validate every body
against the committed schema), and TestCommittedArtifactMatchesRouter
(router-to-artifact reconciliation in both directions). CONTRIBUTING lists
the same commands in its gate list. The contract doc's Foundation
subsection gains the two durable statements it lacked: how the fixtures
are produced and verified, and the v2 observability label set and the two
release counters.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ed operations

The profile_scoped chain appended RequireProfile before RequireViewerAccess,
the reverse of the v1 authenticated group (router.go uses RequireViewerAccess
via r.Use and nests RequireProfile later) and of the ratified order in
docs/architecture/api-contract.md. Swap the pair and correct the parity test
message that pinned the reversed order. The empty-header response is
unchanged: RequireViewerAccess resolves an empty X-Profile-Id to the account
scope, so RequireProfile still produces the 400 that renders as
validation_failed.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The sealed-handler refusal only fired for a one-hop binding
(h := v2.NewHandler(); r.Handle(..., h)). An alias of that local, or a
wrapper call taking the sealed value as an argument, slipped past it and was
recorded as leaf rows with an expression handler and public auth class, so
the delegated listener's operations vanished from the artifact.

sealedListenerValue now propagates the mark through a plain identifier alias
of a sealed binding and through any call expression that receives a sealed
value as an argument, and noteSealedListener reuses it so the mark follows
assignment chains. Both shapes are refused with the existing message. Two
fixtures, consumer_sealed_alias and consumer_sealed_wrapped, join
consumer_sealed_var in the table-driven refusal test; both fail against the
previous analyzer. The production inventory regenerates byte-identical.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…lease

The release job never checked out the repository and attached no assets, so
nothing carried the committed contracts/api/v2/openapi.json bytes to the
GitHub release even though the v2 plan requires the exact committed artifact
and a verified digest on every release.

Check out the release commit after validation, stage the artifact as
openapi.json beside an openapi.json.sha256 written and verified with
sha256sum, print the digest to the job log, and pass both files as assets
to the existing gh release create call. Validation and flags are unchanged.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…oundation notes

The Foundation subsection still opened with "Four facts" after growing to
seven bullets; the contract-foundation list claimed request-ID behavior
identical to v1 while Foundation records that only v2 sets X-Request-ID; and
the publishing paragraph described a website copy step that does not exist
yet. Fix the count, cross-reference the X-Request-ID difference, and state
that the release attaches the committed bytes and digest as GitHub release
assets with the siloserver.org publish as a post-1.0 follow-up.

Add a closing "Not yet encoded" bullet listing the ratified wire rules that
have no foundation code or tests yet — optimistic concurrency, mutation
retry / idempotency classification, durable 202 job acceptance, the bulk
contract, and the deprecation / link / sunset headers — each landing with
the first v2 operation that needs it, before the first Phase 3 domain PR,
tracked on #882.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@Quick104 Quick104 added api-v2 API v2 / Huma migration program (epic #135); long-running, stacked by phase stacked Base is another open PR; merge in stack order named in the body labels Sep 4, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 4, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-09-04T17:24:50.380372Z 42ea446 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@coderabbitai

coderabbitai Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Team

Run ID: b3f61ae4-82c2-4027-bd57-61fda2a4f801

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

Comment @coderabbitai help to get the list of available commands.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a3ac33a994

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread internal/apiv2/observe.go Outdated
Comment on lines +154 to +155
requestsTotal.WithLabelValues(major, o.operationID, r.Method, statusClass(status), o.errorCode, o.authClass, clientLabel(name)).Inc()
requestDuration.WithLabelValues(major, o.operationID, r.Method).Observe(elapsed.Seconds())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Bound the HTTP method metric label

An unauthenticated caller can send requests with arbitrarily many valid custom method tokens, and both metric vectors use each raw r.Method as a new label value. Because public v2 routes and the 404/405 fallbacks are not rate-limited, this permits unbounded Prometheus series growth and eventual process memory pressure; map unsupported methods to a fixed label such as other.

AGENTS.md reference: AGENTS.md:L12-L17

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Accepted, fixed in 8229a55. The observe middleware runs ahead of routing so it also records the unauthenticated 404/405 fallbacks, and chi routes any syntactically valid custom method to MethodNotAllowed, so raw r.Method was indeed an unbounded label. methodLabel now passes through GET/HEAD/POST/PUT/PATCH/DELETE/OPTIONS and maps everything else to other for both metric vectors and the log attribute. TestMethodLabelIsBounded sends BREW through the built handler and asserts no series carries it.

Comment thread internal/apiv2/gates.go
if deps.ActingAdmin == nil {
return nil, "acting admin"
}
chain = append(chain, deps.ViewerAccess.RequireViewerAccess, deps.ActingAdmin)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Enforce the required profile on privileged classes

Once an acting_admin operation is registered, an admin request without X-Profile-Id passes this chain: viewer access resolves account scope and RequireActingAdmin explicitly accepts an absent profile, even though documentDeclaration marks the header required and the class promises that admin powers are exercised through the primary profile. The permission_gated branch at line 81 has the same omission and lets an admin bypass profile selection through its admin shortcut; include RequireProfile in both chains so account admin status cannot substitute for the required household profile.

AGENTS.md reference: AGENTS.md:L96-L98

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Partly accepted, addressed in 5e80c73. The gate behaviour is intentional v1 parity, not an omission: v1's RequireActingAdmin explicitly accepts an admin with no declared profile and refuses a declared non-primary or unknown one (internal/api/middleware/acting_admin_test.go), the v1 acting-admin groups in router.go sit outside any RequireProfile group, and the policy-engine path agrees (resolveActingAdminFacts returns empty facts for a missing header and permission.rego acting_admin_allowed admits admin_role with declared_profile_id == ""). Making v2 stricter than v1 here is a ratification question for #135, not a foundation defect. What was wrong is the declaration: documentDeclaration marked X-Profile-Id required for all three profile-resolving classes. It is now required only for profile_scoped, and documented as optional-with-constraints for acting_admin and permission_gated, with TestProfileHeaderRequiredMatchesGateChain pinning the flag per class. The committed artifact is unchanged (its two operations are public).

Quick104 and others added 2 commits September 4, 2026 13:12
The observe middleware runs ahead of routing, so it also records the 404
and 405 fallbacks, and chi routes any syntactically valid method token to
MethodNotAllowed. report() passed the raw request method to both
requests_total and request_duration_seconds, so an unauthenticated caller
could mint an unbounded number of series by inventing methods.

Fold the method into a bounded label: the standard GET, HEAD, POST, PUT,
PATCH, DELETE and OPTIONS keep their name, anything else is "other" in
both metric vectors and in the request log line, so the two agree. A test
sends BREW through the built handler and asserts the series lands on
"other" and that no series names the raw method.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…rmission_gated

documentDeclaration marked the X-Profile-Id header required for every
class that resolves a profile, but the gate chain only runs RequireProfile
for profile_scoped. The acting-admin and permission gates accept an absent
header exactly as v1's RequireActingAdmin does (an admin with no declared
profile is admitted; a declared non-primary or unknown profile is refused),
so the declaration overstated the contract.

Document the header as required only for profile_scoped. For acting_admin
and permission_gated keep it documented but optional, with a description
of what a present value must name. Reword the ClassActingAdmin comment to
match, and add a test pinning the Required flag per class. The committed
OpenAPI artifact only carries public operations and is unchanged.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5e80c734d7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread internal/apiv2/gates.go Outdated
Comment on lines +284 to +285
if mt == "*/*" || mt == "application/*" || mt == mediaTypeJSON {
return true

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Honor specific Accept exclusions before wildcards

For Accept: application/json;q=0, */*;q=1, this returns true upon reaching the wildcard even though the more-specific media range explicitly makes JSON unacceptable. normalizeAccept then rewrites the header and serves a 200 instead of the promised 406, which breaks standards-based negotiation for third-party clients; compute JSON's effective quality from the most-specific matching range before deciding.

AGENTS.md reference: AGENTS.md:L19-L22

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Accepted, fixed in 017e52c (plus a lint-only touch in 42ea446). acceptsJSON now evaluates the header by specificity (application/json over application/* over */*) and lets the most specific matching range's q decide, per RFC 9110 §12.5.1. application/json;q=0, */*;q=1 is 406; */*;q=0, application/json is 200. Both directions are covered in TestUnacceptableAcceptIs406.

Comment thread internal/apiv2/observe.go Outdated
)

// RecordV1Tombstone counts one request answered by the v1 tombstone.
func RecordV1Tombstone(method string) { v1TombstoneRequests.WithLabelValues(method).Inc() }

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Bound the tombstone method label

Once the unauthenticated v1 tombstone is wired, callers can send arbitrarily many syntactically valid custom methods and create one Prometheus series per value here. The follow-up in 8229a55 bounds the live v2 request vectors via methodLabel, but the fresh remaining evidence is that this exported recorder still forwards the raw method directly; apply the same fixed-label mapping before incrementing the tombstone counter.

AGENTS.md reference: AGENTS.md:L12-L17

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Accepted, fixed in 772671c: RecordV1Tombstone now goes through the same methodLabel mapping, and the observe test asserts an invented method lands on other.

Quick104 and others added 3 commits September 4, 2026 13:23
RecordV1Tombstone forwarded the raw method to its counter, so once the
unauthenticated tombstone is wired a caller could mint one Prometheus
series per invented method token, the same hole 8229a55 closed for the
v2 request vectors. It now goes through methodLabel.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
… acceptable

acceptsJSON returned true at the first matching range with q > 0, so
"application/json;q=0, */*" was accepted and served a 200 where RFC 9110
§12.5.1 says the explicit q=0 on the more specific range wins and the answer
is 406. The header is now evaluated by specificity (application/json over
application/* over */*) and the winning range's q decides; a q=0 wildcard
no longer vetoes an explicit JSON range either.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

@Quick104 Quick104 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Three P2 findings are attached inline: stable-identifier changes escape the lock policy, committed approvals fail after their change merges, and middleware can emit responses absent from the generated operation contract. I found no confirmed authorization bypass in the reviewed middleware composition.

Validation: reproduced both identifier-only changes passing with LOCKED present, an exact approval passing followed by the merged revision failing its self-comparison, and the production GET endpoints returning undocumented 415 responses. Focused contract, command, runtime, middleware, and fixture checks returned success. A fresh socket-timeout test was sandbox-blocked; the 408 observation is supported by source and existing coverage rather than a fresh socket run.

Reviewed as part of the api-v2 stack intended for individual review and a coordinated merge once satisfactory. Review tooling: Codex, with gpt-6-astra subagents at medium reasoning and parent verification.

c := Change{
ID: f.GetId(),
Level: f.GetLevel().String(),
Breaking: f.GetLevel().IsBreaking(),

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Enforce Silo's compatibility policy for stable identifiers

The implementation adopts oasdiff's default severity, which classifies operation-ID and schema-name removal as informational. Silo explicitly promises to treat both as breaking changes. I reproduced renaming getSystemInfo and SystemInfo: both commands exited successfully with locked=true. Silo needs to apply its stronger compatibility policy on top of the library's defaults.

The governing rule is explicit in the stable identifier contract. The current assignment is at diff.go:73–76.

Comment on lines +245 to +248
if !locked {
for fp, a := range approved {
if !used[fp] {
failures = append(failures, fmt.Sprintf("stale approval for %s %s (fingerprint=%s) matches no change; remove it", a.OperationID, a.ChangeID, fp))

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Account for merged approvals when checking for stale entries

An exact approval correctly permits a breaking PR. Once merged, main's CI compares the new document with itself, while the committed approval remains. The policy then rejects it as "stale." I reproduced the approved change passing, followed by the same revision compared with itself exiting with code 3. Approval validation needs to account for the comparison base and the approval's lifecycle; otherwise main and subsequent unrelated PRs fail until the entries are removed.

The self-comparison is intentional in the main-push CI configuration; the failing policy is at diff.go:245–250.

Comment on lines +108 to +114
if hasBody {
set[http.StatusRequestEntityTooLarge] = true
set[http.StatusUnsupportedMediaType] = true
}
if hasPath {
set[http.StatusNotFound] = true
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Document every middleware-produced response status

Both production GET operations return 415 unsupported_media_type for Content-Encoding: gzip, but neither documents 415. The shared status table also misses body-read timeout 408s and profile-resolution 404s on operations without path parameters. The lint check misses this because it uses the same incomplete table as generation. Runtime response tests need to validate against the operation's actual response map.

Document 415 for every operation subject to the encoding guard, 408 for body operations, and 404 for profile-resolving classes. The incomplete table is at document.go:108–114; the lint check reuses it.

Base automatically changed from api-v2/phase-1-scenario-catalogs to apiv2 September 5, 2026 04:28
@Quick104
Quick104 merged commit c48f5a8 into apiv2 Sep 5, 2026
13 checks passed
@Quick104
Quick104 deleted the api-v2/phase-2-foundation branch September 5, 2026 04:28
Quick104 added a commit that referenced this pull request Sep 5, 2026
The apiv2 integration branch merges #929 (which added the push display
gate calling writeUnauthorized with two arguments) with #936 (which gave
writeUnauthorized a third reason argument), so the branch does not
compile. The gate now records invalid_credential for a bad token and
session_invalid for a revoked session, the same reasons the bearer gate
records for those outcomes.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

api-v2 API v2 / Huma migration program (epic #135); long-running, stacked by phase stacked Base is another open PR; merge in stack order named in the body

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant