Heimdall sign-in: accept only a Heimdall-signed token for an attempt Start issued, in the browser that started it

The callback verifies the EdDSA access token against Heimdall's JWKS and takes the
account, display name and member access from its claims; attempts expire, are
bounded, are completed only if issued, and are redeemed once with a per-attempt
binding cookie. Not yet built or tested; the first verification run follows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-10-11 02:54:13 +02:00
commit f3b8acbbc5
6 changed files with 1534 additions and 80 deletions

View file

@ -11,6 +11,7 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="BouncyCastle.Cryptography" Version="2.4.0" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.0" />
</ItemGroup>

View file

@ -17,6 +17,7 @@ namespace Bifrost.Web.Features.Heimdall;
public sealed class HeimdallAuthService(
HttpClient httpClient,
HeimdallAuthAttemptStore attemptStore,
HeimdallTokenVerifier tokenVerifier,
BifrostDbContext dbContext,
BifrostIdentityService bifrostIdentityService,
IOptions<HeimdallOptions> heimdallOptions,
@ -38,7 +39,7 @@ public sealed class HeimdallAuthService(
{
if (!AllowedProviders.Contains(provider))
{
throw new HeimdallAuthException($"Unsupported Heimdall provider '{provider}'.");
throw new HeimdallAuthException("Unsupported Heimdall provider.");
}
var options = heimdallOptions.Value;
@ -67,8 +68,7 @@ public sealed class HeimdallAuthService(
if (!response.IsSuccessStatusCode)
{
var detail = await response.Content.ReadAsStringAsync(cancellationToken);
throw new HeimdallAuthException($"Heimdall rejected {provider} auth start: {detail}");
throw new HeimdallAuthException("Heimdall rejected the auth start.");
}
var payload = await response.Content.ReadFromJsonAsync<HeimdallStartResponse>(cancellationToken);
@ -77,59 +77,59 @@ public sealed class HeimdallAuthService(
throw new HeimdallAuthException("Heimdall auth start returned no authorization URL.");
}
attemptStore.Create(attemptId, returnUrl);
attemptStore.SetRequiresMemberAccess(attemptId, requireMemberAccess);
return new HeimdallAuthStartResult(new Uri(payload.AuthorizationUrl, UriKind.Absolute), attemptId);
var binding = attemptStore.Create(attemptId, provider, returnUrl, requireMemberAccess);
return new HeimdallAuthStartResult(new Uri(payload.AuthorizationUrl, UriKind.Absolute), attemptId, binding);
}
public void StoreBackendCallback(HeimdallBackendCallbackPayload payload)
public async Task StoreBackendCallbackAsync(
HeimdallBackendCallbackPayload payload,
CancellationToken cancellationToken)
{
if (!string.Equals(payload.AppSlug, heimdallOptions.Value.AppSlug, StringComparison.OrdinalIgnoreCase))
{
throw new HeimdallAuthException("Heimdall callback targeted a different app.");
}
if (string.IsNullOrWhiteSpace(payload.AttemptId))
{
throw new HeimdallAuthException("Heimdall callback omitted attempt id.");
}
attemptStore.Complete(payload.AttemptId, payload);
if (string.IsNullOrWhiteSpace(payload.AccessToken))
{
throw new HeimdallAuthException("Heimdall callback carried no access token.");
}
var identity = await tokenVerifier.VerifyAsync(payload.AccessToken, payload.Account?.Id, cancellationToken);
attemptStore.Complete(payload.AttemptId, identity);
}
public async Task<HeimdallCompletedSignIn> CompleteAttemptAsync(
string attemptId,
string? binding,
CancellationToken cancellationToken)
{
var attempt = attemptStore.TryTake(attemptId)
?? throw new HeimdallAuthPendingException("Heimdall has not delivered this auth attempt yet.");
var payload = attempt.Payload
?? throw new HeimdallAuthPendingException("Heimdall has not delivered this auth attempt yet.");
if (!payload.IsSuccessful)
{
throw new HeimdallAuthException(payload.ErrorDescription ?? payload.Error ?? "Heimdall auth did not succeed.");
}
if (attempt.RequiresMemberAccess && !payload.HasMemberAccess)
var attempt = attemptStore.TryTake(attemptId, binding);
var identity = attempt.Identity;
if (attempt.RequiresMemberAccess && !identity.HasMemberAccess)
{
throw new HeimdallAuthException("Heimdall did not grant Bifrost member access.");
}
var userAccount = await UpsertUserAccountAsync(payload, attempt.RequiresMemberAccess, cancellationToken);
var userAccount = await UpsertUserAccountAsync(
identity,
attempt.Provider,
attempt.RequiresMemberAccess,
cancellationToken);
return new HeimdallCompletedSignIn(
bifrostIdentityService.BuildPrincipal(userAccount, payload.Provider ?? "heimdall"),
bifrostIdentityService.BuildPrincipal(userAccount, attempt.Provider),
string.IsNullOrWhiteSpace(attempt.ReturnUrl) ? "/App" : attempt.ReturnUrl);
}
private async Task<UserAccount> UpsertUserAccountAsync(
HeimdallBackendCallbackPayload payload,
HeimdallVerifiedIdentity identity,
string provider,
bool grantMemberAccess,
CancellationToken cancellationToken)
{
var now = timeProvider.GetUtcNow();
var accountId = payload.Account?.Id ?? throw new HeimdallAuthException("Heimdall response omitted account id.");
var displayName = payload.Account.DisplayName ?? accountId;
var accountId = identity.AccountId;
var displayName = identity.DisplayName ?? accountId;
var userAccount = await dbContext.UserAccounts
.Include(x => x.MemberProfile)
@ -150,7 +150,7 @@ public sealed class HeimdallAuthService(
MemberProfile = new MemberProfile
{
Nickname = displayName,
Headline = $"Verified through Heimdall {payload.Provider}",
Headline = $"Verified through Heimdall {provider}",
UpdatedAtUtc = now
},
Membership = new Bifrost.Web.Domain.Membership
@ -160,7 +160,7 @@ public sealed class HeimdallAuthService(
ApprovedAtUtc = grantMemberAccess ? now : null,
Notes = grantMemberAccess
? "Activated by Heimdall member access claim"
: $"Identity verified through Heimdall {payload.Provider}"
: $"Identity verified through Heimdall {provider}"
}
};
dbContext.UserAccounts.Add(userAccount);
@ -173,7 +173,7 @@ public sealed class HeimdallAuthService(
{
UserAccountId = userAccount.Id,
Nickname = displayName,
Headline = $"Verified through Heimdall {payload.Provider}",
Headline = $"Verified through Heimdall {provider}",
UpdatedAtUtc = now
};
userAccount.Membership ??= new Bifrost.Web.Domain.Membership
@ -264,45 +264,96 @@ public class HeimdallAuthException(string message) : InvalidOperationException(m
public sealed class HeimdallAuthPendingException(string message) : HeimdallAuthException(message);
public sealed record HeimdallAuthStartResult(Uri AuthorizationUrl, string AttemptId);
public sealed record HeimdallAuthStartResult(Uri AuthorizationUrl, string AttemptId, string Binding);
public sealed record HeimdallCompletedSignIn(ClaimsPrincipal Principal, string RedirectUri);
public sealed class HeimdallAuthAttemptStore
/// <summary>
/// Attempts Start issued. An attempt lives for <see cref="Lifetime"/>, is completed only by a verified
/// Heimdall identity, and is redeemed once by the browser that holds its binding value. The store holds at
/// most <see cref="Capacity"/> attempts; a full store drops the one that expires first.
/// </summary>
public sealed class HeimdallAuthAttemptStore(TimeProvider timeProvider)
{
private readonly ConcurrentDictionary<string, HeimdallAuthAttempt> _attempts = new(StringComparer.Ordinal);
public static readonly TimeSpan Lifetime = TimeSpan.FromMinutes(10);
public const int Capacity = 1024;
public void Create(string attemptId, string returnUrl)
private readonly object _gate = new();
private readonly Dictionary<string, HeimdallAuthAttempt> _attempts = new(StringComparer.Ordinal);
public string Create(string attemptId, string provider, string returnUrl, bool requiresMemberAccess)
{
_attempts[attemptId] = new HeimdallAuthAttempt(returnUrl, null);
var now = timeProvider.GetUtcNow();
var binding = Microsoft.AspNetCore.WebUtilities.WebEncoders.Base64UrlEncode(
System.Security.Cryptography.RandomNumberGenerator.GetBytes(32));
lock (_gate)
{
while (_attempts.Count >= Capacity)
{
_attempts.Remove(_attempts.MinBy(x => x.Value.ExpiresAt).Key);
}
_attempts[attemptId] = new HeimdallAuthAttempt(
provider, returnUrl, requiresMemberAccess, binding, now + Lifetime, null);
}
return binding;
}
public void SetRequiresMemberAccess(string attemptId, bool requiresMemberAccess)
public void Complete(string attemptId, HeimdallVerifiedIdentity identity)
{
_attempts.AddOrUpdate(
attemptId,
_ => new HeimdallAuthAttempt("/App", null, requiresMemberAccess),
(_, existing) => existing with { RequiresMemberAccess = requiresMemberAccess });
lock (_gate)
{
if (!_attempts.TryGetValue(attemptId, out var attempt) ||
attempt.ExpiresAt <= timeProvider.GetUtcNow() ||
attempt.Identity is not null)
{
throw new HeimdallAuthException("Heimdall callback did not match a pending attempt.");
}
_attempts[attemptId] = attempt with { Identity = identity };
}
}
public void Complete(string attemptId, HeimdallBackendCallbackPayload payload)
public HeimdallRedeemedAttempt TryTake(string attemptId, string? binding)
{
_attempts.AddOrUpdate(
attemptId,
_ => new HeimdallAuthAttempt(payload.ReturnTo ?? "/App", payload),
(_, existing) => existing with { Payload = payload });
}
lock (_gate)
{
if (!_attempts.TryGetValue(attemptId, out var attempt) ||
attempt.ExpiresAt <= timeProvider.GetUtcNow() ||
binding is null ||
!System.Security.Cryptography.CryptographicOperations.FixedTimeEquals(
System.Text.Encoding.UTF8.GetBytes(binding),
System.Text.Encoding.UTF8.GetBytes(attempt.Binding)))
{
throw new HeimdallAuthException("Heimdall auth attempt is not valid for this browser.");
}
public HeimdallAuthAttempt? TryTake(string attemptId)
{
return _attempts.TryRemove(attemptId, out var attempt) ? attempt : null;
if (attempt.Identity is null)
{
throw new HeimdallAuthPendingException("Heimdall has not delivered this auth attempt yet.");
}
_attempts.Remove(attemptId);
return new HeimdallRedeemedAttempt(
attempt.Provider, attempt.ReturnUrl, attempt.RequiresMemberAccess, attempt.Identity);
}
}
}
public sealed record HeimdallAuthAttempt(
string Provider,
string ReturnUrl,
HeimdallBackendCallbackPayload? Payload,
bool RequiresMemberAccess = false);
bool RequiresMemberAccess,
string Binding,
DateTimeOffset ExpiresAt,
HeimdallVerifiedIdentity? Identity);
public sealed record HeimdallRedeemedAttempt(
string Provider,
string ReturnUrl,
bool RequiresMemberAccess,
HeimdallVerifiedIdentity Identity);
public sealed record HeimdallStartRequest(
[property: JsonPropertyName("appSlug")] string AppSlug,
@ -333,29 +384,22 @@ public sealed record HeimdallStartResponse(
public sealed record HeimdallBackendCallbackPayload(
[property: JsonPropertyName("attemptId")] string AttemptId,
[property: JsonPropertyName("appSlug")] string? AppSlug,
[property: JsonPropertyName("status")] string? Status,
[property: JsonPropertyName("provider")] string? Provider,
[property: JsonPropertyName("returnTo")] string? ReturnTo,
[property: JsonPropertyName("error")] string? Error,
[property: JsonPropertyName("errorDescription")] string? ErrorDescription,
[property: JsonPropertyName("account")] HeimdallAccount? Account,
[property: JsonPropertyName("sharedCapabilities")] string[]? SharedCapabilities,
[property: JsonPropertyName("entitlements")] HeimdallEntitlements? Entitlements)
{
public bool IsSuccessful => string.Equals(Status, "success", StringComparison.OrdinalIgnoreCase);
public bool HasMemberAccess =>
SharedCapabilities?.Any(capability =>
string.Equals(capability, "member_access", StringComparison.OrdinalIgnoreCase) ||
string.Equals(capability, "app_access", StringComparison.OrdinalIgnoreCase)) == true ||
Entitlements?.Facts?.Any(fact =>
string.Equals(fact, "entitlement.app_access", StringComparison.OrdinalIgnoreCase)) == true;
}
[property: JsonPropertyName("accessToken")] string? AccessToken,
[property: JsonPropertyName("account")] HeimdallAccount? Account);
public sealed record HeimdallAccount(
[property: JsonPropertyName("id")] string Id,
[property: JsonPropertyName("displayName")] string? DisplayName);
[property: JsonPropertyName("id")] string Id);
public sealed record HeimdallEntitlements(
[property: JsonPropertyName("facts")] string[]? Facts);
public static class HeimdallBindingCookie
{
public const string Name = "bifrost_heimdall_binding";
public static CookieOptions Options() => new()
{
HttpOnly = true,
Secure = true,
SameSite = SameSiteMode.Lax,
Path = "/auth/heimdall",
MaxAge = HeimdallAuthAttemptStore.Lifetime
};
}

View file

@ -0,0 +1,249 @@
using System.Text.Json;
using Bifrost.Web.Configuration;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Options;
using Org.BouncyCastle.Math.EC.Rfc8032;
namespace Bifrost.Web.Features.Heimdall;
/// <summary>
/// The identity a Heimdall-signed access token asserts. Everything here comes from verified claims.
/// </summary>
public sealed record HeimdallVerifiedIdentity(string AccountId, string? DisplayName, bool HasMemberAccess);
/// <summary>
/// Verifies Heimdall's access tokens (EdDSA) against Heimdall's published JWKS. Heimdall is the issuer
/// at <see cref="HeimdallOptions.BaseUrl"/>; the audience is this app's slug. Failures name a rule and
/// never echo the token or any of its contents.
/// </summary>
public sealed class HeimdallTokenVerifier(
HttpClient httpClient,
IOptions<HeimdallOptions> heimdallOptions,
TimeProvider timeProvider)
{
public const string TokenType = "heimdall_access";
internal static readonly TimeSpan ClockSkew = TimeSpan.FromSeconds(60);
internal static readonly TimeSpan KeyRefreshInterval = TimeSpan.FromSeconds(30);
internal static readonly TimeSpan KeyMaxAge = TimeSpan.FromHours(1);
private static readonly string[] MemberCapabilities = ["member_access", "app_access"];
private readonly SemaphoreSlim _fetchGate = new(1, 1);
private Dictionary<string, byte[]> _keys = new(StringComparer.Ordinal);
private DateTimeOffset _fetchedAt = DateTimeOffset.MinValue;
private DateTimeOffset _attemptedAt = DateTimeOffset.MinValue;
public async Task<HeimdallVerifiedIdentity> VerifyAsync(
string token,
string? payloadAccountId,
CancellationToken cancellationToken)
{
var options = heimdallOptions.Value;
var parts = token.Split('.');
if (parts.Length != 3)
{
throw Refuse("token is not a compact JWS");
}
byte[] headerBytes, payloadBytes, signature;
try
{
headerBytes = WebEncoders.Base64UrlDecode(parts[0]);
payloadBytes = WebEncoders.Base64UrlDecode(parts[1]);
signature = WebEncoders.Base64UrlDecode(parts[2]);
}
catch (FormatException)
{
throw Refuse("token is not base64url");
}
string kid;
try
{
using var header = JsonDocument.Parse(headerBytes);
if (header.RootElement.ValueKind != JsonValueKind.Object ||
StringClaim(header.RootElement, "alg") != "EdDSA")
{
throw Refuse("token algorithm is not EdDSA");
}
kid = StringClaim(header.RootElement, "kid") is { Length: > 0 } found
? found
: throw Refuse("token has no key id");
}
catch (JsonException)
{
throw Refuse("token header is not JSON");
}
var publicKey = await FindKeyAsync(kid, cancellationToken);
if (publicKey is null)
{
throw Refuse("token key is not published");
}
var signingInput = System.Text.Encoding.ASCII.GetBytes($"{parts[0]}.{parts[1]}");
if (signature.Length != Ed25519.SignatureSize ||
!Ed25519.Verify(signature, 0, publicKey, 0, signingInput, 0, signingInput.Length))
{
throw Refuse("token signature is invalid");
}
try
{
using var payload = JsonDocument.Parse(payloadBytes);
return CheckClaims(payload.RootElement, options, payloadAccountId);
}
catch (JsonException)
{
throw Refuse("token payload is not JSON");
}
}
private HeimdallVerifiedIdentity CheckClaims(JsonElement claims, HeimdallOptions options, string? payloadAccountId)
{
if (claims.ValueKind != JsonValueKind.Object)
{
throw Refuse("token payload is not an object");
}
if (StringClaim(claims, "iss") != options.BaseUrl.TrimEnd('/'))
{
throw Refuse("token issuer is not Heimdall");
}
if (StringClaim(claims, "aud") != options.AppSlug)
{
throw Refuse("token audience is not this app");
}
if (StringClaim(claims, "typ") != TokenType)
{
throw Refuse("token type is not an access token");
}
if (!claims.TryGetProperty("app", out var app) ||
app.ValueKind != JsonValueKind.Object ||
StringClaim(app, "slug") != options.AppSlug)
{
throw Refuse("token app is not this app");
}
var now = timeProvider.GetUtcNow();
if (NumericDate(claims, "nbf") is not { } notBefore || now < notBefore - ClockSkew)
{
throw Refuse("token is not yet valid");
}
if (NumericDate(claims, "exp") is not { } expires || now >= expires + ClockSkew)
{
throw Refuse("token has expired");
}
var subject = StringClaim(claims, "sub");
if (string.IsNullOrEmpty(subject) ||
subject != StringClaim(claims, "account_id") ||
subject != payloadAccountId)
{
throw Refuse("token subject does not match the account");
}
var capabilities = new List<string>();
if (claims.TryGetProperty("capabilities", out var list) && list.ValueKind == JsonValueKind.Array)
{
foreach (var capability in list.EnumerateArray())
{
if (capability.ValueKind == JsonValueKind.String)
{
capabilities.Add(capability.GetString()!);
}
}
}
return new HeimdallVerifiedIdentity(
subject,
StringClaim(claims, "display_name"),
capabilities.Any(capability => MemberCapabilities.Contains(capability, StringComparer.OrdinalIgnoreCase)));
}
private async Task<byte[]?> FindKeyAsync(string kid, CancellationToken cancellationToken)
{
await _fetchGate.WaitAsync(cancellationToken);
try
{
var now = timeProvider.GetUtcNow();
var stale = now - _fetchedAt >= KeyMaxAge;
if ((stale || !_keys.ContainsKey(kid)) && now - _attemptedAt >= KeyRefreshInterval)
{
_attemptedAt = now;
_keys = await FetchKeysAsync(cancellationToken);
_fetchedAt = now;
}
return _keys.GetValueOrDefault(kid);
}
finally
{
_fetchGate.Release();
}
}
private async Task<Dictionary<string, byte[]>> FetchKeysAsync(CancellationToken cancellationToken)
{
try
{
using var response = await httpClient.GetAsync("/.well-known/jwks.json", cancellationToken);
response.EnsureSuccessStatusCode();
await using var body = await response.Content.ReadAsStreamAsync(cancellationToken);
using var document = await JsonDocument.ParseAsync(body, cancellationToken: cancellationToken);
var keys = new Dictionary<string, byte[]>(StringComparer.Ordinal);
if (document.RootElement.TryGetProperty("keys", out var list) && list.ValueKind == JsonValueKind.Array)
{
foreach (var jwk in list.EnumerateArray())
{
if (jwk.ValueKind != JsonValueKind.Object ||
StringClaim(jwk, "kty") != "OKP" ||
StringClaim(jwk, "crv") != "Ed25519" ||
StringClaim(jwk, "kid") is not { Length: > 0 } id ||
StringClaim(jwk, "x") is not { } x)
{
continue;
}
var key = WebEncoders.Base64UrlDecode(x);
if (key.Length == Ed25519.PublicKeySize)
{
keys[id] = key;
}
}
}
return keys;
}
catch (Exception error) when (error is HttpRequestException or JsonException or FormatException)
{
throw Refuse("Heimdall keys could not be fetched");
}
}
private static string? StringClaim(JsonElement element, string name) =>
element.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String
? value.GetString()
: null;
private static DateTimeOffset? NumericDate(JsonElement element, string name)
{
if (!element.TryGetProperty(name, out var value) ||
value.ValueKind != JsonValueKind.Number ||
!value.TryGetInt64(out var seconds) ||
seconds is < 0 or > 253402300799)
{
return null;
}
return DateTimeOffset.FromUnixTimeSeconds(seconds);
}
private static HeimdallAuthException Refuse(string rule) => new($"Heimdall token refused: {rule}.");
}

View file

@ -130,6 +130,11 @@ builder.Services.AddHttpClient<HeimdallAuthService>((serviceProvider, client) =>
var options = serviceProvider.GetRequiredService<IOptions<HeimdallOptions>>().Value;
client.BaseAddress = new Uri(options.BaseUrl.TrimEnd('/'));
});
builder.Services.AddHttpClient<HeimdallTokenVerifier>((serviceProvider, client) =>
{
var options = serviceProvider.GetRequiredService<IOptions<HeimdallOptions>>().Value;
client.BaseAddress = new Uri(options.BaseUrl.TrimEnd('/'));
});
builder.Services.AddHttpClient<StripeCheckoutService>(client =>
{
client.BaseAddress = new Uri("https://api.stripe.com/");
@ -388,6 +393,7 @@ app.MapGet("/auth/heimdall/{provider}", async (
requireMemberAccess,
cancellationToken);
httpContext.Response.Cookies.Append(HeimdallBindingCookie.Name, start.Binding, HeimdallBindingCookie.Options());
return Results.Redirect(start.AuthorizationUrl.ToString());
}
catch (HeimdallAuthException error)
@ -396,18 +402,21 @@ app.MapGet("/auth/heimdall/{provider}", async (
}
}).AllowAnonymous();
app.MapPost("/auth/heimdall/callback", (
app.MapPost("/auth/heimdall/callback", async (
HeimdallBackendCallbackPayload payload,
HeimdallAuthService heimdallAuthService) =>
HeimdallAuthService heimdallAuthService,
ILogger<HeimdallAuthService> logger,
CancellationToken cancellationToken) =>
{
try
{
heimdallAuthService.StoreBackendCallback(payload);
await heimdallAuthService.StoreBackendCallbackAsync(payload, cancellationToken);
return Results.Accepted();
}
catch (HeimdallAuthException error)
{
return Results.BadRequest(error.Message);
logger.LogWarning("Heimdall callback refused: {Reason}", error.Message);
return Results.BadRequest("Heimdall callback refused.");
}
}).AllowAnonymous();
@ -546,8 +555,12 @@ app.MapGet("/auth/heimdall/wait", async (
try
{
var signIn = await heimdallAuthService.CompleteAttemptAsync(attemptId, cancellationToken);
var signIn = await heimdallAuthService.CompleteAttemptAsync(
attemptId,
httpContext.Request.Cookies[HeimdallBindingCookie.Name],
cancellationToken);
await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, signIn.Principal);
httpContext.Response.Cookies.Delete(HeimdallBindingCookie.Name, HeimdallBindingCookie.Options());
return Results.Redirect(signIn.RedirectUri);
}
catch (HeimdallAuthPendingException)