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
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 @@ -39,6 +39,7 @@
<None Update="UnenrollRecoveryCodes\Data\*.json" CopyToOutputDirectory="PreserveNewest" />
<None Update="GenerateRecoveryCodes\Data\*.json" CopyToOutputDirectory="PreserveNewest" />
<None Update="VerifyRecoveryCode\Data\*.json" CopyToOutputDirectory="PreserveNewest" />
<None Update="ListPasskeys\Data\*.json" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[]
12 changes: 12 additions & 0 deletions packages/Gotrue/Gotrue.Tests/ListPasskeys/Data/passkeys.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[
{
"id": "5f0b6c1e-8a43-4d1f-9c7e-2b8f3e6a1d24",
"friendly_name": "iCloud Keychain",
"created_at": "2026-03-02T09:15:30.123456Z",
"last_used_at": "2026-10-28T17:42:05Z"
},
{
"id": "c3a9e2d7-41b6-4f08-8e5a-9d1c7b2f6e30",
"created_at": "2026-04-11T08:00:00Z"
}
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"code": 404,
"error_code": "passkey_disabled",
"msg": "Passkeys are disabled"
}
186 changes: 186 additions & 0 deletions packages/Gotrue/Gotrue.Tests/ListPasskeys/ListPasskeysContractTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
#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.Exceptions;
using Supabase.Gotrue.Interfaces;
using Supabase.Gotrue.ListPasskeys;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
using static Supabase.Gotrue.Exceptions.FailureHint.Reason;

#endregion

namespace Gotrue.Tests.ListPasskeys;

