diff --git a/.gitea/workflows/README.md b/.gitea/workflows/README.md index 7e6e811..d1661e0 100644 --- a/.gitea/workflows/README.md +++ b/.gitea/workflows/README.md @@ -8,6 +8,8 @@ Job responsibilities: 2. `login`: pinned pnpm workspace frozen install, proto/client/Login build and upstream unit checks. 3. `backend`: install Git before Alpine `checkout`, Docker daemon preflight, disposable local-only P02 ZITADEL Compose, ready/discovery/JWKS smoke and safe cleanup. **Full interactive OIDC login is NOT certified.** +**P05-CI-02 additions:** Account Portal CI negative route/API smoke, npm/pnpm structured Moderate advisory detail, and disposable Postgres restart persistence plus stronger OIDC issuer/JWKS negative checks. Full authenticated user sign-in/MFA remains deferred; only CI success counts as verified. + **Run #81 evidence:** backend's first revision failed during checkout because Alpine had no Git. Added a pre-checkout Git installation afterward; the corrected backend job remains **UNVERIFIED** until a separately approved CI rerun. See `docs/P05-CI-01.md`. A green job indicates only its executed steps. Full CI acceptance also needs end-to-end OIDC session/callback, real login/MFA, admin console and session controls in a disposable environment, documented separately. diff --git a/.gitea/workflows/p05-ci.yml b/.gitea/workflows/p05-ci.yml index d57fc8a..82cc383 100644 --- a/.gitea/workflows/p05-ci.yml +++ b/.gitea/workflows/p05-ci.yml @@ -32,6 +32,21 @@ jobs: npm run typecheck npm run build echo ZITPLANE_ACCOUNT_BUILD_PASS + - name: Negative account API and protected page smoke (no real login) + working-directory: users/ui + run: | + set -eu + export AUTH_SECRET="$(node -e "process.stdout.write(require('node:crypto').randomBytes(48).toString('base64url'))")" + export AUTH_URL=https://localhost:3001 + export AUTH_TRUST_HOST=true + export ZITADEL_ISSUER=https://zitadel-ci.invalid + export ZITADEL_CLIENT_ID=disposable-negative-only + export ZITADEL_CLIENT_SECRET=disposable-negative-only + npm run start -- -p 3001 > /tmp/zitplane-account-server.log 2>&1 & + server_pid=$! + trap 'kill "$server_pid" 2>/dev/null || true' EXIT + python3 ../../tests/ci/account_negative.py + echo ZITPLANE_ACCOUNT_NEGATIVE_ACCESS_PASS login: name: Upstream Login V2 frozen workspace build @@ -88,6 +103,10 @@ jobs: set -eu npm audit --omit=dev --audit-level=high echo ZITPLANE_ACCOUNT_ADVISORY_GATE_PASS + # Advisory collection is non-mutating; tolerate moderate-only exit 1, + # but require valid JSON and preserve the HIGH/CRITICAL gate above. + npm audit --omit=dev --json > /tmp/zitplane-npm-audit.json || true + python3 ../../tests/ci/advisory_triage.py npm /tmp/zitplane-npm-audit.json - name: Login workspace production dependency advisories (high and critical) working-directory: auth/ui/v2 run: | @@ -96,6 +115,8 @@ jobs: corepack prepare pnpm@10.30.3 --activate pnpm audit --prod --audit-level high echo ZITPLANE_LOGIN_ADVISORY_GATE_PASS + pnpm audit --prod --json > /tmp/zitplane-pnpm-audit.json || true + python3 ../../../tests/ci/advisory_triage.py pnpm /tmp/zitplane-pnpm-audit.json backend: name: Disposable ZITADEL Docker and OIDC discovery @@ -124,6 +145,11 @@ jobs: echo '::error::CI local network already exists; refusing to touch another stack' exit 1 fi + project="zitplane-p05-${GITHUB_RUN_ID:-0}" + if docker ps -a --filter "label=com.docker.compose.project=$project" -q | grep -q .; then + echo '::error::Disposable CI project already exists; refusing takeover' + exit 1 + fi echo ZITPLANE_DOCKER_PREFLIGHT_PASS - name: Start disposable backend and verify OIDC discovery/JWKS run: | @@ -135,6 +161,20 @@ jobs: touch .p05-ci-started docker compose --env-file .env -p "$project" -f deployment/docker/compose.backend.dev.yaml up -d --wait docker compose --env-file .env -p "$project" -f deployment/docker/compose.backend.dev.yaml ps + # The disposable Postgres volume must retain independently written data + # after a database-container restart; this is NOT a production migration. + docker compose --env-file .env -p "$project" -f deployment/docker/compose.backend.dev.yaml \ + exec -T postgres psql -U zitadel -d postgres -v ON_ERROR_STOP=1 \ + -c 'CREATE TABLE IF NOT EXISTS public.zitplane_ci_persist(marker text PRIMARY KEY)' + docker compose --env-file .env -p "$project" -f deployment/docker/compose.backend.dev.yaml \ + exec -T postgres psql -U zitadel -d postgres -v ON_ERROR_STOP=1 \ + -c "INSERT INTO public.zitplane_ci_persist(marker) VALUES ('p05-$project') ON CONFLICT DO NOTHING" + docker compose --env-file .env -p "$project" -f deployment/docker/compose.backend.dev.yaml restart postgres + docker compose --env-file .env -p "$project" -f deployment/docker/compose.backend.dev.yaml up -d --wait + marker="$(docker compose --env-file .env -p "$project" -f deployment/docker/compose.backend.dev.yaml \ + exec -T postgres psql -U zitadel -d postgres -tAc 'SELECT marker FROM public.zitplane_ci_persist LIMIT 1')" + test "$marker" = "p05-$project" + echo ZITPLANE_POSTGRES_RESTART_PERSISTENCE_PASS docker run --rm --network zitplane-backend-dev-internal \ -e ZITPLANE_CI_PROXY=http://proxy \ python:3.12-alpine python -c "$(cat tests/ci/oidc_discovery.py)" @@ -144,9 +184,14 @@ jobs: if: always() run: | set +e + cleanup_rc=0 if [ -f .p05-ci-started ] && [ -f .env ]; then project="zitplane-p05-${GITHUB_RUN_ID:-0}" - docker compose --env-file .env -p "$project" -f deployment/docker/compose.backend.dev.yaml down -v --remove-orphans + docker compose --env-file .env -p "$project" -f deployment/docker/compose.backend.dev.yaml down -v --remove-orphans || cleanup_rc=1 fi rm -f .env .p05-ci-started + if [ "$cleanup_rc" -ne 0 ]; then + echo '::error::Disposable Docker cleanup failed; operator must inspect exact CI-owned resources' + exit 1 + fi echo ZITPLANE_DISPOSABLE_CLEANUP_COMPLETE diff --git a/README.md b/README.md index bcf7611..597aa57 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,8 @@ Compact, developer-friendly monorepo for a central identity service, a branded l - **P02 ZITADEL local backend:** pinned official images, development Compose and secure local bootstrap helper source prepared. **Docker startup and Admin Console integration remain unverified**; all follow-up local testing is explicitly deferred to a future Gitea Actions scope. - **P03 Login V2 source:** official v4.20.4 source and matching client/proto workspace imported under `auth/ui/v2/`; no redesign or runtime build/test was performed. **CI validation remains pending.** - **P04 Account Portal:** Next.js + ZITADEL OIDC Auth.js source, server-protected overview/profile/security pages and compact responsive foundation implemented under `users/ui/`. **No build/test/runtime validation yet; future Gitea Actions required.** -- **P05-CI-01:** Manual Gitea Run #81 completed **overall FAILURE**: Login V2 build + 1219 unit tests PASS, security high/critical gate PASS (18 moderate findings unresolved), Account Auth.js typecheck FAIL, and Docker job checkout FAIL before backend startup. In-scope Git checkout prerequisite was fixed afterward without a rerun. Full acceptance/interactive OIDC E2E remains pending; see `docs/P05-CI-01.md`. +- **P05-CI-01:** Manual Gitea Run #81 **overall FAILURE**: Login V2 build + 1219 unit tests PASS, high/critical gate PASS (18 Moderate Login findings), Account Auth.js TS2345 and Docker checkout FAIL. Details: `docs/P05-CI-01.md`. +- **P05-CI-02:** Narrow Auth.js JWT subject typing correction and a single-run Gitea verification enhancement for anonymous Account access, disposable PostgreSQL restart, OIDC discovery/JWKS negative cases and per-advisory triage. **Acceptance pending CI results**, full interactive user login/MFA E2E excluded. Details: `docs/P05-CI-02.md`. - **Production / Coolify:** not configured or deployed. ## Documentation and project knowledge diff --git a/docs/FEATURES-STATUS.md b/docs/FEATURES-STATUS.md index a9d0e02..9ff7305 100644 --- a/docs/FEATURES-STATUS.md +++ b/docs/FEATURES-STATUS.md @@ -1,6 +1,6 @@ # ZitPlane - Actual feature availability / limitations -Snapshot: 2026-11-22, P05-CI-01 source preparation based on baseline `7ecf531`. **SOURCE EXISTS != RUNNING != VERIFIED != PRODUCTION**. +Snapshot: 2026-11-22, P05-CI-02 source preparation based on baseline `42adaba`. New patch acceptance pending a focused Gitea Actions run. **SOURCE EXISTS != RUNNING != VERIFIED != PRODUCTION**. | Feature | Source present | CI/build verified | Live/deployed | | --- | --- | --- | --- | diff --git a/docs/MINIFEST.md b/docs/MINIFEST.md index 73d7fc4..b80e378 100644 --- a/docs/MINIFEST.md +++ b/docs/MINIFEST.md @@ -8,6 +8,7 @@ Every file listed below is a direct child of `docs/`. Add/remove rows whenever t | [MINIFEST.md](MINIFEST.md) | Direct-file manifest and phase ownership | DOCS-01 / active | | [USER-GUIDE.md](USER-GUIDE.md) | Source-grounded Account Portal page/button-by-button manual | DOCS-01 / active; runtime pending | | [P05-CI-01.md](P05-CI-01.md) | Gitea Actions manual verification workflow, gates, limitations and real run evidence | P05-CI-01 / Run #81 complete, acceptance blocked | +| [P05-CI-02.md](P05-CI-02.md) | TypeScript remediation, Gitea CI verification, dependency risk and isolation evidence | P05-CI-02 / awaiting CI | | [SETUP-GUIDE.md](SETUP-GUIDE.md) | Operator/developer prerequisites, configs, activation and safety | DOCS-01 / active; runtime pending | | [FEATURES-STATUS.md](FEATURES-STATUS.md) | Exact implemented/unavailable/unverified feature matrix | DOCS-01 / active | | [TROUBLESHOOTING.md](TROUBLESHOOTING.md) | Known blockers and safe diagnosis based on source status | DOCS-01 / active | diff --git a/docs/P05-CI-02.md b/docs/P05-CI-02.md new file mode 100644 index 0000000..74a13c3 --- /dev/null +++ b/docs/P05-CI-02.md @@ -0,0 +1,26 @@ +# ZitPlane P05-CI-02 — Targeted CI acceptance + +**Date:** 2026-11-22 +**Baseline:** `42adaba0044ee5cb86e6e6bcfd4e00e5fe96ad00` +**State:** Source prepared; Gitea acceptance run pending. + +## What changed and why + +- Account Portal's Auth.js `session` callback now narrows the JWT's optional identity subject to a real `string` before computing the valid session identity. The previous code's non-null assertion could infer `{}` and failed TypeScript `TS2345` in Run #81. No login provider flow, PKCE/state/nonce, expiry rule, API guard, password or UI changes. +- Gitea's existing `p05-ci.yml` remains manual only, builds Account Portal with exact npm lock, runs Login V2 frozen build/1,219 upstream unit regressions, collects npm/pnpm advisory metadata, checks disposable Docker readiness/Postgres restart persistence/OIDC metadata/JWKS and always cleans up. +- Source-only/negative contract tests verify untrusted issuer/JWKS rejection; a CI-only started Account Portal checks unauthenticated `/api/account/me` returns 401/no-store and protected `/account` redirects to `/signin`. **No real authenticated user test**. +- Security gate still fails for HIGH/CRITICAL advisories. Separate JSON inventory records Moderate IDs, affected package/range and available patches; **no dependency changes**. + +## How to run + +Gitea > `vibtools/ZitPlane` > Actions > `ZitPlane P05 CI Verification` > Run workflow on `main`. This runs only on a Docker-capable, isolated Gitea runner. It never deploys to Coolify or production identity domains. + +## Status and scope of proof + +A green source/typecheck job does not prove an authenticated OIDC callback or MFA. A green Docker job proves **disposable local** backend readiness/discovery and Postgres persistence only, not Admin Console human login. Full OIDC E2E remains a separate planned scope. + +The workflow uses a fixed P02 dev network, so it refuses to start when that network already exists; it must never stop another owner's containers or volumes. Temporary CI credentials must not appear in logs or the repository. When runner/Compose startup is unavailable, mark **BLOCKED**, not PASS. + +## Actual Gitea run evidence + +**PENDING.** Record run ID/SHA, individual terminal job results, real advisory IDs, persistence/cleanup evidence and exact blockers after the single focused CI cycle. See `notes/P05-CI-02.md` for the detailed phase record. diff --git a/docs/PHASES.md b/docs/PHASES.md index 3012f0a..308576e 100644 --- a/docs/PHASES.md +++ b/docs/PHASES.md @@ -40,6 +40,12 @@ Implement one explicitly approved phase at a time. Keep out-of-scope files, exis - Full OIDC login/session/MFA/Admin Console interactive acceptance is not covered without disposable app/user provisioning; status remains BLOCKED/PENDING, not fabricated PASS. - **Gitea Run #81:** 2 PASS (Login V2 frozen build + 1219/1219 unit tests; high/critical audit) and 2 FAIL (Account Auth.js TypeScript TS2345; Docker Alpine checkout missing Git). 18 moderate advisories unresolved. Pre-checkout Git source fix applied *after* the run, not rerun. See `notes/P05-CI-01.md` and `docs/P05-CI-01.md`. No production deployment/release. +## P05-CI-02 - Targeted Root-Cause Remediation (APPROVED 2026-11-22) +- Baseline `42adaba0044ee5cb86e6e6bcfd4e00e5fe96ad00` (Gitea `main`). +- Narrow write scope: `users/ui/src/auth.ts`, optional `src/types/next-auth.d.ts`, `.gitea/workflows/p05-ci.yml`, `tests/ci/**`, `notes/**`, `project/**`, relevant `docs/**`, associated CI README/MINIFEST, root navigation only if required. +- B01 Auth.js TypeScript TS2345: real subject string narrowing, preserve PKCE/state/nonce, expiry and protected identity guard. B02: verify in-CI Docker checkout, disposable ZITADEL, PostgreSQL restart persistence and OIDC discovery/JWKS. B03: report real Moderate advisory IDs/package/fix; HIGH+ security threshold remains a failure gate. B04: negative OIDC metadata and anonymous Account Portal checks, with interactive user E2E explicitly deferred. +- One focused manually triggered Gitea Actions cycle, no local builds/tests/Docker, no production deployment. Exact result: `notes/P05-CI-02.md`, `docs/P05-CI-02.md`; blocked results remain blocked. + ## P05 - Full Integration (proposed, NOT approved) Shared design system, production-safe Compose topology and verified Login/Account OIDC wiring. No live deployment; separate approval. diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md index c8288ad..9908148 100644 --- a/docs/TROUBLESHOOTING.md +++ b/docs/TROUBLESHOOTING.md @@ -20,6 +20,13 @@ Include environment (local disposable vs CI vs production), exact phase/commit, which page/action, a **redacted** error and reproduction conditions. Never publish `.env`, client secret, passwords, access tokens, cookies, private keys or user data. Link to relevant phase note; record the fix and updated user guidance together. +## P05-CI-02 verification and error boundaries + +- Prior Account Portal `TS2345` at `src/auth.ts(14,61)` in Gitea Run #81 was caused by the callback returning a JWT subject not statically narrowed to `string`. P05-CI-02 source narrows it with `typeof`; it is not considered fixed until CI typecheck/build passes. +- Previous Alpine backend checkout missed Git; current workflow installs Git before checkout. Docker readiness/persistence must be proved by the new CI run, not inferred from this change. +- A green HIGH/CRITICAL advisory audit gate still allows Moderate findings; the P05-CI-02 registry detail report records IDs/package/fix separately, without package upgrades. +- CI negative access tests do not simulate real login; actual OIDC app registration/authorized login/MFA must receive separate approval. + ## Known limitations No live integration verification, Account Portal lockfile, CI pipeline, Coolify production deployment, tested authentication redirects or production support guarantees exist as of P04. Before adding any diagnostic workaround, consult the Scope Lock in `notes/` and preserve ZITADEL's security boundaries. diff --git a/notes/CHANGELOG.md b/notes/CHANGELOG.md index bd30ce7..e1c2a48 100644 --- a/notes/CHANGELOG.md +++ b/notes/CHANGELOG.md @@ -10,5 +10,6 @@ This is the chronological **index**. Phase-specific scope/implementation evidenc | 2026-11-22 | P04 | Account Portal OIDC and protected frontend foundation | `40af500`; patch/scope audit, CI deferred | | 2026-11-22 | DOCS-01 | Knowledge folders, first-party file/function maps, exact source inventory, user guides and mandatory AGENTS documentation policy | Documentation implementation complete; focused manifest/link/scope audit PASS; Git SHA in DOCS-01 local commit, see [DOCS-01.md](DOCS-01.md) | | 2026-11-22 | P05-CI-01 | Gitea verification workflow, dependency lock reconciliation, narrow checkout remediation | Run #81: 2 PASS/2 FAIL; 1219 Login tests PASS, Account TS2345 and Docker checkout blocked; see [P05-CI-01.md](P05-CI-01.md) | +| 2026-11-22 | P05-CI-02 | Narrow Auth.js TS2345 fix, disposable backend persistence/OIDC negative CI and Moderate advisory triage | Implementation in progress; see [P05-CI-02.md](P05-CI-02.md) | Rules: Append new phases or fixes; never silently rewrite a past result. Separate **implemented**, **verified**, **blocked**, and **proposed**. Never log a user secret or personal data. diff --git a/notes/MINIFEST.md b/notes/MINIFEST.md index 845d176..b7bbe28 100644 --- a/notes/MINIFEST.md +++ b/notes/MINIFEST.md @@ -6,6 +6,7 @@ | [MINIFEST.md](MINIFEST.md) | File list and ownership; **MINIFEST is the exact required filename** | DOCS-01 / active | | [DOCS-01.md](DOCS-01.md) | This documentation-governance change: baseline, scope, plan, implementation and closure | DOCS-01 / implementation complete | | [P05-CI-01.md](P05-CI-01.md) | Scope/roots, allowed paths, implementation and Gitea CI acceptance evidence | P05-CI-01 / source complete, CI blockers open | +| [P05-CI-02.md](P05-CI-02.md) | Auth.js narrow patch, isolated Gitea CI gate, advisory triage and exact acceptance evidence | P05-CI-02 / in progress | | [CHANGELOG.md](CHANGELOG.md) | Short append-only chronological phase log and links to detailed reports | DOCS-01 / active | Update this manifest whenever any direct child file or directory changes. Use **actual source state**; a planned file must be labeled planned, not present. diff --git a/notes/P05-CI-02.md b/notes/P05-CI-02.md new file mode 100644 index 0000000..d8a0175 --- /dev/null +++ b/notes/P05-CI-02.md @@ -0,0 +1,36 @@ +# P05-CI-02 — Targeted Remediation & CI Acceptance + +**Date:** 2026-11-22 +**Baseline:** `42adaba0044ee5cb86e6e6bcfd4e00e5fe96ad00` (local `main` = Gitea `main`) +**State:** APPROVED / PRE-CHANGE SCOPE LOCK +**Previous CI evidence:** Gitea Run [#81](https://dev.ivib.cc/vibtools/ZitPlane/actions/runs/81), tested `42b79362c13b9dbb07f85a58ad278742d91b1f5b`, overall FAILURE. + +## Exact approved write scope + +- `users/ui/src/auth.ts` — B01 narrow session callback typing only. +- `users/ui/src/types/next-auth.d.ts` — only if needed; avoid otherwise. +- `.gitea/workflows/p05-ci.yml` — CI isolation/verification/triage/cleanup. +- `tests/ci/**` — focused CI-only OIDC negative/discovery/production and audit scripts, plus README/MINIFEST. +- `notes/**`, `project/**`, relevant `docs/**`, associated `.gitea/**/README.md` and `MINIFEST.md`; root `README.md`, `MINIFEST.md` only as necessary. + +READ ONLY: `core/backend/zitadel/dev.py`, `deployment/docker/compose.backend.dev.yaml`, all `auth/ui/v2/**` original source and lockfile, `users/ui/package.json` / `package-lock.json`, portal UI pages/feature logic and all other files. Preserve unrelated untracked `AI_INSTRUCTIONS.md`. + +**No local builds, local tests, dev servers, Docker, real credentials/users, production deployments, tags or releases.** Source-level preflight/diff is permitted. Only ONE new manually dispatched Gitea CI acceptance cycle; no repeated reruns to chase green checks. + +## Root-cause evidence (before edits) + +- **B01 / TS2345**: Run #81 job 165, `users/ui/src/auth.ts(14,61)` generic NextAuth config callback rejected; downstream `callbacks.session` at lines 50–65 returns inferred `user.id: {}` instead of `string`. The current ternary uses `valid ? token.zitadelSubject! : ""`; the inferred `token.zitadelSubject!` type is not a reliable string despite the boolean `valid` expression. Correct by independently narrowing the JWT subject using `typeof ... === "string"` before constructing the session, and preserve expiry fail-closed. No `as any`, disabling strict mode or weakening route guards. +- **B02 / Docker checkout**: Run #81 job 168 failed in `node:22-alpine` `actions/checkout@v4`: Git missing, archive fallback `Not found`. Current Gitea `main` already has pre-checkout `apk add --no-cache git` at workflow lines 106–110, not yet executed by CI. Current Compose uses fixed local-only network/port; refuse collisions and cleanup ONLY owned disposable project volumes. Verify Postgres volume survives service restart, then readiness, OIDC issuer/discovery/JWKS on disposable network. No edits to Compose or backend helper. +- **B03 / Moderates**: Run #81 job 167 passed HIGH/CRITICAL threshold, but `pnpm audit --prod` reported **18 MODERATE findings**, without individual package/advisory IDs. Account `npm audit` also found **1 MODERATE Next.js issue** with multiple GHSA IDs. Generate structured advisory inventory in CI using registry data, record package/affected range/available fix; no blind dependency upgrades. +- **B04 / OIDC**: `tests/ci/oidc_discovery.py` currently checks ready/discovery/JWKS only, not authenticated user callback, session, MFA or admin login. Add robust negative/issuer/JWKS tests, while keeping real login E2E explicitly BLOCKED until separately approved disposable user/client provisioning. + +## Implementation plan + +1. Narrow `users/ui/src/auth.ts` TypeScript narrowing patch, no auth flow change. Add CI negative contract probes and source contract checks. +2. Strengthen Gitea job: auth typecheck/build, Login frozen build/unit regression, JSON advisory triage alongside existing HIGH+ gates, disposable Docker preflight plus Postgres persistence/ready/discovery/JWKS verification and always cleanup. +3. Ensure job isolation: no shared Docker network/port takeover, no existing project teardown; fail-closed if daemon/capability/isolation unavailable. No real secrets. One CI run, read job logs and exact conclusions. +4. Update `project/`, `docs/`, `notes/`, manifests. Exact scope/security diff audit, Git commit and authorized Gitea `main` push, verify final remote/local SHA. Phase acceptance remains BLOCKED if required gates fail; never claim unexecuted E2E PASS. + +## Verification ledger + +**NOT STARTED.** Record run ID/SHA, exact terminal job statuses, advisory IDs and severity, Docker persistence/cleanup, remaining blockers and final Git SHA only after real evidence is received. diff --git a/project/CHANGELOG.md b/project/CHANGELOG.md index 130805f..c225a89 100644 --- a/project/CHANGELOG.md +++ b/project/CHANGELOG.md @@ -10,6 +10,7 @@ This is the **developer-focused implementation history**. `notes/CHANGELOG.md` i | 2026-11-22 | P04 | `users/ui/` Account Portal OIDC, pages, styling, read-only identity API | `40af500`; `docs/P04-ACCOUNT-PORTAL.md`; no build/CI | | 2026-11-22 | DOCS-01 | Documentation governance; developer architecture, reviewed first-party function/file/page mapping and 701-path source inventory; user manual/setup/status/troubleshooting | Documentation complete; manifest/link/source-scope audit PASS; `notes/DOCS-01.md`, local commit SHA via Git history | | 2026-11-22 | P05-CI-01 | `.gitea/workflows/p05-ci.yml`, `tests/ci/**`, Account npm lock, Login pnpm importer reconciliation and in-scope Alpine Git checkout correction | Run #81 overall FAIL; 2 jobs PASS, 2 FAIL; Login 1219/1219 tests PASS, Account TS2345 and Docker checkout blocked; `notes/P05-CI-01.md` | +| 2026-11-22 | P05-CI-02 | Type-safe Auth.js subject narrowing; Gitea CI negative API/OIDC tests, Postgres restart persistence and Moderate advisory detail inventory | CI result pending; `notes/P05-CI-02.md`, `docs/P05-CI-02.md` | ## Required entry for each future change diff --git a/project/CI-ARCHITECTURE.md b/project/CI-ARCHITECTURE.md index d327831..c034124 100644 --- a/project/CI-ARCHITECTURE.md +++ b/project/CI-ARCHITECTURE.md @@ -37,6 +37,15 @@ The P02 Compose has a fixed named network `zitplane-backend-dev-internal` and lo Reference: `notes/P05-CI-01.md`, `docs/PHASES.md`, `.gitea/workflows/p05-ci.yml`, `tests/ci/`. +## P05-CI-02 Narrow Auth.js and CI additions + +- `users/ui/src/auth.ts` `callbacks.session`: `const subject: string = typeof token.zitadelSubject === "string" ? token.zitadelSubject : "";` explicitly narrows the JWT claim. Session still sets `id` only when subject nonempty and OIDC access-token expiry is in the future. `users/ui/src/types/next-auth.d.ts` was not changed. This addresses Run #81's `TS2345` (`user.id: {}`) without a cast or altered PKCE/state/nonce. +- `tests/ci/account_negative.py` + Account job: anonymous identity API 401/no-store and protected route redirect; no fake logged-in account. `tests/ci/oidc_discovery.py`: issuer/origin/JWKS negative contracts plus actual disposable ready/discovery/JWKS. Tests are CI-only. +- `tests/ci/advisory_triage.py`: parse live npm/pnpm registry JSON into advisory IDs, package, affected range, patch availability. Prior high/critical failure threshold maintained; no dependency versions changed. +- Backend CI: after safe Docker/network preflight and startup, write one marker in **disposable Postgres database `postgres`**, restart its container, verify marker persists and ZITADEL becomes ready, then test OIDC discovery/JWKS. Always cleanup only the current CI Compose project and its volumes; failure must remain visible. +- Corrected Alpine Git checkout from P05-CI-01 is exercised by the new run. Fixed name `zitplane-backend-dev-internal` is a known isolation limitation: existing network triggers fail-closed instead of reuse. +- No full interactive user login callback, MFA, Admin Console user session or production TLS verification; separate future scope. + ## Verified Gitea Run #81 and source follow-up Initial dispatched commit `42b79362c13b9dbb07f85a58ad278742d91b1f5b`. Two PASS: Login V2 frozen reproducible install, production build and 1219/1219 upstream unit tests; dependency advisory gate at high/critical only (18 moderate findings outstanding). Two FAIL: Account Portal TS2345 Auth.js session callback type mismatch; Alpine backend actions/checkout fallback `Not found` because Git missing before checkout. The Docker runtime and full interactive OIDC flow **were not executed**. diff --git a/project/FILE-MAP.md b/project/FILE-MAP.md index 6337a0e..99233f1 100644 --- a/project/FILE-MAP.md +++ b/project/FILE-MAP.md @@ -96,6 +96,17 @@ These paths describe **source**, not a verified running app. Do not infer API co | `project/CI-ARCHITECTURE.md` | Runner/CI security and runtime-verification boundaries | | `notes/P05-CI-01.md`, `docs/P05-CI-01.md` | Pre-change plan and operator-facing CI evidence | +## P05-CI-02 file ownership update + +| Path | Verified narrow function | +| --- | --- | +| `users/ui/src/auth.ts` | `callbacks.session` optional JWT subject type narrowing; no change to provider, policy or PKCE/state/nonce | +| `.gitea/workflows/p05-ci.yml` | CI-only Account negative smoke, Postgres restart persistence, registry advisory JSON collection and cleanup status | +| `tests/ci/account_negative.py` | Anonymous API 401 and protected route redirect CI probe | +| `tests/ci/advisory_triage.py` | Nonmutating npm/pnpm vulnerability inventory with IDs and patch availability | +| `tests/ci/oidc_discovery.py` | Read-only disposable issuer/JWKS negative validation and live metadata smoke | +| `notes/P05-CI-02.md`, `docs/P05-CI-02.md` | Pre-change Scope Lock, actual Gitea CI results and user/operator limitations | + ## Other first-party folders `packages/README.md`: intentionally empty shared-package placeholder, not the upstream `auth/ui/v2/packages/`. diff --git a/project/FUNCTIONS.md b/project/FUNCTIONS.md index 398c4f3..e88a7e9 100644 --- a/project/FUNCTIONS.md +++ b/project/FUNCTIONS.md @@ -65,6 +65,13 @@ `tests/test_backend_dev.py`: `BackendDevContract.test_initialization_is_private_and_idempotent`, `test_compose_local_only_and_version_pinned`, `test_secrets_ignored`. They validate **static P02 contracts**, not real authentication or Docker. +## P05-CI-02 Auth.js and CI helpers + +- `callbacks.session({session, token})` (`users/ui/src/auth.ts`): before populating `Session.user.id`, explicitly narrow optional/unknown JWT claim using `typeof ... === "string"`; only nonempty string + future expiry gives a user ID, otherwise `""`. Fixes TypeScript return typing; protects previously implemented auth behavior. +- `tests/ci/advisory_triage.py`: `read_report` rejects invalid/network-error JSON; `triage_pnpm` lists registry advisory IDs, affected modules/versions and available fixes; `triage_npm` summarizes direct/transitive npm vulnerable packages and their advisory links; `main` dispatches formats. +- `tests/ci/account_negative.py`: `NoRedirect` prevents following protected-account redirects; `main` validates 401/no-store API and redirects for anonymous users against a disposable CI Account Portal instance. +- `tests/ci/oidc_discovery.py`: `verify_metadata` enforces exact disposable issuer/origin for OIDC endpoints, `verify_jwks` rejects empty/malformed public key sets, `verify_negative_contracts` exercises malformed fixtures, `fetch` stays within CI Docker proxy, `main` probes live disposable OIDC. + ## Future update minimum for each function Record: exact path, function name/signature, callers, inputs/outputs, error behavior, security assumptions, user-visible effect, tests/CI reference, phase + commit. Do not speculate from a filename alone. diff --git a/project/SOURCE-INVENTORY.md b/project/SOURCE-INVENTORY.md index e98e1f2..12d926f 100644 --- a/project/SOURCE-INVENTORY.md +++ b/project/SOURCE-INVENTORY.md @@ -1,25 +1,23 @@ # Source inventory ? all Git-tracked paths -**Snapshot:** 2026-11-22, P05-CI-01 staging based on baseline `7ecf531`. Files listed from the local Git index; final Git commit records the snapshot. +**Snapshot:** 2026-11-22, P05-CI-02 staged source on baseline `42adaba`; before final CI acceptance. -**Tracked paths: 714.** Excludes ignored secrets, local builds and untracked `AI_INSTRUCTIONS.md`. +**Exact tracked file paths: 718.** This is a locator and does not assert every upstream file/function was independently audited or tested. Untracked `AI_INSTRUCTIONS.md` and ignored secrets are excluded. -This is an exact **source location inventory**, not an audit of each upstream Login V2 function or proof of CI success. For behavior see `project/FILE-MAP.md`, `project/FUNCTIONS.md` and the phase evidence. - -| Group | Files | Ownership | +| Top-level group | Files | Ownership | | --- | ---: | --- | -| `(repository root)` | 6 | Main Git/project config and documentation navigation | -| `.gitea` | 5 | Gitea CI workflows and owner documentation | -| `auth` | 639 | Pinned upstream Login V2 and dependency workspace | -| `core` | 2 | Official backend orchestration; not Go core source | -| `deployment` | 2 | Local-only P02 Compose | -| `docs` | 13 | User/operator docs and evidence | -| `notes` | 5 | Phase plans and logs | -| `packages` | 1 | Future first-party shared component placeholder | -| `project` | 10 | Developer knowledge and source inventory | -| `scripts` | 1 | Future development script placeholder | -| `tests` | 6 | P02 static and P05 CI-only verification scripts | -| `users` | 24 | P04 Account Portal and P05 lockfile | +| `(repository root)` | 6 | Git-tracked content | +| `.gitea` | 5 | Gitea manual CI files | +| `auth` | 639 | Original Login V2 upstream imports | +| `core` | 2 | ZITADEL backend orchestration | +| `deployment` | 2 | Dev-only Docker Compose | +| `docs` | 14 | Operator/user guides and CI evidence | +| `notes` | 6 | Pre-change plans and phase logs | +| `packages` | 1 | Shared package placeholder | +| `project` | 10 | Developer architecture and source map | +| `scripts` | 1 | Script placeholder | +| `tests` | 8 | Backend and CI scripts | +| `users` | 24 | Account Portal and Auth.js | ## Exact Git-tracked paths @@ -692,7 +690,7 @@ This is an exact **source location inventory**, not an audit of each upstream Lo - `deployment/README.md` - `deployment/docker/compose.backend.dev.yaml` -### docs ? 13 files +### docs ? 14 files - `docs/ARCHITECTURE.md` - `docs/DEVELOPMENT.md` @@ -702,18 +700,20 @@ This is an exact **source location inventory**, not an audit of each upstream Lo - `docs/P03-SOURCE-IMPORT.md` - `docs/P04-ACCOUNT-PORTAL.md` - `docs/P05-CI-01.md` +- `docs/P05-CI-02.md` - `docs/PHASES.md` - `docs/README.md` - `docs/SETUP-GUIDE.md` - `docs/TROUBLESHOOTING.md` - `docs/USER-GUIDE.md` -### notes ? 5 files +### notes ? 6 files - `notes/CHANGELOG.md` - `notes/DOCS-01.md` - `notes/MINIFEST.md` - `notes/P05-CI-01.md` +- `notes/P05-CI-02.md` - `notes/README.md` ### packages ? 1 files @@ -737,11 +737,13 @@ This is an exact **source location inventory**, not an audit of each upstream Lo - `scripts/README.md` -### tests ? 6 files +### tests ? 8 files - `tests/README.md` - `tests/ci/MINIFEST.md` - `tests/ci/README.md` +- `tests/ci/account_negative.py` +- `tests/ci/advisory_triage.py` - `tests/ci/oidc_discovery.py` - `tests/ci/source_contract.py` - `tests/test_backend_dev.py` diff --git a/tests/ci/MINIFEST.md b/tests/ci/MINIFEST.md index febc453..f120fcd 100644 --- a/tests/ci/MINIFEST.md +++ b/tests/ci/MINIFEST.md @@ -5,4 +5,6 @@ | [README.md](README.md) | CI-only test boundaries and safety constraints | P05-CI-01 | | [MINIFEST.md](MINIFEST.md) | Exact tests/ci direct-file register | P05-CI-01 | | [source_contract.py](source_contract.py) | Source and lockfile structural checks, no network/secrets | P05-CI-01 | -| [oidc_discovery.py](oidc_discovery.py) | Disposable ZITADEL ready/discovery/JWKS smoke only | P05-CI-01 | +| [oidc_discovery.py](oidc_discovery.py) | Disposable ZITADEL ready/discovery/JWKS plus malformed issuer/JWKS negative contracts | P05-CI-01/P05-CI-02 | +| [account_negative.py](account_negative.py) | CI-only Account Portal unauthenticated 401/protected redirect smoke | P05-CI-02 | +| [advisory_triage.py](advisory_triage.py) | Extract registry audit advisory IDs/package/range/fix from npm/pnpm JSON | P05-CI-02 | diff --git a/tests/ci/README.md b/tests/ci/README.md index 0c7013c..fd2e869 100644 --- a/tests/ci/README.md +++ b/tests/ci/README.md @@ -3,7 +3,9 @@ This folder contains **CI-only** source/lockfile checks and OIDC discovery smoke support. Run these through the approved `.gitea/workflows/p05-ci.yml` on a disposable Linux runner. - `source_contract.py` checks the narrow P05 source/package constraints and paths. It is not a typecheck or application test. -- `oidc_discovery.py` checks ZITADEL readiness, OIDC discovery, and the public JWKS endpoint on the **disposable** Docker network. It does NOT log in a user, check a real callback, prove protected routes or administer accounts. +- `oidc_discovery.py` checks ZITADEL readiness, OIDC discovery, JWKS and fail-closed issuer/JWKS negative fixtures on the **disposable** Docker network. It does NOT log in a user or check an authenticated callback. +- `account_negative.py` checks that an anonymous Account Portal call returns 401 and that a protected page redirects to `/signin`. It does NOT create a test user or prove real login. +- `advisory_triage.py` summarizes available npm/pnpm registry advisory JSON with IDs, ranges and fixes, without changing dependency versions. No real credentials or production domains are used. Never print bootstrap PATs, admin secrets, session cookies or `.env` contents. Cleanup of disposable volumes is mandatory; never apply `docker compose down -v` to a user's non-CI stack. diff --git a/tests/ci/account_negative.py b/tests/ci/account_negative.py new file mode 100644 index 0000000..cc6ec0f --- /dev/null +++ b/tests/ci/account_negative.py @@ -0,0 +1,58 @@ +"""CI-only negative access checks against a disposable Next.js account server. + +No login, credential acquisition, mock positive authentication or real accounts. +""" +from __future__ import annotations + +import os +import time +from urllib.error import HTTPError, URLError +from urllib.request import build_opener, HTTPRedirectHandler, Request + + +class NoRedirect(HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + return None + + +def main() -> None: + base = os.environ.get("ZITPLANE_CI_ACCOUNT", "http://127.0.0.1:3001") + if base != "http://127.0.0.1:3001": + raise RuntimeError("Account probe must use only CI localhost:3001") + opener = build_opener(NoRedirect()) + # Keep bounded startup polling; every other error is an actual test failure. + deadline = time.monotonic() + 30 + while True: + try: + opener.open(Request(base + "/api/account/me"), timeout=3) + raise AssertionError("Unauthenticated identity API returned 200") + except HTTPError as exc: + if exc.code in (401, 500, 503) and time.monotonic() < deadline and exc.code != 401: + time.sleep(1) + continue + if exc.code != 401: + raise AssertionError(f"Expected API HTTP 401, got {exc.code}") from exc + if "no-store" not in exc.headers.get("Cache-Control", "").lower(): + raise AssertionError("Unauthorized identity response must be no-store") + break + except URLError: + if time.monotonic() >= deadline: + raise + time.sleep(1) + print("ZITPLANE_ACCOUNT_UNAUTHENTICATED_API_401_PASS") + + try: + opener.open(Request(base + "/account"), timeout=8) + raise AssertionError("Unauthenticated account page returned 200") + except HTTPError as exc: + if exc.code not in (302, 303, 307, 308): + raise AssertionError(f"Expected protected redirect, got HTTP {exc.code}") from exc + location = exc.headers.get("Location", "") + if not (location.endswith("/signin") or location == "/signin"): + raise AssertionError("Protected route redirects anywhere other than /signin") + print("ZITPLANE_ACCOUNT_PROTECTED_REDIRECT_PASS") + print("ZITPLANE_INTERACTIVE_LOGIN_E2E_DEFERRED") + + +if __name__ == "__main__": + main() diff --git a/tests/ci/advisory_triage.py b/tests/ci/advisory_triage.py new file mode 100644 index 0000000..7c983e7 --- /dev/null +++ b/tests/ci/advisory_triage.py @@ -0,0 +1,83 @@ +"""Summarize CI registry advisory JSON without changing dependencies. + +npm: audit --omit=dev --json; pnpm: audit --prod --json. +High/critical gating is performed separately by the workflow. +""" +from __future__ import annotations + +import json +from pathlib import Path +import sys + + +def read_report(path: str) -> dict: + report = json.loads(Path(path).read_text(encoding="utf-8")) + if not isinstance(report, dict) or ( + "advisories" not in report and "vulnerabilities" not in report + ): + raise ValueError("Unexpected or incomplete audit JSON; triage cannot pass") + if "error" in report: + raise ValueError("Registry audit reported an error; not a valid pass") + return report + + +def triage_pnpm(report: dict) -> None: + advisories = report.get("advisories") + if not isinstance(advisories, dict): + raise ValueError("Expected pnpm audit advisories map") + counts: dict[str, int] = {} + for identifier, issue in sorted(advisories.items()): + if not isinstance(issue, dict): + raise ValueError(f"Invalid advisory record: {identifier}") + severity = str(issue.get("severity", "unknown")).lower() + counts[severity] = counts.get(severity, 0) + 1 + aid = issue.get("github_advisory_id") or issue.get("url") or identifier + package = issue.get("module_name") or issue.get("name") or "unknown" + affected = issue.get("vulnerable_versions") or "unknown" + fixed = issue.get("patched_versions") or "not provided" + print(f"PNPM_ADVISORY id={aid} package={package} severity={severity} affected={affected} fixed={fixed}") + summary = report.get("metadata", {}).get("vulnerabilities", {}) + print(f"PNPM_ADVISORY_RECORDS={len(advisories)} COUNT_BY_SEVERITY={counts}") + print(f"PNPM_REPORTED_SEVERITIES={summary}") + if sum(counts.values()) != len(advisories): + raise ValueError("Inconsistent advisory record count") + + +def triage_npm(report: dict) -> None: + issues = report.get("vulnerabilities") + if not isinstance(issues, dict): + raise ValueError("Expected npm audit vulnerabilities map") + for name, entry in sorted(issues.items()): + if not isinstance(entry, dict): + raise ValueError(f"Invalid npm record: {name}") + via = entry.get("via", []) + advisories = [ + (item.get("url") or item.get("source") or "unknown") + for item in via if isinstance(item, dict) + ] + print( + f"NPM_VULNERABILITY package={name} severity={entry.get('severity', 'unknown')} " + f"affected={entry.get('range', 'unknown')} fix={entry.get('fixAvailable', 'unknown')} " + f"advisories={advisories}" + ) + print(f"NPM_VULNERABLE_PACKAGE_COUNT={len(issues)}") + print(f"NPM_REPORTED_SEVERITIES={report.get('metadata', {}).get('vulnerabilities', {})}") + + +def main() -> None: + if len(sys.argv) != 3 or sys.argv[1] not in ("npm", "pnpm"): + raise SystemExit("Usage: advisory_triage.py npm|pnpm audit-report.json") + report = read_report(sys.argv[2]) + if sys.argv[1] == "npm": + triage_npm(report) + else: + triage_pnpm(report) + print("ZITPLANE_ADVISORY_TRIAGE_COMPLETE") + + +if __name__ == "__main__": + try: + main() + except (ValueError, OSError, json.JSONDecodeError) as exc: + print(f"ZITPLANE_ADVISORY_TRIAGE_FAILED: {exc}", file=sys.stderr) + raise SystemExit(1) from exc diff --git a/tests/ci/oidc_discovery.py b/tests/ci/oidc_discovery.py index 2bca00f..4b49fd7 100644 --- a/tests/ci/oidc_discovery.py +++ b/tests/ci/oidc_discovery.py @@ -1,4 +1,7 @@ -"""Read-only OIDC smoke: disposable Docker network only; not a login E2E.""" +"""Disposable ZITADEL OIDC metadata/JWKS and fail-closed negative checks. + +No interactive login, account provisioning, MFA or real user sessions. +""" from __future__ import annotations import json @@ -10,30 +13,83 @@ PROXY = os.environ.get("ZITPLANE_CI_PROXY", "http://proxy") EXPECTED_ISSUER = "http://localhost:8080" HOST = "localhost:8080" -def fetch(path: str): + +def verify_metadata(discovery: dict) -> str: + if discovery.get("issuer") != EXPECTED_ISSUER: + raise RuntimeError("OIDC issuer does not match disposable local origin") + for field in ("authorization_endpoint", "token_endpoint", "jwks_uri"): + value = discovery.get(field) + if not isinstance(value, str): + raise RuntimeError(f"OIDC {field} missing") + parsed = urlparse(value) + if ( + parsed.scheme != "http" + or parsed.netloc != "localhost:8080" + or not parsed.path.startswith("/") + or parsed.username or parsed.password + ): + raise RuntimeError(f"OIDC {field} not on the allowed origin") + return urlparse(discovery["jwks_uri"]).path + + +def verify_jwks(jwks: dict) -> None: + keys = jwks.get("keys") + if not isinstance(keys, list) or not keys: + raise RuntimeError("JWKS must contain at least one public key") + for key in keys: + if not isinstance(key, dict) or not key.get("kty"): + raise RuntimeError("JWKS contains an invalid public key") + + +def verify_negative_contracts() -> None: + safe = { + "issuer": EXPECTED_ISSUER, + "authorization_endpoint": EXPECTED_ISSUER + "/oauth/v2/authorize", + "token_endpoint": EXPECTED_ISSUER + "/oauth/v2/token", + "jwks_uri": EXPECTED_ISSUER + "/oauth/v2/keys", + } + for field, dangerous in ( + ("issuer", "http://evil.invalid"), + ("jwks_uri", "https://evil.invalid/keys"), + ("authorization_endpoint", "//evil.invalid/authorize"), + ("token_endpoint", "http://localhost:8080.evil.invalid/token"), + ): + obj = {**safe, field: dangerous} + try: + verify_metadata(obj) + except RuntimeError: + continue + raise AssertionError(f"Unsafe OIDC {field} accepted") + for obj in ({"keys": []}, {"keys": "wrong"}, {"keys": [{}]}): + try: + verify_jwks(obj) + except RuntimeError: + continue + raise AssertionError("Unsafe JWKS payload accepted") + print("ZITPLANE_OIDC_NEGATIVE_CONTRACTS_PASS") + + +def fetch(path: str) -> bytes: + if PROXY != "http://proxy" or not path.startswith("/") or path.startswith("//"): + raise RuntimeError("Only disposable Docker proxy is allowed") request = Request(PROXY + path, headers={"Host": HOST, "Accept": "application/json"}) with urlopen(request, timeout=20) as reply: if reply.status != 200: raise RuntimeError(f"HTTP {reply.status}: {path}") return reply.read() + def main() -> None: + verify_negative_contracts() fetch("/debug/ready") print("ZITPLANE_BACKEND_READY_PASS") discovery = json.loads(fetch("/.well-known/openid-configuration")) - if discovery.get("issuer") != EXPECTED_ISSUER: - raise RuntimeError("OIDC issuer does not match local dev origin") - for field in ("authorization_endpoint", "token_endpoint", "jwks_uri"): - value = discovery.get(field) - if not isinstance(value, str) or not value.startswith(EXPECTED_ISSUER + "/"): - raise RuntimeError(f"Missing/unsafe OIDC {field}") + jwks_path = verify_metadata(discovery) print("ZITPLANE_OIDC_DISCOVERY_PASS") - jwks_path = urlparse(discovery["jwks_uri"]).path - jwks = json.loads(fetch(jwks_path)) - if not isinstance(jwks.get("keys"), list): - raise RuntimeError("Invalid JWKS shape") + verify_jwks(json.loads(fetch(jwks_path))) print("ZITPLANE_OIDC_JWKS_PASS") - print("ZITPLANE_OIDC_INTERACTIVE_E2E_BLOCKED: no disposable OIDC app/user provisioning in P05") + print("ZITPLANE_OIDC_INTERACTIVE_E2E_DEFERRED: no disposable OIDC client/user") + if __name__ == "__main__": main() diff --git a/tests/ci/source_contract.py b/tests/ci/source_contract.py index b1ada7f..9370049 100644 --- a/tests/ci/source_contract.py +++ b/tests/ci/source_contract.py @@ -53,9 +53,18 @@ def check_security_boundaries() -> None: src = (ACCOUNT / "src/auth.ts").read_text(encoding="utf-8") endpoint = (ACCOUNT / "src/app/api/account/me/route.ts").read_text(encoding="utf-8") identity = (ACCOUNT / "src/lib/identity.ts").read_text(encoding="utf-8") - for flag in ('checks: ["pkce", "state", "nonce"]', 'zitadelTokenExpiresAt', 'token.zitadelSubject'): + for flag in ( + 'checks: ["pkce", "state", "nonce"]', + 'typeof token.zitadelSubject === "string"', + 'const subject: string', + 'typeof token.zitadelTokenExpiresAt === "number"', + 'token.zitadelTokenExpiresAt * 1000 > Date.now()', + 'id: valid ? subject : ""', + ): if flag not in src: - fail(f"Missing reviewed OIDC source contract: {flag}") + fail(f"Missing reviewed fail-closed OIDC source contract: {flag}") + if "token.zitadelSubject!" in src or "as any" in src: + fail("Unsafe subject assertion or cast is not allowed") if "session?.user?.id" not in endpoint or "session?.user?.id" not in identity: fail("Protected source must gate on valid user id") print("ZITPLANE_SOURCE_GUARD_CONTRACT_PASS") diff --git a/users/ui/src/auth.ts b/users/ui/src/auth.ts index a44e221..c2ae6e3 100644 --- a/users/ui/src/auth.ts +++ b/users/ui/src/auth.ts @@ -48,19 +48,23 @@ export const { handlers, auth, signIn, signOut } = NextAuth(() => { return token; }, async session({ session, token }) { + // Narrow the untrusted JWT claim to a string before constructing the + // Auth.js Session. A boolean "valid" expression does not narrow the + // original unknown claim in the callback return type (P05-B01 TS2345). + const subject: string = + typeof token.zitadelSubject === "string" ? token.zitadelSubject : ""; const valid = - typeof token.zitadelSubject === "string" && - token.zitadelSubject.length > 0 && + subject.length > 0 && typeof token.zitadelTokenExpiresAt === "number" && token.zitadelTokenExpiresAt * 1000 > Date.now(); - // Never expose an authenticated identity when an OIDC token has expired. - // Every page and API checks nonempty user.id; do not gate on !!session alone. + // Fail closed: expired/missing provider tokens expose no user identity. + // Every page and API checks nonempty user.id, not just !!session. return { ...session, user: { ...session.user, - id: valid ? token.zitadelSubject! : "" + id: valid ? subject : "" } }; }