From dbac3b06274f8dbdf3189830a5ea5652d2d32e73 Mon Sep 17 00:00:00 2001 From: tr00d Date: Thu, 29 Oct 2026 10:21:23 +0100 Subject: [PATCH] feat(auth): delete a custom OAuth/OIDC provider as an admin --- .../Admin/AdminCustomProviderContractTests.cs | 65 +++++++++++++ .../AdminCustomProviderIdentifierTests.cs | 57 ++++++++++++ .../Admin/AdminCustomProviderTests.cs | 91 +++++++++++++++++++ .../Gotrue.Tests/Errors/FailureHintTests.cs | 1 + packages/Gotrue/Gotrue/AdminClient.cs | 6 ++ packages/Gotrue/Gotrue/Api.cs | 5 + .../CustomProviderIdentifier.cs | 22 +++++ .../Gotrue/Gotrue/Exceptions/FailureReason.cs | 6 ++ .../Gotrue/Interfaces/IGotrueAdminClient.cs | 25 +++++ .../Gotrue/Gotrue/Interfaces/IGotrueApi.cs | 10 ++ .../Gotrue/Gotrue/PublicAPI.Unshipped.txt | 5 + 11 files changed, 293 insertions(+) create mode 100644 packages/Gotrue/Gotrue.Tests/Admin/AdminCustomProviderContractTests.cs create mode 100644 packages/Gotrue/Gotrue.Tests/Admin/AdminCustomProviderIdentifierTests.cs create mode 100644 packages/Gotrue/Gotrue.Tests/Admin/AdminCustomProviderTests.cs create mode 100644 packages/Gotrue/Gotrue/CustomProviders/CustomProviderIdentifier.cs diff --git a/packages/Gotrue/Gotrue.Tests/Admin/AdminCustomProviderContractTests.cs b/packages/Gotrue/Gotrue.Tests/Admin/AdminCustomProviderContractTests.cs new file mode 100644 index 000000000..363dad000 --- /dev/null +++ b/packages/Gotrue/Gotrue.Tests/Admin/AdminCustomProviderContractTests.cs @@ -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; + +/// +/// Pins the wire contract of custom OAuth/OIDC provider administration against a stubbed auth server: +/// the route, the service-role credentials, and cancellation. +/// +[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(); + this.server.CountReceivedRequests().Should().Be(0, "a cancelled token must stop the request before it reaches the wire"); + } +} diff --git a/packages/Gotrue/Gotrue.Tests/Admin/AdminCustomProviderIdentifierTests.cs b/packages/Gotrue/Gotrue.Tests/Admin/AdminCustomProviderIdentifierTests.cs new file mode 100644 index 000000000..e121581b1 --- /dev/null +++ b/packages/Gotrue/Gotrue.Tests/Admin/AdminCustomProviderIdentifierTests.cs @@ -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; + +/// +/// The identifier checks made before a custom provider request leaves the SDK: the custom: prefix the +/// auth server requires, and the characters that would change which route the request reaches. +/// +[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().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() + .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() + .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"); + } +} diff --git a/packages/Gotrue/Gotrue.Tests/Admin/AdminCustomProviderTests.cs b/packages/Gotrue/Gotrue.Tests/Admin/AdminCustomProviderTests.cs new file mode 100644 index 000000000..9bc104842 --- /dev/null +++ b/packages/Gotrue/Gotrue.Tests/Admin/AdminCustomProviderTests.cs @@ -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; + +/// +/// 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. +/// +[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() + .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() + .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 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); + } +} diff --git a/packages/Gotrue/Gotrue.Tests/Errors/FailureHintTests.cs b/packages/Gotrue/Gotrue.Tests/Errors/FailureHintTests.cs index 91794a8b2..dbd006610 100644 --- a/packages/Gotrue/Gotrue.Tests/Errors/FailureHintTests.cs +++ b/packages/Gotrue/Gotrue.Tests/Errors/FailureHintTests.cs @@ -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")] diff --git a/packages/Gotrue/Gotrue/AdminClient.cs b/packages/Gotrue/Gotrue/AdminClient.cs index 19e3a75ba..b58dd374f 100644 --- a/packages/Gotrue/Gotrue/AdminClient.cs +++ b/packages/Gotrue/Gotrue/AdminClient.cs @@ -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; @@ -136,6 +137,11 @@ public async Task DeleteUser(string uid, bool shouldSoftDelete = false) [ImplementedCapability("auth.admin.delete_mfa_factor")] public async Task DeleteFactor(MfaAdminDeleteFactorParams deleteFactorParams) => await this.api.DeleteFactor(this.serviceKey, deleteFactorParams); + /// + [ImplementedCapability("auth.admin.delete_provider")] + public Task DeleteCustomProviderAsync(string identifier, CancellationToken cancellationToken = default) => + this.api.DeleteCustomProviderAsync(this.serviceKey, identifier, cancellationToken); + /// public async Task Update(UserAttributes attributes) { diff --git a/packages/Gotrue/Gotrue/Api.cs b/packages/Gotrue/Gotrue/Api.cs index 0b3f4abb8..258d4b17a 100644 --- a/packages/Gotrue/Gotrue/Api.cs +++ b/packages/Gotrue/Gotrue/Api.cs @@ -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; @@ -637,6 +638,10 @@ public ProviderAuthState GetUriForProvider(Provider provider, SignInOptions? opt /// public Task DeleteFactor(string jwt, MfaAdminDeleteFactorParams deleteFactorParams) => this.MakeRequestAsync(HttpMethod.Delete, $"{this.Url}/admin/users/{deleteFactorParams.UserId}/factors/{deleteFactorParams.Id}", null, this.CreateAuthedRequestHeaders(jwt)); + /// + 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); + /// public async Task LinkIdentity(string token, Provider provider, SignInOptions options) { diff --git a/packages/Gotrue/Gotrue/CustomProviders/CustomProviderIdentifier.cs b/packages/Gotrue/Gotrue/CustomProviders/CustomProviderIdentifier.cs new file mode 100644 index 000000000..0bdad5843 --- /dev/null +++ b/packages/Gotrue/Gotrue/CustomProviders/CustomProviderIdentifier.cs @@ -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; + } +} diff --git a/packages/Gotrue/Gotrue/Exceptions/FailureReason.cs b/packages/Gotrue/Gotrue/Exceptions/FailureReason.cs index 370bdba78..a08a378e7 100644 --- a/packages/Gotrue/Gotrue/Exceptions/FailureReason.cs +++ b/packages/Gotrue/Gotrue/Exceptions/FailureReason.cs @@ -130,6 +130,11 @@ public enum Reason /// The JWT is expired, malformed, or its signature did not verify. /// InvalidJwt, + + /// + /// No custom OAuth/OIDC provider has the requested identifier. + /// + CustomProviderNotFound, } /// @@ -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, diff --git a/packages/Gotrue/Gotrue/Interfaces/IGotrueAdminClient.cs b/packages/Gotrue/Gotrue/Interfaces/IGotrueAdminClient.cs index addd559fd..df63c49eb 100644 --- a/packages/Gotrue/Gotrue/Interfaces/IGotrueAdminClient.cs +++ b/packages/Gotrue/Gotrue/Interfaces/IGotrueAdminClient.cs @@ -1,3 +1,5 @@ +using System; +using System.Threading; using System.Threading.Tasks; using Supabase.Core.Interfaces; using Supabase.Gotrue.Mfa; @@ -107,4 +109,27 @@ public interface IGotrueAdminClient : IGettableHeaders /// A object that contains the user id. /// A containing the deleted factor id. Task DeleteFactor(MfaAdminDeleteFactorParams deleteFactorParams); + + /// + /// 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. + /// + /// The provider identifier, starting with custom: (for example custom:mycompany). + /// Cancels the request. + /// + /// The identifier lacks the custom: prefix or contains /, \, ?, # or %. + /// Nothing is sent. + /// + /// + /// The server rejected the request. is + /// when no provider has this identifier; + /// is feature_disabled when custom providers are disabled on the project. + /// + /// + /// + /// var admin = new AdminClient(serviceRoleKey, new ClientOptions { Url = authUrl }); + /// await admin.DeleteCustomProviderAsync("custom:mycompany"); + /// + /// + Task DeleteCustomProviderAsync(string identifier, CancellationToken cancellationToken = default); } diff --git a/packages/Gotrue/Gotrue/Interfaces/IGotrueApi.cs b/packages/Gotrue/Gotrue/Interfaces/IGotrueApi.cs index b3b0fa8b9..7c07d0a79 100644 --- a/packages/Gotrue/Gotrue/Interfaces/IGotrueApi.cs +++ b/packages/Gotrue/Gotrue/Interfaces/IGotrueApi.cs @@ -59,6 +59,16 @@ public interface IGotrueApi : IGettableHeaders Task ListFactors(string jwt, MfaAdminListFactorsParams listFactorsParams); Task DeleteFactor(string jwt, MfaAdminDeleteFactorParams deleteFactorParams); + /// + /// Deletes a custom OAuth/OIDC provider. + /// + /// A full-access API key, such as the service_role key. + /// The provider identifier, starting with custom:. + /// Cancels the request. + /// The identifier lacks the custom: prefix or contains /, \, ?, # or %. + /// The server rejected the request. + Task DeleteCustomProviderAsync(string jwt, string identifier, CancellationToken cancellationToken = default); + /// /// Links an oauth identity to an existing user. /// diff --git a/packages/Gotrue/Gotrue/PublicAPI.Unshipped.txt b/packages/Gotrue/Gotrue/PublicAPI.Unshipped.txt index 7dc5c5811..74a550c8d 100644 --- a/packages/Gotrue/Gotrue/PublicAPI.Unshipped.txt +++ b/packages/Gotrue/Gotrue/PublicAPI.Unshipped.txt @@ -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.DeleteCustomProviderAsync(string! identifier, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +Supabase.Gotrue.Interfaces.IGotrueApi.DeleteCustomProviderAsync(string! jwt, string! identifier, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task!