mirror of
https://github.com/azaion/admin.git
synced 2026-06-22 07:31:09 +00:00
[AZ-531] [AZ-532] Refresh-token rotation + ES256 signing with JWKS
AZ-531 — /login now returns access (15 min) + opaque refresh; rotation on /token/refresh; reuse of a rotated refresh kills the entire session family per OAuth 2.1 §6.1; sliding 8 h + absolute 12 h windows; new sessions table with serializable-tx rotation. AZ-532 — switched access-token signing from HS256 shared-secret to ES256 file-backed PEMs; new JwtSigningKeyProvider, JWKS at /.well-known/jwks.json with public-only fields and 1 h cache; ValidAlgorithms pinned so an HS256-with-public-key alg-confusion attack is rejected; production keys ignored under secrets/jwt-keys, deterministic test fixtures committed under e2e/test-keys. Tests: 10/10 new ACs covered (RefreshTokenFlowTests, AsymmetricSigningTests). Pre-existing AuthTests.Jwt_contains_expected_claims_and_lifetime updated for 15 min + sid/jti claims; SecurityTests.Expired_jwt re-signed with ES256; ResilienceTests login p95 SLO raised 500 ms → 1500 ms in test env to reflect Argon2id + dual DB writes + ES256 sign cost (production Linux budget unchanged, see batch_02_cycle2_review.md F1). Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -33,14 +33,27 @@ public sealed class ApiClient : IDisposable
|
||||
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||
}
|
||||
|
||||
public async Task<LoginResponse> LoginFullAsync(string email, string password, CancellationToken cancellationToken = default)
|
||||
{
|
||||
using var response = await PostAsync("/login", new { email, password }, cancellationToken).ConfigureAwait(false);
|
||||
response.EnsureSuccessStatusCode();
|
||||
var body = await response.Content.ReadFromJsonAsync<LoginResponse>(JsonOptions, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
if (body?.AccessToken is not { Length: > 0 })
|
||||
throw new InvalidOperationException("Login response did not contain an access token.");
|
||||
if (body.RefreshToken is not { Length: > 0 })
|
||||
throw new InvalidOperationException("Login response did not contain a refresh token.");
|
||||
return body;
|
||||
}
|
||||
|
||||
public async Task<string> LoginAsync(string email, string password, CancellationToken cancellationToken = default)
|
||||
{
|
||||
using var response = await PostAsync("/login", new { email, password }, cancellationToken).ConfigureAwait(false);
|
||||
response.EnsureSuccessStatusCode();
|
||||
var body = await response.Content.ReadFromJsonAsync<LoginResponse>(JsonOptions, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
if (body?.Token is not { Length: > 0 } t)
|
||||
throw new InvalidOperationException("Login response did not contain a token.");
|
||||
if (body?.AccessToken is not { Length: > 0 } t)
|
||||
throw new InvalidOperationException("Login response did not contain an access token.");
|
||||
return t;
|
||||
}
|
||||
|
||||
@@ -84,8 +97,11 @@ public sealed class ApiClient : IDisposable
|
||||
return _httpClient.PostAsync(url, content, cancellationToken);
|
||||
}
|
||||
|
||||
private sealed class LoginResponse
|
||||
public sealed class LoginResponse
|
||||
{
|
||||
public string Token { get; init; } = "";
|
||||
public string AccessToken { get; init; } = "";
|
||||
public DateTime AccessExp { get; init; }
|
||||
public string RefreshToken { get; init; } = "";
|
||||
public DateTime RefreshExp { get; init; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,17 @@ namespace Azaion.E2E.Helpers;
|
||||
/// or seed rows directly. Used by AZ-536 (password hash format) and AZ-537
|
||||
/// (lockout state, audit_events) acceptance tests.
|
||||
/// </summary>
|
||||
public sealed record SessionRow(
|
||||
Guid Id,
|
||||
Guid UserId,
|
||||
Guid FamilyId,
|
||||
DateTime IssuedAt,
|
||||
DateTime ExpiresAt,
|
||||
DateTime? RevokedAt,
|
||||
string? RevokedReason,
|
||||
Guid? ParentSessionId,
|
||||
DateTime FamilyStartedAt);
|
||||
|
||||
public sealed class DbHelper
|
||||
{
|
||||
private readonly string _connectionString;
|
||||
@@ -108,6 +119,87 @@ public sealed class DbHelper
|
||||
await cmd.ExecuteNonQueryAsync(ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// AZ-531 — looks up a session row by the refresh token's sha256 hash. Tests
|
||||
/// hash the opaque token the same way RefreshTokenService does, then assert
|
||||
/// on the persisted row.
|
||||
/// </summary>
|
||||
public async Task<SessionRow?> GetSessionByHash(string refreshHashHex, CancellationToken ct = default)
|
||||
{
|
||||
await using var conn = await OpenAsync(ct);
|
||||
await using var cmd = new NpgsqlCommand(@"
|
||||
SELECT id, user_id, family_id, issued_at, expires_at, revoked_at,
|
||||
revoked_reason, parent_session_id, family_started_at
|
||||
FROM public.sessions
|
||||
WHERE refresh_hash = @h", conn);
|
||||
cmd.Parameters.AddWithValue("h", refreshHashHex);
|
||||
await using var rd = await cmd.ExecuteReaderAsync(ct);
|
||||
if (!await rd.ReadAsync(ct)) return null;
|
||||
return new SessionRow(
|
||||
Id: rd.GetGuid(0),
|
||||
UserId: rd.GetGuid(1),
|
||||
FamilyId: rd.GetGuid(2),
|
||||
IssuedAt: DateTime.SpecifyKind(rd.GetDateTime(3), DateTimeKind.Utc),
|
||||
ExpiresAt: DateTime.SpecifyKind(rd.GetDateTime(4), DateTimeKind.Utc),
|
||||
RevokedAt: rd.IsDBNull(5) ? null : DateTime.SpecifyKind(rd.GetDateTime(5), DateTimeKind.Utc),
|
||||
RevokedReason: rd.IsDBNull(6) ? null : rd.GetString(6),
|
||||
ParentSessionId: rd.IsDBNull(7) ? null : rd.GetGuid(7),
|
||||
FamilyStartedAt: DateTime.SpecifyKind(rd.GetDateTime(8), DateTimeKind.Utc));
|
||||
}
|
||||
|
||||
public async Task<int> CountActiveInFamily(Guid familyId, CancellationToken ct = default)
|
||||
{
|
||||
await using var conn = await OpenAsync(ct);
|
||||
await using var cmd = new NpgsqlCommand(
|
||||
"SELECT COUNT(*) FROM public.sessions WHERE family_id = @f AND revoked_at IS NULL", conn);
|
||||
cmd.Parameters.AddWithValue("f", familyId);
|
||||
return Convert.ToInt32(await cmd.ExecuteScalarAsync(ct), CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
public async Task<int> CountReuseRevokedInFamily(Guid familyId, CancellationToken ct = default)
|
||||
{
|
||||
await using var conn = await OpenAsync(ct);
|
||||
await using var cmd = new NpgsqlCommand(
|
||||
"SELECT COUNT(*) FROM public.sessions WHERE family_id = @f AND revoked_reason = 'reuse_detected'", conn);
|
||||
cmd.Parameters.AddWithValue("f", familyId);
|
||||
return Convert.ToInt32(await cmd.ExecuteScalarAsync(ct), CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// AZ-531 AC-4 — backdate a family so the absolute-expiry check fires
|
||||
/// without waiting 12 hours of wall-clock time.
|
||||
/// </summary>
|
||||
public async Task BackdateFamily(Guid familyId, TimeSpan ageFromNow, CancellationToken ct = default)
|
||||
{
|
||||
await using var conn = await OpenAsync(ct);
|
||||
await using var cmd = new NpgsqlCommand(@"
|
||||
UPDATE public.sessions
|
||||
SET family_started_at = now() - @age,
|
||||
issued_at = now() - @age,
|
||||
last_used_at = now() - @age
|
||||
WHERE family_id = @f", conn);
|
||||
cmd.Parameters.AddWithValue("age", ageFromNow);
|
||||
cmd.Parameters.AddWithValue("f", familyId);
|
||||
await cmd.ExecuteNonQueryAsync(ct);
|
||||
}
|
||||
|
||||
public async Task DeleteSessionsFor(string email, CancellationToken ct = default)
|
||||
{
|
||||
await using var conn = await OpenAsync(ct);
|
||||
await using var cmd = new NpgsqlCommand(@"
|
||||
DELETE FROM public.sessions
|
||||
WHERE user_id = (SELECT id FROM public.users WHERE email = @e)", conn);
|
||||
cmd.Parameters.AddWithValue("e", email);
|
||||
await cmd.ExecuteNonQueryAsync(ct);
|
||||
}
|
||||
|
||||
public static string HashRefreshToken(string opaqueToken)
|
||||
{
|
||||
var bytes = System.Text.Encoding.ASCII.GetBytes(opaqueToken);
|
||||
var digest = System.Security.Cryptography.SHA256.HashData(bytes);
|
||||
return Convert.ToHexString(digest);
|
||||
}
|
||||
|
||||
private async Task<NpgsqlConnection> OpenAsync(CancellationToken ct)
|
||||
{
|
||||
var conn = new NpgsqlConnection(_connectionString);
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace Azaion.E2E.Helpers;
|
||||
|
||||
/// <summary>
|
||||
/// AZ-532 — test helper for loading the same ES256 PEMs the SUT trusts. Used
|
||||
/// by tests that need to forge a token (expired JWT, alg-confusion attack) so
|
||||
/// the only failure mode under test is the one being asserted.
|
||||
/// </summary>
|
||||
public static class JwtTestSigner
|
||||
{
|
||||
public static ECDsa LoadActive(string keysFolder, string activeKid)
|
||||
{
|
||||
var path = Path.Combine(keysFolder, $"{activeKid}.pem");
|
||||
if (!File.Exists(path))
|
||||
throw new FileNotFoundException(
|
||||
$"Test key '{path}' not found. The e2e-consumer container must mount the same /etc/jwt-keys directory as the SUT.",
|
||||
path);
|
||||
var ecdsa = ECDsa.Create();
|
||||
ecdsa.ImportFromPem(File.ReadAllText(path));
|
||||
return ecdsa;
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,8 @@ public sealed class TestSettings
|
||||
[Required] public string AdminPassword { get; init; } = null!;
|
||||
[Required] public string UploaderEmail { get; init; } = null!;
|
||||
[Required] public string UploaderPassword { get; init; } = null!;
|
||||
[Required] public string JwtSecret { get; init; } = null!;
|
||||
[Required] public string JwtKeysFolder { get; init; } = null!;
|
||||
[Required] public string JwtActiveKid { get; init; } = null!;
|
||||
[Required] public string TestDbConnectionString { get; init; } = null!;
|
||||
}
|
||||
|
||||
@@ -25,7 +26,8 @@ public sealed class TestFixture : IAsyncLifetime
|
||||
public string AdminPassword => Settings.AdminPassword;
|
||||
public string UploaderEmail => Settings.UploaderEmail;
|
||||
public string UploaderPassword => Settings.UploaderPassword;
|
||||
public string JwtSecret => Settings.JwtSecret;
|
||||
public string JwtKeysFolder => Settings.JwtKeysFolder;
|
||||
public string JwtActiveKid => Settings.JwtActiveKid;
|
||||
public DbHelper Db { get; private set; } = null!;
|
||||
public IConfiguration Configuration { get; private set; } = null!;
|
||||
|
||||
@@ -59,10 +61,18 @@ public sealed class TestFixture : IAsyncLifetime
|
||||
|
||||
public ApiClient CreateApiClient()
|
||||
{
|
||||
var client = new HttpClient { BaseAddress = new Uri(Settings.ApiBaseUrl, UriKind.Absolute), Timeout = TimeSpan.FromMinutes(5) };
|
||||
var client = CreateHttpClient();
|
||||
return new ApiClient(client, disposeClient: true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a fresh, unauthenticated <see cref="HttpClient"/> for tests that need
|
||||
/// to send raw requests (forged headers, manual JSON bodies, JWKS fetch, etc.).
|
||||
/// Caller owns the disposal.
|
||||
/// </summary>
|
||||
public HttpClient CreateHttpClient() =>
|
||||
new() { BaseAddress = new Uri(Settings.ApiBaseUrl, UriKind.Absolute), Timeout = TimeSpan.FromMinutes(5) };
|
||||
|
||||
public ApiClient CreateAuthenticatedClient(string token)
|
||||
{
|
||||
var api = CreateApiClient();
|
||||
|
||||
Reference in New Issue
Block a user