OIDC: tests for key-material faults, scope-limited claims, userinfo refusal, client re-seeding; redirect URI must be http(s)

A rooted path parses as an absolute file URI on Linux, so RedirectUri now also requires an http or https scheme. The authorize challenge no longer re-checks the resume path length: OpenIddict's request_uri keeps it short and a test pins that. The token endpoint no longer re-checks the grant type OpenIddict already restricts.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-10-22 18:40:11 +02:00
commit 06ca8209da
4 changed files with 193 additions and 18 deletions

View file

@ -36,13 +36,11 @@ public static class OidcEndpoints
if (http.User.Identity?.IsAuthenticated != true)
{
// OpenIddict has already replaced the request with a short request_uri; sign-in resumes at this URL.
var resume = http.Request.PathBase + http.Request.Path + http.Request.QueryString;
return LocalReturnPath.Parse(resume).Value == resume
? Results.Challenge(
new AuthenticationProperties { RedirectUri = resume },
[CookieAuthenticationDefaults.AuthenticationScheme])
: Deny(Errors.InvalidRequest, "The authorization request is too long to resume after sign-in.");
// OpenIddict has already replaced the request with a short request_uri, so this URL fits a sign-in
// return path (LocalReturnPath.MaxLength); a test pins that, because Parse would otherwise fall back to /App.
return Results.Challenge(
new AuthenticationProperties { RedirectUri = http.Request.PathBase + http.Request.Path + http.Request.QueryString },
[CookieAuthenticationDefaults.AuthenticationScheme]);
}
var actor = await actors.GetAsync(http.RequestAborted);
@ -79,13 +77,7 @@ public static class OidcEndpoints
private static async Task<IResult> ExchangeAsync(HttpContext http)
{
var request = http.GetOpenIddictServerRequest()
?? throw new InvalidOperationException("The OpenIddict request could not be retrieved.");
if (!request.IsAuthorizationCodeGrantType())
{
return Deny(Errors.UnsupportedGrantType, "Only the authorization code grant is supported.");
}
// Only the authorization code grant is enabled, so OpenIddict has refused every other grant already.
// The code's own principal carries the claims chosen at authorize time.
var result = await http.AuthenticateAsync(OpenIddictScheme);
return Results.SignIn(result.Principal!, properties: null, OpenIddictScheme);

View file

@ -40,9 +40,11 @@ public sealed class OidcKeyMaterial : IDisposable
Require(mas.ClientId, "Bifrost:Oidc:Clients:Mas:ClientId");
Require(mas.ClientSecretPath, "Bifrost:Oidc:Clients:Mas:ClientSecretPath");
Require(mas.RedirectUri, "Bifrost:Oidc:Clients:Mas:RedirectUri");
if (!Uri.TryCreate(mas.RedirectUri, UriKind.Absolute, out _))
// A rooted path such as "/callback" parses as an absolute file URI on Linux, so the scheme is checked too.
if (!Uri.TryCreate(mas.RedirectUri, UriKind.Absolute, out var redirect) ||
redirect.Scheme is not ("https" or "http"))
{
throw new OidcConfigurationException("Bifrost:Oidc:Clients:Mas:RedirectUri must be an absolute URI.");
throw new OidcConfigurationException("Bifrost:Oidc:Clients:Mas:RedirectUri must be an absolute http(s) URI.");
}
var ecdsa = LoadSigningKey(options.SigningKeyPath);

View file

@ -9,6 +9,7 @@ using Bifrost.Web.Features.Shared;
using Bifrost.Web.Tests.Support;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
@ -242,6 +243,81 @@ public sealed class OidcIssuerTests : IClassFixture<OidcWebApplicationFactory>
Assert.Equal("Original", account.BifrostIdentity);
}
[Fact]
public async Task The_openid_scope_alone_releases_the_subject_and_nothing_else()
{
var (client, identity) = await SignedInAsync(MembershipStatus.Active, "Scoped Down");
var request = NewRequest(scope: "openid");
var code = await CodeAsync(client, request);
var tokens = await ExchangeAsync(client, request, code);
var verified = await ValidateIdTokenAsync(tokens.IdToken, request.Nonce);
Assert.Equal(_factory.AccountId(identity).ToString("D"), verified.Claim("sub"));
Assert.Null(verified.Claim("preferred_username"));
Assert.Null(verified.Claim("name"));
using var userinfo = new HttpRequestMessage(HttpMethod.Get, "/connect/userinfo");
userinfo.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokens.AccessToken);
using var response = await NewClient().SendAsync(userinfo);
var info = (await response.Content.ReadFromJsonAsync<JsonElement>()).EnumerateObject().Select(x => x.Name).ToArray();
Assert.Equal(["sub"], info);
}
[Fact]
public async Task A_blank_display_name_falls_back_to_the_bifrost_identity()
{
var (client, identity) = await SignedInAsync(MembershipStatus.Active, " ");
var verified = await ValidateIdTokenAsync((await CompleteFlowAsync(client)).IdToken, null);
Assert.Equal(identity, verified.Claim("name"));
}
[Fact]
public async Task Userinfo_without_a_valid_token_is_refused()
{
using var client = NewClient();
using var none = await client.GetAsync("/connect/userinfo");
Assert.Equal(HttpStatusCode.Unauthorized, none.StatusCode);
using var forged = new HttpRequestMessage(HttpMethod.Get, "/connect/userinfo");
forged.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "not-a-token");
using var forgedResponse = await client.SendAsync(forged);
Assert.Equal(HttpStatusCode.Unauthorized, forgedResponse.StatusCode);
}
[Fact]
public async Task Startup_makes_the_one_client_match_configuration_again()
{
using var warm = NewClient();
await warm.GetAsync("/healthz");
using var scope = _factory.Services.CreateScope();
var manager = scope.ServiceProvider.GetRequiredService<OpenIddict.Abstractions.IOpenIddictApplicationManager>();
var application = await manager.FindByClientIdAsync(OidcTestKit.ClientId);
Assert.NotNull(application);
// Someone widened the client in the database; the next start puts configuration back.
var drifted = new OpenIddict.Abstractions.OpenIddictApplicationDescriptor
{
ClientId = OidcTestKit.ClientId,
ClientType = OpenIddict.Abstractions.OpenIddictConstants.ClientTypes.Confidential,
ClientSecret = "drifted-secret",
RedirectUris = { new Uri("https://evil.example.test/callback") }
};
await manager.UpdateAsync(application, drifted);
foreach (var seeder in _factory.Services.GetServices<IHostedService>().OfType<Bifrost.Web.Features.Oidc.OidcClientSeeder>())
{
await seeder.StartAsync(CancellationToken.None);
}
Assert.Equal(1, await manager.CountAsync());
var restored = (await manager.FindByClientIdAsync(OidcTestKit.ClientId))!;
Assert.Equal([OidcTestKit.RedirectUri], (await manager.GetRedirectUrisAsync(restored)).ToArray());
Assert.True(await manager.ValidateClientSecretAsync(restored, _factory.Kit.ClientSecret));
Assert.False(await manager.ValidateClientSecretAsync(restored, "drifted-secret"));
}
// ---- helpers ----
private static WebApplicationFactoryClientOptions ClientOptions() => new()
@ -288,7 +364,8 @@ public sealed class OidcIssuerTests : IClassFixture<OidcWebApplicationFactory>
string clientId = OidcTestKit.ClientId,
string redirectUri = OidcTestKit.RedirectUri,
bool pkce = true,
string extra = "")
string extra = "",
string scope = "openid%20profile")
{
var verifier = Base64UrlEncoder.Encode(RandomNumberGenerator.GetBytes(48));
var state = Base64UrlEncoder.Encode(RandomNumberGenerator.GetBytes(24));
@ -297,7 +374,7 @@ public sealed class OidcIssuerTests : IClassFixture<OidcWebApplicationFactory>
var path = "/connect/authorize?response_type=code" +
$"&client_id={Uri.EscapeDataString(clientId)}" +
$"&redirect_uri={Uri.EscapeDataString(redirectUri)}" +
"&scope=openid%20profile" +
$"&scope={scope}" +
$"&state={state}&nonce={nonce}" +
(pkce ? $"&code_challenge={challenge}&code_challenge_method=S256" : string.Empty) +
extra;

View file

@ -0,0 +1,104 @@
using System.Security.Cryptography;
using Bifrost.Web.Configuration;
using Bifrost.Web.Features.Oidc;
using Bifrost.Web.Tests.Support;
using Microsoft.IdentityModel.Tokens;
namespace Bifrost.Web.Tests;
public sealed class OidcKeyMaterialTests : IDisposable
{
private readonly OidcTestKit _kit = new();
public void Dispose() => _kit.Dispose();
[Fact]
public void A_complete_configuration_loads_the_signing_key_the_secret_and_the_encryption_key()
{
using var material = OidcKeyMaterial.Load(Options());
var signing = Assert.IsType<ECDsaSecurityKey>(material.SigningKey);
Assert.False(string.IsNullOrEmpty(signing.KeyId));
Assert.Equal(_kit.ClientSecret, material.ClientSecret);
Assert.Equal(32, Assert.IsType<SymmetricSecurityKey>(material.EncryptionKey).Key.Length);
}
[Theory]
[InlineData("SigningKeyPath", "Bifrost:Oidc:SigningKeyPath")]
[InlineData("EncryptionKeyPath", "Bifrost:Oidc:EncryptionKeyPath")]
[InlineData("ClientId", "Bifrost:Oidc:Clients:Mas:ClientId")]
[InlineData("ClientSecretPath", "Bifrost:Oidc:Clients:Mas:ClientSecretPath")]
[InlineData("RedirectUri", "Bifrost:Oidc:Clients:Mas:RedirectUri")]
public void A_missing_setting_stops_startup_naming_that_setting(string blank, string expectedField)
{
var failure = Assert.Throws<OidcConfigurationException>(() => OidcKeyMaterial.Load(Options(blank: blank)));
Assert.Contains(expectedField, failure.Message, StringComparison.Ordinal);
}
[Fact]
public void A_redirect_uri_that_is_not_absolute_stops_startup()
{
var failure = Assert.Throws<OidcConfigurationException>(() => OidcKeyMaterial.Load(Options(redirectUri: "/callback")));
Assert.Contains("Bifrost:Oidc:Clients:Mas:RedirectUri", failure.Message, StringComparison.Ordinal);
}
[Theory]
[InlineData("missing")]
[InlineData("not base64 !!")]
[InlineData("AAAAAAAAAAAAAAAAAAAAAA==")]
public void An_unusable_encryption_key_stops_startup_naming_the_setting_not_the_path(string content)
{
if (content == "missing")
{
File.Delete(_kit.EncryptionKeyPath);
}
else
{
File.WriteAllText(_kit.EncryptionKeyPath, content);
}
var failure = Assert.Throws<OidcConfigurationException>(() => OidcKeyMaterial.Load(Options()));
Assert.Contains("Bifrost:Oidc:EncryptionKeyPath", failure.Message, StringComparison.Ordinal);
Assert.DoesNotContain("canary-", failure.Message, StringComparison.Ordinal);
}
[Fact]
public void A_missing_client_secret_file_stops_startup_naming_the_setting_not_the_path()
{
File.Delete(_kit.ClientSecretPath);
var failure = Assert.Throws<OidcConfigurationException>(() => OidcKeyMaterial.Load(Options()));
Assert.Contains("Bifrost:Oidc:Clients:Mas:ClientSecretPath", failure.Message, StringComparison.Ordinal);
Assert.DoesNotContain("canary-", failure.Message, StringComparison.Ordinal);
}
[Fact]
public void A_P384_key_is_not_a_P256_key()
{
using var p384 = ECDsa.Create(ECCurve.NamedCurves.nistP384);
File.WriteAllText(_kit.SigningKeyPath, p384.ExportPkcs8PrivateKeyPem());
var failure = Assert.Throws<OidcConfigurationException>(() => OidcKeyMaterial.Load(Options()));
Assert.Contains("Bifrost:Oidc:SigningKeyPath", failure.Message, StringComparison.Ordinal);
}
private OidcIssuerOptions Options(string? blank = null, string? redirectUri = null) => new()
{
SigningKeyPath = blank == "SigningKeyPath" ? "" : _kit.SigningKeyPath,
EncryptionKeyPath = blank == "EncryptionKeyPath" ? "" : _kit.EncryptionKeyPath,
Clients = new OidcClientsOptions
{
Mas = new OidcClientOptions
{
ClientId = blank == "ClientId" ? "" : OidcTestKit.ClientId,
ClientSecretPath = blank == "ClientSecretPath" ? "" : _kit.ClientSecretPath,
RedirectUri = blank == "RedirectUri" ? "" : redirectUri ?? OidcTestKit.RedirectUri
}
}
};
}