Heimdall sign-in: the attempt is a cookie, and a code the browser presents is redeemed at Heimdall
Start puts a per-attempt nonce in the returnTo it sends Heimdall and keeps the attempt (provider, member flag, local return path, expiry) in a Data Protection cookie named for that nonce. Heimdall's completion page sends the browser to /auth/heimdall/complete with a code in the URL fragment; the page posts it back, Bifrost redeems it at Heimdall, requires the redeemed returnTo to name the cookie's nonce, verifies the access token for the redeemed account, and signs that browser in. Deleted: the callback route, the wait route, the server-side attempt store, the pending state and the backend_callback handoff. Added: LocalReturnPath for return targets, Heimdall:AppSecret sent as x-heimdall-app-secret (member starts are refused without it), a short timeout on the key fetch, and a key lookup that does not hold the fetch gate for cached keys. Refusals at the completion route all answer one redirect and log a fixed reason. Tests are rewritten against a fake Heimdall with start and redeem routes. Not compile-checked by this commit alone; later commits record the verification. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
1ab67da47b
commit
bad2117ea8
10 changed files with 1581 additions and 1132 deletions
|
|
@ -124,18 +124,11 @@ builder.Services.AddScoped<ReadinessService>();
|
|||
builder.Services.AddScoped<ApplicationBootstrapper>();
|
||||
builder.Services.AddSingleton<StartupConfigurationValidator>();
|
||||
builder.Services.AddScoped<IAuthorizationHandler, ActiveMemberAuthorizationHandler>();
|
||||
builder.Services.AddSingleton<HeimdallAuthAttemptStore>();
|
||||
builder.Services.AddHttpClient<HeimdallAuthService>((serviceProvider, client) =>
|
||||
{
|
||||
var options = serviceProvider.GetRequiredService<IOptions<HeimdallOptions>>().Value;
|
||||
client.BaseAddress = new Uri(options.BaseUrl.TrimEnd('/'));
|
||||
});
|
||||
HeimdallAuthService.ConfigureClient(client, serviceProvider.GetRequiredService<IOptions<HeimdallOptions>>().Value));
|
||||
builder.Services.AddSingleton<HeimdallTokenVerifier>();
|
||||
builder.Services.AddHttpClient(HeimdallTokenVerifier.ClientName, (serviceProvider, client) =>
|
||||
{
|
||||
var options = serviceProvider.GetRequiredService<IOptions<HeimdallOptions>>().Value;
|
||||
client.BaseAddress = new Uri(options.BaseUrl.TrimEnd('/'));
|
||||
});
|
||||
HeimdallTokenVerifier.ConfigureClient(client, serviceProvider.GetRequiredService<IOptions<HeimdallOptions>>().Value));
|
||||
builder.Services.AddHttpClient<StripeCheckoutService>(client =>
|
||||
{
|
||||
client.BaseAddress = new Uri("https://api.stripe.com/");
|
||||
|
|
@ -305,22 +298,18 @@ app.MapPost("/github/webhooks", async (
|
|||
|
||||
app.MapGet("/auth/sign-in", async (HttpContext httpContext, IOptions<GitHubOAuthOptions> gitHubOptions) =>
|
||||
{
|
||||
var returnUrl = httpContext.Request.Query["returnUrl"].ToString();
|
||||
if (string.IsNullOrWhiteSpace(returnUrl))
|
||||
{
|
||||
returnUrl = "/App";
|
||||
}
|
||||
var returnPath = LocalReturnPath.Parse(httpContext.Request.Query["returnUrl"].ToString());
|
||||
|
||||
var provider = httpContext.Request.Query["provider"].ToString();
|
||||
if (string.IsNullOrWhiteSpace(provider))
|
||||
{
|
||||
await WriteSignInChooserAsync(httpContext, returnUrl);
|
||||
await WriteSignInChooserAsync(httpContext, returnPath.Value);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!provider.Equals("github", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
httpContext.Response.Redirect($"/auth/heimdall/{Uri.EscapeDataString(provider)}?returnUrl={Uri.EscapeDataString(returnUrl)}");
|
||||
httpContext.Response.Redirect($"/auth/heimdall/{Uri.EscapeDataString(provider)}?returnUrl={Uri.EscapeDataString(returnPath.Value)}");
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -332,7 +321,7 @@ app.MapGet("/auth/sign-in", async (HttpContext httpContext, IOptions<GitHubOAuth
|
|||
|
||||
await httpContext.ChallengeAsync(
|
||||
GitHubAuthenticationDefaults.AuthenticationScheme,
|
||||
new() { RedirectUri = returnUrl });
|
||||
new() { RedirectUri = returnPath.Value });
|
||||
}).AllowAnonymous();
|
||||
|
||||
app.MapPost("/auth/bifrost/register", async (
|
||||
|
|
@ -372,16 +361,12 @@ app.MapGet("/auth/heimdall/{provider}", async (
|
|||
HttpContext httpContext,
|
||||
HeimdallAuthService heimdallAuthService,
|
||||
IOptions<BifrostHostOptions> hostOptions,
|
||||
ILogger<HeimdallAuthService> logger,
|
||||
CancellationToken cancellationToken) =>
|
||||
{
|
||||
try
|
||||
{
|
||||
var returnUrl = httpContext.Request.Query["returnUrl"].ToString();
|
||||
if (string.IsNullOrWhiteSpace(returnUrl))
|
||||
{
|
||||
returnUrl = "/App";
|
||||
}
|
||||
|
||||
var returnPath = LocalReturnPath.Parse(httpContext.Request.Query["returnUrl"].ToString());
|
||||
var requireMemberAccess = string.Equals(
|
||||
httpContext.Request.Query["access"].ToString(),
|
||||
"member",
|
||||
|
|
@ -390,34 +375,20 @@ app.MapGet("/auth/heimdall/{provider}", async (
|
|||
var start = await heimdallAuthService.StartAsync(
|
||||
provider,
|
||||
hostOptions.Value.PublicBaseUrl,
|
||||
returnUrl,
|
||||
returnPath,
|
||||
requireMemberAccess,
|
||||
cancellationToken);
|
||||
|
||||
httpContext.Response.Cookies.Append(HeimdallBindingCookie.Name, start.Binding, HeimdallBindingCookie.Options());
|
||||
httpContext.Response.Cookies.Append(
|
||||
HeimdallAttemptCookie.NameFor(start.Nonce),
|
||||
start.CookieValue,
|
||||
HeimdallAttemptCookie.Options());
|
||||
return Results.Redirect(start.AuthorizationUrl.ToString());
|
||||
}
|
||||
catch (HeimdallAuthException error)
|
||||
{
|
||||
return Results.Redirect($"/?auth=heimdall-error&detail={Uri.EscapeDataString(error.Message)}");
|
||||
}
|
||||
}).AllowAnonymous();
|
||||
|
||||
app.MapPost("/auth/heimdall/callback", async (
|
||||
HeimdallBackendCallbackPayload payload,
|
||||
HeimdallAuthService heimdallAuthService,
|
||||
ILogger<HeimdallAuthService> logger,
|
||||
CancellationToken cancellationToken) =>
|
||||
{
|
||||
try
|
||||
{
|
||||
await heimdallAuthService.StoreBackendCallbackAsync(payload, cancellationToken);
|
||||
return Results.Accepted();
|
||||
}
|
||||
catch (HeimdallAuthException error)
|
||||
{
|
||||
logger.LogWarning("Heimdall callback refused: {Reason}", error.Message);
|
||||
return Results.BadRequest("Heimdall callback refused.");
|
||||
logger.LogWarning("Heimdall start refused: {Reason}", error.Message);
|
||||
return Results.Redirect(HeimdallAuthService.ErrorRedirect);
|
||||
}
|
||||
}).AllowAnonymous();
|
||||
|
||||
|
|
@ -543,37 +514,46 @@ eveGovernance.MapGet("/surface", async (
|
|||
"application/json");
|
||||
});
|
||||
|
||||
app.MapGet("/auth/heimdall/wait", async (
|
||||
app.MapGet("/auth/heimdall/complete", (HttpContext httpContext) =>
|
||||
{
|
||||
httpContext.Response.Headers.CacheControl = "no-store";
|
||||
httpContext.Response.Headers["Referrer-Policy"] = "no-referrer";
|
||||
return Results.Content(HeimdallCompletePage.Html, "text/html", System.Text.Encoding.UTF8);
|
||||
}).AllowAnonymous();
|
||||
|
||||
app.MapPost("/auth/heimdall/complete", async (
|
||||
HttpContext httpContext,
|
||||
HeimdallAuthService heimdallAuthService,
|
||||
IOptions<BifrostHostOptions> hostOptions,
|
||||
ILogger<HeimdallAuthService> logger,
|
||||
CancellationToken cancellationToken) =>
|
||||
{
|
||||
var attemptId = httpContext.Request.Query["attemptId"].ToString();
|
||||
if (string.IsNullOrWhiteSpace(attemptId))
|
||||
{
|
||||
return Results.Redirect("/?auth=heimdall-error&detail=missing-attempt-id");
|
||||
}
|
||||
|
||||
var form = await ReadFormOrNullAsync(httpContext.Request, cancellationToken);
|
||||
var attempt = form?["attempt"].ToString();
|
||||
var cookieName = HeimdallAttemptCookie.NameFor(attempt);
|
||||
try
|
||||
{
|
||||
var signIn = await heimdallAuthService.CompleteAttemptAsync(
|
||||
attemptId,
|
||||
httpContext.Request.Cookies[HeimdallBindingCookie.Name],
|
||||
var signIn = await heimdallAuthService.CompleteAsync(
|
||||
hostOptions.Value.PublicBaseUrl,
|
||||
attempt,
|
||||
cookieName is null ? null : httpContext.Request.Cookies[cookieName],
|
||||
form?["code"].ToString(),
|
||||
cancellationToken);
|
||||
await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, signIn.Principal);
|
||||
httpContext.Response.Cookies.Delete(HeimdallBindingCookie.Name, HeimdallBindingCookie.Options());
|
||||
return Results.Redirect(signIn.RedirectUri);
|
||||
}
|
||||
catch (HeimdallAuthPendingException)
|
||||
{
|
||||
httpContext.Response.Headers.Append("Refresh", "2");
|
||||
return Results.Text("Waiting for Heimdall sign-in to complete.", "text/plain");
|
||||
httpContext.Response.Cookies.Delete(cookieName!, HeimdallAttemptCookie.Options());
|
||||
return Results.LocalRedirect(signIn.ReturnPath.Value);
|
||||
}
|
||||
catch (HeimdallAuthException error)
|
||||
{
|
||||
return Results.Redirect($"/?auth=heimdall-error&detail={Uri.EscapeDataString(error.Message)}");
|
||||
logger.LogWarning("Heimdall completion refused: {Reason}", error.Message);
|
||||
if (cookieName is not null)
|
||||
{
|
||||
httpContext.Response.Cookies.Delete(cookieName, HeimdallAttemptCookie.Options());
|
||||
}
|
||||
|
||||
return Results.Redirect(HeimdallAuthService.ErrorRedirect);
|
||||
}
|
||||
}).AllowAnonymous();
|
||||
}).AllowAnonymous().DisableAntiforgery();
|
||||
|
||||
app.MapPost("/auth/sign-out", async (HttpContext httpContext) =>
|
||||
{
|
||||
|
|
@ -591,6 +571,23 @@ static IResult JsonResult<T>(T value, JsonSerializerOptions options, int statusC
|
|||
"application/json",
|
||||
statusCode: statusCode);
|
||||
|
||||
static async Task<IFormCollection?> ReadFormOrNullAsync(HttpRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!request.HasFormContentType)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return await request.ReadFormAsync(cancellationToken);
|
||||
}
|
||||
catch (Exception error) when (error is InvalidDataException or BadHttpRequestException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
static async Task WriteSignInChooserAsync(HttpContext httpContext, string returnUrl)
|
||||
{
|
||||
httpContext.Response.ContentType = "text/html; charset=utf-8";
|
||||
|
|
|
|||
Loading…
Reference in a new issue