/// <summary>
/// Pins how ListPasskeysAsync lists the signed-in user's passkeys: the GET /passkeys request it puts on the
/// wire, how the passkey list maps to the result, and the failures raised before and after the request, all
/// against a stubbed server.
/// </summary>
[TestClass]
[TestCategory("Contract")]
public class ListPasskeysContractTests
{
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 ListPasskeysAsync_ShouldGetThePasskeysWithTheSessionBearer()
{
this.SignIn();
this.MockPasskeysResponse(200, Fixture("passkeys.json"));
await this.client.ListPasskeysAsync();
this.server.VerifySingleReceivedRequest()
.WithMethod(HttpMethod.Get)
.WithPath("/passkeys")
.WithHeader("Authorization", $"Bearer {AccessToken}")
.WithHeader("apikey", MockGotrueServer.ApiKey);
}

[TestMethod]
public async Task ListPasskeysAsync_ShouldReturnEachPasskeyInServerOrder_GivenUserWithPasskeys()
{
this.SignIn();
this.MockPasskeysResponse(200, Fixture("passkeys.json"));
var passkeys = await this.client.ListPasskeysAsync();
passkeys.Should().BeEquivalentTo(new[]
{
new Passkey
{
Id = Guid.Parse("5f0b6c1e-8a43-4d1f-9c7e-2b8f3e6a1d24"),
FriendlyName = "iCloud Keychain",
CreatedAt = new DateTime(2026, 3, 2, 9, 15, 30, DateTimeKind.Utc).AddTicks(1234560),
LastUsedAt = new DateTime(2026, 10, 28, 17, 42, 5, DateTimeKind.Utc),
},
new Passkey
{
Id = Guid.Parse("c3a9e2d7-41b6-4f08-8e5a-9d1c7b2f6e30"),
CreatedAt = new DateTime(2026, 4, 11, 8, 0, 0, DateTimeKind.Utc),
},
}, options => options.WithStrictOrdering(),
"each item is a PasskeyListItem (id, friendly_name, created_at, last_used_at), listed in the server's created_at order (supabase/auth PasskeyList)");
}

[TestMethod]
public async Task ListPasskeysAsync_ShouldReturnEmptyList_GivenUserWithoutPasskeys()
{
this.SignIn();
this.MockPasskeysResponse(200, Fixture("no_passkeys.json"));
var passkeys = await this.client.ListPasskeysAsync();
passkeys.Should().BeEmpty("GET /passkeys answers an empty array for a user without passkeys (supabase/auth PasskeyList)");
}

[TestMethod]
public async Task ListPasskeysAsync_ShouldReturnEmptyList_GivenSuccessWithoutBody()
{
this.SignIn();
this.MockPasskeysResponse(200, "null");
var passkeys = await this.client.ListPasskeysAsync();
passkeys.Should().BeEmpty("a collection on the public surface is never null");
}

[TestMethod]
public async Task ListPasskeysAsync_ShouldThrowServerRejection_GivenPasskeysDisabled()
{
this.SignIn();
this.MockPasskeysResponse(404, Fixture("passkeys_disabled_error.json"));
var listing = () => this.client.ListPasskeysAsync();
(await listing.Should().ThrowAsync<GotrueException>()).Which.ErrorCode.Should().Be("passkey_disabled",
"every /passkeys route answers 404 passkey_disabled when passkeys are off on the server (supabase/auth requirePasskeyEnabled)");
}

[TestMethod]
public async Task ListPasskeysAsync_ShouldThrowNoSessionFound_GivenNoSession()
{
var listing = () => this.client.ListPasskeysAsync();
(await listing.Should().ThrowAsync<GotrueException>().WithMessage("A valid session is required.")).Which.Reason.Should().Be(NoSessionFound,
"GET /passkeys requires the signed-in user's access token");
}

[TestMethod]
public async Task ListPasskeysAsync_ShouldThrowNoSessionFound_GivenSessionWithoutAccessToken()
{
this.SignIn(new Session { RefreshToken = "a-refresh-token", ExpiresIn = 3600 });
var listing = () => this.client.ListPasskeysAsync();
(await listing.Should().ThrowAsync<GotrueException>()).Which.Reason.Should().Be(NoSessionFound,
"GET /passkeys requires the signed-in user's access token");
}

[TestMethod]
public async Task ListPasskeysAsync_ShouldNotSendARequest_GivenNoSession()
{
var listing = () => this.client.ListPasskeysAsync();
await listing.Should().ThrowAsync<GotrueException>();
this.server.CountReceivedRequests().Should().Be(0, "the missing session is detected before the wire");
}

[TestMethod]
public async Task ListPasskeysAsync_ShouldThrowOffline_GivenClientIsOffline()
{
this.SignIn();
this.client.Online = false;
var listing = () => this.client.ListPasskeysAsync();
(await listing.Should().ThrowAsync<GotrueException>().WithMessage("Only supported when online")).Which.Reason.Should().Be(Offline,
"the passkeys are read from the server");
}

[TestMethod]
public async Task ListPasskeysAsync_ShouldCancelTheRequest_GivenCancelledToken()
{
this.SignIn();
this.MockPasskeysResponse(200, Fixture("passkeys.json"));
using var cancellation = new CancellationTokenSource();
cancellation.Cancel();
var listing = () => this.client.ListPasskeysAsync(cancellation.Token);
await listing.Should().ThrowAsync<OperationCanceledException>("the cancellation token reaches the HTTP call");
}

[TestMethod]
public void ListPasskeysAsync_ShouldComplete_GivenCallerBlockingOnContextThatNeverRunsContinuations()
{
this.SignIn();
this.MockPasskeysResponse(200, Fixture("passkeys.json"));
BlockingCaller.Completes(() => this.client.ListPasskeysAsync()).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 MockPasskeysResponse(int statusCode, string body) =>
this.server
.Given(Request.Create().WithPath("/passkeys").UsingGet())
.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, "ListPasskeys", "Data", name));
}
51 changes: 51 additions & 0 deletions packages/Gotrue/Gotrue.Tests/ListPasskeys/ListPasskeysTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
#region

using System;
using System.Linq;
using System.Threading.Tasks;
using FluentAssertions;
using Gotrue.Tests.Support;
using Microsoft.VisualStudio.TestTools.UnitTesting;

