Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
emptyString
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
emptyString
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"friendly_name":"Backup codes"}
Original file line number Diff line number Diff line change
@@ -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"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"code": 403,
"error_code": "insufficient_aal",
"msg": "AAL2 required to generate recovery codes"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"id": "2b306a77-21dc-4110-ba71-537cb56b9e98",
"type": "recovery_code",
"friendly_name": "Backup codes",
"total": 3,
"codes": [
"k4m9x7qp2ab8ht3z",
"9wze6r5npd4cmq7v",
"2h8kqw3m7xt49rpn"
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"id": "2b306a77-21dc-4110-ba71-537cb56b9e98",
"type": "recovery_code",
"friendly_name": "Backup codes",
"total": 0
}
Original file line number Diff line number Diff line change
@@ -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"
}
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// 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.
/// </summary>
[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");
}
}
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// 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.
/// </summary>
[TestClass]
[TestCategory("Contract")]
public class GenerateRecoveryCodesContractTests
{
private const string AccessToken = "an-access-token";
private IGotrueClient<User, Session> 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<GotrueException>("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<GotrueException>()).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<GotrueException>()).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<GotrueException>()).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<GotrueException>().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<GotrueException>()).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<GotrueException>();
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<GotrueException>().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<OperationCanceledException>("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));
}
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// 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
/// <see cref="GenerateRecoveryCodesContractTests" />.
/// </summary>
[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<GotrueException>()).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<GotrueException>()).Which.ErrorCode.Should().Be("no_authorization",
"anonymous users cannot use recovery codes (auth OpenAPI, POST /factors/recovery-codes 403)");
}
}
1 change: 1 addition & 0 deletions packages/Gotrue/Gotrue.Tests/Gotrue.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
<None Update="UpdateFactor\Data\*.json" CopyToOutputDirectory="PreserveNewest" />
<None Update="GetRecoveryCodesStatus\Data\*.json" CopyToOutputDirectory="PreserveNewest" />
<None Update="UnenrollRecoveryCodes\Data\*.json" CopyToOutputDirectory="PreserveNewest" />
<None Update="GenerateRecoveryCodes\Data\*.json" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -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()
{
Expand Down Expand Up @@ -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())
Expand Down
8 changes: 8 additions & 0 deletions packages/Gotrue/Gotrue/Api.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -657,6 +658,13 @@ public ProviderAuthState GetUriForProvider(Provider provider, SignInOptions? opt
}
}

/// <inheritdoc />
public async Task<RecoveryCodes> GenerateRecoveryCodesAsync(string jwt, GenerateRecoveryCodesOptions? options = null, CancellationToken cancellationToken = default)
{
var generated = await this.MakeRequestAsync<RecoveryCodesResponse>(HttpMethod.Post, $"{this.Url}/factors/recovery-codes", GenerateRecoveryCodesBody.For(options), this.CreateAuthedRequestHeaders(jwt), cancellationToken).ConfigureAwait(false);
return RecoveryCodesResponse.Read(generated);
}

/// <inheritdoc />
public Task UnenrollRecoveryCodesAsync(string jwt, CancellationToken cancellationToken = default) =>
this.MakeRequestAsync(HttpMethod.Delete, $"{this.Url}/factors/recovery-codes", null, this.CreateAuthedRequestHeaders(jwt), cancellationToken);
Expand Down
Loading
Loading