feat(zgw): real per-request identity seam + citizen-scoping (WP-53)
CI / frontend (push) Failing after 1m19s
CI / backend (push) Successful in 2m0s
CI / e2e (push) Successful in 3m57s
CI / storybook-a11y (push) Successful in 7m45s
CI / semgrep (push) Successful in 1m6s
CI / api-client-drift (push) Successful in 1m55s

Replaces the hardcoded DocumentStore.DemoOwner and the static ZgwOptions
UserId/UserRepresentation with one per-request CallerIdentity, resolved by a
pluggable IIdentityProvider (StubIdentityProvider reads X-Role/X-Subject
today; a real OIDC/DigiD provider swaps in without touching any consumer).

- Domain/Authorization/{CallerIdentity,IIdentityProvider,StubIdentityProvider}.cs
  + a resolution middleware in Program.cs, right after correlation-id.
- Authz.ResolvePrincipal(ctx) keeps its signature (now reads ctx.Caller().Role),
  so its ~15 call sites needed no changes.
- Every endpoint that passed DocumentStore.DemoOwner to a store now passes
  ctx.Caller().Bsn.
- ZgwTokenProvider gains Mint(CallerIdentity) alongside the original Mint()
  (kept for calls not tied to one citizen); ZgwHttpClient threads an optional
  caller through to pick the right overload.
- IZaakSource gains ListMyCases(caller, now) — the citizen-scoped read
  OpenZaakZaakSource backs with ZGW's rol__...__inpBsn filter. GET /applications
  now routes through it instead of ApplicationStore directly, closing the last
  "reads a static store" gap for a citizen-facing endpoint.

