# PDS — implementation spec

**PDS** = *Prestataire De Service*, the third party whose MCP tool the agent uses. In the POC
it is a fictional bank, **Banque Test (`bqt`)**. This module is the **verifier**: it holds the
account data, exposes one MCP tool, and carries our mandate layer as an *isolated* security
route without touching its existing Keycloak-protected REST layer.

Base repo already cloned into this folder (MIT, `NOTICE` records upstream `223cde71`). See
[architecture.md §9](../architecture.md) for the file-by-file evaluation. Shared wire formats:
[`../contracts.md`](../contracts.md).

---

## 1. Scope

| We add | We keep untouched | We do **not** build |
|---|---|---|
| `accounts` domain (JPA + H2): `customer`, `account`, `account_link` | The existing `SecurityFilterChain` on `/api/**` (Keycloak resource server) | Any write/payment tool |
| REST `GET /accounts/me` (bank-Keycloak protected — demo step 1) | `KeycloakRoleConverter`, `UserController` demo endpoints | Multi-issuer core trust (we use the isolated-route variant) |
| MCP route at `/mcp`: `tools/list` + `get_balance` (Streamable HTTP) | `application.yml` issuer wiring (only the realm name changes) | Periodic schema re-polling / drift (Phase 0.6–0.8) |
| Second, `@Order`-ed `SecurityFilterChain` on `/mcp/**`: our JWT + DPoP + introspection + **account-link assertion re-verify** ([contracts §2](../contracts.md) steps 14–18) | | `DPoP-Nonce` server challenge |
| `mcp_call_audit` table (Trace Prestataire) | | Behavioural / per-call dynamic scoring (stays clear of the Daon patent) |
| **Account-linking (§7)**: an Ed25519 assertion key (`bqt-assertion-1`), `GET /pds-jwks.json`, `POST /account-link/assert` (front-channel signed-assertion, [contracts §8](../contracts.md)) | | The real `prompt=none` OIDC handoff (Variante 1) — the assert endpoint's customer auth is mocked (§7.3) |

---

## 2. Build order within this module

