# Copyright (C) 2026 Alberto Irurueta Carro (alberto@irurueta.com)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Contract of the REST API of the authorization server (version 1). This file is the source of truth: the Spring
# interfaces and DTOs implemented by the controllers of auth-server/api/web are generated from it by
# openapi-generator, and OpenApiDriftIT fails when the running application serves an operation or a status code
# this file does not declare. The OAuth 2.1 / OpenID Connect protocol endpoints are defined by their specifications
# and described by the discovery document, so they are not part of this contract.
openapi: 3.1.0
info:
  title: Irurueta Auth Server API
  description: REST endpoints of the example OAuth 2.1 / OpenID Connect authorization server.
  version: 1.0.0
  license:
    name: Apache License 2.0
    url: https://www.apache.org/licenses/LICENSE-2.0.txt
servers:
  - url: http://localhost:9000
    description: Local development instance (the dev profile).
tags:
  - name: Account
    description: Self-service account management
  - name: Totp
    description: Enrolment and removal of the authenticator app (TOTP) of the authenticated account
  - name: Recovery codes
    description: Single-use recovery codes that replace the authenticator app code
  - name: Trusted devices
    description: Browsers on which the second factor is skipped for a limited time
  - name: Passkeys
    description: WebAuthn credentials of the authenticated account
  - name: Phone
    description: The phone number of the authenticated account, used to receive one-time codes by SMS
  - name: Identities
    description: Identities of external providers (Google, Microsoft, Apple, GitHub) linked to the authenticated account
  - name: Certificates
    description: X.509 client certificates bound to the authenticated account, to sign in with
  - name: Signing keys
    description: Administration of the signing keys
  - name: Clients
    description: Administration of the registered clients
security:
  - bearer: [ ]
