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

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

#endregion

namespace Gotrue.Tests.GetCustomProvider;

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

private MockGotrueServer server = null!;

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

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

[TestMethod]
[DataRow("custom:mycompany")]
[DataRow("custom:my.company")]
public async Task GetCustomProviderAsync_ShouldFetchProviderByIdentifierWithServiceRoleCredentials(string identifier)
{
this.AnswerWith(HttpStatusCode.OK, CustomProviderResponses.Oidc);
await this.Admin.GetCustomProviderAsync(identifier);
this.server.VerifySingleReceivedRequest()
.WithMethod(HttpMethod.Get)
.WithPath($"/admin/custom-providers/{identifier}")
.WithHeader("Authorization", $"Bearer {ServiceKey}");
}

[TestMethod]
public async Task GetCustomProviderAsync_ShouldReturnProvider()
{
this.AnswerWith(HttpStatusCode.OK, CustomProviderResponses.OAuth2);
(await this.Admin.GetCustomProviderAsync("custom:customauth")).Should().BeEquivalentTo(new
{
Id = Guid.Parse("6ea7e0b6-ee41-4791-802c-ea0625ee8d6b"),
Type = CustomProviderType.OAuth2,
Identifier = "custom:customauth",
AuthorizationUrl = new Uri("https://provider.example.com/oauth/authorize"),
}, "the auth server answers 200 with the stored provider, as in its CustomOAuthProviderSchema");
}

