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

using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using Gotrue.Tests.Common;
using Gotrue.Tests.Support;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Supabase.Gotrue;
using Supabase.Gotrue.Common;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;

#endregion

namespace Gotrue.Tests.ListCustomProviders;

/// <summary>
/// Pins the wire contract of listing custom OAuth/OIDC providers against a stubbed auth server: the route, the
/// service-role credentials, the type filter, the response mapping, and cancellation.
/// </summary>
[TestClass]
[TestCategory("Contract")]
public class ListCustomProvidersContractTests
{
private const string ServiceKey = "service-role-jwt";
private const string NoProviders = """{"providers":[]}""";

private MockGotrueServer server = null!;

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

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

[TestMethod]
public async Task ListCustomProvidersAsync_ShouldListEveryProviderWithServiceRoleCredentials_GivenNoType()
{
this.AnswerWith(NoProviders);
await this.Admin.ListCustomProvidersAsync();
this.server.VerifySingleReceivedRequest()
.WithMethod(HttpMethod.Get)
.WithPath("/admin/custom-providers")
.WithHeader("Authorization", $"Bearer {ServiceKey}")
.WithoutQueryParam("type");
}

[TestMethod]
[DataRow(CustomProviderType.OAuth2, "oauth2")]
[DataRow(CustomProviderType.Oidc, "oidc")]
public async Task ListCustomProvidersAsync_ShouldFilterByType_GivenType(CustomProviderType type, string wireType)
{
this.AnswerWith(NoProviders);
await this.Admin.ListCustomProvidersAsync(type);
this.server.VerifySingleReceivedRequest().WithQueryParam("type", wireType);
}

[TestMethod]
public async Task ListCustomProvidersAsync_ShouldReturnEveryListedProvider()
{
this.AnswerWith($$"""{"providers":[{{CustomProviderResponses.OAuth2}},{{CustomProviderResponses.Oidc}}]}""");
(await this.Admin.ListCustomProvidersAsync()).Select(provider => (provider.Identifier, provider.Type)).Should().Equal(
new[] { ("custom:customauth", CustomProviderType.OAuth2), ("custom:mycompany", CustomProviderType.Oidc) },
"the auth server answers 200 with every stored provider under providers");
}

[TestMethod]
[DataRow("""{"providers":null}""")]
[DataRow("""{}""")]
[DataRow("null")]
public async Task ListCustomProvidersAsync_ShouldReturnEmptyList_GivenNoProvidersInResponse(string body)
{
this.AnswerWith(body);
(await this.Admin.ListCustomProvidersAsync()).Should().BeEmpty("the returned list is never null, whatever the server sends");
}

[TestMethod]
public void ListCustomProvidersAsync_ShouldComplete_GivenCallerBlockingOnContextThatNeverRunsContinuations()
{
this.AnswerWith(NoProviders);
BlockingCaller.Completes(() => this.Admin.ListCustomProvidersAsync()).Should().BeTrue(
"a library must not resume on the caller's context: a UI thread blocking on the task would deadlock");
}

[TestMethod]
public async Task ListCustomProvidersAsync_ShouldNotSendRequest_GivenCancelledToken()
{
using var cancelled = new CancellationTokenSource();
cancelled.Cancel();
var list = () => this.Admin.ListCustomProvidersAsync(cancellationToken: cancelled.Token);
await list.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 });

private void AnswerWith(string body) =>
this.server.Given(Request.Create().WithPath("/admin/custom-providers").UsingGet())
.RespondWith(Response.Create().WithStatusCode(HttpStatusCode.OK)
.WithHeader("Content-Type", "application/json").WithBody(body));
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#region

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

#endregion

namespace Gotrue.Tests.ListCustomProviders;