paths:
  # tag::account-api[]
  /api/account/register:
    post:
      tags: [ Account ]
      operationId: register
      summary: Registers an account
      description: >-
        The answer is the same whether or not the e-mail address or the username is already taken. Rate limited per
        client address and per e-mail address.
      security: [ ]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/RegisterRequest'
      responses:
        '202':
          description: Registration accepted; an e-mail is sent
        '400':
          description: Invalid request or rejected password
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
        '429':
          $ref: '#/components/responses/TooManyRequests'
        '503':
          description: The e-mail could not be sent; nothing was registered
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
  /api/account/verify:
    get:
      tags: [ Account ]
      operationId: verify
      summary: Verifies an e-mail address
      description: A verification link works once. Rate limited per client address.
      security: [ ]
      parameters:
        - name: token
          in: query
          required: true
          description: Verification token received by e-mail.
          schema:
            type: string
      responses:
        '204':
          description: E-mail address verified
        '400':
          description: The token is invalid, expired or already used
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
        '429':
          $ref: '#/components/responses/TooManyRequests'
  /api/account/password:
    post:
      tags: [ Account ]
      operationId: changePassword
      summary: Changes the password of the authenticated account
      description: Requires a bearer token issued by this server.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ChangePasswordRequest'
      responses:
        '204':
          description: Password changed
        '400':
          description: Wrong current password or rejected new password
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
        '401':
          $ref: '#/components/responses/Unauthorized'
  /api/account/password/reset-request:
    post:
      tags: [ Account ]
      operationId: requestPasswordReset
      summary: Requests a password reset link
      description: >-
        The answer is the same whether or not the e-mail address belongs to an account; only a registered address
        receives a message. Rate limited per client address and per e-mail address.
      security: [ ]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/PasswordResetRequest'
      responses:
        '202':
          description: Request accepted; a registered address is sent a link
        '400':
          description: Invalid request
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
        '429':
          $ref: '#/components/responses/TooManyRequests'
  /api/account/password/reset:
    post:
      tags: [ Account ]
      operationId: resetPassword
      summary: Resets a forgotten password
      description: A rejected password does not use up the token. Rate limited per client address.
      security: [ ]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ResetPasswordRequest'
      responses:
        '204':
          description: Password reset
        '400':
          description: Invalid token or rejected password
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
        '429':
          $ref: '#/components/responses/TooManyRequests'
  # end::account-api[]
  # tag::totp-api-contract[]
  /api/account/totp:
    post:
      tags: [ Totp ]
      operationId: enrollTotp
      summary: Starts the enrolment of an authenticator app
      description: >-
        Generates a new shared secret for the authenticated account and answers the otpauth URI and its QR code. The
        enrolment is pending until it is confirmed with a code; starting it again replaces a pending secret. Requires
        a bearer token issued by this server.
      responses:
        '200':
          description: Enrolment started
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TotpEnrollmentResponse'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '409':
          description: An authenticator app is already enabled for the account
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
    delete:
      tags: [ Totp ]
      operationId: disableTotp
      summary: Disables the authenticator app
      description: >-
        Removes the authenticator app and the recovery codes of the authenticated account and revokes every trusted
        device of the account. Disabling a factor that is not enabled succeeds as well. While the account has a
        confirmed second factor, the bearer token must show a recent multi-factor sign-in (step-up, RFC 9470).
      responses:
        '204':
          description: The authenticator app is disabled
        '401':
          $ref: '#/components/responses/StepUpRequired'
  /api/account/totp/confirm:
    post:
      tags: [ Totp ]
      operationId: confirmTotp
      summary: Confirms the enrolment of the authenticator app
      description: >-
        Checks a code produced by the authenticator app against the pending secret, enables the factor and generates
        a fresh set of recovery codes, shown only in this answer.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ConfirmTotpRequest'
      responses:
        '200':
          description: The authenticator app is enabled
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RecoveryCodesResponse'
        '400':
          description: Invalid request, no enrolment in progress or wrong code
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '409':
          description: The authenticator app is already enabled
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
  /api/account/recovery-codes:
    post:
      tags: [ Recovery codes ]
      operationId: generateRecoveryCodes
      summary: Generates a new set of recovery codes
      description: >-
        Replaces every existing recovery code of the authenticated account with a new set, shown only in this answer.
        Recovery codes only stand in for a second factor, so the account must have a confirmed authenticator app;
        the bearer token must also show a recent multi-factor sign-in (step-up, RFC 9470).
      responses:
        '200':
          description: The new recovery codes
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RecoveryCodesResponse'
        '400':
          description: The account has no confirmed authenticator app (problem type urn:problem:mfa:totp-not-enrolled)
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
        '401':
          $ref: '#/components/responses/StepUpRequired'
  /api/account/trusted-devices:
    get:
      tags: [ Trusted devices ]
      operationId: listTrustedDevices
      summary: Lists the trusted devices
      description: Lists the devices of the authenticated account that are still trusted, never anything of another account.
      responses:
        '200':
          description: The trusted devices
          content:
            application/json:
              schema:
                type: array
                description: The trusted devices, possibly empty.
                items:
                  $ref: '#/components/schemas/TrustedDeviceResponse'
        '401':
          $ref: '#/components/responses/Unauthorized'
  /api/account/trusted-devices/{id}:
    delete:
      tags: [ Trusted devices ]
      operationId: revokeTrustedDevice
      summary: Revokes a trusted device
      description: >-
        The device is asked for the second factor again. A device of another account is never touched and is answered
        as not found. While the account has a confirmed second factor, the bearer token must show a recent
        multi-factor sign-in (step-up, RFC 9470).
      parameters:
        - name: id
          in: path
          required: true
          description: Identifier of the trusted device.
          schema:
            type: string
            format: uuid
      responses:
        '204':
          description: Device revoked
        '401':
          $ref: '#/components/responses/StepUpRequired'
        '404':
          description: No such trusted device for the authenticated account
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
  # tag::passkeys-api-contract[]
  /api/account/passkeys:
    get:
      tags: [ Passkeys ]
      operationId: listPasskeys
      summary: Lists the passkeys
      description: Lists the passkeys registered by the authenticated account, never anything of another account.
      responses:
        '200':
          description: The passkeys
          content:
            application/json:
              schema:
                type: array
                description: The passkeys, possibly empty.
                items:
                  $ref: '#/components/schemas/Passkey'
        '401':
          $ref: '#/components/responses/Unauthorized'
  /api/account/passkeys/{id}:
    patch:
      tags: [ Passkeys ]
      operationId: renamePasskey
      summary: Renames a passkey
      description: >-
        Changes the label that identifies the passkey in the list. A passkey of another account is never touched and
        is answered as not found.
      parameters:
        - $ref: '#/components/parameters/PasskeyId'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/RenamePasskeyRequest'
      responses:
        '200':
          description: The renamed passkey
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Passkey'
        '400':
          description: >-
            The identifier is not unpadded base64url (problem type invalid-parameter) or the label is blank or too
            long once trimmed (problem type invalid-label)
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          description: No such passkey for the authenticated account
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
    delete:
      tags: [ Passkeys ]
      operationId: deletePasskey
      summary: Deletes a passkey
      description: >-
        The passkey can no longer be used to sign in. A passkey of another account is never touched and is answered
        as not found. While the account has a confirmed second factor, the bearer token must show a recent
        multi-factor sign-in (step-up, RFC 9470). When the deletion leaves the account without any confirmed second
        factor, every trusted device of the account is revoked too.
      parameters:
        - $ref: '#/components/parameters/PasskeyId'
      responses:
        '204':
          description: Passkey deleted
        '400':
          description: The identifier is not unpadded base64url (problem type invalid-parameter)
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
        '401':
          $ref: '#/components/responses/StepUpRequired'
        '404':
          description: No such passkey for the authenticated account
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
  # end::passkeys-api-contract[]
  # end::totp-api-contract[]
  # tag::phone-api-contract[]
  /api/account/phone:
    get:
      tags: [ Phone ]
      operationId: getPhone
      summary: Gets the verified phone number
      description: >-
        Answers the verified phone number of the authenticated account, masked so that only its last digits are
        shown. A number whose verification is still pending is not reported, and neither is any number of another
        account.
      responses:
        '200':
          description: The verified phone number
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PhoneResponse'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          description: The account has no verified phone number (problem type urn:problem:phone:phone-not-found)
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
    put:
      tags: [ Phone ]
      operationId: startPhoneEnrolment
      summary: Starts the enrolment of a phone number
      description: >-
        Normalises the number to E.164 (a number without a country prefix is read in the default region of the
        server), checks that SMS messages may be sent to its country and sends a verification code by SMS. The
        enrolment is pending until it is confirmed with the code on POST /api/account/phone/verify; starting it again
        replaces the pending one. The answer is the same whether or not the number already belongs to another
        account, and in that case no message is sent, so the endpoint never reveals which numbers are registered.
        The message is sent after the answer, so a slow or failing SMS gateway never shows in it. Limited per client
        address and per account. While the account has a confirmed second factor (the new number would replace the
        verified one), the bearer token must show a recent multi-factor sign-in (step-up, RFC 9470).
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/StartPhoneEnrolmentRequest'
      responses:
        '202':
          description: The verification code was requested
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PhoneEnrolmentResponse'
        '400':
          description: >-
            The request is invalid, the number is not a valid phone number (problem type
            urn:problem:phone:invalid-phone) or SMS messages are not sent to its country (problem type
            urn:problem:phone:country-not-allowed)
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
        '401':
          $ref: '#/components/responses/StepUpRequired'
        '429':
          $ref: '#/components/responses/TooManyRequests'
    delete:
      tags: [ Phone ]
      operationId: removePhone
      summary: Removes the phone number
      description: >-
        Removes the verified phone number and any pending verification of the authenticated account, so SMS codes can
        no longer be used, and audits the removal; when the account is then left without any confirmed second factor,
        every trusted device of the account is revoked. Removing a phone that is not set succeeds as well. While the account has a confirmed second
        factor, the bearer token must show a recent multi-factor sign-in (step-up, RFC 9470).
      responses:
        '204':
          description: The phone number is removed
        '401':
          $ref: '#/components/responses/StepUpRequired'
  /api/account/phone/verify:
    post:
      tags: [ Phone ]
      operationId: verifyPhone
      summary: Confirms the phone number with the code sent by SMS
      description: >-
        Checks the code against the pending verification of the authenticated account. A correct code makes the
        number the verified phone of the account; a wrong one counts as an attempt, and the verification is discarded
        after too many. A number that replaces another verified one is audited as the removal of a second factor and
        revokes every trusted device of the account. Limited per client address and per account.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/VerifyPhoneRequest'
      responses:
        '200':
          description: The phone number is verified
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PhoneResponse'
        '400':
          description: >-
            The request is invalid, or the code is wrong, expired or there is no verification in progress (problem
            type urn:problem:phone:invalid-code)
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '429':
          $ref: '#/components/responses/TooManyRequests'
  # end::phone-api-contract[]
  # tag::clients-api[]
  # tag::identities-api-contract[]
  /api/account/identities:
    get:
      tags: [ Identities ]
      operationId: listIdentities
      summary: Lists the linked identities
      description: >-
        Lists the identities of external providers linked to the authenticated account, never anything of another
        account. The subject the provider assigned to the user is not disclosed.
      responses:
        '200':
          description: The linked identities
          content:
            application/json:
              schema:
                type: array
                description: The linked identities, possibly empty.
                items:
                  $ref: '#/components/schemas/Identity'
        '401':
          $ref: '#/components/responses/Unauthorized'
  /api/account/identities/{id}:
    delete:
      tags: [ Identities ]
      operationId: unlinkIdentity
      summary: Unlinks an identity
      description: >-
        The identity can no longer be used to sign in. An identity of another account is never touched and is answered
        as not found. While the account has a confirmed second factor, the bearer token must show a recent
        multi-factor sign-in (step-up, RFC 9470). The last way to sign in to the account is never removed: an identity
        is refused while the account has neither a password nor another linked identity or credential.
      parameters:
        - name: id
          in: path
          required: true
          description: Identifier of the linked identity.
          schema:
            type: string
            format: uuid
      responses:
        '204':
          description: Identity unlinked
        '401':
          $ref: '#/components/responses/StepUpRequired'
        '404':
          description: No such linked identity for the authenticated account
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
        '409':
          description: >-
            The identity is the last way to sign in to the account (problem type urn:problem:identity:last-sign-in-method)
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
  # end::identities-api-contract[]
  # tag::certificates-api-contract[]
  /api/account/certificates:
    get:
      tags: [ Certificates ]
      operationId: listCertificates
      summary: Lists the bound certificates
      description: >-
        Lists the X.509 client certificates bound to the authenticated account, oldest first, never anything of another
        account. A bound certificate signs the account in on POST /login/x509 when authserver.x509.enabled is true.
      responses:
        '200':
          description: The bound certificates
          content:
            application/json:
              schema:
                type: array
                description: The bound certificates, possibly empty.
                items:
                  $ref: '#/components/schemas/Certificate'
        '401':
          $ref: '#/components/responses/Unauthorized'
    post:
      tags: [ Certificates ]
      operationId: bindCertificate
      summary: Binds a certificate
      description: >-
        Binds the X.509 certificate of the request, in PEM form, to the authenticated account, so it can sign in with
        it. Only the public certificate is sent, never its private key. The certificate is recognised by the SHA-256
        fingerprint of its DER form, never by its subject; it must be within its validity period. Binding a certificate
        the account already has answers the existing binding. While the account has a confirmed second factor, the
        bearer token must show a recent multi-factor sign-in (step-up, RFC 9470).
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/BindCertificateRequest'
      responses:
        '201':
          description: The certificate is bound (or was already bound to the account)
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Certificate'
        '400':
          description: >-
            The request is invalid, or the value is not a single PEM X.509 certificate within its validity period
            (problem type urn:problem:certificate:invalid-certificate)
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
        '401':
          $ref: '#/components/responses/StepUpRequired'
        '409':
          description: >-
            The certificate is bound to another account (problem type urn:problem:certificate:certificate-already-bound)
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
  /api/account/certificates/{id}:
    delete:
      tags: [ Certificates ]
      operationId: unbindCertificate
      summary: Unbinds a certificate
      description: >-
        The certificate can no longer be used to sign in. A certificate of another account is never touched and is
        answered as not found. While the account has a confirmed second factor, the bearer token must show a recent
        multi-factor sign-in (step-up, RFC 9470). The last way to sign in to the account is never removed: a
        certificate is refused while the account has neither a password nor a linked identity, a passkey or another
        certificate.
      parameters:
        - name: id
          in: path
          required: true
          description: Identifier of the binding.
          schema:
            type: string
            format: uuid
      responses:
        '204':
          description: Certificate unbound
        '401':
          $ref: '#/components/responses/StepUpRequired'
        '404':
          description: >-
            No such certificate for the authenticated account (problem type
            urn:problem:certificate:certificate-not-found)
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
        '409':
          description: >-
            The certificate is the last way to sign in to the account (problem type
            urn:problem:certificate:last-sign-in-method)
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
  # end::certificates-api-contract[]
  /api/admin/clients:
    get:
      tags: [ Clients ]
      operationId: listClients
      summary: Lists the registered clients
      description: Never returns a client secret. Needs scope admin.
      security:
        - bearer: [ admin ]
      responses:
        '200':
          description: The clients
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/ClientResponse'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/AdminScopeRequired'
    post:
      tags: [ Clients ]
      operationId: createClient
      summary: Creates a client
      description: The generated secret of a confidential client is returned only in this answer. Needs scope admin.
      security:
        - bearer: [ admin ]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ClientRequest'
      responses:
        '201':
          description: The created client
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CreatedClientResponse'
        '400':
          description: Invalid definition, including a jwks that holds a private key (invalid-jwks)
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/AdminScopeRequired'
        '409':
          description: The client identifier is already registered
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
  /api/admin/clients/{clientId}:
    parameters:
      - $ref: '#/components/parameters/ClientId'
    get:
      tags: [ Clients ]
      operationId: getClient
      summary: Gets a registered client
      description: Never returns the client secret. Needs scope admin.
      security:
        - bearer: [ admin ]
      responses:
        '200':
          description: The client
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ClientResponse'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/AdminScopeRequired'
        '404':
          $ref: '#/components/responses/ClientNotFound'
    put:
      tags: [ Clients ]
      operationId: updateClient
      summary: Updates a client
      description: >-
        Replaces the definition of the client; the clientId of the body must match the path. The secret of the
        client is not changed. Needs scope admin.
      security:
        - bearer: [ admin ]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ClientRequest'
      responses:
        '200':
          description: The updated client
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ClientResponse'
        '400':
          description: Invalid definition, or a clientId in the body that differs from the path
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/AdminScopeRequired'
        '404':
          $ref: '#/components/responses/ClientNotFound'
    delete:
      tags: [ Clients ]
      operationId: deleteClient
      summary: Deletes a client
      description: Needs scope admin.
      security:
        - bearer: [ admin ]
      responses:
        '204':
          description: Client deleted
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/AdminScopeRequired'
        '404':
          $ref: '#/components/responses/ClientNotFound'
  /api/admin/clients/{clientId}/secret:
    parameters:
      - $ref: '#/components/parameters/ClientId'
    post:
      tags: [ Clients ]
      operationId: rotateClientSecret
      summary: Rotates the secret of a confidential client
      description: The new secret is returned only in this answer. Needs scope admin.
      security:
        - bearer: [ admin ]
      responses:
        '200':
          description: The new secret
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ClientSecretResponse'
        '400':
          description: The client is public
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/Problem'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/AdminScopeRequired'
        '404':
          $ref: '#/components/responses/ClientNotFound'
  # end::clients-api[]
  # tag::keys-api[]
  /api/admin/keys:
    get:
      tags: [ Signing keys ]
      operationId: listSigningKeys
      summary: Lists the signing keys
      description: Never exposes private key material. Needs scope admin.
      security:
        - bearer: [ admin ]
      responses:
        '200':
          description: The keys
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/SigningKeyResponse'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/AdminScopeRequired'
  /api/admin/keys/rotate:
    post:
      tags: [ Signing keys ]
      operationId: rotateSigningKeys
      summary: Rotates the signing keys now
      description: >-
        Forces a rotation whatever the age of the active key: the active key is retired (it stays published until
        the tokens it signed expire), the next key becomes active and a new next key is generated. Keys retired for
        longer than the retention are deleted, and the published keys are refreshed. The scheduled rotation, in
        contrast, only rotates a key that is due. Needs scope admin.
      security:
        - bearer: [ admin ]
      responses:
        '200':
          description: The keys after the rotation
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/SigningKeyResponse'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/AdminScopeRequired'
  # end::keys-api[]
