feat(zgw): real per-request identity seam + citizen-scoping (WP-53)
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:
@@ -2,6 +2,7 @@ using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using BigRegister.Api.Contracts;
|
||||
using BigRegister.Api.Data;
|
||||
using BigRegister.Domain.Authorization;
|
||||
|
||||
namespace BigRegister.Api.Zgw;
|
||||
|
||||
@@ -26,15 +27,15 @@ public sealed class OpenZaakDocumentSource(HttpClient http, ZgwTokenProvider tok
|
||||
// existing sync upload/submit endpoints, same reasoning as OpenZaakZaakSource.
|
||||
public UploadResponse Upload(
|
||||
string localId, string categoryId, string wizardId, string fileName, string contentType,
|
||||
byte[] content, string owner) =>
|
||||
UploadAsync(localId, categoryId, wizardId, fileName, contentType, content, owner)
|
||||
byte[] content, CallerIdentity caller) =>
|
||||
UploadAsync(localId, categoryId, wizardId, fileName, contentType, content, caller)
|
||||
.GetAwaiter().GetResult();
|
||||
|
||||
private async Task<UploadResponse> UploadAsync(
|
||||
string localId, string categoryId, string wizardId, string fileName, string contentType,
|
||||
byte[] content, string owner)
|
||||
byte[] content, CallerIdentity caller)
|
||||
{
|
||||
var doc = DocumentStore.Add(localId, categoryId, wizardId, fileName, contentType, content, owner);
|
||||
var doc = DocumentStore.Add(localId, categoryId, wizardId, fileName, contentType, content, caller.Bsn);
|
||||
|
||||
if (!options.InformatieobjecttypeUrls.TryGetValue(categoryId, out var informatieobjecttypeUrl))
|
||||
throw new InvalidOperationException(
|
||||
@@ -54,7 +55,7 @@ public sealed class OpenZaakDocumentSource(HttpClient http, ZgwTokenProvider tok
|
||||
// ponytail: hardcoded "openbaar" (public) — real usage would likely vary the
|
||||
// confidentiality level per category (e.g. an identity document is more sensitive
|
||||
// than a diploma); a fixed value is enough to prove the seam end-to-end.
|
||||
Vertrouwelijkheidaanduiding: "openbaar"));
|
||||
Vertrouwelijkheidaanduiding: "openbaar"), caller);
|
||||
|
||||
DocumentStore.SetDrcUrl(doc.DocumentId, eio.Url);
|
||||
return new UploadResponse(doc.DocumentId, doc.LocalId);
|
||||
@@ -64,21 +65,21 @@ public sealed class OpenZaakDocumentSource(HttpClient http, ZgwTokenProvider tok
|
||||
/// once a zaak exists, POST a zaakinformatieobject for every document that has a DRC url —
|
||||
/// documents uploaded before Zgw:Enabled was ever true (or under a config gap) simply have
|
||||
/// no DrcUrl yet and are skipped, matching "nothing extra to link" for the local case.</summary>
|
||||
public void LinkToZaak(IReadOnlyList<string> documentIds, string? zaakUrl)
|
||||
public void LinkToZaak(IReadOnlyList<string> documentIds, string? zaakUrl, CallerIdentity caller)
|
||||
{
|
||||
DocumentStore.Link(documentIds);
|
||||
if (zaakUrl is null) return;
|
||||
LinkToZaakAsync(documentIds, zaakUrl).GetAwaiter().GetResult();
|
||||
LinkToZaakAsync(documentIds, zaakUrl, caller).GetAwaiter().GetResult();
|
||||
}
|
||||
|
||||
private async Task LinkToZaakAsync(IReadOnlyList<string> documentIds, string zaakUrl)
|
||||
private async Task LinkToZaakAsync(IReadOnlyList<string> documentIds, string zaakUrl, CallerIdentity caller)
|
||||
{
|
||||
foreach (var documentId in documentIds)
|
||||
{
|
||||
var drcUrl = DocumentStore.Get(documentId)?.DrcUrl;
|
||||
if (drcUrl is null) continue;
|
||||
await zgw.PostAsync<JsonElement>($"{options.ZrcBaseUrl}/zaakinformatieobjecten",
|
||||
new CreateZaakInformatieobjectRequest(zaakUrl, drcUrl));
|
||||
new CreateZaakInformatieobjectRequest(zaakUrl, drcUrl), caller);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using BigRegister.Api.Contracts;
|
||||
using BigRegister.Api.Data;
|
||||
using BigRegister.Domain.Authorization;
|
||||
|
||||
namespace BigRegister.Api.Zgw;
|
||||
|
||||
@@ -32,11 +33,20 @@ public sealed class OpenZaakZaakSource(HttpClient http, ZgwTokenProvider tokens,
|
||||
// whole cases read path async (endpoint + CasesAdmin + interface) if OpenZaak becomes the
|
||||
// default and this blocking call shows up under load.
|
||||
public IReadOnlyList<ApplicationSummaryDto> ListCases(DateTimeOffset now) =>
|
||||
ListCasesAsync().GetAwaiter().GetResult();
|
||||
ListCasesAsync(bsn: null, caller: null).GetAwaiter().GetResult();
|
||||
|
||||
private async Task<IReadOnlyList<ApplicationSummaryDto>> ListCasesAsync()
|
||||
/// <summary>WP-53: same read, filtered to one citizen's own zaken via ZGW's rol filter param
|
||||
/// (see <see cref="ListCasesAsync"/>) — and minted with that citizen's identity, not the
|
||||
/// system-level one <see cref="ListCases"/> uses.</summary>
|
||||
public IReadOnlyList<ApplicationSummaryDto> ListMyCases(CallerIdentity caller, DateTimeOffset now) =>
|
||||
ListCasesAsync(caller.Bsn, caller).GetAwaiter().GetResult();
|
||||
|
||||
private async Task<IReadOnlyList<ApplicationSummaryDto>> ListCasesAsync(string? bsn, CallerIdentity? caller)
|
||||
{
|
||||
var zaken = await GetAllAsync<ZgwZaak>($"{options.ZrcBaseUrl}/zaken");
|
||||
var url = $"{options.ZrcBaseUrl}/zaken";
|
||||
if (bsn is not null)
|
||||
url += $"?rol__betrokkeneIdentificatie__natuurlijkPersoon__inpBsn={Uri.EscapeDataString(bsn)}";
|
||||
var zaken = await GetAllAsync<ZgwZaak>(url, caller);
|
||||
var labels = new Dictionary<string, string>();
|
||||
var result = new List<ApplicationSummaryDto>(zaken.Count);
|
||||
foreach (var z in zaken)
|
||||
@@ -49,13 +59,13 @@ public sealed class OpenZaakZaakSource(HttpClient http, ZgwTokenProvider tokens,
|
||||
}
|
||||
|
||||
/// <summary>Follow the <c>next</c> links, accumulating every page's results.</summary>
|
||||
private async Task<IReadOnlyList<T>> GetAllAsync<T>(string url)
|
||||
private async Task<IReadOnlyList<T>> GetAllAsync<T>(string url, CallerIdentity? caller = null)
|
||||
{
|
||||
var all = new List<T>();
|
||||
string? next = url;
|
||||
while (next is not null)
|
||||
{
|
||||
var page = await zgw.GetAsync<ZgwPage<T>>(next);
|
||||
var page = await zgw.GetAsync<ZgwPage<T>>(next, caller);
|
||||
all.AddRange(page.Results);
|
||||
next = page.Next;
|
||||
}
|
||||
@@ -80,10 +90,10 @@ public sealed class OpenZaakZaakSource(HttpClient http, ZgwTokenProvider tokens,
|
||||
/// already marked Submitted locally (ApplicationStore.Submit already ran) but has no zaak.
|
||||
/// Acceptable for a first write slice against a demo backend; a production arc would need a
|
||||
/// retry/reconciliation story (or an outbox) before this dual-write can be trusted.
|
||||
public (string Referentie, AanvraagStatusDto Status, string? ZaakUrl) CreateZaak(Aanvraag aanvraag, DateTimeOffset now) =>
|
||||
CreateZaakAsync(aanvraag, now).GetAwaiter().GetResult();
|
||||
public (string Referentie, AanvraagStatusDto Status, string? ZaakUrl) CreateZaak(Aanvraag aanvraag, DateTimeOffset now, CallerIdentity caller) =>
|
||||
CreateZaakAsync(aanvraag, now, caller).GetAwaiter().GetResult();
|
||||
|
||||
private async Task<(string Referentie, AanvraagStatusDto Status, string? ZaakUrl)> CreateZaakAsync(Aanvraag aanvraag, DateTimeOffset now)
|
||||
private async Task<(string Referentie, AanvraagStatusDto Status, string? ZaakUrl)> CreateZaakAsync(Aanvraag aanvraag, DateTimeOffset now, CallerIdentity caller)
|
||||
{
|
||||
if (!options.ZaaktypeUrls.TryGetValue(aanvraag.Type, out var zaaktypeUrl))
|
||||
throw new InvalidOperationException(
|
||||
@@ -95,11 +105,11 @@ public sealed class OpenZaakZaakSource(HttpClient http, ZgwTokenProvider tokens,
|
||||
VerantwoordelijkeOrganisatie: options.VerantwoordelijkeOrganisatie,
|
||||
Startdatum: DateOnly.FromDateTime(now.UtcDateTime),
|
||||
Identificatie: aanvraag.Referentie
|
||||
?? throw new InvalidOperationException("Aanvraag has no Referentie yet — submit it locally first.")));
|
||||
?? throw new InvalidOperationException("Aanvraag has no Referentie yet — submit it locally first.")), caller);
|
||||
|
||||
var statustypeUrl = await FirstStatustypeUrlAsync(zaaktypeUrl);
|
||||
await zgw.PostAsync<JsonElement>($"{options.ZrcBaseUrl}/statussen",
|
||||
new CreateStatusRequest(zaak.Url, statustypeUrl, now));
|
||||
new CreateStatusRequest(zaak.Url, statustypeUrl, now), caller);
|
||||
|
||||
var roltypeUrl = await FirstInitiatorRoltypeUrlAsync(zaaktypeUrl);
|
||||
await zgw.PostAsync<JsonElement>($"{options.ZrcBaseUrl}/rollen", new CreateRolRequest(
|
||||
@@ -107,7 +117,7 @@ public sealed class OpenZaakZaakSource(HttpClient http, ZgwTokenProvider tokens,
|
||||
BetrokkeneType: "natuurlijk_persoon",
|
||||
Roltype: roltypeUrl,
|
||||
Roltoelichting: "Initiator",
|
||||
BetrokkeneIdentificatie: new BetrokkeneIdentificatie(aanvraag.Owner)));
|
||||
BetrokkeneIdentificatie: new BetrokkeneIdentificatie(aanvraag.Owner)), caller);
|
||||
|
||||
return (zaak.Identificatie, ZgwZaakMapper.ToCreatedStatusDto(zaak.Identificatie), zaak.Url);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using BigRegister.Domain.Authorization;
|
||||
|
||||
namespace BigRegister.Api.Zgw;
|
||||
|
||||
@@ -7,33 +8,35 @@ namespace BigRegister.Api.Zgw;
|
||||
/// Shared GET/POST-with-Bearer-JWT plumbing for the ZGW source classes. Factored out of
|
||||
/// <see cref="OpenZaakZaakSource"/> once <c>OpenZaakDocumentSource</c> (WP-51) needed the
|
||||
/// identical auth + JSON + error-handling boilerplate — every ZGW call mints a fresh token
|
||||
/// (<see cref="ZgwTokenProvider"/>) and expects/returns JSON.
|
||||
/// (<see cref="ZgwTokenProvider"/>) and expects/returns JSON. <paramref name="caller"/> is
|
||||
/// optional (WP-53): omitted for calls not tied to one citizen (metadata lookups, the admin
|
||||
/// cross-owner list), which mint with the BFF's own system identity instead.
|
||||
/// </summary>
|
||||
internal sealed class ZgwHttpClient(HttpClient http, ZgwTokenProvider tokens)
|
||||
{
|
||||
public async Task<T> GetAsync<T>(string url)
|
||||
public async Task<T> GetAsync<T>(string url, CallerIdentity? caller = null)
|
||||
{
|
||||
using var req = new HttpRequestMessage(HttpMethod.Get, url);
|
||||
Authorize(req);
|
||||
Authorize(req, caller);
|
||||
using var res = await http.SendAsync(req);
|
||||
res.EnsureSuccessStatusCode();
|
||||
return (await res.Content.ReadFromJsonAsync<T>())
|
||||
?? throw new InvalidOperationException($"ZGW GET {url} returned null body.");
|
||||
}
|
||||
|
||||
public async Task<T> PostAsync<T>(string url, object body)
|
||||
public async Task<T> PostAsync<T>(string url, object body, CallerIdentity? caller = null)
|
||||
{
|
||||
using var req = new HttpRequestMessage(HttpMethod.Post, url) { Content = JsonContent.Create(body) };
|
||||
Authorize(req);
|
||||
Authorize(req, caller);
|
||||
using var res = await http.SendAsync(req);
|
||||
res.EnsureSuccessStatusCode();
|
||||
return (await res.Content.ReadFromJsonAsync<T>())
|
||||
?? throw new InvalidOperationException($"ZGW POST {url} returned null body.");
|
||||
}
|
||||
|
||||
private void Authorize(HttpRequestMessage req)
|
||||
private void Authorize(HttpRequestMessage req, CallerIdentity? caller)
|
||||
{
|
||||
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokens.Mint());
|
||||
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", caller is null ? tokens.Mint() : tokens.Mint(caller));
|
||||
req.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using BigRegister.Domain.Authorization;
|
||||
|
||||
namespace BigRegister.Api.Zgw;
|
||||
|
||||
@@ -18,7 +19,17 @@ namespace BigRegister.Api.Zgw;
|
||||
/// </summary>
|
||||
public sealed class ZgwTokenProvider(ZgwOptions options)
|
||||
{
|
||||
public string Mint()
|
||||
/// <summary>System-level identity (this BFF acting as itself) — for calls not tied to one
|
||||
/// specific citizen (e.g. the admin cross-owner <c>ListCases</c>).</summary>
|
||||
public string Mint() => MintCore(options.UserId, options.UserRepresentation);
|
||||
|
||||
/// <summary>Per-request variant (WP-53): the ZGW audit trail (<c>user_id</c>/
|
||||
/// <c>user_representation</c>) reflects the acting citizen instead of this BFF's static
|
||||
/// config identity, for any call made on a specific citizen's behalf (create zaak, upload,
|
||||
/// link, citizen-scoped list).</summary>
|
||||
public string Mint(CallerIdentity caller) => MintCore(caller.Bsn, caller.DisplayName);
|
||||
|
||||
private string MintCore(string userId, string userRepresentation)
|
||||
{
|
||||
var header = new { alg = "HS256", typ = "JWT" };
|
||||
var payload = new
|
||||
@@ -26,8 +37,8 @@ public sealed class ZgwTokenProvider(ZgwOptions options)
|
||||
iss = options.ClientId,
|
||||
iat = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
|
||||
client_id = options.ClientId,
|
||||
user_id = options.UserId,
|
||||
user_representation = options.UserRepresentation,
|
||||
user_id = userId,
|
||||
user_representation = userRepresentation,
|
||||
};
|
||||
|
||||
var signingInput = $"{Encode(header)}.{Encode(payload)}";
|
||||
|
||||
Reference in New Issue
Block a user