From 8bcc1b815d35247aaf032378ece5400ed0485800 Mon Sep 17 00:00:00 2001 From: tr00d Date: Mon, 2 Nov 2026 10:38:49 +0100 Subject: [PATCH] feat(auth): generate the signed-in user's MFA recovery codes --- ...ouldSendNoBody_GivenNoOptions.verified.txt | 1 + ...venOptionsWithoutFriendlyName.verified.txt | 1 + ...riendlyName_GivenFriendlyName.verified.txt | 1 + .../Data/already_enrolled_error.json | 5 + .../Data/insufficient_aal_error.json | 5 + .../Data/recovery_codes.json | 11 + .../Data/recovery_codes_without_codes.json | 6 + .../Data/sole_factor_error.json | 5 + .../GenerateRecoveryCodesApprovalTests.cs | 45 ++++ .../GenerateRecoveryCodesContractTests.cs | 200 ++++++++++++++++++ .../GenerateRecoveryCodesTests.cs | 40 ++++ .../Gotrue/Gotrue.Tests/Gotrue.Tests.csproj | 1 + .../ObservabilityContractTests.cs | 19 ++ packages/Gotrue/Gotrue/Api.cs | 8 + packages/Gotrue/Gotrue/Client.cs | 15 ++ .../Gotrue/Gotrue/Common/RecoveryCodes.cs | 23 ++ .../Gotrue/Common/RecoveryCodesResponse.cs | 29 +++ .../GenerateRecoveryCodesBody.cs | 14 ++ .../GenerateRecoveryCodesOptions.cs | 13 ++ .../Gotrue/Gotrue/GotrueInstrumentation.cs | 1 + .../Gotrue/Gotrue/Interfaces/IGotrueApi.cs | 11 + .../Gotrue/Gotrue/Interfaces/IGotrueClient.cs | 38 ++++ .../Gotrue/Gotrue/PublicAPI.Unshipped.txt | 30 +++ 23 files changed, 522 insertions(+) create mode 100644 packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/Data/GenerateRecoveryCodesApprovalTests.GenerateRecoveryCodesRequest_ShouldSendNoBody_GivenNoOptions.verified.txt create mode 100644 packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/Data/GenerateRecoveryCodesApprovalTests.GenerateRecoveryCodesRequest_ShouldSendNoBody_GivenOptionsWithoutFriendlyName.verified.txt create mode 100644 packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/Data/GenerateRecoveryCodesApprovalTests.GenerateRecoveryCodesRequest_ShouldSendTheFriendlyName_GivenFriendlyName.verified.txt create mode 100644 packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/Data/already_enrolled_error.json create mode 100644 packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/Data/insufficient_aal_error.json create mode 100644 packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/Data/recovery_codes.json create mode 100644 packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/Data/recovery_codes_without_codes.json create mode 100644 packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/Data/sole_factor_error.json create mode 100644 packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/GenerateRecoveryCodesApprovalTests.cs create mode 100644 packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/GenerateRecoveryCodesContractTests.cs create mode 100644 packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/GenerateRecoveryCodesTests.cs create mode 100644 packages/Gotrue/Gotrue/Common/RecoveryCodes.cs create mode 100644 packages/Gotrue/Gotrue/Common/RecoveryCodesResponse.cs create mode 100644 packages/Gotrue/Gotrue/GenerateRecoveryCodes/GenerateRecoveryCodesBody.cs create mode 100644 packages/Gotrue/Gotrue/GenerateRecoveryCodes/GenerateRecoveryCodesOptions.cs diff --git a/packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/Data/GenerateRecoveryCodesApprovalTests.GenerateRecoveryCodesRequest_ShouldSendNoBody_GivenNoOptions.verified.txt b/packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/Data/GenerateRecoveryCodesApprovalTests.GenerateRecoveryCodesRequest_ShouldSendNoBody_GivenNoOptions.verified.txt new file mode 100644 index 00000000..c1b8d743 --- /dev/null +++ b/packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/Data/GenerateRecoveryCodesApprovalTests.GenerateRecoveryCodesRequest_ShouldSendNoBody_GivenNoOptions.verified.txt @@ -0,0 +1 @@ +emptyString \ No newline at end of file diff --git a/packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/Data/GenerateRecoveryCodesApprovalTests.GenerateRecoveryCodesRequest_ShouldSendNoBody_GivenOptionsWithoutFriendlyName.verified.txt b/packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/Data/GenerateRecoveryCodesApprovalTests.GenerateRecoveryCodesRequest_ShouldSendNoBody_GivenOptionsWithoutFriendlyName.verified.txt new file mode 100644 index 00000000..c1b8d743 --- /dev/null +++ b/packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/Data/GenerateRecoveryCodesApprovalTests.GenerateRecoveryCodesRequest_ShouldSendNoBody_GivenOptionsWithoutFriendlyName.verified.txt @@ -0,0 +1 @@ +emptyString \ No newline at end of file diff --git a/packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/Data/GenerateRecoveryCodesApprovalTests.GenerateRecoveryCodesRequest_ShouldSendTheFriendlyName_GivenFriendlyName.verified.txt b/packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/Data/GenerateRecoveryCodesApprovalTests.GenerateRecoveryCodesRequest_ShouldSendTheFriendlyName_GivenFriendlyName.verified.txt new file mode 100644 index 00000000..18efb1ce --- /dev/null +++ b/packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/Data/GenerateRecoveryCodesApprovalTests.GenerateRecoveryCodesRequest_ShouldSendTheFriendlyName_GivenFriendlyName.verified.txt @@ -0,0 +1 @@ +{"friendly_name":"Backup codes"} \ No newline at end of file diff --git a/packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/Data/already_enrolled_error.json b/packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/Data/already_enrolled_error.json new file mode 100644 index 00000000..4fb7a262 --- /dev/null +++ b/packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/Data/already_enrolled_error.json @@ -0,0 +1,5 @@ +{ + "code": 422, + "error_code": "mfa_verified_factor_exists", + "msg": "Recovery codes are already enrolled for this user, use regenerate to rotate them" +} diff --git a/packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/Data/insufficient_aal_error.json b/packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/Data/insufficient_aal_error.json new file mode 100644 index 00000000..633c9765 --- /dev/null +++ b/packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/Data/insufficient_aal_error.json @@ -0,0 +1,5 @@ +{ + "code": 403, + "error_code": "insufficient_aal", + "msg": "AAL2 required to generate recovery codes" +} diff --git a/packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/Data/recovery_codes.json b/packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/Data/recovery_codes.json new file mode 100644 index 00000000..0fa1df1f --- /dev/null +++ b/packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/Data/recovery_codes.json @@ -0,0 +1,11 @@ +{ + "id": "2b306a77-21dc-4110-ba71-537cb56b9e98", + "type": "recovery_code", + "friendly_name": "Backup codes", + "total": 3, + "codes": [ + "k4m9x7qp2ab8ht3z", + "9wze6r5npd4cmq7v", + "2h8kqw3m7xt49rpn" + ] +} diff --git a/packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/Data/recovery_codes_without_codes.json b/packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/Data/recovery_codes_without_codes.json new file mode 100644 index 00000000..4553c12e --- /dev/null +++ b/packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/Data/recovery_codes_without_codes.json @@ -0,0 +1,6 @@ +{ + "id": "2b306a77-21dc-4110-ba71-537cb56b9e98", + "type": "recovery_code", + "friendly_name": "Backup codes", + "total": 0 +} diff --git a/packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/Data/sole_factor_error.json b/packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/Data/sole_factor_error.json new file mode 100644 index 00000000..8589f884 --- /dev/null +++ b/packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/Data/sole_factor_error.json @@ -0,0 +1,5 @@ +{ + "code": 422, + "error_code": "mfa_recovery_codes_sole_factor", + "msg": "At least one other verified factor is required to generate recovery codes" +} diff --git a/packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/GenerateRecoveryCodesApprovalTests.cs b/packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/GenerateRecoveryCodesApprovalTests.cs new file mode 100644 index 00000000..bd28b19e --- /dev/null +++ b/packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/GenerateRecoveryCodesApprovalTests.cs @@ -0,0 +1,45 @@ +#region + +using System.Threading.Tasks; +using Gotrue.Tests.Support; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Supabase.Gotrue.GenerateRecoveryCodes; + +#endregion + +namespace Gotrue.Tests.GenerateRecoveryCodes; + +/// +/// Pins the exact bytes a recovery codes generation puts on the wire: the friendly name when one is given, and no +/// body at all otherwise, since the server treats the body as optional. +/// +[TestClass] +[TestCategory("Contract")] +public class GenerateRecoveryCodesApprovalTests : RequestApprovalFixture +{ + private const string GeneratedCodes = """{"id":"2b306a77-21dc-4110-ba71-537cb56b9e98","friendly_name":"Recovery codes","codes":["k4m9x7qp2ab8ht3z"]}"""; + + [TestInitialize] + public void AnswerWithGeneratedCodes() => this.RespondTo("/factors/recovery-codes", GeneratedCodes); + + [TestMethod] + public async Task GenerateRecoveryCodesRequest_ShouldSendTheFriendlyName_GivenFriendlyName() + { + await this.Api.GenerateRecoveryCodesAsync("user-jwt", new GenerateRecoveryCodesOptions { FriendlyName = "Backup codes" }); + await this.Verify(this.EmittedRequestBody).UseDirectory("Data"); + } + + [TestMethod] + public async Task GenerateRecoveryCodesRequest_ShouldSendNoBody_GivenNoOptions() + { + await this.Api.GenerateRecoveryCodesAsync("user-jwt"); + await this.Verify(this.EmittedRequestBody).UseDirectory("Data"); + } + + [TestMethod] + public async Task GenerateRecoveryCodesRequest_ShouldSendNoBody_GivenOptionsWithoutFriendlyName() + { + await this.Api.GenerateRecoveryCodesAsync("user-jwt", new GenerateRecoveryCodesOptions()); + await this.Verify(this.EmittedRequestBody).UseDirectory("Data"); + } +} diff --git a/packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/GenerateRecoveryCodesContractTests.cs b/packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/GenerateRecoveryCodesContractTests.cs new file mode 100644 index 00000000..c0ba532e --- /dev/null +++ b/packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/GenerateRecoveryCodesContractTests.cs @@ -0,0 +1,200 @@ +#region + +using System; +using System.IO; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using FluentAssertions; +using Gotrue.Tests.Support; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Supabase.Gotrue; +using Supabase.Gotrue.Common; +using Supabase.Gotrue.Exceptions; +using Supabase.Gotrue.GenerateRecoveryCodes; +using Supabase.Gotrue.Interfaces; +using WireMock.RequestBuilders; +using WireMock.ResponseBuilders; +using static Supabase.Gotrue.Exceptions.FailureHint.Reason; + +#endregion + +namespace Gotrue.Tests.GenerateRecoveryCodes; + +/// +/// Pins how GenerateRecoveryCodesAsync generates the signed-in user's MFA recovery codes: the +/// POST /factors/recovery-codes request it puts on the wire, how the generated set maps to the result, and the +/// failures raised before and after the request, all against a stubbed server. +/// +[TestClass] +[TestCategory("Contract")] +public class GenerateRecoveryCodesContractTests +{ + private const string AccessToken = "an-access-token"; + private IGotrueClient client = null!; + private MockGotrueServer server = null!; + + [TestInitialize] + public void TestInitializer() + { + this.server = new MockGotrueServer(); + this.client = TestClients.Against(this.server); + } + + [TestCleanup] + public void TestCleanup() => this.server.Dispose(); + + [TestMethod] + public async Task GenerateRecoveryCodesAsync_ShouldPostTheGenerationWithTheSessionBearer() + { + this.SignIn(); + this.MockGenerateResponse(200, Fixture("recovery_codes.json")); + await this.client.GenerateRecoveryCodesAsync(); + this.server.VerifySingleReceivedRequest() + .WithMethod(HttpMethod.Post) + .WithPath("/factors/recovery-codes") + .WithHeader("Authorization", $"Bearer {AccessToken}") + .WithHeader("apikey", MockGotrueServer.ApiKey); + } + + [TestMethod] + public async Task GenerateRecoveryCodesAsync_ShouldReturnTheFactorAndItsCodes_GivenGeneratedSet() + { + this.SignIn(); + this.MockGenerateResponse(200, Fixture("recovery_codes.json")); + var recoveryCodes = await this.client.GenerateRecoveryCodesAsync(new GenerateRecoveryCodesOptions { FriendlyName = "Backup codes" }); + recoveryCodes.Should().BeEquivalentTo(new RecoveryCodes + { + FactorId = "2b306a77-21dc-4110-ba71-537cb56b9e98", + FriendlyName = "Backup codes", + Codes = new[] { "k4m9x7qp2ab8ht3z", "9wze6r5npd4cmq7v", "2h8kqw3m7xt49rpn" }, + }, + options => options.WithStrictOrdering(), + "the result is the id, friendly_name and codes of MFARecoveryCodesSchema (auth OpenAPI, POST /factors/recovery-codes)"); + } + + [TestMethod] + public async Task GenerateRecoveryCodesAsync_ShouldReturnNoCodes_GivenSetWithoutCodes() + { + this.SignIn(); + this.MockGenerateResponse(200, Fixture("recovery_codes_without_codes.json")); + var recoveryCodes = await this.client.GenerateRecoveryCodesAsync(); + recoveryCodes.Codes.Should().BeEmpty("the server omits an empty codes array, and the codes are never null"); + } + + [TestMethod] + public async Task GenerateRecoveryCodesAsync_ShouldThrow_GivenSuccessWithoutBody() + { + this.SignIn(); + this.MockGenerateResponse(200, "null"); + var generating = () => this.client.GenerateRecoveryCodesAsync(); + await generating.Should().ThrowAsync("a 200 answer must carry the generated codes, which cannot be read back later") + .WithMessage("The auth server returned no recovery codes."); + } + + [TestMethod] + public async Task GenerateRecoveryCodesAsync_ShouldThrowServerRejection_GivenSessionBelowAal2() + { + this.SignIn(); + this.MockGenerateResponse(403, Fixture("insufficient_aal_error.json")); + var generating = () => this.client.GenerateRecoveryCodesAsync(); + (await generating.Should().ThrowAsync()).Which.ErrorCode.Should().Be("insufficient_aal", + "POST /factors/recovery-codes requires an aal2 session (auth OpenAPI, 403 insufficient_aal)"); + } + + [TestMethod] + public async Task GenerateRecoveryCodesAsync_ShouldThrowServerRejection_GivenUserWithoutOtherVerifiedFactor() + { + this.SignIn(); + this.MockGenerateResponse(422, Fixture("sole_factor_error.json")); + var generating = () => this.client.GenerateRecoveryCodesAsync(); + (await generating.Should().ThrowAsync()).Which.ErrorCode.Should().Be("mfa_recovery_codes_sole_factor", + "recovery codes can never be the user's only second factor (auth OpenAPI, 422 mfa_recovery_codes_sole_factor)"); + } + + [TestMethod] + public async Task GenerateRecoveryCodesAsync_ShouldThrowServerRejection_GivenUserWithRecoveryCodes() + { + this.SignIn(); + this.MockGenerateResponse(422, Fixture("already_enrolled_error.json")); + var generating = () => this.client.GenerateRecoveryCodesAsync(); + (await generating.Should().ThrowAsync()).Which.ErrorCode.Should().Be("mfa_verified_factor_exists", + "a user has at most one set of recovery codes; regenerate replaces it (auth OpenAPI, 422 mfa_verified_factor_exists)"); + } + + [TestMethod] + public async Task GenerateRecoveryCodesAsync_ShouldThrowNoSessionFound_GivenNoSession() + { + var generating = () => this.client.GenerateRecoveryCodesAsync(); + (await generating.Should().ThrowAsync().WithMessage("A valid session is required.")).Which.Reason.Should().Be(NoSessionFound, + "POST /factors/recovery-codes requires the signed-in user's access token"); + } + + [TestMethod] + public async Task GenerateRecoveryCodesAsync_ShouldThrowNoSessionFound_GivenSessionWithoutAccessToken() + { + this.SignIn(new Session { RefreshToken = "a-refresh-token", ExpiresIn = 3600 }); + var generating = () => this.client.GenerateRecoveryCodesAsync(); + (await generating.Should().ThrowAsync()).Which.Reason.Should().Be(NoSessionFound, + "POST /factors/recovery-codes requires the signed-in user's access token"); + } + + [TestMethod] + public async Task GenerateRecoveryCodesAsync_ShouldNotSendARequest_GivenNoSession() + { + var generating = () => this.client.GenerateRecoveryCodesAsync(); + await generating.Should().ThrowAsync(); + this.server.CountReceivedRequests().Should().Be(0, "the missing session is detected before the wire"); + } + + [TestMethod] + public async Task GenerateRecoveryCodesAsync_ShouldThrowOffline_GivenClientIsOffline() + { + this.SignIn(); + this.client.Online = false; + var generating = () => this.client.GenerateRecoveryCodesAsync(); + (await generating.Should().ThrowAsync().WithMessage("Only supported when online")).Which.Reason.Should().Be(Offline, + "generating the recovery codes needs the server, like the other MFA operations"); + } + + [TestMethod] + public async Task GenerateRecoveryCodesAsync_ShouldCancelTheRequest_GivenCancelledToken() + { + this.SignIn(); + this.MockGenerateResponse(200, Fixture("recovery_codes.json")); + using var cancellation = new CancellationTokenSource(); + cancellation.Cancel(); + var generating = () => this.client.GenerateRecoveryCodesAsync(cancellationToken: cancellation.Token); + await generating.Should().ThrowAsync("the cancellation token reaches the HTTP call"); + } + + [TestMethod] + public void GenerateRecoveryCodesAsync_ShouldComplete_GivenCallerBlockingOnContextThatNeverRunsContinuations() + { + this.SignIn(); + this.MockGenerateResponse(200, Fixture("recovery_codes.json")); + BlockingCaller.Completes(() => this.client.GenerateRecoveryCodesAsync()).Should().BeTrue( + "a library must not resume on the caller's context: a UI thread blocking on the task would deadlock"); + } + + private void SignIn() => this.SignIn(new Session { AccessToken = AccessToken, RefreshToken = "a-refresh-token", ExpiresIn = 3600, User = new User { Id = "user-id-123" } }); + + private void SignIn(Session session) + { + var persistence = SessionPersistenceSubstitute.Tracking(); + persistence.SaveSession(session); + this.client.SetPersistence(persistence); + this.client.LoadSession(); + } + + private void MockGenerateResponse(int statusCode, string body) => + this.server + .Given(Request.Create().WithPath("/factors/recovery-codes").UsingPost()) + .RespondWith(Response.Create() + .WithStatusCode(statusCode) + .WithHeader("Content-Type", "application/json") + .WithBody(body)); + + private static string Fixture(string name) => + File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "GenerateRecoveryCodes", "Data", name)); +} diff --git a/packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/GenerateRecoveryCodesTests.cs b/packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/GenerateRecoveryCodesTests.cs new file mode 100644 index 00000000..6c49261f --- /dev/null +++ b/packages/Gotrue/Gotrue.Tests/GenerateRecoveryCodes/GenerateRecoveryCodesTests.cs @@ -0,0 +1,40 @@ +#region + +using System.Threading.Tasks; +using FluentAssertions; +using Gotrue.Tests.Support; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Supabase.Gotrue.Exceptions; + +#endregion + +namespace Gotrue.Tests.GenerateRecoveryCodes; + +/// +/// End-to-end generation of the signed-in user's MFA recovery codes against the live stack. The local stack +/// cannot enroll recovery codes (the CLI does not expose the auth server's recovery codes enroll setting, which +/// defaults to off), so these cover the rejections the stack can reach; a successful generation is pinned by +/// . +/// +[TestClass] +[TestCategory("E2E")] +public class GenerateRecoveryCodesTests : AuthClientFixture +{ + [TestMethod] + public async Task GenerateRecoveryCodesAsync_ShouldThrowEnrollNotEnabled_GivenServerWithRecoveryCodesDisabled() + { + await this.SignUpNewUser(); + var generating = () => this.Client.GenerateRecoveryCodesAsync(); + (await generating.Should().ThrowAsync()).Which.ErrorCode.Should().Be("mfa_recovery_codes_enroll_not_enabled", + "the auth server leaves GOTRUE_MFA_RECOVERY_CODES_ENROLL_ENABLED off by default (auth OpenAPI, POST /factors/recovery-codes 422)"); + } + + [TestMethod] + public async Task GenerateRecoveryCodesAsync_ShouldThrowNoAuthorization_GivenAnonymousUser() + { + await this.Client.SignInAnonymously(); + var generating = () => this.Client.GenerateRecoveryCodesAsync(); + (await generating.Should().ThrowAsync()).Which.ErrorCode.Should().Be("no_authorization", + "anonymous users cannot use recovery codes (auth OpenAPI, POST /factors/recovery-codes 403)"); + } +} diff --git a/packages/Gotrue/Gotrue.Tests/Gotrue.Tests.csproj b/packages/Gotrue/Gotrue.Tests/Gotrue.Tests.csproj index 2d702c33..90276099 100644 --- a/packages/Gotrue/Gotrue.Tests/Gotrue.Tests.csproj +++ b/packages/Gotrue/Gotrue.Tests/Gotrue.Tests.csproj @@ -37,6 +37,7 @@ + diff --git a/packages/Gotrue/Gotrue.Tests/Observability/ObservabilityContractTests.cs b/packages/Gotrue/Gotrue.Tests/Observability/ObservabilityContractTests.cs index 8c0e51a3..609d625c 100644 --- a/packages/Gotrue/Gotrue.Tests/Observability/ObservabilityContractTests.cs +++ b/packages/Gotrue/Gotrue.Tests/Observability/ObservabilityContractTests.cs @@ -141,6 +141,17 @@ public async Task DomainSpan_ShouldParentTheHttpSpan_GivenRecoveryCodesStatusRea this.activities.Should().ContainSingle(a => a.OperationName == "GET /factors/recovery-codes").Which.ParentSpanId.Should().Be(domainSpan.SpanId); } + [TestMethod] + public async Task DomainSpan_ShouldParentTheHttpSpan_GivenRecoveryCodesGeneration() + { + this.MockTokenSuccess(); + await this.Refresh(); + this.MockRecoveryCodesGenerationSuccess(); + await this.client.GenerateRecoveryCodesAsync(); + var domainSpan = this.activities.Should().ContainSingle(a => a.OperationName == "gotrue.generate_recovery_codes").Which; + this.activities.Should().ContainSingle(a => a.OperationName == "POST /factors/recovery-codes").Which.ParentSpanId.Should().Be(domainSpan.SpanId); + } + [TestMethod] public async Task DomainSpan_ShouldParentTheHttpSpan_GivenRecoveryCodesUnenrollment() { @@ -266,6 +277,14 @@ private void MockRecoveryCodesStatusSuccess() => .WithHeader("Content-Type", "application/json") .WithBody(File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "GetRecoveryCodesStatus", "Data", "recovery_codes_status.json")))); + private void MockRecoveryCodesGenerationSuccess() => + this.server + .Given(Request.Create().WithPath("/factors/recovery-codes").UsingPost()) + .RespondWith(Response.Create() + .WithStatusCode(200) + .WithHeader("Content-Type", "application/json") + .WithBody(File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "GenerateRecoveryCodes", "Data", "recovery_codes.json")))); + private void MockRecoveryCodesUnenrollmentSuccess() => this.server .Given(Request.Create().WithPath("/factors/recovery-codes").UsingDelete()) diff --git a/packages/Gotrue/Gotrue/Api.cs b/packages/Gotrue/Gotrue/Api.cs index ea6d050b..269f4ce1 100644 --- a/packages/Gotrue/Gotrue/Api.cs +++ b/packages/Gotrue/Gotrue/Api.cs @@ -13,6 +13,7 @@ using Supabase.Gotrue.CreateCustomProvider; using Supabase.Gotrue.CustomProviders; using Supabase.Gotrue.Exceptions; +using Supabase.Gotrue.GenerateRecoveryCodes; using Supabase.Gotrue.GetRecoveryCodesStatus; using Supabase.Gotrue.Interfaces; using Supabase.Gotrue.ListCustomProviders; @@ -657,6 +658,13 @@ public ProviderAuthState GetUriForProvider(Provider provider, SignInOptions? opt } } + /// + public async Task GenerateRecoveryCodesAsync(string jwt, GenerateRecoveryCodesOptions? options = null, CancellationToken cancellationToken = default) + { + var generated = await this.MakeRequestAsync(HttpMethod.Post, $"{this.Url}/factors/recovery-codes", GenerateRecoveryCodesBody.For(options), this.CreateAuthedRequestHeaders(jwt), cancellationToken).ConfigureAwait(false); + return RecoveryCodesResponse.Read(generated); + } + /// public Task UnenrollRecoveryCodesAsync(string jwt, CancellationToken cancellationToken = default) => this.MakeRequestAsync(HttpMethod.Delete, $"{this.Url}/factors/recovery-codes", null, this.CreateAuthedRequestHeaders(jwt), cancellationToken); diff --git a/packages/Gotrue/Gotrue/Client.cs b/packages/Gotrue/Gotrue/Client.cs index 08748075..dd42bd17 100644 --- a/packages/Gotrue/Gotrue/Client.cs +++ b/packages/Gotrue/Gotrue/Client.cs @@ -11,7 +11,9 @@ using Supabase.Core.Attributes; using Supabase.Core.Diagnostics; using Supabase.Gotrue.Claims; +using Supabase.Gotrue.Common; using Supabase.Gotrue.Exceptions; +using Supabase.Gotrue.GenerateRecoveryCodes; using Supabase.Gotrue.GetRecoveryCodesStatus; using Supabase.Gotrue.Interfaces; using Supabase.Gotrue.Mfa; @@ -1224,6 +1226,19 @@ public void StartAutoRefresh() return await this.api.GetRecoveryCodesStatusAsync(accessToken, cancellationToken).ConfigureAwait(false); } + /// + [ImplementedCapability("auth.mfa_recovery_codes.generate")] + public async Task GenerateRecoveryCodesAsync(GenerateRecoveryCodesOptions? options = null, CancellationToken cancellationToken = default) + { + using var activity = GotrueInstrumentation.Source.StartActivity(GotrueInstrumentation.Spans.GenerateRecoveryCodes); + if (!this.Online) + { + throw new GotrueException("Only supported when online", Offline); + } + var accessToken = this.CurrentSession?.AccessToken ?? throw new GotrueException("A valid session is required.", NoSessionFound); + return await this.api.GenerateRecoveryCodesAsync(accessToken, options, cancellationToken).ConfigureAwait(false); + } + /// [ImplementedCapability("auth.mfa_recovery_codes.unenroll")] public async Task UnenrollRecoveryCodesAsync(CancellationToken cancellationToken = default) diff --git a/packages/Gotrue/Gotrue/Common/RecoveryCodes.cs b/packages/Gotrue/Gotrue/Common/RecoveryCodes.cs new file mode 100644 index 00000000..96e9b64a --- /dev/null +++ b/packages/Gotrue/Gotrue/Common/RecoveryCodes.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; + +namespace Supabase.Gotrue.Common; + +/// +/// A freshly generated set of the signed-in user's single-use MFA recovery codes. The codes are returned exactly once +/// and cannot be read back from the server: show them to the user and ask them to store them safely. +/// +public sealed record RecoveryCodes +{ + /// The id of the user's recovery codes factor, as listed in . + public string FactorId { get; init; } = null!; + + /// The name of the recovery codes factor shown in the user's factor list. + public string FriendlyName { get; init; } = null!; + + /// + /// The plaintext codes in canonical form: lowercase, without separators. Group them for display if you like; the + /// server ignores letter case, whitespace and - when a code is verified. + /// + public IReadOnlyList Codes { get; init; } = Array.Empty(); +} diff --git a/packages/Gotrue/Gotrue/Common/RecoveryCodesResponse.cs b/packages/Gotrue/Gotrue/Common/RecoveryCodesResponse.cs new file mode 100644 index 00000000..f3048677 --- /dev/null +++ b/packages/Gotrue/Gotrue/Common/RecoveryCodesResponse.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Text.Json.Serialization; +using Supabase.Gotrue.Exceptions; + +namespace Supabase.Gotrue.Common; + +internal sealed record RecoveryCodesResponse +{ + [JsonPropertyName("id")] + public string Id { get; init; } = null!; + + [JsonPropertyName("friendly_name")] + public string FriendlyName { get; init; } = null!; + + [JsonPropertyName("codes")] + public IReadOnlyList? Codes { get; init; } + + internal static RecoveryCodes Read(RecoveryCodesResponse? response) => + response?.ToRecoveryCodes() ?? throw new GotrueException("The auth server returned no recovery codes."); + + private RecoveryCodes ToRecoveryCodes() => + new() + { + FactorId = this.Id, + FriendlyName = this.FriendlyName, + Codes = this.Codes ?? Array.Empty(), + }; +} diff --git a/packages/Gotrue/Gotrue/GenerateRecoveryCodes/GenerateRecoveryCodesBody.cs b/packages/Gotrue/Gotrue/GenerateRecoveryCodes/GenerateRecoveryCodesBody.cs new file mode 100644 index 00000000..d987843c --- /dev/null +++ b/packages/Gotrue/Gotrue/GenerateRecoveryCodes/GenerateRecoveryCodesBody.cs @@ -0,0 +1,14 @@ +using System.Text.Json.Serialization; + +namespace Supabase.Gotrue.GenerateRecoveryCodes; + +internal sealed record GenerateRecoveryCodesBody +{ + private GenerateRecoveryCodesBody(string friendlyName) => this.FriendlyName = friendlyName; + + [JsonPropertyName("friendly_name")] + public string FriendlyName { get; } + + internal static GenerateRecoveryCodesBody? For(GenerateRecoveryCodesOptions? options) => + options?.FriendlyName is null ? null : new GenerateRecoveryCodesBody(options.FriendlyName); +} diff --git a/packages/Gotrue/Gotrue/GenerateRecoveryCodes/GenerateRecoveryCodesOptions.cs b/packages/Gotrue/Gotrue/GenerateRecoveryCodes/GenerateRecoveryCodesOptions.cs new file mode 100644 index 00000000..14e8a2bb --- /dev/null +++ b/packages/Gotrue/Gotrue/GenerateRecoveryCodes/GenerateRecoveryCodesOptions.cs @@ -0,0 +1,13 @@ +namespace Supabase.Gotrue.GenerateRecoveryCodes; + +/// +/// Optional settings for generating the signed-in user's MFA recovery codes. +/// +public sealed record GenerateRecoveryCodesOptions +{ + /// + /// The name of the recovery codes factor shown in the user's factor list. Must be unique among the user's factors. + /// The server names it Recovery codes when this is null or blank. + /// + public string? FriendlyName { get; init; } +} diff --git a/packages/Gotrue/Gotrue/GotrueInstrumentation.cs b/packages/Gotrue/Gotrue/GotrueInstrumentation.cs index e1db7ad5..f6c4a5d0 100644 --- a/packages/Gotrue/Gotrue/GotrueInstrumentation.cs +++ b/packages/Gotrue/Gotrue/GotrueInstrumentation.cs @@ -72,6 +72,7 @@ internal static class Spans internal const string LinkIdentityWithIdToken = "gotrue.link_identity.id_token"; internal const string GetUserIdentities = "gotrue.get_user_identities"; internal const string GetRecoveryCodesStatus = "gotrue.get_recovery_codes_status"; + internal const string GenerateRecoveryCodes = "gotrue.generate_recovery_codes"; internal const string UnenrollRecoveryCodes = "gotrue.unenroll_recovery_codes"; internal const string SignInWithOtp = "gotrue.sign_in.otp"; internal const string SignIn = "gotrue.sign_in"; diff --git a/packages/Gotrue/Gotrue/Interfaces/IGotrueApi.cs b/packages/Gotrue/Gotrue/Interfaces/IGotrueApi.cs index 032577aa..7c6a38d7 100644 --- a/packages/Gotrue/Gotrue/Interfaces/IGotrueApi.cs +++ b/packages/Gotrue/Gotrue/Interfaces/IGotrueApi.cs @@ -6,6 +6,7 @@ using Supabase.Gotrue.Claims; using Supabase.Gotrue.Common; using Supabase.Gotrue.CreateCustomProvider; +using Supabase.Gotrue.GenerateRecoveryCodes; using Supabase.Gotrue.GetRecoveryCodesStatus; using Supabase.Gotrue.Mfa; using Supabase.Gotrue.Resend; @@ -81,6 +82,16 @@ public interface IGotrueApi : IGettableHeaders /// The server rejected the request. Task GetRecoveryCodesStatusAsync(string jwt, CancellationToken cancellationToken = default); + /// + /// Generates the user's one-time set of MFA recovery codes. + /// + /// The user's access token, at the aal2 assurance level. + /// Optional settings, such as the factor's friendly name. + /// Cancels the request. + /// The generated codes, returned only this once. + /// The server rejected the request. + Task GenerateRecoveryCodesAsync(string jwt, GenerateRecoveryCodesOptions? options = null, CancellationToken cancellationToken = default); + /// /// Removes the user's MFA recovery codes factor together with every remaining code. /// diff --git a/packages/Gotrue/Gotrue/Interfaces/IGotrueClient.cs b/packages/Gotrue/Gotrue/Interfaces/IGotrueClient.cs index e6bcaeb2..5e6186f0 100644 --- a/packages/Gotrue/Gotrue/Interfaces/IGotrueClient.cs +++ b/packages/Gotrue/Gotrue/Interfaces/IGotrueClient.cs @@ -6,7 +6,9 @@ using System.Threading.Tasks; using Supabase.Core.Interfaces; using Supabase.Gotrue.Claims; +using Supabase.Gotrue.Common; using Supabase.Gotrue.Exceptions; +using Supabase.Gotrue.GenerateRecoveryCodes; using Supabase.Gotrue.GetRecoveryCodesStatus; using Supabase.Gotrue.Mfa; using Supabase.Gotrue.Resend; @@ -679,6 +681,42 @@ public interface IGotrueClient : IGettableHeaders /// Task GetRecoveryCodesStatusAsync(CancellationToken cancellationToken = default); + /// + /// Generates the signed-in user's single set of MFA recovery codes. The plaintext codes are returned exactly + /// once and cannot be read back: show them to the user and ask them to store them safely. The session must be at + /// the aal2 assurance level and the user must already have another verified factor, because recovery codes + /// can never be the only second factor. A user has at most one set of recovery codes. + /// The new recovery_code factor is not in the current session's , which + /// reads, until the session is refreshed or the user is fetched again. + /// Recovery codes are experimental on the auth server. + /// + /// Optional settings, such as the factor's friendly name. + /// Cancels the request. + /// The generated codes, returned only this once. + /// + /// when the client is offline, + /// when no user is signed in, + /// or the server's rejection of the request, with its : + /// insufficient_aal when the session is not at aal2, + /// mfa_recovery_codes_sole_factor when the user has no other verified factor, + /// mfa_verified_factor_exists when the user already has recovery codes, + /// mfa_factor_name_conflict when another factor has the same friendly name, + /// too_many_enrolled_mfa_factors when the user has reached the factor limit, + /// mfa_recovery_codes_enroll_not_enabled when recovery codes are disabled on the server, + /// no_authorization for an anonymous user. + /// + /// + /// + /// await client.ChallengeAndVerify(new MfaChallengeAndVerifyParams { FactorId = totpFactorId, Code = code }); + /// var recoveryCodes = await client.GenerateRecoveryCodesAsync(new GenerateRecoveryCodesOptions { FriendlyName = "Backup codes" }); + /// foreach (var recoveryCode in recoveryCodes.Codes) + /// { + /// // show each code once; they cannot be retrieved again + /// } + /// + /// + Task GenerateRecoveryCodesAsync(GenerateRecoveryCodesOptions? options = null, CancellationToken cancellationToken = default); + /// /// Removes the signed-in user's MFA recovery codes factor, invalidating every remaining code. The session must /// be at the aal2 assurance level. Sessions that reached aal2 with a recovery code are lowered to diff --git a/packages/Gotrue/Gotrue/PublicAPI.Unshipped.txt b/packages/Gotrue/Gotrue/PublicAPI.Unshipped.txt index 7dc5c581..37f69ce4 100644 --- a/packages/Gotrue/Gotrue/PublicAPI.Unshipped.txt +++ b/packages/Gotrue/Gotrue/PublicAPI.Unshipped.txt @@ -1 +1,31 @@ #nullable enable +override Supabase.Gotrue.Common.RecoveryCodes.Equals(object? obj) -> bool +override Supabase.Gotrue.Common.RecoveryCodes.GetHashCode() -> int +override Supabase.Gotrue.Common.RecoveryCodes.ToString() -> string! +override Supabase.Gotrue.GenerateRecoveryCodes.GenerateRecoveryCodesOptions.Equals(object? obj) -> bool +override Supabase.Gotrue.GenerateRecoveryCodes.GenerateRecoveryCodesOptions.GetHashCode() -> int +override Supabase.Gotrue.GenerateRecoveryCodes.GenerateRecoveryCodesOptions.ToString() -> string! +static Supabase.Gotrue.Common.RecoveryCodes.operator !=(Supabase.Gotrue.Common.RecoveryCodes? left, Supabase.Gotrue.Common.RecoveryCodes? right) -> bool +static Supabase.Gotrue.Common.RecoveryCodes.operator ==(Supabase.Gotrue.Common.RecoveryCodes? left, Supabase.Gotrue.Common.RecoveryCodes? right) -> bool +static Supabase.Gotrue.GenerateRecoveryCodes.GenerateRecoveryCodesOptions.operator !=(Supabase.Gotrue.GenerateRecoveryCodes.GenerateRecoveryCodesOptions? left, Supabase.Gotrue.GenerateRecoveryCodes.GenerateRecoveryCodesOptions? right) -> bool +static Supabase.Gotrue.GenerateRecoveryCodes.GenerateRecoveryCodesOptions.operator ==(Supabase.Gotrue.GenerateRecoveryCodes.GenerateRecoveryCodesOptions? left, Supabase.Gotrue.GenerateRecoveryCodes.GenerateRecoveryCodesOptions? right) -> bool +Supabase.Gotrue.Api.GenerateRecoveryCodesAsync(string! jwt, Supabase.Gotrue.GenerateRecoveryCodes.GenerateRecoveryCodesOptions? options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +Supabase.Gotrue.Client.GenerateRecoveryCodesAsync(Supabase.Gotrue.GenerateRecoveryCodes.GenerateRecoveryCodesOptions? options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +Supabase.Gotrue.Common.RecoveryCodes +Supabase.Gotrue.Common.RecoveryCodes.$() -> Supabase.Gotrue.Common.RecoveryCodes! +Supabase.Gotrue.Common.RecoveryCodes.Codes.get -> System.Collections.Generic.IReadOnlyList! +Supabase.Gotrue.Common.RecoveryCodes.Codes.init -> void +Supabase.Gotrue.Common.RecoveryCodes.Equals(Supabase.Gotrue.Common.RecoveryCodes? other) -> bool +Supabase.Gotrue.Common.RecoveryCodes.FactorId.get -> string! +Supabase.Gotrue.Common.RecoveryCodes.FactorId.init -> void +Supabase.Gotrue.Common.RecoveryCodes.FriendlyName.get -> string! +Supabase.Gotrue.Common.RecoveryCodes.FriendlyName.init -> void +Supabase.Gotrue.Common.RecoveryCodes.RecoveryCodes() -> void +Supabase.Gotrue.GenerateRecoveryCodes.GenerateRecoveryCodesOptions +Supabase.Gotrue.GenerateRecoveryCodes.GenerateRecoveryCodesOptions.$() -> Supabase.Gotrue.GenerateRecoveryCodes.GenerateRecoveryCodesOptions! +Supabase.Gotrue.GenerateRecoveryCodes.GenerateRecoveryCodesOptions.Equals(Supabase.Gotrue.GenerateRecoveryCodes.GenerateRecoveryCodesOptions? other) -> bool +Supabase.Gotrue.GenerateRecoveryCodes.GenerateRecoveryCodesOptions.FriendlyName.get -> string? +Supabase.Gotrue.GenerateRecoveryCodes.GenerateRecoveryCodesOptions.FriendlyName.init -> void +Supabase.Gotrue.GenerateRecoveryCodes.GenerateRecoveryCodesOptions.GenerateRecoveryCodesOptions() -> void +Supabase.Gotrue.Interfaces.IGotrueApi.GenerateRecoveryCodesAsync(string! jwt, Supabase.Gotrue.GenerateRecoveryCodes.GenerateRecoveryCodesOptions? options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +Supabase.Gotrue.Interfaces.IGotrueClient.GenerateRecoveryCodesAsync(Supabase.Gotrue.GenerateRecoveryCodes.GenerateRecoveryCodesOptions? options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task!