components:
  securitySchemes:
    bearer:
      type: http
      scheme: bearer
      bearerFormat: JWT
      description: >-
        Access token issued by this server for the audience authserver.api.audience (default auth-server). The
        /api/admin/** operations also need the admin scope, listed as the role of their security requirement.
        Failures are answered with an RFC 6750 WWW-Authenticate challenge and no body.
  parameters:
    ClientId:
      name: clientId
      in: path
      required: true
      description: Public identifier of the client.
      schema:
        type: string
  # tag::passkeys-parameters[]
    PasskeyId:
      name: id
      in: path
      required: true
      description: Credential identifier of the passkey, as unpadded base64url.
      schema:
        type: string
        minLength: 1
        maxLength: 1000
        pattern: '^[A-Za-z0-9_-]+$'
  # end::passkeys-parameters[]
  headers:
    RetryAfter:
      description: Seconds to wait before retrying; at least 1.
      schema:
        type: integer
        format: int64
        minimum: 1
    WwwAuthenticate:
      description: >-
        RFC 6750 bearer challenge, for example Bearer error="invalid_token", or the RFC 9470 step-up challenge
        Bearer error="insufficient_user_authentication", acr_values="...", max_age="...".
      schema:
        type: string
  responses:
    Unauthorized:
      description: Missing or invalid bearer token
      headers:
        WWW-Authenticate:
          $ref: '#/components/headers/WwwAuthenticate'
    # tag::mfa-step-up-response[]
    StepUpRequired:
      description: >-
        Missing or invalid bearer token (an RFC 6750 challenge and no body), or the account has a confirmed second
        factor and the token does not show a multi-factor sign-in (acr urn:irurueta:acr:mfa) whose auth_time is within
        authserver.mfa.step-up-max-age (default 5 minutes). The latter is answered as RFC 9470 describes, with
        WWW-Authenticate Bearer error="insufficient_user_authentication", acr_values="urn:irurueta:acr:mfa",
        max_age="300" (the configured age in seconds) and a problem body; the client signs the user in again with
        those acr_values and max_age and retries with the new token.
      headers:
        WWW-Authenticate:
          $ref: '#/components/headers/WwwAuthenticate'
      content:
        application/problem+json:
          schema:
            $ref: '#/components/schemas/Problem'
    # end::mfa-step-up-response[]
    AdminScopeRequired:
      description: The token lacks the admin scope
      headers:
        WWW-Authenticate:
          $ref: '#/components/headers/WwwAuthenticate'
    TooManyRequests:
      description: Too many requests from this client or for this address
      headers:
        Retry-After:
          $ref: '#/components/headers/RetryAfter'
      content:
        application/problem+json:
          schema:
            $ref: '#/components/schemas/Problem'
    ClientNotFound:
      description: No such client
      content:
        application/problem+json:
          schema:
            $ref: '#/components/schemas/Problem'
  schemas:
    # tag::account-schemas[]
    RegisterRequest:
      type: object
      description: Registration of a new account
      required: [ username, email, password ]
      properties:
        username:
          type: string
          description: Desired username; it must contain a non-blank character.
          minLength: 1
          pattern: '[\s\S]*\S[\s\S]*'
        email:
          type: string
          format: email
          description: E-mail address that receives the verification link; it must contain a non-blank character.
          minLength: 1
          pattern: '[\s\S]*\S[\s\S]*'
        password:
          type: string
          format: password
          description: Chosen password; it must contain a non-blank character. Never logged.
          minLength: 1
          pattern: '[\s\S]*\S[\s\S]*'
    ChangePasswordRequest:
      type: object
      description: Change of the password of the authenticated account
      required: [ currentPassword, newPassword ]
      properties:
        currentPassword:
          type: string
          format: password
          description: Password in use; it must contain a non-blank character. Never logged.
          minLength: 1
          pattern: '[\s\S]*\S[\s\S]*'
        newPassword:
          type: string
          format: password
          description: Password to set; it must contain a non-blank character. Never logged.
          minLength: 1
          pattern: '[\s\S]*\S[\s\S]*'
    PasswordResetRequest:
      type: object
      description: Request of a password reset link
      required: [ email ]
      properties:
        email:
          type: string
          format: email
          description: E-mail address of the account; it must contain a non-blank character.
          minLength: 1
          pattern: '[\s\S]*\S[\s\S]*'
    ResetPasswordRequest:
      type: object
      description: Reset of a forgotten password with the token received by e-mail
      required: [ token, newPassword ]
      properties:
        token:
          type: string
          format: password
          description: >-
            Reset token received by e-mail; it must contain a non-blank character. Declared with the password
            format because it is confidential and never logged.
          minLength: 1
          pattern: '[\s\S]*\S[\s\S]*'
        newPassword:
          type: string
          format: password
          description: Password to set; it must contain a non-blank character. Never logged.
          minLength: 1
          pattern: '[\s\S]*\S[\s\S]*'
    # end::account-schemas[]
    # tag::totp-schemas[]
    TotpEnrollmentResponse:
      type: object
      description: The secret of a pending authenticator app enrolment, as a URI and as a QR code
      required: [ otpauthUri, qrCode ]
      properties:
        otpauthUri:
          type: string
          description: The otpauth:// URI that carries the shared secret. Never logged.
        qrCode:
          type: string
          description: The otpauth URI as a PNG QR code in a data URI (data:image/png;base64,...).
    ConfirmTotpRequest:
      type: object
      description: A code produced by the authenticator app
      required: [ code ]
      properties:
        code:
          type: string
          description: Six-digit one-time code shown by the authenticator app.
          pattern: '^[0-9]{6}$'
    RecoveryCodesResponse:
      type: object
      description: A set of recovery codes, shown only once
      required: [ recoveryCodes, remaining ]
      properties:
        recoveryCodes:
          type: array
          description: The new codes in clear text, each usable once. Never logged and never shown again.
          items:
            type: string
        remaining:
          type: integer
          format: int32
          minimum: 0
          description: Number of unused recovery codes, which is the size of the new set.
    TrustedDeviceResponse:
      type: object
      description: A browser on which the second factor is skipped until it expires
      required: [ id, createdAt, expiresAt ]
      properties:
        id:
          type: string
          format: uuid
          description: Identifier of the trusted device.
        userAgentSummary:
          type: string
          description: Short description of the browser, taken from its user agent; absent when unknown.
        createdAt:
          type: string
          format: date-time
          description: When the device was trusted.
        expiresAt:
          type: string
          format: date-time
          description: When the device stops being trusted.
    # end::totp-schemas[]
    # tag::passkeys-schemas[]
    Passkey:
      type: object
      description: A WebAuthn credential registered by the account
      required: [ id, label, createdAt, signatureCount, backupEligible, backedUp ]
      properties:
        id:
          type: string
          minLength: 1
          maxLength: 1000
          pattern: '^[A-Za-z0-9_-]+$'
          description: Credential identifier, as unpadded base64url.
        label:
          type: string
          minLength: 1
          maxLength: 100
          description: Name that identifies the passkey in the list.
        createdAt:
          type: string
          format: date-time
          description: When the passkey was registered.
        lastUsedAt:
          type: [ string, 'null' ]
          format: date-time
          description: When the passkey was last used to authenticate; equal to createdAt until its first use, because the credential store always records a value.
        signatureCount:
          type: integer
          format: int64
          minimum: 0
          description: Signature counter reported by the authenticator at its last use.
        backupEligible:
          type: boolean
          description: Whether the credential may be synchronised (the WebAuthn BE flag).
        backedUp:
          type: boolean
          description: Whether the credential is currently synchronised (the WebAuthn BS flag).
    RenamePasskeyRequest:
      type: object
      description: The new label of a passkey
      required: [ label ]
      properties:
        label:
          type: string
          description: New name of the passkey; it must contain a non-blank character.
          minLength: 1
          maxLength: 100
          pattern: '[\s\S]*\S[\s\S]*'
    # end::passkeys-schemas[]
    # tag::phone-schemas[]
    PhoneResponse:
      type: object
      description: The verified phone number of the account
      required: [ maskedNumber, verifiedAt ]
      properties:
        maskedNumber:
          type: string
          description: The number in E.164 form with every digit but the last four hidden, for example +*******1222.
        verifiedAt:
          type: string
          format: date-time
          description: When the number was verified.
    StartPhoneEnrolmentRequest:
      type: object
      description: The phone number to enrol
      required: [ phone ]
      properties:
        phone:
          type: string
          description: >-
            The number, in international form (+34 600 11 22 33) or national form of the default region; spaces,
            dashes and brackets are ignored.
          minLength: 1
          maxLength: 32
          pattern: '[\s\S]*\S[\s\S]*'
    PhoneEnrolmentResponse:
      type: object
      description: Confirmation that a verification code was requested
      required: [ expiresIn ]
      properties:
        expiresIn:
          type: string
          format: duration
          description: How long the verification code stays valid, as an ISO-8601 duration.
    VerifyPhoneRequest:
      type: object
      description: The code received by SMS
      required: [ code ]
      properties:
        code:
          type: string
          description: The numeric verification code.
          pattern: '^[0-9]{4,10}$'
    # end::phone-schemas[]
    # tag::identities-schemas[]
    Identity:
      type: object
      description: An identity of an external provider linked to the account
      required: [ id, provider, linkedAt ]
      properties:
        id:
          type: string
          format: uuid
          description: Identifier of the link.
        provider:
          type: string
          enum: [ google, microsoft, apple, github ]
          description: The provider that holds the identity.
        email:
          type: [ string, 'null' ]
          description: E-mail address the provider reported when the identity was last used, if any.
        linkedAt:
          type: string
          format: date-time
          description: When the identity was linked to the account.
        lastLoginAt:
          type: [ string, 'null' ]
          format: date-time
          description: When the identity was last used to sign in, or null when it has not been used since it was linked.
    # end::identities-schemas[]
    # tag::certificates-schemas[]
    Certificate:
      type: object
      description: An X.509 client certificate bound to the account
      required: [ id, fingerprintSha256, subjectDn, createdAt ]
      properties:
        id:
          type: string
          format: uuid
          description: Identifier of the binding.
        fingerprintSha256:
          type: string
          description: SHA-256 fingerprint of the DER form of the certificate, as lower case hexadecimal digits.
          pattern: '^[0-9a-f]{64}$'
        subjectDn:
          type: string
          description: Subject distinguished name of the certificate, to tell the bindings apart.
        createdAt:
          type: string
          format: date-time
          description: When the certificate was bound.
    BindCertificateRequest:
      type: object
      description: The certificate to bind
      required: [ certificate ]
      properties:
        certificate:
          type: string
          description: >-
            The X.509 certificate in PEM form (-----BEGIN CERTIFICATE----- ... -----END CERTIFICATE-----); never a
            private key.
          minLength: 1
          maxLength: 16384
    # end::certificates-schemas[]
    # tag::clients-schemas[]
    ClientRequest:
      type: object
      description: Definition of a registered client; it never contains a secret, which the server generates
      required: [ clientId, name, authMethods, grantTypes, redirectUris, scopes, accessTokenTtl, refreshTokenTtl ]
      properties:
        clientId:
          type: string
          description: Public identifier of the client; it must contain a non-blank character.
          minLength: 1
          pattern: '[\s\S]*\S[\s\S]*'
        name:
          type: string
          description: Human readable name; it must contain a non-blank character.
          minLength: 1
          pattern: '[\s\S]*\S[\s\S]*'
        confidential:
          type: boolean
          description: Whether the client can keep a secret. Defaults to false.
          default: false
        authMethods:
          type: array
          description: >-
            Client authentication methods. Accepted values: client_secret_basic, client_secret_post, none,
            private_key_jwt (needs jwks or jwkSetUrl), tls_client_auth (needs tlsClientAuthSubjectDn) and
            self_signed_tls_client_auth (needs jwks or jwkSetUrl). Only a client with a client_secret_* method is
            given a generated secret.
          items:
            type: string
        grantTypes:
          type: array
          description: >-
            Allowed grant types. Accepted values: authorization_code, refresh_token, client_credentials,
            urn:ietf:params:oauth:grant-type:device_code and urn:ietf:params:oauth:grant-type:token-exchange. The
            legacy implicit grant is refused here (400): only the demo client seeded under the opt-in
            legacy-implicit profile has it, and it may appear in a response for that client.
          items:
            type: string
        redirectUris:
          type: array
          description: Allowed redirect URIs.
          items:
            type: string
        scopes:
          type: array
          description: Allowed scopes.
          items:
            type: string
        requireProofKey:
          type: boolean
          description: Whether PKCE is required. Defaults to false.
          default: false
        audiences:
          type: array
          description: Audiences of the issued access tokens; absent or empty means the client identifier.
          items:
            type: string
        accessTokenTtl:
          type: string
          format: duration
          description: Lifetime of the access tokens, as an ISO-8601 duration such as PT5M.
        refreshTokenTtl:
          type: string
          format: duration
          description: Lifetime of the refresh tokens, as an ISO-8601 duration such as PT1H.
        accessTokenFormat:
          type: string
          description: >-
            Format of the access tokens, self-contained (a signed JWT) or reference (an opaque token resolved by
            introspection); absent or blank means self-contained.
        reuseRefreshTokens:
          type: boolean
          description: Whether refresh tokens are reused instead of rotated. Defaults to false.
          default: false
        postLogoutRedirectUris:
          type: array
          description: >-
            URIs the user may be redirected to after an OpenID Connect RP-initiated logout; a
            post_logout_redirect_uri that is not listed is never honoured. Absent means none.
          items:
            type: string
        requireConsent:
          type: boolean
          description: >-
            Whether the end-user must explicitly grant the requested scopes on a consent page.
            Defaults to false.
          default: false
        mfaRequired:
          type: boolean
          description: >-
            Whether every user who signs in through this client must complete a second factor, whatever their
            account setting. Defaults to false.
          default: false
        # tag::clients-auth-settings[]
        jwkSetUrl:
          type: string
          format: uri
          description: >-
            URL of the client's public JWK set, used to verify private_key_jwt assertions and self-signed
            certificates. Absent means none.
        jwks:
          type: object
          description: >-
            The client's public JWK set (an object with a keys array), alternative to jwkSetUrl. Only public keys
            are accepted: a key with private material is refused with 400 invalid-jwks. Absent means none.
          additionalProperties: true
        tokenEndpointAuthSigningAlgorithm:
          type: string
          description: JWS algorithm a client signs its private_key_jwt assertions with.
          enum: [ RS256, RS384, RS512, ES256, ES384, ES512, PS256, PS384, PS512 ]
        tlsClientAuthSubjectDn:
          type: string
          description: >-
            Expected subject distinguished name of the certificate of a tls_client_auth client, for example
            CN=client,O=Example. Required by tls_client_auth.
        certificateBoundAccessTokens:
          type: boolean
          description: >-
            Whether the access tokens issued to the client are bound to its mutual TLS certificate (cnf x5t#S256).
            Defaults to false.
          default: false
        # end::clients-auth-settings[]
    ClientResponse:
      type: object
      description: A registered client, without any secret
      required:
        - clientId
        - name
        - confidential
        - authMethods
        - grantTypes
        - redirectUris
        - scopes
        - requireProofKey
        - audiences
        - accessTokenTtl
        - refreshTokenTtl
        - accessTokenFormat
        - reuseRefreshTokens
        - postLogoutRedirectUris
        - requireConsent
        - mfaRequired
        - certificateBoundAccessTokens
      properties:
        clientId:
          type: string
          description: Public identifier of the client.
        name:
          type: string
          description: Human readable name.
        confidential:
          type: boolean
          description: Whether the client can keep a secret.
        authMethods:
          type: array
          description: Client authentication methods.
          items:
            type: string
        grantTypes:
          type: array
          description: Allowed grant types.
          items:
            type: string
        redirectUris:
          type: array
          description: Allowed redirect URIs.
          items:
            type: string
        scopes:
          type: array
          description: Allowed scopes.
          items:
            type: string
        requireProofKey:
          type: boolean
          description: Whether PKCE is required.
        audiences:
          type: array
          description: Audiences of the issued access tokens.
          items:
            type: string
        accessTokenTtl:
          type: string
          format: duration
          description: Lifetime of the access tokens, as an ISO-8601 duration.
        refreshTokenTtl:
          type: string
          format: duration
          description: Lifetime of the refresh tokens, as an ISO-8601 duration.
        accessTokenFormat:
          type: string
          description: Format of the access tokens, self-contained or reference.
        reuseRefreshTokens:
          type: boolean
          description: Whether refresh tokens are reused instead of rotated.
        postLogoutRedirectUris:
          type: array
          description: URIs the user may be redirected to after an OpenID Connect RP-initiated logout.
          items:
            type: string
        requireConsent:
          type: boolean
          description: Whether the end-user must explicitly grant the requested scopes on a consent page.
        mfaRequired:
          type: boolean
          description: Whether every user who signs in through this client must complete a second factor.
        # tag::clients-auth-settings-response[]
        jwkSetUrl:
          type: string
          format: uri
          description: URL of the client's public JWK set, when it has one.
        jwks:
          type: object
          description: The client's registered public JWK set, when it has one.
          additionalProperties: true
        tokenEndpointAuthSigningAlgorithm:
          type: string
          description: JWS algorithm a client signs its private_key_jwt assertions with.
          enum: [ RS256, RS384, RS512, ES256, ES384, ES512, PS256, PS384, PS512 ]
        tlsClientAuthSubjectDn:
          type: string
          description: Expected subject distinguished name of the certificate of a tls_client_auth client.
        certificateBoundAccessTokens:
          type: boolean
          description: Whether the access tokens issued to the client are bound to its mutual TLS certificate.
        # end::clients-auth-settings-response[]
    CreatedClientResponse:
      type: object
      description: The created client; the secret is shown only once
      required: [ client ]
      properties:
        client:
          $ref: '#/components/schemas/ClientResponse'
        clientSecret:
          type: string
          format: password
          description: >-
            Generated secret in clear text, shown only in this answer and never logged; null for a public client.
    ClientSecretResponse:
      type: object
      description: The new client secret; it is shown only once
      required: [ clientSecret ]
      properties:
        clientSecret:
          type: string
          format: password
          description: The new secret in clear text, shown only in this answer and never logged.
    # end::clients-schemas[]
    # tag::keys-schemas[]
    SigningKeyResponse:
      type: object
      description: A signing key, without its private half
      required: [ kid, alg, status, createdAt, publicJwk ]
      properties:
        kid:
          type: string
          description: Key identifier, the kid header of the tokens it signs.
        alg:
          type: string
          description: JWS algorithm, for example RS256.
        status:
          type: string
          description: Lifecycle state, NEXT, ACTIVE or RETIRED.
        createdAt:
          type: string
          format: date-time
          description: Creation instant.
        activatedAt:
          type: string
          format: date-time
          description: Instant at which the key started signing; null while it is the next key.
        retiredAt:
          type: string
          format: date-time
          description: Instant at which the key stopped signing; null until it is retired.
        publicJwk:
          type: string
          description: The public key as a serialized JSON Web Key.
    # end::keys-schemas[]
    Problem:
      type: object
      description: >-
        RFC 9457 problem details. The type is a URN naming the failure, for example urn:problem:account:rate-limited
        or urn:problem:client:not-found. Request validation failures use about:blank.
      properties:
        type:
          type: string
          format: uri
          description: URI reference identifying the problem type.
        title:
          type: string
          description: Short, human-readable summary of the problem type.
        status:
          type: integer
          format: int32
          description: HTTP status code of the answer.
        detail:
          type: string
          description: Human-readable explanation specific to this occurrence.
        instance:
          type: string
          format: uri
          description: URI reference identifying this occurrence, usually the request path.
        violations:
          type: array
          description: Only for urn:problem:account:invalid-password, the names of the broken password rules.
          items:
            type: string
