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,33 @@
#region

using System;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Supabase.Gotrue;

#endregion

namespace Gotrue.Tests.SignOut;

/// <summary>
/// The access-token check made before an admin sign-out leaves the SDK.
/// </summary>
[TestClass]
[TestCategory("Unit")]
public class AdminSignOutAccessTokenTests
{
private static readonly AdminClient Admin = new("service-role-jwt", new ClientOptions { Url = "http://localhost" });

[TestMethod]
[DataRow(null)]
[DataRow("")]
[DataRow(" ")]
public async Task SignOutAsync_ShouldThrowArgument_GivenBlankAccessToken(string? accessToken)
{
var signOut = () => Admin.SignOutAsync(accessToken!);
await signOut.Should().ThrowExactlyAsync<ArgumentException>()
.WithMessage("*access token is required*", "without a token the auth server can only answer 401 no_authorization")
.WithParameterName("accessToken");
}
}
96 changes: 96 additions & 0 deletions packages/Gotrue/Gotrue.Tests/SignOut/AdminSignOutContractTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
#region

using System;
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 WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
using static Supabase.Gotrue.Constants;

#endregion

namespace Gotrue.Tests.SignOut;

/// <summary>
/// Pins the wire contract of signing a user out as an admin against a stubbed auth server: the scope, the user's
/// token as the credentials instead of the service key, failures, and cancellation.
/// </summary>
[TestClass]
[TestCategory("Contract")]
public class AdminSignOutContractTests
{
private const string ServiceKey = "service-role-jwt";
private const string UserAccessToken = "user-access-token";

private MockGotrueServer server = null!;

[TestInitialize]
public void TestInitialize() => this.server = new MockGotrueServer();

[TestCleanup]
public void TestCleanup() => this.server.Dispose();

[TestMethod]
public async Task SignOutAsync_ShouldPostToLogoutWithUserAccessTokenAndConfiguredApiKey()
{
this.AnswerLogoutWith(204);
await this.Admin.SignOutAsync(UserAccessToken);
this.server.VerifySingleReceivedRequest()
.WithMethod(HttpMethod.Post)
.WithPath("/logout")
.WithHeader("Authorization", $"Bearer {UserAccessToken}")
.WithHeader("apikey", MockGotrueServer.ApiKey);
}

[TestMethod]
public async Task SignOutAsync_ShouldSendGlobalScope_GivenNoScope()
{
this.AnswerLogoutWith(204);
await this.Admin.SignOutAsync(UserAccessToken);
this.server.VerifySingleReceivedRequest().WithQueryParam("scope", "global");
}

[TestMethod]
[DataRow(SignOutScope.Global, "global")]
[DataRow(SignOutScope.Local, "local")]
[DataRow(SignOutScope.Others, "others")]
public async Task SignOutAsync_ShouldSendTheRequestedScope(SignOutScope scope, string expected)
{
this.AnswerLogoutWith(204);
await this.Admin.SignOutAsync(UserAccessToken, scope);
this.server.VerifySingleReceivedRequest().WithQueryParam("scope", expected);
}

[TestMethod]
public async Task SignOutAsync_ShouldThrowSessionNotFound_GivenSessionAlreadyRevoked()
{
this.AnswerLogoutWith(403, """{"code":403,"error_code":"session_not_found","msg":"Session from session_id claim in JWT does not exist"}""");
var signOut = () => this.Admin.SignOutAsync(UserAccessToken);
await signOut.Should().ThrowExactlyAsync<GotrueException>()
.Where(failure => failure.ErrorCode == "session_not_found",
"unlike a client's own sign-out, an admin sign-out reports a session that is already gone");
}

[TestMethod]
public async Task SignOutAsync_ShouldNotSendRequest_GivenCancelledToken()
{
using var cancelled = new CancellationTokenSource();
cancelled.Cancel();
var signOut = () => this.Admin.SignOutAsync(UserAccessToken, cancellationToken: cancelled.Token);
await signOut.Should().ThrowAsync<OperationCanceledException>();
this.server.CountReceivedRequests().Should().Be(0, "a cancelled token must stop the request before it reaches the wire");
}

private AdminClient Admin =>
new(ServiceKey, new ClientOptions { Url = this.server.Url, Headers = { ["apikey"] = MockGotrueServer.ApiKey } });

private void AnswerLogoutWith(int status, string body = "") =>
this.server.Given(Request.Create().WithPath("/logout").UsingPost())
.RespondWith(Response.Create().WithStatusCode(status).WithHeader("Content-Type", "application/json").WithBody(body));
}
52 changes: 52 additions & 0 deletions packages/Gotrue/Gotrue.Tests/SignOut/AdminSignOutTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
#region

using System;
using System.Threading.Tasks;
using FluentAssertions;
using Gotrue.Tests.Admin;
using Gotrue.Tests.Support;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Supabase.Gotrue.Exceptions;
using static Gotrue.Tests.TestUtils;
using static Supabase.Gotrue.Constants;

#endregion

namespace Gotrue.Tests.SignOut;

