Path: redb-identity/tests/redb.Identity.Tests/FullStack/AdminMfaManagementTests.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/AdminMfaManagementTests.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 OtpNet;
using redb.Identity.Client;
using redb.Identity.Tests.Infrastructure;
using Xunit;
namespace redb.Identity.Tests.FullStack;
///
/// The admin MFA operations of the management API end to end, over real HTTP: TOTP setup, confirm with the first
/// code and the setup token, status, recovery code regeneration, disable. Once with raw requests, once through
/// , so neither the controller nor the client can drop a member the processor needs
/// (confirm lost the setup token in April and nothing noticed: the client tests only look at the request URL,
/// and the processor tests call the processor directly).
///
[Collection("ProductionHttp")]
public class AdminMfaManagementTests
{
private const string Base = "/api/v1/identity/mfa";
private readonly ProductionHttpFixture _fx;
public AdminMfaManagementTests(ProductionHttpFixture fx) => _fx = fx;
[Fact]
public async Task Totp_enrollment_runs_through_the_management_api()
{
var userId = await CreateUserAsync();
var setup = await Post($"{Base}/totp/setup", new { userId, username = "admin-mfa" });
var secret = setup.GetProperty("secret_base32").GetString()!;
var setupToken = setup.GetProperty("setup_token").GetString()!;
var confirmed = await Post($"{Base}/totp/confirm", new { userId, code = Code(secret), setupToken });
confirmed.GetProperty("confirmed").GetBoolean().Should().BeTrue();
confirmed.GetProperty("recovery_codes").GetArrayLength().Should().Be(10);
var status = await Get($"{Base}/status/{userId}");
status.GetProperty("enabled").GetBoolean().Should().BeTrue();
status.GetProperty("methods").EnumerateArray().Select(m => m.GetString()).Should().Contain("totp");
status.GetProperty("recovery_codes_remaining").GetInt32().Should().Be(10);
var regenerated = await Post($"{Base}/recovery-codes/regenerate", new { userId });
regenerated.GetProperty("recovery_codes").GetArrayLength().Should().Be(10);
var disabled = await Send(HttpMethod.Delete, $"{Base}/totp/{userId}", null);
disabled.GetProperty("disabled").GetBoolean().Should().BeTrue();
(await Get($"{Base}/status/{userId}")).GetProperty("enabled").GetBoolean().Should().BeFalse();
}
[Fact]
public async Task Totp_enrollment_runs_through_the_identity_client()
{
var client = Client();
var userId = await CreateUserAsync();
var setup = await client.SetupUserTotpAsync(userId, "admin-mfa-client");
var secret = setup.GetProperty("secret_base32").GetString()!;
var setupToken = setup.GetProperty("setup_token").GetString()!;
var confirmed = await client.ConfirmUserTotpAsync(userId, Code(secret), setupToken);
confirmed.GetProperty("confirmed").GetBoolean().Should().BeTrue(confirmed.ToString());
var status = await client.GetUserMfaStatusAsync(userId);
status.GetProperty("enabled").GetBoolean().Should().BeTrue();
var regenerated = await client.RegenerateUserRecoveryCodesAsync(userId);
regenerated.GetProperty("recovery_codes").GetArrayLength().Should().Be(10);
var disabled = await client.DisableUserTotpAsync(userId);
disabled.GetProperty("disabled").GetBoolean().Should().BeTrue();
(await client.GetUserMfaStatusAsync(userId)).GetProperty("enabled").GetBoolean().Should().BeFalse();
}
private static string Code(string base32Secret) => new Totp(Base32Encoding.ToBytes(base32Secret)).ComputeTotp();
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 CreateUserAsync()
{
var login = "mfa-" + Guid.NewGuid().ToString("N")[..10];
var created = await Post("/api/v1/identity/users", new { login, password = "Str0ng!Passw0rd", displayName = login });
return created.GetProperty("id").GetInt64();
}
private Task Get(string path) => Send(HttpMethod.Get, path, null);
private Task Post(string path, object body) => Send(HttpMethod.Post, path, body);
private Task Send(HttpMethod method, string path, object? body) =>
SendAs(_fx.ManagementToken, method, path, body, HttpStatusCode.OK);
private async Task SendAs(string token, HttpMethod method, string path, object? body, HttpStatusCode expected)
{
var request = new HttpRequestMessage(method, path) { Content = body is null ? null : JsonContent.Create(body) };
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
var response = await _fx.Http.SendAsync(request);
var text = await response.Content.ReadAsStringAsync();
response.StatusCode.Should().Be(expected, $"{method} {path}: {text}");
return JsonDocument.Parse(text).RootElement;
}
// ── The granular scopes of the MFA surface ──
[Fact]
public async Task A_token_with_identity_mfa_write_runs_the_whole_enrollment_of_another_user()
{
var token = await GranularTokenAsync("identity:mfa:write");
var userId = await CreateUserAsync();
var setup = await SendAs(token, HttpMethod.Post, $"{Base}/totp/setup", new { userId, username = "granular-mfa" }, HttpStatusCode.OK);
var secret = setup.GetProperty("secret_base32").GetString()!;
var setupToken = setup.GetProperty("setup_token").GetString()!;
(await SendAs(token, HttpMethod.Post, $"{Base}/totp/confirm", new { userId, code = Code(secret), setupToken }, HttpStatusCode.OK))
.GetProperty("confirmed").GetBoolean().Should().BeTrue();
(await SendAs(token, HttpMethod.Get, $"{Base}/status/{userId}", null, HttpStatusCode.OK))
.GetProperty("enabled").GetBoolean().Should().BeTrue("identity:mfa:write implies read");
(await SendAs(token, HttpMethod.Post, $"{Base}/recovery-codes/regenerate", new { userId }, HttpStatusCode.OK))
.GetProperty("recovery_codes").GetArrayLength().Should().Be(10);
(await SendAs(token, HttpMethod.Delete, $"{Base}/totp/{userId}", null, HttpStatusCode.OK))
.GetProperty("disabled").GetBoolean().Should().BeTrue();
}
[Fact]
public async Task A_token_with_identity_mfa_read_reads_the_status_and_changes_nothing()
{
var token = await GranularTokenAsync("identity:mfa:read");
var userId = await CreateUserAsync();
(await SendAs(token, HttpMethod.Get, $"{Base}/status/{userId}", null, HttpStatusCode.OK))
.GetProperty("enabled").GetBoolean().Should().BeFalse();
await SendAs(token, HttpMethod.Post, $"{Base}/totp/setup", new { userId, username = "granular-mfa" }, HttpStatusCode.Forbidden);
await SendAs(token, HttpMethod.Post, $"{Base}/recovery-codes/regenerate", new { userId }, HttpStatusCode.Forbidden);
await SendAs(token, HttpMethod.Delete, $"{Base}/totp/{userId}", null, HttpStatusCode.Forbidden);
(await Get($"{Base}/status/{userId}")).GetProperty("enabled").GetBoolean().Should().BeFalse("nothing was set up");
}
[Fact]
public async Task A_token_with_identity_users_write_alone_cannot_touch_mfa()
{
var token = await GranularTokenAsync("identity:users:write");
var userId = await CreateUserAsync();
await SendAs(token, HttpMethod.Get, $"{Base}/status/{userId}", null, HttpStatusCode.Forbidden);
await SendAs(token, HttpMethod.Post, $"{Base}/totp/setup", new { userId, username = "granular-mfa" }, HttpStatusCode.Forbidden);
await SendAs(token, HttpMethod.Delete, $"{Base}/totp/{userId}", null, HttpStatusCode.Forbidden);
}
/// A client_credentials token of a fresh client allowed exactly .
private async Task GranularTokenAsync(string scope)
{
var clientId = "mfa-scope-" + Guid.NewGuid().ToString("N")[..10];
const string clientSecret = "mfa-scope-client-secret-1234";
await Post("/api/v1/identity/applications", new
{
clientId,
clientSecret,
displayName = clientId,
permissions = new[] { "ept:token", "gt:client_credentials", "scp:" + scope },
});
var response = await _fx.Http.PostAsync("/connect/token", new FormUrlEncodedContent(new Dictionary
{
["grant_type"] = "client_credentials",
["scope"] = scope,
["client_id"] = clientId,
["client_secret"] = clientSecret,
}));
var text = await response.Content.ReadAsStringAsync();
response.StatusCode.Should().Be(HttpStatusCode.OK, text);
return JsonDocument.Parse(text).RootElement.GetProperty("access_token").GetString()!;
}
}