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");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
#region

using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Supabase.Gotrue.UpdateCustomProvider;

#endregion

namespace Gotrue.Tests.UpdateCustomProvider;

/// <summary>
/// Changes to a custom provider: keeping a new client secret out of logs.
/// </summary>
[TestClass]
[TestCategory("Unit")]
public class CustomProviderChangesTests
{
[TestMethod]
public void ToString_ShouldLeaveOutClientSecret() =>
new CustomProviderChanges { Name = "Renamed", ClientId = "client-id", ClientSecret = "client-secret" }.ToString().Should().Be(
"CustomProviderChanges { Name = Renamed, ClientId = client-id, Issuer = , AuthorizationUrl = , TokenUrl = , UserInfoUrl = , Options = }",
"a record prints every property by default, and the secret must never reach a log");
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"name":"Renamed","client_id":"new-client-id","client_secret":"new-client-secret","acceptable_client_ids":["ios-client-id"],"scopes":["email"],"pkce_enabled":true,"attribute_mapping":{"name":"full_name"},"custom_claims_allowlist":["org_id"],"authorization_params":{"prompt":"login"},"enabled":false,"email_optional":false,"issuer":"https://accounts.mycompany.com","discovery_url":"https://accounts.mycompany.com/.well-known/openid-configuration","skip_nonce_check":false,"authorization_url":"https://provider.example.com/v2/authorize","token_url":"https://provider.example.com/v2/token","userinfo_url":"https://provider.example.com/v2/userinfo","jwks_uri":"https://provider.example.com/v2/jwks"}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"name":"Renamed"}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
#region

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Gotrue.Tests.Common;
using Gotrue.Tests.Support;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Supabase.Gotrue.Common;
using Supabase.Gotrue.UpdateCustomProvider;

#endregion

namespace Gotrue.Tests.UpdateCustomProvider;

/// <summary>
/// Pins the exact bytes an update puts on the wire: only the members set, and every member when all are set.
/// </summary>
[TestClass]
[TestCategory("Contract")]
public class UpdateCustomProviderApprovalTests : RequestApprovalFixture
{
[TestInitialize]
public void AnswerWithProvider() => this.RespondTo("/admin/custom-providers/custom:customauth", CustomProviderResponses.OAuth2);

[TestMethod]
public async Task UpdateCustomProviderRequest_ShouldSendOnlySetChanges_GivenNameOnly()
{
await this.Api.UpdateCustomProviderAsync("service-jwt", "custom:customauth", new CustomProviderChanges { Name = "Renamed" });
await this.Verify(this.EmittedRequestBody).UseDirectory("Data");
}

[TestMethod]
public async Task UpdateCustomProviderRequest_ShouldSendEveryChange_GivenEveryMember()
{
await this.Api.UpdateCustomProviderAsync("service-jwt", "custom:customauth", new CustomProviderChanges
{
Name = "Renamed",
ClientId = "new-client-id",
ClientSecret = "new-client-secret",
Issuer = new Uri("https://accounts.mycompany.com"),
AuthorizationUrl = new Uri("https://provider.example.com/v2/authorize"),
TokenUrl = new Uri("https://provider.example.com/v2/token"),
UserInfoUrl = new Uri("https://provider.example.com/v2/userinfo"),
Options = new CustomProviderOptions
{
AcceptableClientIds = new[] { "ios-client-id" },
Scopes = new[] { "email" },
PkceEnabled = true,
AttributeMapping = new Dictionary<string, object> { ["name"] = "full_name" },
CustomClaimsAllowlist = new[] { "org_id" },
AuthorizationParameters = new Dictionary<string, string> { ["prompt"] = "login" },
Enabled = false,
EmailOptional = false,
DiscoveryUrl = new Uri("https://accounts.mycompany.com/.well-known/openid-configuration"),
SkipNonceCheck = false,
JwksUri = new Uri("https://provider.example.com/v2/jwks"),
},
});
await this.Verify(this.EmittedRequestBody).UseDirectory("Data");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
#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 Supabase.Gotrue.UpdateCustomProvider;
using WireMock.Matchers;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;

#endregion

namespace Gotrue.Tests.UpdateCustomProvider;

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

private static readonly CustomProviderChanges Rename = new() { Name = "Renamed" };

private MockGotrueServer server = null!;

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

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

[TestMethod]
public async Task UpdateCustomProviderAsync_ShouldPutChangesByIdentifierWithServiceRoleCredentials()
{
this.AnswerWith(HttpStatusCode.OK, CustomProviderResponses.OAuth2);
await this.Admin.UpdateCustomProviderAsync("custom:customauth", Rename);
this.server.VerifySingleReceivedRequest()
.WithMethod(HttpMethod.Put)
.WithPath("/admin/custom-providers/custom:customauth")
.WithHeader("Authorization", $"Bearer {ServiceKey}")
.WithJsonContentType();
}

[TestMethod]
public async Task UpdateCustomProviderAsync_ShouldReturnUpdatedProvider()
{
this.AnswerWith(HttpStatusCode.OK, CustomProviderResponses.Oidc);
(await this.Admin.UpdateCustomProviderAsync("custom:mycompany", new CustomProviderChanges { Name = "My Company SSO" })).Should().BeEquivalentTo(new
{
Id = Guid.Parse("1f0c6b8e-3d1a-4c55-9a43-5f1a2b7c9d10"),
Type = CustomProviderType.Oidc,
Identifier = "custom:mycompany",
Name = "My Company SSO",
}, "the auth server answers 200 with the provider as stored after the update");
}

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

[TestMethod]
public async Task UpdateCustomProviderAsync_ShouldThrowArgumentNull_GivenNullChanges()
{
var update = () => this.Admin.UpdateCustomProviderAsync("custom:mycompany", null!);
await update.Should().ThrowExactlyAsync<ArgumentNullException>().WithParameterName("changes");
this.server.CountReceivedRequests().Should().Be(0, "argument misuse is rejected before any I/O");
}

[TestMethod]
public void UpdateCustomProviderAsync_ShouldComplete_GivenCallerBlockingOnContextThatNeverRunsContinuations()
{
this.AnswerWith(HttpStatusCode.OK, CustomProviderResponses.OAuth2);
BlockingCaller.Completes(() => this.Admin.UpdateCustomProviderAsync("custom:customauth", Rename)).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 UpdateCustomProviderAsync_ShouldNotSendRequest_GivenCancelledToken()
{
using var cancelled = new CancellationTokenSource();
cancelled.Cancel();
var update = () => this.Admin.UpdateCustomProviderAsync("custom:mycompany", Rename, cancelled.Token);
await update.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/*")).UsingPut())
.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,33 @@
#region

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

#endregion

namespace Gotrue.Tests.UpdateCustomProvider;

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

[TestMethod]
[DataRow("mycompany")]
[DataRow("custom:x/../../users/00000000-0000-0000-0000-000000000000")]
public async Task UpdateCustomProviderAsync_ShouldThrowArgument_GivenIdentifierItCannotRoute(string identifier)
{
var update = () => Admin.UpdateCustomProviderAsync(identifier, new CustomProviderChanges { Name = "Renamed" });
await update.Should().ThrowExactlyAsync<ArgumentException>()
.WithParameterName("identifier", "the identifier is a path segment checked like the delete's: 'custom:' prefix, no route-changing characters");
}
}
Loading