# Functions, API handlers and important logic — reviewed first-party source **Scope:** ZitPlane-owned P02 backend helper and P04 Account Portal at baseline `40af500`. Imported Login V2 upstream functions are **not invented or paraphrased**; consult the exact paths in `auth/ui/v2/` and the full tracked-file inventory in `SOURCE-INVENTORY.md`. On an approved future Login UI change, add a reviewed function entry here with signature, inputs/outputs and caller. ## Python backend helper: `core/backend/zitadel/dev.py` | Function / entry | Purpose / input-output | Used from / protection | | --- | --- | --- | | `random_chars(alphabet, length)` | Uses Python `secrets.choice` to create unpredictable strings | Called when generating initial local dev credentials | | `create_dev_env()` | Creates ignored root `.env` **once** with random Postgres password, 32-char ZITADEL master key, initial admin password and Login session cookie secret; refuses overwrites; returns created flag | `main init`; never print secrets or use for production | | `validate_env()` | Reads local `.env`, asserts four required settings and minimum lengths; raises on invalid/missing values | Invoked before running Compose helper actions | | `docker_compose(*args)` | Ensures Docker CLI exists, then executes Compose with explicit dev YAML and local env; raises if nonzero | `main` for `up`, `down`, `ps`, `config` | | `check_ready()` | GET `http://localhost:8080/debug/ready`, requires HTTP 200, otherwise raises; prints expected Admin Console URL | `main check` or after `up` | | `main()` | CLI dispatcher with `init`, `up`, `check`, `down`, `ps`, `config`; prints BLOCKED on RuntimeError | Script entrypoint | | `if __name__ == "__main__"` | Calls `main()` and exits with its status | Python execution entrypoint | **Related YAML:** `deployment/docker/compose.backend.dev.yaml` defines Postgres readiness via `pg_isready`, ZITADEL health command `/app/zitadel ready`, official Login V2 health, and Traefik path routing. These are container declarations, **not Python functions**. ## OIDC: `users/ui/src/auth.ts` | Function / callback | Actual responsibility | Caveat | | --- | --- | --- | | `NextAuth(() => {...})` configuration callback | Creates `handlers`, `auth`, `signIn`, `signOut` with dedicated ZITADEL OIDC provider; PKCE, state and nonce requests; Auth.js-managed JWT sessions | Config and dependency compatibility unverified | | `callbacks.signIn({account,profile})` | Accepts only provider `zitadel` and nonempty OIDC `profile.sub` | Does not implement external account permissions | | `callbacks.jwt({token,account})` | Stores OIDC provider account subject and provider access-token expiry in Auth.js JWT metadata; expiry absent => 0 | No token refresh implementation | | `callbacks.session({session,token})` | Sets `session.user.id` only if subject exists and stored expiry is future; otherwise sets empty ID | All protected actions must check nonempty `user.id`, not mere session presence | ## Config + identity helpers | Function | Source | Inputs, use and guard | | --- | --- | --- | | `required(name)` | `users/ui/src/lib/env.ts` | Server-only required environment lookup; rejects blank/example placeholders | | `validatedUrl(name)` | Same | Parses URL and checks scheme, credentials, query/hash/path; production requires HTTPS; dev allows HTTP localhost | | `oidcSettings()` | Same | Loads valid issuer, client ID/secret, Auth.js secret (length 32+), portal URL and trusted-host boolean | | `requireIdentity()` | `users/ui/src/lib/identity.ts` | Reads `auth()`; no valid `session.user.id` => `redirect("/signin")`; otherwise returns current user | | `zitadelSelfServiceUrl()` | Same | Builds issuer-origin `/ui/console/users/me` link. Route/permission availability **not tested**; never accepts a browser-supplied redirect URL | ## Next.js pages and server actions | Export/function | File | Action / user impact | | --- | --- | --- | | `RootLayout({children})` | `src/app/layout.tsx` | Renders `html` / `body` wrapper and imports global stylesheet | | `Home()` | `src/app/page.tsx` | Server-side redirect from `/` to `/account` | | `SignInPage()` | `src/app/signin/page.tsx` | Calls `auth()`; sends valid users to `/account`; otherwise renders sign-in form | | `startLogin()` | Same, nested server action | Calls `signIn("zitadel", {redirectTo:"/account"})` on button submission | | `ProtectedLayout({children})` | `src/app/(protected)/layout.tsx` | Guards all routes in this route group using `requireIdentity()` | | `AccountPage()` | `src/app/(protected)/account/page.tsx` | Protected overview greeting and profile/security action cards | | `ProfilePage()` | `src/app/(protected)/account/profile/page.tsx` | Protected, read-only display name/email/subject plus self-service link | | `SecurityPage()` | `src/app/(protected)/account/security/page.tsx` | Protected informational password/MFA/passkeys page plus link | | `AccountShell({user,children})` | `src/components/account-shell.tsx` | Nav, authenticated identity tile, sign-out form, topbar and footer | | `portalLogout()` | Same, nested server action | Calls Auth.js `signOut({redirectTo:"/signin"})`; not global SSO logout | | `AccountCard({title,description,href,action})` | `src/components/account-card.tsx` | Reusable linked overview card | | `DataRow({label,value})` | Same | Read-only `dt/dd` identity field with Not provided fallback | ## Next.js HTTP/API handlers | Export | File | Security and behavior | | --- | --- | --- | | `GET`, `POST` (Auth.js handlers) | `src/app/api/auth/[...nextauth]/route.ts` | Delegated to Auth.js `handlers`; callback and session endpoints | | `GET()` | `src/app/api/account/me/route.ts` | Calls `auth()`; nonempty `session.user.id` required; 401 otherwise; returns current id/name/email with private/no-store | | `generateMetadata` | No first-party custom implementation present | Do not invent one; static metadata objects exist in pages | | `next.config.ts async headers()` | `users/ui/next.config.ts` | Declares response security headers via Next config; not an account API | ## Previous first-party unit test functions (prior phase) `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. ## P05-CI-01 — CI-only verification helpers | Function | Exact path | Purpose / security boundary | | --- | --- | --- | | `fail(message)` | `tests/ci/source_contract.py` | Raise a source-contract assertion with a clear reason | | `check_account_lock()` | Same | Check npm lock v3 root dependency snapshot against Account Portal manifest | | `check_login_importers()` | Same | Require exact 4-importer pnpm lockfile and existing 3 upstream workspace members | | `check_security_boundaries()` | Same | Static source markers for PKCE/state/nonce, expiry and nonempty protected user ID; **not** a behavioral auth test | | `main()` | Same | Execute CI structural checks and return clear process success/failure | | `fetch(path)` | `tests/ci/oidc_discovery.py` | HTTP read-only probe of disposable proxy with expected localhost Host header | | `main()` | Same | Check ZITADEL readiness, issuer discovery metadata and JWKS shape; print explicit interactive OIDC E2E BLOCKED | Workflow service orchestration is in `.gitea/workflows/p05-ci.yml`, not Python. It executes only in Gitea CI; no local tests were requested. A green source check does not certify real authentication. ## P05-CI-03 backend CI shell entrypoints | Symbol / entrypoint | Source | Exact behavior | | --- | --- | --- | | `dc()` in acceptance script | `tests/ci/backend_acceptance.sh` | Applies project-specific `docker compose` with the P02 dev file **plus** CI portless override on every operation | | `backend_acceptance.sh` main | Same | Refuses existing project/network/volumes, runs prior backend helper static tests only in Gitea, creates disposable `.env`/ownership marker, checks effective Compose has no published ports, four-service state, Postgres restart marker, OIDC ready/discovery/JWKS | | `dc()` in cleanup script | `tests/ci/backend_cleanup.sh` | Uses identical exact Compose project and two-file configuration only after an ownership marker is present | | `backend_cleanup.sh` main | Same | Always-step removes only marked CI project with volumes; verifies no fixed network, matching project containers or volumes persist; no marker => no project teardown | The scripts execute in the **Gitea Actions** runner, not on the local developer PC. Real user authentication and MFA are not implemented as CI checks. ## P05-SEC-01 — Security-only CI helper behavior `tests/ci/security_advisory_gate.py` owns `main()`: it reads one npm or pnpm production registry audit JSON report, checks for report errors, validates required numeric severity counters and matching npm vulnerable-package or pnpm advisory records, prints the actual counts and **returns a failing CI exit code** if Moderate, High or Critical count is nonzero. Invalid or missing report information is also an error. It does **not** modify package manifests, bypass audit rules or accept a waived advisory. The upstream helper `tests/ci/advisory_triage.py` still displays exact GHSA/package/fix records and remains unchanged. Workflow shell commands are written directly under `.gitea/workflows/p05-security-acceptance.yml`. No application runtime function or auth code changed in this phase. ## P05-SEC-02 — CI contract helper `tests/ci/transitive_override_contract.py::main()` reads the existing `auth/ui/v2/pnpm-workspace.yaml` and resolved `pnpm-lock.yaml` (no network or side effects), verifies exactly seven parent-specific override selectors, checks the four required PNPM importers, rejects any known affected glob (>=9 <=14.0.1) or minimatch (>=7 <11.0.1) snapshot, and asserts that all seven parent dependencies resolve to the exact patched version. Failure returns nonzero in CI; it does not hide audit failures or alter dependencies. Existing `tests/ci/security_advisory_gate.py` remains the independent **live registry report** gate, rejecting malformed reports and any Moderate/High/Critical finding. A clean lockfile alone cannot prove that the live advisory audit passes. **P05-SEC-02 post-run correction:** `overridden(data)` in `tests/ci/transitive_override_contract.py` originally matched every `>`, incorrectly interpreting `axios@>=...`, `brace-expansion@>=...` and `esbuild@>=...` existing PNPM version constraints as new parent-child override selectors. The matching expression now restricts the suffix to `>glob` or `>minimatch` only, preserving the seven exact patch-parent check without changing registry audit logic. Run #88 predates the fix; this parser has **not yet passed CI**. Auth/session flows untouched. ## P05-OIDC-01 — CI-only real browser identity helper functions - `tests/ci/oidc_e2e/provision.py::request()` restricts official management/user API requests to fixed localhost and returns **bounded** JSON, without printing token/secret/error-body values; `wait_until_ready()` and `main()` verify issuer discovery and use ephemeral IAM_OWNER bootstrap to create real disposable project, OIDC client and verified human. The resulting secrets file is written only to a CI Docker volume with mode 0600. - `tests/ci/oidc_e2e/browser.cjs::fixture()` checks fixture integrity; `waitForPortal()` checks the CI-only Account dev server; `assertAuthorization()` validates genuine browser authorization params (S256 PKCE, state, nonce, client and exact redirect); `verifyAnonymous()` asserts unauthenticated API 401/no-store and protected-page redirect; `verifyInvalidCallback()` asserts tampered state/code cannot establish a session; `main()` uses original Login V2 username/password, waits for a *real* Auth.js callback, verifies created user ID, cookie, protected page and local logout. - `run.sh` owns startup and preflight; `cleanup.sh` owns exact run-labeled teardown and failure if anything remains. These are not user-facing endpoints and must never run against shared/production Docker. - `users/ui/src/auth.ts`, Account/API source and all upstream Login V2 runtime functions remain unchanged. **P05-OIDC-01 runtime evidence:** `run.sh` reached four-service readiness in Run #90, then `provision.py::wait_until_ready()` timed out on private `localhost:8080` before `request()` could provision any client, project or user. Thus `browser.cjs::main()` and its positive/negative real login/session checks **were not executed**. The only other completed operation was `cleanup.sh`, which verified removal of owned state. The sidecar's precise root cause is unknown; avoid runtime/PASS claims for unexecuted browser functions.