[TestMethod]
public async Task GetCustomProviderAsync_ShouldThrowCustomProviderNotFound_GivenUnknownIdentifier()
{
this.AnswerWith(HttpStatusCode.NotFound, """{"code":404,"error_code":"custom_provider_not_found","msg":"Custom OAuth provider not found"}""");
var get = () => this.Admin.GetCustomProviderAsync("custom:unknown");
await get.Should().ThrowExactlyAsync<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 GetCustomProviderAsync_ShouldThrowGotrueException_GivenNullResponseBody()
{
this.AnswerWith(HttpStatusCode.OK, "null");
var get = () => this.Admin.GetCustomProviderAsync("custom:mycompany");
await get.Should().ThrowExactlyAsync<GotrueException>().WithMessage("*returned no custom provider*",
"a 200 always carries the provider; anything else is a broken response, not a provider");
}

[TestMethod]
public void GetCustomProviderAsync_ShouldComplete_GivenCallerBlockingOnContextThatNeverRunsContinuations()
{
this.AnswerWith(HttpStatusCode.OK, CustomProviderResponses.OAuth2);
BlockingCaller.Completes(() => this.Admin.GetCustomProviderAsync("custom:customauth")).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 GetCustomProviderAsync_ShouldNotSendRequest_GivenCancelledToken()
{
using var cancelled = new CancellationTokenSource();
cancelled.Cancel();
var get = () => this.Admin.GetCustomProviderAsync("custom:mycompany", cancelled.Token);
await get.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(HttpStatusCode status, string body) =>
this.server.Given(Request.Create().WithPath(new WildcardMatcher("/admin/custom-providers/*")).UsingGet())
.RespondWith(Response.Create().WithStatusCode(status)
.WithHeader("Content-Type", "application/json").WithBody(body));
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
#region

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

#endregion

namespace Gotrue.Tests.GetCustomProvider;

/// <summary>
/// The identifier checks made before a lookup 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 GetCustomProviderIdentifierTests
{
private static readonly AdminClient Admin = new("service-role-jwt", new ClientOptions { Url = "http://localhost" });

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

[TestMethod]
[DataRow("mycompany")]
[DataRow("custom:x/../../users/00000000-0000-0000-0000-000000000000")]
public async Task GetCustomProviderAsync_ShouldThrowArgument_GivenIdentifierItCannotRoute(string identifier)
{
var get = () => Admin.GetCustomProviderAsync(identifier);
await get.Should().ThrowExactlyAsync<ArgumentException>()
.WithParameterName("identifier", "the identifier is a path segment checked like the delete's: 'custom:' prefix, no route-changing characters");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
#region

using System;
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.GetCustomProvider;

/// <summary>
/// End-to-end lookup of a custom OAuth/OIDC provider by its identifier against the live stack.
/// </summary>
[TestClass]
[TestCategory("E2E")]
public class GetCustomProviderTests : CustomProviderAdminFixture
{
[TestMethod]
public async Task GetCustomProviderAsync_ShouldReturnProvider()
{
await this.SeedProvider();
(await this.Admin.GetCustomProviderAsync(this.Identifier)).Should().BeEquivalentTo(new
{
Type = CustomProviderType.OAuth2,
Identifier = this.Identifier,
Name = "E2E provider",
ClientId = "client-id",
AuthorizationUrl = new Uri("https://example.com/authorize"),
TokenUrl = new Uri("https://example.com/token"),
UserInfoUrl = new Uri("https://example.com/userinfo"),
}, "the provider is returned as it was registered");
}

[TestMethod]
public async Task GetCustomProviderAsync_ShouldThrowCustomProviderNotFound_GivenUnknownIdentifier()
{
var get = () => this.Admin.GetCustomProviderAsync(this.Identifier);
await get.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 GetCustomProviderAsync_ShouldThrowAdminTokenRequired_GivenNonAdminKey()
{
await this.SeedProvider();
var get = () => TestClients.AdminAgainstCliStack(TestClients.CliAnonKey).GetCustomProviderAsync(this.Identifier);
await get.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 @@ -165,6 +165,11 @@ public Task<CustomProvider> CreateCustomProviderAsync(NewCustomProvider provider
public Task<CustomProvider> UpdateCustomProviderAsync(string identifier, CustomProviderChanges changes, CancellationToken cancellationToken = default) =>
this.api.UpdateCustomProviderAsync(this.serviceKey, identifier, changes, cancellationToken);

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

/// <inheritdoc />
public async Task<User?> Update(UserAttributes attributes)
{
Expand Down
7 changes: 7 additions & 0 deletions packages/Gotrue/Gotrue/Api.cs
Original file line number Diff line number Diff line change
Expand Up @@ -661,6 +661,13 @@ public async Task<CustomProvider> UpdateCustomProviderAsync(string jwt, string i
return CustomProviderResponse.Read(updated);
}

/// <inheritdoc />
public async Task<CustomProvider> GetCustomProviderAsync(string jwt, string identifier, CancellationToken cancellationToken = default)
{
var provider = await this.MakeRequestAsync<CustomProviderResponse>(HttpMethod.Get, this.CustomProviderUrl(identifier), null, this.CreateAuthedRequestHeaders(jwt), cancellationToken).ConfigureAwait(false);
return CustomProviderResponse.Read(provider);
}

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

Expand Down
25 changes: 25 additions & 0 deletions packages/Gotrue/Gotrue/Interfaces/IGotrueAdminClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -232,4 +232,29 @@ public interface IGotrueAdminClient<TUser> : IGettableHeaders
/// </code>
/// </example>
Task<CustomProvider> UpdateCustomProviderAsync(string identifier, CustomProviderChanges changes, CancellationToken cancellationToken = default);

/// <summary>
/// Fetches a custom OAuth/OIDC provider by its identifier. 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>
/// <returns>The provider. Its client secret is never returned.</returns>
/// <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 and
/// <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>
/// var admin = new AdminClient(serviceRoleKey, new ClientOptions { Url = authUrl });
/// var provider = await admin.GetCustomProviderAsync("custom:mycompany");
/// </code>
/// </example>
Task<CustomProvider> GetCustomProviderAsync(string identifier, 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
Expand Up @@ -106,6 +106,17 @@ public interface IGotrueApi<TUser, TSession> : IGettableHeaders
/// <exception cref="Exceptions.GotrueException">The server rejected the request.</exception>
Task<CustomProvider> UpdateCustomProviderAsync(string jwt, string identifier, CustomProviderChanges changes, CancellationToken cancellationToken = default);

/// <summary>
/// Fetches a custom OAuth/OIDC provider by its identifier.
/// </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>
/// <returns>The provider.</returns>
/// <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<CustomProvider> GetCustomProviderAsync(string jwt, string identifier, CancellationToken cancellationToken = default);

/// <summary>
/// Links an oauth identity to an existing user.
///
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 @@ -27,8 +27,10 @@ static Supabase.Gotrue.CreateCustomProvider.NewCustomProvider.operator ==(Supaba
static Supabase.Gotrue.UpdateCustomProvider.CustomProviderChanges.operator !=(Supabase.Gotrue.UpdateCustomProvider.CustomProviderChanges? left, Supabase.Gotrue.UpdateCustomProvider.CustomProviderChanges? right) -> bool
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.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.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 @@ -144,11 +146,13 @@ Supabase.Gotrue.CreateCustomProvider.NewCustomProvider.TokenUrl.get -> System.Ur
Supabase.Gotrue.CreateCustomProvider.NewCustomProvider.Type.get -> Supabase.Gotrue.Common.CustomProviderType
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>.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>.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