Path: redb-identity/tests/redb.Identity.Tests/FullStack/EmailMfaEnrollmentTests.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/EmailMfaEnrollmentTests.cs
----
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using AwesomeAssertions;
using Microsoft.Extensions.Options;
using redb.Identity.Client;
using redb.Core;
using redb.Identity.Core.Models;
using redb.Identity.Core.Services;
using redb.Identity.Tests.Infrastructure;
using Xunit;
namespace redb.Identity.Tests.FullStack;
///
/// E-mail MFA enrollment end to end over real HTTP: setup sends the one-time code to the candidate address (caught
/// by the fixture's in-memory e-mail channel) and answers with mfa_state and setup_token; confirm takes
/// the code with both. Admin endpoints, the identity client, and the self-service /me/mfa path; a wrong
/// code, and a code sent for another setup, are refused.
///
[Collection("ProductionHttp")]
public class EmailMfaEnrollmentTests
{
private const string Admin = "/api/v1/identity/mfa";
private const string Me = "/api/v1/identity/me/mfa";
private readonly ProductionHttpFixture _fx;
public EmailMfaEnrollmentTests(ProductionHttpFixture fx) => _fx = fx;
[Fact]
public async Task An_admin_enrolls_a_user_with_the_code_sent_to_the_new_address()
{
var (userId, login) = await CreateUserAsync();
var address = $"{login}@example.test";
var setup = await Send(_fx.ManagementToken, HttpMethod.Post, $"{Admin}/email/setup",
new { userId, username = login, destination = address }, HttpStatusCode.OK);
setup.GetProperty("method").GetString().Should().Be("email");
setup.GetProperty("masked_email").GetString().Should().Be($"{login[0]}***@example.test");
var mfaState = setup.GetProperty("mfa_state").GetString()!;
var setupToken = setup.GetProperty("setup_token").GetString()!;
var mail = _fx.Emails.ForRecipient(address).Should().ContainSingle().Subject;
mail.TemplateId.Should().Be(IdentityEmailTemplates.MfaCode);
var code = mail.Vars["code"];
mail.TextBody.Should().Contain(code);
var confirmed = await Send(_fx.ManagementToken, HttpMethod.Post, $"{Admin}/email/confirm",
new { userId, code, mfaState, setupToken }, HttpStatusCode.OK);
confirmed.GetProperty("confirmed").GetBoolean().Should().BeTrue();
confirmed.GetProperty("recovery_codes").GetArrayLength().Should().Be(10);
var status = await Send(_fx.ManagementToken, HttpMethod.Get, $"{Admin}/status/{userId}", null, HttpStatusCode.OK);
status.GetProperty("methods").EnumerateArray().Select(m => m.GetString()).Should().Contain("email");
}
[Fact]
public async Task The_identity_client_runs_the_same_enrollment()
{
var (userId, login) = await CreateUserAsync();
var address = $"{login}@example.test";
var client = Client();
var setup = await client.SetupUserEmailAsync(userId, login, address);
var code = _fx.Emails.ForRecipient(address).Single().Vars["code"];
var confirmed = await client.ConfirmUserEmailAsync(userId, code,
setup.GetProperty("mfa_state").GetString()!, setup.GetProperty("setup_token").GetString()!);
confirmed.GetProperty("confirmed").GetBoolean().Should().BeTrue(confirmed.ToString());
(await client.GetUserMfaStatusAsync(userId)).GetProperty("methods").EnumerateArray()
.Select(m => m.GetString()).Should().Contain("email");
}
[Fact]
public async Task A_wrong_code_and_a_code_sent_for_another_setup_are_refused()
{
var (userId, login) = await CreateUserAsync();
var first = $"{login}-a@example.test";
var second = $"{login}-b@example.test";
var setupA = await Send(_fx.ManagementToken, HttpMethod.Post, $"{Admin}/email/setup",
new { userId, username = login, destination = first }, HttpStatusCode.OK);
await ClearOtpCooldownAsync(userId);
var setupB = await Send(_fx.ManagementToken, HttpMethod.Post, $"{Admin}/email/setup",
new { userId, username = login, destination = second }, HttpStatusCode.OK);
var codeA = _fx.Emails.ForRecipient(first).Single().Vars["code"];
var codeB = _fx.Emails.ForRecipient(second).Single().Vars["code"];
// A wrong code for the right setup.
var wrong = codeB == "000000" ? "111111" : "000000";
(await Send(_fx.ManagementToken, HttpMethod.Post, $"{Admin}/email/confirm", new
{
userId, code = wrong,
mfaState = setupB.GetProperty("mfa_state").GetString(), setupToken = setupB.GetProperty("setup_token").GetString(),
}, HttpStatusCode.BadRequest)).GetProperty("error").GetString().Should().Be("invalid_code");
// The right code and state of setup A, presented with the setup token of B: the code was not sent for B.
(await Send(_fx.ManagementToken, HttpMethod.Post, $"{Admin}/email/confirm", new
{
userId, code = codeA,
mfaState = setupA.GetProperty("mfa_state").GetString(), setupToken = setupB.GetProperty("setup_token").GetString(),
}, HttpStatusCode.BadRequest)).GetProperty("error").GetString().Should().Be("invalid_code");
// Setup B with its own code still goes through.
(await Send(_fx.ManagementToken, HttpMethod.Post, $"{Admin}/email/confirm", new
{
userId, code = codeB,
mfaState = setupB.GetProperty("mfa_state").GetString(), setupToken = setupB.GetProperty("setup_token").GetString(),
}, HttpStatusCode.OK)).GetProperty("confirmed").GetBoolean().Should().BeTrue();
}
[Fact]
public async Task A_second_code_inside_the_cooldown_is_refused_and_nothing_is_sent()
{
var (userId, login) = await CreateUserAsync();
await Send(_fx.ManagementToken, HttpMethod.Post, $"{Admin}/email/setup",
new { userId, username = login, destination = $"{login}-1@example.test" }, HttpStatusCode.OK);
var limited = await Send(_fx.ManagementToken, HttpMethod.Post, $"{Admin}/email/setup",
new { userId, username = login, destination = $"{login}-2@example.test" }, HttpStatusCode.TooManyRequests);
limited.GetProperty("error").GetString().Should().Be("rate_limited");
limited.TryGetProperty("setup_token", out _).Should().BeFalse();
_fx.Emails.ForRecipient($"{login}-2@example.test").Should().BeEmpty();
}
[Fact]
public async Task A_confirm_without_the_setup_token_is_refused_by_validation()
{
var (userId, _) = await CreateUserAsync();
await Send(_fx.ManagementToken, HttpMethod.Post, $"{Admin}/email/confirm",
new { userId, code = "123456", mfaState = "x" }, HttpStatusCode.BadRequest);
}
[Fact]
public async Task A_user_enrolls_their_own_address_through_me_mfa()
{
var (token, login) = await UserTokenAsync();
var address = $"{login}@example.test";
var setup = await Send(token, HttpMethod.Post, $"{Me}/setup", new { method = "email", destination = address }, HttpStatusCode.OK);
var code = _fx.Emails.ForRecipient(address).Single().Vars["code"];
var confirmed = await Send(token, HttpMethod.Post, $"{Me}/confirm", new
{
method = "email", code,
mfa_state = setup.GetProperty("mfa_state").GetString(), setup_token = setup.GetProperty("setup_token").GetString(),
}, HttpStatusCode.OK);
confirmed.GetProperty("confirmed").GetBoolean().Should().BeTrue();
(await Send(token, HttpMethod.Get, Me, null, HttpStatusCode.OK)).GetProperty("methods").EnumerateArray()
.Select(m => m.GetString()).Should().Contain("email");
}
/// Lets the next code go out at once: the setup of another address within the cooldown is refused (see above).
private Task ClearOtpCooldownAsync(long userId) => _fx.UseRedbAsync(async redb =>
{
var record = await redb.Query().WhereRedb(o => o.Key == userId).FirstOrDefaultAsync();
record!.Props.LastOtpSentAt = null;
await redb.SaveAsync(record);
});
private IdentityClient Client()
{
var http = new HttpClient { BaseAddress = _fx.Http.BaseAddress };
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken);
return new IdentityClient(http, Options.Create(new IdentityClientOptions { BaseUrl = _fx.Http.BaseAddress! }));
}
private async Task<(long UserId, string Login)> CreateUserAsync()
{
var login = "emfa" + Guid.NewGuid().ToString("N")[..10];
var created = await Send(_fx.ManagementToken, HttpMethod.Post, "/api/v1/identity/users",
new { login, password = "Str0ng!Passw0rd", displayName = login }, HttpStatusCode.OK);
return (created.GetProperty("id").GetInt64(), login);
}
private async Task<(string Token, string Login)> UserTokenAsync()
{
var (_, login) = await CreateUserAsync();
var clientId = login + "-client";
const string clientSecret = "emfa-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"] = "Str0ng!Passw0rd",
["scope"] = "openid identity:account",
["client_id"] = clientId,
["client_secret"] = clientSecret,
}));
var body = await response.Content.ReadAsStringAsync();
response.StatusCode.Should().Be(HttpStatusCode.OK, body);
return (JsonDocument.Parse(body).RootElement.GetProperty("access_token").GetString()!, login);
}
private async Task Send(string token, HttpMethod method, string path, object? body, HttpStatusCode expected)
{
using var request = new HttpRequestMessage(method, path) { Content = body is null ? null : JsonContent.Create(body) };
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
using var response = await _fx.Http.SendAsync(request);
var text = await response.Content.ReadAsStringAsync();
response.StatusCode.Should().Be(expected, $"{method} {path}: {text}");
return text.Length == 0 ? default : JsonDocument.Parse(text).RootElement.Clone();
}
}