openapi: 3.1.0
info:
  title: Personal Data Vault - cross-site API
  # API contract version, deliberately independent of the module release tag.
  # Bump only when the wire contract changes, not on every module release.
  version: "1.0"
  description: |
    The HTTP surface a remote **consumer** site uses to read and write a
    user's vault on a **vault** site, plus the browser consent ceremony that
    mints the consumer's authorization.

    This API maps one-to-one to the vault's internal `ConsumerApiInterface`;
    the raw `Vault` (crypto) is never exposed. Two independent things gate it:

    - **OAuth2 (machine identity).** Every `/pdv-api/*` data call carries a
      bearer token obtained via the OAuth2 *client-credentials* grant. The
      token proves *which consumer* is calling, nothing about a user.
    - **Per-user authorization (the owner's consent).** Within a consumer's
      identity, access to a given user's items is gated by per-kind *trusts*
      and per-item *grants*, established through the consent ceremony. Read
      and write are **orthogonal**: a write authorization does not confer
      read, and vice versa.

    Users are addressed by an opaque **handle** (an AEAD of the uid under a
    per-consumer key), never by uid. A consumer obtains its handle for a user
    by completing the consent ceremony once.

    Every answer to a call made with the consumer's token, refusals included,
    is sent `Cache-Control: no-store, private` and echoes the vault-minted
    `X-Correlation-ID`, so a caller can join its own logs to the vault's audit
    rows. The browser landings (`/pdv-api/consent/start`,
    `/pdv-api/unlock/start`) answer the owner's browser, not the consumer, and
    the token endpoint is the OAuth server's: neither carries them.

    Two conditions any authorized call can still meet, both answered with 403
    and a JSON body naming which: `consent_required`, when a write has no
    standing authorization, and `vault_locked`, when the owner has passphrase
    protection on and no unlock session is in force. Each carries the URL to
    send the owner to. A call that is simply not authorized gets a 403 with no
    such body, uniform regardless of whether the item exists.

    Every user-scoped call is also rate-limited, per consumer and per
    (consumer, user); over the limit is `429` with a `Retry-After` header.

servers:
  - url: '{vault_base_url}'
    description: The vault site (scheme and host).
    variables:
      vault_base_url:
        default: https://vault.example

security:
  - oauth2: [pdv_api]

paths:
  /oauth/token:
    post:
      operationId: token
      summary: Obtain a client-credentials access token
      description: |
        Standard OAuth2 client-credentials grant, served by simple_oauth. The
        consumer authenticates with its `client_id` and `client_secret`
        (the secret is held in a key module Key on the consumer, never in
        config) and receives a bearer token scoped to `pdv_api`.
      security: []
      requestBody:
        required: true
        content:
          application/x-www-form-urlencoded:
            schema:
              type: object
              required: [grant_type, client_id, client_secret]
              properties:
                grant_type:
                  type: string
                  enum: [client_credentials]
                client_id:
                  type: string
                client_secret:
                  type: string
                scope:
                  type: string
                  example: pdv_api
      responses:
        '200':
          description: A bearer token.
          content:
            application/json:
              schema:
                type: object
                properties:
                  access_token:
                    type: string
                  expires_in:
                    type: integer
                    example: 3600
                  token_type:
                    type: string
                    example: Bearer
        '401':
          description: Invalid client credentials.

  /pdv-api/user/{handle}/items:
    get:
      operationId: listItems
      summary: List the items the consumer is authorized on
      description: |
        Lists item references the consumer may access for the user, filtered
        by scope. Returns references only (id, kind, label) - never content -
        and an empty list for an unauthorized consumer (no existence oracle).
      parameters:
        - $ref: '#/components/parameters/handle'
        - name: kind
          in: query
          required: false
          schema: { type: string }
          description: >-
            Restrict to one kind machine name, or several as a comma-separated
            list (e.g. `id_card,passport`). Omit for all kinds. Listing the
            exact kinds needed avoids both per-kind calls and over-fetching.
        - name: scope
          in: query
          required: false
          schema:
            type: string
            enum: [read, write]
            default: read
          description: |
            `read` (default) lists items the consumer may read; `write` lists
            items it may write (e.g. to choose create vs. update on a
            save-back). Scopes are orthogonal.
      responses:
        '200':
          description: The authorized items for the scope.
          content:
            application/json:
              schema:
                type: object
                properties:
                  items:
                    type: array
                    items: { $ref: '#/components/schemas/ItemReference' }
        '403':
          $ref: '#/components/responses/DeniedOrLocked'
        '429':
          $ref: '#/components/responses/RateLimited'

  /pdv-api/user/{handle}/item/{item_id}/record:
    get:
      operationId: readRecord
      summary: Read a structured record's field values
      parameters:
        - $ref: '#/components/parameters/handle'
        - $ref: '#/components/parameters/item_id'
      responses:
        '200':
          description: The decoded record field values.
          content:
            application/json:
              schema:
                type: object
                properties:
                  values:
                    type: object
                    additionalProperties: true
        '403':
          $ref: '#/components/responses/DeniedOrLocked'
        '429':
          $ref: '#/components/responses/RateLimited'

  /pdv-api/user/{handle}/item/{item_id}/raw:
    get:
      operationId: readRaw
      summary: Read the raw decrypted bytes of an item (e.g. a file)
      parameters:
        - $ref: '#/components/parameters/handle'
        - $ref: '#/components/parameters/item_id'
      responses:
        '200':
          description: The decrypted body bytes.
          content:
            application/octet-stream:
              schema:
                type: string
                format: binary
        '403':
          $ref: '#/components/responses/DeniedOrLocked'
        '429':
          $ref: '#/components/responses/RateLimited'

  /pdv-api/user/{handle}/item/{item_id}/access:
    get:
      operationId: canRead
      summary: Probe whether the consumer may read an item
      description: A side-effect-free read-authorization check.
      parameters:
        - $ref: '#/components/parameters/handle'
        - $ref: '#/components/parameters/item_id'
      responses:
        '200':
          description: Whether the consumer may read the item.
          content:
            application/json:
              schema:
                type: object
                properties:
                  can_read: { type: boolean }
        '403':
          $ref: '#/components/responses/Denied'
        '429':
          $ref: '#/components/responses/RateLimited'

  /pdv-api/user/{handle}/kind-access:
    get:
      operationId: kindAccess
      summary: Report the consumer's per-kind access (read and/or write)
      description: >-
        A side-effect-free, kind-level access check: which of the given kinds
        the consumer may access, per scope. A kind is accessible through a
        trust for it, or, for a unique kind, through a grant on the owner's
        item of it. Lets a UI learn read and write access in one query -- e.g.
        to offer only save targets that will succeed. Nothing is decrypted, so
        a locked vault is answered too.
      parameters:
        - $ref: '#/components/parameters/handle'
        - name: kinds
          in: query
          required: true
          schema: { type: string }
          description: Comma-separated candidate kind machine names.
        - name: scope
          in: query
          required: false
          schema: { type: string }
          description: >-
            Comma-separated scopes to report: `read`, `write`, or both
            (default `read,write`).
      responses:
        '200':
          description: >-
            The trusted kinds keyed by scope (only the requested scopes appear),
            plus `declined`: kinds the owner refused for the requested scopes, so
            a re-prompting UI drops them and stops asking. `declined` is posture,
            not inventory -- it reveals only refusal, never what the owner holds.
          content:
            application/json:
              schema:
                type: object
                properties:
                  read:
                    type: array
                    items: { type: string }
                  write:
                    type: array
                    items: { type: string }
                  declined:
                    type: array
                    items: { type: string }
        '403':
          $ref: '#/components/responses/Denied'
        '429':
          $ref: '#/components/responses/RateLimited'

  /pdv-api/kind-labels:
    get:
      operationId: kindLabels
      summary: Translated, human labels for vault item kinds
      description: >-
        The vault owns kinds and their translations, so it is the single source
        of their labels; a consumer never reconstructs a label from a machine
        name (which is meaningless to a user, in any language). Not user-scoped
        (no handle): kind labels are shared reference metadata, so a consumer
        caches the catalogue and fetches it rarely rather than per call.
      parameters:
        - name: kinds
          in: query
          required: false
          schema: { type: string }
          description: >-
            Comma-separated kind machine names to restrict to; omit for the
            whole catalogue.
        - name: langcode
          in: query
          required: false
          schema: { type: string }
          description: >-
            Language to resolve labels in; defaults to the vault's active
            language.
      responses:
        '200':
          description: A map of kind machine name to human label.
          content:
            application/json:
              schema:
                type: object
                additionalProperties: { type: string }

  /pdv-api/user/{handle}/record/{kind}:
    post:
      operationId: createRecord
      summary: Create a structured record of a kind
      description: |
        Requires a standing write authorization (write-trust on the kind, or a
        write-grant). For a unique kind, fails 409 if one already exists.
      parameters:
        - $ref: '#/components/parameters/handle'
        - $ref: '#/components/parameters/kind'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/RecordWrite' }
      responses:
        '201':
          $ref: '#/components/responses/ItemWritten'
        '400': { description: Body is not JSON with a "values" object. }
        '403':
          $ref: '#/components/responses/ConsentRequiredOrLocked'
        '429':
          $ref: '#/components/responses/RateLimited'
        '409': { description: 'A record of this unique kind already exists, so use PUT; or another write to it is in progress, so retry. The message says which.' }
        '413': { description: Request body too large. }
    put:
      operationId: updateRecord
      summary: Update (merge into) a record of a kind
      description: |
        Field values are merged onto the current ones; the stored label is
        kept when none is supplied. Requires write authorization. Fails 409 if
        no record of the kind exists yet.
      parameters:
        - $ref: '#/components/parameters/handle'
        - $ref: '#/components/parameters/kind'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/RecordWrite' }
      responses:
        '200':
          $ref: '#/components/responses/ItemWritten'
        '400': { description: Body is not JSON with a "values" object. }
        '403':
          $ref: '#/components/responses/ConsentRequiredOrLocked'
        '429':
          $ref: '#/components/responses/RateLimited'
        '409': { description: 'No record of this kind to update, so use POST; or another write to it is in progress, so retry. The message says which.' }
        '413': { description: Request body too large. }

  /pdv-api/user/{handle}/file/{kind}:
    post:
      operationId: saveFile
      summary: Store (or replace) a file of a kind
      description: |
        The request body is the raw file bytes; the MIME comes from
        `Content-Type`. Requires write authorization. Replaces the existing
        file of a unique kind in place.
      parameters:
        - $ref: '#/components/parameters/handle'
        - $ref: '#/components/parameters/kind'
        - name: filename
          in: query
          schema: { type: string }
        - name: label
          in: query
          schema: { type: string }
          description: Defaults to the filename when omitted.
      requestBody:
        required: true
        content:
          application/octet-stream:
            schema:
              type: string
              format: binary
      responses:
        '200':
          $ref: '#/components/responses/ItemWritten'
        '400': { description: Empty file body. }
        '403':
          $ref: '#/components/responses/ConsentRequiredOrLocked'
        '429':
          $ref: '#/components/responses/RateLimited'
        '409': { description: 'Write conflict for this kind, such as another write to it in progress: retry.' }
        '413': { description: Request body too large. }

  /pdv-api/consent/start:
    get:
      operationId: consentStart
      summary: Begin the owner consent ceremony (browser flow)
      description: |
        Not an OAuth call: this is opened in the **owner's** browser (they must
        be logged in on the vault). The vault parks a grant request for the
        named consumer and redirects to the approval page; after the owner
        decides, the browser is redirected back to `return_url` with the
        outcome and an opaque `handle` for the (consumer, owner) pair. A
        `scope=write` ceremony pre-enables the write-trust option; `mode=trust`
        (read only) sends the owner to the streamlined "trust these kinds" page
        (one read-trust decision, a checkbox per kind) instead of the per-item
        picker.
      security: []
      parameters:
        - name: consumer
          in: query
          required: true
          schema: { type: string }
          description: The consumer's OAuth client id.
        - name: kinds
          in: query
          required: true
          schema: { type: string }
          description: Comma-separated kind machine names.
        - name: return_url
          in: query
          required: true
          schema: { type: string, format: uri }
          description: |
            Where to send the owner back. Must be on the vault's configured
            allow-list of consumer origins.
        - name: state
          in: query
          required: true
          schema: { type: string }
          description: Anti-CSRF token the consumer verifies on the callback.
        - name: scope
          in: query
          schema:
            type: string
            enum: [read, write]
            default: read
        - name: mode
          in: query
          required: false
          schema:
            type: string
            enum: [trust]
          description: >-
            `trust` (read only) opens the streamlined "trust these kinds"
            page -- one read-trust decision with a checkbox per kind, instead of
            the per-item picker. Omit for the standard item-by-item ceremony.
      responses:
        '302':
          description: Redirect to the approval page (then back to return_url).
        '400': { description: 'Missing consumer, state, or kinds; a state longer than 64 URL-safe characters (A-Z, a-z, 0-9, ., _, ~, -); or a return_url longer than 1024 characters.' }
        '403': { description: Unknown consumer/kind, or a disallowed return_url. }
        '429':
          $ref: '#/components/responses/RateLimited'

  /pdv-api/unlock/start:
    get:
      operationId: unlockStart
      summary: Begin the owner unlock ceremony (browser flow)
      description: |
        The unlock counterpart of `/pdv-api/consent/start`, and the way out of
        a `vault_locked` 403. Not an OAuth call: it is opened in the **owner's**
        browser, and the vault takes the owner's identity from their session
        rather than from anything the consumer sends, so there is no handle
        here. The vault validates `return_url` against the same allow-list of
        consumer origins, parks the request in the owner's own session, and
        sends them to their unlock form.

        On a successful unlock the browser is redirected back to `return_url`
        with `state` and a one-time unlock handoff `code`, which the consumer
        redeems server-to-server at `/pdv-api/unlock/redeem`. The code expires
        in two minutes and is bound to the consumer it was minted for.
      security: []
      parameters:
        - name: consumer
          in: query
          required: true
          schema: { type: string }
          description: The consumer's OAuth client id.
        - name: return_url
          in: query
          required: true
          schema: { type: string, format: uri }
          description: |
            Where to send the owner back. Must be on the vault's configured
            allow-list of consumer origins.
        - name: state
          in: query
          required: true
          schema: { type: string }
          description: Anti-CSRF token the consumer verifies on the callback.
      responses:
        '302':
          description: Redirect to the owner's unlock form (then back to return_url).
        '400': { description: Missing consumer, return_url, or state. }
        '403': { description: A disallowed return_url origin. }
        '429':
          $ref: '#/components/responses/RateLimited'

  /pdv-api/unlock/redeem:
    post:
      operationId: redeemUnlockHandoffCode
      summary: Redeem a one-time unlock handoff code for the session key
      description: |
        Server-to-server, authenticated as the consumer: redeems the `code` the
        browser carried back from `/pdv-api/unlock/start` for the session key
        `ks`.

        `ks` is what makes subsequent calls readable: relay it on every request
        to that owner's vault in the `X-Pdv-Vault-Unlock` header, base64 as it
        is returned here. Hold it in the visitor's browser and nowhere else --
        it is the owner's unlock, and it is never stored on the vault. The code
        is single-use and consumer-bound, so a second redemption, or one by
        another consumer, is refused. A code whose vault was locked again
        before it was redeemed is refused too.

        Keep the key until `expires_in` seconds from now, and no longer. The
        answers to a request relaying it carry the
        `X-Pdv-Vault-Unlock-Expires-In` header: how long the unlock has left
        from then, in seconds, or zero once the key opens nothing. That is every
        answer the API builds, `vault_locked` and `consent_required` included;
        the uniform 403 and a 429 do not carry it. Take that as the new expiry,
        and forget the key on zero. The vault extends an unlock only once half
        of it is used up, and, in vault-activity mode, only when a vault is read
        or written, so the consumer cannot work the expiry out on its own.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [code]
              properties:
                code:
                  type: string
                  description: The one-time unlock handoff code from the unlock redirect.
      responses:
        '200':
          description: The session key.
          content:
            application/json:
              schema:
                type: object
                required: [ks, idle, expires_in]
                properties:
                  ks:
                    type: string
                    description: Base64 session key, for the X-Pdv-Vault-Unlock header.
                  idle:
                    type: integer
                    description: How long the vault stays unlocked without activity, in seconds.
                  expires_in:
                    type: integer
                    description: How long the unlock has left now, in seconds.
        '403':
          description: >-
            Unknown, expired, already redeemed, or another consumer's code, or
            a vault locked again since. Uniform, so it is not an oracle for
            which.

  /pdv-api/unlock/status:
    get:
      operationId: readUnlockStatus
      summary: Say how long the unlock a consumer relays has left
      description: |
        Server-to-server, authenticated as the consumer, relaying the owner's
        session key in the `X-Pdv-Vault-Unlock` header.

        A consumer about to show the owner a form asks this once half the
        unlock is used up, so the owner does not type into a form that cannot
        be saved. For example, with unlocks living 30 minutes, it asks when
        less than 15 minutes are left. Asking extends the unlock in both
        extension modes, as reading or writing a vault does: the owner is
        about to write to it.

        Counted against the consumer's read limit.
      parameters:
        - name: X-Pdv-Vault-Unlock
          in: header
          required: true
          schema: { type: string }
          description: The base64 session key.
      responses:
        '200':
          description: The unlock is open.
          headers:
            X-Pdv-Vault-Unlock-Expires-In:
              description: How long the unlock has left, in seconds.
              schema: { type: integer }
          content:
            application/json:
              schema:
                type: object
                required: [idle, expires_in]
                properties:
                  idle:
                    type: integer
                    description: How long the vault stays unlocked without activity, in seconds.
                  expires_in:
                    type: integer
                    description: How long the unlock has left now, in seconds.
        '403':
          description: The vault is locked again (`vault_locked`), or the consumer is not authorized.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/VaultLockedError'
        '429':
          $ref: '#/components/responses/RateLimited'

