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:
Heimdall 2026-11-11 10:46:14 +00:00
commit d47f1d5e9d
11 changed files with 376 additions and 56 deletions

View file

@ -13,7 +13,7 @@ const script = scripts[0][1];
const challenge = html.match(/<input type="hidden" name="challenge" value="([^"]*)"/)[1];
const difficulty = html.match(/data-difficulty="(\d+)"/)[1];
async function run(name, { withCrypto, submits }) {
async function run(name, { withCrypto, submits, skipAfter = false }) {
const statuses = [];
let handler = null;
let submitted = 0;
@ -21,7 +21,7 @@ async function run(name, { withCrypto, submits }) {
const done = new Promise((resolve) => (sawSubmit = resolve));
const form = {
elements: { challenge: { value: challenge }, nonce: { value: "" }, waited: { disabled: false } },
getAttribute: (n) => (n === "data-difficulty" ? difficulty : null),
getAttribute: (n) => (n === "data-difficulty" ? difficulty : n === "data-wait" ? "30" : null),
addEventListener: (type, fn) => {
if (type === "submit") handler = fn;
},
@ -41,6 +41,13 @@ async function run(name, { withCrypto, submits }) {
if (!handler) return { name, listening: false, statuses, submitted, nonce: "", waitedDisabled: false, prevented: [], challenge, difficulty };
const prevented = [];
for (let i = 0; i < submits; i++) handler({ preventDefault: () => prevented.push(true) });
if (skipAfter) {
// The skip button pressed while the solve is in flight: the script must let this submit through and drop the solve.
const skipPrevented = [];
handler({ preventDefault: () => skipPrevented.push(true), submitter: { id: "skip" } });
await new Promise((r) => setTimeout(r, 200));
return { name, listening: true, statuses, submitted, nonce: form.elements.nonce.value, waitedDisabled: form.elements.waited.disabled, prevented: skipPrevented, challenge, difficulty };
}
await done;
await new Promise((r) => setTimeout(r, 20));
return { name, listening: true, statuses, submitted, nonce: form.elements.nonce.value, waitedDisabled: form.elements.waited.disabled, prevented, challenge, difficulty };
@ -50,6 +57,7 @@ async function run(name, { withCrypto, submits }) {
const out = [
await run("solves", { withCrypto: true, submits: 1 }),
await run("double-press", { withCrypto: true, submits: 2 }),
await run("skip-during-solve", { withCrypto: true, submits: 1, skipAfter: true }),
await run("no-subtle", { withCrypto: false, submits: 0 }),
];
console.log(JSON.stringify(out));

View file

@ -10,6 +10,7 @@ using Bifrost.Web.Features.ConceptVotes;
using Bifrost.Web.Features.Registration;
using Bifrost.Web.Features.Shared;
using Bifrost.Web.Tests.Support;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
@ -62,8 +63,24 @@ internal static class FormKit
return await response.Content.ReadAsStringAsync();
}
public static Task<HttpResponseMessage> PostAsync(HttpClient client, Dictionary<string, string> fields) =>
client.PostAsync("/auth/bifrost/register/form", new FormUrlEncodedContent(fields));
public const string SiteOrigin = "https://localhost";
// A browser on the site's own page sends its Origin; the guard refuses a post without one.
public static Task<HttpResponseMessage> PostAsync(HttpClient client, Dictionary<string, string> fields, string? origin = SiteOrigin, string? peer = null)
{
var request = new HttpRequestMessage(HttpMethod.Post, "/auth/bifrost/register/form") { Content = new FormUrlEncodedContent(fields) };
if (origin is not null)
{
request.Headers.Add("Origin", origin);
}
if (peer is not null)
{
request.Headers.Add("X-Test-Peer", peer);
}
return client.SendAsync(request);
}
public static Dictionary<string, string> Fields(string html, string identity, bool consent = true, string? nonce = null, bool waited = false, string? returnUrl = null)
{
@ -149,13 +166,16 @@ public sealed class RegistrationFormTests(RegistrationFormFactory factory) : ICl
Assert.Equal(TrainingNotice.Version.ToString(), FormKit.Hidden(html, "acceptedNoticeVersion"));
Assert.False(string.IsNullOrWhiteSpace(FormKit.Hidden(html, "challenge")));
Assert.Matches("wait \\d+ seconds", html);
Assert.Matches("<button type=\"submit\" id=\"skip\"[^>]*>Skip the automatic check and wait \\d+ seconds instead</button>", html);
Assert.DoesNotContain("a few seconds", html);
Assert.DoesNotContain("nothing is lost", html);
Assert.Contains("tick the box again", html);
Assert.DoesNotContain("<noscript", html);
Assert.DoesNotContain("http://", html);
Assert.DoesNotContain("https://", html);
foreach (Match url in Regex.Matches(html, "(?:src|href|action)=\"([^\"]*)\""))
{
Assert.StartsWith("/", url.Groups[1].Value);
Assert.DoesNotMatch("^//", url.Groups[1].Value);
Assert.Matches("^(/(?!/)|#)", url.Groups[1].Value);
}
}
@ -233,6 +253,7 @@ public sealed class RegistrationFormTests(RegistrationFormFactory factory) : ICl
Assert.Matches("role=\"alert\"", again);
Assert.Contains("requires accepting the training notice", again);
Assert.Matches("id=\"consent\"[^>]*aria-invalid=\"true\" aria-describedby=\"errors\"", again);
Assert.Contains("<a href=\"#consent\">", again);
Assert.DoesNotMatch("<input type=\"checkbox\"[^>]*\\bchecked\\b", again);
Assert.Contains($"value=\"{identity}\"", again);
Assert.NotEqual(challenge, FormKit.Hidden(again, "challenge"));
@ -290,6 +311,8 @@ public sealed class RegistrationFormTests(RegistrationFormFactory factory) : ICl
Assert.Contains("already registered", again);
Assert.Matches("id=\"identity\"[^>]*aria-invalid=\"true\" aria-describedby=\"errors\"", again);
Assert.Contains($"value=\"{identity}\"", again);
Assert.Contains("<a href=\"#identity\">", again);
Assert.Equal(FormKit.Hidden(second, "challenge"), FormKit.Hidden(again, "challenge"));
}
[Fact]
@ -419,11 +442,133 @@ public sealed class RegistrationFormTests(RegistrationFormFactory factory) : ICl
public async Task A_form_must_be_urlencoded()
{
using var client = Client();
using var response = await client.PostAsync("/auth/bifrost/register/form", JsonContent.Create(new { identity = "x" }));
using var request = new HttpRequestMessage(HttpMethod.Post, "/auth/bifrost/register/form") { Content = JsonContent.Create(new { identity = "x" }) };
request.Headers.Add("Origin", FormKit.SiteOrigin);
using var response = await client.SendAsync(request);
Assert.Equal(HttpStatusCode.UnsupportedMediaType, response.StatusCode);
}
public static TheoryData<string?, string?> CrossSite => new()
{
{ "https://evil.example", null },
{ "https://evil.example", "same-origin" },
{ "null", null },
{ "https://localhost.evil.example", null },
{ null, "cross-site" },
{ null, "same-site" },
{ null, "none" },
{ null, null }
};
[Theory]
[MemberData(nameof(CrossSite))]
public async Task A_cross_site_or_unattributed_post_is_refused_before_anything_is_read_or_spent(string? origin, string? fetchSite)
{
using var client = Client();
var html = await FormKit.PageAsync(client);
var identity = NewIdentity();
var before = Counts();
factory.Time.Advance(TimeSpan.FromSeconds(31));
var request = new HttpRequestMessage(HttpMethod.Post, "/auth/bifrost/register/form")
{
Content = new FormUrlEncodedContent(FormKit.Fields(html, identity, waited: true))
};
if (origin is not null)
{
request.Headers.Add("Origin", origin);
}
if (fetchSite is not null)
{
request.Headers.Add("Sec-Fetch-Site", fetchSite);
}
using var response = await client.SendAsync(request);
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.False(response.Headers.Contains("Set-Cookie"));
Assert.Equal(before, Counts());
// The challenge was not spent by the refusal.
using var ok = await FormKit.PostAsync(client, FormKit.Fields(html, identity, waited: true));
Assert.Equal(HttpStatusCode.SeeOther, ok.StatusCode);
}
[Fact]
public async Task A_same_origin_post_without_an_Origin_header_is_accepted_on_Sec_Fetch_Site()
{
using var client = Client();
var html = await FormKit.PageAsync(client);
var request = new HttpRequestMessage(HttpMethod.Post, "/auth/bifrost/register/form")
{
Content = new FormUrlEncodedContent(FormKit.Fields(html, NewIdentity(), nonce: FormKit.Solved(html)))
};
request.Headers.Add("Sec-Fetch-Site", "same-origin");
using var response = await client.SendAsync(request);
Assert.Equal(HttpStatusCode.SeeOther, response.StatusCode);
}
[Fact]
public async Task A_form_body_over_the_cap_is_refused_with_413_and_creates_nothing()
{
using var client = Client();
var html = await FormKit.PageAsync(client);
var fields = FormKit.Fields(html, NewIdentity(), nonce: FormKit.Solved(html));
fields["padding"] = new string('x', 17 * 1024);
var before = Counts();
using var response = await FormKit.PostAsync(client, fields);
Assert.Equal(HttpStatusCode.RequestEntityTooLarge, response.StatusCode);
Assert.Equal(before, Counts());
}
[Theory]
[InlineData("support", "reserved")]
[InlineData("a!", "3-80 characters")]
public async Task A_bad_identity_is_refused_without_spending_the_challenge(string identity, string fragment)
{
using var client = Client();
var html = await FormKit.PageAsync(client);
var nonce = FormKit.Solved(html);
using var bad = await FormKit.PostAsync(client, FormKit.Fields(html, identity, nonce: nonce));
var again = await bad.Content.ReadAsStringAsync();
Assert.Equal(HttpStatusCode.BadRequest, bad.StatusCode);
Assert.Contains(fragment, again);
Assert.Equal(FormKit.Hidden(html, "challenge"), FormKit.Hidden(again, "challenge"));
var good = NewIdentity();
using var ok = await FormKit.PostAsync(client, FormKit.Fields(html, good, nonce: nonce));
Assert.Equal(HttpStatusCode.SeeOther, ok.StatusCode);
Assert.Equal((true, true), Created(good));
}
[Theory]
[InlineData(3)]
[InlineData(5)]
public async Task A_challenge_payload_of_another_shape_is_refused(int parts)
{
using var client = Client();
var protector = factory.Services.GetRequiredService<Microsoft.AspNetCore.DataProtection.IDataProtectionProvider>()
.CreateProtector(RegistrationChallengeService.Purpose);
var now = factory.Time.GetUtcNow();
var expiry = (now + TimeSpan.FromMinutes(1)).ToUnixTimeMilliseconds();
var issued = (now - TimeSpan.FromMinutes(1)).ToUnixTimeMilliseconds();
var fields = new[] { Guid.NewGuid().ToString("N"), expiry.ToString(), "1", issued.ToString(), "extra" };
var challenge = protector.Protect(string.Join('.', fields.Take(parts)));
var identity = NewIdentity();
using var pow = await RegistrationKit.PostAsync(client, new { identity, challenge, nonce = RegistrationKit.Solve(challenge, 1), acceptedNoticeVersion = TrainingNotice.Version }, anonymous: true);
using var waited = await RegistrationKit.PostAsync(client, new { identity, challenge, waited = true, acceptedNoticeVersion = TrainingNotice.Version }, anonymous: true);
Assert.Equal(HttpStatusCode.BadRequest, pow.StatusCode);
Assert.Equal(HttpStatusCode.BadRequest, waited.StatusCode);
Assert.False(Exists(identity));
}
[Fact]
public async Task The_page_solver_script_finds_a_nonce_the_server_accepts_under_node()
{
@ -458,7 +603,11 @@ public sealed class RegistrationFormTests(RegistrationFormFactory factory) : ICl
var solved = runs["solves"];
Assert.Equal(1, solved.GetProperty("submitted").GetInt32());
Assert.True(solved.GetProperty("waitedDisabled").GetBoolean());
Assert.Equal("Checking, a few seconds", solved.GetProperty("statuses")[0].GetString());
var first = solved.GetProperty("statuses")[0].GetString()!;
Assert.StartsWith("Checking.", first);
Assert.Contains("Skip the automatic check", first);
Assert.Contains("slow device", first);
Assert.DoesNotContain("a few seconds", first);
var nonce = solved.GetProperty("nonce").GetString()!;
var challenge = FormKit.Hidden(html, "challenge");
Assert.True(RegistrationChallengeService.LeadingZeroBits(System.Security.Cryptography.SHA256.HashData(
@ -470,6 +619,12 @@ public sealed class RegistrationFormTests(RegistrationFormFactory factory) : ICl
Assert.Equal(HttpStatusCode.SeeOther, response.StatusCode);
Assert.Equal((true, true), Created(identity));
var skip = runs["skip-during-solve"];
Assert.Equal(0, skip.GetProperty("submitted").GetInt32());
Assert.Equal("", skip.GetProperty("nonce").GetString());
Assert.False(skip.GetProperty("waitedDisabled").GetBoolean());
Assert.Equal(0, skip.GetProperty("prevented").GetArrayLength());
Assert.Equal(1, runs["double-press"].GetProperty("submitted").GetInt32());
Assert.False(runs["no-subtle"].GetProperty("listening").GetBoolean());
}
@ -587,3 +742,69 @@ public sealed class RegistrationFallbackOptionsTests
Assert.Contains("FallbackPermits", Assert.Throws<InvalidOperationException>(() => Validate(options)).Message);
}
}
public sealed class RegistrationValidationBudgetFactory : RegistrationFormFactory
{
protected override string FallbackPermits => "2";
}
public sealed class RegistrationValidationBudgetTests(RegistrationValidationBudgetFactory factory) : IClassFixture<RegistrationValidationBudgetFactory>
{
[Fact]
public async Task Identity_refusals_spend_neither_a_fallback_permit_nor_the_challenge()
{
using var client = factory.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false });
var first = await FormKit.PageAsync(client);
var second = await FormKit.PageAsync(client);
var third = await FormKit.PageAsync(client);
factory.Time.Advance(TimeSpan.FromSeconds(31));
var taken = $"vb-{Guid.NewGuid():N}";
using (var one = await FormKit.PostAsync(client, FormKit.Fields(first, taken, waited: true)))
{
Assert.Equal(HttpStatusCode.SeeOther, one.StatusCode);
}
foreach (var bad in new[] { taken, "support", "a!" })
{
using var refused = await FormKit.PostAsync(client, FormKit.Fields(second, bad, waited: true));
Assert.Equal(HttpStatusCode.BadRequest, refused.StatusCode);
}
using (var fresh = await FormKit.PostAsync(client, FormKit.Fields(second, $"vb-{Guid.NewGuid():N}", waited: true)))
{
Assert.Equal(HttpStatusCode.SeeOther, fresh.StatusCode);
}
// Two permits, two registrations: the three refusals above cost nothing.
using var over = await FormKit.PostAsync(client, FormKit.Fields(third, $"vb-{Guid.NewGuid():N}", waited: true));
Assert.Equal(HttpStatusCode.TooManyRequests, over.StatusCode);
}
}
public sealed class RegistrationFormBudgetTests(RegistrationBudgetFactory factory) : IClassFixture<RegistrationBudgetFactory>
{
[Fact]
public async Task The_general_budget_is_spent_before_the_body_is_read_and_cross_site_posts_spend_nothing()
{
using var client = factory.CreateClient();
const string peer = "203.0.113.150";
var fields = new Dictionary<string, string> { ["identity"] = "x", ["padding"] = new string('x', 17 * 1024) };
for (var i = 0; i < 5; i++)
{
using var crossSite = await FormKit.PostAsync(client, fields, origin: "https://evil.example", peer: peer);
Assert.Equal(HttpStatusCode.Forbidden, crossSite.StatusCode);
}
// Three permits: the over-cap posts spend them (413), the next is 429 whatever its body.
for (var i = 0; i < 3; i++)
{
using var big = await FormKit.PostAsync(client, fields, peer: peer);
Assert.Equal(HttpStatusCode.RequestEntityTooLarge, big.StatusCode);
}
using var refused = await FormKit.PostAsync(client, fields, peer: peer);
Assert.Equal(HttpStatusCode.TooManyRequests, refused.StatusCode);
}
}

View file

@ -328,9 +328,9 @@ public sealed class RegistrationGateTests(RegistrationGateFactory factory) : ICl
[InlineData(0, false)]
[InlineData(1, true)]
[InlineData(18, true)]
[InlineData(30, true)]
[InlineData(31, false)]
public void Difficulty_outside_one_to_thirty_is_refused_at_startup(int difficulty, bool valid)
[InlineData(24, true)]
[InlineData(25, false)]
public void Difficulty_outside_one_to_twenty_four_is_refused_at_startup(int difficulty, bool valid)
{
var options = new RegistrationOptions { Captcha = new RegistrationCaptchaOptions { Difficulty = difficulty } };
Action validate = () => new StartupConfigurationValidator(