Files
ZitPlane/project/FUNCTIONS.md
T

9.9 KiB

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.