Backend 159/159 tests (+8, incl. an HTTP-level two-identity scoping proof),
npm run ci green, no api-client drift.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
eho
2026-07-30 08:27:53 +02:00
co-authored by Claude Sonnet 5
parent bea04549dd
commit 73172510ea
21 changed files with 418 additions and 110 deletions
@@ -137,6 +137,41 @@ public class ApplicationTests(TestWebApplicationFactory factory) : IClassFixture
Assert.Equal(HttpStatusCode.Conflict, (await _client.DeleteAsync($"/api/v1/applications/{a.Id}")).StatusCode);
}
// --- WP-53: citizen-scoping — GET /applications must never leak across identities. ---
[Fact]
public async Task Applications_are_scoped_to_the_caller_bsn()
{
var mine = await Create("intake");
var createOther = new HttpRequestMessage(HttpMethod.Post, "/api/v1/applications")
{
Content = JsonContent.Create(new { type = "intake" }),
Headers = { { "X-Subject", "999888777" } },
};
var otherRes = await _client.SendAsync(createOther);
Assert.Equal(HttpStatusCode.Created, otherRes.StatusCode);
var other = (await otherRes.Content.ReadFromJsonAsync<ApplicationDetailDto>())!;
try
{
var listOther = new HttpRequestMessage(HttpMethod.Get, "/api/v1/applications") { Headers = { { "X-Subject", "999888777" } } };
var theirCases = (await (await _client.SendAsync(listOther)).Content.ReadFromJsonAsync<List<ApplicationSummaryDto>>())!;
Assert.Contains(theirCases, c => c.Id == other.Id);
Assert.DoesNotContain(theirCases, c => c.Id == mine.Id);
var myCases = (await List())!;
Assert.Contains(myCases, c => c.Id == mine.Id);
Assert.DoesNotContain(myCases, c => c.Id == other.Id);
}
finally
{
var deleteOther = new HttpRequestMessage(HttpMethod.Delete, $"/api/v1/applications/{other.Id}") { Headers = { { "X-Subject", "999888777" } } };
await _client.SendAsync(deleteOther);
await _client.DeleteAsync($"/api/v1/applications/{mine.Id}");
}
}
// --- Auto-approval is computed on read: exercise the window boundary without waiting. ---
private static Aanvraag Accepted(bool autoApprovable) => new()
@@ -1,5 +1,6 @@
using BigRegister.Api.Data;
using BigRegister.Api.Zgw;
using BigRegister.Domain.Authorization;
namespace BigRegister.Tests;
@@ -26,6 +27,8 @@ public class OpenZaakDocumentSourceTests
InformatieobjecttypeUrls = new() { ["identiteit"] = InformatieobjecttypeUrl },
};
private static readonly CallerIdentity Caller = new("111222333", "Dr. Test", PrincipalRole.Drafter);
[Fact]
public void Upload_registers_an_eio_in_drc_and_persists_its_url_locally()
{
@@ -39,7 +42,7 @@ public class OpenZaakDocumentSourceTests
var source = new OpenZaakDocumentSource(new HttpClient(handler), new ZgwTokenProvider(options), options);
var response = source.Upload("local-1", "identiteit", "registratie", "paspoort.pdf", "application/pdf",
"%PDF-1.4 fake"u8.ToArray(), "111222333");
"%PDF-1.4 fake"u8.ToArray(), Caller);
Assert.Equal("local-1", response.LocalId);
Assert.NotEmpty(response.DocumentId);
@@ -65,7 +68,7 @@ public class OpenZaakDocumentSourceTests
var source = new OpenZaakDocumentSource(new HttpClient(handler), new ZgwTokenProvider(options), options);
Assert.Throws<InvalidOperationException>(() =>
source.Upload("local-1", "unknown-category", "registratie", "f.pdf", "application/pdf", [1, 2, 3], "111222333"));
source.Upload("local-1", "unknown-category", "registratie", "f.pdf", "application/pdf", [1, 2, 3], Caller));
}
[Fact]
@@ -75,7 +78,7 @@ public class OpenZaakDocumentSourceTests
var uploadHandler = new ZgwStubHandler(url =>
"""{ "url": "https://oz.example/documenten/api/v1/enkelvoudiginformatieobjecten/eio-1" }""");
var uploader = new OpenZaakDocumentSource(new HttpClient(uploadHandler), new ZgwTokenProvider(options), options);
var doc = uploader.Upload("local-1", "identiteit", "registratie", "paspoort.pdf", "application/pdf", [1, 2, 3], "111222333");
var doc = uploader.Upload("local-1", "identiteit", "registratie", "paspoort.pdf", "application/pdf", [1, 2, 3], Caller);
var linkHandler = new ZgwStubHandler(url => url switch
{
@@ -84,14 +87,14 @@ public class OpenZaakDocumentSourceTests
});
var linker = new OpenZaakDocumentSource(new HttpClient(linkHandler), new ZgwTokenProvider(options), options);
linker.LinkToZaak([doc.DocumentId], $"{ZrcBase}/zaken/uuid-1");
linker.LinkToZaak([doc.DocumentId], $"{ZrcBase}/zaken/uuid-1", Caller);
var body = linkHandler.BodyOf($"{ZrcBase}/zaakinformatieobjecten");
Assert.Contains($"{ZrcBase}/zaken/uuid-1", body);
Assert.Contains("eio-1", body);
// Local link also happened (dual-write) — the document is now Linked (delete blocked).
Assert.Equal(DocumentStore.DeleteResult.Linked, DocumentStore.DeleteOwned(doc.DocumentId, "111222333"));
Assert.Equal(DocumentStore.DeleteResult.Linked, DocumentStore.DeleteOwned(doc.DocumentId, Caller.Bsn));
}
[Fact]
@@ -101,7 +104,7 @@ public class OpenZaakDocumentSourceTests
var handler = new ZgwStubHandler(url => throw new InvalidOperationException($"no HTTP call expected, got {url}"));
var source = new OpenZaakDocumentSource(new HttpClient(handler), new ZgwTokenProvider(options), options);
source.LinkToZaak(["some-document-id"], zaakUrl: null);
source.LinkToZaak(["some-document-id"], zaakUrl: null, Caller);
Assert.Empty(handler.Requests);
}
@@ -1,5 +1,6 @@
using BigRegister.Api.Data;
using BigRegister.Api.Zgw;
using BigRegister.Domain.Authorization;
namespace BigRegister.Tests;
@@ -58,6 +59,26 @@ public class OpenZaakZaakSourceTests
Assert.All(handler.AuthSchemes, s => Assert.Equal("Bearer", s));
}
[Fact]
public void ListMyCases_filters_by_the_callers_bsn()
{
var handler = new ZgwStubHandler(url => url switch
{
_ when url.StartsWith($"{ZrcBase}/zaken") => """{ "count": 0, "next": null, "results": [] }""",
_ => throw new InvalidOperationException($"unexpected ZGW GET {url}"),
});
var options = new ZgwOptions { ZrcBaseUrl = ZrcBase, ZtcBaseUrl = ZtBase, ClientId = "c", Secret = "s" };
var source = new OpenZaakZaakSource(new HttpClient(handler), new ZgwTokenProvider(options), options);
var caller = new CallerIdentity("111222333", "Dr. Test", PrincipalRole.Drafter);
source.ListMyCases(caller, DateTimeOffset.UtcNow);
Assert.Single(handler.Requests, r =>
r.StartsWith($"{ZrcBase}/zaken?") &&
r.Contains("rol__betrokkeneIdentificatie__natuurlijkPersoon__inpBsn=111222333"));
}
[Fact]
public void CreateZaak_posts_zaak_status_and_rol_and_maps_the_result_back()
{
@@ -101,7 +122,8 @@ public class OpenZaakZaakSourceTests
Referentie = "BIG-2026-000123",
};
var (referentie, status, zaakUrl) = source.CreateZaak(aanvraag, new DateTimeOffset(2026, 7, 28, 12, 0, 0, TimeSpan.Zero));
var caller = new CallerIdentity(aanvraag.Owner, "Dr. Test", PrincipalRole.Drafter);
var (referentie, status, zaakUrl) = source.CreateZaak(aanvraag, new DateTimeOffset(2026, 7, 28, 12, 0, 0, TimeSpan.Zero), caller);
Assert.Equal("BIG-2026-000123", referentie);
Assert.Equal("InBehandeling", status.Tag);
@@ -133,7 +155,8 @@ public class OpenZaakZaakSourceTests
var handler = new ZgwStubHandler(url => throw new InvalidOperationException($"no HTTP call expected, got {url}"));
var source = new OpenZaakZaakSource(new HttpClient(handler), new ZgwTokenProvider(options), options);
var aanvraag = new Aanvraag { Id = "a1", Type = "unknown-type", Owner = "111222333", Referentie = "BIG-2026-000123" };
var caller = new CallerIdentity(aanvraag.Owner, "Dr. Test", PrincipalRole.Drafter);
Assert.Throws<InvalidOperationException>(() => source.CreateZaak(aanvraag, DateTimeOffset.UtcNow));
Assert.Throws<InvalidOperationException>(() => source.CreateZaak(aanvraag, DateTimeOffset.UtcNow, caller));
}
}
@@ -0,0 +1,43 @@
using BigRegister.Api.Data;
using BigRegister.Domain.Authorization;
using Microsoft.AspNetCore.Http;
namespace BigRegister.Tests;
/// WP-53: the dev stub identity provider — role from X-Role (unchanged behaviour), subject BSN
/// from the new X-Subject header, defaulting to the single seeded citizen so every existing
/// request (none of which send X-Subject) resolves exactly as before this WP.
public class StubIdentityProviderTests
{
private static CallerIdentity Resolve(string? role, string? subject)
{
var ctx = new DefaultHttpContext();
if (role is not null) ctx.Request.Headers["X-Role"] = role;
if (subject is not null) ctx.Request.Headers["X-Subject"] = subject;
return new StubIdentityProvider().Resolve(ctx);
}
[Fact]
public void No_headers_resolves_to_the_seeded_citizen_as_a_drafter()
{
var caller = Resolve(role: null, subject: null);
Assert.Equal(DocumentStore.DemoOwner, caller.Bsn);
Assert.Equal(PrincipalRole.Drafter, caller.Role);
}
[Theory]
[InlineData("approver", PrincipalRole.Approver)]
[InlineData("admin", PrincipalRole.Admin)]
[InlineData("something-unknown", PrincipalRole.Drafter)]
public void X_role_maps_to_the_principal_role(string header, PrincipalRole expected)
{
Assert.Equal(expected, Resolve(header, subject: null).Role);
}
[Fact]
public void X_subject_overrides_the_default_bsn()
{
var caller = Resolve(role: null, subject: "999888777");
Assert.Equal("999888777", caller.Bsn);
}
}
@@ -2,6 +2,7 @@ using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using BigRegister.Api.Zgw;
using BigRegister.Domain.Authorization;
namespace BigRegister.Tests;
@@ -42,6 +43,19 @@ public class ZgwTokenProviderTests
Assert.InRange(iat, DateTimeOffset.UtcNow.ToUnixTimeSeconds() - 5, DateTimeOffset.UtcNow.ToUnixTimeSeconds() + 5);
}
[Fact]
public void Mint_with_a_caller_carries_that_citizen_not_the_static_config_identity()
{
var caller = new CallerIdentity("111222333", "Dr. Citizen", PrincipalRole.Drafter);
var token = new ZgwTokenProvider(Options).Mint(caller);
var payload = JsonSerializer.Deserialize<JsonElement>(Decode(token.Split('.')[1]));
Assert.Equal("111222333", payload.GetProperty("user_id").GetString());
Assert.Equal("Dr. Citizen", payload.GetProperty("user_representation").GetString());
// iss/client_id stay the BFF's own registered client id either way.
Assert.Equal("big-register", payload.GetProperty("client_id").GetString());
}
[Fact]
public void Signature_verifies_with_the_shared_secret()
{