Path: redb-identity/tests/redb.Identity.Tests/FullStack/IdempotencySecretTests.cs Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/tests/redb.Identity.Tests/FullStack/IdempotencySecretTests.cs ---- using System.Net; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; using AwesomeAssertions; using redb.Identity.Core.Models; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// An answer that carries a one-time secret (a member marked [OneTimeSecret]) is recorded for its /// Idempotency-Key without its body. The first call answers as before, with the secret. A repeat with the /// same key does not run the operation again and answers {"replayed":true,"secretWithheld":true,...} with /// the status of the first answer. Covered for every secret-bearing operation behind the idempotency cache: /// webhook create and rotate-secret, application rotate-secret, MFA setup; dynamic client registration is not cached. MFA confirm /// and recovery-code regeneration carry their codes through types the marker tests cover (OneTimeSecretsTests). /// [Collection("ProductionHttp")] public class IdempotencySecretTests { private const string Withheld = """{"replayed":true,"secretWithheld":true,"description":"The operation was already carried out for this Idempotency-Key. Its answer carried a secret that is shown only once, so it is not shown again."}"""; private readonly ProductionHttpFixture _fx; private readonly HttpClient _http; public IdempotencySecretTests(ProductionHttpFixture fx) { _fx = fx; _http = fx.Http; } [Fact] public async Task Webhook_create_shows_the_secret_once_and_a_repeat_creates_nothing() { var key = Guid.NewGuid().ToString("N"); var url = $"http://127.0.0.1:9/idem-{key}"; var request = new { url, displayName = "idem", eventTypeFilter = "UserCreated", enabled = false }; var (status1, first) = await Send(HttpMethod.Post, "/api/v1/identity/webhooks", request, key); status1.Should().Be(HttpStatusCode.OK, first); var secret = Json(first).GetProperty("hmacSecret").GetString(); secret.Should().NotBeNullOrEmpty("the first answer shows the generated secret"); var (status2, second, replayed) = await SendReplay(HttpMethod.Post, "/api/v1/identity/webhooks", request, key); status2.Should().Be(status1); replayed.Should().BeTrue(); second.Should().Be(Withheld); var (_, list) = await Send(HttpMethod.Get, "/api/v1/identity/webhooks"); list.Split(url).Length.Should().Be(2, "the repeat did not create a second subscription"); await RecordShouldHoldNoSecret(key, secret!); } [Fact] public async Task Webhook_rotate_secret_is_not_rotated_again_by_a_repeat() { var (_, created) = await Send(HttpMethod.Post, "/api/v1/identity/webhooks", new { url = "http://127.0.0.1:9/idem-rotate", displayName = "idem-rotate", eventTypeFilter = "UserCreated", enabled = false }); var id = Json(created).GetProperty("id").GetInt64(); var key = Guid.NewGuid().ToString("N"); var (status1, first) = await Send(HttpMethod.Post, $"/api/v1/identity/webhooks/{id}/rotate-secret", null, key); status1.Should().Be(HttpStatusCode.OK, first); var rotated = Json(first).GetProperty("hmacSecret").GetString()!; rotated.Should().NotBeNullOrEmpty(); var (_, second, replayed) = await SendReplay(HttpMethod.Post, $"/api/v1/identity/webhooks/{id}/rotate-secret", null, key); replayed.Should().BeTrue(); second.Should().Be(Withheld); var stored = await _fx.UseRedbAsync(redb => redb.LoadAsync(id)); stored!.Props.HmacSecret.Should().Be(rotated, "the repeat did not rotate the secret again"); await RecordShouldHoldNoSecret(key, rotated); } [Fact] public async Task Application_rotate_secret_is_not_rotated_again_by_a_repeat() { var clientId = $"idem-rotate-{Guid.NewGuid():N}"; var (_, created) = await Send(HttpMethod.Post, "/api/v1/identity/applications", new { clientId, clientSecret = "idem-initial-secret", displayName = "Idem rotate" }); var id = long.Parse(Json(created).GetProperty("id").GetString()!); var key = Guid.NewGuid().ToString("N"); var (status1, first) = await Send(HttpMethod.Post, $"/api/v1/identity/applications/{id}/rotate-secret", null, key); status1.Should().Be(HttpStatusCode.OK, first); var newSecret = Json(first).GetProperty("newSecret").GetString()!; newSecret.Should().NotBeNullOrEmpty(); var hashAfterFirst = await ClientSecretHash(id); var (_, second, replayed) = await SendReplay(HttpMethod.Post, $"/api/v1/identity/applications/{id}/rotate-secret", null, key); replayed.Should().BeTrue(); second.Should().Be(Withheld); (await ClientSecretHash(id)).Should().Be(hashAfterFirst, "the repeat did not rotate the secret again"); await RecordShouldHoldNoSecret(key, newSecret); } [Fact] public async Task Mfa_setup_is_withheld_on_a_repeat() { var userId = await CreateUserAsync(); var key = Guid.NewGuid().ToString("N"); var request = new { userId, username = "idem" }; var (status1, setup) = await Send(HttpMethod.Post, "/api/v1/identity/mfa/totp/setup", request, key); status1.Should().Be(HttpStatusCode.OK, setup); var secret = Json(setup).GetProperty("secret_base32").GetString()!; var setupToken = Json(setup).GetProperty("setup_token").GetString()!; var (status2, repeat, replayed) = await SendReplay(HttpMethod.Post, "/api/v1/identity/mfa/totp/setup", request, key); status2.Should().Be(status1); replayed.Should().BeTrue(); repeat.Should().Be(Withheld); await RecordShouldHoldNoSecret(key, secret); await RecordShouldHoldNoSecret(key, setupToken); } [Fact] public async Task A_second_registrant_with_the_same_key_gets_its_own_registration_and_nothing_of_the_first() { var key = Guid.NewGuid().ToString("N"); var body = new { redirect_uris = new[] { "http://localhost/callback" }, client_name = "Idem DCR" }; var first = await _http.SendAsync(Dcr(body, key)); var firstJson = await first.Content.ReadAsStringAsync(); first.StatusCode.Should().Be(HttpStatusCode.Created, firstJson); var firstClient = Json(firstJson).GetProperty("client_id").GetString()!; var firstSecret = Json(firstJson).GetProperty("client_secret").GetString()!; var firstToken = Json(firstJson).GetProperty("registration_access_token").GetString()!; // Another party holding the same initial access token sends the same Idempotency-Key. var second = await _http.SendAsync(Dcr(body, key)); var secondJson = await second.Content.ReadAsStringAsync(); second.StatusCode.Should().Be(HttpStatusCode.Created, secondJson); second.Headers.Contains("Idempotency-Replayed").Should().BeFalse("registration answers are not replayed"); secondJson.Should().NotContain(firstClient).And.NotContain(firstSecret).And.NotContain(firstToken) .And.NotContain("secretWithheld"); Json(secondJson).GetProperty("client_id").GetString().Should().NotBe(firstClient, "it got a registration of its own"); (await _fx.UseRedbAsync(redb => redb.Query().Where(r => r.IdempotencyKey == key).ToListAsync())) .Should().BeEmpty("no record is kept for a registration"); } [Fact] public async Task An_answer_without_a_secret_is_still_replayed_whole() { var (_, created) = await Send(HttpMethod.Post, "/api/v1/identity/webhooks", new { url = "http://127.0.0.1:9/idem-update", displayName = "idem-update", eventTypeFilter = "UserCreated", enabled = false }); var id = Json(created).GetProperty("id").GetInt64(); var key = Guid.NewGuid().ToString("N"); var (_, first) = await Send(HttpMethod.Put, $"/api/v1/identity/webhooks/{id}", new { displayName = "idem-update-2" }, key); var (_, second, replayed) = await SendReplay(HttpMethod.Put, $"/api/v1/identity/webhooks/{id}", new { displayName = "idem-update-2" }, key); replayed.Should().BeTrue(); second.Should().Be(first); var record = await RecordOf(key); record.Props.SecretWithheld.Should().BeFalse(); record.Props.ResponseBody.Should().Be(first); } [Fact] public async Task The_upgrading_statements_remove_a_record_stored_with_its_secret_by_an_earlier_version() { var request = new { url = "http://127.0.0.1:9/idem-upgrade", displayName = "idem-upgrade", eventTypeFilter = "UserCreated", enabled = false }; var key = Guid.NewGuid().ToString("N"); var (_, first) = await Send(HttpMethod.Post, "/api/v1/identity/webhooks", request, key); // Turn the record into what an earlier version stored: the whole answer, secret included. var record = await RecordOf(key); record.Props.SecretWithheld = false; record.Props.ResponseBody = first; await _fx.UseRedbAsync(redb => redb.SaveAsync(record)); var (_, replayedBefore, _) = await SendReplay(HttpMethod.Post, "/api/v1/identity/webhooks", request, key); replayedBefore.Should().Be(first, "an earlier record replays the secret until it is removed"); foreach (var statement in UpgradingStatements()) await _fx.UseRedbAsync(redb => redb.Context.ExecuteAsync(statement)); (await _fx.UseRedbAsync(redb => redb.Query().Where(r => r.IdempotencyKey == key).ToListAsync())) .Should().BeEmpty("the statements removed the record"); var (status, again, replayed) = await SendReplay(HttpMethod.Post, "/api/v1/identity/webhooks", request, key); status.Should().Be(HttpStatusCode.OK, again); replayed.Should().BeFalse("with the record gone the request runs again"); Json(again).GetProperty("id").GetInt64().Should().NotBe(Json(first).GetProperty("id").GetInt64()); await RecordShouldHoldNoSecret(key, Json(again).GetProperty("hmacSecret").GetString()!); } // The SQL block of the "Idempotency records keep no secrets" section of redb.Identity/UPGRADING.md, as published. private static IEnumerable UpgradingStatements() { var dir = new DirectoryInfo(AppContext.BaseDirectory); while (dir is not null && !File.Exists(Path.Combine(dir.FullName, "redb.Identity", "UPGRADING.md"))) dir = dir.Parent; dir.Should().NotBeNull("the test runs inside the repository"); var text = File.ReadAllText(Path.Combine(dir!.FullName, "redb.Identity", "UPGRADING.md")); var section = text[text.IndexOf("### Idempotency records keep no secrets", StringComparison.Ordinal)..]; var start = section.IndexOf("```sql", StringComparison.Ordinal) + "```sql".Length; var sql = section[start..section.IndexOf("```", start, StringComparison.Ordinal)]; return sql.Split(';').Select(s => s.Trim()).Where(s => s.Length > 0); } private async Task RecordShouldHoldNoSecret(string key, string secret) { var record = await RecordOf(key); record.Props.SecretWithheld.Should().BeTrue(); record.Props.ResponseBody.Should().BeNull(); JsonSerializer.Serialize(record.Props).Should().NotContain(secret, "the record keeps nothing of the secret"); } private async Task> RecordOf(string key) { var records = await _fx.UseRedbAsync(redb => redb.Query() .Where(r => r.IdempotencyKey == key) .ToListAsync()); return records.Should().ContainSingle().Subject; } private async Task ClientSecretHash(long id) { var app = await _fx.UseRedbAsync(redb => redb.LoadAsync(id)); return app!.Props.ClientSecret; } private async Task CreateUserAsync() { var login = "idem-" + Guid.NewGuid().ToString("N")[..10]; var (status, body) = await Send(HttpMethod.Post, "/api/v1/identity/users", new { login, password = "Str0ng!Passw0rd", displayName = login }); status.Should().Be(HttpStatusCode.OK, body); return Json(body).GetProperty("id").GetInt64(); } private async Task<(HttpStatusCode Status, string Body)> Send(HttpMethod method, string path, object? content = null, string? key = null) { var (status, body, _) = await SendReplay(method, path, content, key); return (status, body); } private async Task<(HttpStatusCode Status, string Body, bool Replayed)> SendReplay(HttpMethod method, string path, object? content, string? key) { var request = new HttpRequestMessage(method, path) { Content = content is null ? null : JsonContent.Create(content) }; request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken); if (key is not null) request.Headers.Add("Idempotency-Key", key); var response = await _http.SendAsync(request); var replayed = response.Headers.TryGetValues("Idempotency-Replayed", out var values) && values.Single() == "true"; return (response.StatusCode, await response.Content.ReadAsStringAsync(), replayed); } private static HttpRequestMessage Dcr(object body, string key) { var request = new HttpRequestMessage(HttpMethod.Post, "/connect/register") { Content = JsonContent.Create(body) }; request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", ProductionHttpFixture.DynamicRegAccessToken); request.Headers.Add("Idempotency-Key", key); return request; } private static JsonElement Json(string body) => JsonDocument.Parse(body).RootElement; }