/// <summary>
/// End-to-end admin sign-out against the live stack: each test signs up its own user, and the admin client ends
/// that user's sessions from their access token.
/// </summary>
[TestClass]
[TestCategory("E2E")]
public class AdminSignOutTests : AdminFixture
{
[TestMethod]
public async Task SignOutAsync_ShouldRevokeUserSession()
{
var accessToken = await SignUpUser();
await this.Admin.SignOutAsync(accessToken);
var lookup = () => this.Admin.GetUser(accessToken);
await lookup.Should().ThrowAsync<GotrueException>()
.Where(failure => failure.ErrorCode == "session_not_found",
"the auth server deletes the token's session on a global sign-out, so the token no longer authenticates");
}

[TestMethod]
public async Task SignOutAsync_ShouldThrowSessionNotFound_GivenSessionAlreadyRevoked()
{
var accessToken = await SignUpUser();
await this.Admin.SignOutAsync(accessToken, SignOutScope.Local);
var signOutAgain = () => this.Admin.SignOutAsync(accessToken);
await signOutAgain.Should().ThrowAsync<GotrueException>()
.Where(failure => failure.ErrorCode == "session_not_found",
"the auth server answers 403 session_not_found to a token whose session was revoked");
}

private static async Task<string> SignUpUser()
{
var session = await TestClients.AgainstCliStack().SignUp(RandomEmail(), Password);
return session?.AccessToken ?? throw new InvalidOperationException("The local stack returned no session on sign-up.");
}
}
10 changes: 10 additions & 0 deletions packages/Gotrue/Gotrue/AdminClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,11 @@ public Func<Dictionary<string, string>>? GetHeaders
/// <inheritdoc />
public Task<User?> GetUser(string jwt) => this.api.GetUser(jwt);

/// <inheritdoc />
[ImplementedCapability("auth.admin.sign_out")]
public Task SignOutAsync(string accessToken, Constants.SignOutScope scope = Constants.SignOutScope.Global, CancellationToken cancellationToken = default) =>
this.api.SignOutAsync(RequireAccessToken(accessToken), scope, cancellationToken);

/// <inheritdoc />
[ImplementedCapability("auth.admin.invite_user")]
public async Task<bool> InviteUserByEmail(string email, InviteUserByEmailOptions? options = null)
Expand Down Expand Up @@ -144,6 +149,11 @@ public async Task<bool> DeleteUser(string uid, bool shouldSoftDelete = false)
public Task DeleteCustomProviderAsync(string identifier, CancellationToken cancellationToken = default) =>
this.api.DeleteCustomProviderAsync(this.serviceKey, identifier, cancellationToken);

private static string RequireAccessToken(string accessToken) =>
string.IsNullOrWhiteSpace(accessToken)
? throw new ArgumentException("A user's access token is required to sign them out.", nameof(accessToken))
: accessToken;

/// <inheritdoc />
[ImplementedCapability("auth.admin.create_provider")]
public Task<CustomProvider> CreateCustomProviderAsync(NewCustomProvider provider, CustomProviderOptions? options = null, CancellationToken cancellationToken = default) =>
Expand Down
13 changes: 8 additions & 5 deletions packages/Gotrue/Gotrue/Api.cs
Original file line number Diff line number Diff line change
Expand Up @@ -723,12 +723,15 @@ public async Task<bool> UnlinkIdentity(string token, UserIdentity userIdentity)
/// <param name="jwt"></param>
/// <param name="scope"></param>
/// <returns></returns>
public Task<BaseResponse> SignOut(string jwt, SignOutScope scope = SignOutScope.Global)
{
var data = new Dictionary<string, string>();
public Task<BaseResponse> SignOut(string jwt, SignOutScope scope = SignOutScope.Global) => this.SendSignOut(jwt, scope, CancellationToken.None);

return this.MakeRequestAsync(HttpMethod.Post, $"{this.Url}/logout?scope={Core.Helpers.GetMappedToAttr(scope).Mapping}", data, this.CreateAuthedRequestHeaders(jwt));
}
/// <inheritdoc />
public Task SignOutAsync(string jwt, SignOutScope scope = SignOutScope.Global, CancellationToken cancellationToken = default) =>
this.SendSignOut(jwt, scope, cancellationToken);

private Task<BaseResponse> SendSignOut(string jwt, SignOutScope scope, CancellationToken cancellationToken) =>
this.MakeRequestAsync(HttpMethod.Post, $"{this.Url}/logout?scope={Core.Helpers.GetMappedToAttr(scope).Mapping}", new Dictionary<string, string>(),
this.CreateAuthedRequestHeaders(jwt), cancellationToken);

/// <summary>
/// Gets User Details
Expand Down
27 changes: 27 additions & 0 deletions packages/Gotrue/Gotrue/Interfaces/IGotrueAdminClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,33 @@ public interface IGotrueAdminClient<TUser> : IGettableHeaders
/// <returns></returns>
Task<TUser?> GetUser(string jwt);

