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)); 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); } [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; } = []; } // Routes the two calls the approval makes: GET statustypen (returns the given page) then POST statussen. private static StubHandler ApprovalStub(Recorder rec, string statustypenJson, HttpStatusCode getStatus = HttpStatusCode.OK, HttpStatusCode postStatus = HttpStatusCode.Created) => new(async req => { rec.Requests.Add(req); // Capture the length BEFORE reading the body (ReadAsStringAsync buffers as a side effect, // which would mask whether the gateway buffered it itself — mirrors the zaak-create tests). rec.ContentLengths.Add(req.Content?.Headers.ContentLength); rec.Bodies.Add(req.Content is null ? null : await req.Content.ReadAsStringAsync()); if (req.Method == HttpMethod.Get) return new HttpResponseMessage(getStatus) { Content = new StringContent(statustypenJson, Encoding.UTF8, "application/json"), }; return new HttpResponseMessage(postStatus) { Content = JsonContent.Create(new { url = "http://openzaak/zaken/api/v1/statussen/new" }), }; }); // 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_queries_statustypen_then_posts_the_flagged_eindstatus_against_the_zaak() { var rec = new Recorder(); await Gateway(ApprovalStub(rec, StatustypenPage(withEindstatusFlag: true))) .SetZaakToEindstatusAsync(new Uri(ZaakUrl), Zaaktype, new DateOnly(2026, 6, 4)); Assert.Equal(2, rec.Requests.Count); var get = rec.Requests[0]; Assert.Equal(HttpMethod.Get, get.Method); Assert.StartsWith("http://openzaak/catalogi/api/v1/statustypen", get.RequestUri!.ToString()); Assert.Contains(Uri.EscapeDataString(Zaaktype.ToString()), get.RequestUri.ToString()); Assert.Equal("Bearer", get.Headers.Authorization!.Scheme); var post = rec.Requests[1]; Assert.Equal(HttpMethod.Post, post.Method); Assert.Equal("http://openzaak/zaken/api/v1/statussen", post.RequestUri!.ToString()); Assert.Equal("Bearer", post.Headers.Authorization!.Scheme); // The isEindstatus-flagged statustype (/1) is chosen — even though /2 has a higher volgnummer. Assert.Contains("\"zaak\":\"" + ZaakUrl + "\"", rec.Bodies[1]); Assert.Contains("\"statustype\":\"http://openzaak/catalogi/api/v1/statustypen/1\"", rec.Bodies[1]); Assert.Contains("\"datumStatusGezet\":\"2026-06-04T00:00:00Z\"", rec.Bodies[1]); // The POST body is buffered (Content-Length set), so uwsgi doesn't get a chunked body. Assert.NotNull(rec.ContentLengths[1]); Assert.True(rec.ContentLengths[1] > 0); } [Fact] public async Task Approving_falls_back_to_the_highest_volgnummer_when_no_eindstatus_is_flagged() { var rec = new Recorder(); await Gateway(ApprovalStub(rec, 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.Bodies[1]); } [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, "{}")) .SetZaakToEindstatusAsync(new Uri(ZaakUrl), Zaaktype, new DateOnly(2026, 6, 4))); Assert.Contains("No statustypen found", ex.Message); // It never posts a status 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, "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(); await Assert.ThrowsAsync(() => Gateway(ApprovalStub(rec, "{}", getStatus: HttpStatusCode.InternalServerError)) .SetZaakToEindstatusAsync(new Uri(ZaakUrl), Zaaktype, new DateOnly(2026, 6, 4))); } [Fact] public async Task Approving_throws_when_posting_the_status_fails() { var rec = new Recorder(); await Assert.ThrowsAsync(() => Gateway(ApprovalStub(rec, StatustypenPage(withEindstatusFlag: true), postStatus: HttpStatusCode.BadRequest)) .SetZaakToEindstatusAsync(new Uri(ZaakUrl), Zaaktype, new DateOnly(2026, 6, 4))); // It resolved the eindstatus and attempted the POST before failing. Assert.Equal(2, rec.Requests.Count); } [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)); } }