/// <summary>
/// End-to-end listing of custom OAuth/OIDC providers against the live stack, with and without a type filter.
/// </summary>
[TestClass]
[TestCategory("E2E")]
public class ListCustomProvidersTests : CustomProviderAdminFixture
{
[TestMethod]
[DataRow(null, true)]
[DataRow(CustomProviderType.OAuth2, true)]
[DataRow(CustomProviderType.Oidc, false)]
public async Task ListCustomProvidersAsync_ShouldListSeededOAuth2ProviderOnlyWhenTypeMatches(CustomProviderType? type, bool listed)
{
await this.SeedProvider();
(await this.Admin.ListCustomProvidersAsync(type)).Any(provider => provider.Identifier == this.Identifier).Should().Be(listed,
"the auth server filters the list by provider_type when type is given and returns every provider otherwise");
}

[TestMethod]
public async Task ListCustomProvidersAsync_ShouldThrowAdminTokenRequired_GivenNonAdminKey()
{
var list = () => TestClients.AdminAgainstCliStack(TestClients.CliAnonKey).ListCustomProvidersAsync();
await list.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");
}
}
5 changes: 5 additions & 0 deletions packages/Gotrue/Gotrue/AdminClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,11 @@ public Task<CustomProvider> UpdateCustomProviderAsync(string identifier, CustomP
public Task<CustomProvider> GetCustomProviderAsync(string identifier, CancellationToken cancellationToken = default) =>
this.api.GetCustomProviderAsync(this.serviceKey, identifier, cancellationToken);

/// <inheritdoc />
[ImplementedCapability("auth.admin.list_providers")]
public Task<IReadOnlyList<CustomProvider>> ListCustomProvidersAsync(CustomProviderType? type = null, CancellationToken cancellationToken = default) =>
this.api.ListCustomProvidersAsync(this.serviceKey, type, cancellationToken);

/// <inheritdoc />
public async Task<User?> Update(UserAttributes attributes)
{
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 @@ -14,6 +14,7 @@
using Supabase.Gotrue.CustomProviders;
using Supabase.Gotrue.Exceptions;
using Supabase.Gotrue.Interfaces;
using Supabase.Gotrue.ListCustomProviders;
using Supabase.Gotrue.Mfa;
using Supabase.Gotrue.Resend;
using Supabase.Gotrue.Responses;
Expand Down Expand Up @@ -668,6 +669,13 @@ public async Task<CustomProvider> GetCustomProviderAsync(string jwt, string iden
return CustomProviderResponse.Read(provider);
}

/// <inheritdoc />
public async Task<IReadOnlyList<CustomProvider>> ListCustomProvidersAsync(string jwt, CustomProviderType? type = null, CancellationToken cancellationToken = default)
{
var listed = await this.MakeRequestAsync<CustomProviderListResponse>(HttpMethod.Get, $"{this.Url}/admin/custom-providers", ListCustomProvidersQuery.For(type), this.CreateAuthedRequestHeaders(jwt), cancellationToken).ConfigureAwait(false);
return CustomProviderListResponse.Read(listed);
}

private string CustomProviderUrl(string identifier) =>
$"{this.Url}/admin/custom-providers/{CustomProviderIdentifier.EnsureRoutable(identifier)}";

Expand Down
23 changes: 23 additions & 0 deletions packages/Gotrue/Gotrue/Interfaces/IGotrueAdminClient.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Supabase.Core.Interfaces;
Expand Down Expand Up @@ -257,4 +258,26 @@ public interface IGotrueAdminClient<TUser> : IGettableHeaders
/// </code>
/// </example>
Task<CustomProvider> GetCustomProviderAsync(string identifier, CancellationToken cancellationToken = default);

/// <summary>
/// Lists the custom OAuth/OIDC providers registered on the project, optionally only those of one type.
/// 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="type">Only providers of this type; every provider when null.</param>
/// <param name="cancellationToken">Cancels the request.</param>
/// <returns>The providers, empty when none is registered. Their client secrets are never returned.</returns>
/// <exception cref="Exceptions.GotrueException">
/// The server rejected the request. <see cref="Exceptions.GotrueException.Reason" /> is
/// <see cref="Exceptions.FailureHint.Reason.AdminTokenRequired" /> when the key is not a full-access key;
/// <see cref="Exceptions.GotrueException.ErrorCode" /> is <c>feature_disabled</c> when custom providers are disabled on the project.
/// </exception>
/// <example>
/// <code>
/// using Supabase.Gotrue.Common;
///
/// var admin = new AdminClient(serviceRoleKey, new ClientOptions { Url = authUrl });
/// var oidcProviders = await admin.ListCustomProvidersAsync(CustomProviderType.Oidc);
/// </code>
/// </example>
Task<IReadOnlyList<CustomProvider>> ListCustomProvidersAsync(CustomProviderType? type = null, CancellationToken cancellationToken = default);
}
11 changes: 11 additions & 0 deletions packages/Gotrue/Gotrue/Interfaces/IGotrueApi.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Supabase.Core.Interfaces;
Expand Down Expand Up @@ -117,6 +118,16 @@ public interface IGotrueApi<TUser, TSession> : IGettableHeaders
/// <exception cref="Exceptions.GotrueException">The server rejected the request.</exception>
Task<CustomProvider> GetCustomProviderAsync(string jwt, string identifier, CancellationToken cancellationToken = default);

/// <summary>
/// Lists the custom OAuth/OIDC providers, optionally only those of one type.
/// </summary>
/// <param name="jwt">A full-access API key, such as the service_role key.</param>
/// <param name="type">Only providers of this type; every provider when null.</param>
/// <param name="cancellationToken">Cancels the request.</param>
/// <returns>The providers.</returns>
/// <exception cref="Exceptions.GotrueException">The server rejected the request.</exception>
Task<IReadOnlyList<CustomProvider>> ListCustomProvidersAsync(string jwt, CustomProviderType? type = null, CancellationToken cancellationToken = default);

/// <summary>
/// Links an oauth identity to an existing user.
///
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json.Serialization;
using Supabase.Gotrue.Common;

namespace Supabase.Gotrue.ListCustomProviders;

internal sealed record CustomProviderListResponse
{
[JsonPropertyName("providers")]
public IReadOnlyList<CustomProviderResponse>? Providers { get; init; }

internal static IReadOnlyList<CustomProvider> Read(CustomProviderListResponse? response) =>
(response?.Providers ?? Array.Empty<CustomProviderResponse>()).Select(provider => provider.ToCustomProvider()).ToList();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
using System.Collections.Generic;
using Supabase.Gotrue.Common;

namespace Supabase.Gotrue.ListCustomProviders;

internal static class ListCustomProvidersQuery
{
internal static Dictionary<string, string>? For(CustomProviderType? type) =>
type is { } filter ? new Dictionary<string, string> { ["type"] = Core.Helpers.GetMappedToAttr(filter).Mapping } : null;
}
4 changes: 4 additions & 0 deletions packages/Gotrue/Gotrue/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,11 @@ static Supabase.Gotrue.UpdateCustomProvider.CustomProviderChanges.operator !=(Su
static Supabase.Gotrue.UpdateCustomProvider.CustomProviderChanges.operator ==(Supabase.Gotrue.UpdateCustomProvider.CustomProviderChanges? left, Supabase.Gotrue.UpdateCustomProvider.CustomProviderChanges? right) -> bool
Supabase.Gotrue.AdminClient.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.AdminClient.GetCustomProviderAsync(string! identifier, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Supabase.Gotrue.Common.CustomProvider!>!
Supabase.Gotrue.AdminClient.ListCustomProvidersAsync(Supabase.Gotrue.Common.CustomProviderType? type = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IReadOnlyList<Supabase.Gotrue.Common.CustomProvider!>!>!
Supabase.Gotrue.AdminClient.UpdateCustomProviderAsync(string! identifier, Supabase.Gotrue.UpdateCustomProvider.CustomProviderChanges! changes, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Supabase.Gotrue.Common.CustomProvider!>!
Supabase.Gotrue.Api.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.Api.GetCustomProviderAsync(string! jwt, string! identifier, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Supabase.Gotrue.Common.CustomProvider!>!
Supabase.Gotrue.Api.ListCustomProvidersAsync(string! jwt, Supabase.Gotrue.Common.CustomProviderType? type = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IReadOnlyList<Supabase.Gotrue.Common.CustomProvider!>!>!
Supabase.Gotrue.Api.UpdateCustomProviderAsync(string! jwt, string! identifier, Supabase.Gotrue.UpdateCustomProvider.CustomProviderChanges! changes, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Supabase.Gotrue.Common.CustomProvider!>!
Supabase.Gotrue.Common.CustomProvider
Supabase.Gotrue.Common.CustomProvider.<Clone>$() -> Supabase.Gotrue.Common.CustomProvider!
Expand Down Expand Up @@ -147,12 +149,14 @@ 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.IGotrueAdminClient<TUser>.GetCustomProviderAsync(string! identifier, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Supabase.Gotrue.Common.CustomProvider!>!
Supabase.Gotrue.Interfaces.IGotrueAdminClient<TUser>.ListCustomProvidersAsync(Supabase.Gotrue.Common.CustomProviderType? type = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IReadOnlyList<Supabase.Gotrue.Common.CustomProvider!>!>!
Supabase.Gotrue.Interfaces.IGotrueAdminClient<TUser>.UpdateCustomProviderAsync(string! identifier, Supabase.Gotrue.UpdateCustomProvider.CustomProviderChanges! changes, 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>.GetCustomProviderAsync(string! jwt, string! identifier, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Supabase.Gotrue.Common.CustomProvider!>!
Supabase.Gotrue.Interfaces.IGotrueApi<TUser, TSession>.ListCustomProvidersAsync(string! jwt, Supabase.Gotrue.Common.CustomProviderType? type = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Generic.IReadOnlyList<Supabase.Gotrue.Common.CustomProvider!>!>!
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!
Supabase.Gotrue.Interfaces.IGotrueApi<TUser, TSession>.UpdateCustomProviderAsync(string! jwt, string! identifier, Supabase.Gotrue.UpdateCustomProvider.CustomProviderChanges! changes, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Supabase.Gotrue.Common.CustomProvider!>!
Supabase.Gotrue.UpdateCustomProvider.CustomProviderChanges
Expand Down
Loading