components:
  securitySchemes:
    oauth2:
      type: oauth2
      flows:
        clientCredentials:
          tokenUrl: /oauth/token
          scopes:
            pdv_api: Access the Personal Data Vault cross-site API.

  parameters:
    handle:
      name: handle
      in: path
      required: true
      schema: { type: string }
      description: The opaque per-(consumer, owner) handle from the consent ceremony.
    item_id:
      name: item_id
      in: path
      required: true
      schema: { type: integer }
    kind:
      name: kind
      in: path
      required: true
      schema: { type: string }
      description: An item-kind machine name (e.g. `civil_status`, `id_card`).

  schemas:
    ItemReference:
      type: object
      properties:
        id: { type: integer }
        kind:
          type: string
          nullable: true
        label: { type: string }
    RecordWrite:
      type: object
      required: [values]
      properties:
        values:
          type: object
          additionalProperties: true
          description: The record's field values, keyed by field name.
        label:
          type: string
          description: Optional; on update the stored label is kept when omitted.
    ConsentRequiredError:
      type: object
      properties:
        error:
          type: string
          enum: [consent_required]
        consent_url:
          type: string
          format: uri
          description: The consent landing to send the owner to (append return_url + state).
        kinds:
          type: array
          items: { type: string }
    VaultLockedError:
      type: object
      properties:
        error:
          type: string
          enum: [vault_locked]
        unlock_url:
          type: string
          format: uri
          description: The unlock landing to send the owner to (append return_url + state).

  responses:
    ItemWritten:
      description: The stored item reference.
      content:
        application/json:
          schema:
            type: object
            properties:
              item: { $ref: '#/components/schemas/ItemReference' }
    Denied:
      description: |
        The consumer is not authorized for this item, or the stored ciphertext
        could not be decrypted (tampered or wrong key). Uniform regardless of
        whether the item exists, so it is neither an existence nor an integrity
        oracle.
    DeniedOrLocked:
      description: |
        Either an ordinary denial, exactly as `Denied` describes it and with no
        body of its own, or the vault is locked: the owner has passphrase
        protection on and no unlock session is in force, so nothing can be
        decrypted for anyone, the operator included. The locked case carries an
        `error: vault_locked` body with the `unlock_url` to send the owner to;
        relay the resulting session key on the retry.
      content:
        application/json:
          schema: { $ref: '#/components/schemas/VaultLockedError' }
    ConsentRequiredOrLocked:
      description: |
        One of three, and the body says which. No standing write authorization
        gives `error: consent_required` with the `consent_url` to send the
        owner through. A locked vault gives `error: vault_locked` with the
        `unlock_url`. An ordinary denial carries no body at all. All three are
        uniform regardless of item/kind existence.
      content:
        application/json:
          schema:
            oneOf:
              - $ref: '#/components/schemas/ConsentRequiredError'
              - $ref: '#/components/schemas/VaultLockedError'
    RateLimited:
      description: |
        Over a configured rate limit. Two independent ceilings apply to a
        user-scoped call, one per consumer and one per (consumer, user), and
        either can trip. `Retry-After` carries the window in seconds; the
        operator sets both thresholds, and either can be turned off.
      headers:
        Retry-After:
          description: Seconds to wait before retrying.
          schema: { type: integer }
