82 lines
2.5 KiB
C#
82 lines
2.5 KiB
C#
using Jiaowu.Api.Infrastructure.Auth;
|
|
using Jiaowu.Api.Infrastructure.Persistence;
|
|
using Microsoft.Data.Sqlite;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.Options;
|
|
|
|
namespace Jiaowu.Api.Tests;
|
|
|
|
public sealed class PasskeyTests
|
|
{
|
|
[Fact]
|
|
public async Task Ceremony_is_single_use()
|
|
{
|
|
await using var connection = new SqliteConnection("Data Source=:memory:");
|
|
await connection.OpenAsync();
|
|
await using var db = new AppDbContext(
|
|
new DbContextOptionsBuilder<AppDbContext>().UseSqlite(connection).Options);
|
|
await db.Database.EnsureCreatedAsync();
|
|
var store = new PasskeyCeremonyStore(db, Options.Create(EnabledOptions()));
|
|
var expected = new PasskeyCeremony(
|
|
PasskeyCeremonyKind.Authentication,
|
|
Guid.NewGuid(),
|
|
false,
|
|
null,
|
|
"{\"challenge\":\"test\"}");
|
|
|
|
var id = await store.CreateAsync(expected);
|
|
var first = await store.TakeAsync(id);
|
|
var replay = await store.TakeAsync(id);
|
|
|
|
Assert.Equal(expected, first);
|
|
Assert.Null(replay);
|
|
Assert.DoesNotContain(id, (await db.PasskeyCeremonyStates.SingleAsync()).TokenHash);
|
|
}
|
|
|
|
[Fact]
|
|
public void Enabled_options_reject_non_https_remote_origin()
|
|
{
|
|
var options = EnabledOptions();
|
|
options.RelyingPartyId = "example.edu.cn";
|
|
options.Origins = ["http://example.edu.cn"];
|
|
|
|
var exception = Assert.Throws<InvalidOperationException>(options.Validate);
|
|
|
|
Assert.Contains("HTTPS", exception.Message);
|
|
}
|
|
|
|
[Fact]
|
|
public void Enabled_options_reject_origin_outside_relying_party()
|
|
{
|
|
var options = EnabledOptions();
|
|
options.RelyingPartyId = "example.edu.cn";
|
|
options.Origins = ["https://accounts.example.com"];
|
|
|
|
var exception = Assert.Throws<InvalidOperationException>(options.Validate);
|
|
|
|
Assert.Contains("RP ID", exception.Message);
|
|
}
|
|
|
|
[Fact]
|
|
public void Loopback_development_origin_is_valid()
|
|
{
|
|
var options = EnabledOptions();
|
|
|
|
options.Validate();
|
|
var configuration = options.CreateConfiguration();
|
|
|
|
Assert.Equal("localhost", configuration.RPID);
|
|
Assert.Contains("http://localhost:5173", configuration.Origins);
|
|
}
|
|
|
|
private static PasskeyOptions EnabledOptions() => new()
|
|
{
|
|
Enabled = true,
|
|
RelyingPartyId = "localhost",
|
|
RelyingPartyName = "测试教务",
|
|
Origins = ["http://localhost:5173"],
|
|
ChallengeMinutes = 5,
|
|
MaximumCredentialsPerUser = 10
|
|
};
|
|
}
|