mirror of
https://github.com/azaion/missions.git
synced 2026-06-21 22:21:08 +00:00
24c4561bef
Batch 3 of test implementation cycle 1 (existing-code Step 6). - AZ-581 AuthClaimsTests: NFT-SEC-01..06+04b (foreign-keypair, byte-flip, 30s skew, iss/aud/perms, multi-value permissions array). - AZ-582 CrossCutting/ErrorRedaction/JwksRotation/StartupConfig/CorsConfig: NFT-SEC-07..13 (alg pin, kid rotation grace window, env fail-fast, CORS Production gate). - AZ-583 CascadeF3/CascadeF4/MigratorRestart: NFT-RES-01..04. CascadeF4 pins current walk-order divergence with carry_forward AC-4.6. - AZ-584 ConfigDbStartup/JwksRotationNoRestart/DefaultVehicleRace: NFT-RES-05..08. NFT-RES-08 pins current behaviour (unique-index closes the race) with carry_forward AC-1.4. Mock contract: SignBody accepts permissions OR permissions_array (mutually exclusive). TokenSigner validates kid_override against published keys so NFT-SEC-11 can assert "mock refuses old kid post-grace". Helpers added: ForeignKeypair (test-only ECDSA P-256), MissionsContainerHelper (docker-run wrapper for startup-time scenarios), DockerLogs. 7 of 22 new tests are Skippable, gated on COMPOSE_RESTART_ENABLED + docker CLI in the e2e-consumer image (explicit skip reason; no silent pass). Build green: test csproj + jwks-mock csproj. Co-authored-by: Cursor <cursoragent@cursor.com>
130 lines
4.6 KiB
C#
130 lines
4.6 KiB
C#
using System.Security.Cryptography;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using System.Text.Json.Nodes;
|
|
|
|
namespace Azaion.Missions.JwksMock.Services;
|
|
|
|
/// <summary>
|
|
/// Hand-rolls JWS-compact ES256 tokens for tests. Honors per-call overrides
|
|
/// the test harness uses to exercise NFT-SEC-* (alg confusion, unknown kid,
|
|
/// claim mismatch, etc.).
|
|
/// </summary>
|
|
public sealed class TokenSigner
|
|
{
|
|
private readonly KeyStore _keys;
|
|
private readonly TimeProvider _clock;
|
|
private readonly string _defaultIssuer;
|
|
private readonly string _defaultAudience;
|
|
|
|
public TokenSigner(KeyStore keys, TimeProvider clock, string defaultIssuer, string defaultAudience)
|
|
{
|
|
_keys = keys;
|
|
_clock = clock;
|
|
_defaultIssuer = defaultIssuer;
|
|
_defaultAudience = defaultAudience;
|
|
}
|
|
|
|
public SignResult Sign(SignRequest request)
|
|
{
|
|
var active = _keys.Active;
|
|
var kid = request.KidOverride ?? active.Kid;
|
|
var alg = request.AlgOverride ?? "ES256";
|
|
|
|
if (request.Permissions is not null && request.PermissionsArray is not null)
|
|
throw new ArgumentException(
|
|
"permissions and permissions_array are mutually exclusive — set at most one.",
|
|
nameof(request));
|
|
|
|
// NFT-SEC-11 AC-5.4: the mock refuses kid_override values that don't
|
|
// correspond to a currently-published kid (active or in-grace retired).
|
|
// Without this guard, a tester could mint a token with any kid string
|
|
// and the SUT would simply 401 on JWKS lookup — defeating the
|
|
// "post-grace mock refuses old kid" assertion.
|
|
if (request.KidOverride is not null)
|
|
{
|
|
var known = _keys.PublishedKeys().Select(k => k.Kid).ToHashSet(StringComparer.Ordinal);
|
|
if (!known.Contains(request.KidOverride))
|
|
throw new ArgumentException(
|
|
$"kid_override '{request.KidOverride}' is not a currently-published kid.",
|
|
nameof(request));
|
|
}
|
|
|
|
var nowUnix = _clock.GetUtcNow().ToUnixTimeSeconds();
|
|
var expUnix = nowUnix + (request.ExpOffsetSeconds ?? 3600);
|
|
|
|
var header = new JsonObject
|
|
{
|
|
["alg"] = alg,
|
|
["kid"] = kid,
|
|
["typ"] = "JWT"
|
|
};
|
|
|
|
var payload = new JsonObject
|
|
{
|
|
["iss"] = request.Issuer ?? _defaultIssuer,
|
|
["aud"] = request.Audience ?? _defaultAudience,
|
|
["iat"] = nowUnix,
|
|
["exp"] = expUnix
|
|
};
|
|
if (request.Permissions is not null)
|
|
payload["permissions"] = request.Permissions;
|
|
if (request.PermissionsArray is not null)
|
|
{
|
|
var arr = new JsonArray();
|
|
foreach (var p in request.PermissionsArray)
|
|
arr.Add(p);
|
|
payload["permissions"] = arr;
|
|
}
|
|
if (request.Subject is not null)
|
|
payload["sub"] = request.Subject;
|
|
|
|
var headerBytes = JsonSerializer.SerializeToUtf8Bytes(header);
|
|
var payloadBytes = JsonSerializer.SerializeToUtf8Bytes(payload);
|
|
var headerSeg = Base64Url.Encode(headerBytes);
|
|
var payloadSeg = Base64Url.Encode(payloadBytes);
|
|
|
|
// Signing input is the literal ASCII string "<header>.<payload>" per RFC 7515 §5.1.
|
|
var signingInput = Encoding.ASCII.GetBytes($"{headerSeg}.{payloadSeg}");
|
|
|
|
byte[] signature;
|
|
if (alg == "ES256")
|
|
{
|
|
signature = active.Ec.SignData(signingInput, HashAlgorithmName.SHA256, DSASignatureFormat.IeeeP1363FixedFieldConcatenation);
|
|
}
|
|
else if (alg == "HS256")
|
|
{
|
|
// alg-confusion attack vector for NFT-SEC-10. We sign with a key derived
|
|
// from the active public key so a naive validator that fails to enforce
|
|
// alg pinning would accept the token.
|
|
var pubKey = active.Ec.ExportSubjectPublicKeyInfo();
|
|
using var hmac = new HMACSHA256(pubKey);
|
|
signature = hmac.ComputeHash(signingInput);
|
|
}
|
|
else if (alg == "none")
|
|
{
|
|
signature = [];
|
|
}
|
|
else
|
|
{
|
|
throw new ArgumentException($"Unsupported alg_override '{alg}'", nameof(request));
|
|
}
|
|
|
|
var sigSeg = Base64Url.Encode(signature);
|
|
var token = $"{headerSeg}.{payloadSeg}.{sigSeg}";
|
|
return new SignResult(token, kid);
|
|
}
|
|
}
|
|
|
|
public sealed record SignRequest(
|
|
string? Issuer,
|
|
string? Audience,
|
|
int? ExpOffsetSeconds,
|
|
string? Permissions,
|
|
string[]? PermissionsArray,
|
|
string? Subject,
|
|
string? AlgOverride,
|
|
string? KidOverride);
|
|
|
|
public sealed record SignResult(string Token, string Kid);
|