[api] implement endpoints per openapi.yaml #8

Merged
nicolas_naranjo merged 1 commit from agent/api into master 2026-10-23 21:49:00 -05:00
Owner

Closes #1 — fulfills the [agent] api brief in docs/TASKS.md.

What changed

Scope: crates/rgxr-api/ + new top-level migrations/ (nothing else; Cargo.lock updated only from the new deps declared inside crates/rgxr-api/Cargo.toml).

  • Stack: axum 0.8 + sqlx 0.8 (postgres, runtime queries — no DATABASE_URL needed at build), tokio, tracing, uuid v7. New deps (sqlx, tower-http, chrono; dev: tower, http-body-util) are declared in my crate's [dependencies] with explicit versions, root Cargo.toml untouched.
  • migrations/0001_automata.sql (repo root, as briefed): automata table + automata_owner_updated_at_idx index. Embedded with sqlx::migrate!("../../migrations"), applied on startup; if the DB isn't reachable yet (compose/k8s cold start) a background task retries with backoff so a pod that boots before postgres self-heals.
  • Identity extractor (src/identity.rs): reads Remote-User / Remote-Name / Remote-Email / Remote-Groups (comma-separated), implements FromRequestParts<AppState> so handlers stay clean. Missing header → 401 envelope in prod, anonymous fallback when RGXR_DEV_MODE=true. Empty/whitespace header values are treated as missing.
  • Automata CRUD (src/automata.rs): GET/POST /api/v1/automata, GET/PUT/DELETE /api/v1/automata/{id}, fully real against Postgres. Every query is scoped to Remote-User; a foreign row is indistinguishable from a missing one (404). Ids are app-side uuid v7 (time-ordered, index-friendly); the DDL default gen_random_uuid() remains as fallback. layout is opaque JSONB passthrough, never parsed (contract).
  • Engine endpoints (/run, /render, /ops/*, /regex/*): deserialize strictly, validate FAs with rgxr_core::Fa::validate (FaError → 400 invalid_fa, regex variant → invalid_regex), then return 501 internal / "engine pending — see core PR" (see decisions). Each handler is a thin call-site with the exact rgxr_core/rgxr_render one-liner commented in place.
  • /readyz: real SELECT 1 against the pool with a 2 s timeout → 200 {status: ok, db: ok} / 503 {status: unavailable, db: down}; 200 {status: ok, db: unconfigured} when DATABASE_URL is unset. /healthz unchanged (ok).
  • API docs: serves the committed openapi.yaml byte-for-byte at /api-docs/openapi.json (include_str! from repo root via CARGO_MANIFEST_DIR) plus a minimal Scalar UI page at /api-docs (CDN script, spec loaded from the endpoint above). No utoipa — the file is the only source of truth.
  • CORS: only when RGXR_DEV_MODE=true, an AllowOrigin::list allowlist for http://localhost:5173 (+ methods/headers incl. the Remote-* set for direct dev calls). Prod = same-origin behind the proxy, no CORS layer at all. Verified: matching origin gets ACAO, foreign origin gets none.
  • Error envelope everywhere: custom ApiJson<T> extractor maps serde rejections (malformed body, unknown fields, bad types) to 400 invalid_request; unknown routes fall through to the envelope-shaped 404. Panic-free: workspace lints inherited, no unwrap/expect outside #[cfg(test)] (crate-root exemption at src/main.rs).

Gate results

$ cargo fmt --check
(no output — clean)

$ cargo clippy --workspace --all-targets
    Checking rgxr-core v0.1.0
    Checking rgxr-api v0.1.0
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.36s
(no warnings)

$ cargo test --workspace
running 40 tests ... test result: ok. 40 passed; 0 failed   (rgxr-api)
running 7 tests  ... test result: ok. 7 passed; 0 failed    (rgxr-core)

47 tests total, 40 in rgxr-api: identity extractor (dev/prod/empty-header/groups parsing), FaError→envelope mapping (invalid_fa vs invalid_regex, 501 shape), name validation (unicode-aware 1..=200), engine cardinality + latex-gate rules, SavedData strictness, camelCase wire shapes, plus router-level probe tests (401, dev fallback, 501, 400s, 500-without-db, openapi serving).

Beyond unit tests, smoke-tested the built binary against a throwaway postgres:17-alpine container: migrations apply, create/list/get/put/delete round-trip, bob gets 404 on alice's row, readyz flips ok→unconfigured→(down) with the DB's lifecycle, prod mode returns the 401 envelope, CORS verified as above.

Semantic decisions

  1. Engine endpoints return 501 with code internal (interim, as briefed): the frozen ErrorCode enum has no not_implemented variant, so the envelope uses internal while the status is 501. Swapping in the real engine later is a one-line change per handler (call-site left as a comment); the 501s disappear then.
  2. The latex gate ships now: POST /render with engine=latex returns 503 render_unavailable when RGXR_LATEX_ENABLED is unset/false — that behavior is fully specified in openapi.yaml and deployable without the engine, so I implemented it instead of returning 501 for a request the deployment has already ruled out. engine=fast (and the default) → 501 like the rest.
  3. Non-UUID {id} path segments → 404, not 400: the documented response set for GET/DELETE /automata/{id} has no 400, and an id that isn't a uuid cannot exist for any user. (PUT documents 400, but only for body problems — a malformed id still yields 404.)
  4. /readyz with unset DATABASE_URL → 200 {ok, unconfigured} (matching the pre-existing bootstrap behavior): unconfigured ≠ down; the k8s probe only fails when a configured DB is unreachable.
  5. CRUD without a pool → 500 internal with a clear message ("database not configured (DATABASE_URL is unset)"): the service still boots so probes/engine routes//api-docs work in local no-DB dev; there is no documented 503 for these endpoints.
  6. Serde-level body failures are 400 invalid_request; Fa::validate failures are 400 invalid_fa (regex parse → invalid_regex). The strict-schema rule (unknown fields rejected) applies to my input types (SavedData, AutomatonInput, all engine request bodies) in addition to the already-frozen Fa.
  7. Saved documents are NOT validated with Fa::validate on POST/PUT: an editor mid-edit must be able to save a transiently invalid automaton (the brief mandates engine-side validation only). The stored fa is deserialized strictly (shape/type/unknown-field errors are 400), but structural validation is deliberately left to the engine endpoints.
  8. /api-docs/openapi.json serves the YAML bytes as-is with Content-Type: application/yaml — the file's own header comment specifies "serves it as-is"; Scalar and Swagger UI both parse YAML specs regardless of the .json extension.
  9. Prod Remote-* header trust: exactly per contract — no extra hardening (e.g. stripping inbound headers) since the proxy is the only path to the pod; noted here so infra can double-check Traefik doesn't forward client-supplied Remote-* headers.

No blockers. The only cross-agent follow-up: once the core PR lands, the commented call-sites in src/engine.rs get swapped in and the 501s go away (separate small PR).

Closes #1 — fulfills the `[agent] api` brief in `docs/TASKS.md`. ## What changed Scope: `crates/rgxr-api/` + new top-level `migrations/` (nothing else; `Cargo.lock` updated only from the new deps declared inside `crates/rgxr-api/Cargo.toml`). - **Stack**: axum 0.8 + sqlx 0.8 (postgres, runtime queries — no `DATABASE_URL` needed at build), tokio, tracing, uuid v7. New deps (`sqlx`, `tower-http`, `chrono`; dev: `tower`, `http-body-util`) are declared in my crate's `[dependencies]` with explicit versions, root `Cargo.toml` untouched. - **`migrations/0001_automata.sql`** (repo root, as briefed): `automata` table + `automata_owner_updated_at_idx` index. Embedded with `sqlx::migrate!("../../migrations")`, applied on startup; if the DB isn't reachable yet (compose/k8s cold start) a background task retries with backoff so a pod that boots before postgres self-heals. - **Identity extractor** (`src/identity.rs`): reads `Remote-User` / `Remote-Name` / `Remote-Email` / `Remote-Groups` (comma-separated), implements `FromRequestParts<AppState>` so handlers stay clean. Missing header → 401 envelope in prod, `anonymous` fallback when `RGXR_DEV_MODE=true`. Empty/whitespace header values are treated as missing. - **Automata CRUD** (`src/automata.rs`): `GET/POST /api/v1/automata`, `GET/PUT/DELETE /api/v1/automata/{id}`, fully real against Postgres. Every query is scoped to `Remote-User`; a foreign row is indistinguishable from a missing one (404). Ids are app-side uuid v7 (time-ordered, index-friendly); the DDL default `gen_random_uuid()` remains as fallback. `layout` is opaque JSONB passthrough, never parsed (contract). - **Engine endpoints** (`/run`, `/render`, `/ops/*`, `/regex/*`): deserialize strictly, validate FAs with `rgxr_core::Fa::validate` (`FaError` → 400 `invalid_fa`, regex variant → `invalid_regex`), then return **501** `internal` / `"engine pending — see core PR"` (see decisions). Each handler is a thin call-site with the exact `rgxr_core`/`rgxr_render` one-liner commented in place. - **`/readyz`**: real `SELECT 1` against the pool with a 2 s timeout → `200 {status: ok, db: ok}` / `503 {status: unavailable, db: down}`; `200 {status: ok, db: unconfigured}` when `DATABASE_URL` is unset. `/healthz` unchanged (`ok`). - **API docs**: serves the committed `openapi.yaml` byte-for-byte at `/api-docs/openapi.json` (`include_str!` from repo root via `CARGO_MANIFEST_DIR`) plus a minimal Scalar UI page at `/api-docs` (CDN script, spec loaded from the endpoint above). No utoipa — the file is the only source of truth. - **CORS**: only when `RGXR_DEV_MODE=true`, an `AllowOrigin::list` allowlist for `http://localhost:5173` (+ methods/headers incl. the `Remote-*` set for direct dev calls). Prod = same-origin behind the proxy, no CORS layer at all. Verified: matching origin gets ACAO, foreign origin gets none. - **Error envelope everywhere**: custom `ApiJson<T>` extractor maps serde rejections (malformed body, unknown fields, bad types) to `400 invalid_request`; unknown routes fall through to the envelope-shaped 404. Panic-free: workspace lints inherited, no `unwrap`/`expect` outside `#[cfg(test)]` (crate-root exemption at `src/main.rs`). ## Gate results ``` $ cargo fmt --check (no output — clean) $ cargo clippy --workspace --all-targets Checking rgxr-core v0.1.0 Checking rgxr-api v0.1.0 Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.36s (no warnings) $ cargo test --workspace running 40 tests ... test result: ok. 40 passed; 0 failed (rgxr-api) running 7 tests ... test result: ok. 7 passed; 0 failed (rgxr-core) ``` 47 tests total, 40 in `rgxr-api`: identity extractor (dev/prod/empty-header/groups parsing), `FaError`→envelope mapping (`invalid_fa` vs `invalid_regex`, 501 shape), name validation (unicode-aware 1..=200), engine cardinality + latex-gate rules, SavedData strictness, camelCase wire shapes, plus router-level probe tests (401, dev fallback, 501, 400s, 500-without-db, openapi serving). Beyond unit tests, smoke-tested the built binary against a throwaway `postgres:17-alpine` container: migrations apply, create/list/get/put/delete round-trip, `bob` gets 404 on `alice`'s row, readyz flips ok→unconfigured→(down) with the DB's lifecycle, prod mode returns the 401 envelope, CORS verified as above. ## Semantic decisions 1. **Engine endpoints return 501 with code `internal`** (interim, as briefed): the frozen `ErrorCode` enum has no `not_implemented` variant, so the envelope uses `internal` while the status is 501. Swapping in the real engine later is a one-line change per handler (call-site left as a comment); the 501s disappear then. 2. **The latex gate ships now**: `POST /render` with `engine=latex` returns `503 render_unavailable` when `RGXR_LATEX_ENABLED` is unset/false — that behavior is fully specified in openapi.yaml and deployable without the engine, so I implemented it instead of returning 501 for a request the deployment has already ruled out. `engine=fast` (and the default) → 501 like the rest. 3. **Non-UUID `{id}` path segments → 404**, not 400: the documented response set for `GET/DELETE /automata/{id}` has no 400, and an id that isn't a uuid cannot exist for any user. (PUT documents 400, but only for body problems — a malformed id still yields 404.) 4. **`/readyz` with unset `DATABASE_URL` → 200 `{ok, unconfigured}`** (matching the pre-existing bootstrap behavior): `unconfigured` ≠ `down`; the k8s probe only fails when a configured DB is unreachable. 5. **CRUD without a pool → 500 `internal`** with a clear message ("database not configured (DATABASE_URL is unset)"): the service still boots so probes/engine routes/`/api-docs` work in local no-DB dev; there is no documented 503 for these endpoints. 6. **Serde-level body failures are `400 invalid_request`**; `Fa::validate` failures are `400 invalid_fa` (regex parse → `invalid_regex`). The strict-schema rule (unknown fields rejected) applies to my input types (`SavedData`, `AutomatonInput`, all engine request bodies) in addition to the already-frozen `Fa`. 7. **Saved documents are NOT validated with `Fa::validate` on POST/PUT**: an editor mid-edit must be able to save a transiently invalid automaton (the brief mandates engine-side validation only). The stored `fa` is deserialized strictly (shape/type/unknown-field errors are 400), but structural validation is deliberately left to the engine endpoints. 8. **`/api-docs/openapi.json` serves the YAML bytes as-is** with `Content-Type: application/yaml` — the file's own header comment specifies "serves it as-is"; Scalar and Swagger UI both parse YAML specs regardless of the `.json` extension. 9. **Prod `Remote-*` header trust**: exactly per contract — no extra hardening (e.g. stripping inbound headers) since the proxy is the only path to the pod; noted here so infra can double-check Traefik doesn't forward client-supplied `Remote-*` headers. No blockers. The only cross-agent follow-up: once the core PR lands, the commented call-sites in `src/engine.rs` get swapped in and the 501s go away (separate small PR).
api: implement endpoints per openapi.yaml
Some checks failed
ci / rust (pull_request) Failing after 2s
ci / web (pull_request) Successful in 4s
ddb3922f14
- axum 0.8 + sqlx (runtime queries), tokio, tracing; deps added inside
  crates/rgxr-api/Cargo.toml only
- migrations/0001_automata.sql (repo root) embedded via sqlx::migrate!,
  applied on startup with background retry if the db is not up yet
- identity extractor: Remote-User/Name/Email/Groups headers; dev-mode
  anonymous fallback (RGXR_DEV_MODE=true), 401 envelope in prod
- automata CRUD: owner-scoped (foreign rows = 404), uuidv7 app-side,
  name 1..=200 chars, layout opaque jsonb passthrough
- engine endpoints (run/render/ops/regex): validate via
  rgxr_core::Fa::validate then 501 'engine pending — see core PR';
  latex gate (503 render_unavailable) enforced already; handlers are
  thin call-sites for the core PR one-liners
- /readyz: real SELECT 1 (ok/down), unconfigured without DATABASE_URL
- serves committed openapi.yaml at /api-docs/openapi.json + Scalar UI
  at /api-docs
- CORS: http://localhost:5173 allowlist only in dev mode
- 40 tests: identity extractor (dev/prod), FaError mapping, name
  validation, engine cardinality/gates, router-level probe tests

Closes #1
nicolas_naranjo deleted branch agent/api 2026-10-23 21:49:00 -05:00
Sign in to join this conversation.
No reviewers
No labels
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
k8s-services/rgxr!8
No description provided.