Path: redb-identity/tests/redb.Identity.Tests/FullStack/MeMfaResultWireTests.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/MeMfaResultWireTests.cs
----
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.RegularExpressions;
using AwesomeAssertions;
using OtpNet;
using redb.Identity.Tests.Infrastructure;
using Xunit;
namespace redb.Identity.Tests.FullStack;
///
/// The self-service MFA answers (/api/v1/identity/me/mfa) as bytes on the wire, for a fresh user with an
/// identity:account token: status, TOTP setup, a refused and an accepted confirm, recovery code regeneration
/// and disable. Taken on the dictionary answers before they become declared types; the types must write the same.
///
[Collection("ProductionHttp")]
public class MeMfaResultWireTests
{
private const string Base = "/api/v1/identity/me/mfa";
private const string Codes = """\["[^"]+"(,"[^"]+"){9}\]""";
private readonly ProductionHttpFixture _fx;
public MeMfaResultWireTests(ProductionHttpFixture fx) => _fx = fx;
[Fact]
public async Task The_self_service_mfa_answers_keep_their_shapes()
{
var token = await UserTokenAsync();
var (_, status) = await Send(token, HttpMethod.Get, Base, null, HttpStatusCode.OK);
status.Should().Be("""{"enabled":false,"methods":[],"recovery_codes_remaining":0}""");
var (_, setup) = await Send(token, HttpMethod.Post, $"{Base}/setup", new { method = "totp" }, HttpStatusCode.OK);
Match(setup, """^\{"method":"totp","secret_base32":"[A-Z2-7]+","qr_uri":"otpauth://totp/[^"]+","setup_token":"[^"]+"\}$""");
var secret = Json(setup).GetProperty("secret_base32").GetString()!;
var setupToken = Json(setup).GetProperty("setup_token").GetString()!;
var (_, refused) = await Send(token, HttpMethod.Post, $"{Base}/confirm",
new { method = "totp", code = "000000", setup_token = setupToken }, HttpStatusCode.BadRequest);
refused.Should().Be("""{"error":"invalid_code","error_description":"Invalid verification code"}""");
var code = new Totp(Base32Encoding.ToBytes(secret)).ComputeTotp();
var (_, confirmed) = await Send(token, HttpMethod.Post, $"{Base}/confirm",
new { method = "totp", code, setup_token = setupToken }, HttpStatusCode.OK);
Match(confirmed, $$"""^\{"confirmed":true,"recovery_codes":{{Codes}}\}$""");
var (_, regenerated) = await Send(token, HttpMethod.Post, $"{Base}/recovery-codes", null, HttpStatusCode.OK);
Match(regenerated, $$"""^\{"recovery_codes":{{Codes}}\}$""");
var (_, after) = await Send(token, HttpMethod.Get, Base, null, HttpStatusCode.OK);
after.Should().Be("""{"enabled":true,"methods":["totp"],"recovery_codes_remaining":10}""");
var (_, disabled) = await Send(token, HttpMethod.Delete, $"{Base}/totp", null, HttpStatusCode.OK);
disabled.Should().Be("""{"disabled":true}""");
}
[Fact]
public async Task The_self_service_email_answers_keep_their_shapes()
{
var token = await UserTokenAsync();
var address = "memfa-" + Guid.NewGuid().ToString("N")[..8] + "@example.test";
var (_, setup) = await Send(token, HttpMethod.Post, $"{Base}/setup", new { method = "email", destination = address }, HttpStatusCode.OK);
Match(setup, """^\{"method":"email","secret_base32":null,"qr_uri":null,"setup_token":"[^"]+","masked_email":"m\*\*\*@example\.test","mfa_state":"[^"]+"\}$""");
var (_, limited) = await Send(token, HttpMethod.Post, $"{Base}/setup", new { method = "email", destination = address }, HttpStatusCode.TooManyRequests);
Match(limited, """^\{"error":"rate_limited","error_description":"Too many codes requested; retry after \d+ seconds"\}$""");
var (_, invalid) = await Send(token, HttpMethod.Post, $"{Base}/setup", new { method = "email", destination = "not-an-address" }, HttpStatusCode.BadRequest);
invalid.Should().Be("""{"error":"invalid_request","error_description":"Invalid email address"}""");
var code = _fx.Emails.ForRecipient(address).Single().Vars["code"];
var (_, confirmed) = await Send(token, HttpMethod.Post, $"{Base}/confirm", new
{
method = "email", code,
mfa_state = Json(setup).GetProperty("mfa_state").GetString(), setup_token = Json(setup).GetProperty("setup_token").GetString(),
}, HttpStatusCode.OK);
Match(confirmed, $$"""^\{"confirmed":true,"recovery_codes":{{Codes}}\}$""");
var (_, disabled) = await Send(token, HttpMethod.Delete, $"{Base}/email", null, HttpStatusCode.OK);
disabled.Should().Be("""{"disabled":true}""");
}
private async Task UserTokenAsync()
{
var login = "memfa-" + Guid.NewGuid().ToString("N")[..10];
const string password = "Str0ng!Passw0rd";
await Send(_fx.ManagementToken, HttpMethod.Post, "/api/v1/identity/users",
new { login, password, displayName = login }, HttpStatusCode.OK);
// A client of this test that may ask for identity:account with the password grant.
var clientId = login + "-client";
const string clientSecret = "memfa-client-secret-1234";
await Send(_fx.ManagementToken, HttpMethod.Post, "/api/v1/identity/applications", new
{
clientId,
clientSecret,
displayName = clientId,
permissions = new[] { "ept:token", "gt:password", "scp:openid", "scp:identity:account" },
}, HttpStatusCode.OK);
var response = await _fx.Http.PostAsync("/connect/token", new FormUrlEncodedContent(new Dictionary
{
["grant_type"] = "password",
["username"] = login,
["password"] = password,
["scope"] = "openid identity:account",
["client_id"] = clientId,
["client_secret"] = clientSecret,
}));
var body = await response.Content.ReadAsStringAsync();
response.StatusCode.Should().Be(HttpStatusCode.OK, body);
return Json(body).GetProperty("access_token").GetString()!;
}
private async Task<(HttpStatusCode Status, string Body)> Send(
string token, HttpMethod method, string path, object? content, HttpStatusCode expected)
{
using var request = new HttpRequestMessage(method, path) { Content = content is null ? null : JsonContent.Create(content) };
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
using var response = await _fx.Http.SendAsync(request);
var body = await response.Content.ReadAsStringAsync();
response.StatusCode.Should().Be(expected, $"{method} {path}: {body}");
return (response.StatusCode, body);
}
private static void Match(string body, string pattern) => Regex.IsMatch(body, pattern).Should().BeTrue(body);
private static JsonElement Json(string body) => JsonDocument.Parse(body).RootElement;
}