Registration gates: proof-of-work CAPTCHA and training-notice consent receipt (#54)
This commit is contained in:
parent
fc8242f655
commit
33be966b7d
28 changed files with 1253 additions and 56 deletions
|
|
@ -44,7 +44,8 @@ public sealed class DeskOptionsTests
|
|||
Options.Create(new StripeOptions()),
|
||||
Options.Create(new BifrostHostOptions()),
|
||||
Options.Create(new ConceptVoteOptions()),
|
||||
Options.Create(Bind(values))).Validate();
|
||||
Options.Create(Bind(values)),
|
||||
Options.Create(new RegistrationOptions())).Validate();
|
||||
}
|
||||
|
||||
private static void Refused(Dictionary<string, string?> values, string expectedFragment)
|
||||
|
|
|
|||
|
|
@ -363,7 +363,8 @@ public sealed class HostTrustTests : IClassFixture<TestWebApplicationFactory>
|
|||
MintWindow = mintWindow ?? TimeSpan.FromHours(1),
|
||||
MaxTrackedKeys = maxTrackedKeys
|
||||
}),
|
||||
Options.Create(new DeskOptions())).Validate();
|
||||
Options.Create(new DeskOptions()),
|
||||
Options.Create(new RegistrationOptions())).Validate();
|
||||
}
|
||||
|
||||
private sealed class StubHostEnvironment(string environmentName) : IHostEnvironment
|
||||
|
|
|
|||
|
|
@ -24,6 +24,7 @@ public sealed class MigrationDiscoveryTests
|
|||
"20261022163159_AddOpenIddict",
|
||||
"20261109200000_AddSealedBallotMotions",
|
||||
"20261109210000_AddMindKeys",
|
||||
"20261111090000_AddConsentReceipts",
|
||||
];
|
||||
|
||||
// Database.GetMigrations() reads assembly metadata only; no connection is opened.
|
||||
|
|
|
|||
|
|
@ -838,7 +838,7 @@ public sealed class OidcIssuerTests : IClassFixture<OidcWebApplicationFactory>
|
|||
|
||||
private static async Task<string> RegisterAsync(HttpClient client, string identity)
|
||||
{
|
||||
using var response = await client.PostAsJsonAsync("/auth/bifrost/register", new { identity, displayName = identity });
|
||||
using var response = await RegistrationKit.RegisterAsync(client, identity);
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
return identity.ToLowerInvariant();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -45,16 +45,8 @@ public sealed class PlatformEndpointsTests : IClassFixture<TestWebApplicationFac
|
|||
public async Task Bifrost_native_registration_creates_authenticated_identity_without_oauth()
|
||||
{
|
||||
using var client = _factory.CreateClient();
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, "/auth/bifrost/register");
|
||||
request.Headers.Add("X-Test-Anonymous", "true");
|
||||
request.Content = JsonContent.Create(new
|
||||
{
|
||||
identity = $"native-{Guid.NewGuid():N}",
|
||||
displayName = "Native Bifrost User",
|
||||
returnUrl = "/App"
|
||||
});
|
||||
|
||||
using var response = await client.SendAsync(request);
|
||||
using var response = await RegistrationKit.RegisterAsync(
|
||||
client, $"native-{Guid.NewGuid():N}", "Native Bifrost User", "/App", anonymous: true);
|
||||
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
var payload = await response.Content.ReadFromJsonAsync<JsonElement>();
|
||||
|
|
@ -79,15 +71,8 @@ public sealed class PlatformEndpointsTests : IClassFixture<TestWebApplicationFac
|
|||
using var client = _factory.CreateClient();
|
||||
var identity = $"native-{Guid.NewGuid():N}";
|
||||
|
||||
using var firstRequest = new HttpRequestMessage(HttpMethod.Post, "/auth/bifrost/register");
|
||||
firstRequest.Headers.Add("X-Test-Anonymous", "true");
|
||||
firstRequest.Content = JsonContent.Create(new { identity, displayName = "First" });
|
||||
using var firstResponse = await client.SendAsync(firstRequest);
|
||||
|
||||
using var secondRequest = new HttpRequestMessage(HttpMethod.Post, "/auth/bifrost/register");
|
||||
secondRequest.Headers.Add("X-Test-Anonymous", "true");
|
||||
secondRequest.Content = JsonContent.Create(new { identity = identity.ToUpperInvariant(), displayName = "Second" });
|
||||
using var secondResponse = await client.SendAsync(secondRequest);
|
||||
using var firstResponse = await RegistrationKit.RegisterAsync(client, identity, "First", anonymous: true);
|
||||
using var secondResponse = await RegistrationKit.RegisterAsync(client, identity.ToUpperInvariant(), "Second", anonymous: true);
|
||||
|
||||
Assert.Equal(HttpStatusCode.OK, firstResponse.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.BadRequest, secondResponse.StatusCode);
|
||||
|
|
|
|||
367
tests/Bifrost.Web.Tests/RegistrationGateTests.cs
Normal file
367
tests/Bifrost.Web.Tests/RegistrationGateTests.cs
Normal file
|
|
@ -0,0 +1,367 @@
|
|||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using Bifrost.Web.Configuration;
|
||||
using Bifrost.Web.Data;
|
||||
using Bifrost.Web.Features.Registration;
|
||||
using Bifrost.Web.Features.Shared;
|
||||
using Bifrost.Web.Tests.Support;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Bifrost.Web.Tests;
|
||||
|
||||
public sealed class RegistrationGateFactory : TestWebApplicationFactory
|
||||
{
|
||||
public ManualClock Time { get; } = new();
|
||||
|
||||
protected override void ConfigureWebHost(Microsoft.AspNetCore.Hosting.IWebHostBuilder builder)
|
||||
{
|
||||
base.ConfigureWebHost(builder);
|
||||
builder.ConfigureServices(services =>
|
||||
{
|
||||
services.RemoveAll<TimeProvider>();
|
||||
services.AddSingleton<TimeProvider>(Time);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// The anonymous register is gated by consent and a proof of work; every refusal must create nothing.
|
||||
public sealed class RegistrationGateTests(RegistrationGateFactory factory) : IClassFixture<RegistrationGateFactory>
|
||||
{
|
||||
private static string NewIdentity() => $"gate-{Guid.NewGuid():N}";
|
||||
|
||||
private HttpClient Client() => factory.CreateClient();
|
||||
|
||||
private (int Accounts, int Receipts) Counts()
|
||||
{
|
||||
using var scope = factory.Services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<BifrostDbContext>();
|
||||
return (db.UserAccounts.Count(), db.ConsentReceipts.Count());
|
||||
}
|
||||
|
||||
private async Task<(string Challenge, string Nonce)> SolvedAsync(HttpClient client) =>
|
||||
await RegistrationKit.SolveAsync(client);
|
||||
|
||||
private async Task AssertRefusedCreatesNothingAsync(HttpClient client, object body, string? expectedFragment = null)
|
||||
{
|
||||
var before = Counts();
|
||||
using var response = await RegistrationKit.PostAsync(client, body, anonymous: true);
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
if (expectedFragment is not null)
|
||||
{
|
||||
Assert.Contains(expectedFragment, await response.Content.ReadAsStringAsync());
|
||||
}
|
||||
|
||||
Assert.Equal(before, Counts());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task No_consent_is_refused_and_creates_nothing()
|
||||
{
|
||||
using var client = Client();
|
||||
var (challenge, nonce) = await SolvedAsync(client);
|
||||
|
||||
await AssertRefusedCreatesNothingAsync(
|
||||
client,
|
||||
new { identity = NewIdentity(), challenge, nonce },
|
||||
$"current version {TrainingNotice.Version}");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0)]
|
||||
[InlineData(-1)]
|
||||
[InlineData(2)]
|
||||
public async Task A_wrong_notice_version_is_refused_and_creates_nothing(int version)
|
||||
{
|
||||
using var client = Client();
|
||||
var (challenge, nonce) = await SolvedAsync(client);
|
||||
|
||||
await AssertRefusedCreatesNothingAsync(
|
||||
client,
|
||||
new { identity = NewIdentity(), challenge, nonce, acceptedNoticeVersion = version });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_missing_challenge_is_refused_and_creates_nothing()
|
||||
{
|
||||
using var client = Client();
|
||||
|
||||
await AssertRefusedCreatesNothingAsync(
|
||||
client,
|
||||
new { identity = NewIdentity(), acceptedNoticeVersion = TrainingNotice.Version });
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("garbage")]
|
||||
[InlineData("")]
|
||||
public async Task A_garbage_challenge_is_refused_and_creates_nothing(string challenge)
|
||||
{
|
||||
using var client = Client();
|
||||
|
||||
await AssertRefusedCreatesNothingAsync(
|
||||
client,
|
||||
new { identity = NewIdentity(), challenge, nonce = "1", acceptedNoticeVersion = TrainingNotice.Version });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_tampered_challenge_is_refused_and_creates_nothing()
|
||||
{
|
||||
using var client = Client();
|
||||
var (challenge, _) = await SolvedAsync(client);
|
||||
var tampered = challenge[..^2] + (challenge[^2] == 'A' ? 'B' : 'A') + challenge[^1];
|
||||
var nonce = RegistrationKit.Solve(tampered, 4);
|
||||
|
||||
await AssertRefusedCreatesNothingAsync(
|
||||
client,
|
||||
new { identity = NewIdentity(), challenge = tampered, nonce, acceptedNoticeVersion = TrainingNotice.Version });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_wrong_nonce_is_refused_and_creates_nothing()
|
||||
{
|
||||
using var client = Client();
|
||||
var issued = await client.GetFromJsonAsync<JsonElement>("/auth/bifrost/challenge");
|
||||
var challenge = issued.GetProperty("challenge").GetString()!;
|
||||
var difficulty = issued.GetProperty("difficulty").GetInt32();
|
||||
var correct = RegistrationKit.Solve(challenge, difficulty);
|
||||
// The next nonce that does not meet the difficulty.
|
||||
var wrong = Enumerable.Range(0, int.MaxValue)
|
||||
.Select(i => i.ToString())
|
||||
.First(n => n != correct && RegistrationChallengeService.LeadingZeroBits(
|
||||
System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(challenge + ":" + n))) < difficulty);
|
||||
|
||||
await AssertRefusedCreatesNothingAsync(
|
||||
client,
|
||||
new { identity = NewIdentity(), challenge, nonce = wrong, acceptedNoticeVersion = TrainingNotice.Version });
|
||||
}
|
||||
|
||||
// Each malformed shape is padded until it meets the difficulty, so only the nonce-format guard can refuse it.
|
||||
[Theory]
|
||||
[InlineData("x", "")]
|
||||
[InlineData("-", "")]
|
||||
[InlineData("", "e")]
|
||||
[InlineData("000000000000000000000", "")]
|
||||
public async Task A_malformed_nonce_is_refused_even_when_its_hash_would_pass(string prefix, string suffix)
|
||||
{
|
||||
using var client = Client();
|
||||
var (challenge, _) = await SolvedAsync(client);
|
||||
var nonce = Enumerable.Range(0, int.MaxValue)
|
||||
.Select(i => prefix + i + suffix)
|
||||
.First(n => RegistrationChallengeService.LeadingZeroBits(
|
||||
System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(challenge + ":" + n))) >= 4);
|
||||
|
||||
await AssertRefusedCreatesNothingAsync(
|
||||
client,
|
||||
new { identity = NewIdentity(), challenge, nonce, acceptedNoticeVersion = TrainingNotice.Version });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task An_expired_challenge_is_refused_and_creates_nothing()
|
||||
{
|
||||
using var client = Client();
|
||||
var (challenge, nonce) = await SolvedAsync(client);
|
||||
factory.Time.Advance(RegistrationChallengeService.Lifetime + TimeSpan.FromSeconds(1));
|
||||
|
||||
await AssertRefusedCreatesNothingAsync(
|
||||
client,
|
||||
new { identity = NewIdentity(), challenge, nonce, acceptedNoticeVersion = TrainingNotice.Version });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_consumed_challenge_cannot_be_replayed()
|
||||
{
|
||||
using var client = Client();
|
||||
var (challenge, nonce) = await SolvedAsync(client);
|
||||
var first = NewIdentity();
|
||||
var body = (string identity) => new { identity, challenge, nonce, acceptedNoticeVersion = TrainingNotice.Version };
|
||||
|
||||
using var accepted = await RegistrationKit.PostAsync(client, body(first), anonymous: true);
|
||||
Assert.Equal(HttpStatusCode.OK, accepted.StatusCode);
|
||||
var before = Counts();
|
||||
|
||||
await AssertRefusedCreatesNothingAsync(client, body(NewIdentity()));
|
||||
Assert.Equal(before, Counts());
|
||||
using var scope = factory.Services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<BifrostDbContext>();
|
||||
Assert.Single(db.UserAccounts.Where(x => x.NormalizedBifrostIdentity == first));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_nonce_solved_for_one_challenge_does_not_pass_another()
|
||||
{
|
||||
using var client = Client();
|
||||
var (_, nonceForFirst) = await SolvedAsync(client);
|
||||
var issued = await client.GetFromJsonAsync<JsonElement>("/auth/bifrost/challenge");
|
||||
var second = issued.GetProperty("challenge").GetString()!;
|
||||
var difficulty = issued.GetProperty("difficulty").GetInt32();
|
||||
// Skip the rare case where the nonce happens to also solve the second challenge.
|
||||
if (RegistrationChallengeService.LeadingZeroBits(
|
||||
System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(second + ":" + nonceForFirst))) >= difficulty)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await AssertRefusedCreatesNothingAsync(
|
||||
client,
|
||||
new { identity = NewIdentity(), challenge = second, nonce = nonceForFirst, acceptedNoticeVersion = TrainingNotice.Version });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Success_stores_the_receipt_with_the_account()
|
||||
{
|
||||
using var client = Client();
|
||||
var identity = NewIdentity();
|
||||
|
||||
using var response = await RegistrationKit.RegisterAsync(client, identity, anonymous: true);
|
||||
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
using var scope = factory.Services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<BifrostDbContext>();
|
||||
var account = db.UserAccounts.Single(x => x.NormalizedBifrostIdentity == identity);
|
||||
var receipt = db.ConsentReceipts.Single(x => x.UserAccountId == account.Id);
|
||||
Assert.Equal(1, receipt.NoticeVersion);
|
||||
Assert.Null(receipt.WithdrawnAtUtc);
|
||||
Assert.InRange((factory.Time.GetUtcNow() - receipt.AcceptedAtUtc).Duration(), TimeSpan.Zero, TimeSpan.FromSeconds(5));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Withdraw_stamps_once_and_touches_only_the_caller()
|
||||
{
|
||||
using var client = Client();
|
||||
var mine = NewIdentity();
|
||||
var theirs = NewIdentity();
|
||||
(await RegistrationKit.RegisterAsync(client, mine, anonymous: true)).Dispose();
|
||||
(await RegistrationKit.RegisterAsync(client, theirs, anonymous: true)).Dispose();
|
||||
|
||||
async Task<JsonElement> WithdrawAsync()
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, "/auth/bifrost/consent/withdraw");
|
||||
request.Headers.Add("X-Test-Bifrost-Identity", mine);
|
||||
using var response = await client.SendAsync(request);
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
return await response.Content.ReadFromJsonAsync<JsonElement>();
|
||||
}
|
||||
|
||||
var first = await WithdrawAsync();
|
||||
factory.Time.Advance(TimeSpan.FromHours(1));
|
||||
var second = await WithdrawAsync();
|
||||
|
||||
using var scope = factory.Services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<BifrostDbContext>();
|
||||
var myReceipt = db.ConsentReceipts.Single(x => x.UserAccount!.NormalizedBifrostIdentity == mine);
|
||||
var theirReceipt = db.ConsentReceipts.Single(x => x.UserAccount!.NormalizedBifrostIdentity == theirs);
|
||||
Assert.NotNull(myReceipt.WithdrawnAtUtc);
|
||||
Assert.Equal(myReceipt.WithdrawnAtUtc, first.GetProperty("withdrawnAtUtc").GetDateTimeOffset());
|
||||
Assert.Equal(first.GetProperty("withdrawnAtUtc").GetDateTimeOffset(), second.GetProperty("withdrawnAtUtc").GetDateTimeOffset());
|
||||
Assert.Null(theirReceipt.WithdrawnAtUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Anonymous_withdraw_is_refused_and_changes_nothing()
|
||||
{
|
||||
using var client = Client();
|
||||
var identity = NewIdentity();
|
||||
(await RegistrationKit.RegisterAsync(client, identity, anonymous: true)).Dispose();
|
||||
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, "/auth/bifrost/consent/withdraw");
|
||||
request.Headers.Add("X-Test-Anonymous", "true");
|
||||
using var response = await client.SendAsync(request);
|
||||
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
using var scope = factory.Services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<BifrostDbContext>();
|
||||
Assert.DoesNotContain(db.ConsentReceipts, x => x.WithdrawnAtUtc != null && x.UserAccount!.NormalizedBifrostIdentity == identity);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Withdraw_for_an_account_with_no_receipt_is_404()
|
||||
{
|
||||
using var client = Client();
|
||||
var identity = NewIdentity();
|
||||
using (var scope = factory.Services.CreateScope())
|
||||
{
|
||||
var db = scope.ServiceProvider.GetRequiredService<BifrostDbContext>();
|
||||
db.UserAccounts.Add(new Bifrost.Web.Domain.UserAccount
|
||||
{
|
||||
BifrostIdentity = identity,
|
||||
NormalizedBifrostIdentity = identity,
|
||||
DisplayName = identity
|
||||
});
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, "/auth/bifrost/consent/withdraw");
|
||||
request.Headers.Add("X-Test-Bifrost-Identity", identity);
|
||||
using var response = await client.SendAsync(request);
|
||||
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_notice_endpoint_names_the_version_and_the_discord_exclusion()
|
||||
{
|
||||
using var client = Client();
|
||||
|
||||
var notice = await client.GetFromJsonAsync<JsonElement>("/auth/bifrost/notice");
|
||||
|
||||
Assert.Equal(1, notice.GetProperty("version").GetInt32());
|
||||
Assert.Contains("Discord", notice.GetProperty("text").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_challenge_response_is_not_cached()
|
||||
{
|
||||
using var client = Client();
|
||||
|
||||
using var response = await client.GetAsync("/auth/bifrost/challenge");
|
||||
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Contains("no-store", response.Headers.CacheControl?.ToString());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[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)
|
||||
{
|
||||
var options = new RegistrationOptions { Captcha = new RegistrationCaptchaOptions { Difficulty = difficulty } };
|
||||
Action validate = () => new StartupConfigurationValidator(
|
||||
new ConfigurationBuilder().Build(),
|
||||
new TestingEnvironment(),
|
||||
Options.Create(new GitHubOAuthOptions()),
|
||||
Options.Create(new GitHubAppOptions()),
|
||||
Options.Create(new HeimdallOptions()),
|
||||
Options.Create(new StripeOptions()),
|
||||
Options.Create(new BifrostHostOptions()),
|
||||
Options.Create(new ConceptVoteOptions()),
|
||||
Options.Create(new DeskOptions()),
|
||||
Options.Create(options)).Validate();
|
||||
|
||||
if (valid)
|
||||
{
|
||||
validate();
|
||||
}
|
||||
else
|
||||
{
|
||||
Assert.Contains("Difficulty", Assert.Throws<InvalidOperationException>(validate).Message);
|
||||
}
|
||||
|
||||
Assert.Equal(18, new RegistrationOptions().Captcha.Difficulty);
|
||||
}
|
||||
|
||||
private sealed class TestingEnvironment : IHostEnvironment
|
||||
{
|
||||
public string EnvironmentName { get; set; } = "Testing";
|
||||
public string ApplicationName { get; set; } = "Bifrost.Web";
|
||||
public string ContentRootPath { get; set; } = string.Empty;
|
||||
public Microsoft.Extensions.FileProviders.IFileProvider ContentRootFileProvider { get; set; } = null!;
|
||||
}
|
||||
}
|
||||
239
tests/Bifrost.Web.Tests/RegistrationLimitTests.cs
Normal file
239
tests/Bifrost.Web.Tests/RegistrationLimitTests.cs
Normal file
|
|
@ -0,0 +1,239 @@
|
|||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Bifrost.Web.Configuration;
|
||||
using Bifrost.Web.Data;
|
||||
using Bifrost.Web.Features.Registration;
|
||||
using Bifrost.Web.Tests.Support;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Bifrost.Web.Tests;
|
||||
|
||||
// The challenge service on its own: single use under contention, the bounded set, the purpose, and the difficulty it issued.
|
||||
public sealed class RegistrationChallengeServiceTests
|
||||
{
|
||||
private sealed class MutableOptions(int difficulty) : IOptions<RegistrationOptions>
|
||||
{
|
||||
public RegistrationOptions Value { get; set; } = With(difficulty);
|
||||
public static RegistrationOptions With(int d) => new() { Captcha = new RegistrationCaptchaOptions { Difficulty = d } };
|
||||
}
|
||||
|
||||
private static RegistrationChallengeService NewService(IDataProtectionProvider provider, IOptions<RegistrationOptions> options, TimeProvider clock) =>
|
||||
new(provider, options, clock);
|
||||
|
||||
[Fact]
|
||||
public async Task Concurrent_consumes_of_one_challenge_yield_exactly_one_success()
|
||||
{
|
||||
var service = NewService(new EphemeralDataProtectionProvider(), new MutableOptions(1), new ManualClock());
|
||||
for (var round = 0; round < 300; round++)
|
||||
{
|
||||
var challenge = service.Issue()!;
|
||||
var nonce = RegistrationKit.Solve(challenge.Challenge, challenge.Difficulty);
|
||||
using var start = new ManualResetEventSlim();
|
||||
|
||||
var tasks = Enumerable.Range(0, 16).Select(_ => Task.Factory.StartNew(
|
||||
() => { start.Wait(); return service.TryConsume(challenge.Challenge, nonce); },
|
||||
TaskCreationOptions.LongRunning)).ToArray();
|
||||
start.Set();
|
||||
var results = await Task.WhenAll(tasks);
|
||||
|
||||
Assert.Equal(1, results.Count(x => x));
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_full_consumed_set_refuses_to_issue_and_to_consume_until_entries_expire()
|
||||
{
|
||||
var clock = new ManualClock();
|
||||
var service = NewService(new EphemeralDataProtectionProvider(), new MutableOptions(1), clock);
|
||||
var pending = new List<(string, string)>();
|
||||
for (var i = 0; i < RegistrationChallengeService.MaxConsumed + 1; i++)
|
||||
{
|
||||
var c = service.Issue()!;
|
||||
pending.Add((c.Challenge, RegistrationKit.Solve(c.Challenge, c.Difficulty)));
|
||||
}
|
||||
|
||||
foreach (var (c, n) in pending.Take(RegistrationChallengeService.MaxConsumed))
|
||||
{
|
||||
Assert.True(service.TryConsume(c, n));
|
||||
}
|
||||
|
||||
Assert.Null(service.Issue());
|
||||
Assert.False(service.TryConsume(pending[^1].Item1, pending[^1].Item2));
|
||||
|
||||
clock.Advance(RegistrationChallengeService.Lifetime + TimeSpan.FromSeconds(1));
|
||||
Assert.NotNull(service.Issue());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_token_protected_for_another_purpose_is_refused()
|
||||
{
|
||||
var provider = new EphemeralDataProtectionProvider();
|
||||
var clock = new ManualClock();
|
||||
var service = NewService(provider, new MutableOptions(1), clock);
|
||||
var expiry = (clock.GetUtcNow() + TimeSpan.FromMinutes(1)).ToUnixTimeMilliseconds();
|
||||
var forged = provider.CreateProtector("Bifrost.Something.Else.v1").Protect($"{Guid.NewGuid():N}.{expiry}.1");
|
||||
var nonce = RegistrationKit.Solve(forged, 1);
|
||||
|
||||
Assert.False(service.TryConsume(forged, nonce));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_challenge_verifies_at_the_difficulty_it_was_issued_with()
|
||||
{
|
||||
var options = new MutableOptions(1);
|
||||
var service = NewService(new EphemeralDataProtectionProvider(), options, new ManualClock());
|
||||
var easy = service.Issue()!;
|
||||
var easyNonce = RegistrationKit.Solve(easy.Challenge, 1);
|
||||
// A nonce that meets 1 bit but not 12: only the embedded difficulty lets it through after the option rises.
|
||||
var weak = Enumerable.Range(0, int.MaxValue).Select(i => i.ToString()).First(n =>
|
||||
{
|
||||
var bits = RegistrationChallengeService.LeadingZeroBits(SHA256.HashData(Encoding.UTF8.GetBytes(easy.Challenge + ":" + n)));
|
||||
return bits >= 1 && bits < 12;
|
||||
});
|
||||
|
||||
options.Value = MutableOptions.With(12);
|
||||
|
||||
Assert.Equal(1, easy.Difficulty);
|
||||
Assert.True(service.TryConsume(easy.Challenge, weak));
|
||||
Assert.Equal(12, service.Issue()!.Difficulty);
|
||||
_ = easyNonce;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class RegistrationBudgetFactory : TestWebApplicationFactory
|
||||
{
|
||||
protected override void ConfigureWebHost(IWebHostBuilder builder)
|
||||
{
|
||||
base.ConfigureWebHost(builder);
|
||||
builder.ConfigureAppConfiguration((_, configuration) =>
|
||||
configuration.AddInMemoryCollection(new Dictionary<string, string?>
|
||||
{
|
||||
["Bifrost:Registration:Limits:PerAddressPermits"] = "3"
|
||||
}));
|
||||
builder.ConfigureServices(services => services.AddTransient<Microsoft.AspNetCore.Hosting.IStartupFilter, PeerFilter>());
|
||||
}
|
||||
|
||||
private sealed class PeerFilter : Microsoft.AspNetCore.Hosting.IStartupFilter
|
||||
{
|
||||
public Action<Microsoft.AspNetCore.Builder.IApplicationBuilder> Configure(Action<Microsoft.AspNetCore.Builder.IApplicationBuilder> next) => app =>
|
||||
{
|
||||
app.Use((context, nextMiddleware) =>
|
||||
{
|
||||
context.Connection.RemoteIpAddress = IPAddress.Parse(context.Request.Headers["X-Test-Peer"].FirstOrDefault() ?? "198.51.100.1");
|
||||
return nextMiddleware();
|
||||
});
|
||||
next(app);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class RegistrationBudgetTests(RegistrationBudgetFactory factory) : IClassFixture<RegistrationBudgetFactory>
|
||||
{
|
||||
private static async Task<HttpResponseMessage> ChallengeAsync(HttpClient client, string peer)
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, "/auth/bifrost/challenge");
|
||||
request.Headers.Add("X-Test-Peer", peer);
|
||||
return await client.SendAsync(request);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_request_past_the_address_budget_gets_429_and_another_address_is_unaffected()
|
||||
{
|
||||
using var client = factory.CreateClient();
|
||||
for (var i = 0; i < 3; i++)
|
||||
{
|
||||
using var ok = await ChallengeAsync(client, "203.0.113.5");
|
||||
Assert.Equal(HttpStatusCode.OK, ok.StatusCode);
|
||||
}
|
||||
|
||||
using var refused = await ChallengeAsync(client, "203.0.113.5");
|
||||
using var other = await ChallengeAsync(client, "203.0.113.6");
|
||||
|
||||
Assert.Equal(HttpStatusCode.TooManyRequests, refused.StatusCode);
|
||||
Assert.True(refused.Headers.RetryAfter is not null);
|
||||
Assert.Equal(HttpStatusCode.OK, other.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task An_IPv6_caller_owns_its_slash_64_and_a_mapped_IPv4_shares_its_IPv4_key()
|
||||
{
|
||||
using var client = factory.CreateClient();
|
||||
string[] sameSlash64 = ["2001:db8:1:2::1", "2001:db8:1:2::2", "2001:db8:1:2:aaaa::3", "2001:db8:1:2:ffff:ffff:ffff:ffff", "2001:db8:1:2::5"];
|
||||
var statuses = new List<HttpStatusCode>();
|
||||
foreach (var peer in sameSlash64)
|
||||
{
|
||||
using var response = await ChallengeAsync(client, peer);
|
||||
statuses.Add(response.StatusCode);
|
||||
}
|
||||
|
||||
Assert.Equal(
|
||||
[HttpStatusCode.OK, HttpStatusCode.OK, HttpStatusCode.OK, HttpStatusCode.TooManyRequests, HttpStatusCode.TooManyRequests],
|
||||
statuses);
|
||||
using var otherSlash64 = await ChallengeAsync(client, "2001:db8:1:3::1");
|
||||
Assert.Equal(HttpStatusCode.OK, otherSlash64.StatusCode);
|
||||
|
||||
for (var i = 0; i < 3; i++)
|
||||
{
|
||||
using var ok = await ChallengeAsync(client, "203.0.113.50");
|
||||
Assert.Equal(HttpStatusCode.OK, ok.StatusCode);
|
||||
}
|
||||
|
||||
using var mapped = await ChallengeAsync(client, "::ffff:203.0.113.50");
|
||||
Assert.Equal(HttpStatusCode.TooManyRequests, mapped.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Challenge_and_register_spend_one_budget_and_a_refused_register_creates_nothing()
|
||||
{
|
||||
using var client = factory.CreateClient();
|
||||
const string peer = "203.0.113.7";
|
||||
for (var i = 0; i < 3; i++)
|
||||
{
|
||||
using var ok = await ChallengeAsync(client, peer);
|
||||
Assert.Equal(HttpStatusCode.OK, ok.StatusCode);
|
||||
}
|
||||
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, "/auth/bifrost/register")
|
||||
{
|
||||
Content = JsonContent.Create(new { identity = $"budget-{Guid.NewGuid():N}", acceptedNoticeVersion = TrainingNotice.Version })
|
||||
};
|
||||
request.Headers.Add("X-Test-Anonymous", "true");
|
||||
request.Headers.Add("X-Test-Peer", peer);
|
||||
using var response = await client.SendAsync(request);
|
||||
|
||||
Assert.Equal(HttpStatusCode.TooManyRequests, response.StatusCode);
|
||||
using var scope = factory.Services.CreateScope();
|
||||
Assert.DoesNotContain(scope.ServiceProvider.GetRequiredService<BifrostDbContext>().UserAccounts, x => x.NormalizedBifrostIdentity!.StartsWith("budget-"));
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class RegistrationFullSetTests(RegistrationGateFactory factory) : IClassFixture<RegistrationGateFactory>
|
||||
{
|
||||
[Fact]
|
||||
public async Task A_full_consumed_set_makes_the_challenge_endpoint_answer_503()
|
||||
{
|
||||
var service = factory.Services.GetRequiredService<RegistrationChallengeService>();
|
||||
for (var i = 0; i < RegistrationChallengeService.MaxConsumed; i++)
|
||||
{
|
||||
var c = service.Issue()!;
|
||||
Assert.True(service.TryConsume(c.Challenge, RegistrationKit.Solve(c.Challenge, c.Difficulty)));
|
||||
}
|
||||
|
||||
using var client = factory.CreateClient();
|
||||
using var response = await client.GetAsync("/auth/bifrost/challenge");
|
||||
|
||||
Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode);
|
||||
factory.Time.Advance(RegistrationChallengeService.Lifetime + TimeSpan.FromSeconds(1));
|
||||
using var after = await client.GetAsync("/auth/bifrost/challenge");
|
||||
Assert.Equal(HttpStatusCode.OK, after.StatusCode);
|
||||
}
|
||||
}
|
||||
|
|
@ -28,7 +28,7 @@ public sealed class ReservedIdentityTests
|
|||
{
|
||||
var service = NewService(out var db);
|
||||
|
||||
var ex = await Assert.ThrowsAsync<BifrostIdentityException>(() => service.RegisterNativeAsync(name, null, default));
|
||||
var ex = await Assert.ThrowsAsync<BifrostIdentityException>(() => service.RegisterNativeAsync(name, null, 1, default));
|
||||
|
||||
Assert.Equal("That Bifrost identity is reserved.", ex.Message);
|
||||
Assert.Empty(db.UserAccounts);
|
||||
|
|
@ -42,7 +42,7 @@ public sealed class ReservedIdentityTests
|
|||
{
|
||||
var service = NewService(out var db);
|
||||
|
||||
await Assert.ThrowsAsync<BifrostIdentityException>(() => service.RegisterNativeAsync(name, null, default));
|
||||
await Assert.ThrowsAsync<BifrostIdentityException>(() => service.RegisterNativeAsync(name, null, 1, default));
|
||||
|
||||
Assert.Empty(db.UserAccounts);
|
||||
}
|
||||
|
|
@ -56,7 +56,7 @@ public sealed class ReservedIdentityTests
|
|||
{
|
||||
var service = NewService(out var db);
|
||||
|
||||
var account = await service.RegisterNativeAsync(name, null, default);
|
||||
var account = await service.RegisterNativeAsync(name, null, 1, default);
|
||||
|
||||
Assert.Equal(name, account.NormalizedBifrostIdentity);
|
||||
Assert.Single(db.UserAccounts);
|
||||
|
|
@ -112,7 +112,7 @@ public sealed class ReservedIdentityTests
|
|||
{
|
||||
var service = NewService(out var db);
|
||||
|
||||
var ex = await Assert.ThrowsAsync<BifrostIdentityException>(() => service.RegisterNativeAsync(name, null, default));
|
||||
var ex = await Assert.ThrowsAsync<BifrostIdentityException>(() => service.RegisterNativeAsync(name, null, 1, default));
|
||||
|
||||
Assert.Equal("That Bifrost identity is reserved.", ex.Message);
|
||||
Assert.Empty(db.UserAccounts);
|
||||
|
|
@ -147,7 +147,7 @@ public sealed class ReservedIdentityTests
|
|||
public async Task Mixed_case_input_is_refused_by_register_and_suffixed_when_derived(string input)
|
||||
{
|
||||
var service = NewService(out var db);
|
||||
await Assert.ThrowsAsync<BifrostIdentityException>(() => service.RegisterNativeAsync(input, null, default));
|
||||
await Assert.ThrowsAsync<BifrostIdentityException>(() => service.RegisterNativeAsync(input, null, 1, default));
|
||||
Assert.Empty(db.UserAccounts);
|
||||
|
||||
var account = new UserAccount { DisplayName = input };
|
||||
|
|
|
|||
|
|
@ -403,7 +403,7 @@ public sealed class OidcLogoutFactory : OidcWebApplicationFactory
|
|||
{
|
||||
using var client = CreateClient(HostClientOptions());
|
||||
var identity = $"member-{Guid.NewGuid():N}";
|
||||
using (var register = await client.PostAsJsonAsync("/auth/bifrost/register", new { identity, displayName = identity }))
|
||||
using (var register = await RegistrationKit.RegisterAsync(client, identity))
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.OK, register.StatusCode);
|
||||
}
|
||||
|
|
|
|||
63
tests/Bifrost.Web.Tests/Support/RegistrationKit.cs
Normal file
63
tests/Bifrost.Web.Tests/Support/RegistrationKit.cs
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
using System.Net.Http.Json;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Bifrost.Web.Features.Registration;
|
||||
|
||||
namespace Bifrost.Web.Tests.Support;
|
||||
|
||||
/// <summary>Registers through the real gate: fetch a challenge, solve it, post with the notice version.</summary>
|
||||
public static class RegistrationKit
|
||||
{
|
||||
public static async Task<(string Challenge, string Nonce)> SolveAsync(HttpClient client)
|
||||
{
|
||||
var issued = await client.GetFromJsonAsync<JsonElement>("/auth/bifrost/challenge");
|
||||
var challenge = issued.GetProperty("challenge").GetString()!;
|
||||
return (challenge, Solve(challenge, issued.GetProperty("difficulty").GetInt32()));
|
||||
}
|
||||
|
||||
public static string Solve(string challenge, int difficulty)
|
||||
{
|
||||
for (long nonce = 0; ; nonce++)
|
||||
{
|
||||
var text = nonce.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
if (RegistrationChallengeService.LeadingZeroBits(SHA256.HashData(Encoding.UTF8.GetBytes(challenge + ":" + text))) >= difficulty)
|
||||
{
|
||||
return text;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static async Task<HttpResponseMessage> RegisterAsync(
|
||||
HttpClient client,
|
||||
string identity,
|
||||
string? displayName = null,
|
||||
string? returnUrl = null,
|
||||
bool anonymous = false)
|
||||
{
|
||||
var (challenge, nonce) = await SolveAsync(client);
|
||||
return await PostAsync(client, new
|
||||
{
|
||||
identity,
|
||||
displayName = displayName ?? identity,
|
||||
returnUrl,
|
||||
challenge,
|
||||
nonce,
|
||||
acceptedNoticeVersion = TrainingNotice.Version
|
||||
}, anonymous);
|
||||
}
|
||||
|
||||
public static async Task<HttpResponseMessage> PostAsync(HttpClient client, object body, bool anonymous = false)
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, "/auth/bifrost/register")
|
||||
{
|
||||
Content = JsonContent.Create(body)
|
||||
};
|
||||
if (anonymous)
|
||||
{
|
||||
request.Headers.Add("X-Test-Anonymous", "true");
|
||||
}
|
||||
|
||||
return await client.SendAsync(request);
|
||||
}
|
||||
}
|
||||
|
|
@ -21,6 +21,16 @@ public sealed class TestAuthHandler(
|
|||
return Task.FromResult(AuthenticateResult.NoResult());
|
||||
}
|
||||
|
||||
// A test may sign in as a native account by naming its Bifrost identity; only that claim is sent, so no GitHub claim also matches.
|
||||
if (Request.Headers.TryGetValue("X-Test-Bifrost-Identity", out var nativeIdentity))
|
||||
{
|
||||
var native = new ClaimsIdentity(
|
||||
[new Claim(BifrostClaimTypes.BifrostIdentity, nativeIdentity.ToString())],
|
||||
SchemeName);
|
||||
return Task.FromResult(AuthenticateResult.Success(
|
||||
new AuthenticationTicket(new ClaimsPrincipal(native), SchemeName)));
|
||||
}
|
||||
|
||||
// A test may sign in as another account by naming its GitHub id and login.
|
||||
var gitHubId = Request.Headers["X-Test-GitHub-Id"].FirstOrDefault() ?? "12345";
|
||||
var login = Request.Headers["X-Test-GitHub-Login"].FirstOrDefault() ?? "test-admin";
|
||||
|
|
|
|||
|
|
@ -38,6 +38,8 @@ public class TestWebApplicationFactory : WebApplicationFactory<Program>
|
|||
["ConceptVotes:CastPermits"] = "100000",
|
||||
["ConceptVotes:MintPermits"] = "100000",
|
||||
["MindIntake:Permits"] = "100000",
|
||||
["Bifrost:Registration:Captcha:Difficulty"] = "4",
|
||||
["Bifrost:Registration:Limits:PerAddressPermits"] = "100000",
|
||||
["Host:PublicBaseUrl"] = "https://localhost",
|
||||
["Host:ExpectedHost"] = "localhost",
|
||||
["Host:RequireStrictHostValidation"] = "false",
|
||||
|
|
|
|||
Loading…
Reference in a new issue