| Sub-step | Global step ([contracts §0](../contracts.md)) | Do it | Before / after |
|---|---|---|---|
| 3.1 Spike | 0b | Bump + trivial MCP server ↔ TS client | ✅ **done 2026-09-09** — [`spike-notes.md`](spike-notes.md). Verdict GO; version coords + a transport-shape correction below |
| 3.2 Standup | 3 | ✅ **done 2026-09-11** — Boot **3.5.13** (not 3.4 — matches the spike pin)/ JDK 21 build green; JPA + H2 + Flyway; `accounts` domain; REST `/accounts/me`; `bqt` realm | after spike |
| 7 Account-linking | 3 | ✅ **done 2026-09-11**, with 3.2 — assertion key + `GET /pds-jwks.json` + `POST /account-link/assert` (§7); curl-tested live | with 3.2 — small; unblocks the stub rework ([contracts §0](../contracts.md) note). Test with `curl` |
| 8 MCP route | 4 | ✅ **done 2026-09-11** — `tools/list` + `get_balance` over the same data; hand-built `McpSchema.Tool`/`SyncToolSpecification` (not `@Tool`, to get `annotations` through); `McpPrincipal` read from the security context, at the time always absent (`/mcp/**` still open, §9 not yet built) so `tools/call` returned `no_mandate_context`; live-tested with `@modelcontextprotocol/inspector --cli` (that command needs the curl-based replacement in §8's quickstart once §9 lands — see note below) | after 3.2. Test with a **raw** MCP client (`@modelcontextprotocol/inspector` or a small script) before the Outil Local exists |
| 9 Isolated filter | 6 | ✅ **done 2026-09-19**, discovery exemption fixed 2026-09-25 — JWT + DPoP + introspection + account-link assertion re-verify on `/mcp/**`; `initialize`/`notifications/initialized`/`tools/list` exempt, `tools/call` always gated | after the **Outil Local runtime** ([outil-local §runtime](../outil-local/spec.md)) so it is exercised against real proofs; **and** after the **platform stub** ([platform §Stub](../platform/spec.md)) for JWKS + introspection. Unit-test earlier with hand-forged tokens/proofs/assertions |

Sub-step 9 is now live: `/mcp/**` requires a real signed mandate for `tools/call`, but discovery
(`initialize`/`notifications/initialized`/`tools/list`) stays open with no auth (§8, §9's
"discovery exemption" note) — see `pds/TESTING.md` §7 for the up-to-date worked example,
including why the `@modelcontextprotocol/inspector` CLI specifically doesn't work for it.

---

## 3. Tech changes to the cloned base

| Change | From | To | Why / attention |
|---|---|---|---|
| `spring-boot-starter-parent` | `3.2.3` | **`3.5.13`** | pinned by the spike ([`spike-notes.md`](spike-notes.md)). **Not** 3.3/3.4 (too old for Spring AI 1.1), **not** 4.x |
| `java.version` | `17` | `21` | LTS carry-forward ([architecture.md §12.0](../architecture.md)) |
| Maven wrapper | absent | `mvn wrapper:wrapper` once, commit `.mvn/` | base repo has no `./mvnw` |
| add | — | `spring-boot-starter-data-jpa` | |
| add | — | `com.h2database:h2` (runtime) | file mode, `jdbc:h2:file:./data/bqt` |
| add (import) | — | `spring-ai-bom` **`1.1.8`** in `<dependencyManagement>` | **not** `2.0.x` — that pulls Spring Boot 4.1 |
| add | — | `spring-ai-starter-mcp-server-webmvc` (version from the BOM) | pulls MCP Java SDK `0.18.3`; Streamable HTTP confirmed working ↔ `@modelcontextprotocol/sdk@1.30.0` |
| add | — | `org.flywaydb:flyway-core` | schema + seed migrations (see §5.6) |
| present | `com.nimbusds:nimbus-jose-jwt` | keep | DPoP proof + thumbprint verification (§9) |
| `KeycloakRoleConverter` | system-role set contains `default-roles-demo` | `default-roles-bqt` | realm renamed |

**Two upstream bugs** (from [architecture.md §9](../architecture.md)) — fix or moot them, since
the whole `/api/**` security is replaced by our config anyway:
- `SecurityConfig.jwtDecoder()` calls `JwtDecoders.fromIssuerLocation(...)` at bean creation →
  the context will not start unless Keycloak is reachable. For the isolated `/mcp/**` chain use
  a **lazily** built `NimbusJwtDecoder` from `PLATFORM_JWKS_URI` (JWKS, not issuer discovery).
- `UserController` maps `/api/public/health` but `SecurityConfig` permits only `/public/**`.
  Irrelevant to us; leave it or delete the demo controller.

**PostgreSQL guardrail** ([architecture.md §6/§7](../architecture.md)): JPA/Hibernate only, no
native SQL in entities, no H2-specific types. Flyway migrations use portable DDL (`BIGINT`,
`VARCHAR`, `TIMESTAMP`; JSON as `TEXT` if ever needed).

---

## 4. Configuration (`application.yml` + env)

```yaml
spring:
  application: { name: bqt-pds }
  datasource:
    url: jdbc:h2:file:./data/bqt   # no AUTO_SERVER=TRUE — see application.yml's comment (build
                                    # step 3: hit a rootless-Podman-interface false-"localhost"
                                    # connection-timeout bug on a real box; nothing here needs
                                    # concurrent access to the file from a second process)
    username: sa
    password: ""
  jpa:
    hibernate.ddl-auto: validate        # Flyway owns the schema
    open-in-view: false
  flyway: { enabled: true, locations: classpath:db/migration }
  security.oauth2.resourceserver.jwt:
    issuer-uri: ${KC_ISSUER_URI:http://localhost:8080/realms/bqt}   # PDS's OWN Keycloak, /api/** only

server: { port: 8081 }

pds:
  mcp:
    canonical-uri: ${MCP_CANONICAL_URI:http://localhost:8081/mcp}   # == token aud
  platform:
    jwks-uri:        ${PLATFORM_JWKS_URI:http://localhost:3000/jwks.json}
    introspect-base: ${PLATFORM_INTROSPECT_BASE:http://localhost:3000/introspect}
    expected-iss:    ${PLATFORM_EXPECTED_ISS:https://veritia.eu}
  dpop:
    iat-skew-seconds: 60
    replay-ttl-seconds: 120
  linking:                                                    # account-linking (§7, contracts §8)
    provider-id:            ${PDS_PROVIDER_ID:9b7c1e40-2f6a-4c11-9e2a-000000000bqt}  # assertion iss
    assertion-key-path:     ${PDS_ASSERTION_KEY_PATH:./data/pds-assertion.jwk.json}  # generated once at boot
    assertion-ttl-seconds:  300
    assert-dev-secret:      ${PDS_ASSERT_DEV_SECRET:poc-dev-secret}                  # mocked-auth guard (§7.3)
```

Values and their compose-network counterparts: [contracts §6](../contracts.md).

---

## 5. Data model (JPA entities on H2)

Five tables. `customer`, `account` and `transaction` are real business data. `account_link` is
the PDS's own `provider_account_ref → customer` record — **seeded** here so the POC has stable
customers (in production a row is minted by the signed handoff, §7 / [contracts
§8](../contracts.md)). `mcp_call_audit` is the Trace Prestataire. The DPoP replay cache is
**in-memory**, not a table ([contracts §2](../contracts.md)).

### 5.1 `customer`

| Column | Type | Constraints | Notes |
|---|---|---|---|
| `id` | `VARCHAR(20)` | **PK** | natural id, e.g. `cust-002` |
| `display_name` | `VARCHAR(120)` | `NOT NULL` | |
| `created_at` | `TIMESTAMP` | `NOT NULL` | |

### 5.2 `account`

| Column | Type | Constraints | Notes |
|---|---|---|---|
| `id` | `BIGINT` | **PK**, identity | |
| `customer_id` | `VARCHAR(20)` | `NOT NULL`, **FK → `customer(id)`** | |
| `iban` | `VARCHAR(34)` | `NOT NULL`, `UNIQUE` | stored with spaces as in [contracts §4](../contracts.md); illustrative, checksum not enforced |
| `currency` | `CHAR(3)` | `NOT NULL` | always `EUR` |
| `balance_cents` | `BIGINT` | `NOT NULL` | integer minor units; format for display only |
| `as_of` | `TIMESTAMP` | `NOT NULL` | returned by `get_balance` |

Index: `ix_account_customer` on `(customer_id)`. One account per customer in the POC (no
constraint enforcing it — keep the 1‑N shape).

### 5.3 `account_link`  *(the PDS's own customer ↔ pairwise-ref table — seeded)*

| Column | Type | Constraints | Notes |
|---|---|---|---|
| `provider_account_ref` | `VARCHAR(64)` | **PK** | opaque, pairwise; matches `provider_account_ref.value` in the JWT |
| `customer_id` | `VARCHAR(20)` | `NOT NULL`, `UNIQUE`, **FK → `customer(id)`** | reverse lookup `findByCustomerId` feeds the assert endpoint (§7.2) |
| `source` | `VARCHAR(32)` | `NOT NULL` | `signed_assertion` (the POC now issues real assertions, §7); real alt value `oidc_silent` |
| `linked_at` | `TIMESTAMP` | `NOT NULL` | |

Used **two ways**: forward (`findById(provider_account_ref)` → customer → account, in
`get_balance` §8) and reverse (`findByCustomerId` → `provider_account_ref`, in the assert
endpoint §7.2).

> Migration comment to carry verbatim: *"This table is the PDS's own record of which opaque
> pairwise ref maps to which customer. In production the ref is minted the first time a
> customer links an agent (via the signed account-linking handoff, spec 2.0ter/2.0quater),
> not seeded, and never derived from the itsme `sub`. Seeded here only so the POC has stable
> customers."*

### 5.4 `mcp_call_audit`  *(Trace Prestataire — [contracts §5.7](../contracts.md))*

| Column | Type | Constraints | Notes |
|---|---|---|---|
| `id` | `BIGINT` | **PK**, identity | |
| `ts` | `TIMESTAMP` | `NOT NULL` | |
| `jti` | `VARCHAR(64)` | `NOT NULL`, indexed | delegation token `jti` — the correlation key with the Trace Plateforme |
| `dpop_jti` | `VARCHAR(64)` | `NULL` | proof `jti` |
| `mandate_sub` | `VARCHAR(128)` | `NULL` | itsme `sub` |
| `agent_jkt` | `VARCHAR(64)` | `NULL` | RFC 7638 thumbprint of `cnf.jwk` |
| `provider_account_ref` | `VARCHAR(64)` | `NULL` | |
| `tool_name` | `VARCHAR(64)` | `NULL` | |
| `decision` | `VARCHAR(16)` | `NOT NULL` | `ALLOW` / `DENY` |
| `deny_reason` | `VARCHAR(64)` | `NULL` | the `error` code from [contracts §2](../contracts.md) |
| `request_htu` | `VARCHAR(255)` | `NULL` | |

**Exposed via `GET /mcp-audit/:jti`** (step 9b, 2026-10-09, [contracts §8.6](../contracts.md)) —
this section originally said "also emit each row as a single-line JSON log to stdout," which
was never actually implemented; found missing live while rehearsing demo beat 8 (no log line,
no endpoint, no console — the only way to see this data was a direct H2 query). Fixed with a
small `permitAll` read-only endpoint instead of a log line, fetched **directly by the SPA's
browser** (not relayed through the stub) and rendered as a second "Trace Prestataire" panel
right next to "Trace Plateforme" in the dashboard's row expansion — no terminal needed for
either trail any more.

### 5.5 `transaction`  *(build step 4b — backs `list_transactions`, §8)*

| Column | Type | Constraints | Notes |
|---|---|---|---|
| `id` | `BIGINT` | **PK**, identity | |
| `customer_id` | `VARCHAR(20)` | `NOT NULL`, **FK → `customer(id)`** | |
| `value_date` | `TIMESTAMP` | `NOT NULL` | |
| `amount_cents` | `BIGINT` | `NOT NULL` | signed; negative = debit, positive = credit |
| `currency` | `VARCHAR(3)` | `NOT NULL` | always `EUR` |
| `counterparty` | `VARCHAR(120)` | `NOT NULL` | |
| `description` | `VARCHAR(255)` | `NULL` | |

Index: `ix_transaction_customer` on `(customer_id)`. Seeded (V3, originally 10 rows/customer — 22/28/34 rows for `cust-001`/`002`/`003` since the
2026-10-14 addendum, see `demo/testing-guide.md` §4) with
`value_date` offsets counted back from each customer's own most recent row — a static demo
snapshot, deliberately not tied to wall-clock "now" so `list_transactions`'s `period` filter
returns deterministic counts regardless of when the POC is run (mirrors the fake PDS's demo
prop, `platform/stub/dev/fake-pds.mjs`).

### 5.6 Migrations & seeding

`src/main/resources/db/migration/`:
- `V1__schema.sql` — the four original tables + indexes + FKs above.
- `V2__seed.sql` — `customer` (3 rows), `account` (3 rows), `account_link` (3 rows) exactly per
  [contracts §4](../contracts.md).
- `V3__transactions.sql` — the `transaction` table + its seed (22/28/34 rows per customer since 2026-10-14, §5.5).

Flyway runs on startup → tables exist and are filled with no manual step, and survive a
container restart (H2 file mode). Wipe = delete `./data/` ([deploy §teardown](../deploy/spec.md)).
`spring.jpa.hibernate.ddl-auto=validate` catches entity/schema drift.

---

## 6. Existing-style REST endpoint (demo step 1)

Protected by the PDS's **own** Keycloak (`bqt` realm), *not* our mandate layer — the point of
step 1 is "this service already has its own security, we change none of it".

| Method | Path | Auth | Request | Response `200` | Errors |
|---|---|---|---|---|---|
| `GET` | `/accounts/me` | `Authorization: Bearer <bqt-Keycloak token>`, role `CUSTOMER` | — | `{ "customer_id","display_name","iban","currency","balance": "12802.50","as_of" }` | `401` no/ના bad token · `403` missing role |

Resolution: Keycloak token `preferred_username` (`pieter`) → map to `customer.id`. For the POC
seed a `username → customer_id` constant (`pieter → cust-001`); it is unrelated to
`account_link` (that one is keyed by `provider_account_ref`).

Keep the base `/api/profile`, `/api/token-info` endpoints or delete them — unused by the demo.

---

## 7. Account-linking — assertion key + endpoints

Implements the PDS half of [contracts §8](../contracts.md) (front-channel signed-assertion,
`liaison-compte-prestataire.md` Variante 2). No Spring Security involved — these are plain
`@RestController` endpoints outside both filter chains (`permitAll` on `/pds-jwks.json` and
`/account-link/**`, or a third tiny `@Order(0)` matcher).

### 7.1 Assertion key (`bqt-assertion-1`)

- On boot: if `pds.linking.assertion-key-path` exists, load it; else generate an Ed25519
  keypair (Nimbus `OctetKeyPairGenerator` / `Ed25519` `OKP`), set `kid=bqt-assertion-1`,
  `use=sig`, `alg=EdDSA`, and write the **private** JWK JSON to that path (`./data/…`, so it
  survives a restart like the H2 file — a mandate minted now embeds this key's thumbprint and
  lives 1 h; a fresh key mid-demo would break `provider_jkt`).
- `GET /pds-jwks.json` → `{ "keys": [ <public JWK, kid bqt-assertion-1> ] }`. Cached by the
  stub (`PDS_ASSERTION_JWKS_URI`).
- This is the **third keypair** ([contracts §4](../contracts.md)) — distinct from the platform
  RSA signing key and the agent Ed25519 key.

### 7.2 `POST /account-link/assert`

Per [contracts §8.3](../contracts.md). Flow:

1. Reject unless header `X-Poc-Dev-Auth == pds.linking.assert-dev-secret` → `401
   poc_dev_auth_required`. *(This is the whole "customer authentication" in the POC — see
   §7.3.)*
2. `account_link.findByCustomerId(pds_customer_id)` → `provider_account_ref`; miss → `400
   unknown_customer`.
3. Build + sign the assertion JWS ([contracts §8.2](../contracts.md)) with `bqt-assertion-1`:
   `iss = pds.linking.provider-id`, `aud = pds.platform.expected-iss`, `sub =
   provider_account_ref`, `iat = now`, `exp = now + assertion-ttl-seconds`, `jti =
   randomUUID()`.
4. Return `{ "assertion": "<compact JWS>" }`. Optionally log a one-line JSON audit row
   (mirrors the stub's `ACCOUNT_LINK_VERIFIED`).

### 7.3 What is mocked here — carry this comment verbatim

```
POC ONLY. In production this endpoint is replaced by an OIDC authorization + token endpoint
(prompt=none) that vouches for the customer's ALREADY-AUTHENTICATED session at the PDS
(liaison-compte-prestataire.md Variante 1). Here the customer identity arrives as a plain
`pds_customer_id` in the request body, gated only by a shared dev secret. The signature,
the JWKS, and the PDS-side re-verification in the /mcp filter (contracts §2 steps 14-18)
are all real; only the caller's right to name a customer is faked.
```

### 7.4 Re-verification in the `/mcp` filter

Steps 14–18 of [contracts §2](../contracts.md), added to `MandateDpopFilter` (§9): parse
`provider_account_ref.assertion`, verify its signature against the **locally held**
`bqt-assertion-1` public key (not fetched — the PDS owns it), check `iss` / `aud` /
`assertion.sub == provider_account_ref.value` / `provider_jkt == thumbprint(own key)` /
`asserted_at == assertion.iat` / assertion valid at the delegation token's `iat`. Fail codes
in the §2 table (`account_ref_assertion_invalid`, `account_ref_value_mismatch`,
`account_ref_jkt_mismatch`, `account_ref_stale`).

---

## 8. MCP route — `tools/list`, `get_balance`, `list_transactions`

Spring AI MCP server starter (webmvc), **Streamable HTTP**, mounted at `/mcp`
([architecture.md §11.2](../architecture.md)). Spike outcome ([`spike-notes.md`](spike-notes.md)):
negotiated protocol is **`2025-11-25`** (session-scoped shape — server issues `Mcp-Session-Id`,
there is a real `GET /mcp` SSE stream). Config:

```yaml
spring.ai.mcp.server:
  name: bqt-pds
  version: 0.0.1
  protocol: STREAMABLE            # evaluate STATELESS at this step — drops sessions + the GET
                                  # stream, simplifies §9; keep only if tools/list+call still work
  streamable-http: { mcp-endpoint: /mcp }
```

### Tool definition

| Field | Value |
|---|---|
| `name` | `get_balance` |
| `description` | `"Return the caller's own Banque Test account balance."` |
| `inputSchema` | `{ "type":"object", "properties":{}, "required":[] }` — **no parameters** (keeps the deterministic parse trivial: one tool, no ceiling fields) |
| `annotations` | `{ "readOnlyHint": true, "title": "Consulter le solde" }` |

### Behaviour

1. Read the authenticated principal from the security context (populated by the isolated
   filter, §9): `provider_account_ref.value`, `sub`, `agent_jkt`, `allowed_tools`.
2. `account_link.findById(provider_account_ref.value)` → `customer` → `account`.
3. Return:
   ```json
   { "iban": "BE71 0961 2345 6769", "currency": "EUR", "balance": "12802.50",
     "as_of": "2026-09-01T00:00:00Z" }
   ```
4. No `account_link` row → MCP tool error `{ "code": "unknown_account" }` (scenario S10).
5. Write a `mcp_call_audit` row (`decision=ALLOW`, `tool_name=get_balance`).

Discovery (`tools/list`) is left **public** for the POC (spec permits it) so the stub's
`/discover` proxy needs no API key.

### `list_transactions`  *(build step 4b)*

Mirrors `get_balance`'s tool (same hand-built `McpSchema.Tool`, same annotation-preservation
reason, same principal/unknown-account handling) — and mirrors the fake PDS's demo-prop tool
(`platform/stub/dev/fake-pds.mjs`) that validated the review-screen UX first (platform/spec.md
§B4). Read-only — no write/payment path (§1).

| Field | Value |
|---|---|
| `name` | `list_transactions` |
| `description` | `"Consulter l'historique des transactions du compte du client."` |
| `inputSchema` | `{ "type":"object", "properties": { "max_results": {"type":"integer","minimum":1,"maximum":50}, "period": {"type":"string","enum":["7j","30j","90j"]} }, "required":[] }` — both optional |
| `annotations` | `{ "readOnlyHint": true, "title": "Consulter l'historique des transactions" }` |

Behaviour: same principal/`account_link` resolution as `get_balance` (steps 1–2, same
`unknown_account` error). `max_results` defaults to 20 if absent, else must be an integer in
`[1,50]` (else MCP tool error `{ "code": "invalid_max_results" }`, `mcp_call_audit DENY`).
`period` defaults to no filter if absent, else must be one of `7j`/`30j`/`90j` (else `{ "code":
"invalid_period" }`, same DENY pattern) and filters `transaction.value_date` against the
customer's own most recent row (§5.5 — not wall-clock "now"). Returns:
```json
{ "transactions": [ { "value_date":"2026-08-31T09:12:00Z", "amount":"-12.50", "currency":"EUR",
                       "counterparty":"Carrefour Ixelles", "description":"Paiement carte" } ],
  "count": 1 }
```
Writes a `mcp_call_audit` row (`decision=ALLOW`, `tool_name=list_transactions`) on success.

**Mandate-declared caps on `max_results`/`period` (contracts §1.1, added 2026-10-12).** After
the two syntactic checks above pass (so the *effective* value is known — `max_results` after
its own default, `period` after its own "absent = unbounded" rule), compare it against
`McpPrincipal.toolConstraints().get("list_transactions")` — `disclosed_scope.tool_constraints`,
carried opaquely through the filter (§9). Done in Java in
`ListTransactionsTool.checkToolConstraints`, **not** the filter (which never parses `tools/call`
arguments). Two checks, each independent, first-match wins:
- `max_results` cap present and `effectiveMaxResults > cap` → `{ "code":
  "max_results_exceeds_mandate" }`.
- `period` cap present (one of `7j`/`30j`/`90j`) and `effectivePeriodDays > capDays` → `{ "code":
  "period_exceeds_mandate" }` — an **absent** `period` counts as unbounded (every row), so it
  violates any finite cap too, not just an explicit over-cap value.
Both are `mcp_call_audit DENY` (`denyReason` = the same code), same pattern as
`invalid_max_results`/`invalid_period`. Deliberately **two specific codes, not one generic
`tool_constraint_exceeded` + a `detail` field** — matches this tool's own existing
`invalid_max_results`/`invalid_period` convention (every MCP tool-level error in this codebase
is a flat `{ "code": "..." }`, no second field), and generalizes the same way: a new constrained
param on a future tool gets `"<param_name>_exceeds_mandate"` for free, no new shape to design.
`GetBalanceTool` has no parameters, so this check doesn't apply there — its `toolConstraints()`
entry (if any) is simply never consulted.

---

## 9. Isolated security filter on `/mcp/**`

A second `SecurityFilterChain`, `@Order(1)` (before the Keycloak chain, which becomes
`@Order(2)` with an explicit `securityMatcher` so it no longer catches `/mcp/**`):

```java
http.securityMatcher("/mcp/**")
    .csrf(csrf -> csrf.disable())
    .sessionManagement(s -> s.sessionCreationPolicy(STATELESS))
    // The real authorization decision is entirely inside MandateDpopFilter, including the
    // initialize/notifications/initialized/tools/list exemption below — this rule just satisfies
    // Spring Security's requirement that the chain have one.
    .authorizeHttpRequests(a -> a.anyRequest().permitAll())
    .addFilterBefore(new MandateDpopFilter(deps...), BearerTokenAuthenticationFilter.class);
```

> Spike correction ([`spike-notes.md`](spike-notes.md)): in the `2025-11-25` shape there is **no**
> unauthenticated "`GET /mcp` discovery handshake" — `GET /mcp` is the session-bound SSE stream and
> it carries the same `Authorization: DPoP` + `DPoP` headers as the POSTs, so authenticate it too.
> `tools/list` requires an established session (`initialize` first). The **first** POST
> (`initialize`) arrives with **no** `MCP-Protocol-Version` and no `Mcp-Session-Id` — the filter
> must tolerate both being absent on that first request. (If `protocol=STATELESS` is adopted at
> §8, there is no GET stream and no session — every request is an independent authenticated POST.)
>
> **Discovery exemption, done 2026-09-25.** §8 already says "discovery (`tools/list`) is left
> public for the POC" — the platform stub's registration-time `POST /discover` (contracts §5.2)
> calls a not-yet-mandated PDS's `initialize`→`notifications/initialized`→`tools/list` with no
> auth at all, since there's nothing to grant a mandate over until the tool catalog is known. A
> post-implementation review found this was documented but never actually wired into
> `MandateDpopFilter`, which silently broke that live registration flow. Fixed by exempting all
> three JSON-RPC methods from every one of the 19 steps — not just `tools/list`, since the
> Streamable HTTP handshake is ordered and a caller can't reach `tools/list` without completing
> `initialize` first. `tools/call` is never exempt.

`MandateDpopFilter` runs the **19-step** check from [contracts §2](../contracts.md) **in that
exact order** (steps 1–13 = JWT + DPoP + tool; steps 14–18 = account-link assertion re-verify,
§7.4; step 19 = build principal). Components:

| Concern | Implementation |
|---|---|
| Discovery exemption | before step 1: parse the JSON-RPC body, and if `method` ∈ `{initialize, notifications/initialized, tools/list}`, call the chain directly — no verification, no audit row, no principal |
| Delegation JWT verify | lazily-built `NimbusJwtDecoder.withJwkSetUri(platform.jwksUri)`, `RS256`, cache JWKS; validators for `iss == expected-iss`, `aud == canonical-uri`, `exp/nbf` with 60 s skew, header `typ == at+jwt` |
| Introspection | `RestClient` GET `${introspect-base}/${jti}`; timeout 2 s; only `active==true` passes; any non-200 / 404 / IOException / timeout → deny `introspection_unreachable`. Never cache a positive result across calls (V1 = check every call) |
| `cnf` thumbprint | `JWK.parse(cnf.jwk).computeThumbprint()` (RFC 7638, SHA-256) |
| DPoP proof | `SignedJWT.parse(header "DPoP")`; assert `typ==dpop+jwt`, `alg==EdDSA`; `Ed25519Verifier(OctetKeyPair from header jwk)`; then compare thumbprint(header.jwk) to `cnf` thumbprint |
| `htu`/`htm` | rebuild canonical URL from the request (scheme+host+path, drop query); compare |
| `bsha` | wrap the request in a `ContentCachingRequestWrapper` (or read once and re-inject); `base64url(SHA-256(body bytes))`; compare |
| Replay | in-memory `Caffeine<String,Boolean>` expireAfterWrite = `replay-ttl-seconds`; `getIfPresent` → deny; else `put` |
| Tool allow-list | parse the JSON-RPC body: for `method=="tools/call"`, `params.name` must be in `disclosed_scope.allowed_tools` |
| `tool_constraints` extraction (contracts §1.1, added 2026-10-12) | read `disclosed_scope.tool_constraints` (a `Map<String, Map<String, Object>>`, absent → `Map.of()`) and carry it **opaquely** into the principal — this filter never interprets a param name or cap value here, only reshapes the raw JSON. The actual comparison against a call's arguments happens in that tool's own handler (§8), not here |
| **Account-link assertion** (steps 14–18) | `SignedJWT.parse(provider_account_ref.assertion)`; `alg==EdDSA`; verify against the **locally held** `bqt-assertion-1` public key (§7.1, not fetched); `iss==linking.provider-id`; `aud==platform.expected-iss`; `assertion.sub == provider_account_ref.value`; `provider_jkt == thumbprint(bqt-assertion-1)`; `asserted_at == assertion.iat`; `assertion.iat ≤ token.iat ≤ assertion.exp + 60 s`. Fail codes: `account_ref_assertion_invalid` / `account_ref_value_mismatch` / `account_ref_jkt_mismatch` / `account_ref_stale` |
| Principal | on success set an `Authentication` whose principal carries `provider_account_ref.value`, `sub`, `agent_jkt`, `allowed_tools`, `tool_constraints` |
| Audit on failure | write `mcp_call_audit` (`decision=DENY`, `deny_reason=<code>`) and return `WWW-Authenticate: DPoP error="<code>"` with `401`/`403` per the table |

**Attention points**

- Body is needed twice (bsha check, then the MCP handler). Use `ContentCachingRequestWrapper`
  or a small caching filter — do not consume the stream.
- Streamable HTTP (`2025-11-25`) issues `POST /mcp` for messages **and** `GET /mcp` for the
  session-bound SSE stream — authenticate **both** (spike correction above). Tolerate the first
  `initialize` POST having no `MCP-Protocol-Version` / `Mcp-Session-Id`.
- `htu` behind the compose network: the request arrives at `pds:8081` but the canonical
  `htu`/`aud` the client signed is `http://localhost:8081/mcp`. Compare against
  `MCP_CANONICAL_URI`, **not** the container-local URL.
- Keep the two chains' `securityMatcher`s disjoint — a request must hit exactly one.
- Nimbus Ed25519: confirm in the spike that `Ed25519Verifier` works without BouncyCastle on
  JDK 21; add `tink`/`bcprov` only if it does not.

---

## 10. Test / scenario matrix

**Done (2026-09-19).** S1 and S4 are live-verified end-to-end against the real stack (real
mandate → real outil-local → real PDS); S2/S3/S5–S9/S14/S15 have a dedicated unit-test class,
`MandateDpopFilterTest`, driving `MandateDpopFilter` directly with hand-forged tokens/proofs
against an in-process platform test double (own RSA test key) — see
[`../step-6-checklist.md`](../step-6-checklist.md). S10 is covered in `GetBalanceToolTest` /
`ListTransactionsToolTest`. `S1'`/`S1''` and S14/S15's exact assertions below are not all
separately automated (`htu` mismatch and proof staleness are exercised implicitly by the
builders' defaults, not as their own negative cases) — worth adding if this matrix grows further.

| Scenario ([contracts §7](../contracts.md)) | Level | Assertion |
|---|---|---|
| S1 happy path | integration + unit | `200`, correct balance for `pacr_bqt_2c8d40`, `mcp_call_audit ALLOW` |
| S2 stolen token / no key | unit | proof signed by a different key → `403 pop_key_mismatch` |
| S3 expired | unit | `exp` in the past → `401 token_expired`, introspection not called |
| S4 revoked | integration | stub `revoke` then call → `403 revoked_or_unknown` |
| S5 wrong `aud` | unit | `aud=http://localhost:9999/mcp` → `403 aud_mismatch` |
| S6 replay | unit | same proof `jti` twice → 2nd `403 dpop_replay` |
| S7 tampered body | unit | body altered post-sign → `403 body_hash_mismatch` |
| S8 introspection down | unit | introspect endpoint unreachable → `403 introspection_unreachable` |
| S9 tool not allowed | unit | `allowed_tools:["get_balance"]`, call `tools/call name=list_transactions` → `403 tool_not_allowed` |
| S10 unknown account | integration | token ref with no `account_link` row → MCP error `unknown_account` |
| S18 tool constraint exceeded (contracts §1.1, added 2026-10-12) | unit (`ListTransactionsToolTest`) | mandate's `tool_constraints.list_transactions.max_results`/`.period` set below the request's effective value → `{ "code": "max_results_exceeds_mandate" }` / `{ "code": "period_exceeds_mandate" }`, `mcp_call_audit DENY`. Enforced in `ListTransactionsTool`, not `MandateDpopFilter` |
| S14 tampered assertion | unit | assertion signature byte-flipped → `403 account_ref_assertion_invalid` |
| S15 assertion/value mismatch | unit | `provider_account_ref.value` changed, assertion itself untouched → `403 account_ref_value_mismatch` |
| S1' `htu` mismatch | unit | proof `htu` with a query string / wrong path → `403 dpop_htu_htm_mismatch` |
| S1'' stale proof | unit | proof `iat` 5 min old → `403 dpop_stale` |
| S14' wrong assertion key | unit | assertion signed by a non-`bqt-assertion-1` key → `403 account_ref_assertion_invalid` |
| S14'' jkt mismatch | unit | `provider_jkt` ≠ thumbprint(own key) → `403 account_ref_jkt_mismatch` |
| S7 (assert endpoint) | integration | `POST /account-link/assert` without `X-Poc-Dev-Auth` → `401 poc_dev_auth_required`; with it, unknown customer → `400 unknown_customer`; valid → JWS verifies against `/pds-jwks.json` |

---

## 11. Local run (no compose)

```
# 1. PDS's own Keycloak (bqt realm) — from deploy/, or the base docker-compose adapted
podman run -p 8080:8080 -v $PWD/docker/realm-export.json:/opt/keycloak/data/import/bqt-realm.json \
  quay.io/keycloak/keycloak:26.0 start-dev --import-realm

# 2. platform stub (for JWKS + introspection) — see platform/spec.md
# 3. PDS
./mvnw spring-boot:run

# demo step 1 — bank-Keycloak token, existing-style endpoint
TOKEN=$(curl -s -X POST http://localhost:8080/realms/bqt/protocol/openid-connect/token \
  -d grant_type=password -d client_id=bqt-rest -d client_secret=bqt-secret \
  -d username=pieter -d password=demo | jq -r .access_token)
curl -H "Authorization: Bearer $TOKEN" http://localhost:8081/accounts/me

# MCP route — discovery is exempt from the isolated filter (§8/§9), so this needs no auth.
# NOT the inspector CLI: its client opens a GET /mcp stream the filter correctly rejects with
# no mandate, failing even though the route is fine (pds/TESTING.md §7 has the full sequence).
curl -s -X POST http://localhost:8081/mcp -H 'Content-Type: application/json' \
  -H 'Accept: application/json, text/event-stream' \
  -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"quickstart","version":"0.0.1"}}}'
```
