Add native Bifrost identity registration

This commit is contained in:
Meta Vens 2026-06-22 15:07:22 +01:00
commit 23c02be2a6
17 changed files with 366 additions and 29 deletions

View file

@ -67,9 +67,12 @@ public sealed class BifrostDbContext(DbContextOptions<BifrostDbContext> options)
{
modelBuilder.Entity<UserAccount>(entity =>
{
entity.HasIndex(x => x.NormalizedBifrostIdentity).IsUnique().HasFilter("\"NormalizedBifrostIdentity\" <> ''");
entity.HasIndex(x => x.GitHubUserId).IsUnique().HasFilter("\"GitHubUserId\" IS NOT NULL");
entity.HasIndex(x => x.HeimdallAccountId).IsUnique().HasFilter("\"HeimdallAccountId\" <> ''");
entity.HasIndex(x => x.NormalizedGitHubLogin).IsUnique().HasFilter("\"NormalizedGitHubLogin\" <> ''");
entity.Property(x => x.BifrostIdentity).HasMaxLength(120);
entity.Property(x => x.NormalizedBifrostIdentity).HasMaxLength(120);
entity.Property(x => x.HeimdallAccountId).HasMaxLength(160);
entity.Property(x => x.GitHubLogin).HasMaxLength(120);
entity.Property(x => x.NormalizedGitHubLogin).HasMaxLength(120);

View file

@ -0,0 +1,54 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Bifrost.Web.Data.Migrations
{
/// <inheritdoc />
[Migration("20260622165000_AddBifrostNativeIdentity")]
public partial class AddBifrostNativeIdentity : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "BifrostIdentity",
table: "UserAccounts",
type: "character varying(120)",
maxLength: 120,
nullable: false,
defaultValue: "");
migrationBuilder.AddColumn<string>(
name: "NormalizedBifrostIdentity",
table: "UserAccounts",
type: "character varying(120)",
maxLength: 120,
nullable: false,
defaultValue: "");
migrationBuilder.CreateIndex(
name: "IX_UserAccounts_NormalizedBifrostIdentity",
table: "UserAccounts",
column: "NormalizedBifrostIdentity",
unique: true,
filter: "\"NormalizedBifrostIdentity\" <> ''");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_UserAccounts_NormalizedBifrostIdentity",
table: "UserAccounts");
migrationBuilder.DropColumn(
name: "BifrostIdentity",
table: "UserAccounts");
migrationBuilder.DropColumn(
name: "NormalizedBifrostIdentity",
table: "UserAccounts");
}
}
}

View file

@ -1227,6 +1227,11 @@ namespace Bifrost.Web.Data.Migrations
.HasMaxLength(500)
.HasColumnType("character varying(500)");
b.Property<string>("BifrostIdentity")
.IsRequired()
.HasMaxLength(120)
.HasColumnType("character varying(120)");
b.Property<DateTimeOffset>("CreatedAtUtc")
.HasColumnType("timestamp with time zone");
@ -1251,6 +1256,11 @@ namespace Bifrost.Web.Data.Migrations
b.Property<DateTimeOffset>("LastSeenAtUtc")
.HasColumnType("timestamp with time zone");
b.Property<string>("NormalizedBifrostIdentity")
.IsRequired()
.HasMaxLength(120)
.HasColumnType("character varying(120)");
b.Property<string>("NormalizedGitHubLogin")
.IsRequired()
.HasMaxLength(120)
@ -1266,6 +1276,10 @@ namespace Bifrost.Web.Data.Migrations
.IsUnique()
.HasFilter("\"HeimdallAccountId\" <> ''");
b.HasIndex("NormalizedBifrostIdentity")
.IsUnique()
.HasFilter("\"NormalizedBifrostIdentity\" <> ''");
b.HasIndex("NormalizedGitHubLogin")
.IsUnique()
.HasFilter("\"NormalizedGitHubLogin\" <> ''");

View file

