Path: redb-identity/tests/redb.Identity.Tests/Management/ResultContractsParityTests.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/Management/ResultContractsParityTests.cs ---- using System.Text.Encodings.Web; using System.Text.Json; using AwesomeAssertions; using redb.Identity.Contracts.ClaimMappers; using redb.Identity.Contracts.Common; using redb.Identity.Contracts.Consents; using redb.Identity.Contracts.Federation; using redb.Identity.Contracts.Groups; using redb.Identity.Contracts.Mfa; using redb.Identity.Contracts.Sessions; using redb.Identity.Contracts.SigningKeys; using redb.Identity.Contracts.Tokens; using redb.Identity.Contracts.Users; using redb.Identity.Contracts.Validation; using redb.Identity.Contracts.Webhooks; using Xunit; namespace redb.Identity.Tests.Management; /// /// Each result type next to the anonymous object or dictionary its route answered with before, as that route built it, /// written under every option set the answer can be serialized with: the HTTP and gRPC controller dispatchers, /// the serializer defaults, and the ASP.NET Core web defaults the Web host answers with. The bytes must be equal. /// This covers the routes no wire test reaches: the self-service ones a user token calls, the cleanup routes a /// timer runs, the signing key retirement that would change the keys of the test host, and the rare branches. /// public class ResultContractsParityTests { private static readonly JsonSerializerOptions HttpDispatcher = new() { PropertyNameCaseInsensitive = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, }; private static readonly JsonSerializerOptions GrpcDispatcher = new() { PropertyNameCaseInsensitive = true }; private static readonly JsonSerializerOptions WebDefaults = new(JsonSerializerDefaults.Web); private static readonly JsonSerializerOptions Defaults = new(); private static readonly DateTimeOffset Created = new(2026, 11, 17, 10, 0, 0, TimeSpan.Zero); private static readonly DateTimeOffset Modified = new(2026, 11, 17, 11, 30, 0, TimeSpan.FromHours(1)); private static readonly JsonElement WebAuthnOptions = JsonSerializer.SerializeToElement(new Dictionary { ["rp"] = new Dictionary { ["id"] = "localhost", ["name"] = "redb" }, ["challenge"] = "AAECAw", ["pubKeyCredParams"] = new[] { new Dictionary { ["type"] = "public-key", ["alg"] = -7 } }, }); private static readonly Dictionary Cases = new() { ["group"] = ( new { id = 7L, name = (string?)"g", parentId = (long?)null, groupType = (string?)null, description = (string?)"d", createdAt = Created, modifiedAt = Modified }, new GroupResponse { Id = 7, Name = "g", ParentId = null, GroupType = null, Description = "d", CreatedAt = Created, ModifiedAt = Modified }), ["group with members"] = ( new { id = 7L, name = (string?)"g", parentId = (long?)3, groupType = (string?)"team", description = (string?)null, createdAt = Created, modifiedAt = Modified, memberCount = 2 }, new GroupResponse { Id = 7, Name = "g", ParentId = 3, GroupType = "team", Description = null, CreatedAt = Created, ModifiedAt = Modified, MemberCount = 2 }), ["group tree"] = ( new { id = 1L, name = (string?)"root", parentId = (long?)null, groupType = (string?)null, description = (string?)null, level = 0, children = new List { new { id = 2L, name = (string?)"leaf", parentId = (long?)1, groupType = (string?)null, description = (string?)null, level = 1, children = new List() } }, }, new GroupTreeNodeResponse { Id = 1, Name = "root", Level = 0, Children = { new GroupTreeNodeResponse { Id = 2, Name = "leaf", ParentId = 1, Level = 1 } }, }), ["group changed"] = (new { success = true, groupId = 5L }, new GroupChangedResponse { GroupId = 5 }), ["group moved"] = (new { success = true, groupId = 5L, newParentGroupId = 9L }, new GroupMovedResponse { GroupId = 5, NewParentGroupId = 9 }), ["member added"] = ( new { success = true, membershipId = 11L, groupId = 5L, userId = 6L, role = "member" }, new GroupMemberAddedResponse { MembershipId = 11, GroupId = 5, UserId = 6, Role = "member" }), ["member changed"] = (new { success = true, groupId = 5L, userId = 6L, role = "owner" }, new GroupMemberChangedResponse { GroupId = 5, UserId = 6, Role = "owner" }), ["member removed"] = (new { success = true, groupId = 5L, userId = 6L }, new GroupMemberRemovedResponse { GroupId = 5, UserId = 6 }), ["membership check"] = (new { isMember = false, groupId = 5L, userId = 6L }, new GroupMembershipCheckResponse { IsMember = false, GroupId = 5, UserId = 6 }), ["claim scope deleted"] = (new { success = true, cascadedAssignments = 2, cascadedMappers = 1 }, new ClaimScopeDeletedResponse { CascadedAssignments = 2, CascadedMappers = 1 }), ["signing key retired"] = (new { success = true, kid = "k-1" }, new SigningKeyRetiredResponse { Kid = "k-1" }), ["webhook secret rotated"] = (new { success = true, hmacSecret = "s3cr3t+/=" }, new WebhookSecretRotatedResponse { HmacSecret = "s3cr3t+/=" }), ["webhook deliveries"] = ( new { items = new[] { new { id = 3L, deliveryId = (string?)"0f0e", eventId = (string?)null, kind = "webhook", destination = "12", eventType = "UserCreated", status = "failed", attempts = 2, lastError = (string?)"HttpRequestException: & \"quoted\"", createdAt = (string?)"2026-11-17 10:00:00", nextAttemptAt = (string?)null, finishedAt = (string?)"2026-11-17 10:05:00", }, }.ToList(), offset = 0, count = 25, }, new WebhookDeliveryPage { Items = new List(), Offset = 0, Count = 25, }), ["impersonation started"] = (new { targetUserId = 42L, targetLogin = (string?)"alice" }, new ImpersonationStartedResponse { TargetUserId = 42, TargetLogin = "alice" }), ["impersonation stopped"] = (new { stopped = true }, new ImpersonationStoppedResponse()), ["my consent granted"] = ( new { id = 9L, userId = 6L, clientId = (string?)"spa", applicationId = 4L, scopes = new[] { "openid", "profile" } }, new MyConsentGrantedResponse { Id = 9, UserId = 6, ClientId = "spa", ApplicationId = 4, Scopes = new[] { "openid", "profile" } }), ["my consent revoked"] = (new { revoked = 1 }, new MyConsentRevokedResponse { Revoked = 1 }), ["federated identity unlinked"] = (new { unlinked = true, providerId = "github" }, new FederatedIdentityUnlinkedResponse { ProviderId = "github" }), ["mfa otp prune"] = (new { prunedMfaOtp = 3 }, new MfaOtpPruneResult { PrunedMfaOtp = 3 }), ["revoked sids prune"] = (new { prunedRevokedSids = 4 }, new RevokedSidsPruneResult { PrunedRevokedSids = 4 }), ["webauthn challenges prune"] = (new { prunedWebAuthnChallenges = 5 }, new WebAuthnChallengePruneResult { PrunedWebAuthnChallenges = 5 }), ["success already absent"] = (new { success = true, alreadyAbsent = true }, new SuccessResponse { AlreadyAbsent = true }), ["success sessions revoked"] = (new { success = true, sessionsRevoked = 0 }, new SuccessResponse { SessionsRevoked = 0 }), ["error without description"] = (new { error = "access_denied", error_description = (string?)null }, new ErrorResponse { Error = "access_denied", ErrorDescription = null }), ["validation error"] = ( new { error = "validation_error", error_description = "name is required.", validation_errors = new[] { "name is required.", "kind is required." } }, new ValidationErrorResponse { ErrorDescription = "name is required.", ValidationErrors = new[] { "name is required.", "kind is required." } }), ["validation error without body"] = ( new { error = "validation_error", error_description = "Request body is required.", validation_errors = Array.Empty() }, new ValidationErrorResponse { ErrorDescription = "Request body is required.", ValidationErrors = Array.Empty() }), ["inactive introspection"] = (new { active = false }, new IntrospectionResponse { Active = false }), ["session page"] = ( new Dictionary { ["items"] = new List { new() { SessionId = 4, UserId = 6, ClientId = "spa", CreatedAt = Created } }, ["total"] = 1, ["offset"] = 0, ["count"] = 25 }, new SessionPage { Items = new List { new() { SessionId = 4, UserId = 6, ClientId = "spa", CreatedAt = Created } }, Total = 1, Offset = 0, Count = 25 }), ["session revoke preview"] = ( new Dictionary { ["success"] = true, ["dryRun"] = true, ["wouldRevoke"] = 2, ["sampleSessionIds"] = new List { 4, 5 } }, new SessionRevokePreview { WouldRevoke = 2, SampleSessionIds = new List { 4, 5 } }), ["sessions revoked"] = (new Dictionary { ["success"] = true, ["revoked"] = 3 }, new SuccessResponse { Revoked = 3 }), ["sessions logged out"] = (new Dictionary { ["success"] = true, ["sessionsRevoked"] = 3 }, new SuccessResponse { SessionsRevoked = 3 }), ["mfa status"] = ( new Dictionary { ["enabled"] = true, ["methods"] = new[] { "totp" }, ["recovery_codes_remaining"] = 8 }, new MfaStatusResponse { Enabled = true, Methods = new[] { "totp" }, RecoveryCodesRemaining = 8 }), ["mfa setup totp"] = ( new Dictionary { ["method"] = "totp", ["secret_base32"] = "JBSWY3DP", ["qr_uri"] = "otpauth://totp/redb:bob?secret=JBSWY3DP&issuer=redb", ["setup_token"] = "CfDJ8+/=" }, new MfaSetupResponse { Method = "totp", SecretBase32 = "JBSWY3DP", QrUri = "otpauth://totp/redb:bob?secret=JBSWY3DP&issuer=redb", SetupToken = "CfDJ8+/=" }), ["mfa setup email"] = ( new Dictionary { ["method"] = "email", ["secret_base32"] = null, ["qr_uri"] = null, ["setup_token"] = "t", ["masked_email"] = "b***@example.test" }, new MfaSetupResponse { Method = "email", SetupToken = "t", Extra = new Dictionary { ["masked_email"] = "b***@example.test" } }), ["mfa confirmed"] = ( new Dictionary { ["confirmed"] = true, ["recovery_codes"] = new[] { "a1", "b2" } }, new MfaConfirmedResponse { RecoveryCodes = new[] { "a1", "b2" } }), ["mfa disabled"] = (new Dictionary { ["disabled"] = true }, new MfaDisabledResponse()), ["mfa recovery codes"] = ( new Dictionary { ["recovery_codes"] = new[] { "a1" } }, new MfaRecoveryCodesResponse { RecoveryCodes = new[] { "a1" } }), ["mfa error"] = ( new Dictionary { ["error"] = "invalid_code", ["error_description"] = "Invalid verification code" }, new ErrorResponse { Error = "invalid_code", ErrorDescription = "Invalid verification code" }), ["mfa setup email with state"] = ( new Dictionary { ["method"] = "email", ["secret_base32"] = null, ["qr_uri"] = null, ["setup_token"] = "t", ["masked_email"] = "b***@example.test", ["mfa_state"] = "CfDJ8+/=" }, new MfaSetupResponse { Method = "email", SetupToken = "t", Extra = new Dictionary { ["masked_email"] = "b***@example.test", ["mfa_state"] = "CfDJ8+/=" } }), ["webauthn status"] = ( new Dictionary { ["enabled"] = true, ["credentials_count"] = 2 }, new WebAuthnStatusResponse { Enabled = true, CredentialsCount = 2 }), ["webauthn registration options"] = ( new Dictionary { ["options"] = WebAuthnOptions, ["setup_token"] = "CfDJ8+/=" }, new WebAuthnRegistrationOptionsResponse { Options = WebAuthnOptions, SetupToken = "CfDJ8+/=" }), ["webauthn registered"] = ( new Dictionary { ["registered"] = true, ["credential_key"] = "k1", ["recovery_codes"] = new[] { "a1" } }, new WebAuthnRegisteredResponse { CredentialKey = "k1", RecoveryCodes = new[] { "a1" } }), ["webauthn registered, no codes"] = ( new Dictionary { ["registered"] = true, ["credential_key"] = "k1", ["recovery_codes"] = Array.Empty() }, new WebAuthnRegisteredResponse { CredentialKey = "k1", RecoveryCodes = Array.Empty() }), ["webauthn credentials"] = ( new Dictionary { ["credentials"] = new List> { new() { ["key"] = "k1", ["display_name"] = "Laptop", ["aaguid"] = null, ["registered_at"] = Created, ["last_used_at"] = (DateTimeOffset?)Modified, ["user_verified"] = true, ["backup_eligible"] = false, ["backup_state"] = false, }, new() { ["key"] = "k2", ["display_name"] = null, ["aaguid"] = "08987058-cadc-4b81-b6e1-30de50dcbe96", ["registered_at"] = Created, ["last_used_at"] = (DateTimeOffset?)null, ["user_verified"] = false, ["backup_eligible"] = true, ["backup_state"] = true, }, }, }, new WebAuthnCredentialList { Credentials = new List { new() { Key = "k1", DisplayName = "Laptop", RegisteredAt = Created, LastUsedAt = Modified, UserVerified = true, BackupEligible = false, BackupState = false }, new() { Key = "k2", Aaguid = "08987058-cadc-4b81-b6e1-30de50dcbe96", RegisteredAt = Created, UserVerified = false, BackupEligible = true, BackupState = true }, }, }), ["webauthn renamed"] = (new Dictionary { ["renamed"] = true }, new WebAuthnRenamedResponse()), ["webauthn deleted"] = (new Dictionary { ["deleted"] = true }, new WebAuthnDeletedResponse()), }; static ResultContractsParityTests() { // The delivery item is built here so it mirrors the anonymous one member for member. ((WebhookDeliveryPage)Cases["webhook deliveries"].Now).Items.Add(new WebhookDeliveryItem { Id = 3, DeliveryId = "0f0e", EventId = null, Kind = "webhook", Destination = "12", EventType = "UserCreated", Status = "failed", Attempts = 2, LastError = "HttpRequestException: & \"quoted\"", CreatedAt = "2026-11-17 10:00:00", NextAttemptAt = null, FinishedAt = "2026-11-17 10:05:00", }); } public static TheoryData All() { var data = new TheoryData(); foreach (var name in Cases.Keys) foreach (var options in new[] { "http", "grpc", "web", "default" }) data.Add(name, options); return data; } [Theory, MemberData(nameof(All))] public void The_type_writes_the_bytes_of_the_anonymous_answer_it_replaced(string @case, string options) { var json = options switch { "http" => HttpDispatcher, "grpc" => GrpcDispatcher, "web" => WebDefaults, _ => Defaults, }; var (before, now) = Cases[@case]; JsonSerializer.Serialize(now, json).Should().Be(JsonSerializer.Serialize(before, json)); } }