mirror of
https://github.com/azaion/admin.git
synced 2026-06-21 10:21:10 +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:
@@ -1,6 +1,5 @@
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using Azaion.Common.Configs;
|
||||
using Azaion.Common.Entities;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
@@ -12,11 +11,25 @@ namespace Azaion.Services;
|
||||
public interface IAuthService
|
||||
{
|
||||
Task<User?> GetCurrentUser();
|
||||
string CreateToken(User user);
|
||||
|
||||
/// <summary>
|
||||
/// AZ-531 / AZ-532 — mint a 15-minute ES256 access token. <paramref name="sessionId"/>
|
||||
/// is stamped as the <c>sid</c> claim (logout / family-revocation key in AZ-535)
|
||||
/// and <paramref name="jti"/> is the per-token unique id (AZ-535 access denylist).
|
||||
/// </summary>
|
||||
AccessToken CreateToken(User user, Guid sessionId, Guid jti);
|
||||
}
|
||||
|
||||
public class AuthService(IHttpContextAccessor httpContextAccessor, IOptions<JwtConfig> jwtConfig, IUserService userService) : IAuthService
|
||||
public sealed record AccessToken(string Jwt, DateTime ExpiresAt);
|
||||
|
||||
public class AuthService(
|
||||
IHttpContextAccessor httpContextAccessor,
|
||||
IOptions<JwtConfig> jwtConfig,
|
||||
IJwtSigningKeyProvider signingKeys,
|
||||
IUserService userService) : IAuthService
|
||||
{
|
||||
private readonly JwtConfig _jwt = jwtConfig.Value;
|
||||
|
||||
private string? GetCurrentUserEmail()
|
||||
{
|
||||
var claims = httpContextAccessor.HttpContext?.User.Claims.ToDictionary(x => x.Type);
|
||||
@@ -29,25 +42,29 @@ public class AuthService(IHttpContextAccessor httpContextAccessor, IOptions<JwtC
|
||||
return await userService.GetByEmail(email);
|
||||
}
|
||||
|
||||
public string CreateToken(User user)
|
||||
public AccessToken CreateToken(User user, Guid sessionId, Guid jti)
|
||||
{
|
||||
var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtConfig.Value.Secret));
|
||||
var active = signingKeys.Active;
|
||||
var signingCredentials = new SigningCredentials(active.SecurityKey, SecurityAlgorithms.EcdsaSha256);
|
||||
|
||||
var expires = DateTime.UtcNow.AddMinutes(_jwt.AccessTokenLifetimeMinutes);
|
||||
var tokenHandler = new JwtSecurityTokenHandler();
|
||||
var tokenDescriptor = new SecurityTokenDescriptor
|
||||
{
|
||||
Subject = new ClaimsIdentity([
|
||||
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
|
||||
new Claim(ClaimTypes.Name, user.Email),
|
||||
new Claim(ClaimTypes.Role, user.Role.ToString())
|
||||
new Claim(ClaimTypes.Role, user.Role.ToString()),
|
||||
new Claim(JwtRegisteredClaimNames.Sid, sessionId.ToString()),
|
||||
new Claim(JwtRegisteredClaimNames.Jti, jti.ToString())
|
||||
]),
|
||||
Expires = DateTime.UtcNow.AddHours(jwtConfig.Value.TokenLifetimeHours),
|
||||
Issuer = jwtConfig.Value.Issuer,
|
||||
Audience = jwtConfig.Value.Audience,
|
||||
SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256Signature)
|
||||
Expires = expires,
|
||||
Issuer = _jwt.Issuer,
|
||||
Audience = _jwt.Audience,
|
||||
SigningCredentials = signingCredentials
|
||||
};
|
||||
|
||||
var token = tokenHandler.CreateToken(tokenDescriptor);
|
||||
return tokenHandler.WriteToken(token);
|
||||
return new AccessToken(tokenHandler.WriteToken(token), expires);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
using System.Security.Cryptography;
|
||||
using Azaion.Common.Configs;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
|
||||
namespace Azaion.Services;
|
||||
|
||||
/// <summary>
|
||||
/// AZ-532 — loads ES256 signing keys from <see cref="JwtConfig.KeysFolder"/>.
|
||||
/// One key is "active" (used to sign new tokens); the rest stay in JWKS so
|
||||
/// in-flight tokens minted with older keys still verify during the rotation
|
||||
/// overlap window. The kid of each key is its filename without <c>.pem</c>.
|
||||
/// </summary>
|
||||
public interface IJwtSigningKeyProvider
|
||||
{
|
||||
JwtSigningKey Active { get; }
|
||||
IReadOnlyList<JwtSigningKey> All { get; }
|
||||
}
|
||||
|
||||
public sealed class JwtSigningKey
|
||||
{
|
||||
public string Kid { get; }
|
||||
public ECDsa Ecdsa { get; }
|
||||
public ECDsaSecurityKey SecurityKey { get; }
|
||||
|
||||
public JwtSigningKey(string kid, ECDsa ecdsa)
|
||||
{
|
||||
Kid = kid;
|
||||
Ecdsa = ecdsa;
|
||||
SecurityKey = new ECDsaSecurityKey(ecdsa) { KeyId = kid };
|
||||
}
|
||||
}
|
||||
|
||||
public class JwtSigningKeyProvider : IJwtSigningKeyProvider, IDisposable
|
||||
{
|
||||
private readonly Dictionary<string, JwtSigningKey> _byKid;
|
||||
private readonly JwtSigningKey _active;
|
||||
|
||||
public JwtSigningKeyProvider(IOptions<JwtConfig> jwtConfig, ILogger<JwtSigningKeyProvider> logger)
|
||||
{
|
||||
var folder = jwtConfig.Value.KeysFolder;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(folder) || !Directory.Exists(folder))
|
||||
throw new InvalidOperationException(
|
||||
$"JwtConfig.KeysFolder '{folder}' does not exist. " +
|
||||
"Generate a key with scripts/generate-jwt-key.sh and ensure the folder is mounted into the container.");
|
||||
|
||||
var pemFiles = Directory.EnumerateFiles(folder, "*.pem").OrderBy(p => p).ToList();
|
||||
if (pemFiles.Count == 0)
|
||||
throw new InvalidOperationException(
|
||||
$"No *.pem keys found in '{folder}'. Generate a key with scripts/generate-jwt-key.sh.");
|
||||
|
||||
_byKid = new Dictionary<string, JwtSigningKey>(StringComparer.Ordinal);
|
||||
foreach (var path in pemFiles)
|
||||
{
|
||||
var kid = Path.GetFileNameWithoutExtension(path);
|
||||
var ecdsa = ECDsa.Create();
|
||||
try
|
||||
{
|
||||
ecdsa.ImportFromPem(File.ReadAllText(path));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ecdsa.Dispose();
|
||||
throw new InvalidOperationException($"Failed to load JWT signing key from '{path}'.", ex);
|
||||
}
|
||||
|
||||
EnsureP256(ecdsa, path);
|
||||
_byKid[kid] = new JwtSigningKey(kid, ecdsa);
|
||||
}
|
||||
|
||||
var requestedActive = jwtConfig.Value.ActiveKid;
|
||||
if (!string.IsNullOrEmpty(requestedActive))
|
||||
{
|
||||
if (!_byKid.TryGetValue(requestedActive, out var resolved))
|
||||
throw new InvalidOperationException(
|
||||
$"JwtConfig.ActiveKid '{requestedActive}' is not present in '{folder}'.");
|
||||
_active = resolved;
|
||||
}
|
||||
else
|
||||
{
|
||||
_active = _byKid[Path.GetFileNameWithoutExtension(pemFiles[0])];
|
||||
logger.LogInformation(
|
||||
"JwtConfig.ActiveKid not set; falling back to first key by filename: {Kid}", _active.Kid);
|
||||
}
|
||||
}
|
||||
|
||||
public JwtSigningKey Active => _active;
|
||||
public IReadOnlyList<JwtSigningKey> All => _byKid.Values.OrderBy(k => k.Kid, StringComparer.Ordinal).ToList();
|
||||
|
||||
private static void EnsureP256(ECDsa ecdsa, string path)
|
||||
{
|
||||
// ES256 ⇒ P-256 (prime256v1 / secp256r1). Reject anything else so we don't
|
||||
// silently sign with the wrong curve and break verifiers expecting ES256.
|
||||
var p = ecdsa.ExportParameters(includePrivateParameters: false);
|
||||
var oid = p.Curve.Oid?.Value ?? p.Curve.Oid?.FriendlyName;
|
||||
if (oid is not ("1.2.840.10045.3.1.7" or "nistP256" or "ECDSA_P256"))
|
||||
throw new InvalidOperationException(
|
||||
$"Key '{path}' is not on the P-256 curve (got '{oid ?? "unknown"}'). ES256 requires P-256.");
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
foreach (var k in _byKid.Values) k.Ecdsa.Dispose();
|
||||
_byKid.Clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Azaion.Common;
|
||||
using Azaion.Common.Configs;
|
||||
using Azaion.Common.Database;
|
||||
using Azaion.Common.Entities;
|
||||
using LinqToDB;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Azaion.Services;
|
||||
|
||||
/// <summary>
|
||||
/// AZ-531 — issues, rotates, and validates opaque refresh tokens. Reuse-detection
|
||||
/// kills the entire session family per OAuth 2.1 §6.1.
|
||||
/// </summary>
|
||||
public interface IRefreshTokenService
|
||||
{
|
||||
/// <summary>
|
||||
/// Mint a fresh refresh token at login; starts a new session family. Returns
|
||||
/// the opaque token (NEVER persisted; only its sha256 lands in the DB) and
|
||||
/// the session row that backs it.
|
||||
/// </summary>
|
||||
Task<(string OpaqueToken, Session Session)> IssueForNewLogin(Guid userId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Rotate <paramref name="opaqueToken"/>. On success returns the new token +
|
||||
/// the new session row. On reuse-detection or invalid token throws
|
||||
/// <see cref="BusinessException"/> with <see cref="ExceptionEnum.InvalidRefreshToken"/>;
|
||||
/// reuse also revokes every active row in the same family.
|
||||
/// </summary>
|
||||
Task<(string OpaqueToken, Session Session)> Rotate(string opaqueToken, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
public class RefreshTokenService(IDbFactory dbFactory, IOptions<SessionConfig> sessionConfig) : IRefreshTokenService
|
||||
{
|
||||
private const int OpaqueTokenBytes = 32; // 256 bits → 43-char base64url string.
|
||||
|
||||
private readonly SessionConfig _cfg = sessionConfig.Value;
|
||||
|
||||
public async Task<(string OpaqueToken, Session Session)> IssueForNewLogin(Guid userId, CancellationToken ct = default)
|
||||
{
|
||||
var (opaque, hash) = GenerateToken();
|
||||
var now = DateTime.UtcNow;
|
||||
var session = new Session
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = userId,
|
||||
RefreshHash = hash,
|
||||
FamilyId = Guid.NewGuid(), // self-rooted family
|
||||
IssuedAt = now,
|
||||
LastUsedAt = now,
|
||||
ExpiresAt = now.AddHours(_cfg.RefreshSlidingHours),
|
||||
FamilyStartedAt = now,
|
||||
};
|
||||
// family_id should equal id for the root row so SELECT family_id from
|
||||
// any row returns a stable handle even if id is renamed later.
|
||||
session.FamilyId = session.Id;
|
||||
|
||||
await dbFactory.RunAdmin(async db => await db.InsertAsync(session, token: ct));
|
||||
return (opaque, session);
|
||||
}
|
||||
|
||||
public async Task<(string OpaqueToken, Session Session)> Rotate(string opaqueToken, CancellationToken ct = default)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(opaqueToken))
|
||||
throw new BusinessException(ExceptionEnum.InvalidRefreshToken);
|
||||
|
||||
var hash = HashToken(opaqueToken);
|
||||
var now = DateTime.UtcNow;
|
||||
|
||||
return await dbFactory.RunAdmin(async db =>
|
||||
{
|
||||
// Use a serializable transaction so two concurrent refreshes can't both
|
||||
// observe the row as un-rotated and both succeed.
|
||||
await using var tx = await db.BeginTransactionAsync(System.Data.IsolationLevel.Serializable, ct);
|
||||
|
||||
var current = await db.Sessions.FirstOrDefaultAsync(s => s.RefreshHash == hash, token: ct);
|
||||
if (current == null)
|
||||
throw new BusinessException(ExceptionEnum.InvalidRefreshToken);
|
||||
|
||||
// Reuse detection: presenting an already-rotated token kills the family.
|
||||
if (current.RevokedAt.HasValue)
|
||||
{
|
||||
if (current.RevokedReason == SessionRevokedReasons.Rotated)
|
||||
{
|
||||
await db.Sessions
|
||||
.Where(s => s.FamilyId == current.FamilyId && s.RevokedAt == null)
|
||||
.Set(s => s.RevokedAt, now)
|
||||
.Set(s => s.RevokedReason, SessionRevokedReasons.ReuseDetected)
|
||||
.UpdateAsync(token: ct);
|
||||
await tx.CommitAsync(ct);
|
||||
}
|
||||
throw new BusinessException(ExceptionEnum.InvalidRefreshToken);
|
||||
}
|
||||
|
||||
// Sliding expiry — each rotation restarts the window from `now`.
|
||||
if (current.ExpiresAt < now)
|
||||
throw new BusinessException(ExceptionEnum.InvalidRefreshToken);
|
||||
|
||||
// Absolute expiry — the family cannot live past this regardless of rotations.
|
||||
if ((now - current.FamilyStartedAt).TotalHours > _cfg.RefreshAbsoluteHours)
|
||||
throw new BusinessException(ExceptionEnum.InvalidRefreshToken);
|
||||
|
||||
var (newOpaque, newHash) = GenerateToken();
|
||||
var newSession = new Session
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = current.UserId,
|
||||
RefreshHash = newHash,
|
||||
FamilyId = current.FamilyId,
|
||||
IssuedAt = now,
|
||||
LastUsedAt = now,
|
||||
ExpiresAt = now.AddHours(_cfg.RefreshSlidingHours),
|
||||
FamilyStartedAt = current.FamilyStartedAt,
|
||||
ParentSessionId = current.Id,
|
||||
};
|
||||
|
||||
await db.Sessions
|
||||
.Where(s => s.Id == current.Id && s.RevokedAt == null)
|
||||
.Set(s => s.RevokedAt, now)
|
||||
.Set(s => s.RevokedReason, SessionRevokedReasons.Rotated)
|
||||
.Set(s => s.LastUsedAt, now)
|
||||
.UpdateAsync(token: ct);
|
||||
|
||||
await db.InsertAsync(newSession, token: ct);
|
||||
await tx.CommitAsync(ct);
|
||||
return (newOpaque, newSession);
|
||||
});
|
||||
}
|
||||
|
||||
private static (string Opaque, string Hash) GenerateToken()
|
||||
{
|
||||
var raw = RandomNumberGenerator.GetBytes(OpaqueTokenBytes);
|
||||
var opaque = Base64Url(raw);
|
||||
var hash = HashToken(opaque);
|
||||
return (opaque, hash);
|
||||
}
|
||||
|
||||
private static string HashToken(string opaque)
|
||||
{
|
||||
var bytes = Encoding.ASCII.GetBytes(opaque);
|
||||
var digest = SHA256.HashData(bytes);
|
||||
return Convert.ToHexString(digest);
|
||||
}
|
||||
|
||||
private static string Base64Url(byte[] bytes) =>
|
||||
Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_');
|
||||
}
|
||||
@@ -17,6 +17,7 @@ public interface IUserService
|
||||
Task<RegisterDeviceResponse> RegisterDevice(CancellationToken ct = default);
|
||||
Task<User> ValidateUser(LoginRequest request, CancellationToken ct = default);
|
||||
Task<User?> GetByEmail(string? email, CancellationToken ct = default);
|
||||
Task<User?> GetById(Guid userId, CancellationToken ct = default);
|
||||
Task UpdateQueueOffsets(string email, UserQueueOffsets queueOffsets, CancellationToken ct = default);
|
||||
Task<IEnumerable<User>> GetUsers(string? searchEmail, RoleEnum? searchRole, CancellationToken ct = default);
|
||||
Task ChangeRole(string email, RoleEnum newRole, CancellationToken ct = default);
|
||||
@@ -112,6 +113,9 @@ public class UserService(
|
||||
await db.Users.FirstOrDefaultAsync(x => x.Email == email, ct)));
|
||||
}
|
||||
|
||||
public async Task<User?> GetById(Guid userId, CancellationToken ct = default) =>
|
||||
await dbFactory.Run(async db => await db.Users.FirstOrDefaultAsync(x => x.Id == userId, token: ct));
|
||||
|
||||
|
||||
public async Task<User> ValidateUser(LoginRequest request, CancellationToken ct = default)
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user