@ -244,6 +244,10 @@ public sealed class UserAccount
{
public Guid Id { get; set; } = Guid.NewGuid();
public string BifrostIdentity { get; set; } = string.Empty;
public string NormalizedBifrostIdentity { get; set; } = string.Empty;
public long? GitHubUserId { get; set; }
public string HeimdallAccountId { get; set; } = string.Empty;

View file

@ -18,6 +18,7 @@ public sealed class HeimdallAuthService(
HttpClient httpClient,
HeimdallAuthAttemptStore attemptStore,
BifrostDbContext dbContext,
BifrostIdentityService bifrostIdentityService,
IOptions<HeimdallOptions> heimdallOptions,
TimeProvider timeProvider)
{
@ -116,25 +117,8 @@ public sealed class HeimdallAuthService(
}
var userAccount = await UpsertUserAccountAsync(payload, attempt.RequiresMemberAccess, cancellationToken);
var claims = new List<Claim>
{
new(ClaimTypes.NameIdentifier, userAccount.GitHubUserId?.ToString() ?? userAccount.HeimdallAccountId),
new(ClaimTypes.Name, userAccount.DisplayName),
new(BifrostClaimTypes.HeimdallAccountId, userAccount.HeimdallAccountId),
new(BifrostClaimTypes.AuthProvider, payload.Provider ?? "heimdall"),
new(BifrostClaimTypes.DisplayName, userAccount.DisplayName),
new(BifrostClaimTypes.AvatarUrl, userAccount.AvatarUrl)
};
if (!string.IsNullOrWhiteSpace(userAccount.GitHubLogin))
{
claims.Add(new Claim(BifrostClaimTypes.GitHubLogin, userAccount.GitHubLogin));
}
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(identity);
return new HeimdallCompletedSignIn(
principal,
bifrostIdentityService.BuildPrincipal(userAccount, payload.Provider ?? "heimdall"),
string.IsNullOrWhiteSpace(attempt.ReturnUrl) ? "/App" : attempt.ReturnUrl);
}
@ -206,6 +190,10 @@ public sealed class HeimdallAuthService(
userAccount.MemberProfile!.Nickname = displayName;
userAccount.MemberProfile.UpdatedAtUtc = now;
await bifrostIdentityService.EnsureIdentityAsync(
userAccount,
displayName,
cancellationToken);
if (grantMemberAccess)
{
ApplicationBootstrapper.EnsureRole(

View file

@ -14,6 +14,7 @@ public static class GitHubAuthenticationDefaults
public static class BifrostClaimTypes
{
public const string BifrostIdentity = "urn:bifrost:identity";
public const string GitHubLogin = "urn:bifrost:github-login";
public const string HeimdallAccountId = "urn:bifrost:heimdall-account-id";
public const string AuthProvider = "urn:bifrost:auth-provider";

View file

@ -0,0 +1,153 @@
using System.Security.Claims;
using System.Text.RegularExpressions;
using Bifrost.Web.Data;
using Bifrost.Web.Domain;
using Bifrost.Web.Features.Shared;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.EntityFrameworkCore;
namespace Bifrost.Web.Features.Membership;
public sealed partial class BifrostIdentityService(
BifrostDbContext dbContext,
TimeProvider timeProvider)
{
public async Task<UserAccount> RegisterNativeAsync(
string identity,
string? displayName,
CancellationToken cancellationToken)
{
var normalizedIdentity = NormalizeIdentity(identity);
var exists = await dbContext.UserAccounts.AnyAsync(
x => x.NormalizedBifrostIdentity == normalizedIdentity,
cancellationToken);
if (exists)
{
throw new BifrostIdentityException("That Bifrost identity is already registered.");
}
var now = timeProvider.GetUtcNow();
var publicIdentity = ToPublicIdentity(normalizedIdentity);
var resolvedDisplayName = string.IsNullOrWhiteSpace(displayName)
? publicIdentity
: displayName.Trim();
var userAccount = new UserAccount
{
BifrostIdentity = publicIdentity,
NormalizedBifrostIdentity = normalizedIdentity,
DisplayName = resolvedDisplayName,
CreatedAtUtc = now,
LastSeenAtUtc = now,
MemberProfile = new MemberProfile
{
Nickname = resolvedDisplayName,
Headline = "Bifrost-native identity",
UpdatedAtUtc = now
},
Membership = new Bifrost.Web.Domain.Membership
{
Status = MembershipStatus.Authenticated,
CreatedAtUtc = now,
Notes = "Registered with native Bifrost identity"
}
};
dbContext.UserAccounts.Add(userAccount);
await dbContext.SaveChangesAsync(cancellationToken);
return userAccount;
}
public async Task EnsureIdentityAsync(
UserAccount userAccount,
string preferredIdentity,
CancellationToken cancellationToken)
{
if (!string.IsNullOrWhiteSpace(userAccount.NormalizedBifrostIdentity))
{
return;
}
var normalizedBase = NormalizeCandidate(preferredIdentity);
var normalizedIdentity = normalizedBase;
for (var suffix = 2; await IdentityExistsAsync(userAccount.Id, normalizedIdentity, cancellationToken); suffix++)
{
normalizedIdentity = $"{normalizedBase}-{suffix}";
}
userAccount.BifrostIdentity = ToPublicIdentity(normalizedIdentity);
userAccount.NormalizedBifrostIdentity = normalizedIdentity;
}
public ClaimsPrincipal BuildPrincipal(UserAccount userAccount, string authProvider = "bifrost")
{
var claims = new List<Claim>
{
new(ClaimTypes.NameIdentifier, userAccount.Id.ToString()),
new(ClaimTypes.Name, userAccount.DisplayName),
new(BifrostClaimTypes.BifrostIdentity, userAccount.BifrostIdentity),
new(BifrostClaimTypes.AuthProvider, authProvider),
new(BifrostClaimTypes.DisplayName, userAccount.DisplayName),
new(BifrostClaimTypes.AvatarUrl, userAccount.AvatarUrl)
};
if (!string.IsNullOrWhiteSpace(userAccount.HeimdallAccountId))
{
claims.Add(new Claim(BifrostClaimTypes.HeimdallAccountId, userAccount.HeimdallAccountId));
}
if (!string.IsNullOrWhiteSpace(userAccount.GitHubLogin))
{
claims.Add(new Claim(BifrostClaimTypes.GitHubLogin, userAccount.GitHubLogin));
}
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
return new ClaimsPrincipal(identity);
}
public static string NormalizeIdentity(string identity)
{
var normalized = identity.Trim().ToLowerInvariant();
if (!IdentityPattern().IsMatch(normalized))
{
throw new BifrostIdentityException(
"Bifrost identity must be 3-80 characters and may contain letters, numbers, dots, underscores, or hyphens.");
}
return normalized;
}
private async Task<bool> IdentityExistsAsync(
Guid currentUserAccountId,
string normalizedIdentity,
CancellationToken cancellationToken) =>
await dbContext.UserAccounts.AnyAsync(
x => x.Id != currentUserAccountId && x.NormalizedBifrostIdentity == normalizedIdentity,
cancellationToken);
private static string NormalizeCandidate(string preferredIdentity)
{
var candidate = CandidateInvalidCharacters().Replace(
preferredIdentity.Trim().ToLowerInvariant(),
"-");
candidate = CandidateSeparators().Replace(candidate, "-").Trim('.', '_', '-');
if (candidate.Length > 80)
{
candidate = candidate[..80].Trim('.', '_', '-');
}
return candidate.Length >= 3 ? candidate : "user";
}
private static string ToPublicIdentity(string normalizedIdentity) => normalizedIdentity;
[GeneratedRegex("^[a-z0-9][a-z0-9._-]{1,78}[a-z0-9]$")]
private static partial Regex IdentityPattern();
[GeneratedRegex("[^a-z0-9._-]+")]
private static partial Regex CandidateInvalidCharacters();
[GeneratedRegex("[._-]{2,}")]
private static partial Regex CandidateSeparators();
}
public sealed class BifrostIdentityException(string message) : InvalidOperationException(message);

View file

@ -10,6 +10,7 @@ namespace Bifrost.Web.Features.Membership;
public sealed class MembershipSynchronizationService(
BifrostDbContext dbContext,
BifrostIdentityService bifrostIdentityService,
IOptions<BootstrapOptions> bootstrapOptions,
TimeProvider timeProvider)
{
@ -97,6 +98,11 @@ public sealed class MembershipSynchronizationService(
userAccount.MemberProfile.Nickname = userAccount.DisplayName;
}
await bifrostIdentityService.EnsureIdentityAsync(
userAccount,
userAccount.GitHubLogin,
cancellationToken);
if (invitation is not null && invitation.AcceptedByUserAccountId is null)
{
invitation.AcceptedByUserAccountId = userAccount.Id;

View file

@ -30,11 +30,17 @@ public sealed class CurrentBifrostActorAccessor(
return Cache(httpContext, CurrentBifrostActor.Anonymous);
}
var bifrostIdentity = httpContext.User.FindFirstValue(BifrostClaimTypes.BifrostIdentity);
var normalizedBifrostIdentity = string.IsNullOrWhiteSpace(bifrostIdentity)
? string.Empty
: BifrostIdentityService.NormalizeIdentity(bifrostIdentity);
var heimdallAccountId = httpContext.User.FindFirstValue(BifrostClaimTypes.HeimdallAccountId);
var gitHubId = httpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
var hasGitHubUserId = long.TryParse(gitHubId, out var gitHubUserId);
if (string.IsNullOrWhiteSpace(heimdallAccountId) && !hasGitHubUserId)
if (string.IsNullOrWhiteSpace(normalizedBifrostIdentity) &&
string.IsNullOrWhiteSpace(heimdallAccountId) &&
!hasGitHubUserId)
{
return Cache(httpContext, CurrentBifrostActor.Anonymous);
}
@ -47,7 +53,8 @@ public sealed class CurrentBifrostActorAccessor(
.Include(x => x.Membership!)
.ThenInclude(x => x.TierSnapshots)
.SingleOrDefaultAsync(
x => (!string.IsNullOrWhiteSpace(heimdallAccountId) && x.HeimdallAccountId == heimdallAccountId) ||
x => (!string.IsNullOrWhiteSpace(normalizedBifrostIdentity) && x.NormalizedBifrostIdentity == normalizedBifrostIdentity) ||
(!string.IsNullOrWhiteSpace(heimdallAccountId) && x.HeimdallAccountId == heimdallAccountId) ||
(hasGitHubUserId && x.GitHubUserId == gitHubUserId),
cancellationToken);

View file

@ -88,6 +88,7 @@ builder.Services.AddScoped<AgentDispatchRunService>();
builder.Services.AddScoped<AgentTransportReceiptService>();
builder.Services.AddScoped<GovernanceActivityReceiptService>();
builder.Services.AddScoped<MembershipSynchronizationService>();
builder.Services.AddScoped<BifrostIdentityService>();
builder.Services.AddScoped<GitHubWebhookService>();
builder.Services.AddScoped<MotionGovernanceService>();
builder.Services.AddScoped<MotionEveSurfaceService>();
@ -282,6 +283,38 @@ app.MapGet("/auth/sign-in", async (HttpContext httpContext, IOptions<GitHubOAuth
new() { RedirectUri = returnUrl });
}).AllowAnonymous();
app.MapPost("/auth/bifrost/register", async (
NativeBifrostRegistrationRequest request,
HttpContext httpContext,
BifrostIdentityService bifrostIdentityService,
CancellationToken cancellationToken) =>
{
try
{
var userAccount = await bifrostIdentityService.RegisterNativeAsync(
request.Identity,
request.DisplayName,
cancellationToken);
await httpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
bifrostIdentityService.BuildPrincipal(userAccount));
var returnUrl = string.IsNullOrWhiteSpace(request.ReturnUrl) ? "/App" : request.ReturnUrl;
return JsonResult(
new NativeBifrostRegistrationResponse(
userAccount.Id,
userAccount.BifrostIdentity,
userAccount.DisplayName,
userAccount.Membership?.Status.ToString() ?? MembershipStatus.Authenticated.ToString(),
returnUrl),
appJsonSerializerOptions);
}
catch (BifrostIdentityException error)
{
return Results.Text(error.Message, statusCode: StatusCodes.Status400BadRequest);
}
}).AllowAnonymous();
app.MapGet("/auth/heimdall/{provider}", async (
string provider,
HttpContext httpContext,
@ -894,3 +927,15 @@ static bool HasValidLocalBridgeToken(HttpRequest request, BridgeOptions bridgeOp
}
public partial class Program;
public sealed record NativeBifrostRegistrationRequest(
string Identity,
string? DisplayName,
string? ReturnUrl);
public sealed record NativeBifrostRegistrationResponse(
Guid UserAccountId,
string BifrostIdentity,
string DisplayName,
string MembershipStatus,
string ReturnUrl);