Plan: The request extractors validate what they extract

Status

Done (2026-11-19) — the shared Json, Query and Form extractors require Validate and validate before the handler runs (422 validation-failed, before a handler’s own 403/404); 195 redundant handler validate() calls are deleted (craig-cases 56, craig-security 30, craig-financial 32, craig-placement 41, craig-exchange 21, craig-rules 9, craig-reporting 5, craig-ledger 1), and each service step’s red proof failed with the extractor’s check disabled.

Closes: #2662, on the last step.
Tree: written against main.
Ruling (maintainer, 2026-11-18, on #2662): the shared extractors take a T: Validate bound and validate. The duplicated length caps stay as they are, with the dto-length lint; no bounded-string newtypes, no compiled-spec check.

Erratum (2026-11-19): the two craig-composition Value bodies (OverrideDelta, UserDeltaBody) carry the NUL rule the override handler already applies (validate_json_no_nul), not a byte-size rule: a rule equal to the body limit would never fire, because the body limit applies first.

Erratum (2026-11-19): step 1 removes one DTO_LENGTH_BASELINE entry, rule_set_writes.rs::delete_rule_set: its raw query map is now DeleteRuleSetQuery, whose length rule caps every key and value, so the lint reports the entry stale and requires its removal. The baseline only shrinks; no entry is added or raised.

Erratum (2026-11-19): HouseholdQuery and MatchingQuery, the queries of the two handlers that take Result<Query<_>, ParamRejection>, have no string field and every field is #[garde(skip)], so no request to them can fail validation. The planned API tests ("422 for an over-length query parameter") cannot be written; their handlers still map is_invalid() as designed, pinned by the unit test a_param_rejection_tells_validation_from_deserialize.

Erratum (2026-11-19): step 1’s compile census found 22 production request types without Validate, not 39 (the regex census over-counted generic and re-exported types). None of the 22 has a string field, so each derives Validate with #[garde(skip)] on non-string fields only.

Erratum (2026-11-19): the craig-intake-keyring and craig-intake signer-key routes keep their documented fixed 400 for a field error: they take Result<Json<T>, BodyRejection> and answer the validation failure themselves, as the bound’s first car showed.

Erratum (2026-11-19): step 4 deleted 103 calls, not 96: the first census skipped every line after a file’s first #[cfg(test)] and missed 14 craig-placement handlers; the rescan that skips only test blocks found nothing missed in the other services.

Erratum (2026-11-19): calls kept, on values no extractor sees: craig-security’s audit, NIST and signer-key path segments and its issuer settings; craig-placement’s arrangement facts; craig-rules' rule-set-name path segment and the delete parameters rebuilt after the permission check; craig-intake’s report submission (raw bytes); the keyring’s path segments. Steps 3 to 5 carry no devstack green run of their own; the car is that run.

Erratum (2026-11-19): step 3 kept the shared ledger read’s call on LedgerAsOfQuery in the belief that the AFCARS export builds that query; the export calls a different read, and all seven callers extract the query, so the close step deletes it. Its only field is skipped, so it could never fail and has no red proof.

Context

A request type states its limits with garde (#[garde(length(max = …))]). Nothing applies them unless the handler calls body.validate()?. The shared extractors in crates/craig-common/src/extract.rs (Json, Query, Form, Path) only deserialize. #3136 was three list handlers that never made the call.

Measured on main (a script over handler parameters; regex level, so the implementing step confirms each by compiling):

  • The ten REST services take 293 parameters through the shared wrappers: 197 Json, 96 Query. No production code uses the shared Form.

  • Those services hold 227 manual .validate() calls outside tests.

  • 39 of the 293 parameters name a type the script did not see deriving Validate. Three are not structs at all: Json<serde_json::Value> twice in craig-composition and Query<HashMap<String, String>> once in craig-rules.

  • craig-web and craig-portal use their own wrappers (crates/craig-bff/src/extract.rs), which answer plain text, and their form types do not derive Validate. They are out of scope.

  • Json is also used in response position (Json<T>: IntoResponse). The bound must not apply there.

  • No type uses a garde context (validate_with has no caller), so the bound is Validate<Context = ()>.

  • garde is already a dependency of craig-common, and From<garde::Report> for ApiError (crates/craig-common/src/validation.rs) already produces the 422 validation-failed document.

One behaviour moves. An extractor runs before the handler body, so validation will run before every check the handler makes itself. Today about 74 handlers run a caller or feature check first (deny_pure_service, require_operator, bearer_require_service_caller, require_sg_enabled, an authorize_item read). After this plan, a request that is both invalid and refused by such a check is answered 422, where today it is 403 or 404. Authentication (401) is middleware and still comes first.

Design

The bound

In crates/craig-common/src/extract.rs, the FromRequest / FromRequestParts / OptionalFromRequest impls of Json, Query and Form gain T: garde::Validate<Context = ()> and call value.validate() after a successful deserialize. Path is unchanged: its payloads are ids and the dto-length lint already covers string path parameters. The struct definitions and the IntoResponse impl are unchanged, so Json in response position needs no bound.

A failed validation answers the ApiError that From<garde::Report> builds, so the wire document is what the manual call produces today: 422 validation-failed with the field errors.

  • BodyRejection (an enum) gains the arm Invalid(ApiError); its IntoResponse answers the `ApiError’s response.

  • ParamRejection is a struct with private status and detail fields and two consumers. It gains a private invalid: Option<ApiError> field, None for today’s deserialize rejections. When it is Some: status() returns 422, detail() returns the fixed text the query parameters failed validation (value-free), IntoResponse answers the ApiError’s response, and a new `pub fn into_api_error(self) → ApiError returns the validation error, or for a deserialize rejection the 400 it answers today.

  • The two handlers that take Result<Query<_>, ParamRejection> so they can run their permission check first (services/craig-cases/src/api/cases/lifecycle.rs list_household, services/craig-placement/src/api/matching.rs) map every Err to a 400 structural-mismatch through detail(). Step 2 changes each to keep that mapping for a deserialize rejection and return into_api_error() for a validation failure, so an over-length parameter is a 422 there too, still after their permission check. A ParamRejection::is_invalid() accessor tells the two apart.

There is no opt-out wrapper. The three non-struct payloads (Json<serde_json::Value> twice in craig-composition, Query<HashMap<String, String>> in services/craig-rules/src/api/rule_set_writes.rs) each get a request type in their own service: [serde(transparent)], deriving Validate. The dto-length lint treats [garde(skip)] as its opt-out and holds shrink-only baselines (DTO_LENGTH_BASELINE, DTO_OUT_OF_MODEL_CEILINGS in xtask/src/cmd/lints.rs), so step 1 may not use a bare skip there: the map’s keys and values get a custom(…​) rule applying the caps the handler enforces by hand today, and the two Value payloads get a custom(…​) byte-size rule equal to the body limit they already live under. If the lint’s counts would still move, step 1 stops and reports; it does not edit a baseline.

Order of checks, on record

Validation before a handler’s own permission check is accepted, for these reasons: the 422 describes only the caller’s own request and reveals nothing about any record; the 401 still comes first; and 131 handlers already validate as their first statement. The ADR-style record is a paragraph in docs/modules/ROOT/pages/architecture.adoc under the cross-cutting contracts, and the changelog Ops clause.

A test that sends a deliberately invalid body and expects 403 or 404 will fail on its car. The fix is a valid body in the test, listed in the MR; the expected status is not changed.

Manual calls

After the bound, a .validate() on a value that came out of a shared extractor is redundant. Each is deleted. A .validate() on anything else stays: a nested value built by the handler, a value read from a file or a message, the callee-side calls in craig_ledger::act (whose callers extract the same type, so those become redundant and are deleted too, once every caller is on the bound).

Scope

Steps, one MR each, stacked:

  1. Types. Give Validate to every extracted request type that lacks it (the 39 candidates, confirmed by a throwaway local compile with the bound applied), and add the three transparent request types. The lint already requires a cap or a reasoned #[garde(skip)] on every string field of these types, so deriving Validate adds no new annotation to them; a type whose fields carry no garde attribute at all gets the caps the lint’s finding names, never a new bare skip. The lint’s baselines are not edited. No behaviour change: nothing calls the new impls yet. The plan page and nav entry land here.

  2. Bound. The bound, the validate call and the rejection arms in craig-common, with their tests; the architecture.adoc paragraph; the changelog fragment. This is the behaviour change. Manual calls still exist and now run second, harmlessly.

  3. craig-cases: delete its redundant calls (56 candidates).

  4. craig-security, craig-financial, craig-placement: delete theirs (96).

  5. craig-exchange, craig-rules, craig-reporting, craig-intake, craig-intake-keyring, craig-ledger: delete theirs.

  6. Close. Plan archived; #2662 closed with the measured count of deleted calls.

Out of scope: the BFF wrappers and form types; Path; the length-cap duplication and the dto-length lint (ruled to stay); craig-intake’s public submit, which reads Bytes by design; the partner mock servers.

Tests

Category Test

Contract (wire: the 422 body)

craig-common an_invalid_json_body_is_the_same_422_document_a_manual_validate_gives: the extractor’s response and ApiError::from(report)’s response for one over-length body are equal in status, type URL and field errors. The same test for `Query (an_invalid_query_is_the_same_422_document) and for Form (an_invalid_form_is_the_same_422_document).

Unit

craig-common a_param_rejection_tells_validation_from_deserialize: is_invalid(), status(), the fixed detail(), and into_api_error() for both kinds.

Devstack-gated (car only)

New, one per consumer: list_household and the matching list answer 422 for an over-length query parameter and still 400 structural-mismatch for an unknown one.

Unit

craig-common a_valid_body_reaches_the_handler, a_malformed_body_keeps_its_deserialize_rejection (400/415/413 unchanged, validation not reached), an_absent_optional_body_is_none_and_a_present_invalid_one_is_422.

Regression (the case that would have caught #3136)

craig-common a_handler_that_never_calls_validate_still_refuses_an_over_length_field: a router whose handler body ignores the payload answers 422.

Compile

The bound itself: a service handler extracting a type without Validate does not compile. Shown once in step 1’s MR by the throwaway compile; no trybuild test is added.

Regression (unchanged, must stay green)

Each service’s existing validation API tests (about 120 assertions of validation-failed across services/*/tests), and an_over_length_list_filter_is_a_422_on_every_reporting_list.

Devstack-gated (car only)

All of the above API tests. Tests that move from 403/404 to 422 because their body was invalid are fixed by a valid body and listed.

Red proof

Step 2: remove the validate call from the extractor and name the craig-common tests that fail. Steps 3 to 5: with the manual calls deleted, remove the extractor’s call locally and name one validation API test per service that fails (devstack run, as ruled on #3093).

Risks

Risk Mode Mitigation

A manual call is deleted on a value that did not come from a shared extractor, so it is no longer validated

fail-open

Each deletion is checked against the handler signature; the per-service red proof and the unchanged validation API tests run on the car. Each MR lists the calls kept and why.

A type given Validate in step 1 hides a missing cap behind #[garde(skip)], which the dto-length lint accepts as an opt-out

silent

Step 1 adds no bare skip and edits no lint baseline; each MR lists every garde attribute it adds. The three free-form payloads get custom(…​) rules, not skips.

The two Result<Query<_>, ParamRejection> handlers turn a validation failure into a 400 structural-mismatch

silent

Step 2 changes both in the same MR as the bound; the two new API tests pin 422 against 400.

An invalid and unauthorised request now gets 422, not 403

fail-closed

The request is still refused. Recorded in architecture.adoc and the Ops clause; tests fixed by a valid body.

A handler relied on mutating the body before validating it (a canonicalised field that is valid only after the belt)

fail-closed

A legitimate request would be refused with 422. The step-2 car runs every API test before any manual call is removed; any such handler is listed and its type’s rule fixed.

The transparent wrapper for a free-form payload changes the wire

fail-closed

#[serde(transparent)]; the service’s existing API tests for those three routes run unchanged.

The 422 document differs between extractor and manual path

silent

The contract test above compares them.

Delivery

  • Doc page: docs/modules/ROOT/pages/architecture.adoc (cross-cutting contracts: the extractors validate; validation precedes handler checks).

  • CHANGELOG entry: CRAIG’s release notes are changelog.d/ fragments, folded into CHANGELOG.adoc at a release. One fragment with step 2, changelog.d/2662.changed.adoc; Ops clause: a request that is both invalid and not permitted is now answered 422 validation-failed, not 403 or 404. Steps 1 and 3 to 5 change no behaviour and carry none.

  • Gates before each push: fmt, clippy, machete, nextest for the touched crates, cargo xtask validate --profile fast, cargo xtask test --doc.

  • Close: Closes #2662 on step 6; plan archived; note with merge evidence and the measured count.

Edit this page · latest