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

using System;
using System.Net;
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 WireMock.Matchers;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;

#endregion

namespace Gotrue.Tests.Admin;

/// <summary>
/// Pins the wire contract of custom OAuth/OIDC provider administration against a stubbed auth server:
/// the route, the service-role credentials, and cancellation.
/// </summary>
[TestClass]
[TestCategory("Contract")]
public class AdminCustomProviderContractTests
{
private const string ServiceKey = "service-role-jwt";

private MockGotrueServer server = null!;

[TestInitialize]
public void TestInitialize()
{
this.server = new MockGotrueServer();
this.server.Given(Request.Create().WithPath(new WildcardMatcher("/admin/custom-providers/*")).UsingDelete())
.RespondWith(Response.Create().WithStatusCode(HttpStatusCode.NoContent));
}

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

[TestMethod]
[DataRow("custom:mycompany")]
[DataRow("custom:my.company")]
public async Task DeleteCustomProviderAsync_ShouldDeleteProviderByIdentifier(string identifier)
{
await new AdminClient(ServiceKey, new ClientOptions { Url = this.server.Url }).DeleteCustomProviderAsync(identifier);
this.server.VerifySingleReceivedRequest()
.WithMethod(HttpMethod.Delete)
.WithPath($"/admin/custom-providers/{identifier}")
.WithHeader("Authorization", $"Bearer {ServiceKey}");
}

[TestMethod]
public async Task DeleteCustomProviderAsync_ShouldNotSendRequest_GivenCancelledToken()
{
using var cancelled = new CancellationTokenSource();
cancelled.Cancel();
var delete = () => new AdminClient(ServiceKey, new ClientOptions { Url = this.server.Url })
.DeleteCustomProviderAsync("custom:mycompany", cancelled.Token);
await delete.Should().ThrowAsync<OperationCanceledException>();
this.server.CountReceivedRequests().Should().Be(0, "a cancelled token must stop the request before it reaches the wire");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
#region

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

#endregion

namespace Gotrue.Tests.Admin;

/// <summary>
/// The identifier checks made before a custom provider request leaves the SDK: the <c>custom:</c> prefix the
/// auth server requires, and the characters that would change which route the request reaches.
/// </summary>
[TestClass]
[TestCategory("Unit")]
public class AdminCustomProviderIdentifierTests
{
private static readonly AdminClient Admin = new("service-role-jwt", new ClientOptions { Url = "http://localhost" });

[TestMethod]
public async Task DeleteCustomProviderAsync_ShouldThrowArgumentNull_GivenNullIdentifier()
{
var delete = () => Admin.DeleteCustomProviderAsync(null!);
await delete.Should().ThrowExactlyAsync<ArgumentNullException>().WithParameterName("identifier");
}

[TestMethod]
[DataRow("")]
[DataRow("mycompany")]
[DataRow("Custom:mycompany")]
[DataRow(" custom:mycompany")]
public async Task DeleteCustomProviderAsync_ShouldThrowArgument_GivenIdentifierWithoutCustomPrefix(string identifier)
{
var delete = () => Admin.DeleteCustomProviderAsync(identifier);
await delete.Should().ThrowExactlyAsync<ArgumentException>()
.WithMessage("*start with 'custom:'*", "the auth server rejects any identifier without the case-sensitive 'custom:' prefix with 400 validation_failed")
.WithParameterName("identifier");
}

[TestMethod]
[DataRow("custom:my/company")]
[DataRow("custom:x/../../users/00000000-0000-0000-0000-000000000000")]
[DataRow("custom:my\\company")]
[DataRow("custom:my?company")]
[DataRow("custom:my#company")]
[DataRow("custom:my%2Fcompany")]
public async Task DeleteCustomProviderAsync_ShouldThrowArgument_GivenIdentifierThatChangesTheRoute(string identifier)
{
var delete = () => Admin.DeleteCustomProviderAsync(identifier);
await delete.Should().ThrowExactlyAsync<ArgumentException>()
.WithMessage("*cannot contain*", "the identifier is a path segment: these characters would send the delete to another route, such as /admin/users/{id}")
.WithParameterName("identifier");
}
}
91 changes: 91 additions & 0 deletions packages/Gotrue/Gotrue.Tests/Admin/AdminCustomProviderTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
#region

using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using FluentAssertions;
using Gotrue.Tests.Support;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Supabase.Gotrue.Exceptions;
using static Gotrue.Tests.TestUtils;

#endregion

namespace Gotrue.Tests.Admin;

/// <summary>
/// End-to-end custom OAuth/OIDC provider administration against the live stack. Each test works on its own
/// provider, seeded and removed through the admin API directly so the assertions only exercise the SDK call
/// under test.
/// </summary>
[TestClass]
[TestCategory("E2E")]
public class AdminCustomProviderTests : AdminFixture
{
private static readonly HttpClient AdminApi = new();
private static readonly string ServiceKey = GenerateServiceRoleToken(TestClients.CliJwtSecret);

private readonly string identifier = $"custom:{RandomString(12)}";

[TestCleanup]
public async Task RemoveSeededProvider() => (await SendAdminRequest(HttpMethod.Delete, this.ProviderUrl)).Dispose();

[TestMethod]
public async Task DeleteCustomProviderAsync_ShouldRemoveProvider()
{
await this.SeedProvider();
await this.Admin.DeleteCustomProviderAsync(this.identifier);
using var lookup = await SendAdminRequest(HttpMethod.Get, this.ProviderUrl);
lookup.StatusCode.Should().Be(HttpStatusCode.NotFound, "a deleted provider is no longer retrievable by its identifier");
}

[TestMethod]
public async Task DeleteCustomProviderAsync_ShouldThrowCustomProviderNotFound_GivenUnknownIdentifier()
{
var delete = () => this.Admin.DeleteCustomProviderAsync(this.identifier);
await delete.Should().ThrowAsync<GotrueException>()
.Where(failure => failure.Reason == FailureHint.Reason.CustomProviderNotFound,
"the auth server answers 404 custom_provider_not_found when no provider has the identifier");
}

[TestMethod]
public async Task DeleteCustomProviderAsync_ShouldThrowAdminTokenRequired_GivenNonAdminKey()
{
await this.SeedProvider();
var delete = () => TestClients.AdminAgainstCliStack(TestClients.CliAnonKey).DeleteCustomProviderAsync(this.identifier);
await delete.Should().ThrowAsync<GotrueException>()
.Where(failure => failure.Reason == FailureHint.Reason.AdminTokenRequired,
"the auth server answers 403 not_admin to a key without the service_role claim");
}

private string ProviderUrl => $"{TestClients.CliAuthUrl}/admin/custom-providers/{this.identifier}";

private async Task SeedProvider()
{
using var created = await SendAdminRequest(HttpMethod.Post, $"{TestClients.CliAuthUrl}/admin/custom-providers", $$"""
{
"provider_type": "oauth2",
"identifier": "{{this.identifier}}",
"name": "E2E provider",
"client_id": "client-id",
"client_secret": "client-secret",
"authorization_url": "https://example.com/authorize",
"token_url": "https://example.com/token",
"userinfo_url": "https://example.com/userinfo"
}
""");
created.EnsureSuccessStatusCode();
}

private static async Task<HttpResponseMessage> SendAdminRequest(HttpMethod method, string url, string? json = null)
{
using var request = new HttpRequestMessage(method, url);
request.Headers.Add("apikey", TestClients.CliAnonKey);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", ServiceKey);
if (json != null)
request.Content = new StringContent(json, Encoding.UTF8, "application/json");
return await AdminApi.SendAsync(request);
}
}
1 change: 1 addition & 0 deletions packages/Gotrue/Gotrue.Tests/Errors/FailureHintTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ public async Task DetectReason_ShouldFallBackToStatusCode_GivenNoErrorCode(int s
[DataRow("no_authorization", AdminTokenRequired, DisplayName = "no_authorization")]
[DataRow("not_admin", AdminTokenRequired, DisplayName = "not_admin")]
[DataRow("sso_provider_not_found", SsoProviderNotFound, DisplayName = "sso_provider_not_found")]
[DataRow("custom_provider_not_found", CustomProviderNotFound, DisplayName = "custom_provider_not_found")]
[DataRow("mfa_verification_failed", MfaChallengeUnverified, DisplayName = "mfa_verification_failed")]
[DataRow("mfa_verification_rejected", MfaChallengeUnverified, DisplayName = "mfa_verification_rejected")]
[DataRow("mfa_challenge_expired", MfaChallengeUnverified, DisplayName = "mfa_challenge_expired")]
Expand Down
6 changes: 6 additions & 0 deletions packages/Gotrue/Gotrue/AdminClient.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Supabase.Core.Attributes;
using Supabase.Gotrue.Interfaces;
Expand Down Expand Up @@ -136,6 +137,11 @@ public async Task<bool> DeleteUser(string uid, bool shouldSoftDelete = false)
[ImplementedCapability("auth.admin.delete_mfa_factor")]
public async Task<MfaAdminDeleteFactorResponse?> DeleteFactor(MfaAdminDeleteFactorParams deleteFactorParams) => await this.api.DeleteFactor(this.serviceKey, deleteFactorParams);

/// <inheritdoc />
[ImplementedCapability("auth.admin.delete_provider")]
public Task DeleteCustomProviderAsync(string identifier, CancellationToken cancellationToken = default) =>
this.api.DeleteCustomProviderAsync(this.serviceKey, identifier, cancellationToken);

/// <inheritdoc />
public async Task<User?> Update(UserAttributes attributes)
{
Expand Down
5 changes: 5 additions & 0 deletions packages/Gotrue/Gotrue/Api.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using Supabase.Core.Extensions;
using Supabase.Core.Http;
using Supabase.Gotrue.Claims;
using Supabase.Gotrue.CustomProviders;
using Supabase.Gotrue.Exceptions;
using Supabase.Gotrue.Interfaces;
using Supabase.Gotrue.Mfa;
Expand Down Expand Up @@ -637,6 +638,10 @@ public ProviderAuthState GetUriForProvider(Provider provider, SignInOptions? opt
/// <inheritdoc />
public Task<MfaAdminDeleteFactorResponse?> DeleteFactor(string jwt, MfaAdminDeleteFactorParams deleteFactorParams) => this.MakeRequestAsync<MfaAdminDeleteFactorResponse>(HttpMethod.Delete, $"{this.Url}/admin/users/{deleteFactorParams.UserId}/factors/{deleteFactorParams.Id}", null, this.CreateAuthedRequestHeaders(jwt));

/// <inheritdoc />
public Task DeleteCustomProviderAsync(string jwt, string identifier, CancellationToken cancellationToken = default) =>
this.MakeRequestAsync(HttpMethod.Delete, $"{this.Url}/admin/custom-providers/{CustomProviderIdentifier.EnsureRoutable(identifier)}", null, this.CreateAuthedRequestHeaders(jwt), cancellationToken);

/// <inheritdoc />
public async Task<ProviderAuthState> LinkIdentity(string token, Provider provider, SignInOptions options)
{
Expand Down
22 changes: 22 additions & 0 deletions packages/Gotrue/Gotrue/CustomProviders/CustomProviderIdentifier.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using System;
using System.Linq;

namespace Supabase.Gotrue.CustomProviders;

internal static class CustomProviderIdentifier
{
private const string Prefix = "custom:";

private static readonly char[] RouteChangingCharacters = { '/', '\\', '?', '#', '%' };

internal static string EnsureRoutable(string identifier)
{
if (identifier is null)
throw new ArgumentNullException(nameof(identifier));
if (!identifier.StartsWith(Prefix, StringComparison.Ordinal))
throw new ArgumentException($"Custom provider identifiers start with '{Prefix}', for example '{Prefix}mycompany'.", nameof(identifier));
if (identifier.Any(RouteChangingCharacters.Contains))
throw new ArgumentException("Custom provider identifiers cannot contain '/', '\\', '?', '#' or '%': they would change the route of the request.", nameof(identifier));
return identifier;
}
}
6 changes: 6 additions & 0 deletions packages/Gotrue/Gotrue/Exceptions/FailureReason.cs
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,11 @@ public enum Reason
/// The JWT is expired, malformed, or its signature did not verify.
/// </summary>
InvalidJwt,

/// <summary>
/// No custom OAuth/OIDC provider has the requested identifier.
/// </summary>
CustomProviderNotFound,
}

/// <summary>
Expand All @@ -156,6 +161,7 @@ public enum Reason
["no_authorization"] = AdminTokenRequired,
["not_admin"] = AdminTokenRequired,
["sso_provider_not_found"] = SsoProviderNotFound,
["custom_provider_not_found"] = CustomProviderNotFound,
["mfa_verification_failed"] = MfaChallengeUnverified,
["mfa_verification_rejected"] = MfaChallengeUnverified,
["mfa_challenge_expired"] = MfaChallengeUnverified,
Expand Down
25 changes: 25 additions & 0 deletions packages/Gotrue/Gotrue/Interfaces/IGotrueAdminClient.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using Supabase.Core.Interfaces;
using Supabase.Gotrue.Mfa;
Expand Down Expand Up @@ -107,4 +109,27 @@ public interface IGotrueAdminClient<TUser> : IGettableHeaders
/// <param name="listFactorParams">A <see cref="MfaAdminListFactorsParams"/> object that contains the user id.</param>
/// <returns>A <see cref="MfaAdminDeleteFactorResponse"/> containing the deleted factor id.</returns>
Task<MfaAdminDeleteFactorResponse?> DeleteFactor(MfaAdminDeleteFactorParams deleteFactorParams);

/// <summary>
/// Deletes a custom OAuth/OIDC provider. Requires a full-access API key, such as the service_role key:
/// call it from a server, never from a client app.
/// </summary>
/// <param name="identifier">The provider identifier, starting with <c>custom:</c> (for example <c>custom:mycompany</c>).</param>
/// <param name="cancellationToken">Cancels the request.</param>
/// <exception cref="ArgumentException">
/// The identifier lacks the <c>custom:</c> prefix or contains <c>/</c>, <c>\</c>, <c>?</c>, <c>#</c> or <c>%</c>.
/// Nothing is sent.
/// </exception>
/// <exception cref="Exceptions.GotrueException">
/// The server rejected the request. <see cref="Exceptions.GotrueException.Reason" /> is
/// <see cref="Exceptions.FailureHint.Reason.CustomProviderNotFound" /> when no provider has this identifier;
/// <see cref="Exceptions.GotrueException.ErrorCode" /> is <c>feature_disabled</c> when custom providers are disabled on the project.
/// </exception>
/// <example>
/// <code>
/// var admin = new AdminClient(serviceRoleKey, new ClientOptions { Url = authUrl });
/// await admin.DeleteCustomProviderAsync("custom:mycompany");
/// </code>
/// </example>
Task DeleteCustomProviderAsync(string identifier, CancellationToken cancellationToken = default);
}
10 changes: 10 additions & 0 deletions packages/Gotrue/Gotrue/Interfaces/IGotrueApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,16 @@ public interface IGotrueApi<TUser, TSession> : IGettableHeaders
Task<BaseResponse> ListFactors(string jwt, MfaAdminListFactorsParams listFactorsParams);
Task<MfaAdminDeleteFactorResponse?> DeleteFactor(string jwt, MfaAdminDeleteFactorParams deleteFactorParams);

/// <summary>
/// Deletes a custom OAuth/OIDC provider.
/// </summary>
/// <param name="jwt">A full-access API key, such as the service_role key.</param>
/// <param name="identifier">The provider identifier, starting with <c>custom:</c>.</param>
/// <param name="cancellationToken">Cancels the request.</param>
/// <exception cref="ArgumentException">The identifier lacks the <c>custom:</c> prefix or contains <c>/</c>, <c>\</c>, <c>?</c>, <c>#</c> or <c>%</c>.</exception>
/// <exception cref="Exceptions.GotrueException">The server rejected the request.</exception>
Task DeleteCustomProviderAsync(string jwt, string identifier, CancellationToken cancellationToken = default);

/// <summary>
/// Links an oauth identity to an existing user.
///
Expand Down
5 changes: 5 additions & 0 deletions packages/Gotrue/Gotrue/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
@@ -1 +1,6 @@
#nullable enable
Supabase.Gotrue.AdminClient.DeleteCustomProviderAsync(string! identifier, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task!
Supabase.Gotrue.Api.DeleteCustomProviderAsync(string! jwt, string! identifier, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task!
Supabase.Gotrue.Exceptions.FailureHint.Reason.CustomProviderNotFound = 23 -> Supabase.Gotrue.Exceptions.FailureHint.Reason
Supabase.Gotrue.Interfaces.IGotrueAdminClient<TUser>.DeleteCustomProviderAsync(string! identifier, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task!
Supabase.Gotrue.Interfaces.IGotrueApi<TUser, TSession>.DeleteCustomProviderAsync(string! jwt, string! identifier, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task!
Loading