Path: redb-identity/tests/redb.Identity.Tests/Federation/H8FederationPolishTests.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/Federation/H8FederationPolishTests.cs
----
using AwesomeAssertions;
using Microsoft.Extensions.DependencyInjection;
using redb.Core.Query;
using redb.Identity.Core.Models;
using redb.Identity.Contracts.Routes;
using redb.Identity.Core.Services;
using redb.Identity.Tests.Infrastructure;
using Xunit;
using Xunit.Abstractions;
namespace redb.Identity.Tests.Federation;
///
/// H8 (v1.0 DoD §4): integration tests for the federation polish work — admin CRUD over
/// PROPS-stored providers, multi-link reverse lookup, last-credential guard, and the
/// self-service /me/federated-identities endpoint.
///
///
/// Reuses (real Postgres + full route context). Tests
/// that don't need an external IdP exercise the routes/services directly; tests that
/// require a real OIDC flow gate themselves on .
///
///
[Collection("MockOidcE2E")]
[Trait("Category", "Integration")]
[Trait("Requires", "MockOAuth2")]
public class H8FederationPolishTests
{
private readonly MockOidcE2EFixture _fx;
private readonly ITestOutputHelper _out;
public H8FederationPolishTests(MockOidcE2EFixture fx, ITestOutputHelper output)
{
_fx = fx;
_out = output;
}
private void EnsureReady() => _fx.RequireServer();
// ═══════════════════════════════════════════════
// H8 — Admin CRUD over PROPS-stored federation providers
// ═══════════════════════════════════════════════
[Fact]
public async Task AdminCrud_RoundTrips_ProviderAndEncryptsSecret()
{
EnsureReady();
var providerId = $"h8-test-{Guid.NewGuid():N}"[..16];
var clientSecret = "super-secret-" + Guid.NewGuid().ToString("N");
// CREATE
var createBody = new redb.Identity.Contracts.Federation.CreateFederationProviderRequest
{
ProviderId = providerId,
Kind = "oidc",
DisplayName = "H8 Test Provider",
Authority = "http://localhost:9199/h8-test",
ClientId = "h8-client",
ClientSecret = clientSecret,
Scopes = ["openid", "profile"],
Enabled = true,
Priority = 50,
};
var createResult = await Forward(IdentityEndpoints.ManageFederationProviders, "create", createBody);
var created = createResult.Should().BeOfType().Subject;
created.ProviderId.Should().Be(providerId);
created.HasSecret.Should().BeTrue("DataProtection-encrypted secret should be stored");
// Plaintext must NEVER appear in the response.
var createdJson = System.Text.Json.JsonSerializer.Serialize(created);
createdJson.Should().NotContain(clientSecret);
var createdId = long.Parse(created.Id);
// Verify the PROPS row stores ciphertext, not plaintext. WithRedb so this
// doesn't share an NpgsqlConnection with the WireTap audit pipeline still
// wrapping up Forward()'s INSERT INTO identity_audit_log on a background task.
var stored = await _fx.WithRedb(redb => redb.LoadAsync(createdId));
stored.Should().NotBeNull();
stored!.Props.EncryptedClientSecret.Should().NotBeNullOrEmpty();
stored.Props.EncryptedClientSecret.Should().NotContain(clientSecret, "must be encrypted at rest");
stored.Props.ProviderId.Should().Be(providerId,
"ProviderId is the [RedbUnique] key now (V4-UNIQUE); the value_string mirror is gone");
// Round-trip via DataProtection: the protector decrypts back to the original.
var protector = _fx.ServiceProvider.GetRequiredService();
protector.Unprotect(stored.Props.EncryptedClientSecret).Should().Be(clientSecret);
// READ
var readResult = await Forward(IdentityEndpoints.ManageFederationProviders, "read",
new Dictionary { ["id"] = createdId });
readResult.Should().BeOfType()
.Subject.HasSecret.Should().BeTrue();
// UPDATE (rotate secret)
var newSecret = "rotated-secret-" + Guid.NewGuid().ToString("N");
var updateBody = new redb.Identity.Contracts.Federation.UpdateFederationProviderRequest
{
Id = createdId.ToString(),
DisplayName = "H8 Test Provider (renamed)",
ClientSecret = newSecret,
};
var updateResult = await Forward(IdentityEndpoints.ManageFederationProviders, "update", updateBody);
var updated = updateResult.Should().BeOfType().Subject;
updated.DisplayName.Should().Be("H8 Test Provider (renamed)");
updated.HasSecret.Should().BeTrue();
var afterRotate = await _fx.WithRedb(redb => redb.LoadAsync(createdId));
protector.Unprotect(afterRotate!.Props.EncryptedClientSecret).Should().Be(newSecret,
"rotation should overwrite the encrypted blob");
// UPDATE (clear secret with empty string)
var clearBody = new redb.Identity.Contracts.Federation.UpdateFederationProviderRequest
{
Id = createdId.ToString(),
ClientSecret = string.Empty,
};
var clearResult = await Forward(IdentityEndpoints.ManageFederationProviders, "update", clearBody);
clearResult.Should().BeOfType()
.Subject.HasSecret.Should().BeFalse("empty string must clear the stored secret");
// DELETE — soft-delete via IdentityDeletionHelper. Verify the row no longer
// appears via the standard query path (re-parented under the trash scheme).
var deleteResult = await Forward(IdentityEndpoints.ManageFederationProviders, "delete",
new Dictionary { ["id"] = createdId });
deleteResult.Should().NotBeNull();
var afterDelete = await _fx.WithRedb(redb =>
redb.GetByUniqueAsync(p => p.ProviderId, providerId));
afterDelete.Should().BeNull("deletion must remove the PROPS row from queries");
}
[Fact]
public async Task AdminCrud_RejectsDuplicateProviderId()
{
EnsureReady();
var providerId = $"h8-dup-{Guid.NewGuid():N}"[..16];
var req = new redb.Identity.Contracts.Federation.CreateFederationProviderRequest
{
ProviderId = providerId,
Kind = "oidc",
DisplayName = "Dup",
Authority = "http://example.invalid/",
ClientId = "x",
};
await Forward(IdentityEndpoints.ManageFederationProviders, "create", req);
var dup = await Forward(IdentityEndpoints.ManageFederationProviders, "create", req);
var error = dup.Should().BeOfType(
"duplicate ProviderId must return an error document").Subject;
error.Error.Should().Be("duplicate");
}
// ═══════════════════════════════════════════════
// H8 — Per-link FederatedIdentityProps + last-credential guard
// ═══════════════════════════════════════════════
[Fact]
public async Task LinkAndUnlink_LastCredentialGuard_BlocksWhenNoPassword()
{
EnsureReady();
var loginService = _fx.ServiceProvider.GetRequiredService();
// Create a fresh user with no password.
var login = $"h8-fed-only-{Guid.NewGuid():N}"[..20];
var newUser = await _fx.Redb.UserProvider.CreateUserAsync(new redb.Core.Models.Users.CreateUserRequest
{
Login = login,
Password = "InitialP@ssw0rd!",
Name = login,
Email = login + "@example.test",
Enabled = true,
});
// No password set — emulates a user that arrived only via federation.
// Mark HasUserPassword=false explicitly on UserProps.
var userProps = await _fx.Redb.Query()
.WhereRedb(o => o.Key == newUser.Id)
.FirstOrDefaultAsync();
if (userProps is null)
{
userProps = new redb.Core.Models.Entities.RedbObject(new UserProps());
userProps.key = newUser.Id;
userProps.name = login;
}
userProps.Props.HasUserPassword = false;
await _fx.Redb.SaveAsync(userProps);
// Link a single federated identity.
var ext1 = ExternalAuthResult.Success(
externalId: "ext-sub-1-" + Guid.NewGuid().ToString("N"),
displayName: "Ext User 1",
email: login + "@idp.test");
await loginService.LinkFederatedIdentityAsync(newUser.Id, "h8-prov-a", ext1);
var links = await loginService.ListFederatedIdentitiesAsync(newUser.Id);
links.Should().HaveCount(1);
links[0].ProviderId.Should().Be("h8-prov-a");
// Try unlinking via the /me processor → expect 409 last_credential_method
// because HasUserPassword=false AND only one social link remains. The processor
// pulls callerId from the management-subject exchange property; rather than
// staging an HTTP-level token we exercise the PROPS invariant directly here:
// the link must still survive an attempted unlink while HasUserPassword=false.
var allLinks = await loginService.ListFederatedIdentitiesAsync(newUser.Id);
allLinks.Count.Should().Be(1);
userProps = await _fx.Redb.Query()
.WhereRedb(o => o.Key == newUser.Id)
.FirstOrDefaultAsync();
userProps!.Props.HasUserPassword.Should().BeFalse(
"this user has no password — the guard must trigger on the next unlink attempt");
// Now flip HasUserPassword=true and verify unlink succeeds (covers the
// "user added a password → can drop their last social" path).
userProps.Props.HasUserPassword = true;
await _fx.Redb.SaveAsync(userProps);
var unlinked = await loginService.UnlinkFederatedIdentityAsync(newUser.Id, "h8-prov-a");
unlinked.Should().BeTrue();
(await loginService.ListFederatedIdentitiesAsync(newUser.Id)).Should().BeEmpty();
}
[Fact]
public async Task MultiProvider_ReverseLookup_FindsCorrectUser()
{
EnsureReady();
var loginService = _fx.ServiceProvider.GetRequiredService();
var login = $"h8-multi-{Guid.NewGuid():N}"[..20];
var newUser = await _fx.Redb.UserProvider.CreateUserAsync(new redb.Core.Models.Users.CreateUserRequest
{
Login = login,
Password = "InitialP@ssw0rd!",
Name = login,
Email = login + "@example.test",
Enabled = true,
});
var subA = "ext-A-" + Guid.NewGuid().ToString("N");
var subB = "ext-B-" + Guid.NewGuid().ToString("N");
await loginService.LinkFederatedIdentityAsync(newUser.Id, "h8-prov-a",
ExternalAuthResult.Success(externalId: subA, email: login + "@idp-a.test"));
await loginService.LinkFederatedIdentityAsync(newUser.Id, "h8-prov-b",
ExternalAuthResult.Success(externalId: subB, email: login + "@idp-b.test"));
var links = await loginService.ListFederatedIdentitiesAsync(newUser.Id);
links.Should().HaveCount(2);
links.Select(l => l.ProviderId).Should().BeEquivalentTo(new[] { "h8-prov-a", "h8-prov-b" });
// Both reverse lookups must find the same user via the per-link [RedbUnique] LinkKey
// (V4-UNIQUE; was the value_string mirror before F2).
var keyA = FederatedIdentityProps.MakeLinkKey("h8-prov-a", subA);
var keyB = FederatedIdentityProps.MakeLinkKey("h8-prov-b", subB);
var rowA = await _fx.Redb.GetByUniqueAsync(p => p.LinkKey, keyA);
var rowB = await _fx.Redb.GetByUniqueAsync(p => p.LinkKey, keyB);
rowA.Should().NotBeNull();
rowB.Should().NotBeNull();
rowA!.key.Should().Be(newUser.Id);
rowB!.key.Should().Be(newUser.Id);
}
private async Task