2026-10-27 04:57:16 +01:00
using System.Security.Claims ;
using Microsoft.AspNetCore ;
using Bifrost.Web.Data ;
using Bifrost.Web.Domain ;
2026-11-11 17:44:38 +00:00
using Bifrost.Web.Features.Desk ;
2026-11-11 06:39:35 +00:00
using Bifrost.Web.Features.Membership ;
2026-11-11 14:32:06 +00:00
using Bifrost.Web.Features.Registration ;
2026-10-27 04:57:16 +01:00
using Bifrost.Web.Features.Shared ;
using Microsoft.EntityFrameworkCore ;
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 ;
/// <summary>
/// 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.
/// </summary>
public static class OidcEndpoints
{
2026-11-11 08:13:09 +00:00
public const string SuspendedDescription = "The account is suspended." ;
2026-10-27 04:57:16 +01:00
public const string NoIdentityDescription = "The account has no Bifrost identity." ;
2026-11-11 06:39:35 +00:00
public const string ReservedIdentityDescription = "The account's Bifrost identity is reserved." ;
2026-11-11 14:32:06 +00:00
public const string ConsentRequiredDescription = "Agreement to the training notice in force is needed to speak in a recorded room." ;
2026-10-27 04:57:16 +01:00
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 ( ) ;
}
2026-11-11 14:32:06 +00:00
private static async Task < IResult > AuthorizeAsync ( HttpContext http , ICurrentBifrostActorAccessor actors , BifrostDbContext db )
2026-10-27 04:57:16 +01:00
{
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, 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 ) ;
2026-11-11 08:13:09 +00:00
// Chat tier: any account that is not suspended may sign in to chat. Membership is neither required nor written;
// every member or governance surface keeps asking for Active itself (the Active-member policy, IsActiveMember, ActiveMemberIdAsync).
if ( actor . UserAccount is null )
2026-10-27 04:57:16 +01:00
{
2026-11-11 08:13:09 +00:00
return Deny ( Errors . AccessDenied , NoIdentityDescription ) ;
}
if ( actor . Membership ? . Status = = MembershipStatus . Suspended )
{
return Deny ( Errors . AccessDenied , SuspendedDescription ) ;
2026-10-27 04:57:16 +01:00
}
var account = actor . UserAccount ;
if ( string . IsNullOrWhiteSpace ( account . NormalizedBifrostIdentity ) )
{
return Deny ( Errors . AccessDenied , NoIdentityDescription ) ;
}
2026-11-11 06:39:35 +00:00
// The identity becomes the Matrix localpart. Creation refuses reserved names (BifrostIdentityService), but a row minted
// before that refusal may hold one, and there is no rename path: the issuer never vouches for a Mind's or a system's localpart.
if ( BifrostIdentityService . IsReserved ( account . NormalizedBifrostIdentity ) )
{
return Deny ( Errors . AccessDenied , ReservedIdentityDescription ) ;
}
2026-10-27 04:57:16 +01:00
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 ( ) ) ;
2026-11-11 17:44:38 +00:00
// A desk scope is what makes a token a desk token: its audience is the desk's. The client's permissions already
// decided whether it may ask for the scope (the MAS client may not), so this branch is reached only by one that may.
if ( request . GetScopes ( ) . Any ( DeskEndpoints . IsDeskScope ) )
{
principal . SetResources ( DeskEndpoints . Audience ) ;
}
2026-10-27 04:57:16 +01:00
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 ]
} ) ;
2026-11-11 14:32:06 +00:00
// Last, so a refusal that no agreement can cure (suspended, no identity, reserved) is never answered with an invitation to agree.
// Not an OIDC error: the member is sent to the consent page with this request's resume path, and the parked request
// (single use, ten minutes) is still there when they come back, because only an OpenIddict response spends it.
if ( ! await ConsentEndpoints . HasLiveReceiptAsync ( db , account . Id , http . RequestAborted ) )
{
return Results . Redirect ( ConsentEndpoints . PathFor ( http . Request . PathBase + http . Request . Path + http . Request . QueryString ) ) ;
}
2026-10-27 04:57:16 +01:00
return Results . SignIn ( principal , properties : null , OpenIddictScheme ) ;
}
private static async Task < IResult > ExchangeAsync ( HttpContext http , BifrostDbContext db )
{
// Only the authorization code grant is enabled, so OpenIddict has refused every other grant already.
2026-11-11 14:32:06 +00:00
// The code's own principal carries the claims chosen at authorize time; suspension and agreement are read again here,
// because the code outlives the authorize decision (an account suspended or withdrawn since gets no tokens).
2026-10-27 04:57:16 +01:00
var result = await http . AuthenticateAsync ( OpenIddictScheme ) ;
var subject = result . Principal ? . GetClaim ( Claims . Subject ) ;
2026-11-11 14:32:06 +00:00
if ( await ChatRefusalAsync ( db , subject , http . RequestAborted ) is { } refusal )
2026-10-27 04:57:16 +01:00
{
2026-11-11 14:32:06 +00:00
return Deny ( Errors . InvalidGrant , refusal ) ;
2026-10-27 04:57:16 +01:00
}
return Results . SignIn ( result . Principal ! , properties : null , OpenIddictScheme ) ;
}
private static async Task < IResult > UserInfoAsync ( HttpContext http , BifrostDbContext db )
{
var result = await http . AuthenticateAsync ( OpenIddictScheme ) ;
if ( ! result . Succeeded | | result . Principal is null )
{
return Results . Challenge ( authenticationSchemes : [ OpenIddictScheme ] ) ;
}
2026-11-11 14:32:06 +00:00
// An access token outlives the authorize decision too: an account suspended since, or one whose agreement has gone, is no longer answered.
if ( await ChatRefusalAsync ( db , result . Principal . GetClaim ( Claims . Subject ) , http . RequestAborted ) is { } refusal )
2026-10-27 04:57:16 +01:00
{
2026-11-11 14:32:06 +00:00
return Deny ( Errors . InsufficientAccess , refusal ) ;
2026-10-27 04:57:16 +01:00
}
var claims = new Dictionary < string , object? > { [ 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 ) ;
}
2026-11-11 08:13:09 +00:00
/// <summary>
/// The one reading of "this subject may still chat", shared by the token and userinfo endpoints and the logout reconciler:
2026-11-11 14:32:06 +00:00
/// null when they may, else the description of why not. The account exists, its membership is not Suspended (absent, pending
/// or Active all chat), and it holds a live receipt for the notice version in force. Re-read on every call.
2026-11-11 08:13:09 +00:00
/// </summary>
2026-11-11 14:32:06 +00:00
internal static async Task < string? > ChatRefusalAsync ( BifrostDbContext db , string? subject , CancellationToken cancellationToken )
2026-11-11 08:13:09 +00:00
{
if ( ! Guid . TryParse ( subject , out var accountId ) )
{
2026-11-11 14:32:06 +00:00
return SuspendedDescription ;
2026-11-11 08:13:09 +00:00
}
var account = await db . UserAccounts . AsNoTracking ( )
. Include ( x = > x . Membership )
. SingleOrDefaultAsync ( x = > x . Id = = accountId , cancellationToken ) ;
2026-11-11 14:32:06 +00:00
if ( account is null | | account . Membership ? . Status = = MembershipStatus . Suspended )
{
return SuspendedDescription ;
}
return await ConsentEndpoints . HasLiveReceiptAsync ( db , accountId , cancellationToken ) ? null : ConsentRequiredDescription ;
2026-11-11 08:13:09 +00:00
}
2026-11-11 01:02:36 +00:00
2026-11-11 08:13:09 +00:00
/// <summary>The account id of the subject when it is an Active member now, else null. The door to the fork desk (cookie surfaces check IsActiveMember); a chat-tier token does not pass it. Re-read on every call.</summary>
2026-11-11 01:02:36 +00:00
internal static async Task < Guid ? > ActiveMemberIdAsync ( BifrostDbContext db , string? subject , CancellationToken cancellationToken )
2026-10-27 04:57:16 +01:00
{
if ( ! Guid . TryParse ( subject , out var accountId ) )
{
2026-11-11 01:02:36 +00:00
return null ;
2026-10-27 04:57:16 +01:00
}
var account = await db . UserAccounts . AsNoTracking ( )
. Include ( x = > x . Membership )
. SingleOrDefaultAsync ( x = > x . Id = = accountId , cancellationToken ) ;
2026-11-11 01:02:36 +00:00
return new CurrentBifrostActor ( true , account ) . IsActiveMember ? accountId : null ;
2026-10-27 04:57:16 +01:00
}
private static IResult Deny ( string error , string description ) = >
Results . Forbid (
new AuthenticationProperties ( new Dictionary < string , string? >
{
[OpenIddictServerAspNetCoreConstants.Properties.Error] = error ,
[OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = description
} ) ,
[OpenIddictScheme] ) ;
}