diff --git a/.changeset/apps-one-document.md b/.changeset/apps-one-document.md new file mode 100644 index 0000000000..97dde5b988 --- /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 clients, the APIs it serves and whether clients may register into it. `POST /apps` creates an app or revises it by slug, and `POST /apps/query`, `GET /apps/{id}` and the revision reads return it with each client's `client_id`. A client keeps the `client_id` the server minted or the one its document chose, for life, states its `type`, and takes RFC 7591's `grant_types`; a confidential client without `grant_types` holds only credentials. Credentials are named and written on their own: `POST /apps/{id}/clients/{client}/credentials` adds a generated secret, shown once, an imported secret or hash, a v4 bcrypt hash included, or a public key, for declared and registered apps alike, and a deploy never removes one; each is listed and revoked on its own. A release declares the developer's own apps from `.zitadel/apps/.json`, which `zitadel deploy` shows in its diff, 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, and `@zitadel/config/app` exports the presets. Clients that register themselves through dynamic client registration (RFC 7591) are stored per project under a `dcr_` client_id, with the name, logo and links they claim, and join the app whose API their first authorization request names; one nobody consented to expires an hour after it registered. `POST /client_registrations/query`, `GET /client_registrations/{id}` and `zitadel client-registrations list` and `get` show them, and `DELETE /client_registrations/{id}` or `zitadel client-registrations delete` removes one with the consents users gave it. diff --git a/.redocly.lint-ignore.yaml b/.redocly.lint-ignore.yaml index a494127cca..2e47d5cbe7 100644 --- a/.redocly.lint-ignore.yaml +++ b/.redocly.lint-ignore.yaml @@ -8,6 +8,11 @@ apps/api/api/openapi/endpoints/schemas/user-schema.yaml: # a data-format migration. - '#/properties/objectType' - '#/properties/metaSchema' +apps/api/api/openapi/endpoints/schemas/app-client-jwk.yaml: + rule/wire-enum-no-camel-case: + # `EdDSA` is the JOSE name of the Ed25519 signature algorithm (RFC 8037), a + # value a JWK carries as written, not a wire enum of ours. + - '#/properties/alg/enum' apps/api/api/openapi/endpoints/schemas/sso-auth-method.yaml: no-required-schema-properties-undefined: # `providers` is defined at the schema root; the if/then/else arms only @@ -27,6 +32,8 @@ apps/api/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}' apps/api/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/apps/api/api/cmd/gen_event_schemas/main.go b/apps/api/api/cmd/gen_event_schemas/main.go index 246281465e..c76c7396d6 100644 --- a/apps/api/api/cmd/gen_event_schemas/main.go +++ b/apps/api/api/cmd/gen_event_schemas/main.go @@ -81,6 +81,14 @@ 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.credential.added": "app-credential-payload.yaml", + "app.credential.revoked": "app-credential-payload.yaml", + + "client_registration.created": "client-registration-payload.yaml", + "client_registration.deleted": "client-registration-payload.yaml", + "deployment.created": "deployment-created-payload.yaml", "origin.added": "origin-payload.yaml", @@ -185,6 +193,19 @@ 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.credential.added": {description: "A client of an app got a named credential through the API: a " + + "secret the server generated or imported, or a public key."}, + "app.credential.revoked": {description: "A credential of a client of an app was revoked; the client's " + + "other credentials keep working."}, + + "client_registration.created": {description: "A client registered itself through dynamic client " + + "registration (RFC 7591)."}, + "client_registration.deleted": {description: "A client registration was deleted, with its consents " + + "and their tokens. A registration purged after its lifetime emits no event."}, + "deployment.created": {description: "A release was deployed, or a deployment rolled back. One event " + "per deployment, however many targets it has."}, diff --git a/apps/api/api/cmd/gen_event_schemas/main_test.go b/apps/api/api/cmd/gen_event_schemas/main_test.go index f1faf54236..c6f449f66e 100644 --- a/apps/api/api/cmd/gen_event_schemas/main_test.go +++ b/apps/api/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, 50, "domain EventType constant count changed; update payloadByEventType") require.NoError(t, validateMappings(eventTypes, payloadsDir)) } diff --git a/apps/api/api/openapi/components/parameters/app-client-credential-id.yaml b/apps/api/api/openapi/components/parameters/app-client-credential-id.yaml new file mode 100644 index 0000000000..8d7ce67372 --- /dev/null +++ b/apps/api/api/openapi/components/parameters/app-client-credential-id.yaml @@ -0,0 +1,7 @@ +name: credential_id +in: path +required: true +description: The id of a credential of the client. +schema: + type: string +example: cred_01KWH3B72K7M7F0N9WD3P2E4YQ diff --git a/apps/api/api/openapi/components/parameters/app-client-slug.yaml b/apps/api/api/openapi/components/parameters/app-client-slug.yaml new file mode 100644 index 0000000000..650d41aea5 --- /dev/null +++ b/apps/api/api/openapi/components/parameters/app-client-slug.yaml @@ -0,0 +1,9 @@ +name: client +in: path +required: true +description: The slug of a client of the app. +schema: + type: string + pattern: ^[a-z0-9][a-z0-9_-]*$ + maxLength: 64 +example: web diff --git a/apps/api/api/openapi/components/parameters/app-id.yaml b/apps/api/api/openapi/components/parameters/app-id.yaml new file mode 100644 index 0000000000..01a1d3c489 --- /dev/null +++ b/apps/api/api/openapi/components/parameters/app-id.yaml @@ -0,0 +1,7 @@ +name: id +in: path +required: true +description: The app id, allocated when the app was created. +schema: + type: string +example: app_01KWH3B72K7M7F0N9WD3P2E4YM diff --git a/apps/api/api/openapi/components/parameters/app-revision-id.yaml b/apps/api/api/openapi/components/parameters/app-revision-id.yaml new file mode 100644 index 0000000000..8c5b0b8a50 --- /dev/null +++ b/apps/api/api/openapi/components/parameters/app-revision-id.yaml @@ -0,0 +1,7 @@ +name: revision_id +in: path +required: true +description: The id of one revision of an app, the value a release pins. +schema: + type: string +example: apprev_01KWH3B72K7M7F0N9WD3P2E4YN diff --git a/apps/api/api/openapi/components/parameters/client-registration-id.yaml b/apps/api/api/openapi/components/parameters/client-registration-id.yaml new file mode 100644 index 0000000000..dede9cdc35 --- /dev/null +++ b/apps/api/api/openapi/components/parameters/client-registration-id.yaml @@ -0,0 +1,7 @@ +name: id +in: path +required: true +description: The registration's client_id, which the server minted when the client registered. +schema: + type: string +example: dcr_01KWH3B72K7M7F0N9WD3P2E4YM diff --git a/apps/api/api/openapi/components/schemas/errors/app-api_not_found.yaml b/apps/api/api/openapi/components/schemas/errors/app-api_not_found.yaml new file mode 100644 index 0000000000..a527771ef2 --- /dev/null +++ b/apps/api/api/openapi/components/schemas/errors/app-api_not_found.yaml @@ -0,0 +1,14 @@ +# Code generated by gen_error_schemas; DO NOT EDIT. +description: | + App: no API has the identifier + + Error code: app.api_not_found +allOf: + - $ref: ../../error-details.yaml + - type: object + properties: + code: + type: string + const: app.api_not_found + required: + - code diff --git a/apps/api/api/openapi/components/schemas/errors/app-client_id_taken.yaml b/apps/api/api/openapi/components/schemas/errors/app-client_id_taken.yaml new file mode 100644 index 0000000000..63b508dd73 --- /dev/null +++ b/apps/api/api/openapi/components/schemas/errors/app-client_id_taken.yaml @@ -0,0 +1,14 @@ +# Code generated by gen_error_schemas; DO NOT EDIT. +description: | + App: another client in the project holds the client_id + + Error code: app.client_id_taken +allOf: + - $ref: ../../error-details.yaml + - type: object + properties: + code: + type: string + const: app.client_id_taken + required: + - code diff --git a/apps/api/api/openapi/components/schemas/errors/app-client_not_found.yaml b/apps/api/api/openapi/components/schemas/errors/app-client_not_found.yaml new file mode 100644 index 0000000000..d202f8e0d0 --- /dev/null +++ b/apps/api/api/openapi/components/schemas/errors/app-client_not_found.yaml @@ -0,0 +1,14 @@ +# Code generated by gen_error_schemas; DO NOT EDIT. +description: | + App: no client has the client_id + + Error code: app.client_not_found +allOf: + - $ref: ../../error-details.yaml + - type: object + properties: + code: + type: string + const: app.client_not_found + required: + - code diff --git a/apps/api/api/openapi/components/schemas/errors/app-client_registration_invalid.yaml b/apps/api/api/openapi/components/schemas/errors/app-client_registration_invalid.yaml new file mode 100644 index 0000000000..d58e1e15d8 --- /dev/null +++ b/apps/api/api/openapi/components/schemas/errors/app-client_registration_invalid.yaml @@ -0,0 +1,14 @@ +# Code generated by gen_error_schemas; DO NOT EDIT. +description: | + App: the client metadata is invalid + + Error code: app.client_registration_invalid +allOf: + - $ref: ../../error-details.yaml + - type: object + properties: + code: + type: string + const: app.client_registration_invalid + required: + - code diff --git a/apps/api/api/openapi/components/schemas/errors/app-client_registration_not_found.yaml b/apps/api/api/openapi/components/schemas/errors/app-client_registration_not_found.yaml new file mode 100644 index 0000000000..0d196c6113 --- /dev/null +++ b/apps/api/api/openapi/components/schemas/errors/app-client_registration_not_found.yaml @@ -0,0 +1,14 @@ +# Code generated by gen_error_schemas; DO NOT EDIT. +description: | + App: no registered client has the client_id + + Error code: app.client_registration_not_found +allOf: + - $ref: ../../error-details.yaml + - type: object + properties: + code: + type: string + const: app.client_registration_not_found + required: + - code diff --git a/apps/api/api/openapi/components/schemas/errors/app-client_registration_other_app.yaml b/apps/api/api/openapi/components/schemas/errors/app-client_registration_other_app.yaml new file mode 100644 index 0000000000..df789391f7 --- /dev/null +++ b/apps/api/api/openapi/components/schemas/errors/app-client_registration_other_app.yaml @@ -0,0 +1,14 @@ +# Code generated by gen_error_schemas; DO NOT EDIT. +description: | + App: the registered client joined another app + + Error code: app.client_registration_other_app +allOf: + - $ref: ../../error-details.yaml + - type: object + properties: + code: + type: string + const: app.client_registration_other_app + required: + - code diff --git a/apps/api/api/openapi/components/schemas/errors/app-client_secret_invalid.yaml b/apps/api/api/openapi/components/schemas/errors/app-client_secret_invalid.yaml new file mode 100644 index 0000000000..76e6d9a941 --- /dev/null +++ b/apps/api/api/openapi/components/schemas/errors/app-client_secret_invalid.yaml @@ -0,0 +1,14 @@ +# Code generated by gen_error_schemas; DO NOT EDIT. +description: | + App: the client secret does not match + + Error code: app.client_secret_invalid +allOf: + - $ref: ../../error-details.yaml + - type: object + properties: + code: + type: string + const: app.client_secret_invalid + required: + - code diff --git a/apps/api/api/openapi/components/schemas/errors/app-credential_not_found.yaml b/apps/api/api/openapi/components/schemas/errors/app-credential_not_found.yaml new file mode 100644 index 0000000000..4ad567abaa --- /dev/null +++ b/apps/api/api/openapi/components/schemas/errors/app-credential_not_found.yaml @@ -0,0 +1,14 @@ +# Code generated by gen_error_schemas; DO NOT EDIT. +description: | + App: the client holds no credential with the id + + Error code: app.credential_not_found +allOf: + - $ref: ../../error-details.yaml + - type: object + properties: + code: + type: string + const: app.credential_not_found + required: + - code diff --git a/apps/api/api/openapi/components/schemas/errors/app-credential_taken.yaml b/apps/api/api/openapi/components/schemas/errors/app-credential_taken.yaml new file mode 100644 index 0000000000..c582ef9a0e --- /dev/null +++ b/apps/api/api/openapi/components/schemas/errors/app-credential_taken.yaml @@ -0,0 +1,14 @@ +# Code generated by gen_error_schemas; DO NOT EDIT. +description: | + App: another credential of the client has the name or the key id + + Error code: app.credential_taken +allOf: + - $ref: ../../error-details.yaml + - type: object + properties: + code: + type: string + const: app.credential_taken + required: + - code diff --git a/apps/api/api/openapi/components/schemas/errors/app-declared.yaml b/apps/api/api/openapi/components/schemas/errors/app-declared.yaml new file mode 100644 index 0000000000..31390f789b --- /dev/null +++ b/apps/api/api/openapi/components/schemas/errors/app-declared.yaml @@ -0,0 +1,14 @@ +# Code generated by gen_error_schemas; DO NOT EDIT. +description: | + App: declared in the release, so only a release changes it + + Error code: app.declared +allOf: + - $ref: ../../error-details.yaml + - type: object + properties: + code: + type: string + const: app.declared + required: + - code diff --git a/apps/api/api/openapi/components/schemas/errors/app-field_immutable.yaml b/apps/api/api/openapi/components/schemas/errors/app-field_immutable.yaml new file mode 100644 index 0000000000..7b434b4714 --- /dev/null +++ b/apps/api/api/openapi/components/schemas/errors/app-field_immutable.yaml @@ -0,0 +1,14 @@ +# Code generated by gen_error_schemas; DO NOT EDIT. +description: | + App: the field is fixed for the life of the client + + Error code: app.field_immutable +allOf: + - $ref: ../../error-details.yaml + - type: object + properties: + code: + type: string + const: app.field_immutable + required: + - code diff --git a/apps/api/api/openapi/components/schemas/errors/app-identifier_taken.yaml b/apps/api/api/openapi/components/schemas/errors/app-identifier_taken.yaml new file mode 100644 index 0000000000..35941587f7 --- /dev/null +++ b/apps/api/api/openapi/components/schemas/errors/app-identifier_taken.yaml @@ -0,0 +1,14 @@ +# Code generated by gen_error_schemas; DO NOT EDIT. +description: | + App: another app in the project holds the API identifier + + Error code: app.identifier_taken +allOf: + - $ref: ../../error-details.yaml + - type: object + properties: + code: + type: string + const: app.identifier_taken + required: + - code diff --git a/apps/api/api/openapi/components/schemas/errors/app-invalid.yaml b/apps/api/api/openapi/components/schemas/errors/app-invalid.yaml new file mode 100644 index 0000000000..51faef7f2e --- /dev/null +++ b/apps/api/api/openapi/components/schemas/errors/app-invalid.yaml @@ -0,0 +1,14 @@ +# Code generated by gen_error_schemas; DO NOT EDIT. +description: | + App: invalid + + Error code: app.invalid +allOf: + - $ref: ../../error-details.yaml + - type: object + properties: + code: + type: string + const: app.invalid + required: + - code diff --git a/apps/api/api/openapi/components/schemas/errors/app-invalid_scope.yaml b/apps/api/api/openapi/components/schemas/errors/app-invalid_scope.yaml new file mode 100644 index 0000000000..7ef221dbf1 --- /dev/null +++ b/apps/api/api/openapi/components/schemas/errors/app-invalid_scope.yaml @@ -0,0 +1,14 @@ +# Code generated by gen_error_schemas; DO NOT EDIT. +description: | + App: a requested scope is unknown or not allowed for the client + + Error code: app.invalid_scope +allOf: + - $ref: ../../error-details.yaml + - type: object + properties: + code: + type: string + const: app.invalid_scope + required: + - code diff --git a/apps/api/api/openapi/components/schemas/errors/app-not_found.yaml b/apps/api/api/openapi/components/schemas/errors/app-not_found.yaml new file mode 100644 index 0000000000..1b0e57f8e7 --- /dev/null +++ b/apps/api/api/openapi/components/schemas/errors/app-not_found.yaml @@ -0,0 +1,14 @@ +# Code generated by gen_error_schemas; DO NOT EDIT. +description: | + App: not found + + Error code: app.not_found +allOf: + - $ref: ../../error-details.yaml + - type: object + properties: + code: + type: string + const: app.not_found + required: + - code diff --git a/apps/api/api/openapi/components/schemas/errors/app-permission_denied.yaml b/apps/api/api/openapi/components/schemas/errors/app-permission_denied.yaml new file mode 100644 index 0000000000..393ad2562c --- /dev/null +++ b/apps/api/api/openapi/components/schemas/errors/app-permission_denied.yaml @@ -0,0 +1,14 @@ +# Code generated by gen_error_schemas; DO NOT EDIT. +description: | + App: the caller's project role does not allow this operation + + Error code: app.permission_denied +allOf: + - $ref: ../../error-details.yaml + - type: object + properties: + code: + type: string + const: app.permission_denied + required: + - code diff --git a/apps/api/api/openapi/components/schemas/errors/app-revision_conflict.yaml b/apps/api/api/openapi/components/schemas/errors/app-revision_conflict.yaml new file mode 100644 index 0000000000..7b64de1bbc --- /dev/null +++ b/apps/api/api/openapi/components/schemas/errors/app-revision_conflict.yaml @@ -0,0 +1,14 @@ +# Code generated by gen_error_schemas; DO NOT EDIT. +description: | + App: another revision of the same app was created at the same instant + + Error code: app.revision_conflict +allOf: + - $ref: ../../error-details.yaml + - type: object + properties: + code: + type: string + const: app.revision_conflict + required: + - code diff --git a/apps/api/api/openapi/endpoints/apps/app-client-credential.yaml b/apps/api/api/openapi/endpoints/apps/app-client-credential.yaml new file mode 100644 index 0000000000..ac23ecfef6 --- /dev/null +++ b/apps/api/api/openapi/endpoints/apps/app-client-credential.yaml @@ -0,0 +1,47 @@ +type: object +description: | + One credential a confidential client authenticates with: a secret the + server generated or imported, or a public key the client signs its + `private_key_jwt` assertions with. Each is named, and rotated or revoked on + its own: rotating adds the new one and revokes the old one later, so the + client, its `client_id` and its history stay. A secret's value is shown + once, when the server generates it, and never stored. +required: + - id + - name + - kind + - client_id + - created_at +properties: + id: + type: string + description: The credential's id. + example: cred_01KWH3B72K7M7F0N9WD3P2E4YQ + name: + type: string + description: Names the credential, unique among the client's credentials. + example: ci-2026-11 + kind: + type: string + enum: + - secret + - key + description: '`secret` authenticates with `client_secret_basic` or `client_secret_post`, `key` with `private_key_jwt`.' + client_id: + type: string + description: The client the credential authenticates. + example: client_01KWH3B72K7M7F0N9WD3P2E4YP + key_id: + type: string + description: The public key's `kid`, for a key. + created_at: + type: string + format: date-time + expires_at: + type: string + format: date-time + description: When the credential stops working. Absent for one that does not expire. + secret: + type: string + description: The generated secret, shown once, in the answer that created it. Absent on reads and for an import or a key. + example: zcs_4zW8kXbqP2mT9vR1nC6yL3hD7fJ0sA5gE2uQ8wN4iK9oB1pa0Wj4L diff --git a/apps/api/api/openapi/endpoints/apps/app-client-id.yaml b/apps/api/api/openapi/endpoints/apps/app-client-id.yaml new file mode 100644 index 0000000000..8d9d954b94 --- /dev/null +++ b/apps/api/api/openapi/endpoints/apps/app-client-id.yaml @@ -0,0 +1,16 @@ +type: object +description: The `client_id` one client of the app presents. +required: + - slug + - client_id +properties: + slug: + type: string + description: The client's slug in the document. + example: web + client_id: + type: string + description: | + The id the server minted when the client was first written, or the one + the document chose. Fixed for the life of the client. + example: client_01KWH3B72K7M7F0N9WD3P2E4YP diff --git a/apps/api/api/openapi/endpoints/apps/app-client-secret.yaml b/apps/api/api/openapi/endpoints/apps/app-client-secret.yaml new file mode 100644 index 0000000000..edb1eda2bd --- /dev/null +++ b/apps/api/api/openapi/endpoints/apps/app-client-secret.yaml @@ -0,0 +1,19 @@ +type: object +description: A client secret the server generated, returned once. +required: + - client + - credential_id + - secret +properties: + client: + type: string + description: The slug of the client the secret belongs to. + example: web + credential_id: + type: string + description: The id of the credential that holds the secret, which revokes it. + example: cred_01KWH3B72K7M7F0N9WD3P2E4YQ + secret: + type: string + description: The secret. The server keeps only its hash, so it cannot be shown again. + example: zcs_4zW8kXbqP2mT9vR1nC6yL3hD7fJ0sA5gE2uQ8wN4iK9oB1pa0Wj4L diff --git a/apps/api/api/openapi/endpoints/apps/app-response.yaml b/apps/api/api/openapi/endpoints/apps/app-response.yaml new file mode 100644 index 0000000000..cf38cd6604 --- /dev/null +++ b/apps/api/api/openapi/endpoints/apps/app-response.yaml @@ -0,0 +1,62 @@ +type: object +description: | + An app at one revision, with the `client_id` of each client that revision + lists. +required: + - id + - revision_id + - slug + - source + - definition + - clients + - created_at + - updated_at +properties: + id: + type: string + description: The app id, shared by every revision. + example: app_01KWH3B72K7M7F0N9WD3P2E4YM + revision_id: + type: string + description: | + The revision this row holds, pinned by releases. `GET /apps/{id}` and + the query return the newest one. + example: apprev_01KWH3B72K7M7F0N9WD3P2E4YN + slug: + type: string + description: The app's slug, fixed for its life. + example: shop + source: + type: string + enum: + - declared + - registered + description: | + Who writes the app: `declared` apps are files in the release and change + only with it, `registered` apps are written through `POST /apps`. + definition: + $ref: ../schemas/app.yaml + description: The stored app document, as written. + clients: + type: array + description: The client_id of each client the document lists, in its order. + items: + $ref: app-client-id.yaml + client_secrets: + type: array + description: | + The secrets this write generated: one for each new confidential client + of a registered app that holds no key, as its credential named + `initial`. Present only in the answer to the write that generated them. + items: + $ref: app-client-secret.yaml + created_at: + type: string + format: date-time + description: When the app was created. + example: '2026-10-28T09:11:00Z' + updated_at: + type: string + format: date-time + description: When this revision was created. + example: '2026-10-28T09:11:00Z' diff --git a/apps/api/api/openapi/endpoints/apps/by_id/clients/by_slug/credentials/add-app-client-credential-request.yaml b/apps/api/api/openapi/endpoints/apps/by_id/clients/by_slug/credentials/add-app-client-credential-request.yaml new file mode 100644 index 0000000000..aae9e40cdf --- /dev/null +++ b/apps/api/api/openapi/endpoints/apps/by_id/clients/by_slug/credentials/add-app-client-credential-request.yaml @@ -0,0 +1,39 @@ +type: object +description: | + Adds a credential to a confidential client, whether the app is declared in + the release or registered through the API; a deploy never removes it. Send + only `name` and the server generates a secret, shown once. `secret` + imports a value the client already uses, such as one compiled into it; + `hash` imports a hash another identity provider wrote, such as v4's bcrypt, + which the server replaces with its own hash the first time the client + authenticates with it; `public_key` adds a key for `private_key_jwt`. Give + at most one of the three. Every credential stays valid until it is revoked + or expires, so rotating one needs no downtime. +required: + - name +properties: + name: + type: string + pattern: ^[a-z0-9][a-z0-9_-]*$ + maxLength: 64 + description: Names the credential, unique among the client's credentials. + example: ci-2026-11 + secret: + type: string + minLength: 1 + maxLength: 512 + description: A secret to import, as plaintext. Stored as a hash. + hash: + type: string + minLength: 1 + maxLength: 512 + description: | + An encoded hash to import, in a format passwap reads: bcrypt (`$2a$`, + `$2b$`, `$2y$`), argon2, scrypt, pbkdf2 and the others the server's hash + configuration lists as verifiers. + public_key: + $ref: ../../../../../schemas/app-client-jwk.yaml + expires_at: + type: string + format: date-time + description: When the credential stops working. It never expires when left out. diff --git a/apps/api/api/openapi/endpoints/apps/by_id/clients/by_slug/credentials/addAppClientCredential-error-response.yaml b/apps/api/api/openapi/endpoints/apps/by_id/clients/by_slug/credentials/addAppClientCredential-error-response.yaml new file mode 100644 index 0000000000..a68c3c0679 --- /dev/null +++ b/apps/api/api/openapi/endpoints/apps/by_id/clients/by_slug/credentials/addAppClientCredential-error-response.yaml @@ -0,0 +1,101 @@ +# generated by gen_openapi_errors; DO NOT EDIT +description: Error response +content: + application/json: + schema: + oneOf: + - $ref: '../../../../../../components/schemas/errors/app-client_not_found.yaml' + - $ref: '../../../../../../components/schemas/errors/app-credential_taken.yaml' + - $ref: '../../../../../../components/schemas/errors/app-invalid.yaml' + - $ref: '../../../../../../components/schemas/errors/app-not_found.yaml' + - $ref: '../../../../../../components/schemas/errors/app-permission_denied.yaml' + - $ref: '../../../../../../components/schemas/errors/app-revision_conflict.yaml' + - $ref: '../../../../../../components/schemas/errors/auth-csrf_invalid.yaml' + - $ref: '../../../../../../components/schemas/errors/auth-unauthorized.yaml' + - $ref: '../../../../../../components/schemas/errors/evt-invalid.yaml' + - $ref: '../../../../../../components/schemas/errors/internal.yaml' + - $ref: '../../../../../../components/schemas/errors/not_implemented.yaml' + - $ref: '../../../../../../components/schemas/errors/req-invalid.yaml' + - $ref: '../../../../../../components/schemas/errors/unavailable.yaml' + discriminator: + propertyName: code + mapping: + app.client_not_found: '../../../../../../components/schemas/errors/app-client_not_found.yaml' + app.credential_taken: '../../../../../../components/schemas/errors/app-credential_taken.yaml' + app.invalid: '../../../../../../components/schemas/errors/app-invalid.yaml' + app.not_found: '../../../../../../components/schemas/errors/app-not_found.yaml' + app.permission_denied: '../../../../../../components/schemas/errors/app-permission_denied.yaml' + app.revision_conflict: '../../../../../../components/schemas/errors/app-revision_conflict.yaml' + auth.csrf_invalid: '../../../../../../components/schemas/errors/auth-csrf_invalid.yaml' + auth.unauthorized: '../../../../../../components/schemas/errors/auth-unauthorized.yaml' + evt.invalid: '../../../../../../components/schemas/errors/evt-invalid.yaml' + internal: '../../../../../../components/schemas/errors/internal.yaml' + not_implemented: '../../../../../../components/schemas/errors/not_implemented.yaml' + req.invalid: '../../../../../../components/schemas/errors/req-invalid.yaml' + unavailable: '../../../../../../components/schemas/errors/unavailable.yaml' + examples: + app.client_not_found: + summary: app.client_not_found + value: + code: app.client_not_found + message: 'app: no client has the client_id' + app.credential_taken: + summary: app.credential_taken + value: + code: app.credential_taken + message: 'app: another credential of the client has the name or the key id' + app.invalid: + summary: app.invalid + value: + code: app.invalid + message: 'app: invalid' + app.not_found: + summary: app.not_found + value: + code: app.not_found + message: 'app: not found' + app.permission_denied: + summary: app.permission_denied + value: + code: app.permission_denied + message: 'app: the caller''s project role does not allow this operation' + app.revision_conflict: + summary: app.revision_conflict + value: + code: app.revision_conflict + message: 'app: another revision of the same app was created at the same instant' + auth.csrf_invalid: + summary: auth.csrf_invalid + value: + code: auth.csrf_invalid + message: 'The request failed cross-site request forgery validation.' + auth.unauthorized: + summary: auth.unauthorized + value: + code: auth.unauthorized + message: 'The request lacks valid authentication credentials.' + evt.invalid: + summary: evt.invalid + value: + code: evt.invalid + message: 'event: invalid' + internal: + summary: internal + value: + code: internal + message: 'An unexpected error occurred.' + not_implemented: + summary: not_implemented + value: + code: not_implemented + message: 'This feature is not implemented yet.' + req.invalid: + summary: req.invalid + value: + code: req.invalid + message: 'The request is invalid and fails base validation (missing required fields, wrong types, failed regex, etc.). Check the details for more information.' + unavailable: + summary: unavailable + value: + code: unavailable + message: 'The service could not complete the request right now. Try again.' diff --git a/apps/api/api/openapi/endpoints/apps/by_id/clients/by_slug/credentials/by_id/methods.yaml b/apps/api/api/openapi/endpoints/apps/by_id/clients/by_slug/credentials/by_id/methods.yaml new file mode 100644 index 0000000000..87b2ff1589 --- /dev/null +++ b/apps/api/api/openapi/endpoints/apps/by_id/clients/by_slug/credentials/by_id/methods.yaml @@ -0,0 +1,40 @@ +delete: + operationId: revokeAppClientCredential + summary: Revoke a credential of an app's client + description: | + Revokes one credential: the client can no longer authenticate with it, + and its other credentials keep working. Emits `app.credential.revoked`. + tags: + - Apps + security: + - oauth2: + - app.write + - sessionCookie: [] + parameters: + - $ref: ../../../../../../../components/parameters/project-id.yaml + - $ref: ../../../../../../../components/parameters/app-id.yaml + - $ref: ../../../../../../../components/parameters/app-client-slug.yaml + - $ref: ../../../../../../../components/parameters/app-client-credential-id.yaml + responses: + '204': + description: The credential was revoked. + '401': + description: Missing or invalid credentials. + content: + application/json: + schema: + $ref: ../../../../../../../components/error-details.yaml + '403': + description: Insufficient permissions. + content: + application/json: + schema: + $ref: ../../../../../../../components/error-details.yaml + '404': + description: No such app, client or credential. + content: + application/json: + schema: + $ref: ../../../../../../../components/error-details.yaml + default: + $ref: revokeAppClientCredential-error-response.yaml diff --git a/apps/api/api/openapi/endpoints/apps/by_id/clients/by_slug/credentials/by_id/revokeAppClientCredential-error-response.yaml b/apps/api/api/openapi/endpoints/apps/by_id/clients/by_slug/credentials/by_id/revokeAppClientCredential-error-response.yaml new file mode 100644 index 0000000000..005ea622bc --- /dev/null +++ b/apps/api/api/openapi/endpoints/apps/by_id/clients/by_slug/credentials/by_id/revokeAppClientCredential-error-response.yaml @@ -0,0 +1,94 @@ +# generated by gen_openapi_errors; DO NOT EDIT +description: Error response +content: + application/json: + schema: + oneOf: + - $ref: '../../../../../../../components/schemas/errors/app-client_not_found.yaml' + - $ref: '../../../../../../../components/schemas/errors/app-credential_not_found.yaml' + - $ref: '../../../../../../../components/schemas/errors/app-not_found.yaml' + - $ref: '../../../../../../../components/schemas/errors/app-permission_denied.yaml' + - $ref: '../../../../../../../components/schemas/errors/app-revision_conflict.yaml' + - $ref: '../../../../../../../components/schemas/errors/auth-csrf_invalid.yaml' + - $ref: '../../../../../../../components/schemas/errors/auth-unauthorized.yaml' + - $ref: '../../../../../../../components/schemas/errors/evt-invalid.yaml' + - $ref: '../../../../../../../components/schemas/errors/internal.yaml' + - $ref: '../../../../../../../components/schemas/errors/not_implemented.yaml' + - $ref: '../../../../../../../components/schemas/errors/req-invalid.yaml' + - $ref: '../../../../../../../components/schemas/errors/unavailable.yaml' + discriminator: + propertyName: code + mapping: + app.client_not_found: '../../../../../../../components/schemas/errors/app-client_not_found.yaml' + app.credential_not_found: '../../../../../../../components/schemas/errors/app-credential_not_found.yaml' + app.not_found: '../../../../../../../components/schemas/errors/app-not_found.yaml' + app.permission_denied: '../../../../../../../components/schemas/errors/app-permission_denied.yaml' + app.revision_conflict: '../../../../../../../components/schemas/errors/app-revision_conflict.yaml' + auth.csrf_invalid: '../../../../../../../components/schemas/errors/auth-csrf_invalid.yaml' + auth.unauthorized: '../../../../../../../components/schemas/errors/auth-unauthorized.yaml' + evt.invalid: '../../../../../../../components/schemas/errors/evt-invalid.yaml' + internal: '../../../../../../../components/schemas/errors/internal.yaml' + not_implemented: '../../../../../../../components/schemas/errors/not_implemented.yaml' + req.invalid: '../../../../../../../components/schemas/errors/req-invalid.yaml' + unavailable: '../../../../../../../components/schemas/errors/unavailable.yaml' + examples: + app.client_not_found: + summary: app.client_not_found + value: + code: app.client_not_found + message: 'app: no client has the client_id' + app.credential_not_found: + summary: app.credential_not_found + value: + code: app.credential_not_found + message: 'app: the client holds no credential with the id' + app.not_found: + summary: app.not_found + value: + code: app.not_found + message: 'app: not found' + app.permission_denied: + summary: app.permission_denied + value: + code: app.permission_denied + message: 'app: the caller''s project role does not allow this operation' + app.revision_conflict: + summary: app.revision_conflict + value: + code: app.revision_conflict + message: 'app: another revision of the same app was created at the same instant' + auth.csrf_invalid: + summary: auth.csrf_invalid + value: + code: auth.csrf_invalid + message: 'The request failed cross-site request forgery validation.' + auth.unauthorized: + summary: auth.unauthorized + value: + code: auth.unauthorized + message: 'The request lacks valid authentication credentials.' + evt.invalid: + summary: evt.invalid + value: + code: evt.invalid + message: 'event: invalid' + internal: + summary: internal + value: + code: internal + message: 'An unexpected error occurred.' + not_implemented: + summary: not_implemented + value: + code: not_implemented + message: 'This feature is not implemented yet.' + req.invalid: + summary: req.invalid + value: + code: req.invalid + message: 'The request is invalid and fails base validation (missing required fields, wrong types, failed regex, etc.). Check the details for more information.' + unavailable: + summary: unavailable + value: + code: unavailable + message: 'The service could not complete the request right now. Try again.' diff --git a/apps/api/api/openapi/endpoints/apps/by_id/clients/by_slug/credentials/list-app-client-credentials-response.yaml b/apps/api/api/openapi/endpoints/apps/by_id/clients/by_slug/credentials/list-app-client-credentials-response.yaml new file mode 100644 index 0000000000..c25faea531 --- /dev/null +++ b/apps/api/api/openapi/endpoints/apps/by_id/clients/by_slug/credentials/list-app-client-credentials-response.yaml @@ -0,0 +1,9 @@ +type: object +description: The credentials a client holds through the API, oldest first. A declared client's secret reference and keys in its file are not listed. +required: + - credentials +properties: + credentials: + type: array + items: + $ref: ../../../../app-client-credential.yaml diff --git a/apps/api/api/openapi/endpoints/apps/by_id/clients/by_slug/credentials/listAppClientCredentials-error-response.yaml b/apps/api/api/openapi/endpoints/apps/by_id/clients/by_slug/credentials/listAppClientCredentials-error-response.yaml new file mode 100644 index 0000000000..9377132eb5 --- /dev/null +++ b/apps/api/api/openapi/endpoints/apps/by_id/clients/by_slug/credentials/listAppClientCredentials-error-response.yaml @@ -0,0 +1,66 @@ +# generated by gen_openapi_errors; DO NOT EDIT +description: Error response +content: + application/json: + schema: + oneOf: + - $ref: '../../../../../../components/schemas/errors/app-client_not_found.yaml' + - $ref: '../../../../../../components/schemas/errors/app-not_found.yaml' + - $ref: '../../../../../../components/schemas/errors/app-permission_denied.yaml' + - $ref: '../../../../../../components/schemas/errors/auth-unauthorized.yaml' + - $ref: '../../../../../../components/schemas/errors/internal.yaml' + - $ref: '../../../../../../components/schemas/errors/not_implemented.yaml' + - $ref: '../../../../../../components/schemas/errors/req-invalid.yaml' + - $ref: '../../../../../../components/schemas/errors/unavailable.yaml' + discriminator: + propertyName: code + mapping: + app.client_not_found: '../../../../../../components/schemas/errors/app-client_not_found.yaml' + app.not_found: '../../../../../../components/schemas/errors/app-not_found.yaml' + app.permission_denied: '../../../../../../components/schemas/errors/app-permission_denied.yaml' + auth.unauthorized: '../../../../../../components/schemas/errors/auth-unauthorized.yaml' + internal: '../../../../../../components/schemas/errors/internal.yaml' + not_implemented: '../../../../../../components/schemas/errors/not_implemented.yaml' + req.invalid: '../../../../../../components/schemas/errors/req-invalid.yaml' + unavailable: '../../../../../../components/schemas/errors/unavailable.yaml' + examples: + app.client_not_found: + summary: app.client_not_found + value: + code: app.client_not_found + message: 'app: no client has the client_id' + app.not_found: + summary: app.not_found + value: + code: app.not_found + message: 'app: not found' + app.permission_denied: + summary: app.permission_denied + value: + code: app.permission_denied + message: 'app: the caller''s project role does not allow this operation' + auth.unauthorized: + summary: auth.unauthorized + value: + code: auth.unauthorized + message: 'The request lacks valid authentication credentials.' + internal: + summary: internal + value: + code: internal + message: 'An unexpected error occurred.' + not_implemented: + summary: not_implemented + value: + code: not_implemented + message: 'This feature is not implemented yet.' + req.invalid: + summary: req.invalid + value: + code: req.invalid + message: 'The request is invalid and fails base validation (missing required fields, wrong types, failed regex, etc.). Check the details for more information.' + unavailable: + summary: unavailable + value: + code: unavailable + message: 'The service could not complete the request right now. Try again.' diff --git a/apps/api/api/openapi/endpoints/apps/by_id/clients/by_slug/credentials/methods.yaml b/apps/api/api/openapi/endpoints/apps/by_id/clients/by_slug/credentials/methods.yaml new file mode 100644 index 0000000000..79a3974dcd --- /dev/null +++ b/apps/api/api/openapi/endpoints/apps/by_id/clients/by_slug/credentials/methods.yaml @@ -0,0 +1,121 @@ +post: + operationId: addAppClientCredential + summary: Add a credential to an app's client + description: | + Adds a named credential to a confidential client: a secret the server + generates and shows once, an imported secret or hash, or a public key. + The app may be declared in the release or registered through the API, and + a deploy never removes a credential written here. A public client holds + no credential, and a request for one is refused with `app.invalid`. + Emits `app.credential.added`. + tags: + - Apps + security: + - oauth2: + - app.write + - sessionCookie: [] + parameters: + - $ref: ../../../../../../components/parameters/project-id.yaml + - $ref: ../../../../../../components/parameters/app-id.yaml + - $ref: ../../../../../../components/parameters/app-client-slug.yaml + requestBody: + required: true + content: + application/json: + schema: + $ref: add-app-client-credential-request.yaml + examples: + generate: + summary: Generate a secret + value: + name: ci-2026-11 + importBcrypt: + summary: Import a v4 secret's bcrypt hash + value: + name: imported-from-v4 + hash: $2a$04$KLQ8Oa0xFlVm1b0wN8E6kOpH0n1m1Oh8m2V3o4p5q6r7s8t9u0v1w + responses: + '201': + description: The credential was added. A generated secret is in `secret`, shown once. + content: + application/json: + schema: + $ref: ../../../../app-client-credential.yaml + '400': + description: | + The client is public, more than one of `secret`, `hash` and + `public_key` was given, the hash is in no format the server reads, or + the key is not a public key. + content: + application/json: + schema: + $ref: ../../../../../../components/error-details.yaml + '401': + description: Missing or invalid credentials. + content: + application/json: + schema: + $ref: ../../../../../../components/error-details.yaml + '403': + description: Insufficient permissions. + content: + application/json: + schema: + $ref: ../../../../../../components/error-details.yaml + '404': + description: No app with this id, or no client with this slug in its newest revision. + content: + application/json: + schema: + $ref: ../../../../../../components/error-details.yaml + '409': + description: The client already holds a credential with this name, or a key with this `kid`. + content: + application/json: + schema: + $ref: ../../../../../../components/error-details.yaml + default: + $ref: addAppClientCredential-error-response.yaml +get: + operationId: listAppClientCredentials + summary: List the credentials of an app's client + description: | + Lists the credentials a client holds through the API, revoked ones left + out, without any secret. + tags: + - Apps + security: + - oauth2: + - app.read + - sessionCookie: [] + parameters: + - $ref: ../../../../../../components/parameters/project-id.yaml + - $ref: ../../../../../../components/parameters/app-id.yaml + - $ref: ../../../../../../components/parameters/app-client-slug.yaml + responses: + '200': + description: The client's credentials. + content: + application/json: + schema: + $ref: list-app-client-credentials-response.yaml + '401': + description: Missing or invalid credentials. + content: + application/json: + schema: + $ref: ../../../../../../components/error-details.yaml + '403': + description: Insufficient permissions. + content: + application/json: + schema: + $ref: ../../../../../../components/error-details.yaml + '404': + description: No app with this id, or no client with this slug in its newest revision. + content: + application/json: + schema: + $ref: ../../../../../../components/error-details.yaml + default: + $ref: listAppClientCredentials-error-response.yaml diff --git a/apps/api/api/openapi/endpoints/apps/by_id/getAppById-error-response.yaml b/apps/api/api/openapi/endpoints/apps/by_id/getAppById-error-response.yaml new file mode 100644 index 0000000000..b97123b446 --- /dev/null +++ b/apps/api/api/openapi/endpoints/apps/by_id/getAppById-error-response.yaml @@ -0,0 +1,59 @@ +# generated by gen_openapi_errors; DO NOT EDIT +description: Error response +content: + application/json: + schema: + oneOf: + - $ref: '../../../components/schemas/errors/app-not_found.yaml' + - $ref: '../../../components/schemas/errors/app-permission_denied.yaml' + - $ref: '../../../components/schemas/errors/auth-unauthorized.yaml' + - $ref: '../../../components/schemas/errors/internal.yaml' + - $ref: '../../../components/schemas/errors/not_implemented.yaml' + - $ref: '../../../components/schemas/errors/req-invalid.yaml' + - $ref: '../../../components/schemas/errors/unavailable.yaml' + discriminator: + propertyName: code + mapping: + app.not_found: '../../../components/schemas/errors/app-not_found.yaml' + app.permission_denied: '../../../components/schemas/errors/app-permission_denied.yaml' + auth.unauthorized: '../../../components/schemas/errors/auth-unauthorized.yaml' + internal: '../../../components/schemas/errors/internal.yaml' + not_implemented: '../../../components/schemas/errors/not_implemented.yaml' + req.invalid: '../../../components/schemas/errors/req-invalid.yaml' + unavailable: '../../../components/schemas/errors/unavailable.yaml' + examples: + app.not_found: + summary: app.not_found + value: + code: app.not_found + message: 'app: not found' + app.permission_denied: + summary: app.permission_denied + value: + code: app.permission_denied + message: 'app: the caller''s project role does not allow this operation' + auth.unauthorized: + summary: auth.unauthorized + value: + code: auth.unauthorized + message: 'The request lacks valid authentication credentials.' + internal: + summary: internal + value: + code: internal + message: 'An unexpected error occurred.' + not_implemented: + summary: not_implemented + value: + code: not_implemented + message: 'This feature is not implemented yet.' + req.invalid: + summary: req.invalid + value: + code: req.invalid + message: 'The request is invalid and fails base validation (missing required fields, wrong types, failed regex, etc.). Check the details for more information.' + unavailable: + summary: unavailable + value: + code: unavailable + message: 'The service could not complete the request right now. Try again.' diff --git a/apps/api/api/openapi/endpoints/apps/by_id/methods.yaml b/apps/api/api/openapi/endpoints/apps/by_id/methods.yaml new file mode 100644 index 0000000000..3b2746668d --- /dev/null +++ b/apps/api/api/openapi/endpoints/apps/by_id/methods.yaml @@ -0,0 +1,45 @@ +get: + operationId: getAppById + x-zitadel-cli: apps get + summary: Get an app by id + description: | + 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`. + tags: + - Apps + security: + - oauth2: + - app.read + - sessionCookie: [] + parameters: + - $ref: ../../../components/parameters/project-id.yaml + - $ref: ../../../components/parameters/app-id.yaml + responses: + '200': + description: The app was retrieved successfully. + content: + application/json: + schema: + $ref: ../app-response.yaml + '401': + description: Missing or invalid credentials. + content: + application/json: + schema: + $ref: ../../../components/error-details.yaml + '403': + description: Insufficient permissions. + content: + application/json: + schema: + $ref: ../../../components/error-details.yaml + '404': + description: No app with this id exists in the given project. + content: + application/json: + schema: + $ref: ../../../components/error-details.yaml + default: + $ref: getAppById-error-response.yaml diff --git a/apps/api/api/openapi/endpoints/apps/by_id/revisions/list-app-revisions-response.yaml b/apps/api/api/openapi/endpoints/apps/by_id/revisions/list-app-revisions-response.yaml new file mode 100644 index 0000000000..edae34179c --- /dev/null +++ b/apps/api/api/openapi/endpoints/apps/by_id/revisions/list-app-revisions-response.yaml @@ -0,0 +1,16 @@ +type: object +description: Paginated list of the revisions of one app, newest first. +required: + - revisions +properties: + revisions: + type: array + items: + $ref: ../../app-response.yaml + next_page_token: + description: | + Token to pass as `page_token` in the next request to fetch the following + page. Absent when there are no more results. + oneOf: + - $ref: ../../../../components/schemas/page-token.yaml + - type: 'null' diff --git a/apps/api/api/openapi/endpoints/apps/by_id/revisions/listAppRevisions-error-response.yaml b/apps/api/api/openapi/endpoints/apps/by_id/revisions/listAppRevisions-error-response.yaml new file mode 100644 index 0000000000..cf9ba36127 --- /dev/null +++ b/apps/api/api/openapi/endpoints/apps/by_id/revisions/listAppRevisions-error-response.yaml @@ -0,0 +1,59 @@ +# generated by gen_openapi_errors; DO NOT EDIT +description: Error response +content: + application/json: + schema: + oneOf: + - $ref: '../../../../components/schemas/errors/app-not_found.yaml' + - $ref: '../../../../components/schemas/errors/app-permission_denied.yaml' + - $ref: '../../../../components/schemas/errors/auth-unauthorized.yaml' + - $ref: '../../../../components/schemas/errors/internal.yaml' + - $ref: '../../../../components/schemas/errors/not_implemented.yaml' + - $ref: '../../../../components/schemas/errors/req-invalid.yaml' + - $ref: '../../../../components/schemas/errors/unavailable.yaml' + discriminator: + propertyName: code + mapping: + app.not_found: '../../../../components/schemas/errors/app-not_found.yaml' + app.permission_denied: '../../../../components/schemas/errors/app-permission_denied.yaml' + auth.unauthorized: '../../../../components/schemas/errors/auth-unauthorized.yaml' + internal: '../../../../components/schemas/errors/internal.yaml' + not_implemented: '../../../../components/schemas/errors/not_implemented.yaml' + req.invalid: '../../../../components/schemas/errors/req-invalid.yaml' + unavailable: '../../../../components/schemas/errors/unavailable.yaml' + examples: + app.not_found: + summary: app.not_found + value: + code: app.not_found + message: 'app: not found' + app.permission_denied: + summary: app.permission_denied + value: + code: app.permission_denied + message: 'app: the caller''s project role does not allow this operation' + auth.unauthorized: + summary: auth.unauthorized + value: + code: auth.unauthorized + message: 'The request lacks valid authentication credentials.' + internal: + summary: internal + value: + code: internal + message: 'An unexpected error occurred.' + not_implemented: + summary: not_implemented + value: + code: not_implemented + message: 'This feature is not implemented yet.' + req.invalid: + summary: req.invalid + value: + code: req.invalid + message: 'The request is invalid and fails base validation (missing required fields, wrong types, failed regex, etc.). Check the details for more information.' + unavailable: + summary: unavailable + value: + code: unavailable + message: 'The service could not complete the request right now. Try again.' diff --git a/apps/api/api/openapi/endpoints/apps/by_id/revisions/methods.yaml b/apps/api/api/openapi/endpoints/apps/by_id/revisions/methods.yaml new file mode 100644 index 0000000000..f96ae254a1 --- /dev/null +++ b/apps/api/api/openapi/endpoints/apps/by_id/revisions/methods.yaml @@ -0,0 +1,45 @@ +get: + operationId: listAppRevisions + summary: List the revisions of an app + description: | + 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`. + tags: + - Apps + security: + - oauth2: + - app.read + parameters: + - $ref: ../../../../components/parameters/project-id.yaml + - $ref: ../../../../components/parameters/app-id.yaml + - $ref: ../../../../components/parameters/limit.yaml + - $ref: ../../../../components/parameters/page-token.yaml + responses: + '200': + description: The revisions of the app were returned successfully. + content: + application/json: + schema: + $ref: list-app-revisions-response.yaml + '401': + description: Missing or invalid credentials. + content: + application/json: + schema: + $ref: ../../../../components/error-details.yaml + '403': + description: Insufficient permissions. + content: + application/json: + schema: + $ref: ../../../../components/error-details.yaml + '404': + description: No app with this id exists in the given project. + content: + application/json: + schema: + $ref: ../../../../components/error-details.yaml + default: + $ref: listAppRevisions-error-response.yaml diff --git a/apps/api/api/openapi/endpoints/apps/create-app-request.yaml b/apps/api/api/openapi/endpoints/apps/create-app-request.yaml new file mode 100644 index 0000000000..663c24a3c3 --- /dev/null +++ b/apps/api/api/openapi/endpoints/apps/create-app-request.yaml @@ -0,0 +1,12 @@ +type: object +description: Creates or revises an app document. +required: + - app +properties: + app: + $ref: ../schemas/app.yaml + description: | + The app document, in the shape of a `.zitadel/apps/.json` file. If + its slug is new in the project, the app is created; if an app the API + registered has that slug, this is a new revision of it. An app the + release declares is changed only by a release. diff --git a/apps/api/api/openapi/endpoints/apps/createApp-error-response.yaml b/apps/api/api/openapi/endpoints/apps/createApp-error-response.yaml new file mode 100644 index 0000000000..166a365409 --- /dev/null +++ b/apps/api/api/openapi/endpoints/apps/createApp-error-response.yaml @@ -0,0 +1,115 @@ +# generated by gen_openapi_errors; DO NOT EDIT +description: Error response +content: + application/json: + schema: + oneOf: + - $ref: '../../components/schemas/errors/app-client_id_taken.yaml' + - $ref: '../../components/schemas/errors/app-credential_taken.yaml' + - $ref: '../../components/schemas/errors/app-declared.yaml' + - $ref: '../../components/schemas/errors/app-field_immutable.yaml' + - $ref: '../../components/schemas/errors/app-identifier_taken.yaml' + - $ref: '../../components/schemas/errors/app-invalid.yaml' + - $ref: '../../components/schemas/errors/app-not_found.yaml' + - $ref: '../../components/schemas/errors/app-permission_denied.yaml' + - $ref: '../../components/schemas/errors/app-revision_conflict.yaml' + - $ref: '../../components/schemas/errors/auth-unauthorized.yaml' + - $ref: '../../components/schemas/errors/evt-invalid.yaml' + - $ref: '../../components/schemas/errors/internal.yaml' + - $ref: '../../components/schemas/errors/not_implemented.yaml' + - $ref: '../../components/schemas/errors/req-invalid.yaml' + - $ref: '../../components/schemas/errors/unavailable.yaml' + discriminator: + propertyName: code + mapping: + app.client_id_taken: '../../components/schemas/errors/app-client_id_taken.yaml' + app.credential_taken: '../../components/schemas/errors/app-credential_taken.yaml' + app.declared: '../../components/schemas/errors/app-declared.yaml' + app.field_immutable: '../../components/schemas/errors/app-field_immutable.yaml' + app.identifier_taken: '../../components/schemas/errors/app-identifier_taken.yaml' + app.invalid: '../../components/schemas/errors/app-invalid.yaml' + app.not_found: '../../components/schemas/errors/app-not_found.yaml' + app.permission_denied: '../../components/schemas/errors/app-permission_denied.yaml' + app.revision_conflict: '../../components/schemas/errors/app-revision_conflict.yaml' + auth.unauthorized: '../../components/schemas/errors/auth-unauthorized.yaml' + evt.invalid: '../../components/schemas/errors/evt-invalid.yaml' + internal: '../../components/schemas/errors/internal.yaml' + not_implemented: '../../components/schemas/errors/not_implemented.yaml' + req.invalid: '../../components/schemas/errors/req-invalid.yaml' + unavailable: '../../components/schemas/errors/unavailable.yaml' + examples: + app.client_id_taken: + summary: app.client_id_taken + value: + code: app.client_id_taken + message: 'app: another client in the project holds the client_id' + app.credential_taken: + summary: app.credential_taken + value: + code: app.credential_taken + message: 'app: another credential of the client has the name or the key id' + app.declared: + summary: app.declared + value: + code: app.declared + message: 'app: declared in the release, so only a release changes it' + app.field_immutable: + summary: app.field_immutable + value: + code: app.field_immutable + message: 'app: the field is fixed for the life of the client' + app.identifier_taken: + summary: app.identifier_taken + value: + code: app.identifier_taken + message: 'app: another app in the project holds the API identifier' + app.invalid: + summary: app.invalid + value: + code: app.invalid + message: 'app: invalid' + app.not_found: + summary: app.not_found + value: + code: app.not_found + message: 'app: not found' + app.permission_denied: + summary: app.permission_denied + value: + code: app.permission_denied + message: 'app: the caller''s project role does not allow this operation' + app.revision_conflict: + summary: app.revision_conflict + value: + code: app.revision_conflict + message: 'app: another revision of the same app was created at the same instant' + auth.unauthorized: + summary: auth.unauthorized + value: + code: auth.unauthorized + message: 'The request lacks valid authentication credentials.' + evt.invalid: + summary: evt.invalid + value: + code: evt.invalid + message: 'event: invalid' + internal: + summary: internal + value: + code: internal + message: 'An unexpected error occurred.' + not_implemented: + summary: not_implemented + value: + code: not_implemented + message: 'This feature is not implemented yet.' + req.invalid: + summary: req.invalid + value: + code: req.invalid + message: 'The request is invalid and fails base validation (missing required fields, wrong types, failed regex, etc.). Check the details for more information.' + unavailable: + summary: unavailable + value: + code: unavailable + message: 'The service could not complete the request right now. Try again.' diff --git a/apps/api/api/openapi/endpoints/apps/methods.yaml b/apps/api/api/openapi/endpoints/apps/methods.yaml new file mode 100644 index 0000000000..20d346e11a --- /dev/null +++ b/apps/api/api/openapi/endpoints/apps/methods.yaml @@ -0,0 +1,138 @@ +post: + operationId: createApp + x-zitadel-cli: apps create + summary: Create or revise an app + description: | + 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 + for each new confidential client that holds no key, a generated secret, + shown once, as its credential named `initial`. + 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 credentials are written through the API, never a + `${{ NAME }}` reference. A refused document stores nothing. + tags: + - Apps + security: + - oauth2: + - app.write + parameters: + - $ref: ../../components/parameters/project-id.yaml + requestBody: + required: true + content: + application/json: + schema: + $ref: create-app-request.yaml + examples: + shop: + summary: A web app with an API + value: + app: + slug: shop + name: Shop + clients: + - slug: web + type: confidential + grant_types: + - authorization_code + - refresh_token + redirect_uris: + - https://shop.example.com/callback + apis: + - api: orders + apis: + - slug: orders + identifier: https://api.shop.example.com + scopes: + - name: orders.read + description: Read your orders + responses: + '200': + description: The app after the revision. + content: + application/json: + schema: + $ref: app-response.yaml + '201': + description: The app after creation. + content: + application/json: + schema: + $ref: app-response.yaml + examples: + created: + summary: A newly registered app + value: + id: app_01KWH3B72K7M7F0N9WD3P2E4YM + revision_id: apprev_01KWH3B72K7M7F0N9WD3P2E4YN + slug: shop + source: registered + created_at: '2026-10-28T09:11:00Z' + updated_at: '2026-10-28T09:11:00Z' + definition: + slug: shop + name: Shop + clients: + - slug: web + type: confidential + grant_types: + - authorization_code + - refresh_token + redirect_uris: + - https://shop.example.com/callback + clients: + - slug: web + client_id: client_01KWH3B72K7M7F0N9WD3P2E4YP + client_secrets: + - client: web + credential_id: cred_01KWH3B72K7M7F0N9WD3P2E4YQ + secret: zcs_4zW8kXbqP2mT9vR1nC6yL3hD7fJ0sA5gE2uQ8wN4iK9oB1pa0Wj4L + '400': + description: | + The document failed schema validation or the rules across its fields, + or a revision changes a client's `client_id`. + content: + application/json: + schema: + $ref: ../../components/error-details.yaml + '401': + description: Missing or invalid credentials. + content: + application/json: + schema: + $ref: ../../components/error-details.yaml + '403': + description: Insufficient permissions. + content: + application/json: + schema: + $ref: ../../components/error-details.yaml + '404': + description: Project not found. + content: + application/json: + schema: + $ref: ../../components/error-details.yaml + '409': + description: | + The slug names an app the release declares, or a `client_id` or API + identifier another app in the project holds. + content: + application/json: + schema: + $ref: ../../components/error-details.yaml + default: + $ref: createApp-error-response.yaml diff --git a/apps/api/api/openapi/endpoints/apps/query/app-filter-field.yaml b/apps/api/api/openapi/endpoints/apps/query/app-filter-field.yaml new file mode 100644 index 0000000000..624a2d378e --- /dev/null +++ b/apps/api/api/openapi/endpoints/apps/query/app-filter-field.yaml @@ -0,0 +1,11 @@ +type: string +description: | + Field to filter or sort apps by: + - `slug`: unique within the project. `equals` returns the newest revision + of that app + - `source`: `declared` or `registered` (filter only) + - `created_at`: RFC3339 timestamp +enum: + - slug + - source + - created_at diff --git a/apps/api/api/openapi/endpoints/apps/query/methods.yaml b/apps/api/api/openapi/endpoints/apps/query/methods.yaml new file mode 100644 index 0000000000..0c36ec781b --- /dev/null +++ b/apps/api/api/openapi/endpoints/apps/query/methods.yaml @@ -0,0 +1,55 @@ +post: + operationId: queryApps + x-zitadel-cli: apps list + summary: Query apps + description: | + 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. + tags: + - Apps + security: + - oauth2: + - app.read + - sessionCookie: [] + parameters: + - $ref: ../../../components/parameters/project-id.yaml + requestBody: + description: Request to query the apps of a project. + required: true + content: + application/json: + schema: + $ref: query-apps-request.yaml + responses: + '200': + description: The apps were returned successfully. + content: + application/json: + schema: + $ref: query-apps-response.yaml + '400': + description: The filter or the sort names a field or an operation apps do not support. + content: + application/json: + schema: + $ref: ../../../components/error-details.yaml + '401': + description: Missing or invalid credentials. + content: + application/json: + schema: + $ref: ../../../components/error-details.yaml + '403': + description: Insufficient permissions. + content: + application/json: + schema: + $ref: ../../../components/error-details.yaml + '404': + description: Project not found. + content: + application/json: + schema: + $ref: ../../../components/error-details.yaml + default: + $ref: queryApps-error-response.yaml diff --git a/apps/api/api/openapi/endpoints/apps/query/query-apps-request.yaml b/apps/api/api/openapi/endpoints/apps/query/query-apps-request.yaml new file mode 100644 index 0000000000..1d7f1acc23 --- /dev/null +++ b/apps/api/api/openapi/endpoints/apps/query/query-apps-request.yaml @@ -0,0 +1,41 @@ +type: object +description: Request to query the apps of a project. +properties: + limit: + $ref: ../../../components/schemas/limit.yaml + page_token: + description: | + Token to retrieve the next page of results. Must be sent with the same + `sorting` as the request that issued the token. + oneOf: + - $ref: ../../../components/schemas/page-token.yaml + - type: 'null' + sorting: + type: object + description: Sort order. Defaults to `created_at` ascending; `id` breaks ties either way. + required: + - field + - direction + properties: + field: + $ref: app-filter-field.yaml + description: The field to sort by. + direction: + $ref: ../../../components/schemas/sort-direction.yaml + description: The direction to sort by. + filter: + type: array + description: Filter criteria for querying apps. Combined with AND. + items: + type: object + required: + - field + - operation + properties: + field: + $ref: app-filter-field.yaml + description: The field to filter by. + value: + $ref: ../../../components/schemas/filter-value.yaml + operation: + $ref: ../../../components/schemas/filter-operation.yaml diff --git a/apps/api/api/openapi/endpoints/apps/query/query-apps-response.yaml b/apps/api/api/openapi/endpoints/apps/query/query-apps-response.yaml new file mode 100644 index 0000000000..24595be721 --- /dev/null +++ b/apps/api/api/openapi/endpoints/apps/query/query-apps-response.yaml @@ -0,0 +1,16 @@ +type: object +description: Paginated list of apps. +required: + - apps +properties: + apps: + type: array + items: + $ref: ../app-response.yaml + next_page_token: + description: | + Token to pass as `page_token` in the next request to fetch the following + page. Absent when there are no more results. + oneOf: + - $ref: ../../../components/schemas/page-token.yaml + - type: 'null' diff --git a/apps/api/api/openapi/endpoints/apps/query/queryApps-error-response.yaml b/apps/api/api/openapi/endpoints/apps/query/queryApps-error-response.yaml new file mode 100644 index 0000000000..29d9bed29f --- /dev/null +++ b/apps/api/api/openapi/endpoints/apps/query/queryApps-error-response.yaml @@ -0,0 +1,66 @@ +# generated by gen_openapi_errors; DO NOT EDIT +description: Error response +content: + application/json: + schema: + oneOf: + - $ref: '../../../components/schemas/errors/app-not_found.yaml' + - $ref: '../../../components/schemas/errors/app-permission_denied.yaml' + - $ref: '../../../components/schemas/errors/auth-csrf_invalid.yaml' + - $ref: '../../../components/schemas/errors/auth-unauthorized.yaml' + - $ref: '../../../components/schemas/errors/internal.yaml' + - $ref: '../../../components/schemas/errors/not_implemented.yaml' + - $ref: '../../../components/schemas/errors/req-invalid.yaml' + - $ref: '../../../components/schemas/errors/unavailable.yaml' + discriminator: + propertyName: code + mapping: + app.not_found: '../../../components/schemas/errors/app-not_found.yaml' + app.permission_denied: '../../../components/schemas/errors/app-permission_denied.yaml' + auth.csrf_invalid: '../../../components/schemas/errors/auth-csrf_invalid.yaml' + auth.unauthorized: '../../../components/schemas/errors/auth-unauthorized.yaml' + internal: '../../../components/schemas/errors/internal.yaml' + not_implemented: '../../../components/schemas/errors/not_implemented.yaml' + req.invalid: '../../../components/schemas/errors/req-invalid.yaml' + unavailable: '../../../components/schemas/errors/unavailable.yaml' + examples: + app.not_found: + summary: app.not_found + value: + code: app.not_found + message: 'app: not found' + app.permission_denied: + summary: app.permission_denied + value: + code: app.permission_denied + message: 'app: the caller''s project role does not allow this operation' + auth.csrf_invalid: + summary: auth.csrf_invalid + value: + code: auth.csrf_invalid + message: 'The request failed cross-site request forgery validation.' + auth.unauthorized: + summary: auth.unauthorized + value: + code: auth.unauthorized + message: 'The request lacks valid authentication credentials.' + internal: + summary: internal + value: + code: internal + message: 'An unexpected error occurred.' + not_implemented: + summary: not_implemented + value: + code: not_implemented + message: 'This feature is not implemented yet.' + req.invalid: + summary: req.invalid + value: + code: req.invalid + message: 'The request is invalid and fails base validation (missing required fields, wrong types, failed regex, etc.). Check the details for more information.' + unavailable: + summary: unavailable + value: + code: unavailable + message: 'The service could not complete the request right now. Try again.' diff --git a/apps/api/api/openapi/endpoints/apps/revisions/by_id/getAppRevisionById-error-response.yaml b/apps/api/api/openapi/endpoints/apps/revisions/by_id/getAppRevisionById-error-response.yaml new file mode 100644 index 0000000000..cf9ba36127 --- /dev/null +++ b/apps/api/api/openapi/endpoints/apps/revisions/by_id/getAppRevisionById-error-response.yaml @@ -0,0 +1,59 @@ +# generated by gen_openapi_errors; DO NOT EDIT +description: Error response +content: + application/json: + schema: + oneOf: + - $ref: '../../../../components/schemas/errors/app-not_found.yaml' + - $ref: '../../../../components/schemas/errors/app-permission_denied.yaml' + - $ref: '../../../../components/schemas/errors/auth-unauthorized.yaml' + - $ref: '../../../../components/schemas/errors/internal.yaml' + - $ref: '../../../../components/schemas/errors/not_implemented.yaml' + - $ref: '../../../../components/schemas/errors/req-invalid.yaml' + - $ref: '../../../../components/schemas/errors/unavailable.yaml' + discriminator: + propertyName: code + mapping: + app.not_found: '../../../../components/schemas/errors/app-not_found.yaml' + app.permission_denied: '../../../../components/schemas/errors/app-permission_denied.yaml' + auth.unauthorized: '../../../../components/schemas/errors/auth-unauthorized.yaml' + internal: '../../../../components/schemas/errors/internal.yaml' + not_implemented: '../../../../components/schemas/errors/not_implemented.yaml' + req.invalid: '../../../../components/schemas/errors/req-invalid.yaml' + unavailable: '../../../../components/schemas/errors/unavailable.yaml' + examples: + app.not_found: + summary: app.not_found + value: + code: app.not_found + message: 'app: not found' + app.permission_denied: + summary: app.permission_denied + value: + code: app.permission_denied + message: 'app: the caller''s project role does not allow this operation' + auth.unauthorized: + summary: auth.unauthorized + value: + code: auth.unauthorized + message: 'The request lacks valid authentication credentials.' + internal: + summary: internal + value: + code: internal + message: 'An unexpected error occurred.' + not_implemented: + summary: not_implemented + value: + code: not_implemented + message: 'This feature is not implemented yet.' + req.invalid: + summary: req.invalid + value: + code: req.invalid + message: 'The request is invalid and fails base validation (missing required fields, wrong types, failed regex, etc.). Check the details for more information.' + unavailable: + summary: unavailable + value: + code: unavailable + message: 'The service could not complete the request right now. Try again.' diff --git a/apps/api/api/openapi/endpoints/apps/revisions/by_id/methods.yaml b/apps/api/api/openapi/endpoints/apps/revisions/by_id/methods.yaml new file mode 100644 index 0000000000..dafc9dddb6 --- /dev/null +++ b/apps/api/api/openapi/endpoints/apps/revisions/by_id/methods.yaml @@ -0,0 +1,44 @@ +get: + operationId: getAppRevisionById + summary: Get one revision of an app + description: | + 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`. + tags: + - Apps + security: + - oauth2: + - app.read + - sessionCookie: [] + parameters: + - $ref: ../../../../components/parameters/project-id.yaml + - $ref: ../../../../components/parameters/app-revision-id.yaml + responses: + '200': + description: The revision was retrieved successfully. + content: + application/json: + schema: + $ref: ../../app-response.yaml + '401': + description: Missing or invalid credentials. + content: + application/json: + schema: + $ref: ../../../../components/error-details.yaml + '403': + description: Insufficient permissions. + content: + application/json: + schema: + $ref: ../../../../components/error-details.yaml + '404': + description: No app with this id exists in the given project. + content: + application/json: + schema: + $ref: ../../../../components/error-details.yaml + default: + $ref: getAppRevisionById-error-response.yaml diff --git a/apps/api/api/openapi/endpoints/client_registrations/by_id/deleteClientRegistration-error-response.yaml b/apps/api/api/openapi/endpoints/client_registrations/by_id/deleteClientRegistration-error-response.yaml new file mode 100644 index 0000000000..5f39bcf5e3 --- /dev/null +++ b/apps/api/api/openapi/endpoints/client_registrations/by_id/deleteClientRegistration-error-response.yaml @@ -0,0 +1,73 @@ +# generated by gen_openapi_errors; DO NOT EDIT +description: Error response +content: + application/json: + schema: + oneOf: + - $ref: '../../../components/schemas/errors/app-permission_denied.yaml' + - $ref: '../../../components/schemas/errors/auth-csrf_invalid.yaml' + - $ref: '../../../components/schemas/errors/auth-unauthorized.yaml' + - $ref: '../../../components/schemas/errors/app-client_registration_not_found.yaml' + - $ref: '../../../components/schemas/errors/evt-invalid.yaml' + - $ref: '../../../components/schemas/errors/internal.yaml' + - $ref: '../../../components/schemas/errors/not_implemented.yaml' + - $ref: '../../../components/schemas/errors/req-invalid.yaml' + - $ref: '../../../components/schemas/errors/unavailable.yaml' + discriminator: + propertyName: code + mapping: + app.permission_denied: '../../../components/schemas/errors/app-permission_denied.yaml' + auth.csrf_invalid: '../../../components/schemas/errors/auth-csrf_invalid.yaml' + auth.unauthorized: '../../../components/schemas/errors/auth-unauthorized.yaml' + app.client_registration_not_found: '../../../components/schemas/errors/app-client_registration_not_found.yaml' + evt.invalid: '../../../components/schemas/errors/evt-invalid.yaml' + internal: '../../../components/schemas/errors/internal.yaml' + not_implemented: '../../../components/schemas/errors/not_implemented.yaml' + req.invalid: '../../../components/schemas/errors/req-invalid.yaml' + unavailable: '../../../components/schemas/errors/unavailable.yaml' + examples: + app.permission_denied: + summary: app.permission_denied + value: + code: app.permission_denied + message: 'app: the caller''s project role does not allow this operation' + auth.csrf_invalid: + summary: auth.csrf_invalid + value: + code: auth.csrf_invalid + message: 'The request failed cross-site request forgery validation.' + auth.unauthorized: + summary: auth.unauthorized + value: + code: auth.unauthorized + message: 'The request lacks valid authentication credentials.' + app.client_registration_not_found: + summary: app.client_registration_not_found + value: + code: app.client_registration_not_found + message: 'app: no registered client has the client_id' + evt.invalid: + summary: evt.invalid + value: + code: evt.invalid + message: 'event: invalid' + internal: + summary: internal + value: + code: internal + message: 'An unexpected error occurred.' + not_implemented: + summary: not_implemented + value: + code: not_implemented + message: 'This feature is not implemented yet.' + req.invalid: + summary: req.invalid + value: + code: req.invalid + message: 'The request is invalid and fails base validation (missing required fields, wrong types, failed regex, etc.). Check the details for more information.' + unavailable: + summary: unavailable + value: + code: unavailable + message: 'The service could not complete the request right now. Try again.' diff --git a/apps/api/api/openapi/endpoints/client_registrations/by_id/getClientRegistrationById-error-response.yaml b/apps/api/api/openapi/endpoints/client_registrations/by_id/getClientRegistrationById-error-response.yaml new file mode 100644 index 0000000000..073d4bab1d --- /dev/null +++ b/apps/api/api/openapi/endpoints/client_registrations/by_id/getClientRegistrationById-error-response.yaml @@ -0,0 +1,59 @@ +# generated by gen_openapi_errors; DO NOT EDIT +description: Error response +content: + application/json: + schema: + oneOf: + - $ref: '../../../components/schemas/errors/app-permission_denied.yaml' + - $ref: '../../../components/schemas/errors/auth-unauthorized.yaml' + - $ref: '../../../components/schemas/errors/app-client_registration_not_found.yaml' + - $ref: '../../../components/schemas/errors/internal.yaml' + - $ref: '../../../components/schemas/errors/not_implemented.yaml' + - $ref: '../../../components/schemas/errors/req-invalid.yaml' + - $ref: '../../../components/schemas/errors/unavailable.yaml' + discriminator: + propertyName: code + mapping: + app.permission_denied: '../../../components/schemas/errors/app-permission_denied.yaml' + auth.unauthorized: '../../../components/schemas/errors/auth-unauthorized.yaml' + app.client_registration_not_found: '../../../components/schemas/errors/app-client_registration_not_found.yaml' + internal: '../../../components/schemas/errors/internal.yaml' + not_implemented: '../../../components/schemas/errors/not_implemented.yaml' + req.invalid: '../../../components/schemas/errors/req-invalid.yaml' + unavailable: '../../../components/schemas/errors/unavailable.yaml' + examples: + app.permission_denied: + summary: app.permission_denied + value: + code: app.permission_denied + message: 'app: the caller''s project role does not allow this operation' + auth.unauthorized: + summary: auth.unauthorized + value: + code: auth.unauthorized + message: 'The request lacks valid authentication credentials.' + app.client_registration_not_found: + summary: app.client_registration_not_found + value: + code: app.client_registration_not_found + message: 'app: no registered client has the client_id' + internal: + summary: internal + value: + code: internal + message: 'An unexpected error occurred.' + not_implemented: + summary: not_implemented + value: + code: not_implemented + message: 'This feature is not implemented yet.' + req.invalid: + summary: req.invalid + value: + code: req.invalid + message: 'The request is invalid and fails base validation (missing required fields, wrong types, failed regex, etc.). Check the details for more information.' + unavailable: + summary: unavailable + value: + code: unavailable + message: 'The service could not complete the request right now. Try again.' diff --git a/apps/api/api/openapi/endpoints/client_registrations/by_id/methods.yaml b/apps/api/api/openapi/endpoints/client_registrations/by_id/methods.yaml new file mode 100644 index 0000000000..81672f4a65 --- /dev/null +++ b/apps/api/api/openapi/endpoints/client_registrations/by_id/methods.yaml @@ -0,0 +1,83 @@ +get: + operationId: getClientRegistrationById + x-zitadel-cli: client-registrations get + summary: Get a client registration + description: | + Reads a client that registered itself through dynamic client registration, + by its client_id. The lookup is scoped to the project in `project_id`. + tags: + - Apps + security: + - oauth2: + - app.read + - sessionCookie: [] + parameters: + - $ref: ../../../components/parameters/project-id.yaml + - $ref: ../../../components/parameters/client-registration-id.yaml + responses: + '200': + description: The client registration was retrieved successfully. + content: + application/json: + schema: + $ref: ../client-registration-response.yaml + '401': + description: Missing or invalid credentials. + content: + application/json: + schema: + $ref: ../../../components/error-details.yaml + '403': + description: Insufficient permissions. + content: + application/json: + schema: + $ref: ../../../components/error-details.yaml + '404': + description: No client registration with this client_id exists in the given project. + content: + application/json: + schema: + $ref: ../../../components/error-details.yaml + default: + $ref: getClientRegistrationById-error-response.yaml +delete: + operationId: deleteClientRegistration + x-zitadel-cli: client-registrations delete + summary: Delete a client registration + description: | + Deletes a client that registered itself, together with the consents users + gave it and the tokens issued under them, so the client can no longer get + or refresh a token. Emits `client_registration.deleted`. + tags: + - Apps + security: + - oauth2: + - app.write + - sessionCookie: [] + parameters: + - $ref: ../../../components/parameters/project-id.yaml + - $ref: ../../../components/parameters/client-registration-id.yaml + responses: + '204': + description: The client registration was deleted. + '401': + description: Missing or invalid credentials. + content: + application/json: + schema: + $ref: ../../../components/error-details.yaml + '403': + description: Insufficient permissions. + content: + application/json: + schema: + $ref: ../../../components/error-details.yaml + '404': + description: No client registration with this client_id exists in the given project. + content: + application/json: + schema: + $ref: ../../../components/error-details.yaml + default: + $ref: deleteClientRegistration-error-response.yaml diff --git a/apps/api/api/openapi/endpoints/client_registrations/client-registration-response.yaml b/apps/api/api/openapi/endpoints/client_registrations/client-registration-response.yaml new file mode 100644 index 0000000000..ddd2245111 --- /dev/null +++ b/apps/api/api/openapi/endpoints/client_registrations/client-registration-response.yaml @@ -0,0 +1,78 @@ +type: object +description: | + A client that registered itself through dynamic client registration + (RFC 7591). It registers at the project and joins the app whose API its + first authorization request names: it may then get tokens for that app's + `third_party` APIs, each with the user's consent, and a request for another + app's API is refused. It is transient: once past `expires_at` it is purged unless + a live consent names it. The display fields are the client's own claims; the + server checked only its redirect URIs. Its secret is never returned. +required: + - id + - redirect_uris + - grant_types + - token_endpoint_auth_method + - created_at + - expires_at +properties: + id: + type: string + description: The client_id the server minted for the client. + example: dcr_01KWH3B72K7M7F0N9WD3P2E4YM + app: + type: string + description: The slug of the app the client joined. Absent until its first authorization request names an API. + example: shop + client_name: + type: string + description: The name the client registered with. + example: Claude Code + client_uri: + type: string + description: The client's home page, as the client claims it. + logo_uri: + type: string + description: The client's logo, as the client claims it. + policy_uri: + type: string + description: The client's privacy policy, as the client claims it. + tos_uri: + type: string + description: The client's terms of service, as the client claims it. + software_id: + type: string + description: The software the client says it is, stable across its registrations. + software_version: + type: string + description: The version of that software. + redirect_uris: + type: array + description: Where the authorization server may send the browser back to. + items: + type: string + example: + - http://localhost:33418/callback + grant_types: + type: array + items: + type: string + enum: + - authorization_code + - refresh_token + token_endpoint_auth_method: + type: string + description: How the client authenticates at the token endpoint. `none` for a public client. + enum: + - none + - client_secret_basic + - client_secret_post + created_at: + type: string + format: date-time + expires_at: + type: string + format: date-time + description: | + The earliest the registration may be purged. Past it, the registration + goes unless a live consent names it; one a consent names is checked + again an hour later. diff --git a/apps/api/api/openapi/endpoints/client_registrations/query/client-registration-filter-field.yaml b/apps/api/api/openapi/endpoints/client_registrations/query/client-registration-filter-field.yaml new file mode 100644 index 0000000000..c61129145c --- /dev/null +++ b/apps/api/api/openapi/endpoints/client_registrations/query/client-registration-filter-field.yaml @@ -0,0 +1,10 @@ +type: string +description: | + Field to filter or sort client registrations by: + - `app`: the slug of the app the client joined (filter only) + - `created_at`: RFC3339 timestamp + - `expires_at`: RFC3339 timestamp +enum: + - app + - created_at + - expires_at diff --git a/apps/api/api/openapi/endpoints/client_registrations/query/methods.yaml b/apps/api/api/openapi/endpoints/client_registrations/query/methods.yaml new file mode 100644 index 0000000000..aa5f3da963 --- /dev/null +++ b/apps/api/api/openapi/endpoints/client_registrations/query/methods.yaml @@ -0,0 +1,57 @@ +post: + operationId: queryClientRegistrations + x-zitadel-cli: client-registrations list + summary: Query client registrations + description: | + Returns the clients that registered themselves into the project through + dynamic client registration (RFC 7591), paginated with a cursor. Clients + register at the authorization server's registration endpoint, never + through this API. + tags: + - Apps + security: + - oauth2: + - app.read + - sessionCookie: [] + parameters: + - $ref: ../../../components/parameters/project-id.yaml + requestBody: + description: Request to query the client registrations of a project. + required: true + content: + application/json: + schema: + $ref: query-client-registrations-request.yaml + responses: + '200': + description: The client registrations were returned successfully. + content: + application/json: + schema: + $ref: query-client-registrations-response.yaml + '400': + description: The filter or the sort names a field or an operation client registrations do not support. + content: + application/json: + schema: + $ref: ../../../components/error-details.yaml + '401': + description: Missing or invalid credentials. + content: + application/json: + schema: + $ref: ../../../components/error-details.yaml + '403': + description: Insufficient permissions. + content: + application/json: + schema: + $ref: ../../../components/error-details.yaml + '404': + description: Project not found. + content: + application/json: + schema: + $ref: ../../../components/error-details.yaml + default: + $ref: queryClientRegistrations-error-response.yaml diff --git a/apps/api/api/openapi/endpoints/client_registrations/query/query-client-registrations-request.yaml b/apps/api/api/openapi/endpoints/client_registrations/query/query-client-registrations-request.yaml new file mode 100644 index 0000000000..c840ae4d23 --- /dev/null +++ b/apps/api/api/openapi/endpoints/client_registrations/query/query-client-registrations-request.yaml @@ -0,0 +1,41 @@ +type: object +description: Request to query the client registrations of a project. +properties: + limit: + $ref: ../../../components/schemas/limit.yaml + page_token: + description: | + Token to retrieve the next page of results. Must be sent with the same + `sorting` as the request that issued the token. + oneOf: + - $ref: ../../../components/schemas/page-token.yaml + - type: 'null' + sorting: + type: object + description: Sort order. Defaults to `created_at` ascending; `id` breaks ties either way. + required: + - field + - direction + properties: + field: + $ref: client-registration-filter-field.yaml + description: The field to sort by. + direction: + $ref: ../../../components/schemas/sort-direction.yaml + description: The direction to sort by. + filter: + type: array + description: Filter criteria for querying client registrations. Combined with AND. + items: + type: object + required: + - field + - operation + properties: + field: + $ref: client-registration-filter-field.yaml + description: The field to filter by. + value: + $ref: ../../../components/schemas/filter-value.yaml + operation: + $ref: ../../../components/schemas/filter-operation.yaml diff --git a/apps/api/api/openapi/endpoints/client_registrations/query/query-client-registrations-response.yaml b/apps/api/api/openapi/endpoints/client_registrations/query/query-client-registrations-response.yaml new file mode 100644 index 0000000000..b0097d13fe --- /dev/null +++ b/apps/api/api/openapi/endpoints/client_registrations/query/query-client-registrations-response.yaml @@ -0,0 +1,16 @@ +type: object +description: Paginated list of client registrations. +required: + - client_registrations +properties: + client_registrations: + type: array + items: + $ref: ../client-registration-response.yaml + next_page_token: + description: | + Token to pass as `page_token` in the next request to fetch the following + page. Absent when there are no more results. + oneOf: + - $ref: ../../../components/schemas/page-token.yaml + - type: 'null' diff --git a/apps/api/api/openapi/endpoints/client_registrations/query/queryClientRegistrations-error-response.yaml b/apps/api/api/openapi/endpoints/client_registrations/query/queryClientRegistrations-error-response.yaml new file mode 100644 index 0000000000..14a8fdf24b --- /dev/null +++ b/apps/api/api/openapi/endpoints/client_registrations/query/queryClientRegistrations-error-response.yaml @@ -0,0 +1,66 @@ +# generated by gen_openapi_errors; DO NOT EDIT +description: Error response +content: + application/json: + schema: + oneOf: + - $ref: '../../../components/schemas/errors/app-permission_denied.yaml' + - $ref: '../../../components/schemas/errors/auth-csrf_invalid.yaml' + - $ref: '../../../components/schemas/errors/auth-unauthorized.yaml' + - $ref: '../../../components/schemas/errors/app-client_registration_not_found.yaml' + - $ref: '../../../components/schemas/errors/internal.yaml' + - $ref: '../../../components/schemas/errors/not_implemented.yaml' + - $ref: '../../../components/schemas/errors/req-invalid.yaml' + - $ref: '../../../components/schemas/errors/unavailable.yaml' + discriminator: + propertyName: code + mapping: + app.permission_denied: '../../../components/schemas/errors/app-permission_denied.yaml' + auth.csrf_invalid: '../../../components/schemas/errors/auth-csrf_invalid.yaml' + auth.unauthorized: '../../../components/schemas/errors/auth-unauthorized.yaml' + app.client_registration_not_found: '../../../components/schemas/errors/app-client_registration_not_found.yaml' + internal: '../../../components/schemas/errors/internal.yaml' + not_implemented: '../../../components/schemas/errors/not_implemented.yaml' + req.invalid: '../../../components/schemas/errors/req-invalid.yaml' + unavailable: '../../../components/schemas/errors/unavailable.yaml' + examples: + app.permission_denied: + summary: app.permission_denied + value: + code: app.permission_denied + message: 'app: the caller''s project role does not allow this operation' + auth.csrf_invalid: + summary: auth.csrf_invalid + value: + code: auth.csrf_invalid + message: 'The request failed cross-site request forgery validation.' + auth.unauthorized: + summary: auth.unauthorized + value: + code: auth.unauthorized + message: 'The request lacks valid authentication credentials.' + app.client_registration_not_found: + summary: app.client_registration_not_found + value: + code: app.client_registration_not_found + message: 'app: no registered client has the client_id' + internal: + summary: internal + value: + code: internal + message: 'An unexpected error occurred.' + not_implemented: + summary: not_implemented + value: + code: not_implemented + message: 'This feature is not implemented yet.' + req.invalid: + summary: req.invalid + value: + code: req.invalid + message: 'The request is invalid and fails base validation (missing required fields, wrong types, failed regex, etc.). Check the details for more information.' + unavailable: + summary: unavailable + value: + code: unavailable + message: 'The service could not complete the request right now. Try again.' diff --git a/apps/api/api/openapi/endpoints/events/event.yaml b/apps/api/api/openapi/endpoints/events/event.yaml index 311beca9e8..12c0479634 100644 --- a/apps/api/api/openapi/endpoints/events/event.yaml +++ b/apps/api/api/openapi/endpoints/events/event.yaml @@ -3,6 +3,10 @@ description: | Discriminated wide-event union (ADR 048 / ADR 049). Clients select the member via event_type; each member carries a typed payload. oneOf: + - $ref: types/app-created-event.yaml + - $ref: types/app-credential-added-event.yaml + - $ref: types/app-credential-revoked-event.yaml + - $ref: types/app-updated-event.yaml - $ref: types/auth-attempt-created-event.yaml - $ref: types/auth-attempt-handed_off-event.yaml - $ref: types/auth-check-failed-event.yaml @@ -17,6 +21,8 @@ oneOf: - $ref: types/authz-granted-event.yaml - $ref: types/authz-revoked-event.yaml - $ref: types/branding-created-event.yaml + - $ref: types/client_registration-created-event.yaml + - $ref: types/client_registration-deleted-event.yaml - $ref: types/deployment-created-event.yaml - $ref: types/flowdef-created-event.yaml - $ref: types/flowdef-deleted-event.yaml @@ -50,6 +56,10 @@ oneOf: discriminator: propertyName: event_type mapping: + app.created: types/app-created-event.yaml + app.credential.added: types/app-credential-added-event.yaml + app.credential.revoked: types/app-credential-revoked-event.yaml + app.updated: types/app-updated-event.yaml auth.attempt.created: types/auth-attempt-created-event.yaml auth.attempt.handed_off: types/auth-attempt-handed_off-event.yaml auth.check.failed: types/auth-check-failed-event.yaml @@ -64,6 +74,8 @@ discriminator: authz.granted: types/authz-granted-event.yaml authz.revoked: types/authz-revoked-event.yaml branding.created: types/branding-created-event.yaml + client_registration.created: types/client_registration-created-event.yaml + client_registration.deleted: types/client_registration-deleted-event.yaml deployment.created: types/deployment-created-event.yaml flowdef.created: types/flowdef-created-event.yaml flowdef.deleted: types/flowdef-deleted-event.yaml diff --git a/apps/api/api/openapi/endpoints/events/payloads/app-credential-payload.yaml b/apps/api/api/openapi/endpoints/events/payloads/app-credential-payload.yaml new file mode 100644 index 0000000000..43eb2c8604 --- /dev/null +++ b/apps/api/api/openapi/endpoints/events/payloads/app-credential-payload.yaml @@ -0,0 +1,32 @@ +title: AppCredentialPayload +type: object +description: | + A credential of a client of the app (the event's `entity_id`) was added or + revoked. Never a secret, its hash or a key. +required: + - client + - client_id + - credential_id + - name + - kind +properties: + client: + type: string + description: The client's slug. + client_id: + type: string + credential_id: + type: string + name: + type: string + kind: + type: string + enum: + - secret + - key + origin: + type: string + enum: + - generated + - imported + description: How a secret was added, on `app.credential.added`. Absent for a key and on `app.credential.revoked`. diff --git a/apps/api/api/openapi/endpoints/events/payloads/app-payload.yaml b/apps/api/api/openapi/endpoints/events/payloads/app-payload.yaml new file mode 100644 index 0000000000..69219bfe14 --- /dev/null +++ b/apps/api/api/openapi/endpoints/events/payloads/app-payload.yaml @@ -0,0 +1,31 @@ +title: AppPayload +type: object +description: | + Shared allowlisted fields for `app.created` (snapshot) and `app.updated` + (delta: only changed fields present, plus the new `revision_id`). The app id + is the event's `entity_id`. The document is never included: a declared + app's secret references and its redirect URIs stay out of the stream, and + the slugs of what the app holds say what changed. +required: + - revision_id +properties: + slug: + type: string + source: + type: string + description: '`declared` or `registered`.' + name: + type: string + clients: + type: array + description: The slugs of the app's clients; on `app.updated`, present only when they changed. + items: + type: string + apis: + type: array + description: The slugs of the app's APIs; on `app.updated`, present only when they changed. + items: + type: string + revision_id: + type: string + description: The revision the write appended. diff --git a/apps/api/api/openapi/endpoints/events/payloads/client-registration-payload.yaml b/apps/api/api/openapi/endpoints/events/payloads/client-registration-payload.yaml new file mode 100644 index 0000000000..1a57558671 --- /dev/null +++ b/apps/api/api/openapi/endpoints/events/payloads/client-registration-payload.yaml @@ -0,0 +1,43 @@ +title: ClientRegistrationPayload +type: object +description: | + The metadata a client registered with through dynamic client registration + (RFC 7591), as the server keeps it, after its defaults. The client + registration (the event's `entity_id`) is the `client_id`. Never the secret + or its hash. +required: + - redirect_uris + - grant_types + - token_endpoint_auth_method +properties: + client_name: + type: string + client_uri: + type: string + logo_uri: + type: string + policy_uri: + type: string + tos_uri: + type: string + software_id: + type: string + software_version: + type: string + redirect_uris: + type: array + items: + type: string + grant_types: + type: array + items: + type: string + enum: + - authorization_code + - refresh_token + token_endpoint_auth_method: + type: string + enum: + - none + - client_secret_basic + - client_secret_post diff --git a/apps/api/api/openapi/endpoints/events/types/app-created-event.yaml b/apps/api/api/openapi/endpoints/events/types/app-created-event.yaml new file mode 100644 index 0000000000..cda8235965 --- /dev/null +++ b/apps/api/api/openapi/endpoints/events/types/app-created-event.yaml @@ -0,0 +1,16 @@ +# Code generated by gen_event_schemas; DO NOT EDIT. +title: AppCreatedEvent +description: | + Wide event with event_type=app.created. +allOf: + - $ref: ../event-base.yaml + - type: object + required: + - event_type + - payload + properties: + event_type: + type: string + const: app.created + payload: + $ref: ../payloads/app-payload.yaml diff --git a/apps/api/api/openapi/endpoints/events/types/app-credential-added-event.yaml b/apps/api/api/openapi/endpoints/events/types/app-credential-added-event.yaml new file mode 100644 index 0000000000..e3b39175b1 --- /dev/null +++ b/apps/api/api/openapi/endpoints/events/types/app-credential-added-event.yaml @@ -0,0 +1,16 @@ +# Code generated by gen_event_schemas; DO NOT EDIT. +title: AppCredentialAddedEvent +description: | + Wide event with event_type=app.credential.added. +allOf: + - $ref: ../event-base.yaml + - type: object + required: + - event_type + - payload + properties: + event_type: + type: string + const: app.credential.added + payload: + $ref: ../payloads/app-credential-payload.yaml diff --git a/apps/api/api/openapi/endpoints/events/types/app-credential-revoked-event.yaml b/apps/api/api/openapi/endpoints/events/types/app-credential-revoked-event.yaml new file mode 100644 index 0000000000..0d1058af05 --- /dev/null +++ b/apps/api/api/openapi/endpoints/events/types/app-credential-revoked-event.yaml @@ -0,0 +1,16 @@ +# Code generated by gen_event_schemas; DO NOT EDIT. +title: AppCredentialRevokedEvent +description: | + Wide event with event_type=app.credential.revoked. +allOf: + - $ref: ../event-base.yaml + - type: object + required: + - event_type + - payload + properties: + event_type: + type: string + const: app.credential.revoked + payload: + $ref: ../payloads/app-credential-payload.yaml diff --git a/apps/api/api/openapi/endpoints/events/types/app-updated-event.yaml b/apps/api/api/openapi/endpoints/events/types/app-updated-event.yaml new file mode 100644 index 0000000000..5865d474b9 --- /dev/null +++ b/apps/api/api/openapi/endpoints/events/types/app-updated-event.yaml @@ -0,0 +1,16 @@ +# Code generated by gen_event_schemas; DO NOT EDIT. +title: AppUpdatedEvent +description: | + Wide event with event_type=app.updated. +allOf: + - $ref: ../event-base.yaml + - type: object + required: + - event_type + - payload + properties: + event_type: + type: string + const: app.updated + payload: + $ref: ../payloads/app-payload.yaml diff --git a/apps/api/api/openapi/endpoints/events/types/client_registration-created-event.yaml b/apps/api/api/openapi/endpoints/events/types/client_registration-created-event.yaml new file mode 100644 index 0000000000..a69de82674 --- /dev/null +++ b/apps/api/api/openapi/endpoints/events/types/client_registration-created-event.yaml @@ -0,0 +1,16 @@ +# Code generated by gen_event_schemas; DO NOT EDIT. +title: ClientRegistrationCreatedEvent +description: | + Wide event with event_type=client_registration.created. +allOf: + - $ref: ../event-base.yaml + - type: object + required: + - event_type + - payload + properties: + event_type: + type: string + const: client_registration.created + payload: + $ref: ../payloads/client-registration-payload.yaml diff --git a/apps/api/api/openapi/endpoints/events/types/client_registration-deleted-event.yaml b/apps/api/api/openapi/endpoints/events/types/client_registration-deleted-event.yaml new file mode 100644 index 0000000000..733a1a55b4 --- /dev/null +++ b/apps/api/api/openapi/endpoints/events/types/client_registration-deleted-event.yaml @@ -0,0 +1,16 @@ +# Code generated by gen_event_schemas; DO NOT EDIT. +title: ClientRegistrationDeletedEvent +description: | + Wide event with event_type=client_registration.deleted. +allOf: + - $ref: ../event-base.yaml + - type: object + required: + - event_type + - payload + properties: + event_type: + type: string + const: client_registration.deleted + payload: + $ref: ../payloads/client-registration-payload.yaml diff --git a/apps/api/api/openapi/endpoints/events/webhooks/app-created.yaml b/apps/api/api/openapi/endpoints/events/webhooks/app-created.yaml new file mode 100644 index 0000000000..cfe800cbd0 --- /dev/null +++ b/apps/api/api/openapi/endpoints/events/webhooks/app-created.yaml @@ -0,0 +1,25 @@ +# Code generated by gen_event_schemas; DO NOT EDIT. +post: + operationId: appCreated + summary: app.created + description: | + An app was created, by a release that declares it or through the API. + + The body is the event as `GET /events` returns it. + tags: + - Event Webhooks + security: [] + requestBody: + required: true + content: + application/json: + schema: + $ref: ../types/app-created-event.yaml + responses: + '2XX': + description: Delivered. Any 2xx status acknowledges the event; the response body is ignored. + default: + description: | + Not delivered: any other status, a failed connection, or a timeout. + The server sends the event again on its next pass, and holds back the + project's later events until this one is delivered. diff --git a/apps/api/api/openapi/endpoints/events/webhooks/app-credential-added.yaml b/apps/api/api/openapi/endpoints/events/webhooks/app-credential-added.yaml new file mode 100644 index 0000000000..ae362e2a93 --- /dev/null +++ b/apps/api/api/openapi/endpoints/events/webhooks/app-credential-added.yaml @@ -0,0 +1,26 @@ +# Code generated by gen_event_schemas; DO NOT EDIT. +post: + operationId: appCredentialAdded + summary: app.credential.added + description: | + A client of an app got a named credential through the API: a secret the + server generated or imported, or a public key. + + The body is the event as `GET /events` returns it. + tags: + - Event Webhooks + security: [] + requestBody: + required: true + content: + application/json: + schema: + $ref: ../types/app-credential-added-event.yaml + responses: + '2XX': + description: Delivered. Any 2xx status acknowledges the event; the response body is ignored. + default: + description: | + Not delivered: any other status, a failed connection, or a timeout. + The server sends the event again on its next pass, and holds back the + project's later events until this one is delivered. diff --git a/apps/api/api/openapi/endpoints/events/webhooks/app-credential-revoked.yaml b/apps/api/api/openapi/endpoints/events/webhooks/app-credential-revoked.yaml new file mode 100644 index 0000000000..d7bb22ecec --- /dev/null +++ b/apps/api/api/openapi/endpoints/events/webhooks/app-credential-revoked.yaml @@ -0,0 +1,26 @@ +# Code generated by gen_event_schemas; DO NOT EDIT. +post: + operationId: appCredentialRevoked + summary: app.credential.revoked + description: | + A credential of a client of an app was revoked; the client's other + credentials keep working. + + The body is the event as `GET /events` returns it. + tags: + - Event Webhooks + security: [] + requestBody: + required: true + content: + application/json: + schema: + $ref: ../types/app-credential-revoked-event.yaml + responses: + '2XX': + description: Delivered. Any 2xx status acknowledges the event; the response body is ignored. + default: + description: | + Not delivered: any other status, a failed connection, or a timeout. + The server sends the event again on its next pass, and holds back the + project's later events until this one is delivered. diff --git a/apps/api/api/openapi/endpoints/events/webhooks/app-updated.yaml b/apps/api/api/openapi/endpoints/events/webhooks/app-updated.yaml new file mode 100644 index 0000000000..bda0584856 --- /dev/null +++ b/apps/api/api/openapi/endpoints/events/webhooks/app-updated.yaml @@ -0,0 +1,26 @@ +# Code generated by gen_event_schemas; DO NOT EDIT. +post: + operationId: appUpdated + summary: app.updated + description: | + An app was revised. The payload holds the new revision and the fields + that changed. + + The body is the event as `GET /events` returns it. + tags: + - Event Webhooks + security: [] + requestBody: + required: true + content: + application/json: + schema: + $ref: ../types/app-updated-event.yaml + responses: + '2XX': + description: Delivered. Any 2xx status acknowledges the event; the response body is ignored. + default: + description: | + Not delivered: any other status, a failed connection, or a timeout. + The server sends the event again on its next pass, and holds back the + project's later events until this one is delivered. diff --git a/apps/api/api/openapi/endpoints/events/webhooks/client_registration-created.yaml b/apps/api/api/openapi/endpoints/events/webhooks/client_registration-created.yaml new file mode 100644 index 0000000000..12b446250e --- /dev/null +++ b/apps/api/api/openapi/endpoints/events/webhooks/client_registration-created.yaml @@ -0,0 +1,26 @@ +# Code generated by gen_event_schemas; DO NOT EDIT. +post: + operationId: clientRegistrationCreated + summary: client_registration.created + description: | + A client registered itself through dynamic client registration (RFC + 7591). + + The body is the event as `GET /events` returns it. + tags: + - Event Webhooks + security: [] + requestBody: + required: true + content: + application/json: + schema: + $ref: ../types/client_registration-created-event.yaml + responses: + '2XX': + description: Delivered. Any 2xx status acknowledges the event; the response body is ignored. + default: + description: | + Not delivered: any other status, a failed connection, or a timeout. + The server sends the event again on its next pass, and holds back the + project's later events until this one is delivered. diff --git a/apps/api/api/openapi/endpoints/events/webhooks/client_registration-deleted.yaml b/apps/api/api/openapi/endpoints/events/webhooks/client_registration-deleted.yaml new file mode 100644 index 0000000000..f33b50f45a --- /dev/null +++ b/apps/api/api/openapi/endpoints/events/webhooks/client_registration-deleted.yaml @@ -0,0 +1,26 @@ +# Code generated by gen_event_schemas; DO NOT EDIT. +post: + operationId: clientRegistrationDeleted + summary: client_registration.deleted + description: | + A client registration was deleted, with its consents and their tokens. A + registration purged after its lifetime emits no event. + + The body is the event as `GET /events` returns it. + tags: + - Event Webhooks + security: [] + requestBody: + required: true + content: + application/json: + schema: + $ref: ../types/client_registration-deleted-event.yaml + responses: + '2XX': + description: Delivered. Any 2xx status acknowledges the event; the response body is ignored. + default: + description: | + Not delivered: any other status, a failed connection, or a timeout. + The server sends the event again on its next pass, and holds back the + project's later events until this one is delivered. diff --git a/apps/api/api/openapi/endpoints/releases/build/buildRelease-error-response.yaml b/apps/api/api/openapi/endpoints/releases/build/buildRelease-error-response.yaml index d736b41a1f..9963c6be59 100644 --- a/apps/api/api/openapi/endpoints/releases/build/buildRelease-error-response.yaml +++ b/apps/api/api/openapi/endpoints/releases/build/buildRelease-error-response.yaml @@ -4,6 +4,11 @@ content: application/json: schema: oneOf: + - $ref: '../../../components/schemas/errors/app-client_id_taken.yaml' + - $ref: '../../../components/schemas/errors/app-credential_taken.yaml' + - $ref: '../../../components/schemas/errors/app-declared.yaml' + - $ref: '../../../components/schemas/errors/app-field_immutable.yaml' + - $ref: '../../../components/schemas/errors/app-identifier_taken.yaml' - $ref: '../../../components/schemas/errors/auth-unauthorized.yaml' - $ref: '../../../components/schemas/errors/evt-invalid.yaml' - $ref: '../../../components/schemas/errors/flowdef-invalid.yaml' @@ -31,6 +36,11 @@ content: discriminator: propertyName: code mapping: + app.client_id_taken: '../../../components/schemas/errors/app-client_id_taken.yaml' + app.credential_taken: '../../../components/schemas/errors/app-credential_taken.yaml' + app.declared: '../../../components/schemas/errors/app-declared.yaml' + app.field_immutable: '../../../components/schemas/errors/app-field_immutable.yaml' + app.identifier_taken: '../../../components/schemas/errors/app-identifier_taken.yaml' auth.unauthorized: '../../../components/schemas/errors/auth-unauthorized.yaml' evt.invalid: '../../../components/schemas/errors/evt-invalid.yaml' flowdef.invalid: '../../../components/schemas/errors/flowdef-invalid.yaml' @@ -56,6 +66,31 @@ content: flowdef.schema_fetch_failed: '../../../components/schemas/errors/flowdef-schema_fetch_failed.yaml' unavailable: '../../../components/schemas/errors/unavailable.yaml' examples: + app.client_id_taken: + summary: app.client_id_taken + value: + code: app.client_id_taken + message: 'app: another client in the project holds the client_id' + app.credential_taken: + summary: app.credential_taken + value: + code: app.credential_taken + message: 'app: another credential of the client has the name or the key id' + app.declared: + summary: app.declared + value: + code: app.declared + message: 'app: declared in the release, so only a release changes it' + app.field_immutable: + summary: app.field_immutable + value: + code: app.field_immutable + message: 'app: the field is fixed for the life of the client' + app.identifier_taken: + summary: app.identifier_taken + value: + code: app.identifier_taken + message: 'app: another app in the project holds the API identifier' auth.unauthorized: summary: auth.unauthorized value: diff --git a/apps/api/api/openapi/endpoints/releases/build/configuration-bundle.yaml b/apps/api/api/openapi/endpoints/releases/build/configuration-bundle.yaml index a3ab68cb9e..efbacd0a0b 100644 --- a/apps/api/api/openapi/endpoints/releases/build/configuration-bundle.yaml +++ b/apps/api/api/openapi/endpoints/releases/build/configuration-bundle.yaml @@ -69,6 +69,21 @@ properties: carries no credentials. items: $ref: ../../idps/idp-connection.yaml + apps: + type: array + maxItems: 50 + description: | + Apps, one per `.zitadel/apps/.json`, each the document + `POST /apps` takes as `app`. The handle is `slug`. A bundled app is + declared: it is created, or revised when its document changed, inside + the build's transaction, and only a release changes it afterwards. A + slug an app registered through the API holds is refused with a + `rel.invalid` entry, as is a document the rules across its fields + refuse. A confidential client names its secret as a `${{ NAME }}` + reference, so a bundle carries no credentials, and a deploy is refused + while the variable has no value. + items: + $ref: ../../schemas/app.yaml policies: type: array maxItems: 50 diff --git a/apps/api/api/openapi/endpoints/schemas/app-api-scope.yaml b/apps/api/api/openapi/endpoints/schemas/app-api-scope.yaml new file mode 100644 index 0000000000..24b42ece71 --- /dev/null +++ b/apps/api/api/openapi/endpoints/schemas/app-api-scope.yaml @@ -0,0 +1,21 @@ +title: AppAPIScope +type: object +required: +- name +additionalProperties: false +properties: + name: + type: string + pattern: ^[A-Za-z0-9][A-Za-z0-9._:/-]*$ + maxLength: 128 + description: The scope as a client requests it. Unique within the API, and none of the built-in + `openid`, `profile`, `email`, `address`, `phone` and `offline_access`. + examples: + - orders.read + description: + type: string + minLength: 1 + maxLength: 256 + description: What the scope lets a client do, shown on the consent screen. + examples: + - Read your orders diff --git a/apps/api/api/openapi/endpoints/schemas/app-api.json b/apps/api/api/openapi/endpoints/schemas/app-api.json new file mode 100644 index 0000000000..442ffa72d8 --- /dev/null +++ b/apps/api/api/openapi/endpoints/schemas/app-api.json @@ -0,0 +1,90 @@ +{ + "$comment": "Code generated by scripts/generate-meta-schemas.ts; DO NOT EDIT.", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "AppAPI", + "description": "An API the app serves, an MCP server among them. Its identifier is the `aud` of every access token\nfor it, and a token is for one API (RFC 8707).\n", + "type": "object", + "required": [ + "slug", + "identifier" + ], + "additionalProperties": false, + "properties": { + "slug": { + "type": "string", + "pattern": "^[a-z0-9][a-z0-9_-]*$", + "maxLength": 64, + "description": "Stable identifier of the API, unique among the app's clients and APIs. Clients of other apps name it as `/`.", + "examples": [ + "orders", + "mcp" + ] + }, + "name": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Shown on the consent screen. Optional." + }, + "identifier": { + "type": "string", + "pattern": "^(https://|http://|urn:)", + "maxLength": 2048, + "description": "The API's canonical URI: what a client sends as `resource` and what its access tokens carry as\n`aud`. An `https` URL, an `http` URL on a loopback host while developing, or a `urn:`. An MCP\nserver's identifier is the URL clients connect to (RFC 9728). No two APIs in a project share\nan identifier, and an identifier an app has used stays with that app.\n", + "examples": [ + "https://api.shop.example.com", + "https://shop.example.com/mcp" + ] + }, + "scopes": { + "type": "array", + "maxItems": 100, + "items": { + "$ref": "#/$defs/AppApiScope" + }, + "description": "The scopes the API defines on top of the built-in OpenID Connect ones. A request for a scope\nneither defines fails with `invalid_scope`; it is never dropped silently. Granted scopes reach\nthe token in `scope` only, never as claims.\n" + }, + "signing_alg": { + "type": "string", + "enum": [ + "RS256", + "ES256" + ], + "description": "The algorithm access tokens for the API are signed with. RS256 when left out (ADR 082 §7)." + }, + "third_party": { + "type": "boolean", + "description": "Lets clients that registered themselves into the app (client ID metadata documents or dynamic registration) ask for this API and any of its scopes, each with the user's consent. Off when left out." + } + }, + "$defs": { + "AppApiScope": { + "title": "AppAPIScope", + "type": "object", + "required": [ + "name" + ], + "additionalProperties": false, + "properties": { + "name": { + "type": "string", + "pattern": "^[A-Za-z0-9][A-Za-z0-9._:/-]*$", + "maxLength": 128, + "description": "The scope as a client requests it. Unique within the API, and none of the built-in `openid`, `profile`, `email`, `address`, `phone` and `offline_access`.", + "examples": [ + "orders.read" + ] + }, + "description": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "What the scope lets a client do, shown on the consent screen.", + "examples": [ + "Read your orders" + ] + } + } + } + } +} diff --git a/apps/api/api/openapi/endpoints/schemas/app-api.yaml b/apps/api/api/openapi/endpoints/schemas/app-api.yaml new file mode 100644 index 0000000000..e1afebe2ed --- /dev/null +++ b/apps/api/api/openapi/endpoints/schemas/app-api.yaml @@ -0,0 +1,58 @@ +x-meta-schema: true +title: AppAPI +description: | + An API the app serves, an MCP server among them. Its identifier is the `aud` of every access token + for it, and a token is for one API (RFC 8707). +type: object +required: +- slug +- identifier +additionalProperties: false +properties: + slug: + type: string + pattern: ^[a-z0-9][a-z0-9_-]*$ + maxLength: 64 + description: Stable identifier of the API, unique among the app's clients and APIs. Clients of + other apps name it as `/`. + examples: + - orders + - mcp + name: + type: string + minLength: 1 + maxLength: 256 + description: Shown on the consent screen. Optional. + identifier: + type: string + pattern: ^(https://|http://|urn:) + maxLength: 2048 + description: | + The API's canonical URI: what a client sends as `resource` and what its access tokens carry as + `aud`. An `https` URL, an `http` URL on a loopback host while developing, or a `urn:`. An MCP + server's identifier is the URL clients connect to (RFC 9728). No two APIs in a project share + an identifier, and an identifier an app has used stays with that app. + examples: + - https://api.shop.example.com + - https://shop.example.com/mcp + scopes: + type: array + maxItems: 100 + items: + $ref: app-api-scope.yaml + description: | + The scopes the API defines on top of the built-in OpenID Connect ones. A request for a scope + neither defines fails with `invalid_scope`; it is never dropped silently. Granted scopes reach + the token in `scope` only, never as claims. + signing_alg: + type: string + enum: + - RS256 + - ES256 + description: The algorithm access tokens for the API are signed with. RS256 when left out + (ADR 082 §7). + third_party: + type: boolean + description: Lets clients that registered themselves into the app (client ID metadata documents + or dynamic registration) ask for this API and any of its scopes, each with the user's consent. + Off when left out. diff --git a/apps/api/api/openapi/endpoints/schemas/app-client-api.yaml b/apps/api/api/openapi/endpoints/schemas/app-client-api.yaml new file mode 100644 index 0000000000..6f7fe6fadd --- /dev/null +++ b/apps/api/api/openapi/endpoints/schemas/app-client-api.yaml @@ -0,0 +1,25 @@ +title: AppClientAPI +type: object +required: +- api +additionalProperties: false +properties: + api: + type: string + pattern: ^[a-z0-9][a-z0-9_-]*(/[a-z0-9][a-z0-9_-]*)?$ + maxLength: 129 + description: An API of this app by its slug, or an API of another app in the project as + `/`. + examples: + - orders + - billing/invoices + scopes: + type: array + uniqueItems: true + maxItems: 100 + items: + type: string + minLength: 1 + maxLength: 128 + description: The API's scopes the client may get. Leave it out for every scope the API defines. A + request for any other scope fails with `invalid_scope`. diff --git a/apps/api/api/openapi/endpoints/schemas/app-client-jwk.yaml b/apps/api/api/openapi/endpoints/schemas/app-client-jwk.yaml new file mode 100644 index 0000000000..a82405cb8c --- /dev/null +++ b/apps/api/api/openapi/endpoints/schemas/app-client-jwk.yaml @@ -0,0 +1,43 @@ +title: AppClientJWK +type: object +required: +- kty +additionalProperties: false +description: One public key (RFC 7517). Private members (`d`, `p`, `q`, `k` and the rest) are not + accepted. +properties: + kty: + type: string + enum: + - RSA + - EC + - OKP + kid: + type: string + minLength: 1 + maxLength: 256 + use: + type: string + enum: + - sig + alg: + type: string + enum: + - RS256 + - ES256 + - EdDSA + n: + type: string + description: RSA modulus. + e: + type: string + description: RSA exponent. + crv: + type: string + enum: + - P-256 + - Ed25519 + x: + type: string + y: + type: string diff --git a/apps/api/api/openapi/endpoints/schemas/app-client.json b/apps/api/api/openapi/endpoints/schemas/app-client.json new file mode 100644 index 0000000000..ff321ac502 --- /dev/null +++ b/apps/api/api/openapi/endpoints/schemas/app-client.json @@ -0,0 +1,241 @@ +{ + "$comment": "Code generated by scripts/generate-meta-schemas.ts; DO NOT EDIT.", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "AppClient", + "description": "A client of the app: a web app, a SPA, a native app, a CLI or a service. Its\n`grant_types` and redirect URIs are its OAuth config, and OpenID Connect is\nOAuth plus the `openid` scope, so one shape serves both. A confidential client\nwithout `grant_types` holds only credentials, and turns on client credentials\nlater without becoming a new principal.\n", + "type": "object", + "required": [ + "slug", + "type" + ], + "additionalProperties": false, + "properties": { + "slug": { + "type": "string", + "pattern": "^[a-z0-9][a-z0-9_-]*$", + "maxLength": 64, + "description": "Stable identifier of the client, unique among the app's clients and APIs. Other documents and the console name it as `/`.", + "examples": [ + "web", + "deploy" + ] + }, + "name": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Shown on the consent screen in place of the app's name. Optional." + }, + "client_id": { + "type": "string", + "pattern": "^[A-Za-z0-9._~@-]+$", + "minLength": 1, + "maxLength": 255, + "description": "The `client_id` the client presents. Leave it out and the server mints one the first time\nthe client is written. Set it to keep an id a client already has: one compiled into a desktop\nor mobile app, one a v4 or another identity provider issued, or one every project the release\nships to should share. Either way it is fixed for the life of the client: a revision that\nchanges it is refused, and a revision that leaves it out keeps it. Unique within the project,\nand never in a form the server mints (`client_` or `dcr_` followed by an id).\n", + "examples": [ + "OpenCloudDesktop", + "289374592837459283@shop" + ] + }, + "type": { + "type": "string", + "enum": [ + "public", + "confidential" + ], + "description": "`public` clients (SPAs, native apps, CLIs) hold no credential and prove themselves with PKCE alone, so they only act for the user who signed in. `confidential` clients hold credentials and authenticate with any of them: a secret (`client_secret_basic` or `client_secret_post`) or a key (`private_key_jwt`)." + }, + "secret": { + "type": "string", + "pattern": "^\\$\\{\\{ *[A-Z_][A-Z0-9_]* *\\}\\}$", + "description": "A secret of a client declared in the release, as a `${{ NAME }}` reference to a project\nvariable (ADR 062), never the value itself. The server reads the variable from the deployment\nwhen the client authenticates. Optional: a confidential client can hold secrets and keys\nwritten through the API instead, or beside it, which a deploy never removes. An app\nregistered through the API holds no reference.\n", + "examples": [ + "${{ SHOP_WEB_CLIENT_SECRET }}" + ] + }, + "jwks": { + "type": "object", + "required": [ + "keys" + ], + "additionalProperties": false, + "description": "Public keys the confidential client signs its `private_key_jwt` assertions with, as a JWK set. Public members only, so a private key can never be committed. Keys written through the API count too.", + "properties": { + "keys": { + "type": "array", + "minItems": 1, + "maxItems": 10, + "items": { + "$ref": "#/$defs/AppClientJwk" + } + } + } + }, + "grant_types": { + "type": "array", + "minItems": 1, + "uniqueItems": true, + "items": { + "type": "string", + "enum": [ + "authorization_code", + "refresh_token", + "client_credentials" + ] + }, + "description": "The grant types the client may use, with RFC 7591's name and values. `authorization_code`\nsigns a user in with PKCE (every client, OAuth 2.1); `refresh_token` keeps a grant alive;\n`client_credentials` lets a confidential client act as itself, so the tokens it gets have the\nclient as `sub`. A public client needs `authorization_code` and may not use\n`client_credentials`. A confidential client that leaves it out holds only credentials, and\nthen takes none of the fields below.\n" + }, + "redirect_uris": { + "type": "array", + "uniqueItems": true, + "maxItems": 50, + "items": { + "type": "string", + "minLength": 1, + "maxLength": 2048 + }, + "description": "Where the authorization endpoint may send the user back, matched exactly. A loopback\n`http://127.0.0.1`, `http://[::1]` or `http://localhost` URI matches on any port (RFC 8252\n§7.3), and a public client may use a private-use scheme such as `com.example.app:/callback`\n(RFC 8252 §7.1). Required with `authorization_code`, and only with it.\n", + "examples": [ + [ + "https://shop.example.com/callback" + ] + ] + }, + "post_logout_redirect_uris": { + "type": "array", + "uniqueItems": true, + "maxItems": 50, + "items": { + "type": "string", + "minLength": 1, + "maxLength": 2048 + }, + "description": "Where RP-initiated logout may send the user afterwards, matched exactly." + }, + "first_party": { + "type": "boolean", + "description": "A first-party client skips consent unless the request asks for it (ADR 082 §3). When left out, a client of an app declared in the release is first-party and a client of an app registered through the API is not." + }, + "consent": { + "type": "string", + "enum": [ + "skip", + "new_scopes", + "always" + ], + "description": "When the user is asked to consent. `skip` never asks unless the request says `prompt=consent`,\nand only a first-party client may skip. `new_scopes` asks for scopes the user has not consented\nto yet. `always` asks on every request. Defaults to `skip` for a first-party client and\n`new_scopes` for a third-party one.\n" + }, + "account_choice": { + "type": "boolean", + "description": "Lets the user pick an account, or sign in as someone else, when a session is already live (ADR 081 §11). A request asks for it with `prompt=select_account` either way." + }, + "id_token_signed_response_alg": { + "type": "string", + "enum": [ + "RS256", + "ES256" + ], + "description": "The algorithm the client's ID tokens are signed with. RS256 when left out (ADR 082 §7)." + }, + "apis": { + "type": "array", + "maxItems": 50, + "items": { + "$ref": "#/$defs/AppClientApi" + }, + "description": "The APIs the client may get access tokens for, its default first. A token is for one API\n(RFC 8707): the request names it with `resource`, and a request for an API not listed here\nfails with `invalid_target`.\n" + } + }, + "$defs": { + "AppClientJwk": { + "title": "AppClientJWK", + "type": "object", + "required": [ + "kty" + ], + "additionalProperties": false, + "description": "One public key (RFC 7517). Private members (`d`, `p`, `q`, `k` and the rest) are not accepted.", + "properties": { + "kty": { + "type": "string", + "enum": [ + "RSA", + "EC", + "OKP" + ] + }, + "kid": { + "type": "string", + "minLength": 1, + "maxLength": 256 + }, + "use": { + "type": "string", + "enum": [ + "sig" + ] + }, + "alg": { + "type": "string", + "enum": [ + "RS256", + "ES256", + "EdDSA" + ] + }, + "n": { + "type": "string", + "description": "RSA modulus." + }, + "e": { + "type": "string", + "description": "RSA exponent." + }, + "crv": { + "type": "string", + "enum": [ + "P-256", + "Ed25519" + ] + }, + "x": { + "type": "string" + }, + "y": { + "type": "string" + } + } + }, + "AppClientApi": { + "title": "AppClientAPI", + "type": "object", + "required": [ + "api" + ], + "additionalProperties": false, + "properties": { + "api": { + "type": "string", + "pattern": "^[a-z0-9][a-z0-9_-]*(/[a-z0-9][a-z0-9_-]*)?$", + "maxLength": 129, + "description": "An API of this app by its slug, or an API of another app in the project as `/`.", + "examples": [ + "orders", + "billing/invoices" + ] + }, + "scopes": { + "type": "array", + "uniqueItems": true, + "maxItems": 100, + "items": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "description": "The API's scopes the client may get. Leave it out for every scope the API defines. A request for any other scope fails with `invalid_scope`." + } + } + } + } +} diff --git a/apps/api/api/openapi/endpoints/schemas/app-client.yaml b/apps/api/api/openapi/endpoints/schemas/app-client.yaml new file mode 100644 index 0000000000..1ae92f2039 --- /dev/null +++ b/apps/api/api/openapi/endpoints/schemas/app-client.yaml @@ -0,0 +1,155 @@ +x-meta-schema: true +title: AppClient +description: | + A client of the app: a web app, a SPA, a native app, a CLI or a service. Its + `grant_types` and redirect URIs are its OAuth config, and OpenID Connect is + OAuth plus the `openid` scope, so one shape serves both. A confidential client + without `grant_types` holds only credentials, and turns on client credentials + later without becoming a new principal. +type: object +required: +- slug +- type +additionalProperties: false +properties: + slug: + type: string + pattern: ^[a-z0-9][a-z0-9_-]*$ + maxLength: 64 + description: Stable identifier of the client, unique among the app's clients and APIs. Other + documents and the console name it as `/`. + examples: + - web + - deploy + name: + type: string + minLength: 1 + maxLength: 256 + description: Shown on the consent screen in place of the app's name. Optional. + client_id: + type: string + pattern: ^[A-Za-z0-9._~@-]+$ + minLength: 1 + maxLength: 255 + description: | + The `client_id` the client presents. Leave it out and the server mints one the first time + the client is written. Set it to keep an id a client already has: one compiled into a desktop + or mobile app, one a v4 or another identity provider issued, or one every project the release + ships to should share. Either way it is fixed for the life of the client: a revision that + changes it is refused, and a revision that leaves it out keeps it. Unique within the project, + and never in a form the server mints (`client_` or `dcr_` followed by an id). + examples: + - OpenCloudDesktop + - 289374592837459283@shop + type: + type: string + enum: + - public + - confidential + description: '`public` clients (SPAs, native apps, CLIs) hold no credential and prove themselves + with PKCE alone, so they only act for the user who signed in. `confidential` clients hold + credentials and authenticate with any of them: a secret (`client_secret_basic` or + `client_secret_post`) or a key (`private_key_jwt`).' + secret: + type: string + pattern: ^\$\{\{ *[A-Z_][A-Z0-9_]* *\}\}$ + description: | + A secret of a client declared in the release, as a `${{ NAME }}` reference to a project + variable (ADR 062), never the value itself. The server reads the variable from the deployment + when the client authenticates. Optional: a confidential client can hold secrets and keys + written through the API instead, or beside it, which a deploy never removes. An app + registered through the API holds no reference. + examples: + - ${{ SHOP_WEB_CLIENT_SECRET }} + jwks: + type: object + required: + - keys + additionalProperties: false + description: Public keys the confidential client signs its `private_key_jwt` assertions with, as + a JWK set. Public members only, so a private key can never be committed. Keys written through + the API count too. + properties: + keys: + type: array + minItems: 1 + maxItems: 10 + items: + $ref: app-client-jwk.yaml + grant_types: + type: array + minItems: 1 + uniqueItems: true + items: + type: string + enum: + - authorization_code + - refresh_token + - client_credentials + description: | + The grant types the client may use, with RFC 7591's name and values. `authorization_code` + signs a user in with PKCE (every client, OAuth 2.1); `refresh_token` keeps a grant alive; + `client_credentials` lets a confidential client act as itself, so the tokens it gets have the + client as `sub`. A public client needs `authorization_code` and may not use + `client_credentials`. A confidential client that leaves it out holds only credentials, and + then takes none of the fields below. + redirect_uris: + type: array + uniqueItems: true + maxItems: 50 + items: + type: string + minLength: 1 + maxLength: 2048 + description: | + Where the authorization endpoint may send the user back, matched exactly. A loopback + `http://127.0.0.1`, `http://[::1]` or `http://localhost` URI matches on any port (RFC 8252 + §7.3), and a public client may use a private-use scheme such as `com.example.app:/callback` + (RFC 8252 §7.1). Required with `authorization_code`, and only with it. + examples: + - - https://shop.example.com/callback + post_logout_redirect_uris: + type: array + uniqueItems: true + maxItems: 50 + items: + type: string + minLength: 1 + maxLength: 2048 + description: Where RP-initiated logout may send the user afterwards, matched exactly. + first_party: + type: boolean + description: A first-party client skips consent unless the request asks for it (ADR 082 §3). When + left out, a client of an app declared in the release is first-party and a client of an app + registered through the API is not. + consent: + type: string + enum: + - skip + - new_scopes + - always + description: | + When the user is asked to consent. `skip` never asks unless the request says `prompt=consent`, + and only a first-party client may skip. `new_scopes` asks for scopes the user has not consented + to yet. `always` asks on every request. Defaults to `skip` for a first-party client and + `new_scopes` for a third-party one. + account_choice: + type: boolean + description: Lets the user pick an account, or sign in as someone else, when a session is already + live (ADR 081 §11). A request asks for it with `prompt=select_account` either way. + id_token_signed_response_alg: + type: string + enum: + - RS256 + - ES256 + description: The algorithm the client's ID tokens are signed with. RS256 when left out + (ADR 082 §7). + apis: + type: array + maxItems: 50 + items: + $ref: app-client-api.yaml + description: | + The APIs the client may get access tokens for, its default first. A token is for one API + (RFC 8707): the request names it with `resource`, and a request for an API not listed here + fails with `invalid_target`. diff --git a/apps/api/api/openapi/endpoints/schemas/app-registration.json b/apps/api/api/openapi/endpoints/schemas/app-registration.json new file mode 100644 index 0000000000..1550f8c93f --- /dev/null +++ b/apps/api/api/openapi/endpoints/schemas/app-registration.json @@ -0,0 +1,18 @@ +{ + "$comment": "Code generated by scripts/generate-meta-schemas.ts; DO NOT EDIT.", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "AppRegistration", + "description": "How clients may join the app on their own. A client that registers names no app: the app is the one\nwhose API its first authorization request names as `resource`, and the client may ask only for that\napp's `third_party` APIs, each with the user's consent. Both ways are off when left out, because open\nregistration is an abuse surface (ADR 078).\n", + "type": "object", + "additionalProperties": false, + "properties": { + "client_id_metadata_documents": { + "type": "boolean", + "description": "A client may use an HTTPS URL as its `client_id`, and the document behind it says who it is (ADR 082 §9). What MCP clients use." + }, + "dynamic": { + "type": "boolean", + "description": "A client may register through RFC 7591 dynamic client registration, for clients that register no other way." + } + } +} diff --git a/apps/api/api/openapi/endpoints/schemas/app-registration.yaml b/apps/api/api/openapi/endpoints/schemas/app-registration.yaml new file mode 100644 index 0000000000..d3d833664b --- /dev/null +++ b/apps/api/api/openapi/endpoints/schemas/app-registration.yaml @@ -0,0 +1,18 @@ +x-meta-schema: true +title: AppRegistration +description: | + How clients may join the app on their own. A client that registers names no app: the app is the one + whose API its first authorization request names as `resource`, and the client may ask only for that + app's `third_party` APIs, each with the user's consent. Both ways are off when left out, because open + registration is an abuse surface (ADR 078). +type: object +additionalProperties: false +properties: + client_id_metadata_documents: + type: boolean + description: A client may use an HTTPS URL as its `client_id`, and the document behind it says who + it is (ADR 082 §9). What MCP clients use. + dynamic: + type: boolean + description: A client may register through RFC 7591 dynamic client registration, for clients that + register no other way. diff --git a/apps/api/api/openapi/endpoints/schemas/app.json b/apps/api/api/openapi/endpoints/schemas/app.json new file mode 100644 index 0000000000..f0674f7cc8 --- /dev/null +++ b/apps/api/api/openapi/endpoints/schemas/app.json @@ -0,0 +1,80 @@ +{ + "$comment": "Code generated by scripts/generate-meta-schemas.ts; DO NOT EDIT.", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "App", + "description": "One piece of software that uses Zitadel, with every config it holds: its OAuth and OIDC clients,\nthe APIs it serves, and whether other clients may register into it. The same document is a file\nin the release (`.zitadel/apps/.json`) and the body of `POST /apps`.\n", + "type": "object", + "required": [ + "slug", + "name" + ], + "additionalProperties": false, + "properties": { + "$schema": { + "type": "string", + "minLength": 1, + "description": "Editor affordance: path or URL of this schema so editors validate and autocomplete the file (scaffolded app files point at `.zitadel/meta/app.json`). Ignored by the platform." + }, + "slug": { + "type": "string", + "pattern": "^[a-z0-9][a-z0-9_-]*$", + "maxLength": 64, + "description": "Stable identifier of the app, unique within the project and fixed for its life. Flows, branding and other apps name it.", + "examples": [ + "shop" + ] + }, + "name": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "The app's name, shown on the consent screen.", + "examples": [ + "Shop" + ] + }, + "logo_uri": { + "type": "string", + "pattern": "^https://", + "maxLength": 2048, + "description": "The app's logo, shown on the consent and account-choice screens. The display fields are those a client ID metadata document carries (RFC 7591), so the screens read both alike." + }, + "client_uri": { + "type": "string", + "pattern": "^https://", + "maxLength": 2048, + "description": "The app's home page, linked from the consent screen." + }, + "policy_uri": { + "type": "string", + "pattern": "^https://", + "maxLength": 2048, + "description": "The app's privacy policy, linked from the consent screen." + }, + "tos_uri": { + "type": "string", + "pattern": "^https://", + "maxLength": 2048, + "description": "The app's terms of service, linked from the consent screen." + }, + "clients": { + "type": "array", + "maxItems": 20, + "items": { + "$ref": "app-client.json" + }, + "description": "The app's OAuth and OIDC clients. A slug is unique among the app's clients and APIs." + }, + "apis": { + "type": "array", + "maxItems": 20, + "items": { + "$ref": "app-api.json" + }, + "description": "The APIs the app serves, MCP servers among them." + }, + "registration": { + "$ref": "app-registration.json" + } + } +} diff --git a/apps/api/api/openapi/endpoints/schemas/app.yaml b/apps/api/api/openapi/endpoints/schemas/app.yaml new file mode 100644 index 0000000000..6c83832326 --- /dev/null +++ b/apps/api/api/openapi/endpoints/schemas/app.yaml @@ -0,0 +1,67 @@ +x-meta-schema: true +title: App +description: | + One piece of software that uses Zitadel, with every config it holds: its OAuth and OIDC clients, + the APIs it serves, and whether other clients may register into it. The same document is a file + in the release (`.zitadel/apps/.json`) and the body of `POST /apps`. +type: object +required: +- slug +- name +additionalProperties: false +properties: + $schema: + type: string + minLength: 1 + description: 'Editor affordance: path or URL of this schema so editors validate and autocomplete the + file (scaffolded app files point at `.zitadel/meta/app.json`). Ignored by the platform.' + slug: + type: string + pattern: ^[a-z0-9][a-z0-9_-]*$ + maxLength: 64 + description: Stable identifier of the app, unique within the project and fixed for its life. + Flows, branding and other apps name it. + examples: + - shop + name: + type: string + minLength: 1 + maxLength: 256 + description: The app's name, shown on the consent screen. + examples: + - Shop + logo_uri: + type: string + pattern: ^https:// + maxLength: 2048 + description: The app's logo, shown on the consent and account-choice screens. The display fields + are those a client ID metadata document carries (RFC 7591), so the screens read both alike. + client_uri: + type: string + pattern: ^https:// + maxLength: 2048 + description: The app's home page, linked from the consent screen. + policy_uri: + type: string + pattern: ^https:// + maxLength: 2048 + description: The app's privacy policy, linked from the consent screen. + tos_uri: + type: string + pattern: ^https:// + maxLength: 2048 + description: The app's terms of service, linked from the consent screen. + clients: + type: array + maxItems: 20 + items: + $ref: app-client.yaml + description: The app's OAuth and OIDC clients. A slug is unique among the app's clients and APIs. + apis: + type: array + maxItems: 20 + items: + $ref: app-api.yaml + description: The APIs the app serves, MCP servers among them. + registration: + $ref: app-registration.yaml diff --git a/apps/api/api/openapi/openapi-spec.yaml b/apps/api/api/openapi/openapi-spec.yaml index a59e4a53d4..2572c03711 100644 --- a/apps/api/api/openapi/openapi-spec.yaml +++ b/apps/api/api/openapi/openapi-spec.yaml @@ -51,6 +51,14 @@ tags: revisioned connection document and referenced by its slug from user schemas and flow definitions. Create-or-revise, query, read by id, and revision reads. A slug resolves through the query. + - name: Apps + description: | + The software that uses Zitadel, each one document holding its OAuth and + OIDC clients, the APIs it serves and whether clients may register into + it. The developer's own apps are declared in the release; apps a product + creates for its customers are registered here. Create-or-revise, query, + read by id, revision reads, the credentials of their clients, and the + clients that registered themselves. - name: Policies description: | Operation policies (ADR 066): a project publishes, per guarded @@ -236,6 +244,24 @@ paths: $ref: endpoints/idps/by_id/revisions/methods.yaml /idps/revisions/{revision_id}: $ref: endpoints/idps/revisions/by_id/methods.yaml + /apps: + $ref: endpoints/apps/methods.yaml + /apps/query: + $ref: endpoints/apps/query/methods.yaml + /apps/{id}: + $ref: endpoints/apps/by_id/methods.yaml + /apps/{id}/revisions: + $ref: endpoints/apps/by_id/revisions/methods.yaml + /apps/{id}/clients/{client}/credentials: + $ref: endpoints/apps/by_id/clients/by_slug/credentials/methods.yaml + /apps/{id}/clients/{client}/credentials/{credential_id}: + $ref: endpoints/apps/by_id/clients/by_slug/credentials/by_id/methods.yaml + /apps/revisions/{revision_id}: + $ref: endpoints/apps/revisions/by_id/methods.yaml + /client_registrations/query: + $ref: endpoints/client_registrations/query/methods.yaml + /client_registrations/{id}: + $ref: endpoints/client_registrations/by_id/methods.yaml /policies: $ref: endpoints/policies/methods.yaml /policies/evaluate: @@ -280,6 +306,14 @@ paths: # One per domain event type, keyed by its event_type. gen_event_schemas writes # the files and fails until this list names exactly the domain's event types. webhooks: + app.created: + $ref: endpoints/events/webhooks/app-created.yaml + app.credential.added: + $ref: endpoints/events/webhooks/app-credential-added.yaml + app.credential.revoked: + $ref: endpoints/events/webhooks/app-credential-revoked.yaml + app.updated: + $ref: endpoints/events/webhooks/app-updated.yaml auth.attempt.created: $ref: endpoints/events/webhooks/auth-attempt-created.yaml auth.attempt.handed_off: @@ -308,6 +342,10 @@ webhooks: $ref: endpoints/events/webhooks/authz-revoked.yaml branding.created: $ref: endpoints/events/webhooks/branding-created.yaml + client_registration.created: + $ref: endpoints/events/webhooks/client_registration-created.yaml + client_registration.deleted: + $ref: endpoints/events/webhooks/client_registration-deleted.yaml deployment.created: $ref: endpoints/events/webhooks/deployment-created.yaml flowdef.created: diff --git a/apps/api/api/openapi/security/oauth2.yaml b/apps/api/api/openapi/security/oauth2.yaml index 9e5ea57d85..55818c4379 100644 --- a/apps/api/api/openapi/security/oauth2.yaml +++ b/apps/api/api/openapi/security/oauth2.yaml @@ -27,6 +27,8 @@ flows: policy.write: Permission to publish operation policies idp.read: Permission to read identity provider connections idp.write: Permission to create and revise identity provider connections + app.read: Permission to read apps + app.write: Permission to register and revise apps, manage their clients' credentials and delete client registrations release.read: Permission to read project configuration releases release.write: Permission to create and revoke project configuration releases deployment.read: Permission to read deployments @@ -77,6 +79,8 @@ flows: policy.write: Permission to publish operation policies idp.read: Permission to read identity provider connections idp.write: Permission to create and revise identity provider connections + app.read: Permission to read apps + app.write: Permission to register and revise apps, manage their clients' credentials and delete client registrations release.read: Permission to read project configuration releases release.write: Permission to create and revoke project configuration releases deployment.read: Permission to read deployments diff --git a/apps/api/cmd/server/server.go b/apps/api/cmd/server/server.go index 1f5e63e848..388aa044aa 100644 --- a/apps/api/cmd/server/server.go +++ b/apps/api/cmd/server/server.go @@ -313,6 +313,12 @@ func run(ctx context.Context, cfg Config, userFiles []string, applyMigrations bo brandingService := service.NewBrandingService(serviceDBPool) variableService := service.NewVariableService(serviceDBPool, keyService) idpConnectionService := service.NewIDPConnectionService(serviceDBPool, schemaValidator) + // Imported client secrets are hashes other systems wrote, such as v4's + // bcrypt; the deployment's hasher reads every format passwap knows. + appService := service.NewAppService(serviceDBPool, schemaValidator, passwordHasher) + // The authorization server keeps no consents for registered clients yet, + // so nothing holds a registration past its lifetime. + clientRegistrationService := service.NewClientRegistrationService(serviceDBPool, service.NoConsents{}) deploymentService := service.NewDeploymentService(serviceDBPool, variableService) eventService := service.NewEventService(serviceDBPool) // Operation policies (ADR 066). Every template is compiled and checked @@ -332,6 +338,7 @@ func run(ctx context.Context, cfg Config, userFiles []string, applyMigrations bo flowDefinitionSvc, brandingService, idpConnectionService, + appService, policyService, builtinBases, ) @@ -484,7 +491,7 @@ func run(ctx context.Context, cfg Config, userFiles []string, applyMigrations bo // Resolved, not the raw pin: in bootstrap mode project_id is empty // and an empty handler pin rejects every claim/complete session. cfg.Platform.ResolvedProjectID(), - ).WithPersonalTeamEnsurer(personalTeams).WithBuiltinSchemaBases(builtinBases).WithRuntimeResolver(runtimeResolver).WithPolicyService(policyService).WithReadinessCheck(pool), + ).WithPersonalTeamEnsurer(personalTeams).WithBuiltinSchemaBases(builtinBases).WithRuntimeResolver(runtimeResolver).WithPolicyService(policyService).WithAppService(appService).WithClientRegistrationService(clientRegistrationService).WithReadinessCheck(pool), // The same platform project the handler resolves: sessions homed there // can reach the platform operator path (ADR 075). api.NewSecurityHandler(tokenService).WithPlatformProject(cfg.Platform.ResolvedProjectID()), diff --git a/apps/api/internal/api/app.go b/apps/api/internal/api/app.go new file mode 100644 index 0000000000..7109ed6e7d --- /dev/null +++ b/apps/api/internal/api/app.go @@ -0,0 +1,305 @@ +package api + +import ( + "context" + "net/http" + "slices" + + api "github.com/zitadel/nextgen/internal/api/generated" + "github.com/zitadel/nextgen/internal/domain" + "github.com/zitadel/nextgen/internal/service" +) + +// CreateApp writes a registered app. The document is the request body as +// sent, not the decoded body written back out: the decoder would fill in +// nothing here, and storing what was sent keeps a release's file and an API +// write byte-comparable. +func (h *Handler) CreateApp(ctx context.Context, req *api.CreateAppRequest, params api.CreateAppParams) (api.CreateAppRes, error) { + if err := h.requireProjectAccess(ctx, string(params.ProjectID), appAccess, opWrite); err != nil { + return nil, err + } + document, err := req.App.MarshalJSON() + if err != nil { + return nil, domain.ErrInternal(err).WithMessage("failed to encode app") + } + result, err := h.appService.CreateOrRevise(ctx, string(params.ProjectID), document) + if err != nil { + return nil, err + } + resp, err := toAPIAppResponse(&result.AppView) + if err != nil { + return nil, err + } + for _, client := range result.Clients { + if secret, ok := result.Secrets[client.Slug]; ok { + resp.ClientSecrets = append(resp.ClientSecrets, api.AppClientSecret{ + Client: client.Slug, + CredentialID: secret.CredentialID, + Secret: secret.Secret, + }) + } + } + if result.Created { + created := api.CreateAppCreated(resp) + return &created, nil + } + revised := api.CreateAppOK(resp) + return &revised, nil +} + +// App reads resolve the path id through the resource scope index in the +// named project, so a grant scoped to one app reaches that app, its revision +// list and each of its revisions, as for connections. + +func (h *Handler) GetAppById(ctx context.Context, params api.GetAppByIdParams) (api.GetAppByIdRes, error) { + projectID, err := h.requireResourceAccessInProject(ctx, string(params.ProjectID), params.ID, appAccess, opRead) + if err != nil { + return nil, err + } + view, err := h.appService.Get(ctx, projectID, params.ID) + if err != nil { + return nil, err + } + resp, err := toAPIAppResponse(view) + if err != nil { + return nil, err + } + return &resp, nil +} + +func (h *Handler) GetAppRevisionById(ctx context.Context, params api.GetAppRevisionByIdParams) (api.GetAppRevisionByIdRes, error) { + projectID := string(params.ProjectID) + view, err := h.appService.GetRevision(ctx, projectID, params.RevisionID) + if err != nil { + // A miss answers as a revision of an app outside the caller's scope + // does, so an unknown id cannot be told from a hidden one. + if accessErr := h.requireTargetAccess(ctx, projectID, params.RevisionID, appAccess, opRead); accessErr != nil { + return nil, accessErr + } + return nil, err + } + if _, err := h.requireResourceAccessInProject(ctx, projectID, view.App.ID, appAccess, opRead); err != nil { + return nil, err + } + resp, err := toAPIAppResponse(view) + if err != nil { + return nil, err + } + return &resp, nil +} + +func (h *Handler) ListAppRevisions(ctx context.Context, params api.ListAppRevisionsParams) (api.ListAppRevisionsRes, error) { + projectID, err := h.requireResourceAccessInProject(ctx, string(params.ProjectID), params.ID, appAccess, opRead) + if err != nil { + return nil, err + } + // The check above allowed the caller on this app, and every row of the + // list is one of its revisions. + ctx = service.WithAuthzListSkipOnce(ctx) + result, err := h.appService.ListRevisions(ctx, service.ListAppRevisionsInput{ + ProjectID: projectID, + ID: params.ID, + Limit: int(params.Limit.Or(0)), + PageToken: string(params.PageToken.Or("")), + }) + if err != nil { + return nil, err + } + revisions, err := toAPIAppResponses(result.Items) + if err != nil { + return nil, err + } + resp := &api.ListAppRevisionsResponse{Revisions: revisions} + if result.NextPageToken != "" { + resp.NextPageToken = api.NewOptNilPageToken(api.PageToken(result.NextPageToken)) + } + return resp, nil +} + +func (h *Handler) QueryApps(ctx context.Context, req *api.QueryAppsRequest, params api.QueryAppsParams) (api.QueryAppsRes, error) { + ctx, _, err := h.requireProjectListAccess(ctx, string(params.ProjectID), appAccess, domain.ResourceKindApp) + if err != nil { + return nil, err + } + input := service.ListAppsInput{ + ProjectID: string(params.ProjectID), + Limit: int(req.Limit.Or(0)), + PageToken: string(req.PageToken.Or("")), + } + if sorting, ok := req.Sorting.Get(); ok { + input.Sorting = sortingToService(sorting.Field, sorting.Direction) + } + for _, filter := range req.Filter { + input.Filters = append(input.Filters, filterToService(filter.Field, filter.Operation, filter.Value)) + } + result, err := h.appService.List(ctx, input) + if err != nil { + return nil, err + } + apps, err := toAPIAppResponses(result.Items) + if err != nil { + return nil, err + } + resp := &api.QueryAppsResponse{Apps: apps} + if result.NextPageToken != "" { + resp.NextPageToken = api.NewOptNilPageToken(api.PageToken(result.NextPageToken)) + } + return resp, nil +} + +// Credentials belong to a client of an app, so they resolve the app id +// through the resource scope index as the app's other reads and writes do. A +// declared app's clients take them too. + +func (h *Handler) AddAppClientCredential(ctx context.Context, req *api.AddAppClientCredentialRequest, params api.AddAppClientCredentialParams) (api.AddAppClientCredentialRes, error) { + projectID, err := h.requireResourceAccessInProject(ctx, string(params.ProjectID), params.ID, appAccess, opWrite) + if err != nil { + return nil, err + } + input := service.AddAppClientCredentialInput{ + ProjectID: projectID, + AppID: params.ID, + ClientSlug: params.Client, + Name: req.Name, + Secret: req.Secret.Or(""), + Hash: req.Hash.Or(""), + } + if key, ok := req.PublicKey.Get(); ok { + if input.PublicKey, err = key.MarshalJSON(); err != nil { + return nil, domain.ErrInternal(err).WithMessage("failed to encode the public key") + } + } + if expiresAt, ok := req.ExpiresAt.Get(); ok { + input.ExpiresAt = &expiresAt + } + result, err := h.appService.AddClientCredential(ctx, input) + if err != nil { + return nil, err + } + resp := toAPIAppClientCredential(result.Credential, result.ClientID) + if result.Secret != "" { + resp.Secret = api.NewOptString(result.Secret) + } + return &resp, nil +} + +func (h *Handler) ListAppClientCredentials(ctx context.Context, params api.ListAppClientCredentialsParams) (api.ListAppClientCredentialsRes, error) { + projectID, err := h.requireResourceAccessInProject(ctx, string(params.ProjectID), params.ID, appAccess, opRead) + if err != nil { + return nil, err + } + result, err := h.appService.ListClientCredentials(ctx, projectID, params.ID, params.Client) + if err != nil { + return nil, err + } + resp := &api.ListAppClientCredentialsResponse{Credentials: make([]api.AppClientCredential, 0, len(result.Credentials))} + for _, credential := range result.Credentials { + resp.Credentials = append(resp.Credentials, toAPIAppClientCredential(credential, result.ClientID)) + } + return resp, nil +} + +func (h *Handler) RevokeAppClientCredential(ctx context.Context, params api.RevokeAppClientCredentialParams) (api.RevokeAppClientCredentialRes, error) { + projectID, err := h.requireResourceAccessInProject(ctx, string(params.ProjectID), params.ID, appAccess, opWrite) + if err != nil { + return nil, err + } + if err := h.appService.RevokeClientCredential(ctx, projectID, params.ID, params.Client, params.CredentialID); err != nil { + return nil, err + } + return &api.RevokeAppClientCredentialNoContent{}, nil +} + +/* ---------------- CONVERTERS ---------------- */ + +func toAPIAppClientCredential(credential *domain.AppClientCredential, clientID string) api.AppClientCredential { + resp := api.AppClientCredential{ + ID: credential.ID, + Name: credential.Name, + Kind: api.AppClientCredentialKind(credential.Kind), + ClientID: clientID, + KeyID: optAPIString(credential.KeyID), + CreatedAt: credential.CreatedAt, + } + if credential.ExpiresAt != nil { + resp.ExpiresAt = api.NewOptDateTime(*credential.ExpiresAt) + } + return resp +} + +func toAPIAppResponse(view *service.AppView) (api.AppResponse, error) { + entity := view.App + resp := api.AppResponse{ + ID: entity.ID, + RevisionID: entity.RevisionID, + Slug: entity.Slug, + Source: api.AppResponseSource(entity.Source), + Clients: make([]api.AppClientID, 0, len(view.Clients)), + CreatedAt: entity.CreatedAt, + UpdatedAt: entity.UpdatedAt, + } + if err := resp.Definition.UnmarshalJSON(entity.Document); err != nil { + return api.AppResponse{}, domain.ErrInternal(err).WithMessage("failed to decode stored app") + } + for _, client := range view.Clients { + resp.Clients = append(resp.Clients, api.AppClientID{Slug: client.Slug, ClientID: client.ClientID}) + } + return resp, nil +} + +func toAPIAppResponses(views []*service.AppView) ([]api.AppResponse, error) { + out := make([]api.AppResponse, 0, len(views)) + for _, view := range views { + resp, err := toAPIAppResponse(view) + if err != nil { + return nil, err + } + out = append(out, resp) + } + return out, nil +} + +// appErrorResponse maps the app error codes onto statuses. +func appErrorResponse(err domain.Error) *api.ErrorDetailsStatusCode { + switch { + case slices.Contains([]string{ + domain.ErrAppNotFound().Code, + domain.ErrAppClientNotFound().Code, + domain.ErrAppAPINotFound().Code, + }, err.Code): + return errorResponseWithStatusCode(http.StatusNotFound, err) + case slices.Contains([]string{ + domain.ErrAppInvalid(nil).Code, + domain.ErrAppFieldImmutable(nil).Code, + domain.ErrInvalidScope(nil).Code, + }, err.Code): + return errorResponseWithStatusCode(http.StatusBadRequest, err) + case err.Code == domain.ErrAppClientSecretInvalid().Code: + // The authorization server answers invalid_client itself; an API path + // that ever surfaced this would be refusing a credential. + return errorResponseWithStatusCode(http.StatusUnauthorized, err) + case slices.Contains([]string{ + domain.ErrClientRegistrationNotFound().Code, + domain.ErrAppCredentialNotFound().Code, + }, err.Code): + return errorResponseWithStatusCode(http.StatusNotFound, err) + case err.Code == domain.ErrClientRegistrationInvalid(nil).Code: + return errorResponseWithStatusCode(http.StatusBadRequest, err) + case err.Code == domain.ErrClientRegistrationOtherApp().Code: + // The authorization server answers invalid_target itself; an API + // path that ever surfaced this would be refusing the request. + return errorResponseWithStatusCode(http.StatusBadRequest, err) + case err.Code == domain.ErrAppPermissionDenied().Code: + return errorResponseWithStatusCode(http.StatusForbidden, err) + case slices.Contains([]string{ + domain.ErrAppDeclared().Code, + domain.ErrAppClientIDTaken(nil).Code, + domain.ErrAppIdentifierTaken(nil).Code, + domain.ErrAppRevisionConflict().Code, + domain.ErrAppCredentialTaken(nil).Code, + }, err.Code): + return errorResponseWithStatusCode(http.StatusConflict, err) + default: + return internalErrorResponse(err) + } +} diff --git a/apps/api/internal/api/authz.go b/apps/api/internal/api/authz.go index c06bf47d41..96d64feacc 100644 --- a/apps/api/internal/api/authz.go +++ b/apps/api/internal/api/authz.go @@ -167,6 +167,26 @@ var idpAccess = resourceAccess{ denied: domain.ErrIDPConnectionPermissionDenied, } +// appAccess guards the project's apps, like idpAccess: every route carries a +// project_id, the app-id reads and writes resolve the path id through RSI in +// that project, and create, query and the single revision read stay +// project-scoped, since revisions have no RSI row. +var appAccess = resourceAccess{ + kind: domain.ResourceKindApp, + readMiss: domain.ErrAppNotFound, + writeMiss: domain.ErrAppNotFound, + denied: domain.ErrAppPermissionDenied, +} + +// clientRegistrationAccess guards the clients that registered themselves. +// A registration belongs to the project, not to an app, and has no RSI row, +// so every route is project-scoped: an app-scoped grant does not reach it. +var clientRegistrationAccess = resourceAccess{ + readMiss: domain.ErrClientRegistrationNotFound, + writeMiss: domain.ErrClientRegistrationNotFound, + denied: domain.ErrAppPermissionDenied, +} + // deploymentAccess gates the record of what runs where (ADR 035, #532). // Same shape as releaseAccess: create and get are project-scoped — both carry // a project_id and the get filters its lookup by it — so no route resolves a diff --git a/apps/api/internal/api/client_registration.go b/apps/api/internal/api/client_registration.go new file mode 100644 index 0000000000..4dfea8c477 --- /dev/null +++ b/apps/api/internal/api/client_registration.go @@ -0,0 +1,87 @@ +package api + +import ( + "context" + + api "github.com/zitadel/nextgen/internal/api/generated" + "github.com/zitadel/nextgen/internal/domain" + "github.com/zitadel/nextgen/internal/service" +) + +// Clients register themselves at the authorization server's registration +// endpoint; this API only lists, reads and deletes what they registered. + +func (h *Handler) QueryClientRegistrations(ctx context.Context, req *api.QueryClientRegistrationsRequest, params api.QueryClientRegistrationsParams) (api.QueryClientRegistrationsRes, error) { + if err := h.requireProjectAccess(ctx, string(params.ProjectID), clientRegistrationAccess, opRead); err != nil { + return nil, err + } + input := service.ListClientRegistrationsInput{ + ProjectID: string(params.ProjectID), + Limit: int(req.Limit.Or(0)), + PageToken: string(req.PageToken.Or("")), + } + if sorting, ok := req.Sorting.Get(); ok { + input.Sorting = sortingToService(sorting.Field, sorting.Direction) + } + for _, filter := range req.Filter { + input.Filters = append(input.Filters, filterToService(filter.Field, filter.Operation, filter.Value)) + } + result, err := h.clientRegistrations.List(ctx, input) + if err != nil { + return nil, err + } + resp := &api.QueryClientRegistrationsResponse{ClientRegistrations: make([]api.ClientRegistrationResponse, 0, len(result.Items))} + for _, item := range result.Items { + resp.ClientRegistrations = append(resp.ClientRegistrations, toAPIClientRegistration(item)) + } + if result.NextPageToken != "" { + resp.NextPageToken = api.NewOptNilPageToken(api.PageToken(result.NextPageToken)) + } + return resp, nil +} + +func (h *Handler) GetClientRegistrationById(ctx context.Context, params api.GetClientRegistrationByIdParams) (api.GetClientRegistrationByIdRes, error) { + if err := h.requireProjectAccess(ctx, string(params.ProjectID), clientRegistrationAccess, opRead); err != nil { + return nil, err + } + registration, err := h.clientRegistrations.Get(ctx, string(params.ProjectID), params.ID) + if err != nil { + return nil, err + } + resp := toAPIClientRegistration(registration) + return &resp, nil +} + +func (h *Handler) DeleteClientRegistration(ctx context.Context, params api.DeleteClientRegistrationParams) (api.DeleteClientRegistrationRes, error) { + if err := h.requireProjectAccess(ctx, string(params.ProjectID), clientRegistrationAccess, opWrite); err != nil { + return nil, err + } + if err := h.clientRegistrations.Delete(ctx, string(params.ProjectID), params.ID); err != nil { + return nil, err + } + return &api.DeleteClientRegistrationNoContent{}, nil +} + +func toAPIClientRegistration(registration *domain.ClientRegistration) api.ClientRegistrationResponse { + m := registration.Metadata + resp := api.ClientRegistrationResponse{ + ID: registration.ID, + App: optAPIString(registration.AppSlug), + ClientName: optAPIString(m.ClientName), + ClientURI: optAPIString(m.ClientURI), + LogoURI: optAPIString(m.LogoURI), + PolicyURI: optAPIString(m.PolicyURI), + TosURI: optAPIString(m.TOSURI), + SoftwareID: optAPIString(m.SoftwareID), + SoftwareVersion: optAPIString(m.SoftwareVersion), + RedirectUris: m.RedirectURIs, + GrantTypes: make([]api.ClientRegistrationResponseGrantTypesItem, 0, len(m.GrantTypes)), + TokenEndpointAuthMethod: api.ClientRegistrationResponseTokenEndpointAuthMethod(m.AuthMethod), + CreatedAt: registration.CreatedAt, + ExpiresAt: registration.ExpiresAt, + } + for _, grant := range m.GrantTypes { + resp.GrantTypes = append(resp.GrantTypes, api.ClientRegistrationResponseGrantTypesItem(grant)) + } + return resp +} diff --git a/apps/api/internal/api/error_handler.go b/apps/api/internal/api/error_handler.go index 69c9d342be..d5ff8ebf95 100644 --- a/apps/api/internal/api/error_handler.go +++ b/apps/api/internal/api/error_handler.go @@ -132,6 +132,8 @@ func errorResponse(err error) *api.ErrorDetailsStatusCode { return releaseErrorResponse(e) case strings.HasPrefix(e.Code, domain.PrefixIDPConnection.ErrorCodePrefix("")): return idpErrorResponse(e) + case strings.HasPrefix(e.Code, domain.PrefixApp.ErrorCodePrefix("")): + return appErrorResponse(e) case strings.HasPrefix(e.Code, domain.PrefixDeployment.ErrorCodePrefix("")): return deploymentErrorResponse(e) case strings.HasPrefix(e.Code, domain.PrefixOrigin.ErrorCodePrefix("")): diff --git a/apps/api/internal/api/generated/oas_cfg_gen.go b/apps/api/internal/api/generated/oas_cfg_gen.go index a7e0f7d722..1998fe300f 100644 --- a/apps/api/internal/api/generated/oas_cfg_gen.go +++ b/apps/api/internal/api/generated/oas_cfg_gen.go @@ -20,21 +20,27 @@ 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://": ogenregex.MustCompile("^https://"), "^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/apps/api/internal/api/generated/oas_defaults_gen.go b/apps/api/internal/api/generated/oas_defaults_gen.go index 24795b7c83..1bd9ef990f 100644 --- a/apps/api/internal/api/generated/oas_defaults_gen.go +++ b/apps/api/internal/api/generated/oas_defaults_gen.go @@ -94,6 +94,22 @@ func (s *PasswordSetEvaluateFacts) setDefaults() { } } +// setDefaults set default value of fields. +func (s *QueryAppsRequest) setDefaults() { + { + val := int(20) + s.Limit.SetTo(Limit(val)) + } +} + +// setDefaults set default value of fields. +func (s *QueryClientRegistrationsRequest) setDefaults() { + { + val := int(20) + s.Limit.SetTo(Limit(val)) + } +} + // setDefaults set default value of fields. func (s *QueryGrantsRequest) setDefaults() { { diff --git a/apps/api/internal/api/generated/oas_handlers_gen.go b/apps/api/internal/api/generated/oas_handlers_gen.go index ddcb879a5c..dc767c148f 100644 --- a/apps/api/internal/api/generated/oas_handlers_gen.go +++ b/apps/api/internal/api/generated/oas_handlers_gen.go @@ -33,6 +33,239 @@ func (c *codeRecorder) Unwrap() http.ResponseWriter { return c.ResponseWriter } +// handleAddAppClientCredentialRequest handles addAppClientCredential operation. +// +// Adds a named credential to a confidential client: a secret the server +// generates and shows once, an imported secret or hash, or a public key. +// The app may be declared in the release or registered through the API, and +// a deploy never removes a credential written here. A public client holds +// no credential, and a request for one is refused with `app.invalid`. +// Emits `app.credential.added`. +// +// POST /apps/{id}/clients/{client}/credentials +func (s *Server) handleAddAppClientCredentialRequest(args [2]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("addAppClientCredential"), + semconv.HTTPRequestMethodKey.String("POST"), + semconv.HTTPRouteKey.String("/apps/{id}/clients/{client}/credentials"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), AddAppClientCredentialOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(codeAttr) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: AddAppClientCredentialOperation, + ID: "addAppClientCredential", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securityOAuth2(ctx, AddAppClientCredentialOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "OAuth2", + Err: err, + } + defer recordError("Security:OAuth2", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + { + sctx, ok, err := s.securitySessionCookie(ctx, AddAppClientCredentialOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + defer recordError("Security:SessionCookie", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if ok { + satisfied[0] |= 1 << 1 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000001}, + {0b00000010}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + defer recordError("Security", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + } + params, err := decodeAddAppClientCredentialParams(args, argsEscaped, r) + if err != nil { + err = &ogenerrors.DecodeParamsError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeParams", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + + var rawBody []byte + request, rawBody, close, err := s.decodeAddAppClientCredentialRequest(r) + if err != nil { + err = &ogenerrors.DecodeRequestError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeRequest", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + defer func() { + if err := close(); err != nil { + recordError("CloseRequest", err) + } + }() + + var response AddAppClientCredentialRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: AddAppClientCredentialOperation, + OperationSummary: "Add a credential to an app's client", + OperationID: "addAppClientCredential", + Body: request, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "project_id", + In: "query", + }: params.ProjectID, + { + Name: "id", + In: "path", + }: params.ID, + { + Name: "client", + In: "path", + }: params.Client, + }, + Raw: r, + } + + type ( + Request = *AddAppClientCredentialRequest + Params = AddAppClientCredentialParams + Response = AddAppClientCredentialRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackAddAppClientCredentialParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.AddAppClientCredential(ctx, request, params) + return response, err + }, + ) + } else { + response, err = s.h.AddAppClientCredential(ctx, request, params) + } + if err != nil { + defer recordError("Internal", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + + if err := encodeAddAppClientCredentialResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + // handleAddOriginRequest handles addOrigin operation. // // Adds one `{pattern, kind}` to the project's origins. A primary pattern @@ -897,33 +1130,41 @@ func (s *Server) handleCompleteClaimRequest(args [1]string, argsEscaped bool, w } } -// handleCreateAuthAttemptRequest handles createAuthAttempt operation. +// handleCreateAppRequest handles 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 +// for each new confidential client that holds no key, a generated secret, +// shown once, as its credential named `initial`. +// 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 credentials are written through the API, never a +// `${{ NAME }}` reference. A refused document stores nothing. // -// POST /auth_attempts -func (s *Server) handleCreateAuthAttemptRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { +// POST /apps +func (s *Server) handleCreateAppRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { statusWriter := &codeRecorder{ResponseWriter: w} w = statusWriter otelAttrs := []attribute.KeyValue{ - otelogen.OperationID("createAuthAttempt"), + otelogen.OperationID("createApp"), semconv.HTTPRequestMethodKey.String("POST"), - semconv.HTTPRouteKey.String("/auth_attempts"), + semconv.HTTPRouteKey.String("/apps"), } // Add attributes from config. otelAttrs = append(otelAttrs, s.cfg.Attributes...) // Start a span for this request. - ctx, span := s.cfg.Tracer.Start(r.Context(), CreateAuthAttemptOperation, + ctx, span := s.cfg.Tracer.Start(r.Context(), CreateAppOperation, trace.WithAttributes(otelAttrs...), serverSpanKind, ) @@ -978,15 +1219,15 @@ func (s *Server) handleCreateAuthAttemptRequest(args [0]string, argsEscaped bool } err error opErrContext = ogenerrors.OperationContext{ - Name: CreateAuthAttemptOperation, - ID: "createAuthAttempt", + Name: CreateAppOperation, + ID: "createApp", } ) { type bitset = [1]uint8 var satisfied bitset { - sctx, ok, err := s.securityOAuth2(ctx, CreateAuthAttemptOperation, r) + sctx, ok, err := s.securityOAuth2(ctx, CreateAppOperation, r) if err != nil { err = &ogenerrors.SecurityError{ OperationContext: opErrContext, @@ -1026,9 +1267,19 @@ func (s *Server) handleCreateAuthAttemptRequest(args [0]string, argsEscaped bool return } } + params, err := decodeCreateAppParams(args, argsEscaped, r) + if err != nil { + err = &ogenerrors.DecodeParamsError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeParams", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } var rawBody []byte - request, rawBody, close, err := s.decodeCreateAuthAttemptRequest(r) + request, rawBody, close, err := s.decodeCreateAppRequest(r) if err != nil { err = &ogenerrors.DecodeRequestError{ OperationContext: opErrContext, @@ -1044,23 +1295,28 @@ func (s *Server) handleCreateAuthAttemptRequest(args [0]string, argsEscaped bool } }() - var response CreateAuthAttemptRes + var response CreateAppRes if m := s.cfg.Middleware; m != nil { mreq := middleware.Request{ Context: ctx, - OperationName: CreateAuthAttemptOperation, - OperationSummary: "Create a new authentication attempt", - OperationID: "createAuthAttempt", + OperationName: CreateAppOperation, + OperationSummary: "Create or revise an app", + OperationID: "createApp", Body: request, RawBody: rawBody, - Params: middleware.Parameters{}, - Raw: r, + Params: middleware.Parameters{ + { + Name: "project_id", + In: "query", + }: params.ProjectID, + }, + Raw: r, } type ( - Request = *CreateAuthAttemptRequest - Params = struct{} - Response = CreateAuthAttemptRes + Request = *CreateAppRequest + Params = CreateAppParams + Response = CreateAppRes ) response, err = middleware.HookMiddleware[ Request, @@ -1069,14 +1325,14 @@ func (s *Server) handleCreateAuthAttemptRequest(args [0]string, argsEscaped bool ]( m, mreq, - nil, + unpackCreateAppParams, func(ctx context.Context, request Request, params Params) (response Response, err error) { - response, err = s.h.CreateAuthAttempt(ctx, request) + response, err = s.h.CreateApp(ctx, request, params) return response, err }, ) } else { - response, err = s.h.CreateAuthAttempt(ctx, request) + response, err = s.h.CreateApp(ctx, request, params) } if err != nil { defer recordError("Internal", err) @@ -1084,7 +1340,7 @@ func (s *Server) handleCreateAuthAttemptRequest(args [0]string, argsEscaped bool return } - if err := encodeCreateAuthAttemptResponse(response, w, span); err != nil { + if err := encodeCreateAppResponse(response, w, span); err != nil { defer recordError("EncodeResponse", err) if !errors.Is(err, ht.ErrInternalServerErrorResponse) { s.cfg.ErrorHandler(ctx, w, r, err) @@ -1093,11 +1349,207 @@ func (s *Server) handleCreateAuthAttemptRequest(args [0]string, argsEscaped bool } } -// handleCreateBrandingRequest handles createBranding operation. +// handleCreateAuthAttemptRequest handles 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. +// 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. +// +// POST /auth_attempts +func (s *Server) handleCreateAuthAttemptRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("createAuthAttempt"), + semconv.HTTPRequestMethodKey.String("POST"), + semconv.HTTPRouteKey.String("/auth_attempts"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), CreateAuthAttemptOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(codeAttr) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: CreateAuthAttemptOperation, + ID: "createAuthAttempt", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securityOAuth2(ctx, CreateAuthAttemptOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "OAuth2", + Err: err, + } + defer recordError("Security:OAuth2", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + + 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 { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + defer recordError("Security", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + } + + var rawBody []byte + request, rawBody, close, err := s.decodeCreateAuthAttemptRequest(r) + if err != nil { + err = &ogenerrors.DecodeRequestError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeRequest", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + defer func() { + if err := close(); err != nil { + recordError("CloseRequest", err) + } + }() + + var response CreateAuthAttemptRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: CreateAuthAttemptOperation, + OperationSummary: "Create a new authentication attempt", + OperationID: "createAuthAttempt", + Body: request, + RawBody: rawBody, + Params: middleware.Parameters{}, + Raw: r, + } + + type ( + Request = *CreateAuthAttemptRequest + Params = struct{} + Response = CreateAuthAttemptRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + nil, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.CreateAuthAttempt(ctx, request) + return response, err + }, + ) + } else { + response, err = s.h.CreateAuthAttempt(ctx, request) + } + if err != nil { + defer recordError("Internal", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + + if err := encodeCreateAuthAttemptResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + +// handleCreateBrandingRequest handles createBranding 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 `