#endregion

namespace Gotrue.Tests.ListPasskeys;

/// <summary>
/// End-to-end listing of the signed-in user's passkeys against the live stack, with passkeys enabled in
/// <c>supabase/config.toml</c>. Passkeys are seeded through the auth server's registration ceremony by
/// <see cref="SoftwareAuthenticator" />, each test on its own freshly signed-up user.
/// </summary>
[TestClass]
[TestCategory("E2E")]
public class ListPasskeysTests : AuthClientFixture
{
[TestMethod]
public async Task ListPasskeysAsync_ShouldReturnEveryRegisteredPasskeyInRegistrationOrder_GivenUserWithPasskeys()
{
var session = await this.SignUpNewUser();
var first = await SoftwareAuthenticator.RegisterPasskeyAsync(session.AccessToken!);
var second = await SoftwareAuthenticator.RegisterPasskeyAsync(session.AccessToken!);
var passkeys = await this.Client.ListPasskeysAsync();
passkeys.Select(passkey => passkey.Id).Should().Equal(new[] { first, second },
"GET /passkeys lists the user's passkeys ordered by created_at ascending (supabase/auth PasskeyList)");
}

[TestMethod]
public async Task ListPasskeysAsync_ShouldDescribeAPasskeyNeverUsedToSignIn_GivenFreshlyRegisteredPasskey()
{
var session = await this.SignUpNewUser();
var registered = await SoftwareAuthenticator.RegisterPasskeyAsync(session.AccessToken!);
var passkeys = await this.Client.ListPasskeysAsync();
passkeys.Should().ContainSingle().Which.Should().BeEquivalentTo(new { Id = registered, FriendlyName = "Passkey", LastUsedAt = (DateTime?) null },
"the server names a passkey from an unknown authenticator model \"Passkey\" and sets last_used_at only on sign-in (supabase/auth PasskeyFriendlyName)");
}

[TestMethod]
public async Task ListPasskeysAsync_ShouldReturnEmptyList_GivenUserWithoutPasskeys()
{
await this.SignUpNewUser();
var passkeys = await this.Client.ListPasskeysAsync();
passkeys.Should().BeEmpty("a freshly signed-up user has registered no passkey");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,17 @@ public async Task DomainSpan_ShouldParentTheHttpSpan_GivenUserIdentitiesListing(
this.activities.Should().ContainSingle(a => a.OperationName == "GET /user").Which.ParentSpanId.Should().Be(domainSpan.SpanId);
}

[TestMethod]
public async Task DomainSpan_ShouldParentTheHttpSpan_GivenPasskeysListing()
{
this.MockTokenSuccess();
await this.Refresh();
this.MockPasskeysSuccess();
await this.client.ListPasskeysAsync();
var domainSpan = this.activities.Should().ContainSingle(a => a.OperationName == "gotrue.list_passkeys").Which;
this.activities.Should().ContainSingle(a => a.OperationName == "GET /passkeys").Which.ParentSpanId.Should().Be(domainSpan.SpanId);
}

[TestMethod]
public async Task DomainSpan_ShouldParentTheHttpSpan_GivenRecoveryCodesStatusReading()
{
Expand Down Expand Up @@ -280,6 +291,14 @@ private void MockUserSuccess() =>
.WithHeader("Content-Type", "application/json")
.WithBody(File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Identities", "Data", "user_with_identities.json"))));

private void MockPasskeysSuccess() =>
this.server
.Given(Request.Create().WithPath("/passkeys").UsingGet())
.RespondWith(Response.Create()
.WithStatusCode(200)
.WithHeader("Content-Type", "application/json")
.WithBody(File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ListPasskeys", "Data", "passkeys.json"))));

private void MockRecoveryCodesStatusSuccess() =>
this.server
.Given(Request.Create().WithPath("/factors/recovery-codes").UsingGet())
Expand Down
Loading
Loading