diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 1d7059a..a26a785 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -82,9 +82,20 @@ Every request needs a JWT bearer token for the audience `rimbank-api`, except th - **Locally**, the AppHost runs Keycloak with the dev-only realm `rimbank` from `src/RimBank.AppHost/Realms`. Get a token with the client-credentials grant of `rimbank-dev-client`, as `src/RimBank.Host/RimBank.Host.http` and the realm's README show. Its secret is published and only for local use. - **Outside Development**, the host needs `Authentication:Authority`, the HTTPS address of the realm (for example `https://login.example.com/realms/rimbank`). Without it, the host refuses to start. MCP clients are sent to the same address unless `Mcp:AuthorizationServer` (also HTTPS) says otherwise ([ADR 0022](docs/adr/0022-mcp-authorization-and-tool-errors.md)). -- **Deny by default:** never call `AllowAnonymous()` or use `[AllowAnonymous]`. New endpoints are protected without opting in, and the architecture rule `allow-anonymous-only-in-service-defaults` fails otherwise. Narrow access with `RequireAuthorization(...)` (per-operation policies come in roadmap 1.15). +- **Deny by default:** never call `AllowAnonymous()` or use `[AllowAnonymous]`. New endpoints are protected without opting in, and the architecture rule `allow-anonymous-only-in-service-defaults` fails otherwise. Do not add your own `RequireAuthorization(...)` to a BIAN endpoint. Use the operation policies below. +- **Scopes and operation policies** ([ADR 0038](docs/adr/0038-per-operation-authorisation-policies.md)): + - Each context has two scopes: `:read` for its `Retrieve` queries and `:write` for its commands, for example `party-reference-data-directory:read`. + - A new BIAN endpoint calls `.RequireOperation(OperationId)` in place of `.WithName(OperationId)`. + - The context's host module registers the operation in `AddOperationPolicies`, with `AddCommand(OperationId, WriteScope)` or `AddQuery(OperationId, ReadScope)`. + - `OperationAuthorizationCoverageTests` fails when either step is missing, or when the kind does not match the verb (`GET` is a query). + - A token without the scope gets a 403 `shared.forbidden`, before the `Idempotency-Key`, `If-Match` and 404 checks. +- **Dev realm scopes:** + - Both dev clients get both Party scopes by default. + - To try a denied call, edit the client's default scopes in the Keycloak admin console. + - The realm declares its own client scopes, so it carries only `basic` (`sub`), `profile` and `email` (no claims) and the operation scopes. + - Keycloak imports the realm only on its first start. After a realm change, remove the volume `rimbank-keycloak-data` (`docker volume rm rimbank-keycloak-data`) and restart the AppHost. - **Caller:** the host turns the token's `sub` and `azp` into an `Actor` (SharedKernel) and hands the subject to the message bus. Adapters and cores never read the token. -- **Tests** sign tokens with an in-memory key: call `builder.UseTestTokens()` and send `TestTokens.Issue()` (in `tests/RimBank.Host.Tests/Security`). +- **Tests** sign tokens with an in-memory key: call `builder.UseTestTokens()` and send `TestTokens.Issue()` (in `tests/RimBank.Host.Testing`). It grants every operation scope unless you pass `scopes:` (`[]` grants none). ### MCP diff --git a/docs/adr/0014-host-composition-and-module-entry-point.md b/docs/adr/0014-host-composition-and-module-entry-point.md index b55f88d..da7e0f0 100644 --- a/docs/adr/0014-host-composition-and-module-entry-point.md +++ b/docs/adr/0014-host-composition-and-module-entry-point.md @@ -60,6 +60,7 @@ The rules govern hand-written code, so types a source generator emits with `[Gen - Adding a context to the host is one new file under `RimBank.Host/Modules//` and one line in `ServiceDomainModules.All`. The CONTRIBUTING checklist for a new context says so. - Since [ADR 0021](0021-mcp-wiring-and-tool-conventions.md), `IServiceDomainModule` has a third member, `AddMcpTools(IMcpServerBuilder)`. The host calls it in list order, after every `AddServices`, so a context registers its MCP tools on the host's single `/mcp` server. +- Since [ADR 0038](0038-per-operation-authorisation-policies.md), `IServiceDomainModule` has a fourth member, `AddOperationPolicies(OperationPolicies)`. The host calls it in list order, after every `AddServices` and before `AddMcpTools`, so a context registers the authorisation policy of each of its BIAN operations. - The host project references every context's adapters, as §4 already allows. Contexts stay unaware of the host, and the architecture rules enforce it. - The probes are public in production. They reveal only a status word, so this is acceptable. If a deployment needs more detail, it gets a separate, authenticated endpoint, decided in its own ADR. - `RimBank.AppHost.Tests` starts real containers. In CI it always runs; locally it is skipped with a clear reason when Docker is not reachable. It removes the PostgreSQL data volume, so it runs on a throwaway database and never touches a developer's data. diff --git a/docs/adr/0019-authentication-baseline.md b/docs/adr/0019-authentication-baseline.md index 103f10a..ff999fc 100644 --- a/docs/adr/0019-authentication-baseline.md +++ b/docs/adr/0019-authentication-baseline.md @@ -59,7 +59,7 @@ How the caller reaches the idempotency policy, which runs on the message bus, no - Two callers using the same idempotency key no longer replay, refuse or block each other. Messages without a caller (later `.Subscriptions`, scheduled messages) share the system scope, and their keys come from record identifiers (§8.4). - The caller's subject also lands in Marten's last-modified-by and on the trace as `enduser.id`. The subject is opaque, but it is still a personal identifier: it is never logged at Information level by RimBank code, and tokens never appear in responses or logs. - Deferred: - - Per-BIAN-operation authorisation policies and separate command and query scopes (1.15). + - Per-BIAN-operation authorisation policies and separate command and query scopes (1.15, done in [ADR 0038](0038-per-operation-authorisation-policies.md): a read and a write scope per context, one policy per operation, and the dev realm's client scopes). - MCP authorization through Keycloak, and relaying the MCP caller the same way (0.16, done in [ADR 0022](0022-mcp-authorization-and-tool-errors.md): `/mcp` is challenged with `resource_metadata`, the MCP scheme serves the RFC 9728 metadata, the dev realm gains `rimbank-mcp-client` and `rimbank-developer`, and tool calls relay the caller through `ActorRelay` unchanged). - Recording the `Actor` (subject and client) in event metadata for audit (with the first events, 1.x; audit query in 7.3). - A production identity-provider setup, Keycloak deployment and key rotation runbook (7.x). diff --git a/docs/adr/0022-mcp-authorization-and-tool-errors.md b/docs/adr/0022-mcp-authorization-and-tool-errors.md index 0b189cc..a4d81d8 100644 --- a/docs/adr/0022-mcp-authorization-and-tool-errors.md +++ b/docs/adr/0022-mcp-authorization-and-tool-errors.md @@ -78,7 +78,7 @@ The realm also gains the user `rimbank-developer` (password `rimbank-developer-l - Deployments must set `Authentication:Authority` (already required by ADR 0019) or `Mcp:AuthorizationServer` to an HTTPS realm address. - Amends [ADR 0019](0019-authentication-baseline.md) (the MCP challenge and metadata; the dev MCP client and user) and [ADR 0021](0021-mcp-wiring-and-tool-conventions.md) (its error contract is now implemented here, and the 0.16 follow-ups are done). - Follow-ups: - - **1.15:** per-operation scopes in `scopes_supported` and on tools, through the SDK's authorization filters (`AddAuthorizationFilters`, `[Authorize]`). + - **1.15:** per-operation scopes in `scopes_supported` (done in [ADR 0038](0038-per-operation-authorisation-policies.md)). The policies on tools, through the SDK's authorization filters (`AddAuthorizationFilters`, `[Authorize]`), come with the first tools in 1.16. - **1.16:** the first `.Mcp` adapter uses `ToToolResult`, and HTTP/MCP parity tests compare its Problem Details with the `.Api`'s. - **4.14:** the money-moving scope. - **7.x:** forwarded headers for the `resource` address, the production identity provider, and RFC 8707 if it becomes available there. diff --git a/docs/adr/0038-per-operation-authorisation-policies.md b/docs/adr/0038-per-operation-authorisation-policies.md new file mode 100644 index 0000000..6f330cb --- /dev/null +++ b/docs/adr/0038-per-operation-authorisation-policies.md @@ -0,0 +1,77 @@ +# 0038. Per-operation authorisation policies + +- Status: Accepted +- Date: 2026-11-09 +- Roadmap phase: 1.15 + +## Context + +The quality bar says "authorised per BIAN operation" ([mission](../../specs/mission.md), quality bar "Security"). Principle 6 says an AI agent gets the same authorisation as any other consumer. [Tech-stack §10](../../specs/tech-stack.md#10-security--supply-chain) defines policies per BIAN operation, and §6 has MCP tool calls go through the same policies. + +Until 1.15, every Party endpoint only needed an authenticated caller, through the fallback policy of [ADR 0019](0019-authentication-baseline.md). The 403 `shared.forbidden` Problem Details existed, but nothing produced it. ADR 0019 left per-operation policies and separate command and query scopes to this phase. [ADR 0022](0022-mcp-authorization-and-tool-errors.md) left `scopes_supported` in the MCP protected-resource metadata to it as well. + +The [BIAN OpenAPI](../../doc-0/release14.0.0/apis-iso20022_ext-ddd/oas3/yamls/PartyReferenceDataDirectory.yaml) declares a 403 on every operation, but no security scheme and no scopes. The scope names are therefore RimBank's own. + +The Party Reference Data Directory has 13 operations: 8 commands (Register, Update, Demographics Update and Exchange, Reference Update, Associations Register and Update, BankRelations Update) and 5 `Retrieve` queries. + +## Options considered + +**Scope granularity** +1. **Per context, read and write.** Two scopes follow the command/query split of [ADR 0003](0003-separate-commands-and-queries.md), and a context's scopes are its own. +2. One scope per operation: 13 scopes today, and more with every Behavior Qualifier. +3. Read and write per Behavior Qualifier: 10 scopes, separating the PII-heavy Reference from the rest. No consumer needs that yet. +4. Global `rimbank:read` / `rimbank:write`. This does not isolate contexts and gives no pattern for the money-moving scope of 4.14. + +**Where the check runs** +1. **An ASP.NET Core authorization requirement in the host, on a policy named by the operation.** HTTP endpoints and, from 1.16, MCP tools (the SDK's `[Authorize]` filters) refer to the same policy. +2. Policies on two route groups, one for commands and one for queries. Less code, but there is no per-operation policy to split later. +3. Wolverine middleware on `ICommand` / `IQuery`. It would cover both channels, but it puts token concepts next to the cores, which ADR 0019 rules out. + +## Decision + +**Scopes (option 1).** Each context has `:read`, needed by its queries, and `:write`, needed by its commands. For this context they are `party-reference-data-directory:read` and `party-reference-data-directory:write`, the constants `ReadScope` and `WriteScope` of `PartyReferenceDataDirectoryModule`. + +**One policy per BIAN operation, named by its operation id.** Examples are `PartyReferenceDataDirectoryEntry/Register` and `Associations/Retrieve`, the same name as the endpoint (`WithName`). Each policy requires an authenticated user and one scope. A later phase can give a single operation its own scope by changing only its registration. + +**Registration by the module.** `IServiceDomainModule` gains a fourth member, `AddOperationPolicies(OperationPolicies)`. This amends [ADR 0014](0014-host-composition-and-module-entry-point.md). +- The host calls it for every module, in list order, after every `AddServices` and before `AddMcpTools`. +- A module declares each operation once, as a command (`AddCommand(operationId, WriteScope)`) or a query (`AddQuery(operationId, ReadScope)`). +- The registrations make up an `OperationPolicyCatalog`, a singleton in the host. +- An operation registered twice, or a scope with whitespace, stops the host from starting. +- Policy names share the host-wide namespace of endpoint names. If two contexts ever have the same operation id, both the endpoint names and the policies clash at startup, and the newer context qualifies its ids. + +**Endpoints.** `RequireOperation(operationId)` lives in the root conventions of `RimBank.Api`, next to `RequireIdempotencyKey`. It names the endpoint, requires the policy of that name and declares the 403 response, and every BIAN endpoint calls it in place of `WithName`. A policy name with no registration makes ASP.NET Core fail the request, so a mistake can never fall back to "authenticated only". + +**The check.** The `OperationScopeRequirement` is met by `OperationScopeAuthorization`. It reads the `scope` claim (RFC 9068, as Keycloak issues it, with `MapInboundClaims = false`) as a space-separated list and needs an exact, case-sensitive match. A prefix or a longer scope does not count. The type's name does not end in `Handler`, because Wolverine would take such a type in the host assembly for a message handler. + +**Order of the answers.** +- No token or an invalid token: 401, as before. +- An authenticated token without the scope: 403 `shared.forbidden`, from the existing status-code pages ([ADR 0015](0015-problem-details-mapping.md)). Authorization runs before endpoint filters and binding, so a denied command is refused before its `Idempotency-Key` 400 and its `If-Match` 428, and before any outcome or event is stored. A denied query is refused before its 404, so a caller without the read scope cannot probe which records exist. + +**MCP.** The protected-resource metadata lists the catalog's distinct scopes in `scopes_supported` (amends ADR 0022), so an MCP client knows which scopes to request. The tools of 1.16 use the same policy names through the SDK's authorization filters. + +**Dev realm** (amends ADR 0019). +- `rimbank-realm.json` declares the two scopes as client scopes, with `include.in.token.scope` on. +- They are default client scopes of `rimbank-dev-client` and `rimbank-mcp-client`, so local flows get both. +- A realm import that lists its own client scopes gets none of Keycloak's built-in ones. Checked on Keycloak 26.6, a user's token then loses `sub` (so every call is `shared.actor-invalid`), and a client asking for `openid profile email` gets `invalid_scope`. So the realm also declares three of them: + - `basic`, holding only the `sub` mapper, as a default scope of both clients; + - `profile` and `email`, with no mappers, as optional scopes of the MCP client. Clients may request them, but RimBank tokens carry no name, email or other personal data. +- The other built-in scopes (`roles`, `web-origins`, `acr`, `address`, `phone`) are not declared, because RimBank reads none of their claims. `offline_access` exists, but Keycloak refuses it (`not_allowed`) for the dev user. MCP clients sign in again when the token expires. +- A Keycloak data volume created before 1.15 keeps the old realm. Remove the volume `rimbank-keycloak-data` to import the new one (CONTRIBUTING "Authentication"). + +## Consequences + +- A new BIAN endpoint calls `RequireOperation(OperationId)`, and its context's module registers the operation as a command or a query. CONTRIBUTING "Authentication" says so, and `OperationAuthorizationCoverageTests` fails when one of the two is missing, when the kind does not match the HTTP verb (`GET` is a query on the read scope, every other verb a command on the write scope), or when a policy protects no endpoint. +- Test tokens grant every catalog scope by default (`TestTokens.Issue(scopes: …)`), so tests that are not about authorisation keep working. Denial tests pass explicit scopes. +- Deployments must grant callers the scopes they need. A token without any RimBank scope can no longer call a BIAN operation. +- Follow-ups: + - **1.16 / 1.17:** each MCP tool carries its operation's policy (`[Authorize(Policy = …)]` with `AddAuthorizationFilters`), and a test checks that the tool and the endpoint share it. + - **4.14:** the money-moving scope, a third scope next to read and write for the Deposit and Payment operations. + - **7.2 / later:** resource-level authorisation (which party a caller may see) is not part of this decision. + - **7.x:** scope provisioning in the production identity provider. +- Proven by: + - `tests/RimBank.Host.Tests/Security/OperationPolicyTests`: exact match, prefix, longer and other-case scopes, 401 before 403, the catalog, and duplicate registration; + - `tests/RimBank.Host.Tests/Mcp/McpAuthorizationTests`: `scopes_supported`; + - `tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/AuthorisationTests`: the 13 operations with the other kind's scope, with no scope and with no token, nothing stored after a denied command, and the write scope alone registering while the read scope alone retrieves; + - `tests/RimBank.Api.Tests/OperationAuthorizationCoverageTests`; + - `tests/RimBank.AppHost.Tests/Model/DevRealmTests`: the dev clients' scopes. diff --git a/specs/2026-11-09-party-authorisation-policies/plan.md b/specs/2026-11-09-party-authorisation-policies/plan.md new file mode 100644 index 0000000..9b435c0 --- /dev/null +++ b/specs/2026-11-09-party-authorisation-policies/plan.md @@ -0,0 +1,49 @@ +# Plan: Authorisation policies + +Order: ADR first, then the host policy machinery with its tests, then the module convention and Party registration, then the endpoints, then the dev realm and docs. The solution builds and all tests pass after each group. Until group 4, `TestTokens` issues every scope, so the existing tests are unaffected. + +## 1. ADR and constitution +- [ ] `docs/adr/0038-per-operation-authorisation-policies.md`, as decided in requirements.md. +- [ ] Amend the Consequences of ADR 0014 (module gains `AddAuthorizationPolicies`), ADR 0019 (1.15 follow-up done, realm scopes) and ADR 0022 (`scopes_supported`; tool `[Authorize]` in 1.16). +- [ ] tech-stack §10: scope naming and "one named policy per BIAN operation, registered by the module". §6: MCP tools use the same policy names. + +## 2. Scope requirement and policy registration (host) +- [ ] `src/RimBank.Host/Security/OperationScopeRequirement.cs` with `OperationScopeHandler`: it splits the `scope` claim on whitespace and requires an exact match. +- [ ] `src/RimBank.Host/Security/OperationPolicies.cs`: `AuthorizationBuilder` extensions `AddCommand(operationId, scope)` and `AddQuery(operationId, scope)`. Each adds a policy named by the operation id that requires an authenticated user and the scope. It also records the operation's kind and scope in an `OperationPolicyCatalog` singleton, used by the MCP metadata and the coverage guard. +- [ ] Register the handler in `AddRimBankAuthentication`. +- [ ] Unit/host tests in `tests/RimBank.Host.Tests/Security/OperationPolicyTests.cs`, with a fake module and fake endpoints: + - the scope is present → allowed; + - the scope is missing, or `scope` holds only a prefix or superstring (`…:reader`) → 403 `shared.forbidden`, `application/problem+json`; + - no token → 401; + - the same operation id registered twice → the host refuses to start. + +## 3. Module convention +- [ ] `IServiceDomainModule.AddAuthorizationPolicies(AuthorizationBuilder policies)`, called for every module from `ServiceDomainModuleComposition`, in list order. Update the fake modules in `RimBank.Host.Tests`. +- [ ] `PartyReferenceDataDirectoryModule`: the constants `ReadScope` / `WriteScope`. It registers 8 commands with `AddCommand(…OperationId, WriteScope)` and 5 queries with `AddQuery(…OperationId, ReadScope)`, using each endpoint's `OperationId` constant. +- [ ] `McpComposition` / `AuthenticationComposition`: `ProtectedResourceMetadata.ScopesSupported` = the distinct scopes in the catalog. Extend the existing `McpAuthorizationTests` metadata assertion. + +## 4. Endpoints +- [ ] `src/RimBank.Api/OperationAuthorization.cs`: `RequireOperation(this RouteHandlerBuilder, string operationId)` → `.WithName(operationId).RequireAuthorization(operationId)`. +- [ ] Replace `.WithName(OperationId)` with `.RequireOperation(OperationId)` and add `.ProducesProblem(StatusCodes.Status403Forbidden)` in all 13 endpoints under `src/RimBank.Api/Party/PartyReferenceDataDirectory/`. +- [ ] Check that the OpenAPI document test and the BIAN conformance tests still pass (403 is declared by BIAN, so it needs no deviation). + +## 5. Test tokens and HTTP authorisation tests +- [ ] `tests/RimBank.Host.Testing/TestTokens.cs`: an `IEnumerable? scopes` parameter on `Issue`. By default it issues every catalog scope, and `[]` issues none. Add the `scope` claim as one space-separated string. +- [ ] `tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/AuthorisationTests.cs` (Alba on `PartyApiHost`), parameterised over the 13 operations: + - a read-only token on a command → 403 `shared.forbidden`, also without `Idempotency-Key` or `If-Match` (403 comes before 400/428); + - a write-only token on a query → 403, also for an unknown id (403 comes before 404); + - a read token on a query → 200 or 404 as usual; + - a write token on a command → the usual success; + - no token → 401. + - The test also checks that nothing was appended to the stream after a 403 command. +- [ ] `tests/RimBank.Api.Tests/OperationAuthorizationCoverageTests.cs` (the coverage guard): enumerate every `RouteEndpoint` with an `EndpointNameMetadata`, except the health probes and the dev-only OpenAPI/Scalar endpoints, and check: + - it carries exactly one `AuthorizeAttribute` policy equal to its name; + - the catalog has that operation; + - `GET` ⇔ query ⇔ read scope, and every other verb ⇔ command ⇔ write scope; + - every catalog operation is mapped by some endpoint (no orphan policies). + +## 6. Dev realm and contributor docs +- [ ] `src/RimBank.AppHost/Realms/rimbank-realm.json`: client scopes `party-reference-data-directory:read` and `:write` (`openid-connect`, `include.in.token.scope: true`), added to the `defaultClientScopes` of `rimbank-dev-client` and `rimbank-mcp-client`. The AppHost startup test stays green. +- [ ] CONTRIBUTING "Authentication": the scopes, how a new BIAN endpoint is protected (`RequireOperation` and the module's `AddCommand`/`AddQuery`), and how to request a token with fewer scopes. +- [ ] Tick roadmap 1.15. +- [ ] `dotnet format --verify-no-changes` and the full test run. diff --git a/specs/2026-11-09-party-authorisation-policies/requirements.md b/specs/2026-11-09-party-authorisation-policies/requirements.md new file mode 100644 index 0000000..33e0b22 --- /dev/null +++ b/specs/2026-11-09-party-authorisation-policies/requirements.md @@ -0,0 +1,57 @@ +# Authorisation policies + +Roadmap phase: 1.15 +Branch: plan/1.15-party-authorisation-policies + +## Context +The quality bar requires access to be "authenticated by default, authorised per BIAN operation" ([mission.md](../mission.md), quality bar "Security"; principle 6: an AI agent gets the same authorisation as any other consumer). Tech-stack §10 says "Authorisation policies are defined per BIAN operation", and §6 says MCP tool calls go through the same per-operation policies as HTTP. Today every Party endpoint only needs an authenticated caller, through the fallback policy of [ADR 0019](../../docs/adr/0019-authentication-baseline.md). The 403 `shared.forbidden` Problem Details response exists, but nothing triggers it yet. + +ADR 0019 and [ADR 0022](../../docs/adr/0022-mcp-authorization-and-tool-errors.md) both leave this phase as a follow-up: per-operation policies, separate command and query scopes, and `scopes_supported` in the MCP protected-resource metadata. The BIAN spec ([PartyReferenceDataDirectory.yaml](../../doc-0/release14.0.0/apis-iso20022_ext-ddd/oas3/yamls/PartyReferenceDataDirectory.yaml)) declares a `403` on every operation but defines no security scheme or scopes, so the scope names are RimBank's own decision. + +Depends on 0.13 (authentication, `TestTokens`), 0.16 (MCP authorization), and 1.5–1.12 (the 13 Party endpoints). All are merged. It unblocks 1.16/1.17: their MCP tools take the same named policies through `[Authorize(Policy = …)]`. It also sets the pattern that 4.14 reuses for the money-moving scope. + +**CQRS split** (tech-stack §8): the policy follows the operation's role. **Commands** (Register, Update, Exchange, and the Register/Update of each BQ: 8 operations) require the context's **write** scope. **Queries** (the 5 `Retrieve` operations, `GET`) require its **read** scope. Commands, queries, handlers and read models do not change. Authorisation runs in front of the adapter, so no read model is added or changed and there is no projection work. + +## Scope +### In scope +- **Two scopes for the context:** `party-reference-data-directory:write` (commands) and `party-reference-data-directory:read` (queries). +- **One named policy per BIAN operation.** The policy name is the operation id, for example `PartyReferenceDataDirectoryEntry/Register`. Each policy requires one of the two scopes. Because every operation has its own policy, a later phase can give one operation its own scope without touching any endpoint. +- **Scope check:** an `OperationScopeRequirement` and its handler in `RimBank.Host/Security/`. The handler reads the space-separated OAuth `scope` claim (RFC 8693/9068, as Keycloak issues it). It never matches substrings. +- **Module convention:** `IServiceDomainModule` gets `AddAuthorizationPolicies(AuthorizationBuilder)`. `PartyReferenceDataDirectoryModule` declares its 13 operations, each as a command or a query, through a host helper (`policies.AddCommand(operationId, writeScope)` / `AddQuery(operationId, readScope)`). +- **Endpoint helper:** `RequireOperation(operationId)` in the root conventions of `RimBank.Api` (namespace `RimBank.Api`, next to `RequireIdempotencyKey`). It does `.WithName(operationId)` and `.RequireAuthorization(operationId)`. All 13 Party endpoints use it in place of `.WithName(OperationId)`, and each declares `.ProducesProblem(403)`. +- **403 behaviour:** a token without the required scope gets 403 `shared.forbidden` Problem Details, from the existing status-code pages. On a command this happens before the `Idempotency-Key` and `If-Match` checks, and on a query before the 404. +- **MCP metadata:** `scopes_supported` in the protected-resource metadata lists the scopes of every module's policies. +- **Dev realm:** both scopes are added as client scopes in `rimbank-realm.json` (`include.in.token.scope: true`). They are default scopes of `rimbank-dev-client` and `rimbank-mcp-client`, so local flows keep working. +- **Test tokens:** `TestTokens.Issue(scopes: …)`. By default it issues every scope the host knows, so existing tests stay green. Denial tests pass explicit scopes. +- **Docs:** ADR 0038; tech-stack §6 and §10 (scope naming and the per-operation policy convention); CONTRIBUTING "Authentication" (a new BIAN endpoint calls `RequireOperation` and its module registers the policy); ADR 0014, 0019 and 0022 consequences amended. + +### Out of scope +- MCP tools and their `[Authorize]` policies, through the SDK's `AddAuthorizationFilters`: added with the tools in **1.16/1.17**. +- One scope per operation or per BQ: possible later without endpoint changes, but not needed now. +- Resource-level authorisation (who may read *which* party): not in Stage 1, and later with PII protection (**7.2**) or KYC contexts. +- The money-moving scope and default-off tools (**4.14**). +- An ArchUnit rule for the convention: the runtime coverage guard is enough (user's choice). +- A manual Keycloak `.http` demo with a read-only token (not chosen; the CONTRIBUTING text explains how to request fewer scopes). +- Production IdP scope provisioning (**7.x**). + +## Decisions +| Decision | Choice | Rationale | +|---|---|---| +| Scope granularity | Per context, read and write: `party-reference-data-directory:read` / `:write` | User's choice. It matches the command/query split of §8 and keeps contexts isolated. It also leaves room for a dedicated money-moving scope (4.14). | +| Policy unit | One named policy per BIAN operation, named by its operation id | Meets "authorised per BIAN operation" literally. A later scope split changes only the module's registration. MCP tools reuse the same names in 1.16. | +| Command/query kind | Declared once, in the module's registration (`AddCommand` / `AddQuery`) | One place per context. The coverage guard cross-checks it against the HTTP verb (`GET` = query, as the conformance harness does, ADR 0020). | +| Where scopes are checked | An ASP.NET Core authorization requirement in `RimBank.Host/Security` | ADR 0019: cores and adapters never read the token. A bus middleware was rejected because it would put token concepts next to the cores. | +| Scope claim format | The space-separated `scope` claim (`MapInboundClaims = false`), split on whitespace with exact matches | Keycloak and RFC 9068 issue scopes this way. `RequireClaim` would compare the whole string. | +| Endpoint wiring | `RequireOperation(operationId)` in the `RimBank.Api` root, replacing `.WithName` | One call names the endpoint and protects it, so a name without its policy is hard to write by accident. `RimBank.Http` no longer exists (ADR 0025). | +| Unknown policy name | ASP.NET Core fails the request when a policy is missing, and the coverage guard catches it in CI | A mistake can never silently fall back to "authenticated only". | +| Dev realm scopes | Default client scopes on both dev clients | `aspire run`, MCP Inspector and Claude Code keep working with no change. Tests prove the denial paths with signed tokens. | + +## ADRs to write +- **0038 Per-operation authorisation policies.** Covers the scope naming (`:read|write`), one policy per BIAN operation named by its id, the module registration convention (amends ADR 0014), the scope requirement and claim format, the order of 403 before the idempotency, concurrency and 404 checks, `scopes_supported` (amends ADR 0022), the dev realm client scopes (amends ADR 0019), and the follow-ups (1.16 tool `[Authorize]`, 4.14 money-moving scope, resource-level authorisation later). + +## Open questions +Answered during implementation (ADR 0038): +- **OpenAPI `security` per operation:** not added. The BIAN document has none, and the OpenAPI document only gains the declared 403 response. +- **Module member:** it takes a dedicated `OperationPolicies` registration (`AddOperationPolicies`), not the raw `AuthorizationBuilder`, so that the host can build the catalog and refuse duplicates. +- **Additional finding:** Wolverine takes any `…Handler` type of the host assembly for a message handler, so the scope check is named `OperationScopeAuthorization`. +- **Additional finding:** a Keycloak realm import that lists its own client scopes loses the built-in ones, and with them `sub` in user tokens. The realm declares `basic` (`sub` only) and claim-less `profile` and `email`. Verified against Keycloak 26.6. diff --git a/specs/2026-11-09-party-authorisation-policies/validation.md b/specs/2026-11-09-party-authorisation-policies/validation.md new file mode 100644 index 0000000..9e857e3 --- /dev/null +++ b/specs/2026-11-09-party-authorisation-policies/validation.md @@ -0,0 +1,40 @@ +# Validation: Authorisation policies + +## Done when (from roadmap) +> **1.15 Authorisation policies:** per-operation policies (separate scopes for command and query operations), with tests. +> + Definition of done ([roadmap.md](../roadmap.md)) + +Concretely: each of the 13 Party BIAN operations has its own named policy. The 8 commands require `party-reference-data-directory:write` and the 5 `Retrieve` queries require `party-reference-data-directory:read`. A token without the right scope gets a 403 `shared.forbidden` Problem Details response. + +## Automated checks +- [ ] `RimBank.Host.Tests` `Security/OperationPolicyTests`: + - an exact scope match is allowed; + - a missing, prefix or superstring scope gets 403 `application/problem+json` with `errorCode: shared.forbidden` and a `traceId`; + - no token gets 401 `shared.unauthenticated`; + - an operation registered twice stops the host. +- [ ] `RimBank.Api.Tests` `Party/PartyReferenceDataDirectory/AuthorisationTests` (Alba), for each of the 13 operations: + - a wrong-kind scope gets 403 Problem Details; + - a right-kind scope gets the usual result; + - no token gets 401. + - 403 comes before the `Idempotency-Key` 400, the `If-Match` 428 and the `Retrieve` 404. + - A denied command appends no event. +- [ ] `RimBank.Api.Tests` `OperationAuthorizationCoverageTests`: + - every named BIAN endpoint carries the policy named by its operation id; + - the catalog kind matches the HTTP verb (`GET` = query = read scope, others = command = write scope); + - there are no orphan policies. +- [ ] `RimBank.Host.Tests` `Mcp/McpAuthorizationTests`: `scopes_supported` lists both scopes. +- [ ] Existing suites stay green with default test tokens (all scopes): Api, Host, Mcp, Conformance (OpenAPI/AsyncAPI), Architecture, AppHost startup. +- [ ] `dotnet format --verify-no-changes` is clean, and the CI workflow is green (build, test, format, CodeQL). + +## Manual / demo checks +- [ ] Review the 13 endpoint diffs: each has `.RequireOperation(OperationId)` and `.ProducesProblem(403)`. +- [ ] Review `rimbank-realm.json`: both client scopes exist and are default scopes of `rimbank-dev-client` and `rimbank-mcp-client`. No real secret is added. +- [ ] `aspire run` still starts. A dev-client token (client credentials) still calls `POST /PartyReferenceDataDirectory/Register` and `GET …/{id}/Retrieve` successfully. A spot check, not a scripted demo. + +## Merge criteria +- [ ] All checks above pass in CI +- [ ] Roadmap checkbox 1.15 ticked in the same PR +- [ ] ADR 0038 written. ADR 0014, 0019 and 0022 consequences amended. tech-stack §6 and §10 updated. +- [ ] CONTRIBUTING "Authentication" explains the scopes and how a new endpoint is protected +- [ ] No tokens, scopes-with-subjects or PII written to logs by the new handler +- [ ] PR opened with the `open-phase-pr` skill (labels, milestone, board, `Closes #`) diff --git a/specs/roadmap.md b/specs/roadmap.md index da79818..070e55f 100644 --- a/specs/roadmap.md +++ b/specs/roadmap.md @@ -61,7 +61,7 @@ - [x] **1.12 BankRelations BQ:** the party's relationships with the bank; Update command and Retrieve query. It records a closed relation type, the bank employee (a person) or unit (an organisation) as a registered entry checked on the write side, and the relationship's dates and lifecycle status ([ADR 0035](../docs/adr/0035-party-bank-relations.md)). - [x] **1.13 Published language:** `PartyReferenceDataDirectoryEntryCreated/Updated` integration events, mapped from domain events (not from read models), carrying the state consumers need, versioned, published through the outbox, and pinned by a schema contract test. - [x] **1.14 Conformance:** OpenAPI and AsyncAPI conformance tests green for the implemented subset. -- [ ] **1.15 Authorisation policies:** per-operation policies (separate scopes for command and query operations), with tests. +- [x] **1.15 Authorisation policies:** per-operation policies (separate scopes for command and query operations), with tests. - [ ] **1.16 MCP adapter: Register & Retrieve:** `RimBank.Party.PartyReferenceDataDirectory.Mcp` tools for Register (command) and Retrieve (query, `readOnly`), with a parity test against the HTTP endpoints. - [ ] **1.17 MCP adapter: remaining operations:** Update and BQ tools; a test that the tool list matches the implemented BIAN operations. diff --git a/specs/tech-stack.md b/specs/tech-stack.md index 1854243..4683312 100644 --- a/specs/tech-stack.md +++ b/specs/tech-stack.md @@ -273,7 +273,7 @@ The architecture tests tell these roles apart by SharedKernel markers ([ADR 0012 - **Hosting:** all contexts' MCP tools are registered in `RimBank.Host` and exposed at a single `/mcp` endpoint over Streamable HTTP in stateless mode. Each context hands its tools to the host through its module's `AddMcpTools(IMcpServerBuilder)`, which calls the one extension its `.Mcp` adapter exposes; contexts never configure the transport or map the route, and a tool name registered twice stops the host ([ADR 0021](../docs/adr/0021-mcp-wiring-and-tool-conventions.md)). When a context is extracted, its `.Mcp` adapter moves with it. - **Naming:** each tool maps 1:1 to a BIAN operation, named `_[_]` in snake_case (for example `party_reference_data_directory_register` and `current_account_retrieve_payment`). Descriptions come from the BIAN operation description, and input schemas reuse the `.Api` request models. - **Tool annotations:** every tool sets `readOnly`, `destructive`, `idempotent` and `openWorld` explicitly (table in ADR 0021). Retrieve tools dispatch queries and are marked `readOnly`; every other tool dispatches a command. Operations that move money or close facilities are marked `destructive` and are not `idempotent` unless an idempotency key is supplied. -- **Security:** the MCP endpoint follows the MCP authorization spec (OAuth 2.1, with Keycloak as the authorization server): a 401 on `/mcp` points to the RFC 9728 protected-resource metadata, which names the realm, and tokens carry the same `rimbank-api` audience as HTTP ([ADR 0022](../docs/adr/0022-mcp-authorization-and-tool-errors.md)). Tool calls go through the same per-BIAN-operation authorisation policies as HTTP. Money-moving tools need a dedicated scope and are disabled by default, so each deployment must turn them on explicitly. +- **Security:** the MCP endpoint follows the MCP authorization spec (OAuth 2.1, with Keycloak as the authorization server): a 401 on `/mcp` points to the RFC 9728 protected-resource metadata, which names the realm, and tokens carry the same `rimbank-api` audience as HTTP ([ADR 0022](../docs/adr/0022-mcp-authorization-and-tool-errors.md)). Tool calls go through the same per-BIAN-operation authorisation policies as HTTP: a tool carries the policy named by its operation id, and the metadata lists every policy scope in `scopes_supported` ([ADR 0038](../docs/adr/0038-per-operation-authorisation-policies.md)). Money-moving tools need a dedicated scope and are disabled by default, so each deployment must turn them on explicitly. - **Errors:** a business or validation failure returns a tool result with `isError: true` whose content (and `structuredContent`) is the Problem Details JSON (same `type`, `errorCode` and `traceId` as HTTP, ADR 0021). Adapters return failures with `ToToolResult` from `RimBank.Mcp`, whose call-tool filter turns unbindable arguments into `shared.tool-arguments-invalid` and any exception into `shared.unexpected` ([ADR 0022](../docs/adr/0022-mcp-authorization-and-tool-errors.md)). Stack traces and internal details are never exposed. - **Audit:** every tool call records the MCP client identity and a correlation ID in event metadata, as HTTP calls do. @@ -342,7 +342,7 @@ CQRS is applied **logically everywhere** and **physically where needed**. Every ## 10. Security & supply chain -- Every endpoint requires authentication by default: the authorization fallback policy requires an authenticated caller, and only the health probes of `RimBank.ServiceDefaults` are anonymous (and, in Development only, the OpenAPI document and Scalar UI it maps, roadmap 1.5), guarded by the architecture rule `allow-anonymous-only-in-service-defaults` ([ADR 0019](../docs/adr/0019-authentication-baseline.md)). Authorisation policies are defined per BIAN operation. +- Every endpoint requires authentication by default: the authorization fallback policy requires an authenticated caller, and only the health probes of `RimBank.ServiceDefaults` are anonymous (and, in Development only, the OpenAPI document and Scalar UI it maps, roadmap 1.5), guarded by the architecture rule `allow-anonymous-only-in-service-defaults` ([ADR 0019](../docs/adr/0019-authentication-baseline.md)). Authorisation policies are defined per BIAN operation ([ADR 0038](../docs/adr/0038-per-operation-authorisation-policies.md)): each context has a read scope for its queries and a write scope for its commands (`:read` / `:write`, for example `party-reference-data-directory:read`). Its host module registers one policy per operation, named by the operation id (`AddOperationPolicies`: `AddCommand` / `AddQuery`). Every BIAN endpoint calls `RequireOperation(OperationId)`, and a token without the scope is a 403 `shared.forbidden`, answered before the endpoint's other checks. - The caller is an `Actor` (SharedKernel: the token's `sub` and `azp`). The host relays its subject to the message bus as the Wolverine user name, which scopes idempotency keys and reaches Marten's last-modified-by and the trace. Cores and adapters never read the token. - PII is masked in logs, and sensitive fields are protected at rest. - Secrets come from user-secrets locally and from a vault in deployed environments. They are never in source. diff --git a/src/RimBank.Api/OperationEndpoints.cs b/src/RimBank.Api/OperationEndpoints.cs new file mode 100644 index 0000000..0f04316 --- /dev/null +++ b/src/RimBank.Api/OperationEndpoints.cs @@ -0,0 +1,28 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; + +namespace RimBank.Api; + +/// Names an endpoint after its BIAN operation and protects it with that operation's policy (ADR 0038). +public static class OperationEndpoints +{ + /// + /// Names the endpoint and requires the authorisation policy of the same name, which + /// the context's host module registers with the context's write scope (a command) or read scope (a query). A + /// caller without that scope gets a 403 shared.forbidden Problem Details response, before the endpoint's + /// other checks run. Use it on every BIAN endpoint, in place of WithName. + /// + /// The endpoint builder. + /// The BIAN operation id, for example PartyReferenceDataDirectoryEntry/Register. + /// The same builder. + public static RouteHandlerBuilder RequireOperation(this RouteHandlerBuilder builder, string operationId) + { + ArgumentNullException.ThrowIfNull(builder); + ArgumentException.ThrowIfNullOrWhiteSpace(operationId); + + return builder + .WithName(operationId) + .RequireAuthorization(operationId) + .ProducesProblem(StatusCodes.Status403Forbidden); + } +} diff --git a/src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/RegisterPartyAssociationEndpoint.cs b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/RegisterPartyAssociationEndpoint.cs index f456fdf..a8a77b1 100644 --- a/src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/RegisterPartyAssociationEndpoint.cs +++ b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/RegisterPartyAssociationEndpoint.cs @@ -27,7 +27,7 @@ public static class RegisterPartyAssociationEndpoint public static RouteHandlerBuilder MapRegisterPartyAssociation(this IEndpointRouteBuilder endpoints) => endpoints.MapPost(Route, HandleAsync) .RequireIdempotencyKey() - .WithName(OperationId) + .RequireOperation(OperationId) .WithTags("Associations") .WithSummary("Capture Association Details") .WithDescription( diff --git a/src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/RetrievePartyAssociationEndpoint.cs b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/RetrievePartyAssociationEndpoint.cs index b587d8b..48f1799 100644 --- a/src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/RetrievePartyAssociationEndpoint.cs +++ b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/RetrievePartyAssociationEndpoint.cs @@ -26,7 +26,7 @@ public static class RetrievePartyAssociationEndpoint /// The endpoint's builder. public static RouteHandlerBuilder MapRetrievePartyAssociation(this IEndpointRouteBuilder endpoints) => endpoints.MapGet(Route, HandleAsync) - .WithName(OperationId) + .RequireOperation(OperationId) .WithTags("Associations") .WithSummary("Retrieve details about association entries in the directory record") .WithDescription( diff --git a/src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/UpdatePartyAssociationEndpoint.cs b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/UpdatePartyAssociationEndpoint.cs index 335b644..4d0d527 100644 --- a/src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/UpdatePartyAssociationEndpoint.cs +++ b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/UpdatePartyAssociationEndpoint.cs @@ -27,7 +27,7 @@ public static class UpdatePartyAssociationEndpoint public static RouteHandlerBuilder MapUpdatePartyAssociation(this IEndpointRouteBuilder endpoints) => endpoints.MapPut(Route, HandleAsync) .RequireIdempotencyKey() - .WithName(OperationId) + .RequireOperation(OperationId) .WithTags("Associations") .WithSummary("Update details about an association entry for the customer") .WithDescription( diff --git a/src/RimBank.Api/Party/PartyReferenceDataDirectory/BankRelations/RetrieveBankRelationsEndpoint.cs b/src/RimBank.Api/Party/PartyReferenceDataDirectory/BankRelations/RetrieveBankRelationsEndpoint.cs index e7a7336..733c7a6 100644 --- a/src/RimBank.Api/Party/PartyReferenceDataDirectory/BankRelations/RetrieveBankRelationsEndpoint.cs +++ b/src/RimBank.Api/Party/PartyReferenceDataDirectory/BankRelations/RetrieveBankRelationsEndpoint.cs @@ -26,7 +26,7 @@ public static class RetrieveBankRelationsEndpoint /// The endpoint's builder. public static RouteHandlerBuilder MapRetrieveBankRelations(this IEndpointRouteBuilder endpoints) => endpoints.MapGet(Route, HandleAsync) - .WithName(OperationId) + .RequireOperation(OperationId) .WithTags("BankRelations") .WithSummary("Retrieve details about customer bank relations entries in the directory") .WithDescription( diff --git a/src/RimBank.Api/Party/PartyReferenceDataDirectory/BankRelations/UpdateBankRelationsEndpoint.cs b/src/RimBank.Api/Party/PartyReferenceDataDirectory/BankRelations/UpdateBankRelationsEndpoint.cs index 3806b30..b502b5f 100644 --- a/src/RimBank.Api/Party/PartyReferenceDataDirectory/BankRelations/UpdateBankRelationsEndpoint.cs +++ b/src/RimBank.Api/Party/PartyReferenceDataDirectory/BankRelations/UpdateBankRelationsEndpoint.cs @@ -28,7 +28,7 @@ public static class UpdateBankRelationsEndpoint public static RouteHandlerBuilder MapUpdateBankRelations(this IEndpointRouteBuilder endpoints) => endpoints.MapPut(Route, HandleAsync) .RequireIdempotencyKey() - .WithName(OperationId) + .RequireOperation(OperationId) .WithTags("BankRelations") .WithSummary("Update details about a customer's bank relations entry for the customer") .WithDescription( diff --git a/src/RimBank.Api/Party/PartyReferenceDataDirectory/Demographics/ExchangeDemographicsEndpoint.cs b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Demographics/ExchangeDemographicsEndpoint.cs index 198fe5b..a6c4878 100644 --- a/src/RimBank.Api/Party/PartyReferenceDataDirectory/Demographics/ExchangeDemographicsEndpoint.cs +++ b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Demographics/ExchangeDemographicsEndpoint.cs @@ -28,7 +28,7 @@ public static class ExchangeDemographicsEndpoint public static RouteHandlerBuilder MapExchangeDemographics(this IEndpointRouteBuilder endpoints) => endpoints.MapPut(Route, HandleAsync) .RequireIdempotencyKey() - .WithName(OperationId) + .RequireOperation(OperationId) .WithTags("Demographics") .WithSummary("Accept, verify, reject etc. details of a customer directory entry") .WithDescription( diff --git a/src/RimBank.Api/Party/PartyReferenceDataDirectory/Demographics/RetrieveDemographicsEndpoint.cs b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Demographics/RetrieveDemographicsEndpoint.cs index add933b..6c747e5 100644 --- a/src/RimBank.Api/Party/PartyReferenceDataDirectory/Demographics/RetrieveDemographicsEndpoint.cs +++ b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Demographics/RetrieveDemographicsEndpoint.cs @@ -26,7 +26,7 @@ public static class RetrieveDemographicsEndpoint /// The endpoint's builder. public static RouteHandlerBuilder MapRetrieveDemographics(this IEndpointRouteBuilder endpoints) => endpoints.MapGet(Route, HandleAsync) - .WithName(OperationId) + .RequireOperation(OperationId) .WithTags("Demographics") .WithSummary("Retrieve details about customer demographics entries in the directory") .WithDescription( diff --git a/src/RimBank.Api/Party/PartyReferenceDataDirectory/Demographics/UpdateDemographicsEndpoint.cs b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Demographics/UpdateDemographicsEndpoint.cs index 7887090..1c9ef0c 100644 --- a/src/RimBank.Api/Party/PartyReferenceDataDirectory/Demographics/UpdateDemographicsEndpoint.cs +++ b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Demographics/UpdateDemographicsEndpoint.cs @@ -27,7 +27,7 @@ public static class UpdateDemographicsEndpoint public static RouteHandlerBuilder MapUpdateDemographics(this IEndpointRouteBuilder endpoints) => endpoints.MapPut(Route, HandleAsync) .RequireIdempotencyKey() - .WithName(OperationId) + .RequireOperation(OperationId) .WithTags("Demographics") .WithSummary("Update details about a customer's demographic entry") .WithDescription( diff --git a/src/RimBank.Api/Party/PartyReferenceDataDirectory/Reference/RetrievePartyReferenceEndpoint.cs b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Reference/RetrievePartyReferenceEndpoint.cs index 549925c..e32026e 100644 --- a/src/RimBank.Api/Party/PartyReferenceDataDirectory/Reference/RetrievePartyReferenceEndpoint.cs +++ b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Reference/RetrievePartyReferenceEndpoint.cs @@ -26,7 +26,7 @@ public static class RetrievePartyReferenceEndpoint /// The endpoint's builder. public static RouteHandlerBuilder MapRetrievePartyReference(this IEndpointRouteBuilder endpoints) => endpoints.MapGet(Route, HandleAsync) - .WithName(OperationId) + .RequireOperation(OperationId) .WithTags("Reference") .WithSummary("Retrieve details about reference entries in the directory") .WithDescription( diff --git a/src/RimBank.Api/Party/PartyReferenceDataDirectory/Reference/UpdatePartyReferenceEndpoint.cs b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Reference/UpdatePartyReferenceEndpoint.cs index 3b505f1..7d1e0ab 100644 --- a/src/RimBank.Api/Party/PartyReferenceDataDirectory/Reference/UpdatePartyReferenceEndpoint.cs +++ b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Reference/UpdatePartyReferenceEndpoint.cs @@ -28,7 +28,7 @@ public static class UpdatePartyReferenceEndpoint public static RouteHandlerBuilder MapUpdatePartyReference(this IEndpointRouteBuilder endpoints) => endpoints.MapPut(Route, HandleAsync) .RequireIdempotencyKey() - .WithName(OperationId) + .RequireOperation(OperationId) .WithTags("Reference") .WithSummary("Update details about a reference entry for the customer") .WithDescription( diff --git a/src/RimBank.Api/Party/PartyReferenceDataDirectory/Registration/RegisterPartyEndpoint.cs b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Registration/RegisterPartyEndpoint.cs index 45b4f5c..1ba19a2 100644 --- a/src/RimBank.Api/Party/PartyReferenceDataDirectory/Registration/RegisterPartyEndpoint.cs +++ b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Registration/RegisterPartyEndpoint.cs @@ -27,7 +27,7 @@ public static class RegisterPartyEndpoint public static RouteHandlerBuilder MapRegisterParty(this IEndpointRouteBuilder endpoints) => endpoints.MapPost(Route, HandleAsync) .RequireIdempotencyKey() - .WithName(OperationId) + .RequireOperation(OperationId) .WithTags("PartyReferenceDataDirectoryEntry") .WithSummary("Register a customer entity in the catalog") .WithDescription( diff --git a/src/RimBank.Api/Party/PartyReferenceDataDirectory/Retrieval/RetrievePartyReferenceDataDirectoryEntryEndpoint.cs b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Retrieval/RetrievePartyReferenceDataDirectoryEntryEndpoint.cs index a91cf9b..01afc60 100644 --- a/src/RimBank.Api/Party/PartyReferenceDataDirectory/Retrieval/RetrievePartyReferenceDataDirectoryEntryEndpoint.cs +++ b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Retrieval/RetrievePartyReferenceDataDirectoryEntryEndpoint.cs @@ -26,7 +26,7 @@ public static class RetrievePartyReferenceDataDirectoryEntryEndpoint /// The endpoint's builder. public static RouteHandlerBuilder MapRetrievePartyReferenceDataDirectoryEntry(this IEndpointRouteBuilder endpoints) => endpoints.MapGet(Route, HandleAsync) - .WithName(OperationId) + .RequireOperation(OperationId) .WithTags("PartyReferenceDataDirectoryEntry") .WithSummary("Retrieve details about a customer directory entry") .WithDescription( diff --git a/src/RimBank.Api/Party/PartyReferenceDataDirectory/Update/UpdatePartyReferenceDataDirectoryEntryEndpoint.cs b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Update/UpdatePartyReferenceDataDirectoryEntryEndpoint.cs index e90c53a..de07b81 100644 --- a/src/RimBank.Api/Party/PartyReferenceDataDirectory/Update/UpdatePartyReferenceDataDirectoryEntryEndpoint.cs +++ b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Update/UpdatePartyReferenceDataDirectoryEntryEndpoint.cs @@ -28,7 +28,7 @@ public static class UpdatePartyReferenceDataDirectoryEntryEndpoint public static RouteHandlerBuilder MapUpdatePartyReferenceDataDirectoryEntry(this IEndpointRouteBuilder endpoints) => endpoints.MapPut(Route, HandleAsync) .RequireIdempotencyKey() - .WithName(OperationId) + .RequireOperation(OperationId) .WithTags("PartyReferenceDataDirectoryEntry") .WithSummary("Update details about the customer's directory entry") .WithDescription( diff --git a/src/RimBank.AppHost/Realms/rimbank-realm.json b/src/RimBank.AppHost/Realms/rimbank-realm.json index 4b3bd1c..6251946 100644 --- a/src/RimBank.AppHost/Realms/rimbank-realm.json +++ b/src/RimBank.AppHost/Realms/rimbank-realm.json @@ -5,6 +5,65 @@ "sslRequired": "external", "registrationAllowed": false, "accessTokenLifespan": 300, + "clientScopes": [ + { + "name": "basic", + "description": "The caller's subject (sub), which RimBank needs to identify the actor (ADR 0019). Declared here because a realm that lists its own client scopes gets none of Keycloak's built-in ones (ADR 0038).", + "protocol": "openid-connect", + "attributes": { + "include.in.token.scope": "false", + "display.on.consent.screen": "false" + }, + "protocolMappers": [ + { + "name": "sub", + "protocol": "openid-connect", + "protocolMapper": "oidc-sub-mapper", + "consentRequired": false, + "config": { + "access.token.claim": "true", + "introspection.token.claim": "true" + } + } + ] + }, + { + "name": "profile", + "description": "Accepted so that OpenID clients may request it, but adds no claim: RimBank's tokens carry no name, email or other personal data (ADR 0038).", + "protocol": "openid-connect", + "attributes": { + "include.in.token.scope": "true", + "display.on.consent.screen": "false" + } + }, + { + "name": "email", + "description": "Accepted so that OpenID clients may request it, but adds no claim: RimBank's tokens carry no name, email or other personal data (ADR 0038).", + "protocol": "openid-connect", + "attributes": { + "include.in.token.scope": "true", + "display.on.consent.screen": "false" + } + }, + { + "name": "party-reference-data-directory:read", + "description": "Party Reference Data Directory queries: the Retrieve operations (ADR 0038).", + "protocol": "openid-connect", + "attributes": { + "include.in.token.scope": "true", + "display.on.consent.screen": "false" + } + }, + { + "name": "party-reference-data-directory:write", + "description": "Party Reference Data Directory commands: Register, Update, Exchange and the Behavior Qualifier Register and Update operations (ADR 0038).", + "protocol": "openid-connect", + "attributes": { + "include.in.token.scope": "true", + "display.on.consent.screen": "false" + } + } + ], "clients": [ { "clientId": "rimbank-api", @@ -45,6 +104,12 @@ "introspection.token.claim": "true" } } + ], + "optionalClientScopes": [], + "defaultClientScopes": [ + "basic", + "party-reference-data-directory:read", + "party-reference-data-directory:write" ] }, { @@ -82,6 +147,15 @@ "introspection.token.claim": "true" } } + ], + "optionalClientScopes": [ + "profile", + "email" + ], + "defaultClientScopes": [ + "basic", + "party-reference-data-directory:read", + "party-reference-data-directory:write" ] } ], diff --git a/src/RimBank.Host/Modules/IServiceDomainModule.cs b/src/RimBank.Host/Modules/IServiceDomainModule.cs index a8ae9ad..5d71dfc 100644 --- a/src/RimBank.Host/Modules/IServiceDomainModule.cs +++ b/src/RimBank.Host/Modules/IServiceDomainModule.cs @@ -28,6 +28,15 @@ public interface IServiceDomainModule /// The host's MCP server builder. void AddMcpTools(IMcpServerBuilder tools); + /// + /// Registers the authorisation policy of each BIAN operation the context exposes (ADR 0038): commands with + /// and the context's write scope, queries with + /// and its read scope. Its endpoints refer to them by operation id; a + /// context without operations yet leaves the body empty. + /// + /// The host's operation policy registration. + void AddOperationPolicies(OperationPolicies policies); + /// Maps the context's HTTP endpoints on the built application. /// The application's endpoint route builder. void MapEndpoints(IEndpointRouteBuilder endpoints); diff --git a/src/RimBank.Host/Modules/Party/PartyReferenceDataDirectoryModule.cs b/src/RimBank.Host/Modules/Party/PartyReferenceDataDirectoryModule.cs index e20d97d..2187acd 100644 --- a/src/RimBank.Host/Modules/Party/PartyReferenceDataDirectoryModule.cs +++ b/src/RimBank.Host/Modules/Party/PartyReferenceDataDirectoryModule.cs @@ -6,10 +6,16 @@ namespace RimBank.Host; /// /// The Party Reference Data Directory (BIAN service domain, business domain Party): its store, inline view, and write /// and read ports, so its command and query handlers run on the host's bus, and its HTTP endpoints (ADR 0014, -/// ADR 0024). Its MCP tools arrive in roadmap 1.16. +/// ADR 0024), each protected by its operation's policy (ADR 0038). Its MCP tools arrive in roadmap 1.16. /// public sealed class PartyReferenceDataDirectoryModule : IServiceDomainModule { + /// The scope a token needs for the context's queries, the Retrieve operations (ADR 0038). + public const string ReadScope = "party-reference-data-directory:read"; + + /// The scope a token needs for the context's commands, every operation except Retrieve (ADR 0038). + public const string WriteScope = "party-reference-data-directory:write"; + /// public string ServiceDomain => PartyReferenceDataDirectoryPostgresql.ServiceDomain; @@ -21,6 +27,27 @@ public void AddMcpTools(IMcpServerBuilder tools) { } + /// + public void AddOperationPolicies(OperationPolicies policies) + { + ArgumentNullException.ThrowIfNull(policies); + + policies + .AddCommand(RegisterPartyEndpoint.OperationId, WriteScope) + .AddQuery(RetrievePartyReferenceDataDirectoryEntryEndpoint.OperationId, ReadScope) + .AddCommand(UpdatePartyReferenceDataDirectoryEntryEndpoint.OperationId, WriteScope) + .AddCommand(UpdateDemographicsEndpoint.OperationId, WriteScope) + .AddCommand(ExchangeDemographicsEndpoint.OperationId, WriteScope) + .AddQuery(RetrieveDemographicsEndpoint.OperationId, ReadScope) + .AddCommand(UpdatePartyReferenceEndpoint.OperationId, WriteScope) + .AddQuery(RetrievePartyReferenceEndpoint.OperationId, ReadScope) + .AddCommand(RegisterPartyAssociationEndpoint.OperationId, WriteScope) + .AddCommand(UpdatePartyAssociationEndpoint.OperationId, WriteScope) + .AddQuery(RetrievePartyAssociationEndpoint.OperationId, ReadScope) + .AddCommand(UpdateBankRelationsEndpoint.OperationId, WriteScope) + .AddQuery(RetrieveBankRelationsEndpoint.OperationId, ReadScope); + } + /// public void MapEndpoints(IEndpointRouteBuilder endpoints) => endpoints.MapPartyReferenceDataDirectoryEndpoints(); } diff --git a/src/RimBank.Host/Modules/ServiceDomainModuleComposition.cs b/src/RimBank.Host/Modules/ServiceDomainModuleComposition.cs index 982fc48..3028323 100644 --- a/src/RimBank.Host/Modules/ServiceDomainModuleComposition.cs +++ b/src/RimBank.Host/Modules/ServiceDomainModuleComposition.cs @@ -3,11 +3,17 @@ namespace RimBank.Host; /// Registers and maps a list of s, in list order (ADR 0014). public static class ServiceDomainModuleComposition { - /// Calls each module's , in list order. + /// + /// Calls each module's , then each module's + /// , in list order, and registers the resulting + /// (ADR 0038). + /// /// The host builder. /// The modules to register. /// The same builder. - /// Two modules have the same service domain name. + /// + /// Two modules have the same service domain name, or a BIAN operation is given more than one policy. + /// public static TBuilder AddServiceDomainModules(this TBuilder builder, IReadOnlyList modules) where TBuilder : IHostApplicationBuilder { @@ -29,6 +35,14 @@ public static TBuilder AddServiceDomainModules(this TBuilder builder, module.AddServices(builder); } + var catalog = new OperationPolicyCatalog(); + var policies = new OperationPolicies(builder.Services.AddAuthorizationBuilder(), catalog); + foreach (var module in modules) + { + module.AddOperationPolicies(policies); + } + + builder.Services.AddSingleton(catalog); return builder; } diff --git a/src/RimBank.Host/Security/AuthenticationComposition.cs b/src/RimBank.Host/Security/AuthenticationComposition.cs index 85ce09e..c2f979a 100644 --- a/src/RimBank.Host/Security/AuthenticationComposition.cs +++ b/src/RimBank.Host/Security/AuthenticationComposition.cs @@ -6,8 +6,8 @@ namespace RimBank.Host; /// -/// Authentication of every request to the host: JWT bearer tokens issued by Keycloak, and deny by default -/// (specs/tech-stack.md §1, §10, ADR 0019). +/// Authentication of every request to the host: JWT bearer tokens issued by Keycloak, deny by default, and the scope +/// check of the per-operation policies the modules register (specs/tech-stack.md §1, §10, ADR 0019, ADR 0038). /// /// /// @@ -115,6 +115,17 @@ public static WebApplicationBuilder AddRimBankAuthentication(this WebApplication BearerMethodsSupported = ["header"], }); + // Lists the scopes of every operation policy the modules register (ADR 0038). The catalog exists once the + // modules are added, after this method, so the metadata reads it when the options are first built. + builder.Services.AddOptions(McpAuthenticationDefaults.AuthenticationScheme) + .Configure((options, services) => + { + var scopes = services.GetService()?.Scopes ?? []; + options.ResourceMetadata ??= new ProtectedResourceMetadata(); + options.ResourceMetadata.ScopesSupported = [.. scopes]; + }); + + builder.Services.AddSingleton(); builder.Services.AddAuthorizationBuilder() .SetFallbackPolicy(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build()) .AddPolicy(McpPolicy, policy => policy diff --git a/src/RimBank.Host/Security/OperationPolicies.cs b/src/RimBank.Host/Security/OperationPolicies.cs new file mode 100644 index 0000000..04c96cd --- /dev/null +++ b/src/RimBank.Host/Security/OperationPolicies.cs @@ -0,0 +1,118 @@ +using Microsoft.AspNetCore.Authorization; + +namespace RimBank.Host; + +/// Whether a BIAN operation is a command (write side) or a query (read side, the Retrieve operations). +public enum OperationKind +{ + /// A command: every BIAN operation except Retrieve (specs/tech-stack.md §8). + Command, + + /// A query: a BIAN Retrieve operation, served from a read model. + Query, +} + +/// The authorisation policy of one BIAN operation: its name is the operation id, and it requires one scope (ADR 0038). +/// The BIAN operation id, for example PartyReferenceDataDirectoryEntry/Register; also the policy name. +/// Whether the operation is a command or a query. +/// The OAuth scope the caller's token must carry. +public sealed record OperationPolicy(string OperationId, OperationKind Kind, string Scope); + +/// +/// Every operation policy the modules registered, in registration order (ADR 0038). The MCP protected-resource metadata +/// lists its scopes, and tests use it to check that every BIAN endpoint carries its policy. +/// +public sealed class OperationPolicyCatalog +{ + private readonly List _policies = []; + + /// The registered policies, in registration order. + public IReadOnlyList Policies => _policies; + + /// The distinct scopes the registered policies require, in registration order. + public IReadOnlyList Scopes => _policies.Select(policy => policy.Scope).Distinct(StringComparer.Ordinal).ToList(); + + /// + /// The policies register, without registering them in any host: to list a host's + /// operations and scopes, for example in tests. + /// + /// The modules, normally . + /// The catalog of their policies. + public static OperationPolicyCatalog Of(IEnumerable modules) + { + ArgumentNullException.ThrowIfNull(modules); + + var catalog = new OperationPolicyCatalog(); + var policies = new OperationPolicies(new AuthorizationBuilder(new ServiceCollection()), catalog); + foreach (var module in modules) + { + module.AddOperationPolicies(policies); + } + + return catalog; + } + + /// The policy of , or when no module registered it. + /// The BIAN operation id. + /// The policy, if any. + public OperationPolicy? Find(string operationId) => + _policies.FirstOrDefault(policy => string.Equals(policy.OperationId, operationId, StringComparison.Ordinal)); + + internal void Add(OperationPolicy policy) + { + if (Find(policy.OperationId) is not null) + { + throw new InvalidOperationException( + $"Each BIAN operation has exactly one authorisation policy, but '{policy.OperationId}' is registered more than once (ADR 0038)."); + } + + _policies.Add(policy); + } +} + +/// +/// What a module uses to register the authorisation policy of each of its BIAN operations (ADR 0038): a command +/// requires the context's write scope, a query its read scope. The policy is named by the operation id, so an endpoint +/// (RequireOperation) and, from roadmap 1.16, an MCP tool refer to it by that id. +/// +public sealed class OperationPolicies +{ + private readonly AuthorizationBuilder _authorization; + private readonly OperationPolicyCatalog _catalog; + + internal OperationPolicies(AuthorizationBuilder authorization, OperationPolicyCatalog catalog) + { + _authorization = authorization; + _catalog = catalog; + } + + /// Registers the policy of a command: an authenticated caller whose token carries . + /// The BIAN operation id, the endpoint's name. + /// The context's write scope. + /// The same registration, to chain the next operation. + /// The operation already has a policy. + public OperationPolicies AddCommand(string operationId, string scope) => Add(operationId, OperationKind.Command, scope); + + /// Registers the policy of a query: an authenticated caller whose token carries . + /// The BIAN Retrieve operation id, the endpoint's name. + /// The context's read scope. + /// The same registration, to chain the next operation. + /// The operation already has a policy. + public OperationPolicies AddQuery(string operationId, string scope) => Add(operationId, OperationKind.Query, scope); + + private OperationPolicies Add(string operationId, OperationKind kind, string scope) + { + ArgumentException.ThrowIfNullOrWhiteSpace(operationId); + ArgumentException.ThrowIfNullOrWhiteSpace(scope); + if (scope.Any(char.IsWhiteSpace)) + { + throw new ArgumentException($"A scope is one token without spaces, but '{scope}' has some.", nameof(scope)); + } + + _catalog.Add(new OperationPolicy(operationId, kind, scope)); + _authorization.AddPolicy(operationId, policy => policy + .RequireAuthenticatedUser() + .AddRequirements(new OperationScopeRequirement(scope))); + return this; + } +} diff --git a/src/RimBank.Host/Security/OperationScopeRequirement.cs b/src/RimBank.Host/Security/OperationScopeRequirement.cs new file mode 100644 index 0000000..940ddef --- /dev/null +++ b/src/RimBank.Host/Security/OperationScopeRequirement.cs @@ -0,0 +1,37 @@ +using Microsoft.AspNetCore.Authorization; + +namespace RimBank.Host; + +/// The caller's access token must carry (ADR 0038). +/// The required OAuth scope, for example party-reference-data-directory:write. +public sealed record OperationScopeRequirement(string Scope) : IAuthorizationRequirement; + +/// +/// Meets an when the token's scope claim, a space-separated list +/// (RFC 9068, as Keycloak issues it), holds the required scope exactly. A prefix or a longer scope does not count. +/// +/// +/// A failed check is a bodiless 403, which the status-code pages turn into shared.forbidden (ADR 0015). The name +/// does not end in Handler: Wolverine would take a …Handler type of the host's assembly for a message handler. +/// +public sealed class OperationScopeAuthorization : AuthorizationHandler +{ + /// The claim that holds the token's granted scopes. + public const string ScopeClaim = "scope"; + + /// + protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, OperationScopeRequirement requirement) + { + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(requirement); + + var granted = context.User.FindAll(ScopeClaim) + .SelectMany(claim => claim.Value.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)); + if (granted.Contains(requirement.Scope, StringComparer.Ordinal)) + { + context.Succeed(requirement); + } + + return Task.CompletedTask; + } +} diff --git a/tests/RimBank.Api.Tests/OperationAuthorizationCoverageTests.cs b/tests/RimBank.Api.Tests/OperationAuthorizationCoverageTests.cs new file mode 100644 index 0000000..4c0a1e5 --- /dev/null +++ b/tests/RimBank.Api.Tests/OperationAuthorizationCoverageTests.cs @@ -0,0 +1,79 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Routing; +using Microsoft.Extensions.DependencyInjection; +using RimBank.Host; +using RimBank.Party.PartyReferenceDataDirectory.Api.Tests; + +namespace RimBank.Api.Tests; + +// Roadmap 1.15: the running host maps no BIAN endpoint without its operation's policy, the policy's kind matches the +// endpoint's verb (GET is a query and needs the read scope; every other verb is a command and needs the write scope), +// and no registered policy is left without its endpoint (ADR 0038). +public sealed class OperationAuthorizationCoverageTests(PostgresqlServer server) +{ + [Fact] + public async Task Every_bian_endpoint_requires_the_policy_named_by_its_operation() + { + await using var host = await server.StartHostAsync(); + var catalog = host.Alba.Services.GetRequiredService(); + + var endpoints = BianEndpoints(host); + + endpoints.ShouldNotBeEmpty(); + foreach (var endpoint in endpoints) + { + var name = endpoint.Metadata.GetRequiredMetadata().EndpointName; + endpoint.Metadata.GetOrderedMetadata().Select(data => data.Policy).ShouldBe([name], endpoint.DisplayName); + catalog.Find(name).ShouldNotBeNull($"{name} has no policy registered by its module"); + } + } + + [Fact] + public async Task A_get_endpoint_is_a_query_on_the_read_scope_and_any_other_verb_a_command_on_the_write_scope() + { + await using var host = await server.StartHostAsync(); + var catalog = host.Alba.Services.GetRequiredService(); + + foreach (var endpoint in BianEndpoints(host)) + { + var name = endpoint.Metadata.GetRequiredMetadata().EndpointName; + var policy = catalog.Find(name).ShouldNotBeNull(name); + var methods = endpoint.Metadata.GetRequiredMetadata().HttpMethods; + var isGet = methods.SequenceEqual(["GET"]); + + policy.Kind.ShouldBe(isGet ? OperationKind.Query : OperationKind.Command, name); + policy.Scope.ShouldEndWith(isGet ? ":read" : ":write", Case.Sensitive, name); + } + } + + [Fact] + public async Task Every_registered_operation_policy_protects_an_endpoint() + { + await using var host = await server.StartHostAsync(); + var catalog = host.Alba.Services.GetRequiredService(); + + var named = BianEndpoints(host).Select(endpoint => endpoint.Metadata.GetRequiredMetadata().EndpointName); + + catalog.Policies.Select(policy => policy.OperationId).ShouldBe(named, ignoreOrder: true); + } + + [Fact] + public async Task The_party_reference_data_directory_has_eight_commands_and_five_queries() + { + await using var host = await server.StartHostAsync(); + var catalog = host.Alba.Services.GetRequiredService(); + + catalog.Policies.Count(policy => policy.Kind == OperationKind.Command).ShouldBe(8); + catalog.Policies.Count(policy => policy.Kind == OperationKind.Query).ShouldBe(5); + catalog.Scopes.ShouldBe([PartyReferenceDataDirectoryModule.WriteScope, PartyReferenceDataDirectoryModule.ReadScope], ignoreOrder: true); + } + + // A BIAN endpoint is a named route endpoint of a module: the health probes, the MCP endpoint and the dev-only API + // description are not BIAN operations and carry no operation name. + private static List BianEndpoints(PartyApiHost host) => + [ + .. host.Alba.Services.GetRequiredService().Endpoints + .OfType() + .Where(endpoint => endpoint.Metadata.GetMetadata() is not null), + ]; +} diff --git a/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/AuthorisationTests.cs b/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/AuthorisationTests.cs new file mode 100644 index 0000000..cec688a --- /dev/null +++ b/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/AuthorisationTests.cs @@ -0,0 +1,138 @@ +using System.Text.Json; +using Alba; +using Microsoft.Net.Http.Headers; +using RimBank.Host; +using RimBank.Host.Testing; + +namespace RimBank.Party.PartyReferenceDataDirectory.Api.Tests; + +// Roadmap 1.15: every BIAN operation of the context is authorised by its own policy. Commands need the write scope and +// queries the read scope, and a token with only the other one is a 403 shared.forbidden problem that comes before every +// other check of the endpoint (ADR 0038). +public sealed class AuthorisationTests(PostgresqlServer server) +{ + private const string Read = PartyReferenceDataDirectoryModule.ReadScope; + private const string Write = PartyReferenceDataDirectoryModule.WriteScope; + private const string ProblemJson = "application/problem+json"; + + // Each operation with its verb and a route to unknown records. The command is sent without a body, + // Idempotency-Key or If-Match, and the query asks for a record that does not exist, so a 403 proves that + // authorisation comes before the 400, 428 and 404 the endpoint would otherwise answer. + public static TheoryData Operations + { + get + { + var entry = Guid.CreateVersion7(); + var record = Guid.CreateVersion7(); + var data = new TheoryData + { + { RegisterPartyEndpoint.OperationId, "POST", "/PartyReferenceDataDirectory/Register", Read }, + { RetrievePartyReferenceDataDirectoryEntryEndpoint.OperationId, "GET", $"/PartyReferenceDataDirectory/{entry}/Retrieve", Write }, + { UpdatePartyReferenceDataDirectoryEntryEndpoint.OperationId, "PUT", $"/PartyReferenceDataDirectory/{entry}/Update", Read }, + { UpdateDemographicsEndpoint.OperationId, "PUT", $"/PartyReferenceDataDirectory/{entry}/Demographics/{record}/Update", Read }, + { ExchangeDemographicsEndpoint.OperationId, "PUT", $"/PartyReferenceDataDirectory/{entry}/Demographics/{record}/Exchange", Read }, + { RetrieveDemographicsEndpoint.OperationId, "GET", $"/PartyReferenceDataDirectory/{entry}/Demographics/{record}/Retrieve", Write }, + { UpdatePartyReferenceEndpoint.OperationId, "PUT", $"/PartyReferenceDataDirectory/{entry}/Reference/{record}/Update", Read }, + { RetrievePartyReferenceEndpoint.OperationId, "GET", $"/PartyReferenceDataDirectory/{entry}/Reference/{record}/Retrieve", Write }, + { RegisterPartyAssociationEndpoint.OperationId, "POST", $"/PartyReferenceDataDirectory/{entry}/Associations/Register", Read }, + { UpdatePartyAssociationEndpoint.OperationId, "PUT", $"/PartyReferenceDataDirectory/{entry}/Associations/{record}/Update", Read }, + { RetrievePartyAssociationEndpoint.OperationId, "GET", $"/PartyReferenceDataDirectory/{entry}/Associations/{record}/Retrieve", Write }, + { UpdateBankRelationsEndpoint.OperationId, "PUT", $"/PartyReferenceDataDirectory/{entry}/BankRelations/{record}/Update", Read }, + { RetrieveBankRelationsEndpoint.OperationId, "GET", $"/PartyReferenceDataDirectory/{entry}/BankRelations/{record}/Retrieve", Write }, + }; + return data; + } + } + + [Theory] + [MemberData(nameof(Operations))] + public async Task A_token_with_only_the_other_kinds_scope_is_forbidden_before_any_other_check( + string operationId, string method, string url, string otherScope) + { + await using var host = await server.StartHostAsync(); + + var result = await host.Alba.Scenario(_ => + { + Send(_, method, url, TestTokens.Issue(scopes: [otherScope])); + _.StatusCodeShouldBe(403); + _.ContentTypeShouldBe(ProblemJson); + }); + + using var problem = JsonDocument.Parse(await result.ReadAsTextAsync()); + problem.RootElement.GetProperty("errorCode").GetString().ShouldBe("shared.forbidden", operationId); + problem.RootElement.GetProperty("instance").GetString().ShouldBe(url); + (await host.ScalarAsync(PartyApiHost.Streams)).ShouldBe(0); + (await host.ScalarAsync(PartyApiHost.Outcomes)).ShouldBe(0); + } + + [Theory] + [MemberData(nameof(Operations))] + public async Task A_token_with_no_scope_is_forbidden(string operationId, string method, string url, string otherScope) + { + _ = otherScope; + await using var host = await server.StartHostAsync(); + + await host.Alba.Scenario(_ => + { + Send(_, method, url, TestTokens.Issue(scopes: [])); + _.StatusCodeShouldBe(403); + }); + + (await host.ScalarAsync(PartyApiHost.Streams)).ShouldBe(0, operationId); + } + + [Theory] + [MemberData(nameof(Operations))] + public async Task A_caller_without_a_token_is_unauthenticated(string operationId, string method, string url, string otherScope) + { + _ = otherScope; + await using var host = await server.StartHostAsync(); + + var result = await host.Alba.Scenario(_ => + { + Send(_, method, url, token: null); + _.StatusCodeShouldBe(401); + }); + + using var problem = JsonDocument.Parse(await result.ReadAsTextAsync()); + problem.RootElement.GetProperty("errorCode").GetString().ShouldBe("shared.unauthenticated", operationId); + } + + [Fact] + public async Task The_write_scope_alone_registers_and_the_read_scope_alone_retrieves() + { + await using var host = await server.StartHostAsync(); + + var registered = await host.Alba.Scenario(_ => + { + _.Post.Json(new { PartyType = "Person" }).ToUrl("/PartyReferenceDataDirectory/Register"); + _.WithRequestHeader("Idempotency-Key", "authorised-register"); + _.WithRequestHeader(HeaderNames.Authorization, "Bearer " + TestTokens.Issue(scopes: [Write])); + _.StatusCodeShouldBeOk(); + }); + var entry = (await registered.ReadAsJsonAsync()).ShouldNotBeNull().PartyReferenceDataDirectoryEntryId; + + await host.Alba.Scenario(_ => + { + _.Get.Url($"/PartyReferenceDataDirectory/{entry}/Retrieve"); + _.WithRequestHeader(HeaderNames.Authorization, "Bearer " + TestTokens.Issue(scopes: [Read])); + _.StatusCodeShouldBeOk(); + }); + } + + private static void Send(Scenario scenario, string method, string url, string? token) + { + _ = method switch + { + "GET" => scenario.Get.Url(url), + "POST" => scenario.Post.Url(url), + "PUT" => scenario.Put.Url(url), + _ => throw new ArgumentOutOfRangeException(nameof(method), method, "Only GET, POST and PUT are mapped."), + }; + + if (token is not null) + { + scenario.WithRequestHeader(HeaderNames.Authorization, "Bearer " + token); + } + } +} diff --git a/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/OpenApiDocumentTests.cs b/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/OpenApiDocumentTests.cs index aa68ba1..b39aeac 100644 --- a/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/OpenApiDocumentTests.cs +++ b/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/OpenApiDocumentTests.cs @@ -24,7 +24,7 @@ public async Task In_Development_the_document_describes_Register_with_its_Idempo var operation = (await result.ReadAsJsonAsync()).GetProperty("paths").GetProperty(Register).GetProperty("post"); operation.GetProperty("operationId").GetString().ShouldBe("PartyReferenceDataDirectoryEntry/Register"); operation.GetProperty("responses").EnumerateObject().Select(response => response.Name) - .ShouldBe(["200", "400", "401", "409", "500"], ignoreOrder: true); + .ShouldBe(["200", "400", "401", "403", "409", "500"], ignoreOrder: true); var header = operation.GetProperty("parameters").EnumerateArray() .Where(parameter => parameter.GetProperty("name").GetString() == "Idempotency-Key") .ShouldHaveSingleItem(); diff --git a/tests/RimBank.AppHost.Tests/Model/DevRealmTests.cs b/tests/RimBank.AppHost.Tests/Model/DevRealmTests.cs index e001ad4..43635fb 100644 --- a/tests/RimBank.AppHost.Tests/Model/DevRealmTests.cs +++ b/tests/RimBank.AppHost.Tests/Model/DevRealmTests.cs @@ -7,6 +7,8 @@ public sealed class DevRealmTests { private static readonly JsonElement _realm = JsonDocument.Parse(File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "Realms", "rimbank-realm.json"))).RootElement; + private static readonly string[] _operationScopes = ["party-reference-data-directory:read", "party-reference-data-directory:write"]; + [Fact] public void The_dev_mcp_client_is_public_with_pkce_and_loopback_redirects_only() { @@ -43,6 +45,42 @@ public void The_dev_user_is_marked_local_only_and_needs_no_first_login_actions() password.GetProperty("temporary").GetBoolean().ShouldBeFalse(); } + // Roadmap 1.15: both dev clients get the Party scopes by default, so local flows may call every operation (ADR 0038). + [Theory] + [InlineData("rimbank-dev-client")] + [InlineData("rimbank-mcp-client")] + public void The_dev_clients_get_the_subject_and_every_operation_scope_by_default(string clientId) + { + Client(clientId).GetProperty("defaultClientScopes").EnumerateArray().Select(scope => scope.GetString()) + .ShouldBe(["basic", .. _operationScopes], ignoreOrder: true); + } + + [Fact] + public void Every_operation_scope_is_a_client_scope_written_into_the_token() + { + foreach (var name in _operationScopes) + { + var scope = ClientScope(name); + scope.GetProperty("protocol").GetString().ShouldBe("openid-connect"); + scope.GetProperty("attributes").GetProperty("include.in.token.scope").GetString().ShouldBe("true", name); + } + } + + // A realm that lists its own client scopes gets none of Keycloak's built-in ones, so it declares basic for the + // subject the actor needs (ADR 0019), and profile and email only so that clients may request them: they add no + // personal data to the token. + [Fact] + public void The_realm_keeps_the_subject_in_tokens_and_adds_no_personal_data() + { + ClientScope("basic").GetProperty("protocolMappers").EnumerateArray().ShouldHaveSingleItem() + .GetProperty("protocolMapper").GetString().ShouldBe("oidc-sub-mapper"); + ClientScope("profile").TryGetProperty("protocolMappers", out _).ShouldBeFalse(); + ClientScope("email").TryGetProperty("protocolMappers", out _).ShouldBeFalse(); + } + + private static JsonElement ClientScope(string name) => + _realm.GetProperty("clientScopes").EnumerateArray().Single(scope => scope.GetProperty("name").GetString() == name); + private static JsonElement Client(string clientId) => _realm.GetProperty("clients").EnumerateArray().Single(client => client.GetProperty("clientId").GetString() == clientId); } diff --git a/tests/RimBank.Host.Testing/TestTokens.cs b/tests/RimBank.Host.Testing/TestTokens.cs index 8fab269..0032798 100644 --- a/tests/RimBank.Host.Testing/TestTokens.cs +++ b/tests/RimBank.Host.Testing/TestTokens.cs @@ -56,15 +56,31 @@ public static IServiceCollection TrustTestTokens(this IServiceCollection service return services; } - /// A token the host accepts, unless one of the arguments says otherwise. + /// + /// Every scope the host's modules require (ADR 0038), granted by default so that a test which is not about + /// authorisation is allowed every operation. + /// + public static IReadOnlyList AllScopes { get; } = AllModuleScopes(); + + /// + /// A token the host accepts, unless one of the arguments says otherwise. It grants , or + /// when they are not given; [] grants none. + /// public static string Issue( string? subject = Subject, string? clientId = ClientId, string audience = AuthenticationComposition.Audience, DateTime? expires = null, - bool trusted = true) + bool trusted = true, + IEnumerable? scopes = null) { var claims = new List(); + var granted = string.Join(' ', scopes ?? AllScopes); + if (granted.Length > 0) + { + claims.Add(new Claim(OperationScopeAuthorization.ScopeClaim, granted)); + } + if (subject is not null) { claims.Add(new Claim(JwtRegisteredClaimNames.Sub, subject)); @@ -88,11 +104,11 @@ public static string Issue( }); } - /// A client that sends a valid token with every request. - public static HttpClient Authenticated(HttpClient client) + /// A client that sends a valid token with every request, granting (default: all). + public static HttpClient Authenticated(HttpClient client, IEnumerable? scopes = null) { ArgumentNullException.ThrowIfNull(client); - client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", Issue()); + client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", Issue(scopes: scopes)); return client; } @@ -108,5 +124,7 @@ public static HttpRequestMessage Get(string path, string? token) return request; } + private static List AllModuleScopes() => [.. OperationPolicyCatalog.Of(ServiceDomainModules.All).Scopes]; + private static RsaSecurityKey NewKey(string keyId) => new(RSA.Create(2048)) { KeyId = keyId }; } diff --git a/tests/RimBank.Host.Tests/Errors/FaultyServiceDomainModule.cs b/tests/RimBank.Host.Tests/Errors/FaultyServiceDomainModule.cs index baa3677..dabe1bc 100644 --- a/tests/RimBank.Host.Tests/Errors/FaultyServiceDomainModule.cs +++ b/tests/RimBank.Host.Tests/Errors/FaultyServiceDomainModule.cs @@ -30,6 +30,10 @@ public void AddServices(IHostApplicationBuilder builder) { } + public void AddOperationPolicies(OperationPolicies policies) + { + } + public void AddMcpTools(IMcpServerBuilder tools) { } diff --git a/tests/RimBank.Host.Tests/Mcp/McpAuthorizationTests.cs b/tests/RimBank.Host.Tests/Mcp/McpAuthorizationTests.cs index dd008b1..655a321 100644 --- a/tests/RimBank.Host.Tests/Mcp/McpAuthorizationTests.cs +++ b/tests/RimBank.Host.Tests/Mcp/McpAuthorizationTests.cs @@ -85,6 +85,21 @@ public async Task The_protected_resource_metadata_is_readable_without_a_token() metadata.RootElement.GetProperty("bearer_methods_supported").EnumerateArray().Select(method => method.GetString()) .ShouldBe(["header"]); metadata.RootElement.GetProperty("resource_name").GetString().ShouldBe(McpComposition.ServerName); + (metadata.RootElement.TryGetProperty("scopes_supported", out var scopes) ? scopes.GetArrayLength() : 0) + .ShouldBe(0, "no module registers an operation policy"); + } + + // Roadmap 1.15: an MCP client learns which scopes to ask for (ADR 0038). + [Fact] + public async Task The_protected_resource_metadata_lists_the_scopes_of_every_operation_policy() + { + await using var app = await McpTestHost.StartAsync(new McpServiceDomainModule(), new ScopedServiceDomainModule()); + using var http = app.GetTestClient(); + + using var metadata = JsonDocument.Parse(await http.GetStringAsync(new Uri(MetadataPath, UriKind.Relative), TestContext.Current.CancellationToken)); + + metadata.RootElement.GetProperty("scopes_supported").EnumerateArray().Select(scope => scope.GetString()) + .ShouldBe([ScopedServiceDomainModule.WriteScope, ScopedServiceDomainModule.ReadScope]); } [Fact] diff --git a/tests/RimBank.Host.Tests/Mcp/McpCallerServiceDomainModule.cs b/tests/RimBank.Host.Tests/Mcp/McpCallerServiceDomainModule.cs index 99aeae8..aa42ca6 100644 --- a/tests/RimBank.Host.Tests/Mcp/McpCallerServiceDomainModule.cs +++ b/tests/RimBank.Host.Tests/Mcp/McpCallerServiceDomainModule.cs @@ -18,6 +18,10 @@ internal sealed class McpCallerServiceDomainModule : IServiceDomainModule public void AddServices(IHostApplicationBuilder builder) => builder.Services.ConfigureWolverine(options => options.Discovery.IncludeType(typeof(WhoSentThisHandler))); + public void AddOperationPolicies(OperationPolicies policies) + { + } + public void AddMcpTools(IMcpServerBuilder tools) => tools.WithTools(); public void MapEndpoints(IEndpointRouteBuilder endpoints) diff --git a/tests/RimBank.Host.Tests/Mcp/McpErrorServiceDomainModule.cs b/tests/RimBank.Host.Tests/Mcp/McpErrorServiceDomainModule.cs index 3eef98f..0b490ac 100644 --- a/tests/RimBank.Host.Tests/Mcp/McpErrorServiceDomainModule.cs +++ b/tests/RimBank.Host.Tests/Mcp/McpErrorServiceDomainModule.cs @@ -23,6 +23,10 @@ public void AddServices(IHostApplicationBuilder builder) { } + public void AddOperationPolicies(OperationPolicies policies) + { + } + public void AddMcpTools(IMcpServerBuilder tools) => tools.WithTools(); public void MapEndpoints(IEndpointRouteBuilder endpoints) diff --git a/tests/RimBank.Host.Tests/Mcp/McpServiceDomainModule.cs b/tests/RimBank.Host.Tests/Mcp/McpServiceDomainModule.cs index c05f1e4..ec179d0 100644 --- a/tests/RimBank.Host.Tests/Mcp/McpServiceDomainModule.cs +++ b/tests/RimBank.Host.Tests/Mcp/McpServiceDomainModule.cs @@ -18,6 +18,10 @@ public void AddServices(IHostApplicationBuilder builder) { } + public void AddOperationPolicies(OperationPolicies policies) + { + } + public void AddMcpTools(IMcpServerBuilder tools) => tools.WithTools(); public void MapEndpoints(IEndpointRouteBuilder endpoints) diff --git a/tests/RimBank.Host.Tests/Modules/FakeServiceDomainModule.cs b/tests/RimBank.Host.Tests/Modules/FakeServiceDomainModule.cs index 844861c..cb962b7 100644 --- a/tests/RimBank.Host.Tests/Modules/FakeServiceDomainModule.cs +++ b/tests/RimBank.Host.Tests/Modules/FakeServiceDomainModule.cs @@ -19,6 +19,8 @@ public void AddServices(IHostApplicationBuilder builder) builder.Services.AddKeyedSingleton(serviceDomain, new FakeModuleMarker(serviceDomain)); } + public void AddOperationPolicies(OperationPolicies policies) => calls.Add($"{serviceDomain}.AddOperationPolicies"); + public void AddMcpTools(IMcpServerBuilder tools) => calls.Add($"{serviceDomain}.AddMcpTools"); public void MapEndpoints(IEndpointRouteBuilder endpoints) diff --git a/tests/RimBank.Host.Tests/Modules/ServiceDomainModuleCompositionTests.cs b/tests/RimBank.Host.Tests/Modules/ServiceDomainModuleCompositionTests.cs index b86cfcc..d15d491 100644 --- a/tests/RimBank.Host.Tests/Modules/ServiceDomainModuleCompositionTests.cs +++ b/tests/RimBank.Host.Tests/Modules/ServiceDomainModuleCompositionTests.cs @@ -25,7 +25,7 @@ public async Task Every_module_registers_its_services_and_maps_its_endpoints() } [Fact] - public async Task Modules_are_registered_then_given_their_tools_then_mapped_in_list_order() + public async Task Modules_are_registered_then_given_their_policies_and_tools_then_mapped_in_list_order() { await using var app = await StartAsync( new FakeServiceDomainModule("SampleStatement", "sample-statement", _calls), @@ -35,6 +35,8 @@ public async Task Modules_are_registered_then_given_their_tools_then_mapped_in_l [ "SampleStatement.AddServices", "SampleLedger.AddServices", + "SampleStatement.AddOperationPolicies", + "SampleLedger.AddOperationPolicies", "SampleStatement.AddMcpTools", "SampleLedger.AddMcpTools", "SampleStatement.MapEndpoints", diff --git a/tests/RimBank.Host.Tests/Security/OperationPolicyTests.cs b/tests/RimBank.Host.Tests/Security/OperationPolicyTests.cs new file mode 100644 index 0000000..fb8f317 --- /dev/null +++ b/tests/RimBank.Host.Tests/Security/OperationPolicyTests.cs @@ -0,0 +1,183 @@ +using System.Net; +using System.Text.Json; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Routing; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +namespace RimBank.Host.Tests; + +// Roadmap 1.15: each BIAN operation has its own policy, named by the operation id, which requires the context's write +// scope (a command) or read scope (a query); a token without it is a 403 shared.forbidden problem (ADR 0038). +public sealed class OperationPolicyTests +{ + private const string ProblemJson = "application/problem+json"; + + [Theory] + [InlineData(ScopedServiceDomainModule.WriteScope)] + [InlineData("openid " + ScopedServiceDomainModule.WriteScope + " profile")] + public async Task A_token_with_the_operations_scope_reaches_the_endpoint(string scope) + { + await using var app = await StartAsync(); + using var client = app.GetTestClient(); + + using var response = await client.SendAsync(Post(ScopedServiceDomainModule.CommandRoute, TestTokens.Issue(scopes: [scope])), TestContext.Current.CancellationToken); + + response.StatusCode.ShouldBe(HttpStatusCode.OK); + } + + [Theory] + [InlineData("no scope", new string[0])] + [InlineData("the other kind's scope", new[] { ScopedServiceDomainModule.ReadScope })] + [InlineData("a prefix of the scope", new[] { "sample-ledger:wri" })] + [InlineData("a longer scope", new[] { ScopedServiceDomainModule.WriteScope + "r" })] + [InlineData("another case", new[] { "SAMPLE-LEDGER:WRITE" })] + public async Task A_token_without_the_operations_scope_is_a_shared_forbidden_problem(string reason, string[] scopes) + { + await using var app = await StartAsync(); + using var client = app.GetTestClient(); + + using var response = await client.SendAsync(Post(ScopedServiceDomainModule.CommandRoute, TestTokens.Issue(scopes: scopes)), TestContext.Current.CancellationToken); + + response.StatusCode.ShouldBe(HttpStatusCode.Forbidden, reason); + response.Content.Headers.ContentType?.MediaType.ShouldBe(ProblemJson); + using var problem = JsonDocument.Parse(await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken)); + problem.RootElement.GetProperty("errorCode").GetString().ShouldBe("shared.forbidden"); + problem.RootElement.GetProperty("traceId").GetString().ShouldNotBeNullOrWhiteSpace(); + } + + [Fact] + public async Task A_query_needs_the_read_scope_and_a_command_the_write_scope() + { + await using var app = await StartAsync(); + using var client = app.GetTestClient(); + var reader = TestTokens.Issue(scopes: [ScopedServiceDomainModule.ReadScope]); + var writer = TestTokens.Issue(scopes: [ScopedServiceDomainModule.WriteScope]); + + using var readerQuery = await client.SendAsync(TestTokens.Get(ScopedServiceDomainModule.QueryRoute, reader), TestContext.Current.CancellationToken); + using var writerQuery = await client.SendAsync(TestTokens.Get(ScopedServiceDomainModule.QueryRoute, writer), TestContext.Current.CancellationToken); + using var readerCommand = await client.SendAsync(Post(ScopedServiceDomainModule.CommandRoute, reader), TestContext.Current.CancellationToken); + + readerQuery.StatusCode.ShouldBe(HttpStatusCode.OK); + writerQuery.StatusCode.ShouldBe(HttpStatusCode.Forbidden); + readerCommand.StatusCode.ShouldBe(HttpStatusCode.Forbidden); + } + + [Fact] + public async Task A_caller_without_a_token_is_unauthenticated_before_it_is_forbidden() + { + await using var app = await StartAsync(); + using var client = app.GetTestClient(); + + using var response = await client.SendAsync(Post(ScopedServiceDomainModule.CommandRoute, token: null), TestContext.Current.CancellationToken); + + response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized); + } + + [Fact] + public async Task The_catalog_lists_every_registered_operation_with_its_kind_and_scope() + { + await using var app = await StartAsync(); + + var catalog = app.Services.GetRequiredService(); + + catalog.Policies.ShouldBe( + [ + new OperationPolicy(ScopedServiceDomainModule.CommandOperation, OperationKind.Command, ScopedServiceDomainModule.WriteScope), + new OperationPolicy(ScopedServiceDomainModule.QueryOperation, OperationKind.Query, ScopedServiceDomainModule.ReadScope), + ]); + catalog.Scopes.ShouldBe([ScopedServiceDomainModule.WriteScope, ScopedServiceDomainModule.ReadScope]); + } + + [Fact] + public void An_operation_given_two_policies_stops_the_host_from_starting() + { + var exception = Should.Throw(() => HostComposition.Build( + NewBuilder(), + [new ScopedServiceDomainModule(), new ScopedServiceDomainModule("SampleLedgerAgain")])); + + exception.Message.ShouldContain(ScopedServiceDomainModule.CommandOperation); + } + + [Theory] + [InlineData("")] + [InlineData("two scopes")] + public void A_scope_must_be_one_token(string scope) + { + var module = new ScopedServiceDomainModule(writeScope: scope); + + Should.Throw(() => OperationPolicyCatalog.Of([module])); + } + + private static HttpRequestMessage Post(string path, string? token) + { + var request = new HttpRequestMessage(HttpMethod.Post, new Uri(path, UriKind.Relative)); + if (token is not null) + { + request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token); + } + + return request; + } + + private static WebApplicationBuilder NewBuilder() + { + var builder = WebApplication.CreateBuilder(new WebApplicationOptions { EnvironmentName = "Production" }); + builder.WebHost.UseTestServer(); + builder.UseTestTokens(); + return builder; + } + + private static async Task StartAsync() + { + var app = HostComposition.Build(NewBuilder(), [new ScopedServiceDomainModule()]); + await app.StartAsync(TestContext.Current.CancellationToken); + return app; + } +} + +/// +/// A test-only module with one command and one query, each protected by its operation's policy, as a real context's +/// module and .Api do (ADR 0038). +/// +internal sealed class ScopedServiceDomainModule(string serviceDomain = "SampleLedger", string writeScope = ScopedServiceDomainModule.WriteScope) + : IServiceDomainModule +{ + public const string ReadScope = "sample-ledger:read"; + + public const string WriteScope = "sample-ledger:write"; + + public const string CommandOperation = "SampleLedgerEntry/Initiate"; + + public const string QueryOperation = "SampleLedgerEntry/Retrieve"; + + public const string CommandRoute = "/sample-ledger/initiate"; + + public const string QueryRoute = "/sample-ledger/retrieve"; + + public string ServiceDomain => serviceDomain; + + public void AddServices(IHostApplicationBuilder builder) + { + } + + public void AddOperationPolicies(OperationPolicies policies) + { + ArgumentNullException.ThrowIfNull(policies); + policies + .AddCommand(CommandOperation, writeScope) + .AddQuery(QueryOperation, ReadScope); + } + + public void AddMcpTools(IMcpServerBuilder tools) + { + } + + public void MapEndpoints(IEndpointRouteBuilder endpoints) + { + endpoints.MapPost(CommandRoute, () => Results.Ok()).RequireAuthorization(CommandOperation); + endpoints.MapGet(QueryRoute, () => Results.Ok()).RequireAuthorization(QueryOperation); + } +} diff --git a/tests/RimBank.Host.Tests/Security/SecuredServiceDomainModule.cs b/tests/RimBank.Host.Tests/Security/SecuredServiceDomainModule.cs index 605315c..6c167bc 100644 --- a/tests/RimBank.Host.Tests/Security/SecuredServiceDomainModule.cs +++ b/tests/RimBank.Host.Tests/Security/SecuredServiceDomainModule.cs @@ -21,6 +21,10 @@ public void AddServices(IHostApplicationBuilder builder) builder.Services.ConfigureWolverine(options => options.Discovery.IncludeType(typeof(WhoSentThisHandler))); } + public void AddOperationPolicies(OperationPolicies policies) + { + } + public void AddMcpTools(IMcpServerBuilder tools) { }