From b4dcd1de8938f80b120c3791030cc0d7d333e812 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 22 Oct 2026 18:35:34 +0200 Subject: [PATCH] OIDC issuer: provider endpoints, authorize gate (Active members, identity required), one MAS client, tests Authorize reads the cookie session and the same actor facts the /App policy reads; sub = UserAccount.Id, preferred_username = NormalizedBifrostIdentity. OpenIddict request caching parks the authorize request as a short request_uri. Mapped only when Bifrost:Oidc is present. Co-Authored-By: Claude Sonnet 5.5 --- .../Features/Oidc/OidcClientSeeder.cs | 60 +++ .../Features/Oidc/OidcEndpoints.cs | 120 +++++ .../Oidc/OidcServiceCollectionExtensions.cs | 73 +++ src/Bifrost.Web/Program.cs | 13 + tests/Bifrost.Web.Tests/OidcIssuerTests.cs | 486 ++++++++++++++++++ .../Bifrost.Web.Tests/Support/OidcTestKit.cs | 218 ++++++++ 6 files changed, 970 insertions(+) create mode 100644 src/Bifrost.Web/Features/Oidc/OidcClientSeeder.cs create mode 100644 src/Bifrost.Web/Features/Oidc/OidcEndpoints.cs create mode 100644 src/Bifrost.Web/Features/Oidc/OidcServiceCollectionExtensions.cs create mode 100644 tests/Bifrost.Web.Tests/OidcIssuerTests.cs create mode 100644 tests/Bifrost.Web.Tests/Support/OidcTestKit.cs diff --git a/src/Bifrost.Web/Features/Oidc/OidcClientSeeder.cs b/src/Bifrost.Web/Features/Oidc/OidcClientSeeder.cs new file mode 100644 index 0000000..344a049 --- /dev/null +++ b/src/Bifrost.Web/Features/Oidc/OidcClientSeeder.cs @@ -0,0 +1,60 @@ +using Bifrost.Web.Configuration; +using Microsoft.Extensions.Options; +using OpenIddict.Abstractions; +using OpenIddict.Server; +using static OpenIddict.Abstractions.OpenIddictConstants; + +namespace Bifrost.Web.Features.Oidc; + +/// +/// Makes the provider's one client match configuration at startup, creating it or updating it in place. +/// Nothing else registers clients: any other client_id is refused by OpenIddict. +/// +public sealed class OidcClientSeeder( + IServiceScopeFactory scopeFactory, + OidcIssuerOptions options, + OidcKeyMaterial material, + IOptions serverOptions) : IHostedService +{ + public async Task StartAsync(CancellationToken cancellationToken) + { + // Reading the server options now runs their configuration, so a bad issuer stops startup rather than the first request. + _ = serverOptions.Value; + + await using var scope = scopeFactory.CreateAsyncScope(); + var manager = scope.ServiceProvider.GetRequiredService(); + var mas = options.Clients.Mas; + + var descriptor = new OpenIddictApplicationDescriptor + { + ClientId = mas.ClientId, + ClientSecret = material.ClientSecret, + ClientType = ClientTypes.Confidential, + ConsentType = ConsentTypes.Implicit, + DisplayName = "Matrix Authentication Service", + RedirectUris = { new Uri(mas.RedirectUri, UriKind.Absolute) }, + Permissions = + { + Permissions.Endpoints.Authorization, + Permissions.Endpoints.Token, + Permissions.GrantTypes.AuthorizationCode, + Permissions.ResponseTypes.Code, + Permissions.Scopes.Profile, + Permissions.Prefixes.Scope + Scopes.OpenId + }, + Requirements = { Requirements.Features.ProofKeyForCodeExchange } + }; + + var existing = await manager.FindByClientIdAsync(mas.ClientId, cancellationToken); + if (existing is null) + { + await manager.CreateAsync(descriptor, cancellationToken); + } + else + { + await manager.UpdateAsync(existing, descriptor, cancellationToken); + } + } + + public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; +} diff --git a/src/Bifrost.Web/Features/Oidc/OidcEndpoints.cs b/src/Bifrost.Web/Features/Oidc/OidcEndpoints.cs new file mode 100644 index 0000000..c7a00f3 --- /dev/null +++ b/src/Bifrost.Web/Features/Oidc/OidcEndpoints.cs @@ -0,0 +1,120 @@ +using System.Security.Claims; +using Microsoft.AspNetCore; +using Bifrost.Web.Features.Shared; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.Cookies; +using OpenIddict.Abstractions; +using OpenIddict.Server.AspNetCore; +using static OpenIddict.Abstractions.OpenIddictConstants; + +namespace Bifrost.Web.Features.Oidc; + +/// +/// The decisions Bifrost owns at the OIDC provider: who the chat user is (sub = UserAccount.Id, +/// preferred_username = NormalizedBifrostIdentity) and whether they may get a session (membership Active). +/// OpenIddict does the protocol; these endpoints read the cookie session and the same actor facts the /App policy reads. +/// +public static class OidcEndpoints +{ + public const string NotActiveDescription = "The account is not an active GameCult member."; + public const string NoIdentityDescription = "The account has no Bifrost identity."; + + private const string OpenIddictScheme = OpenIddictServerAspNetCoreDefaults.AuthenticationScheme; + private const string IdentityAuthenticationType = "Bifrost.Oidc"; + + public static void MapBifrostOidc(this IEndpointRouteBuilder app) + { + app.MapMethods(OidcServiceCollectionExtensions.AuthorizationPath, ["GET", "POST"], (Delegate)AuthorizeAsync).AllowAnonymous(); + app.MapPost(OidcServiceCollectionExtensions.TokenPath, (Delegate)ExchangeAsync).AllowAnonymous(); + app.MapMethods(OidcServiceCollectionExtensions.UserInfoPath, ["GET", "POST"], (Delegate)UserInfoAsync).AllowAnonymous(); + } + + private static async Task AuthorizeAsync(HttpContext http, ICurrentBifrostActorAccessor actors) + { + var request = http.GetOpenIddictServerRequest() + ?? throw new InvalidOperationException("The OpenIddict request could not be retrieved."); + + 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."); + } + + var actor = await actors.GetAsync(http.RequestAborted); + if (actor.UserAccount is null || !actor.IsActiveMember) + { + return Deny(Errors.AccessDenied, NotActiveDescription); + } + + var account = actor.UserAccount; + if (string.IsNullOrWhiteSpace(account.NormalizedBifrostIdentity)) + { + return Deny(Errors.AccessDenied, NoIdentityDescription); + } + + var identity = new ClaimsIdentity(IdentityAuthenticationType, Claims.Name, Claims.Role); + identity.SetClaim(Claims.Subject, account.Id.ToString("D")); + identity.SetClaim(Claims.PreferredUsername, account.NormalizedBifrostIdentity); + identity.SetClaim( + Claims.Name, + string.IsNullOrWhiteSpace(account.DisplayName) ? account.BifrostIdentity : account.DisplayName); + + var principal = new ClaimsPrincipal(identity); + principal.SetScopes(request.GetScopes()); + principal.SetDestinations(claim => claim.Type switch + { + Claims.Subject => [Destinations.AccessToken, Destinations.IdentityToken], + Claims.PreferredUsername or Claims.Name when principal.HasScope(Scopes.Profile) => + [Destinations.AccessToken, Destinations.IdentityToken], + _ => [Destinations.AccessToken] + }); + + return Results.SignIn(principal, properties: null, OpenIddictScheme); + } + + private static async Task 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."); + } + + // 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); + } + + private static async Task UserInfoAsync(HttpContext http) + { + var result = await http.AuthenticateAsync(OpenIddictScheme); + if (!result.Succeeded || result.Principal is null) + { + return Results.Challenge(authenticationSchemes: [OpenIddictScheme]); + } + + var claims = new Dictionary { [Claims.Subject] = result.Principal.GetClaim(Claims.Subject) }; + if (result.Principal.HasScope(Scopes.Profile)) + { + claims[Claims.PreferredUsername] = result.Principal.GetClaim(Claims.PreferredUsername); + claims[Claims.Name] = result.Principal.GetClaim(Claims.Name); + } + + return Results.Json(claims); + } + + private static IResult Deny(string error, string description) => + Results.Forbid( + new AuthenticationProperties(new Dictionary + { + [OpenIddictServerAspNetCoreConstants.Properties.Error] = error, + [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = description + }), + [OpenIddictScheme]); +} diff --git a/src/Bifrost.Web/Features/Oidc/OidcServiceCollectionExtensions.cs b/src/Bifrost.Web/Features/Oidc/OidcServiceCollectionExtensions.cs new file mode 100644 index 0000000..2453eb8 --- /dev/null +++ b/src/Bifrost.Web/Features/Oidc/OidcServiceCollectionExtensions.cs @@ -0,0 +1,73 @@ +using Bifrost.Web.Configuration; +using Bifrost.Web.Data; +using Microsoft.Extensions.Options; +using OpenIddict.Abstractions; +using OpenIddict.Server; +using static OpenIddict.Abstractions.OpenIddictConstants; + +namespace Bifrost.Web.Features.Oidc; + +public static class OidcServiceCollectionExtensions +{ + public const string AuthorizationPath = "/connect/authorize"; + public const string TokenPath = "/connect/token"; + public const string UserInfoPath = "/connect/userinfo"; + + /// How long a parked authorize request (OpenIddict's request token) can wait for the user to sign in. + public static readonly TimeSpan ParkedRequestLifetime = TimeSpan.FromMinutes(10); + + /// + /// Registers Bifrost as an OIDC provider whose issuer is : authorization-code flow with + /// PKCE, ES256 id_tokens, scopes openid and profile, one configured client. Keys come from files, never from + /// generated development keys. The authorize request is parked by OpenIddict's own request caching, so the + /// sign-in return path carries only a short request_uri. + /// + public static IServiceCollection AddBifrostOidc(this IServiceCollection services, OidcIssuerOptions options) + { + var material = OidcKeyMaterial.Load(options); + services.AddSingleton(material); + services.AddSingleton(options); + + services.AddOpenIddict() + .AddCore(core => core.UseEntityFrameworkCore().UseDbContext()) + .AddServer(server => + { + server.SetAuthorizationEndpointUris(AuthorizationPath) + .SetTokenEndpointUris(TokenPath) + .SetUserInfoEndpointUris(UserInfoPath); + + server.AllowAuthorizationCodeFlow().RequireProofKeyForCodeExchange(); + server.RegisterScopes(Scopes.OpenId, Scopes.Profile); + server.RegisterClaims(Claims.Subject, Claims.PreferredUsername, Claims.Name); + server.EnableAuthorizationRequestCaching(); + server.Configure(opts => + { + opts.ClientAuthenticationMethods.Clear(); + opts.ClientAuthenticationMethods.Add(ClientAuthenticationMethods.ClientSecretBasic); + opts.RequestTokenLifetime = ParkedRequestLifetime; + }); + + server.AddSigningKey(material.SigningKey); + server.AddEncryptionKey(material.EncryptionKey); + + server.UseAspNetCore() + .EnableAuthorizationEndpointPassthrough() + .EnableTokenEndpointPassthrough() + .EnableUserInfoEndpointPassthrough(); + }); + + // The issuer is the public host, read from the bound options so it has one source. + services.AddOptions().Configure>((server, host) => + { + if (!Uri.TryCreate(host.Value.PublicBaseUrl, UriKind.Absolute, out var issuer)) + { + throw new OidcConfigurationException("Host:PublicBaseUrl is required when Bifrost:Oidc is configured."); + } + + server.Issuer = issuer; + }); + + services.AddHostedService(); + return services; + } +} diff --git a/src/Bifrost.Web/Program.cs b/src/Bifrost.Web/Program.cs index c0f5e40..d0656d3 100644 --- a/src/Bifrost.Web/Program.cs +++ b/src/Bifrost.Web/Program.cs @@ -11,6 +11,7 @@ using Bifrost.Web.Features.GitHub; using Bifrost.Web.Features.Heimdall; using Bifrost.Web.Features.Membership; using Bifrost.Web.Features.Motions; +using Bifrost.Web.Features.Oidc; using Bifrost.Web.Features.Patronage; using Bifrost.Web.Features.Shared; using Microsoft.AspNetCore.Authentication; @@ -225,6 +226,13 @@ builder.Services.AddAuthorization(options => builder.Services.AddConceptTallyCors(); +// The OIDC provider is mapped only when Bifrost:Oidc is configured; a configured provider that cannot load its keys stops startup. +var oidcOptions = OidcIssuerOptions.FromConfiguration(builder.Configuration); +if (oidcOptions is not null) +{ + builder.Services.AddBifrostOidc(oidcOptions); +} + var app = builder.Build(); var appJsonSerializerOptions = CreateAppJsonSerializerOptions(); @@ -267,6 +275,11 @@ app.MapGet("/readyz", async (ReadinessService readinessService, CancellationToke app.MapConceptTallyExport(); +if (oidcOptions is not null) +{ + app.MapBifrostOidc(); +} + app.MapPost("/github/webhooks", async ( HttpRequest request, GitHubWebhookService gitHubWebhookService, diff --git a/tests/Bifrost.Web.Tests/OidcIssuerTests.cs b/tests/Bifrost.Web.Tests/OidcIssuerTests.cs new file mode 100644 index 0000000..524e8fb --- /dev/null +++ b/tests/Bifrost.Web.Tests/OidcIssuerTests.cs @@ -0,0 +1,486 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using Bifrost.Web.Domain; +using Bifrost.Web.Features.Shared; +using Bifrost.Web.Tests.Support; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.IdentityModel.JsonWebTokens; +using Microsoft.IdentityModel.Tokens; + +namespace Bifrost.Web.Tests; + +public sealed class OidcIssuerTests : IClassFixture +{ + private static readonly Uri Origin = new("https://localhost"); + private readonly OidcWebApplicationFactory _factory; + + public OidcIssuerTests(OidcWebApplicationFactory factory) => _factory = factory; + + [Fact] + public async Task Discovery_advertises_ES256_and_the_code_flow_only() + { + using var client = NewClient(); + var discovery = await client.GetFromJsonAsync("/.well-known/openid-configuration"); + + Assert.Equal(Origin.AbsoluteUri, discovery.GetProperty("issuer").GetString()); + Assert.Equal(["ES256"], Strings(discovery, "id_token_signing_alg_values_supported")); + Assert.Equal(["code"], Strings(discovery, "response_types_supported")); + Assert.Equal(["authorization_code"], Strings(discovery, "grant_types_supported")); + Assert.Contains("S256", Strings(discovery, "code_challenge_methods_supported")); + Assert.Equal(["client_secret_basic"], Strings(discovery, "token_endpoint_auth_methods_supported")); + Assert.Equal(["openid", "profile"], Strings(discovery, "scopes_supported").Order()); + } + + [Fact] + public async Task Jwks_holds_exactly_the_configured_P256_key() + { + using var client = NewClient(); + var jwks = await GetJwksAsync(client); + + var key = Assert.Single(jwks.GetProperty("keys").EnumerateArray()); + Assert.Equal("EC", key.GetProperty("kty").GetString()); + Assert.Equal("P-256", key.GetProperty("crv").GetString()); + Assert.Equal("ES256", key.GetProperty("alg").GetString()); + + using var ec = ECDsa.Create(); + ec.ImportFromPem(_factory.Kit.SigningPublicKeyPem); + var expected = ec.ExportParameters(false); + Assert.Equal(Base64UrlEncoder.Encode(expected.Q.X), key.GetProperty("x").GetString()); + Assert.Equal(Base64UrlEncoder.Encode(expected.Q.Y), key.GetProperty("y").GetString()); + Assert.False(key.TryGetProperty("d", out _)); + } + + [Fact] + public async Task An_active_member_completes_code_and_pkce_and_gets_the_right_claims() + { + var (client, identity) = await SignedInAsync(MembershipStatus.Active, "Ada Lovelace"); + var accountId = _factory.AccountId(identity); + await SetLinksAsync(identity, "heimdall-canary-7", "github-canary-7"); + + var tokens = await CompleteFlowAsync(client); + + var verified = await ValidateIdTokenAsync(tokens.IdToken, tokens.Request.Nonce); + Assert.Equal(accountId.ToString("D"), verified.Claim("sub")); + Assert.Equal(identity, verified.Claim("preferred_username")); + Assert.Equal("Ada Lovelace", verified.Claim("name")); + Assert.Equal(["ES256"], [verified.Alg]); + + // Nothing about the authenticator links, e-mail or membership leaves Bifrost. + Assert.DoesNotContain("heimdall-canary-7", verified.PayloadJson); + Assert.DoesNotContain("github-canary-7", verified.PayloadJson); + Assert.DoesNotContain("email", verified.PayloadJson, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("urn:bifrost", verified.PayloadJson); + + using var userinfo = new HttpRequestMessage(HttpMethod.Get, "/connect/userinfo"); + userinfo.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokens.AccessToken); + using var userinfoResponse = await NewClient().SendAsync(userinfo); + Assert.Equal(HttpStatusCode.OK, userinfoResponse.StatusCode); + var body = await userinfoResponse.Content.ReadAsStringAsync(); + var info = JsonDocument.Parse(body).RootElement; + Assert.Equal(accountId.ToString("D"), info.GetProperty("sub").GetString()); + Assert.Equal(identity, info.GetProperty("preferred_username").GetString()); + Assert.Equal("Ada Lovelace", info.GetProperty("name").GetString()); + Assert.DoesNotContain("canary", body); + } + + [Fact] + public async Task Sub_and_preferred_username_are_stable_across_display_name_changes() + { + var (client, identity) = await SignedInAsync(MembershipStatus.Active, "First Name"); + + var first = await ValidateIdTokenAsync((await CompleteFlowAsync(client)).IdToken, null); + await _factory.SetDisplayNameAsync(identity, "Second Name"); + var second = await ValidateIdTokenAsync((await CompleteFlowAsync(client)).IdToken, null); + + Assert.Equal(first.Claim("sub"), second.Claim("sub")); + Assert.Equal(first.Claim("preferred_username"), second.Claim("preferred_username")); + Assert.Equal("First Name", first.Claim("name")); + Assert.Equal("Second Name", second.Claim("name")); + } + + [Theory] + [InlineData(MembershipStatus.Authenticated)] + [InlineData(MembershipStatus.PendingApproval)] + [InlineData(MembershipStatus.Suspended)] + public async Task A_member_who_is_not_active_is_refused_with_access_denied_and_no_code(MembershipStatus status) + { + var (client, _) = await SignedInAsync(status, "Not Active"); + var request = NewRequest(); + + var final = await DriveAsync(client, request); + + var redirect = AssertRedirectToClient(final, request.State); + Assert.Equal("access_denied", redirect["error"]); + Assert.Equal(Bifrost.Web.Features.Oidc.OidcEndpoints.NotActiveDescription, redirect["error_description"]); + Assert.False(redirect.ContainsKey("code")); + } + + [Fact] + public async Task An_active_account_with_no_bifrost_identity_is_refused_never_given_an_empty_username() + { + using var factory = new OidcNoIdentityFactory(); + using var client = factory.CreateClient(ClientOptions()); + await RegisterAsync(client, $"noid-{Guid.NewGuid():N}"); + var request = NewRequest(); + + var final = await DriveAsync(client, request); + + var redirect = AssertRedirectToClient(final, request.State); + Assert.Equal("access_denied", redirect["error"]); + Assert.Equal(Bifrost.Web.Features.Oidc.OidcEndpoints.NoIdentityDescription, redirect["error_description"]); + Assert.False(redirect.ContainsKey("code")); + } + + [Theory] + [InlineData("unknown-client", OidcTestKit.RedirectUri, true)] + [InlineData(OidcTestKit.ClientId, "https://evil.example.test/callback", true)] + [InlineData(OidcTestKit.ClientId, OidcTestKit.RedirectUri, false)] + public async Task Unknown_client_wrong_redirect_uri_and_missing_pkce_are_refused_before_any_sign_in_redirect( + string clientId, string redirectUri, bool pkce) + { + using var client = NewClient(); + var request = NewRequest(clientId, redirectUri, pkce); + + using var response = await client.GetAsync(request.Path); + + var location = response.Headers.Location?.OriginalString ?? string.Empty; + Assert.DoesNotContain("/auth/sign-in", location); + Assert.DoesNotContain("request_uri=", location); + Assert.DoesNotContain("code=", location); + Assert.NotEqual(HttpStatusCode.OK, response.StatusCode); + } + + [Fact] + public async Task A_mas_sized_authorize_request_survives_sign_in_and_its_handle_is_single_use() + { + var request = NewRequest(extra: "&ui_locales=en&prompt=login&claims_locales=en&max_age=3600"); + Assert.True(request.Path.Length > LocalReturnPath.MaxLength, "the request must be longer than a sign-in return path"); + + using var client = NewClient(); + var signIn = await DriveAsync(client, request); + Assert.Equal(HttpStatusCode.Redirect, signIn.StatusCode); + Assert.Equal("/auth/sign-in", signIn.Headers.Location!.IsAbsoluteUri + ? signIn.Headers.Location.AbsolutePath + : signIn.Headers.Location.OriginalString.Split('?')[0]); + var resume = ReturnUrl(signIn); + Assert.True(resume.Length <= LocalReturnPath.MaxLength, "the resume path must fit the sign-in return path"); + Assert.Equal(resume, LocalReturnPath.Parse(resume).Value); + + var identity = await RegisterAsync(client, $"resume-{Guid.NewGuid():N}"); + await _factory.SetMembershipAsync(identity, MembershipStatus.Active); + + using var resumed = await client.GetAsync(resume); + var redirect = AssertRedirectToClient(resumed, request.State); + Assert.True(redirect.ContainsKey("code"), "the resumed request issues a code"); + + var tokens = await ExchangeAsync(client, request, redirect["code"]!); + var verified = await ValidateIdTokenAsync(tokens.IdToken, request.Nonce); + Assert.Equal(request.Nonce, verified.Claim("nonce")); + + // The handle was spent by the first resume. + using var replay = await client.GetAsync(resume); + var replayRedirect = replay.Headers.Location?.OriginalString ?? string.Empty; + Assert.DoesNotContain("code=", replayRedirect); + Assert.NotEqual(HttpStatusCode.OK, replay.StatusCode); + } + + [Fact] + public async Task A_parked_authorize_request_expires() + { + // Own host: moving the clock must not skew the id_token checks of the other tests. + using var own = new OidcWebApplicationFactory(); + await new OidcIssuerTests(own).ParkedRequestIsRefusedAfterItsLifetimeAsync(); + } + + private async Task ParkedRequestIsRefusedAfterItsLifetimeAsync() + { + var request = NewRequest(); + using var client = NewClient(); + var signIn = await DriveAsync(client, request); + var resume = ReturnUrl(signIn); + var identity = await RegisterAsync(client, $"late-{Guid.NewGuid():N}"); + await _factory.SetMembershipAsync(identity, MembershipStatus.Active); + + _factory.Clock.Advance(Bifrost.Web.Features.Oidc.OidcServiceCollectionExtensions.ParkedRequestLifetime + TimeSpan.FromMinutes(1)); + + using var late = await client.GetAsync(resume); + var location = late.Headers.Location?.OriginalString ?? string.Empty; + Assert.DoesNotContain("code=", location); + Assert.NotEqual(HttpStatusCode.OK, late.StatusCode); + } + + [Fact] + public async Task The_token_endpoint_accepts_client_secret_basic_only() + { + var (client, _) = await SignedInAsync(MembershipStatus.Active, "Basic Only"); + var request = NewRequest(); + var code = await CodeAsync(client, request); + + var wrongSecret = await TokenAsync(client, request, code, secret: "wrong-secret"); + Assert.NotEqual(HttpStatusCode.OK, wrongSecret.StatusCode); + + var asPost = await TokenAsync(client, request, code, secretInBody: true); + Assert.NotEqual(HttpStatusCode.OK, asPost.StatusCode); + } + + [Fact] + public async Task Identity_is_minted_once() + { + using var scope = _factory.Services.CreateScope(); + var service = scope.ServiceProvider.GetRequiredService(); + var account = new UserAccount { BifrostIdentity = "Original", NormalizedBifrostIdentity = "original" }; + + await service.EnsureIdentityAsync(account, "someone-else", CancellationToken.None); + + Assert.Equal("original", account.NormalizedBifrostIdentity); + Assert.Equal("Original", account.BifrostIdentity); + } + + // ---- helpers ---- + + private static WebApplicationFactoryClientOptions ClientOptions() => new() + { + AllowAutoRedirect = false, + HandleCookies = true, + BaseAddress = Origin + }; + + private HttpClient NewClient() => _factory.CreateClient(ClientOptions()); + + private static async Task RegisterAsync(HttpClient client, string identity) + { + using var response = await client.PostAsJsonAsync("/auth/bifrost/register", new { identity, displayName = identity }); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + return identity.ToLowerInvariant(); + } + + private async Task<(HttpClient Client, string Identity)> SignedInAsync(MembershipStatus status, string displayName) + { + var client = NewClient(); + var identity = await RegisterAsync(client, $"member-{Guid.NewGuid():N}"); + await _factory.SetMembershipAsync(identity, status); + await _factory.SetDisplayNameAsync(identity, displayName); + return (client, identity); + } + + private async Task SetLinksAsync(string identity, string heimdallAccountId, string gitHubLogin) + { + using var scope = _factory.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var account = db.UserAccounts.Single(x => x.NormalizedBifrostIdentity == identity); + account.HeimdallAccountId = heimdallAccountId; + account.GitHubLogin = gitHubLogin; + await db.SaveChangesAsync(); + } + + private sealed record AuthRequest(string Verifier, string State, string Nonce, string Path) + { + public string Challenge => Base64UrlEncoder.Encode(SHA256.HashData(Encoding.ASCII.GetBytes(Verifier))); + } + + private static AuthRequest NewRequest( + string clientId = OidcTestKit.ClientId, + string redirectUri = OidcTestKit.RedirectUri, + bool pkce = true, + string extra = "") + { + var verifier = Base64UrlEncoder.Encode(RandomNumberGenerator.GetBytes(48)); + var state = Base64UrlEncoder.Encode(RandomNumberGenerator.GetBytes(24)); + var nonce = Base64UrlEncoder.Encode(RandomNumberGenerator.GetBytes(24)); + var challenge = Base64UrlEncoder.Encode(SHA256.HashData(Encoding.ASCII.GetBytes(verifier))); + var path = "/connect/authorize?response_type=code" + + $"&client_id={Uri.EscapeDataString(clientId)}" + + $"&redirect_uri={Uri.EscapeDataString(redirectUri)}" + + "&scope=openid%20profile" + + $"&state={state}&nonce={nonce}" + + (pkce ? $"&code_challenge={challenge}&code_challenge_method=S256" : string.Empty) + + extra; + return new AuthRequest(verifier, state, nonce, path); + } + + /// Starts an authorize request and follows the provider's own redirects until the first response that is not one of them. + private static async Task DriveAsync(HttpClient client, AuthRequest request) + { + var response = await client.GetAsync(request.Path); + for (var hops = 0; hops < 4 && IsAuthorizeRedirect(response); hops++) + { + var next = response.Headers.Location!; + response.Dispose(); + response = await client.GetAsync(next.IsAbsoluteUri ? next.PathAndQuery : next.OriginalString); + } + + return response; + } + + private static bool IsAuthorizeRedirect(HttpResponseMessage response) => + response.StatusCode is HttpStatusCode.Redirect or HttpStatusCode.Found && + response.Headers.Location is { } location && + (location.IsAbsoluteUri ? location.AbsolutePath : location.OriginalString).StartsWith("/connect/authorize", StringComparison.Ordinal); + + private static string ReturnUrl(HttpResponseMessage signInRedirect) + { + var location = signInRedirect.Headers.Location!; + var query = location.IsAbsoluteUri ? location.Query : location.OriginalString[location.OriginalString.IndexOf('?')..]; + return Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(query) + .Single(x => string.Equals(x.Key, "returnUrl", StringComparison.OrdinalIgnoreCase)).Value.ToString(); + } + + private static Dictionary AssertRedirectToClient(HttpResponseMessage response, string state) + { + Assert.True(response.StatusCode is HttpStatusCode.Redirect or HttpStatusCode.Found, $"expected a redirect, got {(int)response.StatusCode}"); + var location = response.Headers.Location!; + Assert.Equal(new Uri(OidcTestKit.RedirectUri).GetLeftPart(UriPartial.Path), location.GetLeftPart(UriPartial.Path)); + var query = Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(location.Query); + Assert.Equal(state, query["state"].ToString()); + return query.ToDictionary(x => x.Key, x => (string?)x.Value.ToString()); + } + + private async Task CodeAsync(HttpClient signedIn, AuthRequest request) + { + var final = await DriveAsync(signedIn, request); + return AssertRedirectToClient(final, request.State)["code"]!; + } + + private sealed record Tokens(AuthRequest Request, string IdToken, string AccessToken); + + private async Task CompleteFlowAsync(HttpClient signedIn) + { + var request = NewRequest(); + var code = await CodeAsync(signedIn, request); + return await ExchangeAsync(signedIn, request, code); + } + + private async Task ExchangeAsync(HttpClient client, AuthRequest request, string code) + { + using var response = await TokenAsync(client, request, code); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var body = await response.Content.ReadFromJsonAsync(); + Assert.DoesNotContain("refresh_token", body.EnumerateObject().Select(x => x.Name)); + return new Tokens(request, body.GetProperty("id_token").GetString()!, body.GetProperty("access_token").GetString()!); + } + + private async Task TokenAsync( + HttpClient client, AuthRequest request, string code, string? secret = null, bool secretInBody = false) + { + var form = new Dictionary + { + ["grant_type"] = "authorization_code", + ["code"] = code, + ["redirect_uri"] = OidcTestKit.RedirectUri, + ["code_verifier"] = request.Verifier + }; + var message = new HttpRequestMessage(HttpMethod.Post, "/connect/token"); + var effectiveSecret = secret ?? _factory.Kit.ClientSecret; + if (secretInBody) + { + form["client_id"] = OidcTestKit.ClientId; + form["client_secret"] = effectiveSecret; + } + else + { + message.Headers.Authorization = new AuthenticationHeaderValue( + "Basic", + Convert.ToBase64String(Encoding.ASCII.GetBytes($"{OidcTestKit.ClientId}:{effectiveSecret}"))); + } + + message.Content = new FormUrlEncodedContent(form); + // The code is bound to the client; use a cookieless client so a session cannot influence the exchange. + using var bare = NewClient(); + return await bare.SendAsync(message); + } + + private sealed record Verified(string Alg, string PayloadJson, JsonElement Payload) + { + public string? Claim(string name) => Payload.TryGetProperty(name, out var value) ? value.GetString() : null; + } + + private async Task ValidateIdTokenAsync(string idToken, string? nonce) + { + using var client = NewClient(); + var jwks = new JsonWebKeySet((await GetJwksAsync(client)).GetRawText()); + var result = await new JsonWebTokenHandler().ValidateTokenAsync(idToken, new TokenValidationParameters + { + ValidIssuer = Origin.AbsoluteUri, + ValidAudience = OidcTestKit.ClientId, + IssuerSigningKeys = jwks.GetSigningKeys(), + ValidAlgorithms = ["ES256"] + }); + Assert.True(result.IsValid, result.Exception?.Message); + var jwt = (JsonWebToken)result.SecurityToken; + var payload = Encoding.UTF8.GetString(Base64UrlEncoder.DecodeBytes(jwt.EncodedPayload)); + if (nonce is not null) + { + Assert.Equal(nonce, JsonDocument.Parse(payload).RootElement.GetProperty("nonce").GetString()); + } + + return new Verified(jwt.Alg, payload, JsonDocument.Parse(payload).RootElement.Clone()); + } + + private static async Task GetJwksAsync(HttpClient client) + { + var discovery = await client.GetFromJsonAsync("/.well-known/openid-configuration"); + var jwksUri = new Uri(discovery.GetProperty("jwks_uri").GetString()!); + return await client.GetFromJsonAsync(jwksUri.PathAndQuery); + } + + private static string[] Strings(JsonElement document, string property) => + document.GetProperty(property).EnumerateArray().Select(x => x.GetString()!).ToArray(); +} + +public sealed class OidcSurfaceAbsentTests : IClassFixture +{ + private readonly TestWebApplicationFactory _factory; + + public OidcSurfaceAbsentTests(TestWebApplicationFactory factory) => _factory = factory; + + [Theory] + [InlineData("/.well-known/openid-configuration")] + [InlineData("/.well-known/jwks")] + [InlineData("/connect/authorize")] + [InlineData("/connect/token")] + [InlineData("/connect/userinfo")] + public async Task Without_the_configuration_section_no_provider_surface_exists(string path) + { + using var client = _factory.CreateClient(); + using var response = await client.GetAsync(path); + + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + } +} + +public sealed class OidcStartupFailureTests +{ + [Theory] + [InlineData(OidcKeyFault.MissingFile)] + [InlineData(OidcKeyFault.RsaKey)] + [InlineData(OidcKeyFault.PublicKeyOnly)] + [InlineData(OidcKeyFault.NotPem)] + public void A_configured_provider_with_an_unusable_signing_key_stops_startup_naming_the_setting_not_the_path(OidcKeyFault fault) + { + using var factory = new OidcKeyFaultFactory(fault); + + var failure = Assert.ThrowsAny(() => factory.CreateClient()); + + var messages = Flatten(failure).ToList(); + Assert.Contains(messages, m => m.Contains("Bifrost:Oidc:SigningKeyPath", StringComparison.Ordinal)); + Assert.DoesNotContain(messages, m => m.Contains("canary-", StringComparison.Ordinal)); + Assert.DoesNotContain(messages, m => m.Contains("BEGIN", StringComparison.Ordinal)); + } + + private static IEnumerable Flatten(Exception error) + { + for (var current = error; current is not null; current = current.InnerException!) + { + yield return current.Message; + if (current.InnerException is null) + { + yield break; + } + } + } +} diff --git a/tests/Bifrost.Web.Tests/Support/OidcTestKit.cs b/tests/Bifrost.Web.Tests/Support/OidcTestKit.cs new file mode 100644 index 0000000..e334156 --- /dev/null +++ b/tests/Bifrost.Web.Tests/Support/OidcTestKit.cs @@ -0,0 +1,218 @@ +using System.Security.Cryptography; +using Bifrost.Web.Data; +using Bifrost.Web.Domain; +using Bifrost.Web.Features.Shared; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; + +namespace Bifrost.Web.Tests.Support; + +/// What is wrong with the signing key file a test host is started with. +public enum OidcKeyFault +{ + None, + MissingFile, + RsaKey, + PublicKeyOnly, + NotPem +} + +/// Key files and client settings for an OIDC test host. Everything is generated per kit; nothing is shared or committed. +public sealed class OidcTestKit : IDisposable +{ + public const string ClientId = "mas-test"; + public const string RedirectUri = "https://chat.example.test/_synapse/client/oidc/callback"; + + public OidcTestKit(OidcKeyFault fault = OidcKeyFault.None) + { + // The directory name is a canary: no error may echo any part of a configured path. + Directory = Path.Combine(Path.GetTempPath(), "canary-" + Guid.NewGuid().ToString("N")); + System.IO.Directory.CreateDirectory(Directory); + + using var ec = ECDsa.Create(ECCurve.NamedCurves.nistP256); + SigningKeyPem = ec.ExportPkcs8PrivateKeyPem(); + SigningPublicKeyPem = ec.ExportSubjectPublicKeyInfoPem(); + ClientSecret = Convert.ToHexString(RandomNumberGenerator.GetBytes(24)); + + SigningKeyPath = Path.Combine(Directory, "signing.pem"); + EncryptionKeyPath = Path.Combine(Directory, "encryption.key"); + ClientSecretPath = Path.Combine(Directory, "mas.secret"); + + switch (fault) + { + case OidcKeyFault.None: + File.WriteAllText(SigningKeyPath, SigningKeyPem); + break; + case OidcKeyFault.RsaKey: + using (var rsa = RSA.Create(2048)) + { + File.WriteAllText(SigningKeyPath, rsa.ExportPkcs8PrivateKeyPem()); + } + + break; + case OidcKeyFault.PublicKeyOnly: + File.WriteAllText(SigningKeyPath, SigningPublicKeyPem); + break; + case OidcKeyFault.NotPem: + File.WriteAllText(SigningKeyPath, "not a key"); + break; + case OidcKeyFault.MissingFile: + break; + } + + File.WriteAllText(EncryptionKeyPath, Convert.ToBase64String(RandomNumberGenerator.GetBytes(32)) + "\n"); + File.WriteAllText(ClientSecretPath, ClientSecret + "\n"); + } + + public string Directory { get; } + + public string SigningKeyPath { get; } + + public string EncryptionKeyPath { get; } + + public string ClientSecretPath { get; } + + public string ClientSecret { get; } + + public string SigningKeyPem { get; } + + public string SigningPublicKeyPem { get; } + + public IReadOnlyDictionary Configuration => new Dictionary + { + ["Bifrost:Oidc:SigningKeyPath"] = SigningKeyPath, + ["Bifrost:Oidc:EncryptionKeyPath"] = EncryptionKeyPath, + ["Bifrost:Oidc:Clients:Mas:ClientId"] = ClientId, + ["Bifrost:Oidc:Clients:Mas:ClientSecretPath"] = ClientSecretPath, + ["Bifrost:Oidc:Clients:Mas:RedirectUri"] = RedirectUri + }; + + public void Dispose() + { + try + { + System.IO.Directory.Delete(Directory, recursive: true); + } + catch (IOException) + { + } + } +} + +/// A clock the test moves, so a parked authorize request can be aged past its lifetime. +public sealed class OidcTestClock : TimeProvider +{ + private DateTimeOffset _now = DateTimeOffset.UtcNow; + + public override DateTimeOffset GetUtcNow() => _now; + + public void Advance(TimeSpan by) => _now += by; +} + +/// +/// A test host with the OIDC provider configured from generated key files and cookie authentication as the real +/// sign-in state (the shared test host signs everyone in as an admin through a header-driven handler instead). +/// +public class OidcWebApplicationFactory : TestWebApplicationFactory +{ + public OidcWebApplicationFactory() : this(OidcKeyFault.None) + { + } + + protected OidcWebApplicationFactory(OidcKeyFault fault) => Kit = new(fault); + + public OidcTestKit Kit { get; } + + public OidcTestClock Clock { get; } = new(); + + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + base.ConfigureWebHost(builder); + + // Program decides at registration time whether the provider exists, so these must be host settings: + // configuration added with ConfigureAppConfiguration reaches the app only at Build(). + foreach (var (key, value) in Kit.Configuration) + { + builder.UseSetting(key, value); + } + + builder.ConfigureServices(services => + { + services.Configure(options => + { + options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; + options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; + }); + services.RemoveAll(); + services.AddSingleton(Clock); + ConfigureActors(services); + }); + } + + /// A hook for tests that replace the seam Bifrost reads the signed-in account through. + protected virtual void ConfigureActors(IServiceCollection services) + { + } + + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + if (disposing) + { + Kit.Dispose(); + } + } + + /// Sets the membership of the account registered under . + public async Task SetMembershipAsync(string identity, MembershipStatus status) + { + using var scope = Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var account = db.UserAccounts.Single(x => x.NormalizedBifrostIdentity == identity); + db.Memberships.Single(x => x.UserAccountId == account.Id).Status = status; + await db.SaveChangesAsync(); + } + + /// Renames the account's display name, as the owner would between two sign-ins. + public async Task SetDisplayNameAsync(string identity, string displayName) + { + using var scope = Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + db.UserAccounts.Single(x => x.NormalizedBifrostIdentity == identity).DisplayName = displayName; + await db.SaveChangesAsync(); + } + + public Guid AccountId(string identity) + { + using var scope = Services.CreateScope(); + return scope.ServiceProvider.GetRequiredService() + .UserAccounts.Single(x => x.NormalizedBifrostIdentity == identity).Id; + } +} + +/// An OIDC host whose signing key file is unusable, so startup must refuse it. +public sealed class OidcKeyFaultFactory(OidcKeyFault fault) : OidcWebApplicationFactory(fault); + +/// An OIDC host whose actor accessor reports an Active account that has no Bifrost identity, which sign-in itself never produces. +public sealed class OidcNoIdentityFactory : OidcWebApplicationFactory +{ + protected override void ConfigureActors(IServiceCollection services) + { + services.RemoveAll(); + services.AddScoped(); + } + + private sealed class ActiveWithoutIdentity : ICurrentBifrostActorAccessor + { + public Task GetAsync(CancellationToken cancellationToken) => + Task.FromResult(new CurrentBifrostActor(true, new UserAccount + { + NormalizedBifrostIdentity = string.Empty, + DisplayName = "No Identity", + Membership = new Bifrost.Web.Domain.Membership { Status = MembershipStatus.Active } + })); + } +}