Files
ZitPlane/project/FUNCTIONS.md
T

210 lines
31 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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.
**P05-OIDC-02 narrow source audit:** Shell orchestration in `tests/ci/oidc_e2e/run.sh` now probes private Traefik `/debug/ready` with exact `Host: localhost:8080`, verifies prebuilt socat image entrypoint/digest, and stops before credential provisioning when the loopback forwarder state, socket or HTTP response is not ready. Python `provision.py::wait_until_ready()` now checks only `HTTP 200` for `/debug/ready` without interpreting an arbitrary body as JSON. No user API, token, session, IAM policy, Auth.js or official Login V2 code changed.
**P05-OIDC-02 Run #91 actual invocation:** `run.sh` correctly proved the underlying proxy's exact HTTP Host route and pinned image metadata, then observed the forwarder `docker inspect` state `exited`, exit code 1 and **stopped before provisioning**. The updated `provision.py::wait_until_ready()`, official provisioning functions and `browser.cjs` were **not reached** and remain unverified in this phase. Exact owned cleanup completed. Never infer a successful session from source-only logic.
**P05-OIDC-03 narrow new functions:** `run.sh::forwarder_http_ready` makes an actual status-only HTTP probe through private `127.0.0.1:8080` to the original proxy with `Host: localhost:8080`. The socat fallback branch reads *only* its pre-credential startup stderr into an allowlisted Python error classifier, verifies run-owner label before replacement, then resolves official Python by digest. `forwarder.py::copy_bytes` relays opaque 64 KiB TCP chunks without logging payload; `forwarder.py::serve_client` connects only to localhost:80 and transparently relays both directions; `forwarder.py::main` binds IPv4 loopback :8080 and emits fixed safe errno classes. Original IAM/user/PKCE/Auth.js functions unchanged.
**P05-OIDC-04-A01 function audit:** The inline Python private Traefik readiness probe in `tests/ci/oidc_e2e/run.sh` now prints only enumerated socket error classes or numeric HTTP status, closes its HTTP socket and conditionally retries known transient errors (3 attempts max), before any OIDC client/user exists. On successful first attempt, control continues to the already-present safe port-8080 inode/PID inspector, private Socat, official provisioning and real browser acceptance. Run #96 verified all positive/negative browser/session/logout and cleanup gates, but **did not exercise retry or Python fallback**. No protected Account/Auth.js/Login V2 functions were changed.
## P05-OIDC-05 reviewed function boundaries (unchanged)
`users/ui/src/lib/env.ts::required,validatedUrl,oidcSettings` validates required Auth.js settings, production HTTPS origins and min-length secret; does not configure ingress. `users/ui/src/auth.ts` provider+`signIn,jwt,session` callbacks verify standard PKCE/state/nonce and fail-closed ID/expiry, but no refresh or IdP-wide logout. `users/ui/src/lib/identity.ts::requireIdentity,zitadelSelfServiceUrl` protects server identity and constructs a permission-dependent Console link. `users/ui/src/components/account-shell.tsx::portalLogout` invalidates only the portal session. Imported `auth/ui/v2/apps/login/src/proxy.ts::proxy` and `src/lib/server/service-url.ts::getServiceConfig` are source-level proxy handlers, not custom-image integration proof. Run #96 verified the existing prebuilt flow only.
## P05-OIDC-06 tested script behavior
`tests/ci/login_image/build.sh`: rejects preexisting run-owned names, copies source to disposable builder, verifies frozen PNPM and standalone output, creates a local Docker image from an unchanged Dockerfile with run-id label and immutable local image ID. It did **not** assert executable mode of the copied `entrypoint.sh`; OCI startup subsequently failed with permission denied.
`tests/ci/login_image/cleanup.sh`: exact-run builder/image/context ownership checks and removal; Run #98 `ZITPLANE_CUSTOM_LOGIN_ALL_BUILD_RESOURCES_CLEANED_PASS`. Existing `tests/ci/oidc_e2e/cleanup.sh` and backend cleanup separately passed. `tests/ci/oidc_e2e/run.sh::dc` adds only a validated opt-in fourth CI Compose file; actual custom login identity gate was NOT EXECUTED.
## P05-OIDC-06-A01 — bounded CI helper behavior (no auth changes)
`tests/ci/login_image/build.sh` now validates `$context/.next/standalone/entrypoint.sh` is a regular file and not a symlink, checks first bytes `#!` without printing content, records sanitized numeric `mode UID:GID`, accepts either already-executable `755` or the established source-copy `644` and applies `chmod 0755` **only to the latter temporary copy**. Rejects all unexpected file types/modes and then requires `-x` + exactly `755`. After unchanged Dockerfile build, a no-network/no-secrets `docker run --entrypoint /bin/sh` with default image `nextjs` user validates `/app/entrypoint.sh` is regular, non-symlink, `755`, executable and has a shebang, printing only a fixed PASS marker. Original Git source and Dockerfile untouched.
Run #99 confirmed input `644 UID:GID 0:0`, copied output/image executable and actual custom runtime/Chromium OIDC acceptance, negative and local logout success. Existing run-owned cleanup checks PASS. No provision/browser/Auth.js method changed.
## P05-OIDC-07 — inspected function contract, unchanged source
- `users/ui/src/lib/env.ts::validatedUrl` forbids HTTP for `NODE_ENV=production` and credentials/query/hash in origin URLs. `oidcSettings` requires `AUTH_SECRET` min 32 and `ZITADEL_CLIENT_ID/SECRET` and passes `AUTH_TRUST_HOST`; **does not** provision TLS, register redirects or sanitize ingress headers.
- `users/ui/src/auth.ts` provider/NextAuth callbacks require PKCE/state/nonce and valid provider subject+expiry, JWT maxAge 3600; access-token refresh/global provider logout are **not** implemented.
- `users/ui/src/lib/identity.ts::requireIdentity,zitadelSelfServiceUrl` enforces nonempty subject, produces policy-dependent Console self-service link; `users/ui/src/components/account-shell.tsx::portalLogout` calls local `signOut` only.
- `auth/ui/v2/apps/login/src/lib/server/service-url.ts::getServiceConfig,constructUrl` relies on publicHost/forwarded headers, and `src/proxy.ts::proxy` performs upstream rewrites/CSP/CORS; security at public proxy/Host trust must be verified separately. `src/lib/server/custom-headers.ts::applyCustomHeaders` uses configured headers. No upstream change.
- `core/backend/zitadel/dev.py::create_dev_env,validate_env` generates **development** secrets only (master key 32 chars, login cookie >=32), not production KMS/escrow or rotation. No new functions or behavior in P05-OIDC-07; see `notes/P05-OIDC-07.md`.
## P05-OIDC-08 — stdlib static validator function contract
`tests/ci/production_contract/validate.py::validate_policy` validates fixed canonical HTTPS issuer/origin/callback, confidential code+PKCE/state/nonce, exact ordered Login/Console/API/Account routes (ZITADEL h2c), unknown Host reject and forwarded header strip-and-replace, required symbolic secret references.
`validate_compose` accepts normalized JSON from Compose `config --format json` and enforces exact synthetic images, five services, private-only network, zero replicas, no ports/volumes/sockets/privileged fields, referenced-only external placeholder secrets and no embedded environment secrets. **In Run #101 it failed with `RUNTIME_BEHAVIOR`** while checking the normalized service dict; offending field/type not logged and cannot yet be assigned to Compose default vs true runtime field.
`negative_cases` contains **25 targeted in-memory mutation checks** that require a specific error class. Run #101's positive failure occurred **before** this function; negative coverage is **NOT EXECUTED**. `workflow_safety` allows only two `docker compose ... config` commands, manual trigger, and proves no Docker lifecycle actions configured; **PASS** in Run #101. `main` prints fixed status codes; no input/credential dumps, DNS, runtime containers or external contacts. A01 may diagnose/reconcile Compose normalized inert keys only with separate approval.
## P05-OIDC-08-A01 — changed validator-only function semantics
`tests/ci/production_contract/validate.py::diagnose_normalized_runtime_fields` is NEW: only five known service IDs and four predefined fields (`build`, `command`, `entrypoint`, `configs`) with a category such as `NULL`/`EMPTY_LIST`/`NONEMPTY_LIST` are printed; no untrusted key/value, environment, full Compose JSON or secret. Run #102 observed null `command` + null `entrypoint` on every service. `validate_compose` now allows only inert normalized `command=None`, `entrypoint=None`, `configs=None/[]`; still rejects `build` of any kind, non-null executable override and nonempty configs, with exact other port/image/secret/privilege/zero-replica checks preserved.
`negative_cases` preserves original 25 security fixtures and adds four targeted `NONEMPTY_COMMAND`, `NONEMPTY_ENTRYPOINT`, `BUILD_CONTEXT`, `NONEMPTY_CONFIGS` rejects plus a safe inert-null acceptance fixture. **None of these 29 negative checks ran in Run #102**, because `validate_compose` hit `DEPLOY_DISABLED` first. No claim of their acceptance. Safe next diagnostic should inspect only type/category of normalized deploy/replicas and preserve nonzero prohibition, without altering YAML/workflow. See `notes/P05-OIDC-08-A01.md`.
## P05-OIDC-08-A02 — validator-only new source functions and terminal limits
`tests/ci/production_contract/validate.py::verify_tracked_zero_replica_fixture()` reads ONLY the checked-in `deployment/production-contract/compose.ci.yaml` as text, requires exact five service blocks and one `deploy: replicas: 0` per block, prints a static PASS marker. Confirmed **PASS** in Run #103. `diagnose_normalized_deploy()` examines only recognized five service IDs, `deploy` mapping presence/type, unexpected extra field **existence** and `replicas` zero/nonzero TYPE classes without printing arbitrary keys/values. In Run #103, all 5 `deploy` mappings were OBJECT with `REPLICAS_INT_ZERO` and `UNEXPECTED_FIELDS_PRESENT`. Actual unknown key names were intentionally not logged.
`validate_compose()` continues to reject build/executable overrides, public ports, Docker socket, privilege, unexpected images, nonzero replicas and unfamiliar `deploy` keys, with conditional handling of proven source-zero normalized omission. The **actual** normalized mapping had extra keys, so strict `DEPLOY_DISABLED` **FAIL**, before final positive marker or `negative_cases()`. All original 25, prior 4 runtime and 3 additional replica negatives remain **SOURCE PRESENT / NOT CI EXECUTED**. The unchanged `workflow_safety()` checker **PASS**. Future A03 must first identify extra normalized deploy key name/safe type and only narrow-allow inert defaults if truly proven, retaining fail-closed security. No app/backend/Compose/workflow/source other than validator changed.
## P05-OIDC-08-A03 — new inert metadata function, safe diagnostics, next grant RCA
`tests/ci/production_contract/validate.py::inert_deploy_metadata(key,value)` recognizes **only a finite list of Docker Compose deploy metadata keys**, accepting null/empty structures (including resources with strictly empty `limits`/`reservations`) and rejecting populated deployment behavior, `mode` strings, unknown keys and nonzero or missing replicas. `safe_deploy_shape()` and `diagnose_normalized_deploy()` emit predefined known field names and fixed shape categories, never arbitrary input keys or values. `verify_tracked_zero_replica_fixture()` now validates unchanged synthetic fixture Git blob SHA `930c0b0fbfb518555436acd6f0b4bb3bdd421937` plus exact five source `replicas:0`. Eight hostile extra-deploy negative fixtures added to preserved 25+4+3.
Actual [Run #104](https://dev.ivib.cc/vibtools/ZitPlane/actions/runs/104) confirmed `resources: {}` and `placement: {}` on five services, all normalized replicas integer zero, with old `DEPLOY_DISABLED` rejection no longer emitted. **New fail-closed `SERVICE_SECRET_REFS`** came from pre-existing `service_secret_refs()`: it allows string secret entries or restricted dict source/target where `target == source` and then compares expected service grants. The actual normalized grant structure was **not logged**, so a source/target mismatch is only a hypothesis. All 40 negative cases remained NOT EXECUTED. A04 may add value-free per-entry classification and narrowly adapt to actual canonical target if independently verified, without exposing secret values or broadening permissions. No other source/security checks changed.
## P05-OIDC-08-A04 — secret grant normalization functions and complete negative acceptance
**Only source changed**: `tests/ci/production_contract/validate.py`, tested `daaa8b259a519ae0290ba28936ef2279b3a9172c`. `secret_target_class(source,target)` classifies known same-name vs exact `/run/secrets/<source>` mounts; `safe_root_owner()` requires root 0 and `safe_readonly_mode()` permits exact 0444 default (decimal 292) if metadata supplied. `diagnose_normalized_service_grants()` prints only known service names, item indices and fixed `OBJECT`/`TARGET_CANONICAL_MOUNT`/`SOURCE_EXPECTED`/permissions safety classes, not values. `service_secret_refs()` now rejects unknown fields, wrong target, unsafe UID/GID/mode, duplicates and sources outside the six-symbolic-secret registry; `validate_compose()` compares **exact per-service count and source set**, not normalizer-dependent ordering. `negative_cases()` preserves 25 original, 4 runtime, 3 replica and 8 deploy malformed cases; adds **8 secret-grant negative cases** for missing, duplicated, extra known from wrong service, unknown source, wrong target, unexpected metadata, unsafe UID and world-writable mode, plus a canonical-target positive case. Exact expected error class is mandatory.
**All checks executed and PASS in [Run #105](https://dev.ivib.cc/vibtools/ZitPlane/actions/runs/105)**: 48/48 negatives, full static positive and manual-only safety. Input raw JSON/env/secret strings never logged by new diagnostics. No source changes to production/login/Account/backend/workflow/Compose, and actual public HTTPS, secret custody/DB recovery, Console/MFA/SSO or deployment remain NOT TESTED.
## P05-OIDC-10 — imported OCI provenance helpers (CI-only)
`tests/ci/login_image/provenance.py` new stdlib functions `validate_lock`, `verify_source` (exact tracked `HEAD:auth/ui/v2` Git tree/source Dockerfile/entrypoint/PNPM lock), `pin_dockerfile` (only run-owned temporary Dockerfile FROM replacement), `expected_labels`, `validate_image` (image ID, linux/amd64, USER nextjs, exact entrypoint, source/base labels and allowed env keys), `verify_builder` (OCI base index/arch), `negative_cases` (6 lock tampering + 6 bad OCI image configurations) and `write_material_attestations` (partial source/base SPD​X metadata+unsigned JSON in temporary run context). `tests/ci/login_image/build.sh` default original Run #99 behavior remains; new `ZITPLANE_PROVENANCE_CI=1` source-verified pinned builder/runtime and `--verify-image` opt-in. No real secret values printed.
[Run #106](https://dev.ivib.cc/vibtools/ZitPlane/actions/runs/106) source `6ba004808ef47c8856c1a7906faaf7ee807d15a6`: `verify_source`, `negative_cases` 12/12, temporary `pin_dockerfile`, entrypoint fix, pinned image packaging and `verify_builder` **PASS**; `validate_image` **FAIL** at `IMAGE_SECRET_ENV_KEY`, before `write_material_attestations`. Its current unanchored `PAT` substring regex can also match `PATH`; actual offending key **UNKNOWN**. No attestation files. Next independent P05-OIDC-10-A01: ONLY this validator source to add value-free fixed key classification, retain secret rejection with token boundaries, plus PATH/true-PAT focused negatives; no other source edits.
## P05-OIDC-10-A01 — finite OCI environment-key functions (source only)
Only `tests/ci/login_image/provenance.py` changed at candidate SHA `4452a61b0f5a0892399060fd7569231a564bce02`: `SAFE_OCI_ENV_KEYS` is a fixed set of known benign Node/OCI image ENV names (PATH/NODE_VERSION/YARN_VERSION and exact upstream runtime keys). `SENSITIVE_OCI_ENV_SEGMENTS` is an underscore-separated **complete-token** set of AUTH/SECRET/TOKEN/PAT/MASTERKEY/PASSWORD/PRIVATE/KEY/DB and related credentials. `classify_oci_env_key()` maps arbitrary input **only to SAFE/SENSITIVE/UNKNOWN/INVALID**, not its value. `diagnose_oci_image_env()` logs known-safe whitelisted key names and fixed generic error classes, plus legacy PATH matcher evidence **only if verified in a real inspected OCI image**. `validate_image()` fails closed for sensitive, unknown, bad-format, duplicates, non-production NODE_ENV, existing unsafe user/labels/entrypoint/platform and image ID. The 12 original fixture definitions remain; `negative_cases()` now adds 9 sensitive-key + 5 malformed/unknown/duplicate/development-mode rejects (=14) and one benign PATH positive. No value printing, no arbitrary name output, no new network/API operations. **Run #108 currently QUEUED**, so these are SOURCE VERIFIED, NOT CI VERIFIED; actual previous rejected key remains UNKNOWN until runner executes [Run #108](https://dev.ivib.cc/vibtools/ZitPlane/actions/runs/108). No builder, workflow, CI pins or app edits; full details `notes/P05-OIDC-10-A01.md`.