Registration form: origin guard, skip button, identity checks before spending, caps and error links
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
185cfcd0e7
commit
d47f1d5e9d
11 changed files with 376 additions and 56 deletions
|
|
@ -12,11 +12,11 @@ public sealed partial class BifrostIdentityService(
|
|||
BifrostDbContext dbContext,
|
||||
TimeProvider timeProvider)
|
||||
{
|
||||
public async Task<UserAccount> RegisterNativeAsync(
|
||||
string identity,
|
||||
string? displayName,
|
||||
int noticeVersion,
|
||||
CancellationToken cancellationToken)
|
||||
/// <summary>
|
||||
/// The one rule set for a new native identity: well formed, not reserved, not taken. Returns the normalized identity or
|
||||
/// throws <see cref="BifrostIdentityException"/>. Spends nothing; the unique index at insert stays the race backstop.
|
||||
/// </summary>
|
||||
public async Task<string> CheckAvailableAsync(string identity, CancellationToken cancellationToken)
|
||||
{
|
||||
var normalizedIdentity = NormalizeIdentity(identity);
|
||||
if (IsReserved(normalizedIdentity))
|
||||
|
|
@ -24,14 +24,22 @@ public sealed partial class BifrostIdentityService(
|
|||
throw new BifrostIdentityException("That Bifrost identity is reserved.");
|
||||
}
|
||||
|
||||
var exists = await dbContext.UserAccounts.AnyAsync(
|
||||
x => x.NormalizedBifrostIdentity == normalizedIdentity,
|
||||
cancellationToken);
|
||||
if (exists)
|
||||
if (await dbContext.UserAccounts.AnyAsync(x => x.NormalizedBifrostIdentity == normalizedIdentity, cancellationToken))
|
||||
{
|
||||
throw new BifrostIdentityException("That Bifrost identity is already registered.");
|
||||
}
|
||||
|
||||
return normalizedIdentity;
|
||||
}
|
||||
|
||||
public async Task<UserAccount> RegisterNativeAsync(
|
||||
string identity,
|
||||
string? displayName,
|
||||
int noticeVersion,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var normalizedIdentity = await CheckAvailableAsync(identity, cancellationToken);
|
||||
|
||||
var now = timeProvider.GetUtcNow();
|
||||
var publicIdentity = ToPublicIdentity(normalizedIdentity);
|
||||
var resolvedDisplayName = string.IsNullOrWhiteSpace(displayName)
|
||||
|
|
@ -66,10 +74,31 @@ public sealed partial class BifrostIdentityService(
|
|||
NoticeVersion = noticeVersion,
|
||||
AcceptedAtUtc = now
|
||||
});
|
||||
await dbContext.SaveChangesAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
await dbContext.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
catch (DbUpdateException)
|
||||
{
|
||||
// Only a lost race on the unique index is the caller's mistake; anything else is a fault and propagates.
|
||||
if (!await IdentityTakenAsync(normalizedIdentity))
|
||||
{
|
||||
throw;
|
||||
}
|
||||
|
||||
throw new BifrostIdentityException("That Bifrost identity is already registered.");
|
||||
}
|
||||
|
||||
return userAccount;
|
||||
}
|
||||
|
||||
// A lost race on the unique index: the tracked insert is dropped and the identity is read fresh.
|
||||
private async Task<bool> IdentityTakenAsync(string normalizedIdentity)
|
||||
{
|
||||
dbContext.ChangeTracker.Clear();
|
||||
return await dbContext.UserAccounts.AnyAsync(x => x.NormalizedBifrostIdentity == normalizedIdentity);
|
||||
}
|
||||
|
||||
public async Task EnsureIdentityAsync(
|
||||
UserAccount userAccount,
|
||||
string preferredIdentity,
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ public enum RegistrationField { None, Identity, Consent }
|
|||
|
||||
/// <summary>
|
||||
/// Either a signed-in <see cref="Account"/>, or a <see cref="Refusal"/> to return as is (the rate limits), or a rejection
|
||||
/// with a status and message. <see cref="WaitRemaining"/> is set when the time-lock was not over; the challenge is then still unspent.
|
||||
/// with a status and message. <see cref="KeepChallenge"/> is set when the challenge was not spent and a retry needs only a correction, so the form should carry it on (the time-lock clock must not restart).
|
||||
/// </summary>
|
||||
public sealed record RegistrationOutcome(
|
||||
UserAccount? Account,
|
||||
|
|
@ -27,16 +27,17 @@ public sealed record RegistrationOutcome(
|
|||
int Status,
|
||||
string? Message,
|
||||
RegistrationField Field,
|
||||
TimeSpan? WaitRemaining)
|
||||
bool KeepChallenge)
|
||||
{
|
||||
public static RegistrationOutcome Reject(int status, string message, RegistrationField field = RegistrationField.None, TimeSpan? wait = null) =>
|
||||
new(null, null, status, message, field, wait);
|
||||
public static RegistrationOutcome Reject(int status, string message, RegistrationField field = RegistrationField.None, bool keepChallenge = false) =>
|
||||
new(null, null, status, message, field, keepChallenge);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The one registration gate, run by the JSON endpoint and the form alike. Order: address budget, consent, one proof only,
|
||||
/// the challenge (proof of work, or the time-lock plus its tighter budget), then the account and receipt in one save,
|
||||
/// then the cookie. A refusal at any step creates nothing.
|
||||
/// The one registration gate, run by the JSON endpoint and the form alike after each has spent the general address budget.
|
||||
/// Order: consent, one proof only, the identity rules (which spend nothing), the challenge (proof of work, or the
|
||||
/// time-lock plus its tighter budget), then the account and receipt in one save, then the cookie. A refusal at any step
|
||||
/// creates nothing, and a refusal before the challenge step spends neither the challenge nor a fallback permit.
|
||||
/// </summary>
|
||||
public sealed class NativeRegistration(
|
||||
BifrostIdentityService identities,
|
||||
|
|
@ -45,11 +46,6 @@ public sealed class NativeRegistration(
|
|||
{
|
||||
public async Task<RegistrationOutcome> RunAsync(HttpContext http, RegistrationAttempt attempt, CancellationToken cancellationToken)
|
||||
{
|
||||
if (rateLimit.Refuse(http) is { } refused)
|
||||
{
|
||||
return new(null, refused, 0, null, RegistrationField.None, null);
|
||||
}
|
||||
|
||||
// Consent first, then the proof; a refusal here creates nothing.
|
||||
if (attempt.AcceptedNoticeVersion != TrainingNotice.Version)
|
||||
{
|
||||
|
|
@ -65,6 +61,15 @@ public sealed class NativeRegistration(
|
|||
return RegistrationOutcome.Reject(StatusCodes.Status400BadRequest, "Send a nonce or waited, not both.");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await identities.CheckAvailableAsync(attempt.Identity ?? "", cancellationToken);
|
||||
}
|
||||
catch (BifrostIdentityException error)
|
||||
{
|
||||
return RegistrationOutcome.Reject(StatusCodes.Status400BadRequest, error.Message, RegistrationField.Identity, keepChallenge: true);
|
||||
}
|
||||
|
||||
var failed = RegistrationOutcome.Reject(StatusCodes.Status400BadRequest, "Registration challenge failed.");
|
||||
if (hasNonce)
|
||||
{
|
||||
|
|
@ -85,13 +90,13 @@ public sealed class NativeRegistration(
|
|||
var seconds = (int)Math.Ceiling(remaining.TotalSeconds);
|
||||
return RegistrationOutcome.Reject(
|
||||
StatusCodes.Status400BadRequest,
|
||||
$"Too early: {seconds} more second{(seconds == 1 ? "" : "s")} to wait after the page opened. Nothing was spent; submit again then.",
|
||||
wait: remaining);
|
||||
$"Too early: {seconds} more second{(seconds == 1 ? "" : "s")} to wait after the page opened. Your challenge is still good; submit again then.",
|
||||
keepChallenge: true);
|
||||
}
|
||||
|
||||
if (rateLimit.RefuseFallback(http) is { } fallbackRefused)
|
||||
{
|
||||
return new(null, fallbackRefused, 0, null, RegistrationField.None, null);
|
||||
return new(null, fallbackRefused, 0, null, RegistrationField.None, false);
|
||||
}
|
||||
|
||||
if (!challenges.TryConsumeWaited(attempt.Challenge))
|
||||
|
|
@ -108,7 +113,7 @@ public sealed class NativeRegistration(
|
|||
{
|
||||
var account = await identities.RegisterNativeAsync(attempt.Identity ?? "", attempt.DisplayName, TrainingNotice.Version, cancellationToken);
|
||||
await http.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, identities.BuildPrincipal(account));
|
||||
return new(account, null, StatusCodes.Status200OK, null, RegistrationField.None, null);
|
||||
return new(account, null, StatusCodes.Status200OK, null, RegistrationField.None, false);
|
||||
}
|
||||
catch (BifrostIdentityException error)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -31,6 +31,7 @@ public static class RegistrationPage
|
|||
var BATCH = 256;
|
||||
var busy = false;
|
||||
var solved = false;
|
||||
var skipped = false;
|
||||
|
||||
function zeroBits(bytes) {
|
||||
var bits = 0;
|
||||
|
|
@ -43,7 +44,7 @@ public static class RegistrationPage
|
|||
|
||||
async function solve(challenge, difficulty) {
|
||||
var encoder = new TextEncoder();
|
||||
for (var start = 0; ; start += BATCH) {
|
||||
for (var start = 0; !skipped; start += BATCH) {
|
||||
var tries = [];
|
||||
for (var n = start; n < start + BATCH; n++) {
|
||||
tries.push(crypto.subtle.digest("SHA-256", encoder.encode(challenge + ":" + n)));
|
||||
|
|
@ -54,15 +55,26 @@ public static class RegistrationPage
|
|||
}
|
||||
await new Promise(function (resolve) { setTimeout(resolve, 0); });
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
form.addEventListener("submit", function (event) {
|
||||
if (event.submitter && event.submitter.id === "skip") {
|
||||
// The way out of a slow solve: stop it and let this submit go on the time-lock path.
|
||||
skipped = true;
|
||||
solved = true;
|
||||
form.elements.nonce.value = "";
|
||||
form.elements.waited.disabled = false;
|
||||
status.textContent = "Skipping the automatic check.";
|
||||
return;
|
||||
}
|
||||
if (solved) { return; }
|
||||
event.preventDefault();
|
||||
if (busy) { return; }
|
||||
busy = true;
|
||||
status.textContent = "Checking, a few seconds";
|
||||
status.textContent = "Checking. This can take longer on a slow device; press Skip the automatic check to wait " + form.getAttribute("data-wait") + " seconds instead.";
|
||||
solve(form.elements.challenge.value, parseInt(form.getAttribute("data-difficulty"), 10)).then(function (nonce) {
|
||||
if (skipped || nonce === null) { return; }
|
||||
form.elements.nonce.value = nonce;
|
||||
form.elements.waited.disabled = true;
|
||||
solved = true;
|
||||
|
|
@ -71,7 +83,7 @@ public static class RegistrationPage
|
|||
}, function () {
|
||||
solved = true;
|
||||
busy = false;
|
||||
status.textContent = "The quick check did not run in this browser. Press Create account again after the wait described below.";
|
||||
status.textContent = "The automatic check did not run in this browser. Press Skip the automatic check and wait as described below.";
|
||||
});
|
||||
});
|
||||
})();
|
||||
|
|
@ -84,7 +96,13 @@ public static class RegistrationPage
|
|||
var summary = new StringBuilder();
|
||||
if (model.Error is not null)
|
||||
{
|
||||
summary.Append($"""<div id="errors" role="alert" tabindex="-1"><strong>Registration did not go through.</strong><p>{E(model.Error)}</p></div>""");
|
||||
var link = model.ErrorField switch
|
||||
{
|
||||
RegistrationField.Identity => """<ul><li><a href="#identity">Identity name</a></li></ul>""",
|
||||
RegistrationField.Consent => """<ul><li><a href="#consent">I have read this notice and consent</a></li></ul>""",
|
||||
_ => ""
|
||||
};
|
||||
summary.Append($"""<div id="errors" role="alert" tabindex="-1"><strong>Registration did not go through.</strong><p>{E(model.Error)}</p>{link}</div>""");
|
||||
}
|
||||
|
||||
string Invalid(RegistrationField field) => model.Error is not null && model.ErrorField == field ? " aria-invalid=\"true\" aria-describedby=\"errors\"" : "";
|
||||
|
|
@ -109,6 +127,7 @@ public static class RegistrationPage
|
|||
input[type=text] { box-sizing: border-box; width: 100%; min-height: 44px; margin-top: 4px; padding: 0 10px; border: 1px solid #8a7d73; border-radius: 6px; background: #0d0b0a; color: #fff8ef; font: inherit; }
|
||||
input[type=checkbox] { width: 22px; height: 22px; margin: 0 8px 0 0; vertical-align: middle; accent-color: #c43e4f; }
|
||||
label.check { display: flex; align-items: center; margin-top: 14px; }
|
||||
button.secondary { margin-left: 10px; background: #2a2522; border: 1px solid #8a7d73; }
|
||||
button { margin-top: 20px; min-height: 46px; padding: 0 18px; border: 0; border-radius: 6px; background: #c43e4f; color: #fff; font: inherit; font-weight: 750; cursor: pointer; }
|
||||
:focus-visible { outline: 3px solid #ffd27a; outline-offset: 2px; }
|
||||
#errors { margin-top: 18px; padding: 10px 14px; border: 2px solid #ff9aa6; border-radius: 6px; color: #ffc2c9; }
|
||||
|
|
@ -124,7 +143,7 @@ public static class RegistrationPage
|
|||
<h1>Create a Bifrost account</h1>
|
||||
<p>A new account can chat. It has no vote and opens no member or governance surface.</p>
|
||||
{{summary}}
|
||||
<form id="register" method="post" action="/auth/bifrost/register/form" data-difficulty="{{model.Difficulty}}">
|
||||
<form id="register" method="post" action="/auth/bifrost/register/form" data-difficulty="{{model.Difficulty}}" data-wait="{{wait}}">
|
||||
<fieldset>
|
||||
<legend>Your account</legend>
|
||||
<label for="identity">Identity name</label>
|
||||
|
|
@ -143,9 +162,10 @@ public static class RegistrationPage
|
|||
<input type="hidden" name="nonce" value="" />
|
||||
<input type="hidden" name="waited" value="true" />
|
||||
<p id="status" aria-live="polite"></p>
|
||||
<button type="submit">Create account</button>
|
||||
<button type="submit" id="create">Create account</button>
|
||||
<button type="submit" id="skip" class="secondary">Skip the automatic check and wait {{wait}} seconds instead</button>
|
||||
</form>
|
||||
<p class="hint" id="wait-note">Without a script, this page cannot run its quick check. Then wait {{wait}} seconds after the page opened and press Create account; pressed sooner, the page comes back saying how many seconds remain, and nothing is lost. Without the quick check only a few registrations per hour are accepted from one address.</p>
|
||||
<p class="hint" id="wait-note">Without a script, or if the automatic check is slow, wait {{wait}} seconds after the page opened and press the button to skip it (or Create account when there is no script). Pressed sooner, the page comes back saying how many seconds remain and keeps your names; the consent box comes back unchecked, so tick the box again before you submit. Without the automatic check only a few registrations per hour are accepted from one address.</p>
|
||||
<p><small>After registering, Bifrost returns you to {{E(model.ReturnPath)}}.</small></p>
|
||||
</main>
|
||||
<script>{{Script}}</script>
|
||||
|
|
|
|||
|
|
@ -1,14 +1,14 @@
|
|||
using Bifrost.Web.Configuration;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace Bifrost.Web.Features.ConceptVotes;
|
||||
namespace Bifrost.Web.Features.Shared;
|
||||
|
||||
// The one place that decides whether a state-changing request to the vote page came from the site itself. The anonymous
|
||||
// vote flow carries no antiforgery token and no antiforgery cookie, so a cross-site form post is refused here instead
|
||||
// The one place that decides whether a state-changing request to an anonymous form (the vote page, the sign-up form) came from
|
||||
// the site itself. These flows carry no antiforgery token and no antiforgery cookie, so a cross-site form post is refused here instead
|
||||
// (OWASP Fetch Metadata): the Origin header must equal the configured site origin byte for byte, or, when the browser
|
||||
// sent no Origin, Sec-Fetch-Site must be exactly same-origin. Same-site, cross-site, none, absent and a repeated header
|
||||
// are all refused. Header values are compared, never echoed.
|
||||
public static class CastRequestGuard
|
||||
public static class RequestOriginGuard
|
||||
{
|
||||
public static bool Allows(HttpRequest request, BifrostHostOptions host)
|
||||
{
|
||||
Loading…
Reference in a new issue