using System.Net; using System.Net.Http.Json; using System.Text; using System.Text.Json; using Acl.Application; using Acl.Infrastructure; namespace Acl.Tests; public class OpenZaakGatewayTests { private sealed class StubHandler(Func> onSend) : HttpMessageHandler { protected override Task SendAsync(HttpRequestMessage request, CancellationToken ct) => onSend(request); } private static OpenZaakGateway Gateway(StubHandler handler) => new( new HttpClient(handler), new OpenZaakOptions { BaseUrl = new("http://openzaak"), ClientId = "cid", Secret = "sec" }); private static ZaakRequest SampleRequest() => new( "517439943", "517439943", "openbaar", new("http://openzaak/catalogi/api/v1/zaaktypen/big"), new DateOnly(2026, 6, 4), "REG-REF-1"); private static StubHandler Created(out RequestCapture capture) { var c = new RequestCapture(); capture = c; return new StubHandler(async req => { c.Seen = req; // Capture the length BEFORE reading the body: ReadAsStringAsync buffers the // content and would set ContentLength as a side effect, masking the gateway's // own buffering. Read here to assert the gateway sent a length (not chunked). c.ContentLength = req.Content?.Headers.ContentLength; c.Body = req.Content is null ? null : await req.Content.ReadAsStringAsync(); return new HttpResponseMessage(HttpStatusCode.Created) { Content = JsonContent.Create(new { url = "http://openzaak/zaken/api/v1/zaken/xyz" }), }; }); } private sealed class RequestCapture { public HttpRequestMessage? Seen; public string? Body; public long? ContentLength; } [Fact] public async Task Posts_zaak_to_openzaak_with_bearer_and_default_fields_and_returns_url() { var handler = Created(out var capture); var url = await Gateway(handler).OpenZaakAsync(SampleRequest()); Assert.Equal("http://openzaak/zaken/api/v1/zaken/xyz", url.ToString()); Assert.Equal(HttpMethod.Post, capture.Seen!.Method); Assert.Equal("http://openzaak/zaken/api/v1/zaken", capture.Seen.RequestUri!.ToString()); Assert.Equal("Bearer", capture.Seen.Headers.Authorization!.Scheme); Assert.False(string.IsNullOrWhiteSpace(capture.Seen.Headers.Authorization.Parameter)); Assert.Contains("\"bronorganisatie\":\"517439943\"", capture.Body); Assert.Contains("\"verantwoordelijkeOrganisatie\":\"517439943\"", capture.Body); Assert.Contains("\"vertrouwelijkheidaanduiding\":\"openbaar\"", capture.Body); Assert.Contains("\"startdatum\":\"2026-06-04\"", capture.Body); Assert.Contains("\"zaaktype\":\"http://openzaak/catalogi/api/v1/zaaktypen/big\"", capture.Body); // The registration reference is set as the zaak identificatie (#78). Assert.Contains("\"identificatie\":\"REG-REF-1\"", capture.Body); } [Fact] public async Task Sends_the_geo_crs_headers_required_by_the_zaken_api() { var handler = Created(out var capture); await Gateway(handler).OpenZaakAsync(SampleRequest()); Assert.Equal("EPSG:4326", Assert.Single(capture.Seen!.Headers.GetValues("Accept-Crs"))); Assert.Equal("EPSG:4326", Assert.Single(capture.Seen.Content!.Headers.GetValues("Content-Crs"))); } [Fact] public async Task Sends_the_body_with_a_content_length_so_it_is_not_chunked() { // OpenZaak's uwsgi rejects a chunked request body (400). The gateway buffers // the body so a Content-Length is sent. JsonContent has no length until // buffered, so this guards the fix the real-OpenZaak integration test found. var handler = Created(out var capture); await Gateway(handler).OpenZaakAsync(SampleRequest()); Assert.NotNull(capture.ContentLength); Assert.True(capture.ContentLength > 0); } [Fact] public async Task Mints_a_hs256_jwt_carrying_the_acl_identity_claims() { var handler = Created(out var capture); await Gateway(handler).OpenZaakAsync(SampleRequest()); var parts = capture.Seen!.Headers.Authorization!.Parameter!.Split('.'); Assert.Equal(3, parts.Length); using var header = JsonDocument.Parse(DecodeSegment(parts[0])); Assert.Equal("HS256", header.RootElement.GetProperty("alg").GetString()); Assert.Equal("JWT", header.RootElement.GetProperty("typ").GetString()); using var payload = JsonDocument.Parse(DecodeSegment(parts[1])); Assert.Equal("cid", payload.RootElement.GetProperty("client_id").GetString()); Assert.Equal("acl", payload.RootElement.GetProperty("user_id").GetString()); Assert.Equal("acl", payload.RootElement.GetProperty("user_representation").GetString()); } [Fact] public async Task Throws_when_openzaak_rejects_the_request() { var handler = new StubHandler(_ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.BadRequest))); await Assert.ThrowsAsync( () => Gateway(handler).OpenZaakAsync(SampleRequest())); } [Fact] public async Task Throws_when_openzaak_returns_an_empty_body() { var handler = new StubHandler(_ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.Created) { Content = new StringContent("null", Encoding.UTF8, "application/json"), })); var ex = await Assert.ThrowsAsync( () => Gateway(handler).OpenZaakAsync(SampleRequest())); Assert.Contains("empty zaak response", ex.Message); } [Fact] public async Task Rejects_a_null_request() { var handler = new StubHandler(_ => throw new InvalidOperationException("should not be sent")); await Assert.ThrowsAsync( () => Gateway(handler).OpenZaakAsync(null!)); } // --- SetZaakToEindstatusAsync (approval / S-09b) --- private const string ZaakUrl = "http://openzaak/zaken/api/v1/zaken/xyz"; private static readonly Uri Zaaktype = new("http://openzaak/catalogi/api/v1/zaaktypen/big"); private sealed class Recorder { public List Requests { get; } = []; public List Bodies { get; } = []; public List ContentLengths { get; } = []; public int IndexOf(string pathContains) => Requests.FindIndex(r => r.RequestUri!.ToString().Contains(pathContains)); // The (body, content-length, request) of the single request whose URL contains the segment. public (string? Body, long? Length, HttpRequestMessage Request) Sent(string pathContains) { var i = IndexOf(pathContains); return (Bodies[i], ContentLengths[i], Requests[i]); } } // Per-route response config for the four calls the approval makes. private sealed class OzRoutes { public string StatustypenJson { get; init; } = StatustypenPage(withEindstatusFlag: true); public string ResultaattypenJson { get; init; } = """{"results":[{"url":"http://openzaak/catalogi/api/v1/resultaattypen/1","omschrijving":"Geregistreerd"}]}"""; public HttpStatusCode StatustypenStatus { get; init; } = HttpStatusCode.OK; public HttpStatusCode ResultaattypenStatus { get; init; } = HttpStatusCode.OK; public HttpStatusCode ResultaatPostStatus { get; init; } = HttpStatusCode.Created; public HttpStatusCode StatusPostStatus { get; init; } = HttpStatusCode.Created; } // Routes the approval's four calls by URL: GET /statustypen, GET /resultaattypen (catalogus), // then POST /resultaten and POST /statussen (zaken). private static StubHandler ApprovalStub(Recorder rec, OzRoutes routes) => new(async req => { rec.Requests.Add(req); // Capture the length BEFORE reading the body (ReadAsStringAsync buffers as a side effect). rec.ContentLengths.Add(req.Content?.Headers.ContentLength); rec.Bodies.Add(req.Content is null ? null : await req.Content.ReadAsStringAsync()); var url = req.RequestUri!.ToString(); if (req.Method == HttpMethod.Get && url.Contains("/statustypen")) return Json(routes.StatustypenStatus, routes.StatustypenJson); if (req.Method == HttpMethod.Get && url.Contains("/resultaattypen")) return Json(routes.ResultaattypenStatus, routes.ResultaattypenJson); if (url.Contains("/resultaten")) return Json(routes.ResultaatPostStatus, """{"url":"http://openzaak/zaken/api/v1/resultaten/new"}"""); return Json(routes.StatusPostStatus, """{"url":"http://openzaak/zaken/api/v1/statussen/new"}"""); }); private static HttpResponseMessage Json(HttpStatusCode status, string body) => new(status) { Content = new StringContent(body, Encoding.UTF8, "application/json") }; // Two statustypen; the eindstatus is flagged on the *lower* volgnummer so the tests prove the // isEindstatus flag is preferred over "highest volgnummer", not coincidentally equal to it. private static string StatustypenPage(bool withEindstatusFlag) => JsonSerializer.Serialize(new { results = new object[] { new { url = "http://openzaak/catalogi/api/v1/statustypen/1", volgnummer = 1, isEindstatus = withEindstatusFlag }, new { url = "http://openzaak/catalogi/api/v1/statustypen/2", volgnummer = 2, isEindstatus = false }, }, }); [Fact] public async Task Approving_sets_a_resultaat_then_posts_the_flagged_eindstatus_against_the_zaak() { var rec = new Recorder(); await Gateway(ApprovalStub(rec, new OzRoutes())) .SetZaakToEindstatusAsync(new Uri(ZaakUrl), Zaaktype, new DateOnly(2026, 6, 4)); Assert.Equal(4, rec.Requests.Count); // Both catalogus queries filter by the zaaktype and carry the bearer. var statustypenGet = rec.Sent("/statustypen").Request; Assert.Equal(HttpMethod.Get, statustypenGet.Method); Assert.Contains(Uri.EscapeDataString(Zaaktype.ToString()), statustypenGet.RequestUri!.ToString()); Assert.Equal("Bearer", statustypenGet.Headers.Authorization!.Scheme); Assert.Contains(Uri.EscapeDataString(Zaaktype.ToString()), rec.Sent("/resultaattypen").Request.RequestUri!.ToString()); // OpenZaak requires a resultaat before the eindstatus, so /resultaten precedes /statussen. Assert.True(rec.IndexOf("/resultaten") < rec.IndexOf("/statussen")); var resultaat = rec.Sent("/resultaten"); Assert.Equal("http://openzaak/zaken/api/v1/resultaten", resultaat.Request.RequestUri!.ToString()); Assert.Equal("Bearer", resultaat.Request.Headers.Authorization!.Scheme); Assert.Contains("\"zaak\":\"" + ZaakUrl + "\"", resultaat.Body); Assert.Contains("\"resultaattype\":\"http://openzaak/catalogi/api/v1/resultaattypen/1\"", resultaat.Body); Assert.True(resultaat.Length > 0); var status = rec.Sent("/statussen"); Assert.Equal("http://openzaak/zaken/api/v1/statussen", status.Request.RequestUri!.ToString()); Assert.Equal("Bearer", status.Request.Headers.Authorization!.Scheme); Assert.Contains("\"zaak\":\"" + ZaakUrl + "\"", status.Body); // The isEindstatus-flagged statustype (/1) is chosen — even though /2 has a higher volgnummer. Assert.Contains("\"statustype\":\"http://openzaak/catalogi/api/v1/statustypen/1\"", status.Body); Assert.Contains("\"datumStatusGezet\":\"2026-06-04T00:00:00Z\"", status.Body); // Bodies are buffered (Content-Length set), so uwsgi doesn't get a chunked body. Assert.True(status.Length > 0); } [Fact] public async Task Approving_selects_the_geregistreerd_resultaat_by_name_when_several_exist() { // Once S-10c adds a second resultaattype (Vervallen), picking the first is ambiguous — the // Zaken API does not guarantee order. Approval must resolve its resultaat by omschrijving. var rec = new Recorder(); var twoResultaattypen = """ {"results":[ {"url":"http://openzaak/catalogi/api/v1/resultaattypen/vervallen","omschrijving":"Vervallen"}, {"url":"http://openzaak/catalogi/api/v1/resultaattypen/geregistreerd","omschrijving":"Geregistreerd"} ]} """; await Gateway(ApprovalStub(rec, new OzRoutes { ResultaattypenJson = twoResultaattypen })) .SetZaakToEindstatusAsync(new Uri(ZaakUrl), Zaaktype, new DateOnly(2026, 6, 4)); Assert.Contains("\"resultaattype\":\"http://openzaak/catalogi/api/v1/resultaattypen/geregistreerd\"", rec.Sent("/resultaten").Body); } // --- SetZaakToCancellationStatusAsync (document-timeout cancellation / S-10c) --- // A catalogus with the three statustypen S-10c seeds (Geannuleerd is non-terminal, below the // Afgehandeld eindstatus) and both resultaattypen. Cancellation must resolve "Geannuleerd" and // "Vervallen" by omschrijving, never the approval pair. private const string CancellationStatustypenJson = """ {"results":[ {"url":"http://openzaak/catalogi/api/v1/statustypen/ontvangen","volgnummer":1,"omschrijving":"Ontvangen","isEindstatus":false}, {"url":"http://openzaak/catalogi/api/v1/statustypen/geannuleerd","volgnummer":2,"omschrijving":"Geannuleerd","isEindstatus":false}, {"url":"http://openzaak/catalogi/api/v1/statustypen/afgehandeld","volgnummer":3,"omschrijving":"Afgehandeld","isEindstatus":true} ]} """; private const string CancellationResultaattypenJson = """ {"results":[ {"url":"http://openzaak/catalogi/api/v1/resultaattypen/geregistreerd","omschrijving":"Geregistreerd"}, {"url":"http://openzaak/catalogi/api/v1/resultaattypen/vervallen","omschrijving":"Vervallen"} ]} """; [Fact] public async Task Cancelling_records_the_vervallen_resultaat_then_the_geannuleerd_status_against_the_zaak() { var rec = new Recorder(); await Gateway(ApprovalStub(rec, new OzRoutes { StatustypenJson = CancellationStatustypenJson, ResultaattypenJson = CancellationResultaattypenJson, })).SetZaakToCancellationStatusAsync(new Uri(ZaakUrl), Zaaktype, new DateOnly(2026, 6, 4)); // Resultaat precedes status (OpenZaak requires a resultaat before a closing/terminal status). Assert.True(rec.IndexOf("/resultaten") < rec.IndexOf("/statussen")); var resultaat = rec.Sent("/resultaten"); Assert.Contains("\"zaak\":\"" + ZaakUrl + "\"", resultaat.Body); // The cancellation resultaat (Vervallen) is chosen by name — not the approval one (Geregistreerd). Assert.Contains("\"resultaattype\":\"http://openzaak/catalogi/api/v1/resultaattypen/vervallen\"", resultaat.Body); var status = rec.Sent("/statussen"); Assert.Contains("\"zaak\":\"" + ZaakUrl + "\"", status.Body); // The Geannuleerd statustype is chosen by name — not the Afgehandeld eindstatus (approval). Assert.Contains("\"statustype\":\"http://openzaak/catalogi/api/v1/statustypen/geannuleerd\"", status.Body); Assert.Contains("\"datumStatusGezet\":\"2026-06-04T00:00:00Z\"", status.Body); } [Fact] public async Task Cancelling_throws_when_the_zaaktype_has_no_geannuleerd_statustype() { var rec = new Recorder(); var ex = await Assert.ThrowsAsync(() => Gateway(ApprovalStub(rec, new OzRoutes { // Only the approval statustypen — no "Geannuleerd". StatustypenJson = StatustypenPage(withEindstatusFlag: true), ResultaattypenJson = CancellationResultaattypenJson, })).SetZaakToCancellationStatusAsync(new Uri(ZaakUrl), Zaaktype, new DateOnly(2026, 6, 4))); Assert.Contains("Geannuleerd", ex.Message); } [Fact] public async Task Cancelling_rejects_a_null_zaak_without_calling_openzaak() { var handler = new StubHandler(_ => throw new InvalidOperationException("should not be sent")); await Assert.ThrowsAsync(() => Gateway(handler).SetZaakToCancellationStatusAsync(null!, Zaaktype, new DateOnly(2026, 6, 4))); } [Fact] public async Task Cancelling_rejects_a_null_zaaktype_without_calling_openzaak() { var handler = new StubHandler(_ => throw new InvalidOperationException("should not be sent")); await Assert.ThrowsAsync(() => Gateway(handler).SetZaakToCancellationStatusAsync(new Uri(ZaakUrl), null!, new DateOnly(2026, 6, 4))); } [Fact] public async Task Cancelling_surfaces_the_failure_when_recording_the_resultaat_is_rejected() { var rec = new Recorder(); var ex = await Assert.ThrowsAsync(() => Gateway(ApprovalStub(rec, new OzRoutes { StatustypenJson = CancellationStatustypenJson, ResultaattypenJson = CancellationResultaattypenJson, ResultaatPostStatus = HttpStatusCode.BadRequest, })).SetZaakToCancellationStatusAsync(new Uri(ZaakUrl), Zaaktype, new DateOnly(2026, 6, 4))); Assert.Contains("cancellation resultaat", ex.Message); // It fails on the resultaat, before it ever posts the status. Assert.Equal(-1, rec.IndexOf("/statussen")); } [Fact] public async Task Cancelling_surfaces_the_failure_when_recording_the_status_is_rejected() { var rec = new Recorder(); var ex = await Assert.ThrowsAsync(() => Gateway(ApprovalStub(rec, new OzRoutes { StatustypenJson = CancellationStatustypenJson, ResultaattypenJson = CancellationResultaattypenJson, StatusPostStatus = HttpStatusCode.BadRequest, })).SetZaakToCancellationStatusAsync(new Uri(ZaakUrl), Zaaktype, new DateOnly(2026, 6, 4))); Assert.Contains("cancellation status", ex.Message); } [Fact] public async Task Approving_falls_back_to_the_highest_volgnummer_when_no_eindstatus_is_flagged() { var rec = new Recorder(); await Gateway(ApprovalStub(rec, new OzRoutes { StatustypenJson = StatustypenPage(withEindstatusFlag: false) })) .SetZaakToEindstatusAsync(new Uri(ZaakUrl), Zaaktype, new DateOnly(2026, 6, 4)); // No isEindstatus flag → the highest volgnummer (/2) is chosen. Assert.Contains("\"statustype\":\"http://openzaak/catalogi/api/v1/statustypen/2\"", rec.Sent("/statussen").Body); } [Fact] public async Task Approving_throws_when_the_zaaktype_has_no_statustypen() { var rec = new Recorder(); // A page with no `results` property (Results is null) — the eindstatus cannot be resolved. var ex = await Assert.ThrowsAsync(() => Gateway(ApprovalStub(rec, new OzRoutes { StatustypenJson = "{}" })) .SetZaakToEindstatusAsync(new Uri(ZaakUrl), Zaaktype, new DateOnly(2026, 6, 4))); Assert.Contains("No statustypen found", ex.Message); // It never posts anything when it cannot resolve the eindstatus. Assert.Single(rec.Requests); } [Fact] public async Task Approving_throws_when_the_statustypen_response_is_empty() { var rec = new Recorder(); var ex = await Assert.ThrowsAsync(() => Gateway(ApprovalStub(rec, new OzRoutes { StatustypenJson = "null" })) .SetZaakToEindstatusAsync(new Uri(ZaakUrl), Zaaktype, new DateOnly(2026, 6, 4))); Assert.Contains("empty statustypen", ex.Message); Assert.Single(rec.Requests); } [Fact] public async Task Approving_throws_when_the_statustypen_query_fails() { var rec = new Recorder(); var ex = await Assert.ThrowsAsync(() => Gateway(ApprovalStub(rec, new OzRoutes { StatustypenStatus = HttpStatusCode.InternalServerError })) .SetZaakToEindstatusAsync(new Uri(ZaakUrl), Zaaktype, new DateOnly(2026, 6, 4))); Assert.Contains("Querying statustypen", ex.Message); } [Fact] public async Task Approving_throws_when_the_resultaattypen_query_fails() { var rec = new Recorder(); var ex = await Assert.ThrowsAsync(() => Gateway(ApprovalStub(rec, new OzRoutes { ResultaattypenStatus = HttpStatusCode.InternalServerError })) .SetZaakToEindstatusAsync(new Uri(ZaakUrl), Zaaktype, new DateOnly(2026, 6, 4))); Assert.Contains("Querying resultaattypen", ex.Message); Assert.Equal(-1, rec.IndexOf("/resultaten")); } [Fact] public async Task Approving_throws_when_the_zaaktype_has_no_resultaattype() { var rec = new Recorder(); var ex = await Assert.ThrowsAsync(() => Gateway(ApprovalStub(rec, new OzRoutes { ResultaattypenJson = "{}" })) .SetZaakToEindstatusAsync(new Uri(ZaakUrl), Zaaktype, new DateOnly(2026, 6, 4))); Assert.Contains("'Geregistreerd' resultaattype", ex.Message); // Resolved the eindstatus + queried resultaattypen, but posted nothing. Assert.Equal(-1, rec.IndexOf("/resultaten")); Assert.Equal(-1, rec.IndexOf("/statussen")); } [Fact] public async Task Approving_throws_when_posting_the_resultaat_fails() { var rec = new Recorder(); var ex = await Assert.ThrowsAsync(() => Gateway(ApprovalStub(rec, new OzRoutes { ResultaatPostStatus = HttpStatusCode.BadRequest })) .SetZaakToEindstatusAsync(new Uri(ZaakUrl), Zaaktype, new DateOnly(2026, 6, 4))); Assert.Contains("Setting the zaak resultaat", ex.Message); // The status is never posted if the resultaat could not be recorded. Assert.Equal(-1, rec.IndexOf("/statussen")); } [Fact] public async Task Approving_throws_when_posting_the_status_fails() { var rec = new Recorder(); var ex = await Assert.ThrowsAsync(() => Gateway(ApprovalStub(rec, new OzRoutes { StatusPostStatus = HttpStatusCode.BadRequest })) .SetZaakToEindstatusAsync(new Uri(ZaakUrl), Zaaktype, new DateOnly(2026, 6, 4))); Assert.Contains("Setting the zaak status", ex.Message); // It got as far as the resultaat + the status POST (4 calls) before failing. Assert.Equal(4, rec.Requests.Count); } [Fact] public async Task Reading_a_zaak_returns_its_identificatie_with_bearer_and_crs() { RequestCapture? capture = null; var handler = new StubHandler(req => { capture = new RequestCapture { Seen = req }; return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = JsonContent.Create(new { identificatie = "REG-XYZ", url = ZaakUrl }), }); }); var reference = await Gateway(handler).GetZaakIdentificatieAsync(new Uri(ZaakUrl)); Assert.Equal("REG-XYZ", reference); Assert.Equal(HttpMethod.Get, capture!.Seen!.Method); Assert.Equal(ZaakUrl, capture.Seen.RequestUri!.ToString()); Assert.Equal("Bearer", capture.Seen.Headers.Authorization!.Scheme); Assert.Equal("EPSG:4326", Assert.Single(capture.Seen.Headers.GetValues("Accept-Crs"))); } [Fact] public async Task Reading_a_zaak_throws_when_openzaak_rejects_it() { var handler = new StubHandler(_ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.NotFound) { Content = new StringContent("nope") })); var ex = await Assert.ThrowsAsync( () => Gateway(handler).GetZaakIdentificatieAsync(new Uri(ZaakUrl))); Assert.Contains("Reading the zaak", ex.Message); } [Fact] public async Task Reading_a_zaak_throws_when_openzaak_returns_an_empty_body() { var handler = new StubHandler(_ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("null", System.Text.Encoding.UTF8, "application/json"), })); var ex = await Assert.ThrowsAsync( () => Gateway(handler).GetZaakIdentificatieAsync(new Uri(ZaakUrl))); Assert.Contains("empty zaak response", ex.Message); } [Fact] public async Task Reading_a_null_zaak_is_rejected() { var handler = new StubHandler(_ => throw new InvalidOperationException("should not be sent")); await Assert.ThrowsAsync(() => Gateway(handler).GetZaakIdentificatieAsync(null!)); } [Fact] public async Task Approving_rejects_a_null_zaak_or_zaaktype() { var handler = new StubHandler(_ => throw new InvalidOperationException("should not be sent")); await Assert.ThrowsAsync(() => Gateway(handler).SetZaakToEindstatusAsync(null!, Zaaktype, new DateOnly(2026, 6, 4))); await Assert.ThrowsAsync(() => Gateway(handler).SetZaakToEindstatusAsync(new Uri(ZaakUrl), null!, new DateOnly(2026, 6, 4))); } // ZGW tokens are base64url with padding stripped (ZgwToken.B64Url); restore it to decode. private static string DecodeSegment(string segment) { var b64 = segment.Replace('-', '+').Replace('_', '/'); b64 = (b64.Length % 4) switch { 2 => b64 + "==", 3 => b64 + "=", _ => b64 }; return Encoding.UTF8.GetString(Convert.FromBase64String(b64)); } // --- StoreDocumentAsync (diploma upload / S-10b) --- private static readonly Uri Informatieobjecttype = new("http://openzaak/catalogi/api/v1/informatieobjecttypen/dip"); private static DocumentRequest SampleDocument(byte[]? inhoud = null) => new( Bronorganisatie: "517439943", Informatieobjecttype: Informatieobjecttype, Vertrouwelijkheidaanduiding: "openbaar", Zaak: new Uri(ZaakUrl), Creatiedatum: new DateOnly(2026, 6, 4), Titel: "Diploma", Auteur: "zorgprofessional", Taal: "nld", Bestandsnaam: "diploma.pdf", Formaat: "application/pdf", Inhoud: inhoud ?? [1, 2, 3, 4]); // Routes the two document calls: POST /enkelvoudiginformatieobjecten (documenten) then // POST /zaakinformatieobjecten (zaken). private static StubHandler DocumentStub(Recorder rec) => new(async req => { rec.Requests.Add(req); rec.ContentLengths.Add(req.Content?.Headers.ContentLength); rec.Bodies.Add(req.Content is null ? null : await req.Content.ReadAsStringAsync()); return req.RequestUri!.ToString().Contains("/enkelvoudiginformatieobjecten") ? Json(HttpStatusCode.Created, """{"url":"http://openzaak/documenten/api/v1/enkelvoudiginformatieobjecten/doc-1"}""") : Json(HttpStatusCode.Created, """{"url":"http://openzaak/zaken/api/v1/zaakinformatieobjecten/rel-1"}"""); }); [Fact] public async Task Storing_a_document_creates_the_informatieobject_then_relates_it_to_the_zaak() { var rec = new Recorder(); var url = await Gateway(DocumentStub(rec)).StoreDocumentAsync(SampleDocument([10, 20, 30])); Assert.Equal("http://openzaak/documenten/api/v1/enkelvoudiginformatieobjecten/doc-1", url.ToString()); // 1. Create the enkelvoudiginformatieobject in the Documenten API. var create = rec.Sent("/enkelvoudiginformatieobjecten"); Assert.Equal(HttpMethod.Post, create.Request.Method); Assert.Equal("http://openzaak/documenten/api/v1/enkelvoudiginformatieobjecten", create.Request.RequestUri!.ToString()); Assert.Equal("Bearer", create.Request.Headers.Authorization!.Scheme); Assert.Contains("\"bronorganisatie\":\"517439943\"", create.Body); Assert.Contains("\"informatieobjecttype\":\"http://openzaak/catalogi/api/v1/informatieobjecttypen/dip\"", create.Body); Assert.Contains("\"creatiedatum\":\"2026-06-04\"", create.Body); Assert.Contains("\"titel\":\"Diploma\"", create.Body); Assert.Contains("\"auteur\":\"zorgprofessional\"", create.Body); Assert.Contains("\"taal\":\"nld\"", create.Body); Assert.Contains("\"bestandsnaam\":\"diploma.pdf\"", create.Body); Assert.Contains("\"formaat\":\"application/pdf\"", create.Body); Assert.Contains("\"vertrouwelijkheidaanduiding\":\"openbaar\"", create.Body); Assert.Contains("\"status\":\"definitief\"", create.Body); // indicatieGebruiksrecht must be set explicitly (false = no usage restrictions); left null, // OpenZaak refuses to close the zaak this document is related to ("indicatiegebruiksrecht-unset"). Assert.Contains("\"indicatieGebruiksrecht\":false", create.Body); // The file content is base64-encoded into `inhoud`, with its byte length in `bestandsomvang`. Assert.Contains($"\"inhoud\":\"{Convert.ToBase64String([10, 20, 30])}\"", create.Body); Assert.Contains("\"bestandsomvang\":3", create.Body); // 2. Relate that informatieobject to the zaak (Zaken API — no CRS). var relate = rec.Sent("/zaakinformatieobjecten"); Assert.Equal(HttpMethod.Post, relate.Request.Method); Assert.Equal("http://openzaak/zaken/api/v1/zaakinformatieobjecten", relate.Request.RequestUri!.ToString()); Assert.Contains($"\"zaak\":\"{ZaakUrl}\"", relate.Body); Assert.Contains("\"informatieobject\":\"http://openzaak/documenten/api/v1/enkelvoudiginformatieobjecten/doc-1\"", relate.Body); } [Fact] public async Task Storing_a_document_buffers_the_body_and_sends_no_crs_headers() { // uwsgi rejects a chunked body (Content-Length must be present); the Documenten API is not a // geo API, so no CRS headers (unlike the Zaken zaak-create). var rec = new Recorder(); await Gateway(DocumentStub(rec)).StoreDocumentAsync(SampleDocument()); var create = rec.Sent("/enkelvoudiginformatieobjecten"); Assert.NotNull(create.Length); Assert.True(create.Length > 0); Assert.False(create.Request.Headers.Contains("Accept-Crs")); Assert.False(create.Request.Content!.Headers.Contains("Content-Crs")); } [Fact] public async Task Storing_a_document_surfaces_an_openzaak_rejection() { var handler = new StubHandler(_ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent("""{"detail":"bad"}""", Encoding.UTF8, "application/json"), })); var ex = await Assert.ThrowsAsync( () => Gateway(handler).StoreDocumentAsync(SampleDocument())); Assert.Contains("bad", ex.Message); } [Fact] public async Task Storing_a_document_rejects_a_null_request() { var handler = new StubHandler(_ => throw new InvalidOperationException("should not be sent")); await Assert.ThrowsAsync(() => Gateway(handler).StoreDocumentAsync(null!)); } // ── Catalogi resolution by business key (S-27) ──────────────────────────────────────────────── [Fact] public async Task Resolves_the_published_zaaktype_url_by_identificatie() { HttpRequestMessage? seen = null; var handler = new StubHandler(req => { seen = req; return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = JsonContent.Create(new { results = new[] { new { url = "http://openzaak/catalogi/api/v1/zaaktypen/big", identificatie = "BIG-REGISTRATIE" } }, }), }); }); var url = await Gateway(handler).ResolveZaaktypeUrlAsync("BIG-REGISTRATIE"); Assert.Equal("http://openzaak/catalogi/api/v1/zaaktypen/big", url.ToString()); Assert.Equal(HttpMethod.Get, seen!.Method); // Filters to the published zaaktype with that identificatie, and authenticates. Assert.Contains("/catalogi/api/v1/zaaktypen", seen.RequestUri!.ToString()); Assert.Contains("status=definitief", seen.RequestUri!.Query); Assert.Contains("identificatie=BIG-REGISTRATIE", seen.RequestUri!.Query); Assert.Equal("Bearer", seen.Headers.Authorization!.Scheme); } [Fact] public async Task Resolving_a_zaaktype_throws_a_clear_error_when_none_is_published() { var handler = new StubHandler(_ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = JsonContent.Create(new { results = Array.Empty() }), })); var ex = await Assert.ThrowsAsync( () => Gateway(handler).ResolveZaaktypeUrlAsync("BIG-REGISTRATIE")); Assert.Contains("BIG-REGISTRATIE", ex.Message); } [Fact] public async Task Resolves_the_informatieobjecttype_url_by_omschrijving() { HttpRequestMessage? seen = null; var handler = new StubHandler(req => { seen = req; return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = JsonContent.Create(new { results = new[] { new { url = "http://openzaak/catalogi/api/v1/informatieobjecttypen/other", omschrijving = "Overig" }, new { url = "http://openzaak/catalogi/api/v1/informatieobjecttypen/dip", omschrijving = "Diploma" }, }, }), }); }); var url = await Gateway(handler).ResolveInformatieobjecttypeUrlAsync("Diploma"); // Queries the published informatieobjecttypen collection, and matches on omschrijving (not position). Assert.Contains("/catalogi/api/v1/informatieobjecttypen", seen!.RequestUri!.ToString()); Assert.Contains("status=definitief", seen.RequestUri!.Query); Assert.Equal("http://openzaak/catalogi/api/v1/informatieobjecttypen/dip", url.ToString()); } [Fact] public async Task Resolving_a_zaaktype_throws_when_the_response_carries_no_results() { // No "results" property → the page's Results is null; the gateway must treat that as "none // found" (not dereference null). var handler = new StubHandler(_ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = JsonContent.Create(new { count = 0 }), })); await Assert.ThrowsAsync( () => Gateway(handler).ResolveZaaktypeUrlAsync("BIG-REGISTRATIE")); } [Fact] public async Task Resolving_an_informatieobjecttype_throws_when_the_response_carries_no_results() { var handler = new StubHandler(_ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = JsonContent.Create(new { count = 0 }), })); await Assert.ThrowsAsync( () => Gateway(handler).ResolveInformatieobjecttypeUrlAsync("Diploma")); } [Fact] public async Task Resolving_a_zaaktype_surfaces_a_non_success_catalogi_response() { var handler = new StubHandler(_ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent("boom"), })); var ex = await Assert.ThrowsAsync( () => Gateway(handler).ResolveZaaktypeUrlAsync("BIG-REGISTRATIE")); // The error names the resource being queried and includes OpenZaak's body. Assert.Contains("zaaktypen", ex.Message); Assert.Contains("boom", ex.Message); } [Fact] public async Task Resolving_an_informatieobjecttype_surfaces_a_non_success_catalogi_response() { var handler = new StubHandler(_ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent("boom"), })); var ex = await Assert.ThrowsAsync( () => Gateway(handler).ResolveInformatieobjecttypeUrlAsync("Diploma")); Assert.Contains("informatieobjecttypen", ex.Message); } [Fact] public async Task Resolving_an_informatieobjecttype_throws_when_no_omschrijving_matches() { var handler = new StubHandler(_ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = JsonContent.Create(new { results = new[] { new { url = "http://openzaak/catalogi/api/v1/informatieobjecttypen/other", omschrijving = "Overig" } }, }), })); var ex = await Assert.ThrowsAsync( () => Gateway(handler).ResolveInformatieobjecttypeUrlAsync("Diploma")); Assert.Contains("Diploma", ex.Message); } [Fact] public async Task Resolving_rejects_a_blank_business_key_without_calling_openzaak() { var handler = new StubHandler(_ => throw new InvalidOperationException("should not be sent")); await Assert.ThrowsAnyAsync(() => Gateway(handler).ResolveZaaktypeUrlAsync(" ")); await Assert.ThrowsAnyAsync(() => Gateway(handler).ResolveInformatieobjecttypeUrlAsync(" ")); } [Fact] public async Task Listing_zaaktypen_queries_published_zaaktypen_and_maps_them(/* S-15a */) { HttpRequestMessage? seen = null; var handler = new StubHandler(req => { seen = req; const string json = """ {"results":[ {"url":"http://openzaak/catalogi/api/v1/zaaktypen/big","identificatie":"BIG-REGISTRATIE","omschrijving":"BIG-registratie"}, {"url":"http://openzaak/catalogi/api/v1/zaaktypen/her","identificatie":"BIG-HERREGISTRATIE","omschrijving":"BIG-herregistratie"} ]} """; return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json"), }); }); var zaaktypen = await Gateway(handler).ListZaaktypenAsync(); // Only the published zaaktypen collection is queried (status=definitief excludes concepts). Assert.Contains("/catalogi/api/v1/zaaktypen", seen!.RequestUri!.ToString()); Assert.Contains("status=definitief", seen.RequestUri!.ToString()); // Authenticated like the other catalogi reads. Assert.Equal("Bearer", seen.Headers.Authorization!.Scheme); // Each result maps to a public-safe summary (identificatie + omschrijving + url). Assert.Equal(2, zaaktypen.Count); Assert.Equal("BIG-REGISTRATIE", zaaktypen[0].Identificatie); Assert.Equal("BIG-registratie", zaaktypen[0].Omschrijving); Assert.Equal(new Uri("http://openzaak/catalogi/api/v1/zaaktypen/big"), zaaktypen[0].Url); Assert.Equal("BIG-HERREGISTRATIE", zaaktypen[1].Identificatie); } [Fact] public async Task Listing_zaaktypen_returns_empty_when_the_catalogus_has_none() { var handler = new StubHandler(_ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("""{"results":[]}""", Encoding.UTF8, "application/json"), })); var zaaktypen = await Gateway(handler).ListZaaktypenAsync(); Assert.Empty(zaaktypen); } }