From cea5c373d59329efde2234969c6ab1d4af6f399e Mon Sep 17 00:00:00 2001 From: Florian Forster Date: Wed, 28 Oct 2026 19:35:25 -0700 Subject: [PATCH 01/10] docs: design apps as one document with their clients and APIs Decides what the app document holds (clients, APIs, registration; one JSON Schema per config kind), who picks a client_id, how scopes and audiences are refused rather than dropped, the storage and API, how a release declares an app, and the directory the authorization server reads. Lifetimes and claim mappings move to token-issuance policies (ADR 066); SAML IdP and SCIM provisioning configs, the console's filtered lists and the presets are designed here and not yet built. Co-Authored-By: Claude Opus 5.5 --- docs/design/api/README.md | 1 + docs/design/api/apps.md | 383 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 384 insertions(+) create mode 100644 docs/design/api/apps.md diff --git a/docs/design/api/README.md b/docs/design/api/README.md index 2f79f3c421..55b472e964 100644 --- a/docs/design/api/README.md +++ b/docs/design/api/README.md @@ -34,6 +34,7 @@ Individual decisions are marked inline in each doc: 8. [`authz-testing.md`](authz-testing.md) — L1–L4 fuzzy/property strategy for compiler, persist, and (later) resolver oracles. 9. [`security-and-origins.md`](security-and-origins.md) — environment-gated origin wildcards, CORS, CSRF. 10. [`resource-map.md`](resource-map.md) — the full endpoint surface grouped by concern. +11. [`apps.md`](apps.md) — the app document: clients, APIs and registration in one document, its storage, release path and the directory the authorization server reads. ## Sibling doc sets diff --git a/docs/design/api/apps.md b/docs/design/api/apps.md new file mode 100644 index 0000000000..e6dca0769d --- /dev/null +++ b/docs/design/api/apps.md @@ -0,0 +1,383 @@ +# Apps + +> **Status:** Proposal, prototyped on branch `claude/apps-model-25449c`. +> +> **Date:** 2026-10-28 +> +> **Builds on:** the identity model +> ([#2445](https://github.com/zitadel/nextgen/pull/2445)), the platform OAuth +> POC ([#2451](https://github.com/zitadel/nextgen/pull/2451)), +> [ADR 082](../../adrs/082-oauth-and-oidc-server.md), +> [ADR 063](../../adrs/063-resource-revisions-fixed-id-and-revision-id.md), +> [IdP connections](../idp/1-resource-model.md) +> +> **Amends:** ADR 082 §3 (who picks a `client_id`), §5 (where an API is +> declared), §9 (where registration is switched on), and open question 3 +> (lifetimes); ADR 047 §2 (four prefixes) + +## Goal + +The identity model settled that an app is one document holding every config +it has, written in one call, declared in the release when the developer owns +it and registered through the API when someone else does. This note decides +what the document holds, how it is stored, how a release carries it, and how +the authorization server finds a client or an API in it. + +## The document + +An app has a `slug`, a `name`, an optional `preset` label and one array per +config kind. Each config kind has its own JSON Schema, written once in the +OpenAPI YAML and generated by the meta-schema pipeline, so the server, the API +and `.zitadel/meta/` share one shape: + +| Schema | Holds | +| --- | --- | +| [`app.json`](../../../api/openapi/endpoints/schemas/app.yaml) | `slug`, `name`, `preset`, `clients`, `apis`, `registration` | +| [`app-client.json`](../../../api/openapi/endpoints/schemas/app-client.yaml) | One OAuth or OIDC client | +| [`app-api.json`](../../../api/openapi/endpoints/schemas/app-api.yaml) | One API the app serves, MCP servers among them | +| [`app-registration.json`](../../../api/openapi/endpoints/schemas/app-registration.yaml) | Whether clients may register into the app | + +`saml` and `scim` join as kinds once their engines exist (below): nothing is +selectable without an implementation behind it. + +```json +{ + "slug": "shop", + "name": "Shop", + "preset": "web", + "clients": [ + { "slug": "web", "type": "confidential", "secret": "${{ SHOP_WEB_CLIENT_SECRET }}", + "grants": ["authorization_code", "refresh_token"], + "redirect_uris": ["https://shop.example.com/callback"], + "apis": [{ "api": "orders" }, { "api": "billing/invoices", "scopes": ["invoices.read"] }] }, + { "slug": "desktop", "client_id": "ShopDesktop", "type": "public", + "grants": ["authorization_code", "refresh_token"], + "redirect_uris": ["http://127.0.0.1/callback"] }, + { "slug": "repricer", "type": "confidential", "secret": "${{ SHOP_REPRICER_CLIENT_SECRET }}", + "grants": ["client_credentials"], + "apis": [{ "api": "orders", "scopes": ["orders.write"] }] } + ], + "apis": [ + { "slug": "orders", "identifier": "https://api.shop.example.com", + "scopes": [{ "name": "orders.read", "description": "Read your orders" }, { "name": "orders.write" }] }, + { "slug": "mcp", "identifier": "https://shop.example.com/mcp", "third_party": true } + ], + "registration": { "client_id_metadata_documents": true } +} +``` + +- **A slug names one config of the app**, across clients and APIs, so + `shop/web` is unambiguous wherever another document or the console names it. +- **Clients speak the protocol's words** (`type`, `auth_method`, `grants`, + `redirect_uris`), and presets fill them. There is no per-client + `protocol: oidc|oauth`: OIDC is OAuth plus the `openid` scope, and a second + field could only disagree with it. +- **A public client** holds no secret, authenticates with `none` and cannot + use `client_credentials`. **A confidential client with + `client_credentials` is a principal**: its tokens have the client as `sub`. + What it may do is a grant on that principal, which the identity model's + open question 2 decides; the document holds no rights. +- **A client lists the APIs it may call**, its default first: an API of its + own app by slug, another app's as `/`. `scopes` narrows the API's + scopes; leaving it out allows all of them. A same-app reference is checked + when the document is written. Another app's is resolved when a request + names it, so no write waits for another app to exist. +- **An API is an identifier, scopes and `third_party`.** The identifier is the + `aud` of every token for it (RFC 8707): https, loopback http, or a `urn:`. + No two apps in a project share one, and an app keeps every identifier it + ever used, so a token minted for a retired API is never accepted by a new + one. +- **Registration is switched on per app** (amends ADR 082 §9, which put it in + `oauth.json`). A client that registers names no app; the app is the one + whose API its first authorization request names as `resource`, and it may + ask only for that app's `third_party` APIs, as the POC showed. The rule + that open registration needs a login-only issuer stays project-wide. +- **Redirect URIs** are https, loopback http (any port, RFC 8252 §7.3), or a + private-use scheme for a public client, without a fragment and in their + canonical form, so the browser goes byte for byte to the URI that was + checked ([POC findings](https://github.com/zitadel/nextgen/pull/2451)). +- **What the document does not hold:** token lifetimes and claim mappings, + which are policies ([below](#lifetimes-and-claims-are-policies)), and a + principal's rights, which are grants. + +## Client ids and secrets + +ADR 082 §3 had the server mint every `client_id`. It mints one only when the +document leaves it out: + +- **A chosen `client_id` is kept**, for ids compiled into desktop and mobile + apps (ownCloud, OpenCloud), ids a v4 or another identity provider issued, + and ids every project a release ships to should share. Our own CLI's `cli` + is the first case. It takes `[A-Za-z0-9._~@-]`, up to 255 characters: v4's + ids contain `@` and import as they are, while a minted id never does. +- **Fixed for life.** A revision that leaves it out keeps it, one that + changes it is refused (`app.field_immutable`), and a client removed and + added back under its slug gets it again. +- **Unique in the project and never reused**, whichever app held it. +- **Minted ids are row ids** (`client_01K…`): the chosen value sits beside the + row's own key, so no caller picks a primary key (ADR 047 §4). A chosen id in + that form is refused. + +Secrets follow the app's writer: + +| App | Secret | +| --- | --- | +| Declared | A `${{ NAME }}` variable the deployment froze (ADR 062, ADR 069), the developer's own value. A deploy is refused while the variable has no value | +| Registered | Generated by the server for each new confidential client, returned once, stored as SHA-256 (256 random bits need no slow hash). Or imported: a plaintext, or a hash passwap reads (v4's bcrypt, argon2, scrypt, pbkdf2), moved to SHA-256 the first time it matches | + +A client may hold several secrets, so one can be rotated without downtime. +Generated secrets carry a `zcs_` prefix for secret scanners; the final format +is the [apps and machine identities note](https://github.com/zitadel/nextgen/pull/2430)'s +to decide. + +## Scopes and audiences + +- **An API's scopes are its own.** The built-in OpenID Connect scopes stay + built in, and an API may not define them again. +- **Unknown is refused, never dropped.** A requested scope that is neither + built in nor defined by the requested API is `invalid_scope`, and so is one + the API defines but a first-party client's allowlist leaves out. A third + party may ask for any scope of a `third_party` API, and the user's consent + narrows what is granted. +- **Granted scopes are `scope`**, a space-separated claim (RFC 9068), never + claims of their own. v4's project-audience scope + (`urn:zitadel:iam:org:project:id:{id}:aud`) is an unknown scope. +- **One audience per token.** An access token's `aud` is the one API its + request named; an ID token's `aud` is the client alone. v4 put the project + and every client of the project in `aud`, which strict relying parties + reject ([#9200](https://github.com/zitadel/zitadel/issues/9200), + [#8055](https://github.com/zitadel/zitadel/issues/8055)). + +The domain answers these rules +([`app.go`](../../../internal/domain/app.go): `AccessTo`, `GrantScopes`), so +the authorization server and anything else that issues tokens apply them the +same way. + +## Storage + +Apps are stored as IdP connections are (ADR 063): an identity row, an +immutable revision per write holding the document as authored, and newest by +`created_at`. The other three tables outlive revisions and are written in the +revision's transaction: + +| Table | Key | Why | +| --- | --- | --- | +| `apps` | `app_…`, unique slug | Identity and `source` (`declared` or `registered`) | +| `app_revisions` | `apprev_…` | The document; what a release pins | +| `app_clients` | `client_…`, unique `client_id` | The token endpoint finds a client in one lookup, and the id stays with its client | +| `app_api_identifiers` | identifier | `resource` finds its app in one lookup, and an identifier stays with its app | +| `app_client_secrets` | `csec_…` | A registered app's secret hashes | + +The document is stored as written, without the minted ids, so a release that +sends the same file again matches its earlier revision. `app.created`, +`app.updated` and `app.client_secret.added` are emitted in the same +transaction ([events catalog](events-catalog.md)); none carries the document +or a secret. + +## API + +| Operation | Does | +| --- | --- | +| `POST /apps` | Creates a registered app or revises one by slug; answers each client's `client_id` and the secrets it generated, once | +| `POST /apps/query` | Lists apps at their newest revision, filtered by `slug`, `source` or `created_at` | +| `GET /apps/{id}` | One app with its client ids | +| `GET /apps/{id}/revisions`, `GET /apps/revisions/{revision_id}` | ADR 063's revision reads | +| `POST /apps/{id}/clients/{client}/secrets` | Generates or imports a secret for a registered app's confidential client | + +Each app has one writer. `POST /apps` refuses a slug the release declares +(`app.declared`), and a release refuses a slug the API registered: a release +never takes over an app a customer's admin or a product wrote. ADR 081 §12's +adoption of a registered app by a later file waits for team-owned slugs +(`acme/crm`), which make that safe. + +## Releases + +- **Declared apps are files**, `.zitadel/apps/.json`, validated against + `.zitadel/meta/app.json`. +- **The bundle carries them** as `apps[]` in `POST /releases/build`. The build + validates each as declared, reuses a revision whose document matches, + appends one when it changed, and pins it under the `app` pointer kind. + Pointers are JSON, so the kind costs no migration. +- **A deployment serves the revision its release pins.** The authorization + server reads a declared app at that revision, a registered app at its + newest, and a built-in app from the binary. Removing a file drops the app + from the next release, and requests for it fail at the next refresh; the + stored app and its client ids stay. + +## The directory + +The authorization server finds clients and APIs through one interface, +[`AppDirectory`](../../../internal/service/app_directory.go): + +- `Client(at, client_id)` and `API(at, resource)` return the app at the + revision that serves `at` (the project and the deployment the request + resolved, ADR 081 §10). +- `VerifyClientSecret(at, app, client, secret)` checks a registered app's + hashes or a declared app's frozen variable. +- **Built-in apps** are the third source the POC found: apps the server + declares, read-only and versioned with the binary, such as the platform + project's `zitadel`. The directory serves them first. +- **Clients that register themselves** (client ID metadata documents, sealed + dynamic registration) stay in the authorization server; the directory + answers not-found for them. + +`internal/oauth` (part A) would replace its `PlatformApp()` lookups with these +calls. The interface was proposed to the POC session; it is not agreed yet. + +## Lifetimes and claims are policies + +Token lifetimes and claim mappings are not fields of the app. They are +policies on token issuance ([ADR 066](../../adrs/066-operation-policies.md)), +because what customers ask for is a hierarchy that no single document holds: + +- **Lifetimes per organization first.** The most-upvoted request, + [#5219](https://github.com/zitadel/zitadel/issues/5219), is per B2B + tenant, which is a team here; per-client cases (a CLI against a front end, + [#12653](https://github.com/zitadel/zitadel/issues/12653)) came later. + Nobody asked for lifetimes per API. Refresh rotation and reuse per client + ([#9631](https://github.com/zitadel/zitadel/issues/9631)) is the same kind + of setting. +- **Claims per app or API, with a target and a shape**: roles or groups as a + flat string array for Grafana, Kubernetes, Argo CD and oauth2-proxy + ([#9141](https://github.com/zitadel/zitadel/issues/9141), + [#7042](https://github.com/zitadel/zitadel/discussions/7042)); a claim only + in one app's tokens ([#8698](https://github.com/zitadel/zitadel/discussions/8698)); + claims only in userinfo to keep cookies small + ([#12333](https://github.com/zitadel/zitadel/issues/12333)); a scope that + switches a claim on. + +What the policy design has to add, as input to ADR 066: + +1. **Templates that return values.** An ADR 066 policy returns allow or deny; + a lifetime or a claim is a value the token is built with. +2. **An audience** narrower than the project: an app, a client, an API, a + team. ADR 066 leaves it to the audience model of + [#1264](https://github.com/zitadel/nextgen/pull/1264). +3. **Who reads a token** is a candidate rule for defaults: an API's settings + shape its access tokens, a client's its ID tokens, userinfo and refresh + tokens. +4. **Roles** come from the app: ADR 034's app-group catalog becomes the app's, + so a token carries the roles of its own app, never another project's + filtered set. + +## SAML IdP configs + +Designed, not built. A `saml[]` config makes Zitadel the IdP for a service +provider: + +| Field | Holds | +| --- | --- | +| `slug` | As for clients | +| `entity_id` | The SP's entity id, unique per project, as a `client_id` is | +| `acs` | Assertion consumer service URLs with their binding (POST or redirect) | +| `slo` | Single logout URL and binding, optional | +| `metadata_url` | Instead of the three above, the SP's metadata, fetched with ADR 061's egress guards | +| `name_id` | Format (`persistent`, `email`, `unspecified`) and the user property it comes from | +| `attributes` | Attribute name to source, in the claims policy's grammar, so SAML and OIDC map users one way | +| `signing` | Sign the assertion, the response or both; the SP's certificate for signed requests and encrypted assertions | + +- **Engine:** in the server beside the OAuth authorization server. Its + browser endpoints sit under the SDK's `/__nextgen/saml/{project}/…`, which + the proxy already forwards, so customer apps need no new reserved path. An + AuthnRequest becomes a flow as an authorization request does + (ADR 081 §8), which is why it waits for part A's login handoff. +- **Keys:** the project's signing key wrapped in an X.509 certificate + (ADR 039). `github.com/zitadel/saml` (Apache-2.0, v4's) or + `crewjam/saml` (BSD-2-Clause) fit [LICENSING.md](../../../LICENSING.md). + +## SCIM provisioning configs + +Designed, not built. A `scim[]` config makes Zitadel the SCIM client that +keeps the app's own user store in step: + +| Field | Holds | +| --- | --- | +| `slug` | As for clients | +| `endpoint` | The app's SCIM base URL, under ADR 061's egress guards | +| `auth` | A bearer token as `${{ NAME }}`, or OAuth client credentials | +| `users` | Which users (by schema or team), the matching key (`externalId` from the user id), and the attribute mapping, property to SCIM path | +| `deprovision` | `deactivate` (`active: false`) or `delete` | +| `groups` | Later: teams as SCIM groups | + +- **Engine:** an ADR 065 job per config that reads user events (ADR 048) + from a cursor and pushes creates, updates and deactivations, with a row per + config and user (remote id, last pushed hash, attempts, last error) for + idempotency and retries, and a full reconcile when the config changes. +- It needs nothing from part A, so it is the cheaper of the two to build + first. + +## Console + +One Apps screen whose tabs are filters over `POST /apps/query`, in the filter +grammar the CLI shares (ADR 064 §11): + +| Tab | Filter | +| --- | --- | +| All apps | none | +| Sign-in clients | a client with `authorization_code` | +| Service accounts | a client with `client_credentials` | +| APIs and MCP servers | an API | +| SAML, SCIM | a config of that kind | +| Open to registration | `registration` on | + +The query filters by columns today (`slug`, `source`, `created_at`). The tabs +need facets computed when a revision is written, such as `has_api` and +`has_principal` on `app_revisions`, so every dialect filters them alike. +Clients that registered themselves are listed from part A's grants table, on +the app's page, since nothing else stores them. + +## CLI and presets + +```sh +zitadel apps create shop --preset web --redirect-uri https://shop.example.com/callback +zitadel apps create orders --preset backend --identifier https://api.shop.example.com +zitadel apps create assistant --preset mcp-server --identifier https://shop.example.com/mcp +zitadel apps create partner --preset web --redirect-uri https://partner.example/cb --registered +``` + +- **Presets** (`web`, `spa`, `native`, `cli`, `api`, `backend`, + `service-account`, `mcp-server`) live in + [`@zitadel/config/app`](../../../packages/config/src/app/presets.ts), so the + console offers the same ones. A preset only fills the document, and the + app keeps its name in `preset` as a label, like a connection's `template`. +- **`apps create`** writes `.zitadel/apps/.json` and names the secret + variables to set before the deploy that declares the app. `--registered` + writes the same document through `POST /apps` and shows the client ids and + the generated secrets once. +- **`apps list`** and **`apps get`** are registry commands. The noun follows + the CLI's current plural topics and moves to the singular with the + ADR 064 amendment. +- Turning the issuer on in `.zitadel/oauth.json`, as the identity model has + `app create` do, waits for that file (ADR 082 §12). + +## What the prototype covers + +| Piece | State | Tests | +| --- | --- | --- | +| Schemas and domain rules | Built | Domain unit tests | +| Storage on Postgres, SQLite, Spanner | Built | `stmttest` on SQLite and Postgres; Spanner compiles, CI runs it | +| `/apps` API and events | Built | HTTP tests on Postgres, generated error sets, spec lint | +| Release bundle, pinned revisions | Built | Service tests on SQLite | +| `AppDirectory` | Built | Service tests on SQLite, a deployment pinning an older revision included | +| Imported v4 bcrypt secrets | Built | Verified and moved to SHA-256 | +| `apps create`, `apps list`, `apps get`, presets | Built | CLI and config unit tests | +| Declared secret verification | Built | Shares `secretVariable` with SSO sign-in; not tested on its own | +| Lifetimes, claims, SAML, SCIM, console tabs | Designed | — | + +## Open questions + +1. **Team-owned apps.** Whether an app a product creates for a customer + belongs to that customer's team, slugged `acme/crm` like a team's + connection, and whether `team_admin` manages it. +2. **Values per project.** A release ships the same file to staging and + production, but their redirect URIs and an MCP server's identifier + differ. `${{ NAME }}` in those fields would resolve per deployment, which + the identifier lookup table cannot index; a relative form (`/mcp` on the + issuer's origin) covers the common case. +3. **Deleting an app**, with [#1013](https://github.com/zitadel/nextgen/issues/1013) + for declared resources. +4. **Without `resource`**, ADR 082 §5 issues a token for userinfo only, while + the POC used the client's first API. The document keeps "default first" + either way. +5. **The secret format** (prefix, checksum) with the apps and machine + identities note. From c5777787bcc431329eb501f654486ab835e5fb6b Mon Sep 17 00:00:00 2001 From: Florian Forster Date: Wed, 28 Oct 2026 19:35:25 -0700 Subject: [PATCH 02/10] feat: prototype apps with their clients, APIs and secrets One app document holds an app's OAuth and OIDC clients, the APIs it serves and whether clients may register into it. - Schemas: app.json with one schema per config kind, generated from the OpenAPI YAML, shipped into .zitadel/meta/. - Domain: the rules the schema cannot state (slugs, references, redirect URIs, identifiers, public and confidential clients), and the scope rules: an unknown or disallowed scope is invalid_scope, never dropped. - Storage on Postgres, SQLite and Spanner: apps and revisions like IdP connections, plus client ids, API identifiers and secret hashes that outlive revisions. A client keeps a minted or chosen client_id for life. - API: POST /apps (create or revise a registered app), query, get, revision reads, and client secrets (generated, or imported, v4 bcrypt included). - Releases: .zitadel/apps/ rides the bundle as declared apps, pinned per release; a release and the API never write each other's apps. - AppDirectory: the lookup the authorization server would use, serving each deployment the revision its release pins. - CLI: `zitadel apps create --preset` writes the app file from one of eight presets in @zitadel/config/app, or registers it with --registered; `apps list` and `apps get`. Co-Authored-By: Claude Opus 5.5 --- .changeset/apps-one-document.md | 7 + .redocly.lint-ignore.yaml | 2 + api/cmd/gen_event_schemas/main.go | 10 + api/cmd/gen_event_schemas/main_test.go | 2 +- api/generated/oas_cfg_gen.go | 31 +- api/generated/oas_client_gen.go | 1331 +- api/generated/oas_defaults_gen.go | 8 + api/generated/oas_handlers_gen.go | 1510 +- api/generated/oas_interfaces_gen.go | 36 + api/generated/oas_json_gen.go | 38544 ++++++++++------ api/generated/oas_operations_gen.go | 9 + api/generated/oas_parameters_gen.go | 1059 +- api/generated/oas_request_decoders_gen.go | 237 + api/generated/oas_request_encoders_gen.go | 42 + api/generated/oas_response_decoders_gen.go | 2736 +- api/generated/oas_response_encoders_gen.go | 714 +- api/generated/oas_router_gen.go | 987 +- api/generated/oas_schemas_gen.go | 7137 ++- api/generated/oas_security_gen.go | 21 + api/generated/oas_server_gen.go | 63 + api/generated/oas_unimplemented_gen.go | 81 + api/generated/oas_validators_gen.go | 1831 +- .../parameters/app-client-slug.yaml | 9 + api/openapi/components/parameters/app-id.yaml | 7 + .../parameters/app-revision-id.yaml | 7 + .../schemas/errors/app-api_not_found.yaml | 14 + .../schemas/errors/app-client_id_taken.yaml | 14 + .../schemas/errors/app-client_not_found.yaml | 14 + .../errors/app-client_secret_invalid.yaml | 14 + .../schemas/errors/app-declared.yaml | 14 + .../schemas/errors/app-field_immutable.yaml | 14 + .../schemas/errors/app-identifier_taken.yaml | 14 + .../schemas/errors/app-invalid.yaml | 14 + .../schemas/errors/app-invalid_scope.yaml | 14 + .../schemas/errors/app-not_found.yaml | 14 + .../schemas/errors/app-permission_denied.yaml | 14 + .../schemas/errors/app-revision_conflict.yaml | 14 + api/openapi/endpoints/apps/app-client-id.yaml | 16 + .../endpoints/apps/app-client-secret.yaml | 14 + api/openapi/endpoints/apps/app-response.yaml | 62 + .../add-app-client-secret-request.yaml | 22 + .../add-app-client-secret-response.yaml | 18 + .../addAppClientSecret-error-response.yaml | 94 + .../clients/by_slug/secrets/methods.yaml | 71 + .../apps/by_id/getAppById-error-response.yaml | 59 + api/openapi/endpoints/apps/by_id/methods.yaml | 45 + .../list-app-revisions-response.yaml | 16 + .../listAppRevisions-error-response.yaml | 59 + .../apps/by_id/revisions/methods.yaml | 45 + .../endpoints/apps/create-app-request.yaml | 12 + .../apps/createApp-error-response.yaml | 108 + api/openapi/endpoints/apps/methods.yaml | 137 + .../apps/query/app-filter-field.yaml | 11 + api/openapi/endpoints/apps/query/methods.yaml | 55 + .../apps/query/query-apps-request.yaml | 41 + .../apps/query/query-apps-response.yaml | 16 + .../apps/query/queryApps-error-response.yaml | 66 + .../getAppRevisionById-error-response.yaml | 59 + .../apps/revisions/by_id/methods.yaml | 44 + api/openapi/endpoints/events/event.yaml | 6 + .../app-client-secret-added-payload.yaml | 24 + .../events/payloads/app-payload.yaml | 31 + .../types/app-client_secret-added-event.yaml | 16 + .../events/types/app-created-event.yaml | 16 + .../events/types/app-updated-event.yaml | 16 + .../webhooks/app-client_secret-added.yaml | 26 + .../events/webhooks/app-created.yaml | 25 + .../events/webhooks/app-updated.yaml | 26 + .../build/buildRelease-error-response.yaml | 28 + .../releases/build/configuration-bundle.yaml | 15 + .../endpoints/schemas/app-api-scope.yaml | 21 + api/openapi/endpoints/schemas/app-api.json | 82 + api/openapi/endpoints/schemas/app-api.yaml | 51 + .../endpoints/schemas/app-client-api.yaml | 25 + api/openapi/endpoints/schemas/app-client.json | 153 + api/openapi/endpoints/schemas/app-client.yaml | 121 + .../endpoints/schemas/app-registration.json | 18 + .../endpoints/schemas/app-registration.yaml | 18 + api/openapi/endpoints/schemas/app.json | 65 + api/openapi/endpoints/schemas/app.yaml | 54 + api/openapi/openapi-spec.yaml | 25 + api/openapi/security/oauth2.yaml | 4 + apps/cli/command-reference.json | 192 + apps/cli/package.json | 3 + apps/cli/skills/zitadel-cli/SKILL.md | 16 + apps/cli/src/commands/apps/create.ts | 217 + apps/cli/src/commands/resources.ts | 33 + apps/cli/src/index.ts | 2 + apps/cli/src/lib/app/index.ts | 6 + apps/cli/src/lib/release/bundle.ts | 12 +- .../tests/unit/commands/api-coverage.test.ts | 7 + .../tests/unit/commands/app-create.test.ts | 117 + apps/cli/tests/unit/commands/help.test.ts | 1 + .../cli/tests/unit/commands/resources.test.ts | 9 +- .../cli/tests/unit/lib/release/bundle.test.ts | 20 + cmd/server/server.go | 6 +- docs/adrs/047-dialect-id-generation.md | 4 + docs/design/api/events-catalog.md | 3 + internal/api/app.go | 233 + internal/api/authz.go | 11 + internal/api/error_handler.go | 2 + internal/api/handler.go | 8 + internal/api/integration_test/app_test.go | 91 + .../api/integration_test/helpers/release.go | 1 + .../api/integration_test/helpers/server.go | 2 +- internal/api/release.go | 9 + internal/audit/catalog_producers_test.go | 3 + internal/domain/app.go | 670 + internal/domain/app_test.go | 266 + internal/domain/authz.go | 1 + internal/domain/bundle_shape.go | 41 +- internal/domain/event.go | 4 + internal/domain/event_payload.go | 77 + internal/domain/release.go | 5 + internal/domain/releasepointerkind_enumer.go | 12 +- internal/domain/schema_validator.go | 2 + internal/service/app.go | 689 + internal/service/app_directory.go | 248 + internal/service/app_sqlite_test.go | 309 + internal/service/deployment_variables.go | 8 + internal/service/mocks/service.mock.go | 578 + internal/service/release.go | 8 +- internal/service/release_build.go | 70 +- internal/service/release_build_test.go | 6 +- internal/service/release_test.go | 2 +- internal/service/statement.go | 62 + internal/storage/appstore/schema.go | 116 + internal/storage/dialect/postgres/app.go | 355 + .../postgres/migration/sql/000039_apps.sql | 130 + .../storage/dialect/postgres/statement.go | 2 + internal/storage/dialect/spanner/app.go | 361 + .../spanner/migration/sql/000042_apps.sql | 149 + internal/storage/dialect/spanner/statement.go | 2 + internal/storage/dialect/sqlite/app.go | 370 + .../sqlite/migration/sql/000026_apps.sql | 156 + internal/storage/dialect/sqlite/statement.go | 2 + internal/storage/stmttest/app_test.go | 999 + .../stmttest/cursor_battle_apps_test.go | 86 + .../storage/stmttest/cursor_battle_test.go | 2 + .../stmttest/schema_nullability_test.go | 20 +- packages/config/package.json | 5 + packages/config/src/app/index.ts | 12 + packages/config/src/app/presets.test.ts | 63 + packages/config/src/app/presets.ts | 221 + packages/config/src/meta-schemas.test.ts | 4 + packages/config/src/meta-schemas.ts | 15 + packages/config/tsdown.config.ts | 1 + 147 files changed, 49656 insertions(+), 16006 deletions(-) create mode 100644 .changeset/apps-one-document.md create mode 100644 api/openapi/components/parameters/app-client-slug.yaml create mode 100644 api/openapi/components/parameters/app-id.yaml create mode 100644 api/openapi/components/parameters/app-revision-id.yaml create mode 100644 api/openapi/components/schemas/errors/app-api_not_found.yaml create mode 100644 api/openapi/components/schemas/errors/app-client_id_taken.yaml create mode 100644 api/openapi/components/schemas/errors/app-client_not_found.yaml create mode 100644 api/openapi/components/schemas/errors/app-client_secret_invalid.yaml create mode 100644 api/openapi/components/schemas/errors/app-declared.yaml create mode 100644 api/openapi/components/schemas/errors/app-field_immutable.yaml create mode 100644 api/openapi/components/schemas/errors/app-identifier_taken.yaml create mode 100644 api/openapi/components/schemas/errors/app-invalid.yaml create mode 100644 api/openapi/components/schemas/errors/app-invalid_scope.yaml create mode 100644 api/openapi/components/schemas/errors/app-not_found.yaml create mode 100644 api/openapi/components/schemas/errors/app-permission_denied.yaml create mode 100644 api/openapi/components/schemas/errors/app-revision_conflict.yaml create mode 100644 api/openapi/endpoints/apps/app-client-id.yaml create mode 100644 api/openapi/endpoints/apps/app-client-secret.yaml create mode 100644 api/openapi/endpoints/apps/app-response.yaml create mode 100644 api/openapi/endpoints/apps/by_id/clients/by_slug/secrets/add-app-client-secret-request.yaml create mode 100644 api/openapi/endpoints/apps/by_id/clients/by_slug/secrets/add-app-client-secret-response.yaml create mode 100644 api/openapi/endpoints/apps/by_id/clients/by_slug/secrets/addAppClientSecret-error-response.yaml create mode 100644 api/openapi/endpoints/apps/by_id/clients/by_slug/secrets/methods.yaml create mode 100644 api/openapi/endpoints/apps/by_id/getAppById-error-response.yaml create mode 100644 api/openapi/endpoints/apps/by_id/methods.yaml create mode 100644 api/openapi/endpoints/apps/by_id/revisions/list-app-revisions-response.yaml create mode 100644 api/openapi/endpoints/apps/by_id/revisions/listAppRevisions-error-response.yaml create mode 100644 api/openapi/endpoints/apps/by_id/revisions/methods.yaml create mode 100644 api/openapi/endpoints/apps/create-app-request.yaml create mode 100644 api/openapi/endpoints/apps/createApp-error-response.yaml create mode 100644 api/openapi/endpoints/apps/methods.yaml create mode 100644 api/openapi/endpoints/apps/query/app-filter-field.yaml create mode 100644 api/openapi/endpoints/apps/query/methods.yaml create mode 100644 api/openapi/endpoints/apps/query/query-apps-request.yaml create mode 100644 api/openapi/endpoints/apps/query/query-apps-response.yaml create mode 100644 api/openapi/endpoints/apps/query/queryApps-error-response.yaml create mode 100644 api/openapi/endpoints/apps/revisions/by_id/getAppRevisionById-error-response.yaml create mode 100644 api/openapi/endpoints/apps/revisions/by_id/methods.yaml create mode 100644 api/openapi/endpoints/events/payloads/app-client-secret-added-payload.yaml create mode 100644 api/openapi/endpoints/events/payloads/app-payload.yaml create mode 100644 api/openapi/endpoints/events/types/app-client_secret-added-event.yaml create mode 100644 api/openapi/endpoints/events/types/app-created-event.yaml create mode 100644 api/openapi/endpoints/events/types/app-updated-event.yaml create mode 100644 api/openapi/endpoints/events/webhooks/app-client_secret-added.yaml create mode 100644 api/openapi/endpoints/events/webhooks/app-created.yaml create mode 100644 api/openapi/endpoints/events/webhooks/app-updated.yaml create mode 100644 api/openapi/endpoints/schemas/app-api-scope.yaml create mode 100644 api/openapi/endpoints/schemas/app-api.json create mode 100644 api/openapi/endpoints/schemas/app-api.yaml create mode 100644 api/openapi/endpoints/schemas/app-client-api.yaml create mode 100644 api/openapi/endpoints/schemas/app-client.json create mode 100644 api/openapi/endpoints/schemas/app-client.yaml create mode 100644 api/openapi/endpoints/schemas/app-registration.json create mode 100644 api/openapi/endpoints/schemas/app-registration.yaml create mode 100644 api/openapi/endpoints/schemas/app.json create mode 100644 api/openapi/endpoints/schemas/app.yaml create mode 100644 apps/cli/src/commands/apps/create.ts create mode 100644 apps/cli/src/lib/app/index.ts create mode 100644 apps/cli/tests/unit/commands/app-create.test.ts create mode 100644 internal/api/app.go create mode 100644 internal/api/integration_test/app_test.go create mode 100644 internal/domain/app.go create mode 100644 internal/domain/app_test.go create mode 100644 internal/service/app.go create mode 100644 internal/service/app_directory.go create mode 100644 internal/service/app_sqlite_test.go create mode 100644 internal/storage/appstore/schema.go create mode 100644 internal/storage/dialect/postgres/app.go create mode 100644 internal/storage/dialect/postgres/migration/sql/000039_apps.sql create mode 100644 internal/storage/dialect/spanner/app.go create mode 100644 internal/storage/dialect/spanner/migration/sql/000042_apps.sql create mode 100644 internal/storage/dialect/sqlite/app.go create mode 100644 internal/storage/dialect/sqlite/migration/sql/000026_apps.sql create mode 100644 internal/storage/stmttest/app_test.go create mode 100644 internal/storage/stmttest/cursor_battle_apps_test.go create mode 100644 packages/config/src/app/index.ts create mode 100644 packages/config/src/app/presets.test.ts create mode 100644 packages/config/src/app/presets.ts diff --git a/.changeset/apps-one-document.md b/.changeset/apps-one-document.md new file mode 100644 index 0000000000..c94fb360d4 --- /dev/null +++ b/.changeset/apps-one-document.md @@ -0,0 +1,7 @@ +--- +"@zitadel/server": minor +"@zitadel/cli": minor +"@zitadel/config": minor +--- + +Apps: one document per app that holds its OAuth and OIDC clients, the APIs it serves and whether clients may register into it. `POST /apps` creates an app or revises it by slug, `POST /apps/query`, `GET /apps/{id}` and the revision reads return it with each client's `client_id`, and `POST /apps/{id}/clients/{client}/secrets` adds a generated or imported secret, a v4 bcrypt hash included. A client keeps the `client_id` the server minted or the one its document chose, for life. A release declares the developer's own apps from `.zitadel/apps/.json`, and only a release changes them. `zitadel apps create --preset ` writes that file from one of eight presets, or registers the app through the API with `--registered`; `zitadel apps list` and `apps get` read them. `@zitadel/config/app` exports the presets. diff --git a/.redocly.lint-ignore.yaml b/.redocly.lint-ignore.yaml index 3aed8a67b2..6e23ac152a 100644 --- a/.redocly.lint-ignore.yaml +++ b/.redocly.lint-ignore.yaml @@ -27,6 +27,8 @@ api/openapi/openapi-spec.yaml: - '#/paths/~1idps~1revisions~1{revision_id}' # The same for policies, whose ids carry the `pol_` prefix. - '#/paths/~1policies~1revisions~1{revision_id}' + # The same for apps, whose ids carry the `app_` prefix. + - '#/paths/~1apps~1revisions~1{revision_id}' api/openapi/components/flows/flow-definition-step.yaml: no-required-schema-properties-undefined: # Every name is a step property defined at the schema root; each arm of the diff --git a/api/cmd/gen_event_schemas/main.go b/api/cmd/gen_event_schemas/main.go index 246281465e..26842feee4 100644 --- a/api/cmd/gen_event_schemas/main.go +++ b/api/cmd/gen_event_schemas/main.go @@ -81,6 +81,10 @@ var payloadByEventType = map[string]string{ "idp.identity_link.created": "idp-identity-link-created-payload.yaml", + "app.created": "app-payload.yaml", + "app.updated": "app-payload.yaml", + "app.client_secret.added": "app-client-secret-added-payload.yaml", + "deployment.created": "deployment-created-payload.yaml", "origin.added": "origin-payload.yaml", @@ -185,6 +189,12 @@ var webhookByEventType = map[string]webhookDoc{ "idp.identity_link.created": {description: "A user was linked to an account at an identity provider, " + "by an SSO sign-in that created the user."}, + "app.created": {description: "An app was created, by a release that declares it or through the API."}, + "app.updated": {description: "An app was revised. The payload holds the new revision and the fields " + + "that changed."}, + "app.client_secret.added": {description: "A client of an app registered through the API got a secret, " + + "generated by the server or imported."}, + "deployment.created": {description: "A release was deployed, or a deployment rolled back. One event " + "per deployment, however many targets it has."}, diff --git a/api/cmd/gen_event_schemas/main_test.go b/api/cmd/gen_event_schemas/main_test.go index c26ef33337..de82076001 100644 --- a/api/cmd/gen_event_schemas/main_test.go +++ b/api/cmd/gen_event_schemas/main_test.go @@ -23,7 +23,7 @@ func TestPayloadMapCoversDomainEventTypes(t *testing.T) { eventTypes, err := extractEventTypes(domainEventPath) require.NoError(t, err) - require.Len(t, eventTypes, 44, "domain EventType constant count changed; update payloadByEventType") + require.Len(t, eventTypes, 47, "domain EventType constant count changed; update payloadByEventType") require.NoError(t, validateMappings(eventTypes, payloadsDir)) } diff --git a/api/generated/oas_cfg_gen.go b/api/generated/oas_cfg_gen.go index 28903d5092..dd295cb11e 100644 --- a/api/generated/oas_cfg_gen.go +++ b/api/generated/oas_cfg_gen.go @@ -21,21 +21,26 @@ var regexMap = map[string]ogenregex.Regexp{ "^ *(?:\"[^\"\\\\;{}]*\"|'[^'\\\\;{}]*'|[A-Za-z0-9_-]+(?: [A-Za-z0-9_-]+)*)(?: *, *(?:\"[^\"\\\\;{}]*\"|'[^'\\\\;{}]*'|[A-Za-z0-9_-]+(?: [A-Za-z0-9_-]+)*))* *$": ogenregex.MustCompile("^ *(?:\"[^\"\\\\;{}]*\"|'[^'\\\\;{}]*'|[A-Za-z0-9_-]+(?: [A-Za-z0-9_-]+)*)(?: *, *(?:\"[^\"\\\\;{}]*\"|'[^'\\\\;{}]*'|[A-Za-z0-9_-]+(?: [A-Za-z0-9_-]+)*))* *$"), "^(?:#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})|[a-zA-Z]{3,24}|[a-zA-Z][a-zA-Z-]{2,12}\\((?:[0-9a-zA-Z%.,+/# -]|[a-zA-Z][a-zA-Z-]{2,12}\\([0-9a-zA-Z%.,+/# -]*\\))*\\))$": ogenregex.MustCompile("^(?:#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})|[a-zA-Z]{3,24}|[a-zA-Z][a-zA-Z-]{2,12}\\((?:[0-9a-zA-Z%.,+/# -]|[a-zA-Z][a-zA-Z-]{2,12}\\([0-9a-zA-Z%.,+/# -]*\\))*\\))$"), "^([hH][tT][tT][pP][sS]://(?:\\[[0-9A-Fa-f:.]+\\]|[^/:?#@]+)(?::0*(?:[0-9]|[1-9][0-9]{1,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5]))?(?:[/?#]|$)|[hH][tT][tT][pP]://([lL][oO][cC][aA][lL][hH][oO][sS][tT]|127\\.(?:(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\\.){2}(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])|\\[::1\\])(?::0*(?:[0-9]|[1-9][0-9]{1,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5]))?([/?#]|$))": ogenregex.MustCompile("^([hH][tT][tT][pP][sS]://(?:\\[[0-9A-Fa-f:.]+\\]|[^/:?#@]+)(?::0*(?:[0-9]|[1-9][0-9]{1,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5]))?(?:[/?#]|$)|[hH][tT][tT][pP]://([lL][oO][cC][aA][lL][hH][oO][sS][tT]|127\\.(?:(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\\.){2}(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])|\\[::1\\])(?::0*(?:[0-9]|[1-9][0-9]{1,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5]))?([/?#]|$))"), - "^(https://[^\\s/?#]+|http://(localhost|127\\.0\\.0\\.1)(:[0-9]+)?)(/[^\\s?#]*)?$": ogenregex.MustCompile("^(https://[^\\s/?#]+|http://(localhost|127\\.0\\.0\\.1)(:[0-9]+)?)(/[^\\s?#]*)?$"), - "^(https://[^\\s/?#]+|http://(localhost|127\\.0\\.0\\.1)(:[0-9]+)?)([/?][^\\s#]*)?$": ogenregex.MustCompile("^(https://[^\\s/?#]+|http://(localhost|127\\.0\\.0\\.1)(:[0-9]+)?)([/?][^\\s#]*)?$"), + "^(https://[^\\s/?#]+|http://(localhost|127\\.0\\.0\\.1)(:[0-9]+)?)(/[^\\s?#]*)?$": ogenregex.MustCompile("^(https://[^\\s/?#]+|http://(localhost|127\\.0\\.0\\.1)(:[0-9]+)?)(/[^\\s?#]*)?$"), + "^(https://[^\\s/?#]+|http://(localhost|127\\.0\\.0\\.1)(:[0-9]+)?)([/?][^\\s#]*)?$": ogenregex.MustCompile("^(https://[^\\s/?#]+|http://(localhost|127\\.0\\.0\\.1)(:[0-9]+)?)([/?][^\\s#]*)?$"), + "^(https://|http://|urn:)": ogenregex.MustCompile("^(https://|http://|urn:)"), "^(primary|https?://(\\[[0-9a-f:.]+\\]|[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*)(:(6553[0-5]|655[0-2][0-9]|65[0-4][0-9]{2}|6[0-4][0-9]{3}|[1-5][0-9]{4}|[1-9][0-9]{0,3}))?)$": ogenregex.MustCompile("^(primary|https?://(\\[[0-9a-f:.]+\\]|[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*)(:(6553[0-5]|655[0-2][0-9]|65[0-4][0-9]{2}|6[0-4][0-9]{3}|[1-5][0-9]{4}|[1-9][0-9]{0,3}))?)$"), - "^[^$]": ogenregex.MustCompile("^[^$]"), - "^[a-z0-9][a-z0-9_-]*$": ogenregex.MustCompile("^[a-z0-9][a-z0-9_-]*$"), - "^[a-zA-Z0-9_-]+$": ogenregex.MustCompile("^[a-zA-Z0-9_-]+$"), - "^[a-z][a-z0-9-]*$": ogenregex.MustCompile("^[a-z][a-z0-9-]*$"), - "^[a-z][a-z0-9_-]*$": ogenregex.MustCompile("^[a-z][a-z0-9_-]*$"), + "^[A-Za-z0-9._~@-]+$": ogenregex.MustCompile("^[A-Za-z0-9._~@-]+$"), + "^[A-Za-z0-9][A-Za-z0-9._:/-]*$": ogenregex.MustCompile("^[A-Za-z0-9][A-Za-z0-9._:/-]*$"), + "^[^$]": ogenregex.MustCompile("^[^$]"), + "^[a-z0-9][a-z0-9_-]*$": ogenregex.MustCompile("^[a-z0-9][a-z0-9_-]*$"), + "^[a-z0-9][a-z0-9_-]*(/[a-z0-9][a-z0-9_-]*)?$": ogenregex.MustCompile("^[a-z0-9][a-z0-9_-]*(/[a-z0-9][a-z0-9_-]*)?$"), + "^[a-zA-Z0-9_-]+$": ogenregex.MustCompile("^[a-zA-Z0-9_-]+$"), + "^[a-z][a-z0-9-]*$": ogenregex.MustCompile("^[a-z][a-z0-9-]*$"), + "^[a-z][a-z0-9_-]*$": ogenregex.MustCompile("^[a-z][a-z0-9_-]*$"), "^[hH][tT][tT][pP][sS]://(?:\\[[0-9A-Fa-f:.]+\\]|[^/:?#@]+)(?::0*(?:[0-9]|[1-9][0-9]{1,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5]))?(?:[/?#]|$)": ogenregex.MustCompile("^[hH][tT][tT][pP][sS]://(?:\\[[0-9A-Fa-f:.]+\\]|[^/:?#@]+)(?::0*(?:[0-9]|[1-9][0-9]{1,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5]))?(?:[/?#]|$)"), - "^\\$\\{\\{ *[A-Za-z0-9_]+ *\\}\\}$": ogenregex.MustCompile("^\\$\\{\\{ *[A-Za-z0-9_]+ *\\}\\}$"), - "^\\d+\\.\\d+\\.\\d+$": ogenregex.MustCompile("^\\d+\\.\\d+\\.\\d+$"), - "^\\w+$": ogenregex.MustCompile("^\\w+$"), - "^att_[a-zA-Z0-9_-]+$": ogenregex.MustCompile("^att_[a-zA-Z0-9_-]+$"), - "^ch_[a-zA-Z0-9_-]+$": ogenregex.MustCompile("^ch_[a-zA-Z0-9_-]+$"), - "^dep_[a-zA-Z0-9_-]+$": ogenregex.MustCompile("^dep_[a-zA-Z0-9_-]+$"), + "^\\$\\{\\{ *[A-Z_][A-Z0-9_]* *\\}\\}$": ogenregex.MustCompile("^\\$\\{\\{ *[A-Z_][A-Z0-9_]* *\\}\\}$"), + "^\\$\\{\\{ *[A-Za-z0-9_]+ *\\}\\}$": ogenregex.MustCompile("^\\$\\{\\{ *[A-Za-z0-9_]+ *\\}\\}$"), + "^\\d+\\.\\d+\\.\\d+$": ogenregex.MustCompile("^\\d+\\.\\d+\\.\\d+$"), + "^\\w+$": ogenregex.MustCompile("^\\w+$"), + "^att_[a-zA-Z0-9_-]+$": ogenregex.MustCompile("^att_[a-zA-Z0-9_-]+$"), + "^ch_[a-zA-Z0-9_-]+$": ogenregex.MustCompile("^ch_[a-zA-Z0-9_-]+$"), + "^dep_[a-zA-Z0-9_-]+$": ogenregex.MustCompile("^dep_[a-zA-Z0-9_-]+$"), "^https?://(\\[[0-9a-f:.]+\\]|[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*)(:(6553[0-5]|655[0-2][0-9]|65[0-4][0-9]{2}|6[0-4][0-9]{3}|[1-5][0-9]{4}|[1-9][0-9]{0,3}))?$": ogenregex.MustCompile("^https?://(\\[[0-9a-f:.]+\\]|[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*)(:(6553[0-5]|655[0-2][0-9]|65[0-4][0-9]{2}|6[0-4][0-9]{3}|[1-5][0-9]{4}|[1-9][0-9]{0,3}))?$"), "^pol_[a-zA-Z0-9_-]+$": ogenregex.MustCompile("^pol_[a-zA-Z0-9_-]+$"), "^polrev_[a-zA-Z0-9_-]+$": ogenregex.MustCompile("^polrev_[a-zA-Z0-9_-]+$"), diff --git a/api/generated/oas_client_gen.go b/api/generated/oas_client_gen.go index aaebb71b4d..1eda6d44a6 100644 --- a/api/generated/oas_client_gen.go +++ b/api/generated/oas_client_gen.go @@ -28,6 +28,16 @@ func trimTrailingSlashes(u *url.URL) { // Invoker invokes operations described by OpenAPI v3 specification. type Invoker interface { + // AddAppClientSecret invokes addAppClientSecret operation. + // + // Adds a secret to a confidential client of an app registered through the + // API: a generated one, shown once, or an imported value or hash, so a client + // with a secret it cannot change keeps working. An app the release declares + // names its secrets as `${{ NAME }}` variables instead, and is refused with + // `app.declared`. + // + // POST /apps/{id}/clients/{client}/secrets + AddAppClientSecret(ctx context.Context, request *AddAppClientSecretRequest, params AddAppClientSecretParams) (AddAppClientSecretRes, error) // AddOrigin invokes addOrigin operation. // // Adds one `{pattern, kind}` to the project's origins. A primary pattern @@ -90,6 +100,28 @@ type Invoker interface { // // POST /projects/{project_id}/claim/complete CompleteClaim(ctx context.Context, request *CompleteClaimRequest, params CompleteClaimParams) (CompleteClaimRes, error) + // CreateApp invokes createApp operation. + // + // Creates or revises an app document. If the slug is new in the project, the + // app is created; if an app this endpoint registered has the slug, the + // document becomes its new revision. An app the release declares + // (`.zitadel/apps/.json`) changes only with a release, and a write to + // one is refused with `app.declared`. + // The answer carries what comes next: the `client_id` of each client, and a + // generated secret for each confidential client that had none, shown once. + // A client keeps its `client_id` for life: one the document leaves out is + // minted on first write and kept, one it sets is used as given, and a + // revision that changes it is refused with `app.field_immutable`. No two + // clients in a project share a `client_id`, and no two apps an API + // identifier. + // The document is validated against the `app.json` schema, then against the + // rules across its fields: a client's `apis` name APIs the app serves, a + // redirect URI is https or a loopback http URI in canonical form, and a + // registered app's secrets come from the server, never a `${{ NAME }}` + // reference. A refused document stores nothing. + // + // POST /apps + CreateApp(ctx context.Context, request *CreateAppRequest, params CreateAppParams) (CreateAppRes, error) // CreateAuthAttempt invokes createAuthAttempt operation. // // Starts a new authentication attempt. This is the entry point for the auth_attempts state machine. @@ -445,6 +477,22 @@ type Invoker interface { // // POST /users/{user_id}/passkeys/registrations/{registration_id} FinishUserPasskeyRegistration(ctx context.Context, request *FinishUserPasskeyRegistrationRequest, params FinishUserPasskeyRegistrationParams) (FinishUserPasskeyRegistrationRes, error) + // GetAppById invokes getAppById operation. + // + // Reads an app by its id, at its newest revision, with the `client_id` of + // each client. `GET /apps/{id}/revisions` lists every revision. + // The lookup is scoped to the project in `project_id`. + // + // GET /apps/{id} + GetAppById(ctx context.Context, params GetAppByIdParams) (GetAppByIdRes, error) + // GetAppRevisionById invokes getAppRevisionById operation. + // + // Reads one revision of an app by its `revision_id`, the value a release + // pins. + // The lookup is scoped to the project in `project_id`. + // + // GET /apps/revisions/{revision_id} + GetAppRevisionById(ctx context.Context, params GetAppRevisionByIdParams) (GetAppRevisionByIdRes, error) // GetAuthAttempt invokes getAuthAttempt operation. // // Polls the current state of an authentication attempt. @@ -756,6 +804,14 @@ type Invoker interface { // // POST /auth_attempts/{attempt_id}/challenges IssueChallenge(ctx context.Context, request *IssueChallengeRequest, params IssueChallengeParams) (IssueChallengeRes, error) + // ListAppRevisions invokes listAppRevisions operation. + // + // Returns every revision of one app, newest first, paginated with a cursor. + // The order is fixed, so there is no `sorting`. + // The lookup is scoped to the project in `project_id`. + // + // GET /apps/{id}/revisions + ListAppRevisions(ctx context.Context, params ListAppRevisionsParams) (ListAppRevisionsRes, error) // ListBranding invokes listBranding operation. // // Lists branding revisions for the project, newest first, capped at the @@ -1008,6 +1064,13 @@ type Invoker interface { // // POST /policies PublishPolicy(ctx context.Context, request PublishPolicyRequest, params PublishPolicyParams) (PublishPolicyRes, error) + // QueryApps invokes queryApps operation. + // + // Returns the apps of a project, paginated with a cursor. One row per app, + // carrying its newest revision and the `client_id` of each client. + // + // POST /apps/query + QueryApps(ctx context.Context, request *QueryAppsRequest, params QueryAppsParams) (QueryAppsRes, error) // QueryGrants invokes queryGrants operation. // // Returns the collaboration grants of a project, paginated with a cursor. @@ -1292,6 +1355,188 @@ func (c *Client) requestURL(ctx context.Context) *url.URL { return u } +// AddAppClientSecret invokes addAppClientSecret operation. +// +// Adds a secret to a confidential client of an app registered through the +// API: a generated one, shown once, or an imported value or hash, so a client +// with a secret it cannot change keeps working. An app the release declares +// names its secrets as `${{ NAME }}` variables instead, and is refused with +// `app.declared`. +// +// POST /apps/{id}/clients/{client}/secrets +func (c *Client) AddAppClientSecret(ctx context.Context, request *AddAppClientSecretRequest, params AddAppClientSecretParams) (AddAppClientSecretRes, error) { + res, err := c.sendAddAppClientSecret(ctx, request, params) + return res, err +} + +func (c *Client) sendAddAppClientSecret(ctx context.Context, request *AddAppClientSecretRequest, params AddAppClientSecretParams) (res AddAppClientSecretRes, err error) { + // Validate request before sending. + if err := func() error { + if err := request.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return res, errors.Wrap(err, "validate") + } + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("addAppClientSecret"), + semconv.HTTPRequestMethodKey.String("POST"), + semconv.URLTemplateKey.String("/apps/{id}/clients/{client}/secrets"), + } + otelAttrs = append(otelAttrs, c.cfg.Attributes...) + + // Run stopwatch. + startTime := time.Now() + defer func() { + // Use floating point division here for higher precision (instead of Millisecond method). + elapsedDuration := time.Since(startTime) + c.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), metric.WithAttributes(otelAttrs...)) + }() + + // Increment request counter. + c.requests.Add(ctx, 1, metric.WithAttributes(otelAttrs...)) + + // Start a span for this request. + ctx, span := c.cfg.Tracer.Start(ctx, AddAppClientSecretOperation, + trace.WithAttributes(otelAttrs...), + clientSpanKind, + ) + // Track stage for error reporting. + var stage string + defer func() { + if err != nil { + span.RecordError(err) + span.SetStatus(codes.Error, stage) + c.errors.Add(ctx, 1, metric.WithAttributes(otelAttrs...)) + } + span.End() + }() + + stage = "BuildURL" + u := uri.Clone(c.requestURL(ctx)) + var pathParts [5]string + pathParts[0] = "/apps/" + { + // Encode "id" parameter. + e := uri.NewPathEncoder(uri.PathEncoderConfig{ + Param: "id", + Style: uri.PathStyleSimple, + Explode: false, + }) + if err := func() error { + return e.EncodeValue(conv.StringToString(params.ID)) + }(); err != nil { + return res, errors.Wrap(err, "encode path") + } + encoded, err := e.Result() + if err != nil { + return res, errors.Wrap(err, "encode path") + } + pathParts[1] = encoded + } + pathParts[2] = "/clients/" + { + // Encode "client" parameter. + e := uri.NewPathEncoder(uri.PathEncoderConfig{ + Param: "client", + Style: uri.PathStyleSimple, + Explode: false, + }) + if err := func() error { + return e.EncodeValue(conv.StringToString(params.Client)) + }(); err != nil { + return res, errors.Wrap(err, "encode path") + } + encoded, err := e.Result() + if err != nil { + return res, errors.Wrap(err, "encode path") + } + pathParts[3] = encoded + } + pathParts[4] = "/secrets" + uri.AddPathParts(u, pathParts[:]...) + + stage = "EncodeQueryParams" + q := uri.NewQueryEncoder() + { + // Encode "project_id" parameter. + cfg := uri.QueryParameterEncodingConfig{ + Name: "project_id", + Style: uri.QueryStyleForm, + Explode: true, + } + + if err := q.EncodeParam(cfg, func(e uri.Encoder) error { + if unwrapped := string(params.ProjectID); true { + return e.EncodeValue(conv.StringToString(unwrapped)) + } + return nil + }); err != nil { + return res, errors.Wrap(err, "encode query") + } + } + u.RawQuery = q.Values().Encode() + + stage = "EncodeRequest" + r, err := ht.NewRequest(ctx, "POST", u) + if err != nil { + return res, errors.Wrap(err, "create request") + } + if err := encodeAddAppClientSecretRequest(request, r); err != nil { + return res, errors.Wrap(err, "encode request") + } + + { + type bitset = [1]uint8 + var satisfied bitset + { + stage = "Security:OAuth2" + switch err := c.securityOAuth2(ctx, AddAppClientSecretOperation, r); { + case err == nil: // if NO error + satisfied[0] |= 1 << 0 + case errors.Is(err, ogenerrors.ErrSkipClientSecurity): + // Skip this security. + default: + return res, errors.Wrap(err, "security \"OAuth2\"") + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000001}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + return res, ogenerrors.ErrSecurityRequirementIsNotSatisfied + } + } + + stage = "SendRequest" + resp, err := c.cfg.Client.Do(r) + if err != nil { + return res, errors.Wrap(err, "do request") + } + body := resp.Body + defer body.Close() + + stage = "DecodeResponse" + result, err := decodeAddAppClientSecretResponse(resp) + if err != nil { + return res, errors.Wrap(err, "decode response") + } + + return result, nil +} + // AddOrigin invokes addOrigin operation. // // Adds one `{pattern, kind}` to the project's origins. A primary pattern @@ -1905,26 +2150,33 @@ func (c *Client) sendCompleteClaim(ctx context.Context, request *CompleteClaimRe return result, nil } -// CreateAuthAttempt invokes createAuthAttempt operation. +// CreateApp invokes createApp operation. // -// Starts a new authentication attempt. This is the entry point for the auth_attempts state machine. -// An attempt is an ephemeral (15-minute TTL) state machine that drives a single authentication round. -// It accepts factor challenges, verifies proofs, and completes into a session or handoff token. -// Accepts a project_id and challenge_nonce (from POST /bootstrap/challenge). For step-up re-auth, -// also include session_id and that session's session_token to add factors to an existing session. -// The project comes from the project secret. A body `project_id` that disagrees -// answers `403` with `proj.mismatch`. Sealed `deployment_id` / `release_id` are -// filled only when create runs with a runtime resolution already on the -// context (the flow create path); this HTTP entry point does not resolve -// Origin or refuse a revoked release itself. +// Creates or revises an app document. If the slug is new in the project, the +// app is created; if an app this endpoint registered has the slug, the +// document becomes its new revision. An app the release declares +// (`.zitadel/apps/.json`) changes only with a release, and a write to +// one is refused with `app.declared`. +// The answer carries what comes next: the `client_id` of each client, and a +// generated secret for each confidential client that had none, shown once. +// A client keeps its `client_id` for life: one the document leaves out is +// minted on first write and kept, one it sets is used as given, and a +// revision that changes it is refused with `app.field_immutable`. No two +// clients in a project share a `client_id`, and no two apps an API +// identifier. +// The document is validated against the `app.json` schema, then against the +// rules across its fields: a client's `apis` name APIs the app serves, a +// redirect URI is https or a loopback http URI in canonical form, and a +// registered app's secrets come from the server, never a `${{ NAME }}` +// reference. A refused document stores nothing. // -// POST /auth_attempts -func (c *Client) CreateAuthAttempt(ctx context.Context, request *CreateAuthAttemptRequest) (CreateAuthAttemptRes, error) { - res, err := c.sendCreateAuthAttempt(ctx, request) +// POST /apps +func (c *Client) CreateApp(ctx context.Context, request *CreateAppRequest, params CreateAppParams) (CreateAppRes, error) { + res, err := c.sendCreateApp(ctx, request, params) return res, err } -func (c *Client) sendCreateAuthAttempt(ctx context.Context, request *CreateAuthAttemptRequest) (res CreateAuthAttemptRes, err error) { +func (c *Client) sendCreateApp(ctx context.Context, request *CreateAppRequest, params CreateAppParams) (res CreateAppRes, err error) { // Validate request before sending. if err := func() error { if err := request.Validate(); err != nil { @@ -1935,9 +2187,9 @@ func (c *Client) sendCreateAuthAttempt(ctx context.Context, request *CreateAuthA return res, errors.Wrap(err, "validate") } otelAttrs := []attribute.KeyValue{ - otelogen.OperationID("createAuthAttempt"), + otelogen.OperationID("createApp"), semconv.HTTPRequestMethodKey.String("POST"), - semconv.URLTemplateKey.String("/auth_attempts"), + semconv.URLTemplateKey.String("/apps"), } otelAttrs = append(otelAttrs, c.cfg.Attributes...) @@ -1953,7 +2205,7 @@ func (c *Client) sendCreateAuthAttempt(ctx context.Context, request *CreateAuthA c.requests.Add(ctx, 1, metric.WithAttributes(otelAttrs...)) // Start a span for this request. - ctx, span := c.cfg.Tracer.Start(ctx, CreateAuthAttemptOperation, + ctx, span := c.cfg.Tracer.Start(ctx, CreateAppOperation, trace.WithAttributes(otelAttrs...), clientSpanKind, ) @@ -1971,15 +2223,36 @@ func (c *Client) sendCreateAuthAttempt(ctx context.Context, request *CreateAuthA stage = "BuildURL" u := uri.Clone(c.requestURL(ctx)) var pathParts [1]string - pathParts[0] = "/auth_attempts" + pathParts[0] = "/apps" uri.AddPathParts(u, pathParts[:]...) + stage = "EncodeQueryParams" + q := uri.NewQueryEncoder() + { + // Encode "project_id" parameter. + cfg := uri.QueryParameterEncodingConfig{ + Name: "project_id", + Style: uri.QueryStyleForm, + Explode: true, + } + + if err := q.EncodeParam(cfg, func(e uri.Encoder) error { + if unwrapped := string(params.ProjectID); true { + return e.EncodeValue(conv.StringToString(unwrapped)) + } + return nil + }); err != nil { + return res, errors.Wrap(err, "encode query") + } + } + u.RawQuery = q.Values().Encode() + stage = "EncodeRequest" r, err := ht.NewRequest(ctx, "POST", u) if err != nil { return res, errors.Wrap(err, "create request") } - if err := encodeCreateAuthAttemptRequest(request, r); err != nil { + if err := encodeCreateAppRequest(request, r); err != nil { return res, errors.Wrap(err, "encode request") } @@ -1988,7 +2261,7 @@ func (c *Client) sendCreateAuthAttempt(ctx context.Context, request *CreateAuthA var satisfied bitset { stage = "Security:OAuth2" - switch err := c.securityOAuth2(ctx, CreateAuthAttemptOperation, r); { + switch err := c.securityOAuth2(ctx, CreateAppOperation, r); { case err == nil: // if NO error satisfied[0] |= 1 << 0 case errors.Is(err, ogenerrors.ErrSkipClientSecurity): @@ -2025,7 +2298,7 @@ func (c *Client) sendCreateAuthAttempt(ctx context.Context, request *CreateAuthA defer body.Close() stage = "DecodeResponse" - result, err := decodeCreateAuthAttemptResponse(resp) + result, err := decodeCreateAppResponse(resp) if err != nil { return res, errors.Wrap(err, "decode response") } @@ -2033,23 +2306,26 @@ func (c *Client) sendCreateAuthAttempt(ctx context.Context, request *CreateAuthA return result, nil } -// CreateBranding invokes createBranding operation. +// CreateAuthAttempt invokes createAuthAttempt operation. // -// Publishes a new immutable branding revision for the project. Branding -// revisions cannot be updated or deleted; every edit publishes a new -// revision, and flow responses resolve the latest revision per project. -// The `liquid_template` is validated lexically on save (size, encoding, -// banned patterns such as `