diff options
| author | Pjotr Prins <pjotr.public01@thebird.nl> | 2026-10-05 07:34:38 +0000 |
|---|---|---|
| committer | Pjotr <wrk@bosa.lan> | 2026-10-05 07:34:38 +0000 |
| commit | 551bb2f8a6aaa420b6bdd4729e4fb2bd2f739b5d (patch) | |
| tree | 716b848dfc15afe785045c43d3f5164739f0c3b9 /docs | |
| parent | 649ff6395bdca06530ceabd3e216c66851dc60d6 (diff) | |
| download | genenetwork4-551bb2f8a6aaa420b6bdd4729e4fb2bd2f739b5d.tar.gz | |
doc: Add auth/testing insights to docs/SKILL.md
Captures the reusable practices from this session's token-gating work, for reuse on a similar Rust/Axum service: - utoipa: a document-wide default security(...) on #[derive(OpenApi)] instead of repeating it per operation, with per-operation empty security() overrides for the exceptions; a shared #[derive(utoipa::IntoResponses)] type for a response shape (e.g. 401) repeated across many handlers, referenced bare in responses(...). - Authentication/authorization: an opt-in-per-handler extractor (AuthToken) over blanket middleware; keeping "is this token valid" and "is this specific resource public" as independent checks; resolving a (container, item)-addressed resource's container category before ever looking up item, rather than guessing item across categories; a dev-only token-issuing endpoint needing at least two independent config conditions (not runtime-detected), registered conditionally rather than registered-and-rejected, with credentials defaulting to the target service's own published dev fixtures. - Testing: a test suite fetching its own token from that dev endpoint (in-process for an in-process Rust suite, via per-test-class subprocess env for a spawned-binary Python suite) instead of requiring a human to provision one; the concurrency hazard of mutating process-wide env vars across #[tokio::test] functions in one file, and why a spawned-subprocess-per-class suite doesn't have it; Rust edition 2024's unsafe env::set_var/remove_var. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01XDDpXvZBQat9uSgDeEMJ8d
Diffstat (limited to 'docs')
| -rw-r--r-- | docs/SKILL.md | 97 |
1 files changed, 97 insertions, 0 deletions
diff --git a/docs/SKILL.md b/docs/SKILL.md index dade13c..1a28a66 100644 --- a/docs/SKILL.md +++ b/docs/SKILL.md @@ -115,6 +115,74 @@ Use `utoipa` + `utoipa-axum`, not a hand-maintained spec file: - This way a route or schema change that doesn't update its `#[utoipa::path]`/`ToSchema` is a compile error or an obviously incomplete diff, not spec drift noticed weeks later. +- When most endpoints require the same thing (a bearer token, an API + key), set it once as the document default -- `#[openapi(security( + ("scheme_name" = [])), ...)]` on the `#[derive(utoipa::OpenApi)]` + struct -- instead of repeating `security(...)` on every + `#[utoipa::path]`. The handful of endpoints that must NOT require it + (health check, version, the endpoint that hands out the credential in + the first place) override with an empty `security()` of their own; + an absent `security(...)` on an operation inherits the document + default, a present-but-empty one overrides to "none" -- standard + OpenAPI semantics, not utoipa-specific. Audit every operation's + resolved `security` in the generated `/openapi.json` after making this + change (`"security": [...]` present vs. absent per operation) -- it's + easy to silently document a public endpoint as requiring auth, or + vice versa, since nothing fails to compile either way. +- A response shape repeated across many handlers (e.g. "401, missing or + invalid token", always the same error body type) doesn't need + hand-copying into every `responses(...)` list: give it its own + `#[derive(utoipa::IntoResponses)] #[response(status = 401, ...)]` + marker struct wrapping the real body type (`struct Unauthorized( + #[to_schema] ApiError)`), then reference it bare inside any handler's + `responses(...)` (`responses(Unauthorized, (status = 200, ...))`). The + marker struct is never constructed at runtime (the actual response + still comes from wherever the rejection/error is produced, e.g. an + extractor's `FromRequestParts` impl) -- `#[allow(dead_code)]` it with + a comment saying why, rather than leaving an unexplained warning or + actually constructing a throwaway value just to silence one. + +## Authentication/authorization + +- Make requiring a token **opt-in per handler**, not a blanket + middleware layer: a custom extractor (`struct AuthToken; impl + FromRequestParts<S> for AuthToken`) that verifies/rejects in + `from_request_parts`. A handler adds `token: AuthToken` (or `_token: + AuthToken` if it only needs the gate, not the claims) to its + parameter list to require one; omitting the parameter is what makes + it optional, with no central route-list to keep in sync. Non-body + extractors like this can go anywhere in the parameter list except + after a body-consuming one (`Json<T>` etc. must stay last). +- If some data is "public" and some isn't, don't let that become "some + endpoints need a token and some don't" -- keep the token check + universal (cheap: local signature verification, no network call) and + make "is this specific resource public" a second, independent + decision the handler makes afterward, with its own cache, only + calling out to an authorization service for the resources that + actually need it. +- A resource addressed by `(container, item)` where `container` can + belong to more than one underlying category (e.g. a "dataset" that's + sometimes one database table, sometimes another) should resolve + `container`'s category **first**, as its own lookup, before ever + looking up `item`. Resolving `item` by guessing across categories + (try category A's lookup, fall back to category B's) risks a same-named + collision silently returning the wrong thing -- resolving `container` + first instead means only a much smaller set of names (containers) is + ever disambiguated across categories, not every item name ever. +- A dev-only endpoint that hands out a credential (e.g. proxies an + auth service's own token grant for a well-known test user) needs at + least two independent config conditions to enable it (e.g. "dev mode + on" AND "bound to loopback only"), not one flag -- and the condition + should be a plain function with its own unit tests + (`Config::dev_token_enabled()`), not inline `if` logic duplicated at + each call site. Register the route conditionally at startup rather + than registering it unconditionally and rejecting inside the + handler: an unregistered route is a 404 and genuinely absent from the + generated OpenAPI spec, so a production deployment doesn't even + document that a token-issuing endpoint could exist. Default any + credentials this endpoint needs to the target service's own published + "dev fixtures" (a well-known test client/user every checkout of that + service already has) so it works with zero extra configuration. ## Testing @@ -148,6 +216,35 @@ Two parallel suites exercising the same endpoints: once per test *file*, not just once overall -- that's expected, not a sign the fix didn't work; what matters is that repeated calls inside one file (or one real server process) stay fast after it. +- If endpoints need a bearer token and the service has a dev-only + token-issuing endpoint (see "Authentication/authorization" above), + have the test suite fetch its own token from it rather than requiring + a human to mint and export one by hand first. Try that first, fall + back to an externally-provided token (an env var) for a setup that + doesn't want dev mode on even for tests -- so the suite still works + unmodified either way. For the in-process Rust suite this means + calling the router's own dev endpoint via the same `oneshot` plumbing + used for every other request; for a suite that spawns the real + binary as a subprocess (Python, here), it means starting that + specific test's subprocess with the dev-mode env vars set so it can + answer its own token request over the same HTTP connection the test + already uses. +- Mutating process-wide state (env vars, global config) from a test is + only safe when nothing else in the same process can read or write + that same state concurrently. A single compiled test binary (one + `tests/*.rs` file) runs its `#[tokio::test]`/`#[test]` functions + concurrently on different threads by default -- so a test that must + flip an env var through several values keeps all of those mutations + in one sequential test function, with a comment saying why, rather + than splitting them across multiple test functions in the same file. + A suite that instead spawns a fresh subprocess per test class (own + process, own env, e.g. Python's `ServerTestCase`) doesn't have this + problem -- each class can set its own env independently and safely. + On edition 2024, `std::env::set_var`/`remove_var` are `unsafe fn` + (exactly because of this hazard); wrap each call in its own tiny + `unsafe { ... }` with a `// SAFETY:` comment pointing at whichever of + the two guarantees above makes it sound here, rather than one broad + `unsafe` block around unrelated code. ## Guix packaging |
