From ff56e6ecf3d6c670832725158a7a376ac5b05857 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 13:07:53 +0000 Subject: [PATCH 1/7] feat(rust): add the udibo-http-error crate Add a Cargo workspace in rust/ with the udibo-http-error crate: HttpError with a builder and status shortcuts, ProblemDetails, the default title and detail of every status, parsing of another service's problem response, and IntoResponse behind the axum feature. It passes the shared conformance vectors. CI copies oauth2's Rust gates: fmt, clippy, docs, tests on four platforms, a cargo-hack feature matrix, MSRV 1.88, a wasm32 build, cargo-deny and a 3-day release-age check, behind one Rust CI job. Publishing through release-plz stays off until RUST_RELEASE_ENABLED is set. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YPqZepyt7atNAZ12qoUeVS --- .github/workflows/rust-release.yml | 77 ++++ .github/workflows/rust.yml | 228 ++++++++++ README.md | 6 +- rust/.cargo/config.toml | 5 + rust/.gitignore | 1 + rust/AGENTS.md | 48 +++ rust/CLAUDE.md | 1 + rust/Cargo.lock | 224 ++++++++++ rust/Cargo.toml | 43 ++ rust/README.md | 12 + rust/clippy.toml | 6 + rust/crates/udibo-http-error/Cargo.toml | 36 ++ rust/crates/udibo-http-error/LICENSE | 21 + rust/crates/udibo-http-error/README.md | 79 ++++ rust/crates/udibo-http-error/src/axum.rs | 26 ++ rust/crates/udibo-http-error/src/error.rs | 405 ++++++++++++++++++ rust/crates/udibo-http-error/src/lib.rs | 74 ++++ rust/crates/udibo-http-error/src/parse.rs | 138 ++++++ rust/crates/udibo-http-error/src/problem.rs | 53 +++ rust/crates/udibo-http-error/src/status.rs | 190 ++++++++ rust/crates/udibo-http-error/tests/axum.rs | 42 ++ .../udibo-http-error/tests/conformance.rs | 169 ++++++++ .../udibo-http-error/tests/http_error.rs | 183 ++++++++ rust/deny.toml | 32 ++ rust/release-age-exemptions.json | 3 + rust/release-plz.toml | 14 + rust/rustfmt.toml | 2 + rust/scripts/release-age.test.ts | 139 ++++++ rust/scripts/release-age.ts | 129 ++++++ 29 files changed, 2384 insertions(+), 2 deletions(-) create mode 100644 .github/workflows/rust-release.yml create mode 100644 .github/workflows/rust.yml create mode 100644 rust/.cargo/config.toml create mode 100644 rust/.gitignore create mode 100644 rust/AGENTS.md create mode 100644 rust/CLAUDE.md create mode 100644 rust/Cargo.lock create mode 100644 rust/Cargo.toml create mode 100644 rust/README.md create mode 100644 rust/clippy.toml create mode 100644 rust/crates/udibo-http-error/Cargo.toml create mode 100644 rust/crates/udibo-http-error/LICENSE create mode 100644 rust/crates/udibo-http-error/README.md create mode 100644 rust/crates/udibo-http-error/src/axum.rs create mode 100644 rust/crates/udibo-http-error/src/error.rs create mode 100644 rust/crates/udibo-http-error/src/lib.rs create mode 100644 rust/crates/udibo-http-error/src/parse.rs create mode 100644 rust/crates/udibo-http-error/src/problem.rs create mode 100644 rust/crates/udibo-http-error/src/status.rs create mode 100644 rust/crates/udibo-http-error/tests/axum.rs create mode 100644 rust/crates/udibo-http-error/tests/conformance.rs create mode 100644 rust/crates/udibo-http-error/tests/http_error.rs create mode 100644 rust/deny.toml create mode 100644 rust/release-age-exemptions.json create mode 100644 rust/release-plz.toml create mode 100644 rust/rustfmt.toml create mode 100644 rust/scripts/release-age.test.ts create mode 100644 rust/scripts/release-age.ts diff --git a/.github/workflows/rust-release.yml b/.github/workflows/rust-release.yml new file mode 100644 index 0000000..9b6069d --- /dev/null +++ b/.github/workflows/rust-release.yml @@ -0,0 +1,77 @@ +name: Rust release +on: + push: + branches: [main] + paths: ["rust/**"] +permissions: + contents: read +concurrency: + group: rust-release + cancel-in-progress: false +jobs: + # Publishing stays off until the repository variable RUST_RELEASE_ENABLED is + # "true". Trusted publishing needs each crate published once by hand first, + # then this workflow and the crates-io environment registered on crates.io. + release: + name: Publish released crates to crates.io + if: vars.RUST_RELEASE_ENABLED == 'true' + environment: crates-io + runs-on: ubuntu-latest + timeout-minutes: 30 + permissions: + contents: write + id-token: write + steps: + - name: Clone repository + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + with: + fetch-depth: 0 + persist-credentials: false + - name: Install Rust + run: | + rustup toolchain install stable --profile minimal + rustup default stable + - name: Exchange the OIDC token for a crates.io token + id: auth + uses: rust-lang/crates-io-auth-action@c6f97d42243bad5fab37ca0427f495c86d5b1a18 # v1.0.5 + - name: Publish with release-plz + uses: release-plz/action@1fb72a9583c3601c197b3bd6fc6ce50d58e28ef3 # v0.5.148 + with: + command: release + manifest_path: rust/Cargo.toml + config: rust/release-plz.toml + version: 0.4.3 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + CARGO_REGISTRY_TOKEN: ${{ steps.auth.outputs.token }} + + release-pr: + name: Open or update the Rust release pull request + if: vars.RUST_RELEASE_ENABLED == 'true' + runs-on: ubuntu-latest + timeout-minutes: 30 + permissions: + contents: write + pull-requests: write + concurrency: + group: rust-release-pr + cancel-in-progress: false + steps: + - name: Clone repository + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + with: + fetch-depth: 0 + persist-credentials: false + - name: Install Rust + run: | + rustup toolchain install stable --profile minimal + rustup default stable + - name: Open the release pull request with release-plz + uses: release-plz/action@1fb72a9583c3601c197b3bd6fc6ce50d58e28ef3 # v0.5.148 + with: + command: release-pr + manifest_path: rust/Cargo.toml + config: rust/release-plz.toml + version: 0.4.3 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml new file mode 100644 index 0000000..1a833ad --- /dev/null +++ b/.github/workflows/rust.yml @@ -0,0 +1,228 @@ +name: Rust CI +on: + push: + branches: [main] + pull_request: + workflow_dispatch: +permissions: + contents: read +defaults: + run: + working-directory: rust +concurrency: + group: rust-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} +env: + CARGO_TERM_COLOR: always + CARGO_BUILD_WARNINGS: deny + CARGO_INCREMENTAL: "0" + MSRV: "1.88" +jobs: + # A pull request that changes nothing the Rust crates read skips every job + # below; skipped jobs still satisfy required checks. + changes: + name: Detect Rust changes + runs-on: ubuntu-latest + timeout-minutes: 5 + outputs: + rust: ${{ steps.diff.outputs.rust }} + defaults: + run: + working-directory: . + steps: + - name: Clone repository + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + with: + fetch-depth: 0 + - name: List the changed paths + id: diff + env: + EVENT: ${{ github.event_name }} + BASE: ${{ github.event.pull_request.base.sha }} + run: | + if [ "$EVENT" != "pull_request" ]; then + echo "rust=true" >> "$GITHUB_OUTPUT" + exit 0 + fi + if git diff --name-only "$BASE"...HEAD | grep -qE '^(rust/|conformance/|\.github/workflows/rust)'; then + echo "rust=true" >> "$GITHUB_OUTPUT" + else + echo "rust=false" >> "$GITHUB_OUTPUT" + fi + + release-age: + name: Refuse crate versions under 3 days old + needs: changes + if: needs.changes.outputs.rust == 'true' + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - name: Clone repository + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + - name: Setup Node.js + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 + with: + node-version: 24 + - name: Test the release-age check + run: node --test scripts/*.test.ts + - name: Check Cargo.lock + run: node scripts/release-age.ts + + lint: + name: Format, clippy and docs + needs: changes + if: needs.changes.outputs.rust == 'true' + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - name: Clone repository + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + - name: Install Rust + run: | + rustup toolchain install stable --profile minimal --component clippy,rustfmt + rustup default stable + - name: Cache build + uses: Swatinem/rust-cache@63fed3e2fecf6f7b51dc6f043341b79ef82a9ae7 # v2.9.2 + with: + workspaces: rust + - name: Check formatting + run: cargo fmt --all --check + - name: Run clippy + run: cargo clippy --locked --workspace --all-targets --all-features -- -D warnings + - name: Build docs + env: + RUSTDOCFLAGS: -D warnings + run: cargo doc --locked --workspace --all-features --no-deps + + test: + name: Test (${{ matrix.os }}) + needs: changes + if: needs.changes.outputs.rust == 'true' + runs-on: ${{ matrix.os }} + timeout-minutes: 20 + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, ubuntu-24.04-arm, macos-latest, windows-latest] + steps: + - name: Clone repository + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + - name: Install Rust + run: | + rustup toolchain install stable --profile minimal + rustup default stable + - name: Cache build + uses: Swatinem/rust-cache@63fed3e2fecf6f7b51dc6f043341b79ef82a9ae7 # v2.9.2 + with: + workspaces: rust + - name: Run tests + run: cargo test --locked --workspace --all-features --all-targets + - name: Run doc tests + run: cargo test --locked --workspace --all-features --doc + + features: + name: Check feature combinations + needs: changes + if: needs.changes.outputs.rust == 'true' + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - name: Clone repository + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + - name: Install Rust + run: | + rustup toolchain install stable --profile minimal + rustup default stable + - name: Install cargo-hack + uses: taiki-e/install-action@43dc658ea8a4fa76c68a84c0acd17c34169b6e2a # v2.90.12 + with: + tool: cargo-hack@0.6.46 + - name: Cache build + uses: Swatinem/rust-cache@63fed3e2fecf6f7b51dc6f043341b79ef82a9ae7 # v2.9.2 + with: + workspaces: rust + - name: Check every pair of features + run: >- + cargo hack check --locked --workspace --all-targets + --feature-powerset --depth 2 + + msrv: + name: Build on the minimum supported Rust version + needs: changes + if: needs.changes.outputs.rust == 'true' + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - name: Clone repository + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + - name: Install Rust ${{ env.MSRV }} + run: | + rustup toolchain install "$MSRV" --profile minimal + rustup default "$MSRV" + - name: Cache build + uses: Swatinem/rust-cache@63fed3e2fecf6f7b51dc6f043341b79ef82a9ae7 # v2.9.2 + with: + workspaces: rust + - name: Check that rust-version matches the workspace + run: grep -qx "rust-version = \"$MSRV\"" Cargo.toml + - name: Build every crate with every feature + run: cargo check --locked --workspace --all-features + + wasm: + name: Build for wasm32 + needs: changes + if: needs.changes.outputs.rust == 'true' + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - name: Clone repository + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + - name: Install Rust + run: | + rustup toolchain install stable --profile minimal --target wasm32-unknown-unknown + rustup default stable + - name: Cache build + uses: Swatinem/rust-cache@63fed3e2fecf6f7b51dc6f043341b79ef82a9ae7 # v2.9.2 + with: + workspaces: rust + - name: Build for wasm32-unknown-unknown + run: >- + cargo build --locked --workspace --target wasm32-unknown-unknown + --all-features + + deny: + name: Check advisories, licenses and sources + needs: changes + if: needs.changes.outputs.rust == 'true' + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - name: Clone repository + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + - name: Install cargo-deny + uses: taiki-e/install-action@43dc658ea8a4fa76c68a84c0acd17c34169b6e2a # v2.90.12 + with: + tool: cargo-deny@0.22.2 + - name: Run cargo-deny + run: cargo deny --locked check + + # One check for branch protection: fails when any Rust job failed or was + # cancelled, and passes when they all passed or were skipped. + gate: + name: Rust CI + needs: [changes, release-age, lint, test, features, msrv, wasm, deny] + if: always() + runs-on: ubuntu-latest + timeout-minutes: 5 + defaults: + run: + working-directory: . + steps: + - name: Fail when a Rust job failed + env: + RESULTS: ${{ join(needs.*.result, ' ') }} + run: | + echo "$RESULTS" + case " $RESULTS " in + *" failure "*|*" cancelled "*) exit 1 ;; + esac diff --git a/README.md b/README.md index 62962af..370f64b 100644 --- a/README.md +++ b/README.md @@ -7,9 +7,11 @@ package per language. | Directory | Package | | ---------------------------- | --------------------------------------------------------------------------------------------------------- | | [`typescript/`](typescript/) | [`@udibo/http-error`](typescript/README.md) on [npm](https://www.npmjs.com/package/@udibo/http-error) and [JSR](https://jsr.io/@udibo/http-error) | +| [`rust/`](rust/) | [`udibo-http-error`](rust/crates/udibo-http-error/README.md), not yet published to crates.io | -Each package is versioned and released on its own. `conformance/` will hold the test vectors every package must pass, so the -languages produce the same Problem Details for the same error. +Each package is versioned and released on its own. [`conformance/`](conformance/) +holds the test vectors every package must pass, so the languages produce the +same Problem Details for the same error. ## License diff --git a/rust/.cargo/config.toml b/rust/.cargo/config.toml new file mode 100644 index 0000000..6d77215 --- /dev/null +++ b/rust/.cargo/config.toml @@ -0,0 +1,5 @@ +# Cargo 1.100+ skips crate versions younger than this when it resolves, matching +# the TypeScript package's pnpm `minimumReleaseAge`. `scripts/release-age.ts` +# enforces the same age on every version already in Cargo.lock. +[registry] +global-min-publish-age = "3 days" diff --git a/rust/.gitignore b/rust/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/rust/.gitignore @@ -0,0 +1 @@ +/target diff --git a/rust/AGENTS.md b/rust/AGENTS.md new file mode 100644 index 0000000..17e2b3c --- /dev/null +++ b/rust/AGENTS.md @@ -0,0 +1,48 @@ +# Rust agent instructions + +This directory is the Rust port of `@udibo/http-error`: a Cargo workspace +whose crate keeps the TypeScript package's behavior with an idiomatic Rust API. +Both pass `../conformance/vectors/problem-details.json`; a behavior change goes +into the vectors first, then into both packages. Run every command from `rust/`. + +## Gates + +CI (`.github/workflows/rust.yml`) runs each of these, and the `Rust CI` job +fails when any of them does. Run the ones your change reaches before pushing: + +- `cargo fmt --all --check` +- `cargo clippy --workspace --all-targets --all-features -- -D warnings` +- `cargo test --workspace --all-features` (unit, integration and doc tests) +- `cargo hack check --workspace --all-targets --feature-powerset --depth 2` +- `cargo +1.88 check --workspace --all-features` (the MSRV, `rust-version` in `Cargo.toml`) +- `cargo build --workspace --target wasm32-unknown-unknown --all-features` +- `RUSTDOCFLAGS="-D warnings" cargo doc --workspace --all-features --no-deps` +- `cargo deny check` +- `node scripts/release-age.ts` and `node --test scripts/*.test.ts` + +CI sets `CARGO_BUILD_WARNINGS=deny`, so a compiler or Cargo warning fails the +build; set it locally to match. + +## Rules + +- Edition 2024 on Rust 1.100 or later for development; the published MSRV is + 1.88. Raise the MSRV only when a dependency or language feature needs it, in + `Cargo.toml` and the `MSRV` variable in `rust.yml` together. +- Lints live in `[workspace.lints]`: `unsafe_code` is forbidden, every public + item needs docs, and `unwrap`, `expect`, `panic!` and slice indexing are + denied outside tests. Parsing untrusted input must never panic. +- The crate must keep building for `wasm32-unknown-unknown`, since the OAuth2 + crates that depend on it run on Cloudflare Workers; the `wasm` job checks it. +- New dependencies go in `[workspace.dependencies]` and must pass + `cargo deny check`. Cargo 1.100+ skips versions under 3 days old when it + resolves (`.cargo/config.toml`), and `scripts/release-age.ts` refuses any in + `Cargo.lock`. On older Cargo, pin a younger version back with + `cargo update -p --precise `. Never lower the age; an + exact-version exemption for an urgent advisory fix goes in + `release-age-exemptions.json` with the founder's approval and a reason. +- `Cargo.lock` is committed, so CI and contributors build the same graph. +- Releases go through release-plz (`release-plz.toml`, + `.github/workflows/rust-release.yml`) and stay off until the repository + variable `RUST_RELEASE_ENABLED` is `true`. Never publish by hand or set that + variable without an explicit request. Rust commits never cut a TypeScript + release: semantic-release counts only `typescript/` and `conformance/`. diff --git a/rust/CLAUDE.md b/rust/CLAUDE.md new file mode 100644 index 0000000..43c994c --- /dev/null +++ b/rust/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/rust/Cargo.lock b/rust/Cargo.lock new file mode 100644 index 0000000..8d30481 --- /dev/null +++ b/rust/Cargo.lock @@ -0,0 +1,224 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", +] + +[[package]] +name = "bytes" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mime" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" + +[[package]] +name = "pin-project-lite" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f120c8d5021b34abd2f2ffd7ee96687cbcd6c54a3e68d86b6169f4a5cd480ffe" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "pin-project-lite", + "tokio-macros", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "udibo-http-error" +version = "0.1.0" +dependencies = [ + "axum-core", + "http", + "http-body-util", + "serde", + "serde_json", + "tokio", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/rust/Cargo.toml b/rust/Cargo.toml new file mode 100644 index 0000000..b8f0e4b --- /dev/null +++ b/rust/Cargo.toml @@ -0,0 +1,43 @@ +[workspace] +resolver = "3" +members = ["crates/*"] + +[workspace.package] +version = "0.1.0" +edition = "2024" +rust-version = "1.88" +license = "MIT" +repository = "https://github.com/udibo/http-error" +authors = ["Udibo"] +categories = ["web-programming", "web-programming::http-server"] +keywords = ["http", "error", "problem-details", "rfc9457", "axum"] + +[workspace.dependencies] +axum-core = { version = "0.5", default-features = false } +http = { version = "1", default-features = false, features = ["std"] } +http-body-util = "0.1" +serde = { version = "1", default-features = false, features = ["std"] } +serde_json = { version = "1", default-features = false, features = ["std"] } +tokio = { version = "1", default-features = false, features = ["macros", "rt"] } + +[workspace.lints.rust] +unsafe_code = "forbid" +missing_docs = "deny" +unreachable_pub = "warn" +rust_2018_idioms = { level = "warn", priority = -1 } + +[workspace.lints.rustdoc] +broken_intra_doc_links = "deny" +private_intra_doc_links = "deny" + +[workspace.lints.clippy] +all = { level = "warn", priority = -1 } +unwrap_used = "deny" +expect_used = "deny" +panic = "deny" +indexing_slicing = "deny" +dbg_macro = "deny" +todo = "deny" +unimplemented = "deny" +print_stdout = "deny" +print_stderr = "deny" diff --git a/rust/README.md b/rust/README.md new file mode 100644 index 0000000..b222999 --- /dev/null +++ b/rust/README.md @@ -0,0 +1,12 @@ +# Udibo HTTP Error for Rust + +The Rust port of [`@udibo/http-error`](../typescript/README.md), with the same +behavior, proven by the shared [conformance vectors](../conformance/). It is not +published to crates.io yet. + +| Crate | Holds | +| --- | --- | +| [`udibo-http-error`](crates/udibo-http-error/) | `HttpError`, `ProblemDetails`, the status defaults and, with the `axum` feature, `IntoResponse` | + +The minimum supported Rust version is 1.88. Licensed under the +[MIT license](../LICENSE). diff --git a/rust/clippy.toml b/rust/clippy.toml new file mode 100644 index 0000000..36ed2ba --- /dev/null +++ b/rust/clippy.toml @@ -0,0 +1,6 @@ +allow-unwrap-in-tests = true +allow-expect-in-tests = true +allow-panic-in-tests = true +allow-indexing-slicing-in-tests = true +allow-dbg-in-tests = true +allow-print-in-tests = true diff --git a/rust/crates/udibo-http-error/Cargo.toml b/rust/crates/udibo-http-error/Cargo.toml new file mode 100644 index 0000000..f634d9d --- /dev/null +++ b/rust/crates/udibo-http-error/Cargo.toml @@ -0,0 +1,36 @@ +[package] +name = "udibo-http-error" +description = "HTTP errors that serialize to RFC 9457 problem details, with the same behavior as the @udibo/http-error TypeScript package." +readme = "README.md" +include = ["src/**", "README.md", "LICENSE"] +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +authors.workspace = true +categories.workspace = true +keywords.workspace = true + +[features] +default = [] +# `IntoResponse` for axum. +axum = ["dep:axum-core"] + +[dependencies] +axum-core = { workspace = true, optional = true } +http.workspace = true +serde.workspace = true +serde_json.workspace = true + +[dev-dependencies] +http-body-util.workspace = true +tokio.workspace = true +axum-core.workspace = true + +[package.metadata.docs.rs] +all-features = true +rustdoc-args = ["--cfg", "docsrs"] + +[lints] +workspace = true diff --git a/rust/crates/udibo-http-error/LICENSE b/rust/crates/udibo-http-error/LICENSE new file mode 100644 index 0000000..63d5fc7 --- /dev/null +++ b/rust/crates/udibo-http-error/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Udibo + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/rust/crates/udibo-http-error/README.md b/rust/crates/udibo-http-error/README.md new file mode 100644 index 0000000..4b1e38e --- /dev/null +++ b/rust/crates/udibo-http-error/README.md @@ -0,0 +1,79 @@ +# udibo-http-error + +HTTP errors that serialize to [RFC 9457](https://www.rfc-editor.org/rfc/rfc9457) +problem details, with the same behavior as the +[`@udibo/http-error`](https://jsr.io/@udibo/http-error) TypeScript package: +both pass the shared [conformance vectors](https://github.com/udibo/http-error/tree/main/conformance). + +```toml +[dependencies] +udibo-http-error = { version = "0.1", features = ["axum"] } +``` + +## Errors + +```rust +use udibo_http_error::HttpError; + +// A 404 whose message the client sees as the detail. +let missing = HttpError::not_found("No such user."); + +// Every member, through the builder. +let limited = HttpError::builder() + .status(429) + .detail("Try again in 30 seconds.") + .problem_type("https://example.com/errors/rate-limited") + .extension("limit", 10) + .build()?; + +// An unexpected failure: an unexposed 500 whose message stays in your logs. +let failed = HttpError::from_error(std::io::Error::other("disk full")); +assert_eq!(failed.detail(), "The server encountered an unexpected condition."); +# Ok::<(), udibo_http_error::InvalidStatus>(()) +``` + +| Member | Default | +| --- | --- | +| `status` | 500. Must be from 400 to 599, or `build` returns `InvalidStatus`. | +| `expose` | `true` for 4xx, `false` for 5xx. | +| `title` | The status's reason phrase (`default_title`). | +| `detail` | The message when the error is exposed and the message is not empty, else one sentence for the status (`default_detail`). | +| `content-type` header | `application/problem+json`. | + +An extension named `type`, `status`, `title`, `detail` or `instance` is never +serialized, so it cannot replace a standard member. + +## Responses + +With the `axum` feature, `HttpError` implements `IntoResponse`, so a handler +can return `Result`: + +```rust,ignore +use axum::Json; +use udibo_http_error::HttpError; + +async fn user(id: u64) -> Result, HttpError> { + let user = find_user(id).await.map_err(HttpError::from_error)?; + user.map(Json).ok_or_else(|| HttpError::not_found("No such user.")) +} +``` + +Elsewhere, serialize `error.problem_details()` as the body and send +`error.status()` and `error.headers()`. + +## Reading another service's problem + +```rust +use udibo_http_error::HttpError; + +let error = HttpError::from_problem_body(503, br#"{"status": 503, "detail": "db-1 refused"}"#); +assert_eq!(error.message(), "db-1 refused"); +assert_eq!(error.detail(), "The server is currently unavailable."); +``` + +`from_problem_body` never fails: a body that is not a problem gives an +unexposed error with the response's status. A parsed `detail` becomes the +message, so a server error's detail is not passed on to your own clients. + +The minimum supported Rust version is 1.88. Licensed under the +[MIT license](LICENSE). diff --git a/rust/crates/udibo-http-error/src/axum.rs b/rust/crates/udibo-http-error/src/axum.rs new file mode 100644 index 0000000..69ed26d --- /dev/null +++ b/rust/crates/udibo-http-error/src/axum.rs @@ -0,0 +1,26 @@ +use axum_core::body::Body; +use axum_core::response::{IntoResponse, Response}; + +use crate::HttpError; + +/// Answers with the error's status and headers and its problem details as the +/// JSON body. +/// +/// ``` +/// use axum_core::response::IntoResponse; +/// use udibo_http_error::HttpError; +/// +/// let response = HttpError::not_found("No such user.").into_response(); +/// assert_eq!(response.status().as_u16(), 404); +/// assert_eq!(response.headers()["content-type"], "application/problem+json"); +/// ``` +#[cfg_attr(docsrs, doc(cfg(feature = "axum")))] +impl IntoResponse for HttpError { + fn into_response(self) -> Response { + let body = serde_json::to_vec(&self.problem_details()).unwrap_or_default(); + let mut response = Response::new(Body::from(body)); + *response.status_mut() = self.status(); + *response.headers_mut() = self.headers().clone(); + response + } +} diff --git a/rust/crates/udibo-http-error/src/error.rs b/rust/crates/udibo-http-error/src/error.rs new file mode 100644 index 0000000..b73a884 --- /dev/null +++ b/rust/crates/udibo-http-error/src/error.rs @@ -0,0 +1,405 @@ +use std::error::Error; +use std::fmt; +use std::sync::Arc; + +use http::header::CONTENT_TYPE; +use http::{HeaderMap, HeaderName, HeaderValue, StatusCode}; +use serde_json::{Map, Value}; + +use crate::PROBLEM_JSON; +use crate::problem::ProblemDetails; +use crate::status::{default_detail, default_title}; + +type Source = Arc; + +/// An HTTP error that answers with [RFC 9457] problem details. +/// +/// Build one with [`HttpError::builder`], a status shortcut such as +/// [`HttpError::not_found`], or [`HttpError::from_error`] for an unexpected +/// failure. Read a problem another service sent with +/// [`HttpError::from_problem_body`]. +/// +/// The values a client sees follow these rules: +/// +/// - `status` is from 400 to 599 and defaults to 500. +/// - `expose` defaults to true for a 4xx status and false for a 5xx status. +/// - `title` is the given title, else the status's reason phrase +/// ([`default_title`]). +/// - `detail` is the given detail, else the message when the error is exposed +/// and the message is not empty, else the status's default sentence +/// ([`default_detail`]). A server error's message never reaches the client +/// unless the error is exposed. +/// - An empty title, message, type or instance counts as not set. +/// - The `content-type` header defaults to `application/problem+json`. +/// +/// [RFC 9457]: https://www.rfc-editor.org/rfc/rfc9457 +#[derive(Clone, Debug)] +pub struct HttpError { + status: StatusCode, + message: String, + title: String, + detail: String, + problem_type: Option, + instance: Option, + extensions: Map, + headers: HeaderMap, + expose: bool, + source: Option, +} + +/// The error [`HttpErrorBuilder::build`] returns for a status outside 400 to 599. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct InvalidStatus { + status: Option, +} + +impl InvalidStatus { + /// The refused status, or `None` when it was not a valid HTTP status code at all. + pub fn status(&self) -> Option { + self.status + } +} + +impl fmt::Display for InvalidStatus { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.status { + Some(status) => write!(f, "invalid error status {status}: expected 400 to 599"), + None => f.write_str("invalid error status: expected 400 to 599"), + } + } +} + +impl Error for InvalidStatus {} + +/// Builds an [`HttpError`]. Every member is optional; see [`HttpError`] for the +/// defaults. +/// +/// ``` +/// use udibo_http_error::{HttpError, HeaderValue, header}; +/// +/// let error = HttpError::builder() +/// .status(429) +/// .detail("Try again in 30 seconds.") +/// .problem_type("https://example.com/errors/rate-limited") +/// .header(header::RETRY_AFTER, HeaderValue::from_static("30")) +/// .build()?; +/// +/// assert_eq!(error.status().as_u16(), 429); +/// assert_eq!(error.headers()["retry-after"], "30"); +/// # Ok::<(), udibo_http_error::InvalidStatus>(()) +/// ``` +#[derive(Debug, Default)] +#[must_use] +pub struct HttpErrorBuilder { + status: Option>, + message: Option, + title: Option, + detail: Option, + problem_type: Option, + instance: Option, + extensions: Map, + headers: HeaderMap, + expose: Option, + source: Option, +} + +impl HttpErrorBuilder { + /// The response status, a `u16` or a [`StatusCode`]. It must be from 400 to + /// 599, or [`build`](Self::build) fails. Defaults to 500. + pub fn status>(mut self, status: S) -> Self { + self.status = Some( + status + .try_into() + .map_err(|_| InvalidStatus { status: None }), + ); + self + } + + /// The internal message: logged, and sent as the detail only when the error + /// is exposed and has no explicit detail. + pub fn message(mut self, message: impl Into) -> Self { + self.message = Some(message.into()); + self + } + + /// The problem's `title`, a short summary of the problem type. + pub fn title(mut self, title: impl Into) -> Self { + self.title = Some(title.into()); + self + } + + /// The problem's `detail`, sent whether or not the error is exposed. + pub fn detail(mut self, detail: impl Into) -> Self { + self.detail = Some(detail.into()); + self + } + + /// The problem's `type`, a URI reference identifying the problem type. + pub fn problem_type(mut self, problem_type: impl Into) -> Self { + self.problem_type = Some(problem_type.into()); + self + } + + /// The problem's `instance`, a URI reference identifying this occurrence. + pub fn instance(mut self, instance: impl Into) -> Self { + self.instance = Some(instance.into()); + self + } + + /// Adds an extension member to the problem. A member named `type`, + /// `status`, `title`, `detail` or `instance` is kept on the error but never + /// serialized. + pub fn extension(mut self, name: impl Into, value: impl Into) -> Self { + self.extensions.insert(name.into(), value.into()); + self + } + + /// Adds every member of `extensions`, as [`extension`](Self::extension) does. + pub fn extensions(mut self, extensions: impl IntoIterator) -> Self { + self.extensions.extend(extensions); + self + } + + /// Sets a response header, replacing any value it had. + pub fn header(mut self, name: HeaderName, value: HeaderValue) -> Self { + self.headers.insert(name, value); + self + } + + /// Adds every header in `headers`. + pub fn headers(mut self, headers: HeaderMap) -> Self { + self.headers.extend(headers); + self + } + + /// Whether the message may reach the client as the detail. Defaults to + /// true for a 4xx status and false for a 5xx status. + pub fn expose(mut self, expose: bool) -> Self { + self.expose = Some(expose); + self + } + + /// The error that caused this one, returned by [`Error::source`]. + pub fn source(mut self, source: impl Into>) -> Self { + self.source = Some(Arc::from(source.into())); + self + } + + /// Builds the error. + /// + /// # Errors + /// + /// [`InvalidStatus`] when the status is not from 400 to 599. + pub fn build(self) -> Result { + let status = match self.status { + None => StatusCode::INTERNAL_SERVER_ERROR, + Some(status) => status?, + }; + if !(400..=599).contains(&status.as_u16()) { + return Err(InvalidStatus { + status: Some(status.as_u16()), + }); + } + Ok(self.assemble(status)) + } + + fn assemble(self, status: StatusCode) -> HttpError { + let code = status.as_u16(); + let message = self.message.unwrap_or_default(); + let expose = self.expose.unwrap_or(code < 500); + let detail = match self.detail { + Some(detail) => detail, + None if expose && !message.is_empty() => message.clone(), + None => default_detail(code).to_owned(), + }; + let mut headers = self.headers; + if !headers.contains_key(CONTENT_TYPE) { + headers.insert(CONTENT_TYPE, HeaderValue::from_static(PROBLEM_JSON)); + } + HttpError { + status, + title: non_empty(self.title).unwrap_or_else(|| default_title(code).to_owned()), + message, + detail, + problem_type: non_empty(self.problem_type), + instance: non_empty(self.instance), + extensions: self.extensions, + headers, + expose, + source: self.source, + } + } +} + +fn non_empty(value: Option) -> Option { + value.filter(|value| !value.is_empty()) +} + +macro_rules! shortcuts { + ($($(#[$doc:meta])* $name:ident => $status:ident;)*) => { + $( + $(#[$doc])* + pub fn $name(message: impl Into) -> Self { + Self::builder().message(message).assemble(StatusCode::$status) + } + )* + }; +} + +impl HttpError { + /// Starts building an error. + pub fn builder() -> HttpErrorBuilder { + HttpErrorBuilder::default() + } + + /// An error with this status and message and every other member defaulted. + /// + /// # Errors + /// + /// [`InvalidStatus`] when the status is not from 400 to 599. + pub fn new>( + status: S, + message: impl Into, + ) -> Result { + Self::builder().status(status).message(message).build() + } + + shortcuts! { + /// A 400 Bad Request whose message is its detail. + bad_request => BAD_REQUEST; + /// A 401 Unauthorized whose message is its detail. + unauthorized => UNAUTHORIZED; + /// A 403 Forbidden whose message is its detail. + forbidden => FORBIDDEN; + /// A 404 Not Found whose message is its detail. + not_found => NOT_FOUND; + /// A 409 Conflict whose message is its detail. + conflict => CONFLICT; + /// A 422 Unprocessable Content whose message is its detail. + unprocessable_content => UNPROCESSABLE_ENTITY; + /// A 429 Too Many Requests whose message is its detail. + too_many_requests => TOO_MANY_REQUESTS; + /// A 500 Internal Server Error whose message stays private. + internal => INTERNAL_SERVER_ERROR; + /// A 503 Service Unavailable whose message stays private. + service_unavailable => SERVICE_UNAVAILABLE; + } + + /// An unexposed 500 for an unexpected failure: the failure's text becomes + /// the private message and the failure becomes the [`source`](Error::source). + /// + /// ``` + /// use std::error::Error; + /// use udibo_http_error::HttpError; + /// + /// let io = std::io::Error::other("disk full"); + /// let error = HttpError::from_error(io); + /// assert_eq!(error.status().as_u16(), 500); + /// assert_eq!(error.message(), "disk full"); + /// assert!(error.source().is_some()); + /// ``` + pub fn from_error(error: impl Into>) -> Self { + let source: Source = Arc::from(error.into()); + Self::builder() + .message(source.to_string()) + .expose(false) + .assemble_with_source(StatusCode::INTERNAL_SERVER_ERROR, source) + } + + /// The response status. + pub fn status(&self) -> StatusCode { + self.status + } + + /// The internal message, which may be empty. It reaches the client only as + /// the detail of an exposed error with no explicit detail. + pub fn message(&self) -> &str { + &self.message + } + + /// The problem's `title`. + pub fn title(&self) -> &str { + &self.title + } + + /// The problem's `detail`, the explanation the client sees. + pub fn detail(&self) -> &str { + &self.detail + } + + /// The problem's `type`, when set. + pub fn problem_type(&self) -> Option<&str> { + self.problem_type.as_deref() + } + + /// The problem's `instance`, when set. + pub fn instance(&self) -> Option<&str> { + self.instance.as_deref() + } + + /// The problem's extension members. + pub fn extensions(&self) -> &Map { + &self.extensions + } + + /// The problem's extension members, to change. + pub fn extensions_mut(&mut self) -> &mut Map { + &mut self.extensions + } + + /// The response headers, which always include `content-type`. + pub fn headers(&self) -> &HeaderMap { + &self.headers + } + + /// The response headers, to change. + pub fn headers_mut(&mut self) -> &mut HeaderMap { + &mut self.headers + } + + /// Whether the message may reach the client. + pub fn expose(&self) -> bool { + self.expose + } + + /// The problem details a client receives as the response body. + pub fn problem_details(&self) -> ProblemDetails { + ProblemDetails { + problem_type: self.problem_type.clone(), + status: self.status.as_u16(), + title: self.title.clone(), + detail: self.detail.clone(), + instance: self.instance.clone(), + extensions: self.extensions.clone(), + } + } +} + +impl HttpErrorBuilder { + fn assemble_with_source(mut self, status: StatusCode, source: Source) -> HttpError { + self.source = Some(source); + self.assemble(status) + } + + pub(crate) fn assemble_unchecked(self, status: StatusCode) -> HttpError { + self.assemble(status) + } +} + +impl fmt::Display for HttpError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if self.message.is_empty() { + f.write_str(&self.detail) + } else { + f.write_str(&self.message) + } + } +} + +impl Error for HttpError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + self.source + .as_deref() + .map(|source| source as &(dyn Error + 'static)) + } +} diff --git a/rust/crates/udibo-http-error/src/lib.rs b/rust/crates/udibo-http-error/src/lib.rs new file mode 100644 index 0000000..67168c7 --- /dev/null +++ b/rust/crates/udibo-http-error/src/lib.rs @@ -0,0 +1,74 @@ +#![cfg_attr(docsrs, feature(doc_cfg))] +//! HTTP errors that serialize to [RFC 9457] problem details. +//! +//! An [`HttpError`] carries a status from 400 to 599, the problem details a +//! client sees (`title`, `detail`, `type`, `instance` and extension members), +//! the response headers, and an internal message for logs that the client sees +//! only when the error is exposed. It behaves like the +//! [`@udibo/http-error`](https://jsr.io/@udibo/http-error) TypeScript package: +//! both pass the same conformance vectors, so the same error produces the same +//! response in either language. +//! +//! ``` +//! use udibo_http_error::HttpError; +//! +//! let error = HttpError::builder() +//! .status(404) +//! .message("No such user.") +//! .extension("code", "user_missing") +//! .build()?; +//! +//! assert_eq!(error.title(), "Not Found"); +//! assert_eq!(error.detail(), "No such user."); +//! assert_eq!( +//! serde_json::to_value(error.problem_details())?, +//! serde_json::json!({ +//! "status": 404, +//! "title": "Not Found", +//! "detail": "No such user.", +//! "code": "user_missing", +//! }), +//! ); +//! # Ok::<(), Box>(()) +//! ``` +//! +//! A server error's message stays private unless the error is exposed: +//! +//! ``` +//! use udibo_http_error::HttpError; +//! +//! let error = HttpError::internal("connection to db-1 refused"); +//! assert_eq!(error.message(), "connection to db-1 refused"); +//! assert_eq!(error.detail(), "The server encountered an unexpected condition."); +//! ``` +//! +//! # Features +//! +//! - `axum`: [`HttpError`] implements axum's `IntoResponse`, answering with its +//! status, headers and an `application/problem+json` body. +//! +//! [RFC 9457]: https://www.rfc-editor.org/rfc/rfc9457 + +mod error; +mod parse; +mod problem; +mod status; + +#[cfg(feature = "axum")] +mod axum; + +pub use error::{HttpError, HttpErrorBuilder, InvalidStatus}; +pub use problem::ProblemDetails; +pub use status::{default_detail, default_title}; + +/// The media type of an RFC 9457 problem details body. +pub const PROBLEM_JSON: &str = "application/problem+json"; + +/// Re-exported so callers can build extensions and headers without adding the +/// crates themselves. +pub use http::{HeaderMap, HeaderName, HeaderValue, StatusCode, header}; +pub use serde_json::{Map, Value}; + +#[cfg(doctest)] +#[doc = include_str!("../README.md")] +struct ReadmeDoctests; diff --git a/rust/crates/udibo-http-error/src/parse.rs b/rust/crates/udibo-http-error/src/parse.rs new file mode 100644 index 0000000..a25059a --- /dev/null +++ b/rust/crates/udibo-http-error/src/parse.rs @@ -0,0 +1,138 @@ +use http::StatusCode; +use serde_json::{Map, Value}; + +use crate::error::HttpError; +use crate::problem::is_standard_member; + +const BYTE_ORDER_MARK: &[u8] = b"\xEF\xBB\xBF"; + +impl HttpError { + /// Reads the error another service answered with: the response's status + /// and its body, ideally RFC 9457 problem details. It never fails, because + /// a broken body is itself an error to report. + /// + /// - The status is the body's `status` when it is an integer from 400 to + /// 599, else the response's status when that is from 400 to 599, else 500. + /// - The body's `detail` becomes the message, so like any message it + /// reaches a client only when the error is exposed: a 5xx problem's + /// detail is replaced by the status's default. + /// - `title`, `type` and `instance` are kept when they are non-empty + /// strings; a member of the wrong JSON type, or `null`, is ignored. Every + /// other member becomes an extension. + /// - A body that is not a JSON object with a non-null `status`, `title` or + /// `type` gives an unexposed error with the default title and detail. + /// + /// ``` + /// use udibo_http_error::HttpError; + /// + /// let error = HttpError::from_problem_body( + /// 403, + /// br#"{"status": 403, "detail": "You cannot edit this project.", "code": "E1"}"#, + /// ); + /// assert_eq!(error.status().as_u16(), 403); + /// assert_eq!(error.detail(), "You cannot edit this project."); + /// assert_eq!(error.extensions()["code"], "E1"); + /// + /// let error = HttpError::from_problem_body(502, b"Bad Gateway"); + /// assert!(!error.expose()); + /// assert_eq!(error.title(), "Bad Gateway"); + /// ``` + pub fn from_problem_body(response_status: u16, body: &[u8]) -> Self { + let body = body.strip_prefix(BYTE_ORDER_MARK).unwrap_or(body); + match serde_json::from_slice::(body) { + Ok(value) => Self::from_problem_value(response_status, value), + Err(_) => not_a_problem(response_status, "The response body is not JSON."), + } + } + + /// Reads the error from a response status and a body already parsed as + /// JSON, by the rules of [`from_problem_body`](Self::from_problem_body). + pub fn from_problem_value(response_status: u16, body: Value) -> Self { + match body { + Value::Object(members) if is_problem(&members) => { + from_problem(response_status, members) + } + _ => not_a_problem( + response_status, + "The response body is not a problem details object.", + ), + } + } +} + +fn is_problem(members: &Map) -> bool { + ["status", "title", "type"] + .iter() + .any(|name| members.get(*name).is_some_and(|value| !value.is_null())) +} + +fn error_status(status: u16) -> Option { + if (400..=599).contains(&status) { + StatusCode::from_u16(status).ok() + } else { + None + } +} + +fn response_error_status(response_status: u16) -> StatusCode { + error_status(response_status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR) +} + +fn body_status(value: &Value) -> Option { + let number = value.as_number()?; + let status = match number.as_u64() { + Some(status) => status, + None => { + let status = number.as_f64()?; + if status.fract() != 0.0 || !(400.0..=599.0).contains(&status) { + return None; + } + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + let status = status as u64; + status + } + }; + error_status(u16::try_from(status).ok()?) +} + +fn string_member(members: &Map, name: &str) -> Option { + members + .get(name) + .and_then(Value::as_str) + .filter(|value| !value.is_empty()) + .map(str::to_owned) +} + +fn from_problem(response_status: u16, members: Map) -> HttpError { + let status = members + .get("status") + .and_then(body_status) + .unwrap_or_else(|| response_error_status(response_status)); + let mut builder = HttpError::builder(); + if let Some(detail) = string_member(&members, "detail") { + builder = builder.message(detail); + } + if let Some(title) = string_member(&members, "title") { + builder = builder.title(title); + } + if let Some(problem_type) = string_member(&members, "type") { + builder = builder.problem_type(problem_type); + } + if let Some(instance) = string_member(&members, "instance") { + builder = builder.instance(instance); + } + builder + .extensions( + members + .into_iter() + .filter(|(name, _)| !is_standard_member(name)), + ) + .assemble_unchecked(status) +} + +fn not_a_problem(response_status: u16, message: &str) -> HttpError { + HttpError::builder() + .message(message) + .expose(false) + .assemble_unchecked(response_error_status(response_status)) +} diff --git a/rust/crates/udibo-http-error/src/problem.rs b/rust/crates/udibo-http-error/src/problem.rs new file mode 100644 index 0000000..7d2a4b2 --- /dev/null +++ b/rust/crates/udibo-http-error/src/problem.rs @@ -0,0 +1,53 @@ +use serde::ser::{Serialize, SerializeMap, Serializer}; +use serde_json::{Map, Value}; + +/// The members of an RFC 9457 problem details object, as an [`HttpError`] +/// sends them. +/// +/// It serializes to the JSON body: `type` and `instance` only when set, then +/// `status`, `title`, `detail` and every extension member except one named +/// like a standard member. +/// +/// [`HttpError`]: crate::HttpError +#[derive(Clone, Debug, PartialEq)] +pub struct ProblemDetails { + /// `type`: a URI reference identifying the problem type. + pub problem_type: Option, + /// `status`: the response status. + pub status: u16, + /// `title`: a short summary of the problem type. + pub title: String, + /// `detail`: an explanation of this occurrence. + pub detail: String, + /// `instance`: a URI reference identifying this occurrence. + pub instance: Option, + /// Extension members. + pub extensions: Map, +} + +pub(crate) const STANDARD_MEMBERS: [&str; 5] = ["type", "status", "title", "detail", "instance"]; + +pub(crate) fn is_standard_member(name: &str) -> bool { + STANDARD_MEMBERS.contains(&name) +} + +impl Serialize for ProblemDetails { + fn serialize(&self, serializer: S) -> Result { + let mut map = serializer.serialize_map(None)?; + if let Some(problem_type) = &self.problem_type { + map.serialize_entry("type", problem_type)?; + } + map.serialize_entry("status", &self.status)?; + map.serialize_entry("title", &self.title)?; + map.serialize_entry("detail", &self.detail)?; + if let Some(instance) = &self.instance { + map.serialize_entry("instance", instance)?; + } + for (name, value) in &self.extensions { + if !is_standard_member(name) { + map.serialize_entry(name, value)?; + } + } + map.end() + } +} diff --git a/rust/crates/udibo-http-error/src/status.rs b/rust/crates/udibo-http-error/src/status.rs new file mode 100644 index 0000000..f0eb6e2 --- /dev/null +++ b/rust/crates/udibo-http-error/src/status.rs @@ -0,0 +1,190 @@ +//! The default title and detail of each error status. + +/// The standard reason phrase and a default explanation for a status, or `None` +/// when the status has no registered name. +fn known(status: u16) -> Option<(&'static str, &'static str)> { + match status { + 400 => Some(( + "Bad Request", + "The server cannot process the request due to a client error.", + )), + 401 => Some(( + "Unauthorized", + "Authentication is required to access this resource.", + )), + 402 => Some(( + "Payment Required", + "Payment is required to access this resource.", + )), + 403 => Some(( + "Forbidden", + "You do not have permission to access this resource.", + )), + 404 => Some(("Not Found", "The requested resource could not be found.")), + 405 => Some(( + "Method Not Allowed", + "The request method is not supported for this resource.", + )), + 406 => Some(( + "Not Acceptable", + "The server cannot produce a response matching the acceptable values.", + )), + 407 => Some(( + "Proxy Authentication Required", + "Proxy authentication is required.", + )), + 408 => Some(( + "Request Timeout", + "The server timed out waiting for the request.", + )), + 409 => Some(( + "Conflict", + "The request conflicts with the current state of the resource.", + )), + 410 => Some(("Gone", "The requested resource is no longer available.")), + 411 => Some(( + "Length Required", + "The request requires a Content-Length header.", + )), + 412 => Some(( + "Precondition Failed", + "A precondition in the request headers was not met.", + )), + 413 => Some(( + "Content Too Large", + "The request body is larger than the server is willing to process.", + )), + 414 => Some(( + "URI Too Long", + "The request URI is longer than the server is willing to process.", + )), + 415 => Some(( + "Unsupported Media Type", + "The request uses a media type that is not supported.", + )), + 416 => Some(( + "Range Not Satisfiable", + "The requested range cannot be satisfied.", + )), + 417 => Some(( + "Expectation Failed", + "The expectation in the Expect header cannot be met.", + )), + 418 => Some(( + "I'm a teapot", + "The server refuses to brew coffee because it is a teapot.", + )), + 421 => Some(( + "Misdirected Request", + "The request was directed at a server unable to produce a response.", + )), + 422 => Some(( + "Unprocessable Content", + "The request was well-formed but contained semantic errors.", + )), + 423 => Some(("Locked", "The requested resource is locked.")), + 424 => Some(( + "Failed Dependency", + "The request failed due to a previous request failure.", + )), + 425 => Some(( + "Too Early", + "The server is unwilling to process a request that might be replayed.", + )), + 426 => Some(( + "Upgrade Required", + "The client must upgrade to a different protocol.", + )), + 428 => Some(("Precondition Required", "The request must be conditional.")), + 429 => Some(( + "Too Many Requests", + "Too many requests have been sent in a given amount of time.", + )), + 431 => Some(( + "Request Header Fields Too Large", + "The request headers are too large.", + )), + 451 => Some(( + "Unavailable For Legal Reasons", + "The resource is unavailable for legal reasons.", + )), + 500 => Some(( + "Internal Server Error", + "The server encountered an unexpected condition.", + )), + 501 => Some(( + "Not Implemented", + "The server does not support the functionality required.", + )), + 502 => Some(( + "Bad Gateway", + "The server received an invalid response from an upstream server.", + )), + 503 => Some(( + "Service Unavailable", + "The server is currently unavailable.", + )), + 504 => Some(( + "Gateway Timeout", + "The server did not receive a timely response from an upstream server.", + )), + 505 => Some(( + "HTTP Version Not Supported", + "The HTTP version used in the request is not supported.", + )), + 506 => Some(( + "Variant Also Negotiates", + "The server has an internal configuration error.", + )), + 507 => Some(( + "Insufficient Storage", + "The server has insufficient storage to complete the request.", + )), + 508 => Some(( + "Loop Detected", + "The server detected an infinite loop while processing the request.", + )), + 510 => Some(( + "Not Extended", + "Further extensions to the request are required.", + )), + 511 => Some(( + "Network Authentication Required", + "Network authentication is required to access this resource.", + )), + _ => None, + } +} + +/// The title an error with this status gets when it has none of its own: the +/// status's reason phrase, else "Unknown Client Error" or "Unknown Server Error". +/// +/// ``` +/// assert_eq!(udibo_http_error::default_title(404), "Not Found"); +/// assert_eq!(udibo_http_error::default_title(499), "Unknown Client Error"); +/// ``` +pub fn default_title(status: u16) -> &'static str { + match known(status) { + Some((title, _)) => title, + None if status < 500 => "Unknown Client Error", + None => "Unknown Server Error", + } +} + +/// The detail an error with this status gets when it has no detail and its +/// message is not exposed: one sentence explaining the status. +/// +/// ``` +/// assert_eq!( +/// udibo_http_error::default_detail(404), +/// "The requested resource could not be found.", +/// ); +/// assert_eq!(udibo_http_error::default_detail(520), "A server error occurred."); +/// ``` +pub fn default_detail(status: u16) -> &'static str { + match known(status) { + Some((_, detail)) => detail, + None if status < 500 => "A client error occurred.", + None => "A server error occurred.", + } +} diff --git a/rust/crates/udibo-http-error/tests/axum.rs b/rust/crates/udibo-http-error/tests/axum.rs new file mode 100644 index 0000000..22f0de8 --- /dev/null +++ b/rust/crates/udibo-http-error/tests/axum.rs @@ -0,0 +1,42 @@ +//! The `axum` feature's `IntoResponse`. +#![cfg(feature = "axum")] + +use axum_core::response::IntoResponse; +use http_body_util::BodyExt; +use serde_json::{Value, json}; +use udibo_http_error::{HeaderValue, HttpError, header}; + +#[tokio::test] +async fn answers_with_the_status_headers_and_problem_body() { + let error = HttpError::builder() + .status(429) + .message("Slow down.") + .header(header::RETRY_AFTER, HeaderValue::from_static("30")) + .extension("limit", 10) + .build() + .unwrap(); + let response = error.into_response(); + assert_eq!(response.status().as_u16(), 429); + assert_eq!( + response.headers()[header::CONTENT_TYPE], + "application/problem+json" + ); + assert_eq!(response.headers()[header::RETRY_AFTER], "30"); + let body = response.into_body().collect().await.unwrap().to_bytes(); + assert_eq!( + serde_json::from_slice::(&body).unwrap(), + json!({ + "status": 429, + "title": "Too Many Requests", + "detail": "Slow down.", + "limit": 10, + }), + ); +} + +#[tokio::test] +async fn keeps_a_server_error_message_out_of_the_body() { + let response = HttpError::internal("password=hunter2").into_response(); + let body = response.into_body().collect().await.unwrap().to_bytes(); + assert!(!String::from_utf8_lossy(&body).contains("hunter2")); +} diff --git a/rust/crates/udibo-http-error/tests/conformance.rs b/rust/crates/udibo-http-error/tests/conformance.rs new file mode 100644 index 0000000..603932b --- /dev/null +++ b/rust/crates/udibo-http-error/tests/conformance.rs @@ -0,0 +1,169 @@ +//! Runs the shared vectors in `conformance/vectors/problem-details.json`. +#![allow(clippy::unwrap_used, clippy::panic, clippy::indexing_slicing)] + +use std::path::PathBuf; + +use serde_json::{Map, Value, json}; +use udibo_http_error::{ + HeaderMap, HeaderName, HeaderValue, HttpError, default_detail, default_title, +}; + +fn vectors() -> Value { + let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../../conformance/vectors/problem-details.json"); + let text = std::fs::read_to_string(&path).unwrap_or_else(|error| { + panic!("read {}: {error}", path.display()); + }); + serde_json::from_str(&text).unwrap() +} + +fn section(name: &str) -> Vec { + vectors()[name].as_array().unwrap().clone() +} + +fn string(input: &Value, name: &str) -> Option { + input + .get(name) + .map(|value| value.as_str().unwrap().to_owned()) +} + +fn build(input: &Value) -> Result { + let mut builder = HttpError::builder(); + if let Some(status) = input.get("status") { + let Some(status) = status + .as_u64() + .and_then(|status| u16::try_from(status).ok()) + else { + return Err("invalid status".to_owned()); + }; + builder = builder.status(status); + } + if let Some(message) = string(input, "message") { + builder = builder.message(message); + } + if let Some(title) = string(input, "title") { + builder = builder.title(title); + } + if let Some(detail) = string(input, "detail") { + builder = builder.detail(detail); + } + if let Some(problem_type) = string(input, "type") { + builder = builder.problem_type(problem_type); + } + if let Some(instance) = string(input, "instance") { + builder = builder.instance(instance); + } + if let Some(extensions) = input.get("extensions") { + builder = builder.extensions(extensions.as_object().unwrap().clone()); + } + if let Some(headers) = input.get("headers") { + let mut map = HeaderMap::new(); + for (name, value) in headers.as_object().unwrap() { + map.insert( + HeaderName::try_from(name.as_str()).unwrap(), + HeaderValue::try_from(value.as_str().unwrap()).unwrap(), + ); + } + builder = builder.headers(map); + } + if let Some(expose) = input.get("expose") { + builder = builder.expose(expose.as_bool().unwrap()); + } + builder.build().map_err(|_| "invalid status".to_owned()) +} + +fn headers_json(headers: &HeaderMap) -> Value { + let mut map = Map::new(); + for (name, value) in headers { + let previous = map.insert(name.as_str().to_owned(), json!(value.to_str().unwrap())); + assert!(previous.is_none(), "header {name} repeats"); + } + Value::Object(map) +} + +#[test] +fn serialize() { + let cases = section("serialize"); + assert!(!cases.is_empty()); + for case in cases { + let name = case["name"].as_str().unwrap(); + let result = build(&case["input"]); + if let Some(error) = case.get("error") { + assert_eq!(result.err().as_deref(), error.as_str(), "{name}"); + continue; + } + let error = result.unwrap_or_else(|reason| panic!("{name}: {reason}")); + let expected = &case["expected"]; + assert_eq!( + json!(error.status().as_u16()), + expected["status"], + "{name}: status" + ); + assert_eq!(json!(error.expose()), expected["expose"], "{name}: expose"); + assert_eq!( + headers_json(error.headers()), + expected["headers"], + "{name}: headers" + ); + assert_eq!( + serde_json::to_value(error.problem_details()).unwrap(), + expected["body"], + "{name}: body", + ); + } +} + +#[test] +fn parse() { + let cases = section("parse"); + assert!(!cases.is_empty()); + for case in cases { + let name = case["name"].as_str().unwrap(); + let input = &case["input"]; + let status = u16::try_from(input["status"].as_u64().unwrap()).unwrap(); + let error = + HttpError::from_problem_body(status, input["body"].as_str().unwrap().as_bytes()); + let expected = &case["expected"]; + assert_eq!( + json!(error.status().as_u16()), + expected["status"], + "{name}: status" + ); + assert_eq!(json!(error.expose()), expected["expose"], "{name}: expose"); + assert_eq!(json!(error.title()), expected["title"], "{name}: title"); + assert_eq!(json!(error.detail()), expected["detail"], "{name}: detail"); + assert_eq!( + error.problem_type().map(|value| json!(value)), + expected.get("type").cloned(), + "{name}: type", + ); + assert_eq!( + error.instance().map(|value| json!(value)), + expected.get("instance").cloned(), + "{name}: instance", + ); + assert_eq!( + Value::Object(error.extensions().clone()), + expected["extensions"], + "{name}: extensions", + ); + } +} + +#[test] +fn defaults() { + let cases = section("defaults"); + assert_eq!(cases.len(), 200); + for case in cases { + let status = u16::try_from(case["status"].as_u64().unwrap()).unwrap(); + assert_eq!(default_title(status), case["title"], "{status}: title"); + assert_eq!(default_detail(status), case["detail"], "{status}: detail"); + let error = HttpError::builder() + .status(status) + .expose(false) + .build() + .unwrap(); + assert_eq!(error.title(), case["title"], "{status}: error title"); + assert_eq!(error.detail(), case["detail"], "{status}: error detail"); + } +} diff --git a/rust/crates/udibo-http-error/tests/http_error.rs b/rust/crates/udibo-http-error/tests/http_error.rs new file mode 100644 index 0000000..23f34ac --- /dev/null +++ b/rust/crates/udibo-http-error/tests/http_error.rs @@ -0,0 +1,183 @@ +//! Behavior beyond the shared conformance vectors. + +use std::error::Error; + +use serde_json::json; +use udibo_http_error::{HeaderValue, HttpError, Map, ProblemDetails, StatusCode, header}; + +#[test] +fn accepts_a_status_code_or_a_number() { + let from_code = HttpError::new(StatusCode::CONFLICT, "Taken.").unwrap(); + let from_number = HttpError::new(409, "Taken.").unwrap(); + assert_eq!(from_code.status(), StatusCode::CONFLICT); + assert_eq!(from_number.status(), StatusCode::CONFLICT); + assert_eq!(from_number.detail(), "Taken."); +} + +#[test] +fn reports_the_refused_status() { + let refused = HttpError::new(StatusCode::OK, "fine").unwrap_err(); + assert_eq!(refused.status(), Some(200)); + assert_eq!( + refused.to_string(), + "invalid error status 200: expected 400 to 599" + ); +} + +#[test] +fn refuses_a_number_that_is_no_http_status() { + let refused = HttpError::new(1000_u16, "x").unwrap_err(); + assert_eq!(refused, HttpError::new(42_u16, "x").unwrap_err()); + assert_eq!(refused.status(), None); + assert_eq!( + refused.to_string(), + "invalid error status: expected 400 to 599" + ); +} + +#[test] +fn shortcuts_expose_client_errors_and_hide_server_errors() { + let cases: [(HttpError, u16, bool); 9] = [ + (HttpError::bad_request("m"), 400, true), + (HttpError::unauthorized("m"), 401, true), + (HttpError::forbidden("m"), 403, true), + (HttpError::not_found("m"), 404, true), + (HttpError::conflict("m"), 409, true), + (HttpError::unprocessable_content("m"), 422, true), + (HttpError::too_many_requests("m"), 429, true), + (HttpError::internal("m"), 500, false), + (HttpError::service_unavailable("m"), 503, false), + ]; + for (error, status, expose) in cases { + assert_eq!(error.status().as_u16(), status); + assert_eq!(error.expose(), expose, "{status}"); + assert_eq!(error.message(), "m"); + assert_eq!(error.detail() == "m", expose, "{status}"); + } +} + +#[test] +fn wraps_an_unexpected_failure_as_a_private_500() { + let error = HttpError::from_error(std::io::Error::other("disk full")); + assert_eq!(error.status(), StatusCode::INTERNAL_SERVER_ERROR); + assert!(!error.expose()); + assert_eq!(error.message(), "disk full"); + assert_eq!(error.to_string(), "disk full"); + assert_eq!( + error.detail(), + "The server encountered an unexpected condition." + ); + assert_eq!(error.source().unwrap().to_string(), "disk full"); +} + +#[test] +fn keeps_a_builder_source() { + let error = HttpError::builder() + .status(502) + .source("upstream reset") + .build() + .unwrap(); + assert_eq!(error.source().unwrap().to_string(), "upstream reset"); + assert!(HttpError::not_found("x").source().is_none()); +} + +#[test] +fn displays_the_detail_when_there_is_no_message() { + assert_eq!( + HttpError::builder() + .status(404) + .build() + .unwrap() + .to_string(), + "The requested resource could not be found.", + ); + assert_eq!(HttpError::internal("secret").to_string(), "secret"); +} + +#[test] +fn sends_an_explicit_empty_detail() { + let error = HttpError::builder() + .status(400) + .message("m") + .detail("") + .build() + .unwrap(); + assert_eq!(error.detail(), ""); +} + +#[test] +fn changes_extensions_and_headers_after_building() { + let mut error = HttpError::builder() + .status(429) + .header(header::RETRY_AFTER, HeaderValue::from_static("30")) + .build() + .unwrap(); + error.extensions_mut().insert("limit".to_owned(), json!(10)); + error + .headers_mut() + .insert(header::RETRY_AFTER, HeaderValue::from_static("60")); + assert_eq!(error.extensions()["limit"], 10); + assert_eq!(error.headers()[header::RETRY_AFTER], "60"); + assert_eq!(error.problem_details().extensions["limit"], 10); +} + +#[test] +fn later_extensions_replace_earlier_ones() { + let error = HttpError::builder() + .status(400) + .extension("code", "a") + .extensions(Map::from_iter([("code".to_owned(), json!("b"))])) + .build() + .unwrap(); + assert_eq!(error.extensions()["code"], "b"); +} + +#[test] +fn serializes_problem_details_without_standard_extension_names() { + let problem = ProblemDetails { + problem_type: Some("/errors/x".to_owned()), + status: 400, + title: "Bad Request".to_owned(), + detail: "Nope.".to_owned(), + instance: Some("/requests/1".to_owned()), + extensions: Map::from_iter([ + ("title".to_owned(), json!("spoofed")), + ("code".to_owned(), json!("E1")), + ]), + }; + assert_eq!( + serde_json::to_string(&problem).unwrap(), + r#"{"type":"/errors/x","status":400,"title":"Bad Request","detail":"Nope.","instance":"/requests/1","code":"E1"}"#, + ); +} + +#[test] +fn reads_a_parsed_json_value() { + let error = HttpError::from_problem_value(400, json!({"title": "Bad Input", "field": "email"})); + assert_eq!(error.title(), "Bad Input"); + assert!(error.expose()); + assert_eq!(error.extensions()["field"], "email"); + + let error = HttpError::from_problem_value(400, json!("text")); + assert!(!error.expose()); + assert_eq!( + error.message(), + "The response body is not a problem details object." + ); +} + +#[test] +fn says_why_a_body_is_not_json() { + let error = HttpError::from_problem_body(404, b""); + assert_eq!(error.message(), "The response body is not JSON."); +} + +#[test] +fn ignores_a_status_too_large_for_a_status_code() { + let error = HttpError::from_problem_body(404, br#"{"status": 70000, "title": "x"}"#); + assert_eq!(error.status().as_u16(), 404); + let error = HttpError::from_problem_body(404, br#"{"status": 4.04e5, "title": "x"}"#); + assert_eq!(error.status().as_u16(), 404); + let error = HttpError::from_problem_body(404, br#"{"status": -404, "title": "x"}"#); + assert_eq!(error.status().as_u16(), 404); +} diff --git a/rust/deny.toml b/rust/deny.toml new file mode 100644 index 0000000..efbe420 --- /dev/null +++ b/rust/deny.toml @@ -0,0 +1,32 @@ +[graph] +all-features = true + +[advisories] +yanked = "deny" +ignore = [] + +[licenses] +confidence-threshold = 0.9 +allow = [ + "Apache-2.0", + "BSD-2-Clause", + "BSD-3-Clause", + "ISC", + "MIT", + "Unicode-3.0", + "Zlib", +] + +[licenses.private] +ignore = true + +[bans] +multiple-versions = "warn" +wildcards = "deny" +allow-wildcard-paths = true + +[sources] +unknown-registry = "deny" +unknown-git = "deny" +allow-registry = ["https://github.com/rust-lang/crates.io-index"] +allow-git = [] diff --git a/rust/release-age-exemptions.json b/rust/release-age-exemptions.json new file mode 100644 index 0000000..23f40f1 --- /dev/null +++ b/rust/release-age-exemptions.json @@ -0,0 +1,3 @@ +{ + "exemptions": [] +} diff --git a/rust/release-plz.toml b/rust/release-plz.toml new file mode 100644 index 0000000..6ab3720 --- /dev/null +++ b/rust/release-plz.toml @@ -0,0 +1,14 @@ +# Releases run only when the repository variable RUST_RELEASE_ENABLED is +# "true" (.github/workflows/rust-release.yml). release-plz reads the +# conventional commits that touch each crate, runs cargo-semver-checks against +# the version on crates.io to pick the bump, and tags `-v`, so +# Rust tags never collide with the TypeScript package's bare version tags. +[workspace] +changelog_update = true +semver_check = true +git_release_enable = true +git_tag_name = "{{ package }}-v{{ version }}" +git_release_name = "{{ package }} v{{ version }}" + +[changelog] +protect_breaking_commits = true diff --git a/rust/rustfmt.toml b/rust/rustfmt.toml new file mode 100644 index 0000000..f3e454b --- /dev/null +++ b/rust/rustfmt.toml @@ -0,0 +1,2 @@ +edition = "2024" +style_edition = "2024" diff --git a/rust/scripts/release-age.test.ts b/rust/scripts/release-age.test.ts new file mode 100644 index 0000000..151a941 --- /dev/null +++ b/rust/scripts/release-age.test.ts @@ -0,0 +1,139 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { describe, it } from "node:test"; + +import { findTooNew, indexPath, main, parseLockfile, publishTime } from "./release-age.ts"; + +const lockfile = `version = 4 + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc" + +[[package]] +name = "udibo-http-error" +version = "0.1.0" + +[[package]] +name = "from-git" +version = "0.2.0" +source = "git+https://github.com/example/from-git#0123" + +[[package]] +name = "sparse" +version = "2.0.0" +source = "sparse+https://index.crates.io/" +`; + +const now = new Date("2026-12-04T12:00:00Z"); + +function index(entries: Record) { + return async (path: string): Promise => { + const lines = entries[path]; + if (!lines) throw new Error(`unexpected path ${path}`); + return lines.map((line) => JSON.stringify(line)).join("\n") + "\n"; + }; +} + +describe("parseLockfile", () => { + it("keeps crates.io packages and drops path and git packages", () => { + assert.deepEqual(parseLockfile(lockfile), [ + { name: "serde", version: "1.0.229" }, + { name: "sparse", version: "2.0.0" }, + ]); + }); +}); + +describe("indexPath", () => { + it("follows the sparse index layout for each name length", () => { + assert.equal(indexPath("a"), "1/a"); + assert.equal(indexPath("ab"), "2/ab"); + assert.equal(indexPath("abc"), "3/a/abc"); + assert.equal(indexPath("Serde_JSON"), "se/rd/serde_json"); + }); +}); + +describe("publishTime", () => { + it("reads the pubtime of the locked version", async () => { + const fetchIndex = index({ + "se/rd/serde": [ + { vers: "1.0.228", pubtime: "2026-01-01T00:00:00Z" }, + { vers: "1.0.229", pubtime: "2026-07-18T23:00:00Z" }, + ], + }); + assert.deepEqual( + await publishTime({ name: "serde", version: "1.0.229" }, fetchIndex), + new Date("2026-07-18T23:00:00Z"), + ); + }); + + it("returns undefined for an entry older than the pubtime field", async () => { + const fetchIndex = index({ "se/rd/serde": [{ vers: "1.0.0" }] }); + assert.equal(await publishTime({ name: "serde", version: "1.0.0" }, fetchIndex), undefined); + }); + + it("throws when the version is missing from the index", async () => { + const fetchIndex = index({ "se/rd/serde": [{ vers: "1.0.0" }] }); + await assert.rejects( + publishTime({ name: "serde", version: "9.9.9" }, fetchIndex), + /serde@9\.9\.9 is not in the crates.io index/, + ); + }); +}); + +describe("findTooNew", () => { + const fetchIndex = index({ + "se/rd/serde": [{ vers: "1.0.229", pubtime: "2026-12-01T12:00:01Z" }], + "sp/ar/sparse": [{ vers: "2.0.0", pubtime: "2026-12-01T12:00:00Z" }], + }); + const crates = parseLockfile(lockfile); + + it("refuses a version one second short of three days and passes one exactly three days old", async () => { + const tooNew = await findTooNew(crates, [], now, fetchIndex); + assert.deepEqual( + tooNew.map((c) => `${c.name}@${c.version}`), + ["serde@1.0.229"], + ); + }); + + it("passes an exempted exact version", async () => { + const exemptions = [{ name: "serde", version: "1.0.229", reason: "advisory fix" }]; + assert.deepEqual(await findTooNew(crates, exemptions, now, fetchIndex), []); + }); + + it("does not exempt another version of the same crate", async () => { + const exemptions = [{ name: "serde", version: "1.0.228", reason: "advisory fix" }]; + assert.equal((await findTooNew(crates, exemptions, now, fetchIndex)).length, 1); + }); +}); + +describe("main", () => { + function workspace(): string { + const dir = mkdtempSync(join(tmpdir(), "release-age-")); + writeFileSync(join(dir, "Cargo.lock"), lockfile); + writeFileSync(join(dir, "release-age-exemptions.json"), '{ "exemptions": [] }'); + return dir; + } + + it("exits 1 when a locked version is too new", async (t) => { + t.mock.method(console, "error", () => {}); + const fetchIndex = index({ + "se/rd/serde": [{ vers: "1.0.229", pubtime: "2026-12-03T00:00:00Z" }], + "sp/ar/sparse": [{ vers: "2.0.0", pubtime: "2026-01-01T00:00:00Z" }], + }); + assert.equal(await main(workspace(), now, fetchIndex), 1); + }); + + it("exits 0 when every locked version is old enough", async (t) => { + t.mock.method(console, "log", () => {}); + const fetchIndex = index({ + "se/rd/serde": [{ vers: "1.0.229", pubtime: "2026-01-01T00:00:00Z" }], + "sp/ar/sparse": [{ vers: "2.0.0" }], + }); + assert.equal(await main(workspace(), now, fetchIndex), 0); + }); +}); diff --git a/rust/scripts/release-age.ts b/rust/scripts/release-age.ts new file mode 100644 index 0000000..06783ea --- /dev/null +++ b/rust/scripts/release-age.ts @@ -0,0 +1,129 @@ +/** + * Refuses a Cargo.lock that holds a crates.io version published less than + * three days ago, the same age the TypeScript package's pnpm + * `minimumReleaseAge` enforces. Run from `rust/`: + * + * node scripts/release-age.ts + * + * An exact `name@version` listed in `release-age-exemptions.json` passes + * regardless of age; an exemption needs the founder's approval. + */ +import { readFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; + +export const MINIMUM_AGE_MS = 3 * 24 * 60 * 60 * 1000; + +const CRATES_IO_SOURCES = new Set([ + "registry+https://github.com/rust-lang/crates.io-index", + "sparse+https://index.crates.io/", +]); + +export interface LockedCrate { + name: string; + version: string; +} + +export interface Exemption extends LockedCrate { + reason: string; +} + +export interface TooNew extends LockedCrate { + published: Date; +} + +/** The crates.io packages a Cargo.lock pins; path and git packages are left out. */ +export function parseLockfile(text: string): LockedCrate[] { + const crates: LockedCrate[] = []; + for (const block of text.split(/^\[\[package\]\]$/m).slice(1)) { + const field = (key: string): string | undefined => + new RegExp(`^${key} = "([^"]*)"$`, "m").exec(block)?.[1]; + const name = field("name"); + const version = field("version"); + const source = field("source"); + if (name && version && source && CRATES_IO_SOURCES.has(source)) { + crates.push({ name, version }); + } + } + return crates; +} + +/** The sparse-index path of a crate, per https://doc.rust-lang.org/cargo/reference/registry-index.html#index-files. */ +export function indexPath(name: string): string { + const lower = name.toLowerCase(); + if (lower.length <= 2) return `${lower.length}/${lower}`; + if (lower.length === 3) return `3/${lower[0]}/${lower}`; + return `${lower.slice(0, 2)}/${lower.slice(2, 4)}/${lower}`; +} + +/** When crates.io published `version` of `name`, or `undefined` when its index entry predates the `pubtime` field. */ +export async function publishTime( + crate: LockedCrate, + fetchIndex: (path: string) => Promise, +): Promise { + const lines = (await fetchIndex(indexPath(crate.name))).split("\n"); + for (const line of lines) { + if (!line) continue; + const entry = JSON.parse(line) as { vers: string; pubtime?: string }; + if (entry.vers === crate.version) { + return entry.pubtime ? new Date(entry.pubtime) : undefined; + } + } + throw new Error(`${crate.name}@${crate.version} is not in the crates.io index`); +} + +/** The locked crates published within `MINIMUM_AGE_MS` of `now` that no exemption names. */ +export async function findTooNew( + crates: readonly LockedCrate[], + exemptions: readonly Exemption[], + now: Date, + fetchIndex: (path: string) => Promise, +): Promise { + const exempt = new Set(exemptions.map((e) => `${e.name}@${e.version}`)); + const checked = await Promise.all( + crates + .filter((crate) => !exempt.has(`${crate.name}@${crate.version}`)) + .map(async (crate) => ({ ...crate, published: await publishTime(crate, fetchIndex) })), + ); + return checked.filter( + (crate): crate is TooNew => + crate.published !== undefined && + now.getTime() - crate.published.getTime() < MINIMUM_AGE_MS, + ); +} + +async function fetchCratesIoIndex(path: string): Promise { + const response = await fetch(`https://index.crates.io/${path}`, { + headers: { "user-agent": "udibo-http-error-release-age-check" }, + }); + if (!response.ok) { + throw new Error(`index.crates.io/${path} answered ${response.status}`); + } + return await response.text(); +} + +/** Checks `Cargo.lock` in `dir` and returns the process exit code. */ +export async function main( + dir: string, + now: Date = new Date(), + fetchIndex: (path: string) => Promise = fetchCratesIoIndex, +): Promise { + const crates = parseLockfile(readFileSync(`${dir}/Cargo.lock`, "utf8")); + const { exemptions } = JSON.parse( + readFileSync(`${dir}/release-age-exemptions.json`, "utf8"), + ) as { exemptions: Exemption[] }; + const tooNew = await findTooNew(crates, exemptions, now, fetchIndex); + for (const crate of tooNew) { + console.error( + `${crate.name}@${crate.version} was published ${crate.published.toISOString()}, less than 3 days ago`, + ); + } + if (tooNew.length === 0) { + console.log(`All ${crates.length} crates.io packages in Cargo.lock are at least 3 days old.`); + return 0; + } + return 1; +} + +if (process.argv[1] === fileURLToPath(import.meta.url)) { + process.exitCode = await main(process.cwd()); +} From 6f75b425afac803c889c6c969d767f800e9cd9a8 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 13:13:13 +0000 Subject: [PATCH 2/7] test(release): allow the Rust release job its crates-io environment The workflow policy test let only ci.yml's release job use an environment or mint an OIDC token. Add rust-release.yml's release job, and pin that it uses the crates-io environment and runs only once RUST_RELEASE_ENABLED is set. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YPqZepyt7atNAZ12qoUeVS --- typescript/scripts/release-config.test.ts | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/typescript/scripts/release-config.test.ts b/typescript/scripts/release-config.test.ts index 20f397d..679ea8a 100644 --- a/typescript/scripts/release-config.test.ts +++ b/typescript/scripts/release-config.test.ts @@ -144,13 +144,14 @@ describe("release job", () => { }); describe("every workflow", () => { - it("runs no job but the release job in an environment", () => { + it("runs no job but the two release jobs in an environment", () => { expect(jobsMatching((job) => environmentName(job) !== undefined)).toEqual([ "ci.yml: release", + "rust-release.yml: release", ]); }); - it("lets no job but the release job mint an OIDC token", () => { + it("lets no job but the two release jobs mint an OIDC token", () => { expect( workflows .filter(({ workflow }) => grantsIdToken(workflow.permissions)) @@ -158,9 +159,18 @@ describe("every workflow", () => { ).toEqual([]); expect(jobsMatching((job) => grantsIdToken(job.permissions))).toEqual([ "ci.yml: release", + "rust-release.yml: release", ]); }); + it("publishes crates only from the crates-io environment, once RUST_RELEASE_ENABLED is set", () => { + const rustRelease = workflows.find( + ({ file }) => file === "rust-release.yml", + )!.workflow.jobs.release!; + expect(environmentName(rustRelease)).toBe("crates-io"); + expect(rustRelease.if).toBe("vars.RUST_RELEASE_ENABLED == 'true'"); + }); + it("runs no workflow on pull_request_target", () => { expect( workflows From c61f278f0fd57c91c7327b0fd24f15aba7affb60 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 04:55:08 +0000 Subject: [PATCH 3/7] test(conformance): pin case-sensitive member names and repeated headers Add vectors for problem members that differ from a standard member only by case (kept as extensions when parsing and serializing) and for a repeated Set-Cookie response header. A vector header value may now be a list of strings for a field sent more than once. The TypeScript and Rust vector readers build and compare every value of a repeated field instead of keeping the last one. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YPqZepyt7atNAZ12qoUeVS --- conformance/README.md | 10 ++- conformance/vectors/problem-details.json | 84 +++++++++++++++++++ rust/crates/udibo-http-error/tests/axum.rs | 32 +++++++ .../udibo-http-error/tests/conformance.rs | 28 +++++-- typescript/src/conformance.test.ts | 38 +++++++-- 5 files changed, 178 insertions(+), 14 deletions(-) diff --git a/conformance/README.md b/conformance/README.md index f08db71..c017e9a 100644 --- a/conformance/README.md +++ b/conformance/README.md @@ -12,10 +12,12 @@ Three sections: `expected` response or an `error`. - `input` members are the error's options: `status`, `message`, `title`, `detail`, `type`, `instance`, `extensions`, `headers` and `expose`. A - missing member means the option is not set. + missing member means the option is not set. A header's value is a string, + or a list of strings for a field sent more than once, in order. - `expected.status` is the response status; `expected.expose` is the error's `expose` value; `expected.headers` is the complete set of response headers, - names lowercased, one value per name (no case repeats a header); + names lowercased, each value a string, or a list of strings in order for a + field sent more than once (`set-cookie`); `expected.body` is the JSON response body. Compare bodies as JSON values: member order is not significant. - `error: "invalid status"` means constructing the error must fail. @@ -36,6 +38,10 @@ The rules the cases pin: set, and so does an empty parsed `title` or `detail`. - An extension named `type`, `status`, `title`, `detail` or `instance` is never serialized. Any other member, `__proto__` included, is. +- JSON member names are case-sensitive: `Status` and `Title` are extensions, + never the problem's `status` or `title`, when parsing and serializing. +- A header field set more than once, such as `set-cookie`, keeps every value in + order. - `content-type` defaults to `application/problem+json`. - Parsing ignores a leading UTF-8 byte-order mark. It takes the body's `status` when it is a JSON number whose value is an integer from 400 to 599 diff --git a/conformance/vectors/problem-details.json b/conformance/vectors/problem-details.json index 809b9e3..9a1b072 100644 --- a/conformance/vectors/problem-details.json +++ b/conformance/vectors/problem-details.json @@ -393,6 +393,59 @@ } } }, + { + "name": "keeps extensions whose names differ from a standard member only by case", + "input": { + "status": 404, + "message": "No such user.", + "extensions": { + "Status": 418, + "Title": "Other" + } + }, + "expected": { + "status": 404, + "expose": true, + "headers": { + "content-type": "application/problem+json" + }, + "body": { + "status": 404, + "title": "Not Found", + "detail": "No such user.", + "Status": 418, + "Title": "Other" + } + } + }, + { + "name": "sends every value of a repeated header in order", + "input": { + "status": 400, + "headers": { + "Set-Cookie": [ + "session=; Path=/; Max-Age=0", + "theme=dark; Path=/; Expires=Wed, 09 Jun 2027 10:18:14 GMT" + ] + } + }, + "expected": { + "status": 400, + "expose": true, + "headers": { + "content-type": "application/problem+json", + "set-cookie": [ + "session=; Path=/; Max-Age=0", + "theme=dark; Path=/; Expires=Wed, 09 Jun 2027 10:18:14 GMT" + ] + }, + "body": { + "status": 400, + "title": "Bad Request", + "detail": "The server cannot process the request due to a client error." + } + } + }, { "name": "refuses status 399", "input": { @@ -696,6 +749,37 @@ } } } + }, + { + "name": "matches standard member names exactly, keeping other cases as extensions", + "input": { + "status": 400, + "body": "{\"status\":404,\"Status\":418,\"title\":\"Report\",\"Title\":\"Other\"}" + }, + "expected": { + "status": 404, + "expose": true, + "title": "Report", + "detail": "The requested resource could not be found.", + "extensions": { + "Status": 418, + "Title": "Other" + } + } + }, + { + "name": "treats a body with only a capitalised Status as not a problem", + "input": { + "status": 400, + "body": "{\"Status\":418}" + }, + "expected": { + "status": 400, + "expose": false, + "title": "Bad Request", + "detail": "The server cannot process the request due to a client error.", + "extensions": {} + } } ], "defaults": [ diff --git a/rust/crates/udibo-http-error/tests/axum.rs b/rust/crates/udibo-http-error/tests/axum.rs index 22f0de8..10c5337 100644 --- a/rust/crates/udibo-http-error/tests/axum.rs +++ b/rust/crates/udibo-http-error/tests/axum.rs @@ -40,3 +40,35 @@ async fn keeps_a_server_error_message_out_of_the_body() { let body = response.into_body().collect().await.unwrap().to_bytes(); assert!(!String::from_utf8_lossy(&body).contains("hunter2")); } + +#[test] +fn sends_every_value_of_a_repeated_header_in_order() { + let mut cookies = udibo_http_error::HeaderMap::new(); + cookies.append( + header::SET_COOKIE, + HeaderValue::from_static("session=; Max-Age=0"), + ); + cookies.append( + header::SET_COOKIE, + HeaderValue::from_static("theme=dark; Expires=Wed, 09 Jun 2027 10:18:14 GMT"), + ); + let response = HttpError::builder() + .status(400) + .headers(cookies) + .build() + .unwrap() + .into_response(); + let values: Vec<&str> = response + .headers() + .get_all(header::SET_COOKIE) + .iter() + .map(|value| value.to_str().unwrap()) + .collect(); + assert_eq!( + values, + [ + "session=; Max-Age=0", + "theme=dark; Expires=Wed, 09 Jun 2027 10:18:14 GMT" + ], + ); +} diff --git a/rust/crates/udibo-http-error/tests/conformance.rs b/rust/crates/udibo-http-error/tests/conformance.rs index 603932b..5e86875 100644 --- a/rust/crates/udibo-http-error/tests/conformance.rs +++ b/rust/crates/udibo-http-error/tests/conformance.rs @@ -59,10 +59,16 @@ fn build(input: &Value) -> Result { if let Some(headers) = input.get("headers") { let mut map = HeaderMap::new(); for (name, value) in headers.as_object().unwrap() { - map.insert( - HeaderName::try_from(name.as_str()).unwrap(), - HeaderValue::try_from(value.as_str().unwrap()).unwrap(), - ); + let values = match value { + Value::Array(values) => values.clone(), + value => vec![value.clone()], + }; + for value in values { + map.append( + HeaderName::try_from(name.as_str()).unwrap(), + HeaderValue::try_from(value.as_str().unwrap()).unwrap(), + ); + } } builder = builder.headers(map); } @@ -74,9 +80,17 @@ fn build(input: &Value) -> Result { fn headers_json(headers: &HeaderMap) -> Value { let mut map = Map::new(); - for (name, value) in headers { - let previous = map.insert(name.as_str().to_owned(), json!(value.to_str().unwrap())); - assert!(previous.is_none(), "header {name} repeats"); + for name in headers.keys() { + let values: Vec = headers + .get_all(name) + .iter() + .map(|value| json!(value.to_str().unwrap())) + .collect(); + let value = match <[Value; 1]>::try_from(values) { + Ok([value]) => value, + Err(values) => Value::Array(values), + }; + map.insert(name.as_str().to_owned(), value); } Value::Object(map) } diff --git a/typescript/src/conformance.test.ts b/typescript/src/conformance.test.ts index c404afd..442c6d9 100644 --- a/typescript/src/conformance.test.ts +++ b/typescript/src/conformance.test.ts @@ -4,13 +4,15 @@ import { describe, expect, it } from "vitest"; import { HttpError, type HttpErrorOptions } from "./mod.ts"; +type VectorHeaders = Record; + interface SerializeCase { name: string; - input: HttpErrorOptions; + input: Omit & { headers?: VectorHeaders }; expected?: { status: number; expose: boolean; - headers: Record; + headers: VectorHeaders; body: Record; }; error?: "invalid status"; @@ -41,16 +43,42 @@ const vectors = JSON.parse( defaults: { status: number; title: string; detail: string }[]; }; +function toOptions({ + headers, + ...input +}: SerializeCase["input"]): HttpErrorOptions { + if (headers === undefined) return input; + const fields = new Headers(); + for (const [name, value] of Object.entries(headers)) { + for (const item of typeof value === "string" ? [value] : value) { + fields.append(name, item); + } + } + return { ...input, headers: fields }; +} + +function fromHeaders(headers: Headers): VectorHeaders { + const fields: VectorHeaders = {}; + for (const [name, value] of headers) { + const previous = fields[name]; + fields[name] = + previous === undefined + ? value + : [...(typeof previous === "string" ? [previous] : previous), value]; + } + return fields; +} + describe("problem-details vectors: serialize", () => { it.each(vectors.serialize.filter((vector) => vector.expected))( "$name", async ({ input, expected }) => { - const error = new HttpError(input); + const error = new HttpError(toOptions(input)); const response = error.getResponse(); expect({ status: response.status, expose: error.expose, - headers: Object.fromEntries(response.headers), + headers: fromHeaders(response.headers), body: await response.json(), }).toEqual(expected); }, @@ -59,7 +87,7 @@ describe("problem-details vectors: serialize", () => { it.each(vectors.serialize.filter((vector) => vector.error))( "$name", ({ input }) => { - expect(() => new HttpError(input)).toThrow(RangeError); + expect(() => new HttpError(toOptions(input))).toThrow(RangeError); }, ); }); From fed05a1a43feb426e30dc8f551483b7a157eb38e Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 05:59:48 +0000 Subject: [PATCH 4/7] test(conformance): pin extension JSON shapes and the number contract Add a parse and a serialize vector carrying an empty object, an empty list, an object keyed "0" and "1", nested false/0/null values, a string ID beyond 2^53, and a title and detail of "0". Document that every package exchanges integers in the I-JSON range exactly, that larger IDs travel as decimal strings, and that no package quotes or rounds a number to match another language. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YPqZepyt7atNAZ12qoUeVS --- conformance/README.md | 13 +++++ conformance/vectors/problem-details.json | 73 ++++++++++++++++++++++++ rust/crates/udibo-http-error/README.md | 6 +- 3 files changed, 91 insertions(+), 1 deletion(-) diff --git a/conformance/README.md b/conformance/README.md index c017e9a..1f8ce29 100644 --- a/conformance/README.md +++ b/conformance/README.md @@ -42,6 +42,19 @@ The rules the cases pin: never the problem's `status` or `title`, when parsing and serializing. - A header field set more than once, such as `set-cookie`, keeps every value in order. +- Extension values keep their JSON type and shape: an empty object stays an + object, an empty list stays a list, an object with keys `"0"` and `"1"` stays + an object, and `false`, `0` and `null` survive inside nested values. A title or + detail of `"0"` is set, not empty. + +## Numbers in extensions + +Every package exchanges integers from -9007199254740991 through +9007199254740991 exactly (the I-JSON range, RFC 7493 §2.2). Outside that range +a package may lose precision: carry a larger ID or counter as a decimal string, +which every package passes through unchanged. A package keeps the caller's JSON +type: it never quotes a number it received, and never rounds one to imitate +another language. The vectors use only integers inside the range. - `content-type` defaults to `application/problem+json`. - Parsing ignores a leading UTF-8 byte-order mark. It takes the body's `status` when it is a JSON number whose value is an integer from 400 to 599 diff --git a/conformance/vectors/problem-details.json b/conformance/vectors/problem-details.json index 9a1b072..1167ac2 100644 --- a/conformance/vectors/problem-details.json +++ b/conformance/vectors/problem-details.json @@ -446,6 +446,52 @@ } } }, + { + "name": "keeps every JSON shape of an extension and a title and detail of \"0\"", + "input": { + "status": 422, + "title": "0", + "detail": "0", + "extensions": { + "empty": {}, + "list": [], + "numbered": { + "0": "first", + "1": "second" + }, + "nested": { + "flag": false, + "count": 0, + "none": null + }, + "recordId": "9007199254740993" + } + }, + "expected": { + "status": 422, + "expose": true, + "headers": { + "content-type": "application/problem+json" + }, + "body": { + "status": 422, + "title": "0", + "detail": "0", + "empty": {}, + "list": [], + "numbered": { + "0": "first", + "1": "second" + }, + "nested": { + "flag": false, + "count": 0, + "none": null + }, + "recordId": "9007199254740993" + } + } + }, { "name": "refuses status 399", "input": { @@ -780,6 +826,33 @@ "detail": "The server cannot process the request due to a client error.", "extensions": {} } + }, + { + "name": "reads every JSON shape of an extension and a title and detail of \"0\"", + "input": { + "status": 400, + "body": "{\"status\":422,\"title\":\"0\",\"detail\":\"0\",\"empty\":{},\"list\":[],\"numbered\":{\"0\":\"first\",\"1\":\"second\"},\"nested\":{\"flag\":false,\"count\":0,\"none\":null},\"recordId\":\"9007199254740993\"}" + }, + "expected": { + "status": 422, + "expose": true, + "title": "0", + "detail": "0", + "extensions": { + "empty": {}, + "list": [], + "numbered": { + "0": "first", + "1": "second" + }, + "nested": { + "flag": false, + "count": 0, + "none": null + }, + "recordId": "9007199254740993" + } + } } ], "defaults": [ diff --git a/rust/crates/udibo-http-error/README.md b/rust/crates/udibo-http-error/README.md index 4b1e38e..d900323 100644 --- a/rust/crates/udibo-http-error/README.md +++ b/rust/crates/udibo-http-error/README.md @@ -41,7 +41,11 @@ assert_eq!(failed.detail(), "The server encountered an unexpected condition."); | `content-type` header | `application/problem+json`. | An extension named `type`, `status`, `title`, `detail` or `instance` is never -serialized, so it cannot replace a standard member. +serialized, so it cannot replace a standard member. Extension values keep +their JSON type. Integers from -9007199254740991 through 9007199254740991 are +exchanged exactly with every other http-error package; send a larger ID or +counter as a decimal string, since the TypeScript package reads JSON numbers as +64-bit floats. ## Responses From da12614f439dba197ee11a751e1858eec7be8a2b Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 06:07:43 +0000 Subject: [PATCH 5/7] test(conformance): use the PHP spike's JSON-shape vectors as written Replace the two rows rebuilt from the spike's description with the candidate rows it published (handoffs/port-spikes/php/candidate-vectors.json in udibo at db369a7). They cover the same shapes; the precision observation stays out of the vectors. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YPqZepyt7atNAZ12qoUeVS --- conformance/vectors/problem-details.json | 52 ++++++++++++------------ 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/conformance/vectors/problem-details.json b/conformance/vectors/problem-details.json index 1167ac2..d3801d1 100644 --- a/conformance/vectors/problem-details.json +++ b/conformance/vectors/problem-details.json @@ -447,46 +447,46 @@ } }, { - "name": "keeps every JSON shape of an extension and a title and detail of \"0\"", + "name": "keeps zero text and extension object and list identities", "input": { - "status": 422, + "status": 400, "title": "0", - "detail": "0", + "message": "0", "extensions": { - "empty": {}, - "list": [], - "numbered": { + "context": {}, + "tags": [], + "labels": { "0": "first", "1": "second" }, - "nested": { - "flag": false, + "metadata": { + "enabled": false, "count": 0, - "none": null + "note": null }, "recordId": "9007199254740993" } }, "expected": { - "status": 422, + "status": 400, "expose": true, "headers": { "content-type": "application/problem+json" }, "body": { - "status": 422, + "status": 400, "title": "0", "detail": "0", - "empty": {}, - "list": [], - "numbered": { + "context": {}, + "tags": [], + "labels": { "0": "first", "1": "second" }, - "nested": { - "flag": false, + "metadata": { + "enabled": false, "count": 0, - "none": null + "note": null }, "recordId": "9007199254740993" } @@ -828,27 +828,27 @@ } }, { - "name": "reads every JSON shape of an extension and a title and detail of \"0\"", + "name": "retains the nonempty string zero and nested JSON kinds", "input": { "status": 400, - "body": "{\"status\":422,\"title\":\"0\",\"detail\":\"0\",\"empty\":{},\"list\":[],\"numbered\":{\"0\":\"first\",\"1\":\"second\"},\"nested\":{\"flag\":false,\"count\":0,\"none\":null},\"recordId\":\"9007199254740993\"}" + "body": "{\"title\":\"0\",\"detail\":\"0\",\"context\":{},\"tags\":[],\"labels\":{\"0\":\"first\",\"1\":\"second\"},\"metadata\":{\"enabled\":false,\"count\":0,\"note\":null},\"recordId\":\"9007199254740993\"}" }, "expected": { - "status": 422, + "status": 400, "expose": true, "title": "0", "detail": "0", "extensions": { - "empty": {}, - "list": [], - "numbered": { + "context": {}, + "tags": [], + "labels": { "0": "first", "1": "second" }, - "nested": { - "flag": false, + "metadata": { + "enabled": false, "count": 0, - "none": null + "note": null }, "recordId": "9007199254740993" } From 057969c15164e90af7a39a4c369f526e0d602bc7 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 13:34:34 +0000 Subject: [PATCH 6/7] docs(conformance): keep the parsing rules in one list above the number contract Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YPqZepyt7atNAZ12qoUeVS --- conformance/README.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/conformance/README.md b/conformance/README.md index 1f8ce29..c4dd7f1 100644 --- a/conformance/README.md +++ b/conformance/README.md @@ -46,15 +46,6 @@ The rules the cases pin: object, an empty list stays a list, an object with keys `"0"` and `"1"` stays an object, and `false`, `0` and `null` survive inside nested values. A title or detail of `"0"` is set, not empty. - -## Numbers in extensions - -Every package exchanges integers from -9007199254740991 through -9007199254740991 exactly (the I-JSON range, RFC 7493 §2.2). Outside that range -a package may lose precision: carry a larger ID or counter as a decimal string, -which every package passes through unchanged. A package keeps the caller's JSON -type: it never quotes a number it received, and never rounds one to imitate -another language. The vectors use only integers inside the range. - `content-type` defaults to `application/problem+json`. - Parsing ignores a leading UTF-8 byte-order mark. It takes the body's `status` when it is a JSON number whose value is an integer from 400 to 599 @@ -65,3 +56,12 @@ another language. The vectors use only integers inside the range. detail is replaced by the default. - A body that is not a JSON object with a non-null `status`, `title` or `type` member gives an unexposed error with the default title and detail. + +## Numbers in extensions + +Every package exchanges integers from -9007199254740991 through +9007199254740991 exactly (the I-JSON range, RFC 7493 §2.2). Outside that range +a package may lose precision: carry a larger ID or counter as a decimal string, +which every package passes through unchanged. A package keeps the caller's JSON +type: it never quotes a number it received, and never rounds one to imitate +another language. The vectors use only integers inside the range. From 0dd828154b5602070778e9228990ce40b8fbd874 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 16:23:32 +0000 Subject: [PATCH 7/7] test(conformance): pin literal extension keys and a top-level null Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YPqZepyt7atNAZ12qoUeVS --- conformance/vectors/problem-details.json | 27 ++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/conformance/vectors/problem-details.json b/conformance/vectors/problem-details.json index d3801d1..21f5c4c 100644 --- a/conformance/vectors/problem-details.json +++ b/conformance/vectors/problem-details.json @@ -519,6 +519,33 @@ "status": 404.5 }, "error": "invalid status" + }, + { + "name": "preserves literal extension keys and a top-level null", + "input": { + "status": 404, + "message": "No such user.", + "extensions": { + "displayName": "first", + "display_name": "second", + "optionalLabel": null + } + }, + "expected": { + "status": 404, + "expose": true, + "headers": { + "content-type": "application/problem+json" + }, + "body": { + "status": 404, + "title": "Not Found", + "detail": "No such user.", + "displayName": "first", + "display_name": "second", + "optionalLabel": null + } + } } ], "parse": [