/// <summary>
/// Signs a user out on the server from their access token, revoking the refresh tokens of the sessions in
/// <paramref name="scope" />. Access tokens already issued stay valid until they expire. Call it from a server,
/// for example to end a user's sessions after a password reset or a ban.
/// </summary>
/// <param name="accessToken">The user's access token. It authenticates the request: the service key is not sent.</param>
/// <param name="scope">
/// Which sessions to revoke: <see cref="Constants.SignOutScope.Global" /> (the default) revokes every session of the
/// user, <see cref="Constants.SignOutScope.Local" /> only the token's session, and
/// <see cref="Constants.SignOutScope.Others" /> every session but the token's.
/// </param>
/// <param name="cancellationToken">Cancels the request.</param>
/// <exception cref="ArgumentException"><paramref name="accessToken" /> is null, empty or whitespace. Nothing is sent.</exception>
/// <exception cref="Exceptions.GotrueException">
/// The server rejected the token. <see cref="Exceptions.GotrueException.ErrorCode" /> is <c>session_not_found</c>
/// when the token's session was already revoked and <c>user_not_found</c> when its user was deleted;
/// <see cref="Exceptions.GotrueException.Reason" /> is <see cref="Exceptions.FailureHint.Reason.AdminTokenRequired" />
/// (error code <c>bad_jwt</c>) when the token is expired, malformed or not a user's token.
/// </exception>
/// <example>
/// <code>
/// var admin = new AdminClient(serviceRoleKey, new ClientOptions { Url = authUrl, Headers = { ["apikey"] = anonKey } });
/// await admin.SignOutAsync(userAccessToken, Constants.SignOutScope.Global);
/// </code>
/// </example>
Task SignOutAsync(string accessToken, Constants.SignOutScope scope = Constants.SignOutScope.Global, CancellationToken cancellationToken = default);

/// <summary>
/// Gets a user by ID from the server using the admin key (not the anonymous key).
/// </summary>
Expand Down
9 changes: 9 additions & 0 deletions packages/Gotrue/Gotrue/Interfaces/IGotrueApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,15 @@ public interface IGotrueApi<TUser, TSession> : IGettableHeaders
Task<SSOResponse?> SignInWithSSO(Guid providerId, SignInWithSSOOptions? options = null);
Task<SSOResponse?> SignInWithSSO(string domain, SignInWithSSOOptions? options = null);
Task<BaseResponse> SignOut(string jwt, SignOutScope scope = SignOutScope.Global);

/// <summary>
/// Revokes the sessions of the user who owns <paramref name="jwt" />, within <paramref name="scope" />.
/// </summary>
/// <param name="jwt">The user's access token.</param>
/// <param name="scope">Which of the user's sessions to revoke.</param>
/// <param name="cancellationToken">Cancels the request.</param>
/// <exception cref="Exceptions.GotrueException">The server rejected the request.</exception>
Task SignOutAsync(string jwt, SignOutScope scope = SignOutScope.Global, CancellationToken cancellationToken = default);
Task<TSession?> SignUpWithEmail(string email, string password, SignUpOptions? options = null);
Task<TSession?> SignUpWithPhone(string phone, string password, SignUpOptions? options = null);
Task<TUser?> UpdateUser(string jwt, UserAttributes attributes);
Expand Down
4 changes: 4 additions & 0 deletions packages/Gotrue/Gotrue/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
Expand Up @@ -138,3 +138,7 @@ Supabase.Gotrue.CreateCustomProvider.NewCustomProvider.Type.get -> Supabase.Gotr
Supabase.Gotrue.CreateCustomProvider.NewCustomProvider.UserInfoUrl.get -> System.Uri?
Supabase.Gotrue.Interfaces.IGotrueAdminClient<TUser>.CreateCustomProviderAsync(Supabase.Gotrue.CreateCustomProvider.NewCustomProvider! provider, Supabase.Gotrue.Common.CustomProviderOptions? options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Supabase.Gotrue.Common.CustomProvider!>!
Supabase.Gotrue.Interfaces.IGotrueApi<TUser, TSession>.CreateCustomProviderAsync(string! jwt, Supabase.Gotrue.CreateCustomProvider.NewCustomProvider! provider, Supabase.Gotrue.Common.CustomProviderOptions? options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Supabase.Gotrue.Common.CustomProvider!>!
Supabase.Gotrue.AdminClient.SignOutAsync(string! accessToken, Supabase.Gotrue.Constants.SignOutScope scope = Supabase.Gotrue.Constants.SignOutScope.Global, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task!
Supabase.Gotrue.Api.SignOutAsync(string! jwt, Supabase.Gotrue.Constants.SignOutScope scope = Supabase.Gotrue.Constants.SignOutScope.Global, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task!
Supabase.Gotrue.Interfaces.IGotrueAdminClient<TUser>.SignOutAsync(string! accessToken, Supabase.Gotrue.Constants.SignOutScope scope = Supabase.Gotrue.Constants.SignOutScope.Global, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task!
Supabase.Gotrue.Interfaces.IGotrueApi<TUser, TSession>.SignOutAsync(string! jwt, Supabase.Gotrue.Constants.SignOutScope scope = Supabase.Gotrue.Constants.SignOutScope.Global, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task!
Loading