From f3475648bc948610bd7955b18ee987c4c4d9f415 Mon Sep 17 00:00:00 2001 From: Chrison Simtian Date: Sun, 8 Nov 2026 13:40:51 +1300 Subject: [PATCH] Keep the request body across the session re-login retry --- src/UnifiSharp/Legacy/UnifiLegacySession.cs | 53 +++++++++- .../UnifiLegacySessionRetryTests.cs | 96 +++++++++++++++++++ 2 files changed, 145 insertions(+), 4 deletions(-) create mode 100644 tests/UnifiSharp.Tests/UnifiLegacySessionRetryTests.cs diff --git a/src/UnifiSharp/Legacy/UnifiLegacySession.cs b/src/UnifiSharp/Legacy/UnifiLegacySession.cs index 9ae918f..6e4a28e 100644 --- a/src/UnifiSharp/Legacy/UnifiLegacySession.cs +++ b/src/UnifiSharp/Legacy/UnifiLegacySession.cs @@ -93,7 +93,8 @@ public async Task SendAsync( await LoginAsync(ct).ConfigureAwait(false); } - var resp = await SendOnceAsync(method, relativePath, content, ct).ConfigureAwait(false); + var body = await Body.CaptureAsync(content, ct).ConfigureAwait(false); + var resp = await SendOnceAsync(method, relativePath, body.Fresh(), ct).ConfigureAwait(false); // Re-auth-and-retry only makes sense for a session that can expire. In API-key // mode a 401 means the key is wrong or unprivileged, and retrying would just @@ -102,7 +103,7 @@ public async Task SendAsync( { resp.Dispose(); await LoginAsync(ct).ConfigureAwait(false); - resp = await SendOnceAsync(method, relativePath, content, ct).ConfigureAwait(false); + resp = await SendOnceAsync(method, relativePath, body.Fresh(), ct).ConfigureAwait(false); } return resp; @@ -121,12 +122,13 @@ public async Task SendAbsoluteAsync( await LoginAsync(ct).ConfigureAwait(false); } - var resp = await SendOnceAsync(method, url, content, ct).ConfigureAwait(false); + var body = await Body.CaptureAsync(content, ct).ConfigureAwait(false); + var resp = await SendOnceAsync(method, url, body.Fresh(), ct).ConfigureAwait(false); if (resp.StatusCode == HttpStatusCode.Unauthorized && !_options.UsesApiKey) { resp.Dispose(); await LoginAsync(ct).ConfigureAwait(false); - resp = await SendOnceAsync(method, url, content, ct).ConfigureAwait(false); + resp = await SendOnceAsync(method, url, body.Fresh(), ct).ConfigureAwait(false); } return resp; @@ -177,6 +179,49 @@ private void CaptureCsrf(HttpResponseMessage resp) } } + // SendOnceAsync disposes its request, and with it the content, so a retry after the + // re-login cannot reuse the caller's HttpContent. Read the bytes and headers once and + // build a fresh content per attempt. + private sealed class Body + { + private byte[]? _bytes; + private List> _headers = []; + + public static async Task CaptureAsync(HttpContent? content, CancellationToken ct) + { + var b = new Body(); + if (content is null) + { + return b; + } + + using (content) + { + b._bytes = await content.ReadAsByteArrayAsync(ct).ConfigureAwait(false); + b._headers = content.Headers.Select(h => KeyValuePair.Create(h.Key, h.Value.ToArray())).ToList(); + } + + return b; + } + + public HttpContent? Fresh() + { + if (_bytes is null) + { + return null; + } + + var c = new ByteArrayContent(_bytes); + c.Headers.Clear(); + foreach (var (name, values) in _headers) + { + c.Headers.TryAddWithoutValidation(name, values); + } + + return c; + } + } + internal static StringContent JsonBody(string json) => new(json, Encoding.UTF8, "application/json"); private static string Truncate(string s) => s.Length > 300 ? s[..300] : s; diff --git a/tests/UnifiSharp.Tests/UnifiLegacySessionRetryTests.cs b/tests/UnifiSharp.Tests/UnifiLegacySessionRetryTests.cs new file mode 100644 index 0000000..6476bd5 --- /dev/null +++ b/tests/UnifiSharp.Tests/UnifiLegacySessionRetryTests.cs @@ -0,0 +1,96 @@ +using System.Net; +using UnifiSharp.Legacy; + +namespace UnifiSharp.Tests; + +#pragma warning disable CS0618 // UnifiLegacyClient is intentionally obsolete (ADR-0003) + +// Session auth re-logs-in on a 401 and repeats the request. The repeat must carry the same +// body and headers, not throw because the first attempt disposed them. +public class UnifiLegacySessionRetryTests +{ + private static readonly Uri Site = new("https://gw.lan/proxy/network/api/s/default"); + private static readonly Uri V2 = new("https://gw.lan/proxy/network/v2/api/site/default/nat/abc"); + + [Theory] + [InlineData("PUT")] + [InlineData("POST")] + [InlineData("DELETE")] + [InlineData("GET")] + public async Task SendAsync_repeats_the_request_with_its_body_after_the_relogin(string verb) + { + var h = new ExpiringSessionHandler(); + using var session = h.Session(); + var body = verb is "PUT" or "POST" ? UnifiLegacySession.JsonBody("""{"a":1}""") : null; + + using var resp = await session.SendAsync(new HttpMethod(verb), "rest/thing/1", body); + + Assert.Equal(HttpStatusCode.OK, resp.StatusCode); + AssertLoginThenRepeat(h, verb, body is null ? null : """{"a":1}"""); + } + + [Theory] + [InlineData("PUT")] + [InlineData("POST")] + [InlineData("DELETE")] + public async Task SendAbsoluteAsync_repeats_the_request_with_its_body_after_the_relogin(string verb) + { + var h = new ExpiringSessionHandler(); + using var session = h.Session(); + var body = verb is "PUT" or "POST" ? UnifiLegacySession.JsonBody("""{"b":2}""") : null; + + using var resp = await session.SendAbsoluteAsync(new HttpMethod(verb), V2, body); + + Assert.Equal(HttpStatusCode.OK, resp.StatusCode); + AssertLoginThenRepeat(h, verb, body is null ? null : """{"b":2}"""); + } + + [Fact] + public async Task A_second_401_after_the_relogin_is_returned_not_retried_again() + { + var h = new ExpiringSessionHandler(alwaysExpired: true); + using var session = h.Session(); + + using var resp = await session.SendAsync(HttpMethod.Put, "rest/thing/1", UnifiLegacySession.JsonBody("{}")); + + Assert.Equal(HttpStatusCode.Unauthorized, resp.StatusCode); + Assert.Equal(2, h.Requests.Count(r => !IsLogin(r.Uri))); + } + + private static bool IsLogin(Uri u) => u.AbsolutePath.EndsWith("/api/auth/login"); + + private static void AssertLoginThenRepeat(ExpiringSessionHandler h, string verb, string? body) + { + // The session logs in before its first request; the 401 then forces a second login. + Assert.Equal(["login", "op", "login", "op"], h.Requests.Select(r => IsLogin(r.Uri) ? "login" : "op")); + var attempts = h.Requests.Where(r => !IsLogin(r.Uri)).ToList(); + Assert.All(attempts, a => Assert.Equal(new HttpMethod(verb), a.Method)); + Assert.All(attempts, a => Assert.Equal(body, a.Body)); + if (body is not null) Assert.All(attempts, a => Assert.Equal("application/json", a.ContentType)); + } + + // Answers 401 to the first non-login request (or to all of them), 200 to the login and after. + private sealed class ExpiringSessionHandler(bool alwaysExpired = false) : HttpMessageHandler + { + public List<(HttpMethod Method, Uri Uri, string? Body, string? ContentType)> Requests { get; } = []; + private bool _expiredOnce; + + public UnifiLegacySession Session() => new( + new UnifiLegacyOptions { BaseUrl = Site, Username = "u", Password = "p" }, this); + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken ct) + { + var body = request.Content is null ? null : await request.Content.ReadAsStringAsync(ct); + Requests.Add((request.Method, request.RequestUri!, body, request.Content?.Headers.ContentType?.MediaType)); + if (request.RequestUri!.AbsolutePath.EndsWith("/api/auth/login")) + return new(HttpStatusCode.OK) { Content = new StringContent("{}") }; + if (alwaysExpired || !_expiredOnce) + { + _expiredOnce = true; + return new(HttpStatusCode.Unauthorized) { Content = new StringContent("") }; + } + + return new(HttpStatusCode.OK) { Content = new StringContent("[]") }; + } + } +}