Files
missions/tests/Azaion.Missions.JwksMock/Services/TokenSigner.cs
T
Oleksandr Bezdieniezhnykh ccd85a09df
ci/woodpecker/push/build-arm Pipeline failed
[AZ-576] Add e2e test infrastructure (xUnit + jwks-mock + reporting)
Scaffold the blackbox test project the rest of epic AZ-575 (AZ-577..AZ-586)
will build on. Two new csprojs under tests/, plus the TLS materials and
TRX->CSV reporting hand-off the existing docker-compose.test.yml already
calls for.

JWKS mock (tests/Azaion.Missions.JwksMock/):
- ASP.NET Core minimal API on .NET 10, no NuGet deps; JWS is hand-rolled
  to keep the surface tight and avoid version drift with the SUT
- KeyStore with one in-memory ECDSA P-256 keypair + retired-key grace
  window for NFT-RES-07 / NFT-SEC-11 rotation observability
- Endpoints: GET /.well-known/jwks.json, POST /sign, POST /rotate-key
- Mock-only alg_override / kid_override switches drive NFT-SEC-09/10/11
- TLS keypair committed under tls/; tests/jwks-mock-ca.crt is a copy
  mounted into both missions and e2e-consumer per docker-compose.test.yml

E2E consumer (tests/Azaion.Missions.E2E.Tests/):
- xUnit 2.9.2 + Bogus 35.6.1 + Npgsql 10.0.2 + Xunit.SkippableFact 1.4.13
- TestBase / TokenMinter scaffolding for downstream tasks
- Fixtures/ for DbReset, DbSeed, ComposeRestart, JwksRotate, JwksMockReverse
- Helpers/ for DbAssertions (side-channel), HttpAssertions, FixtureSql
- 8 Tests/<category>/Sanity.cs discovery smoke tests (AC-3)
- Tests/InfrastructureSanity.cs SkippableFacts for AC-1/2/5/6
- Tests/AaaPatternEnforcement.cs greps source files for AC-7
- Tests/Reporting/TrxToCsvPostProcessorTests.cs covers AC-4
- Reporting/TrxToCsvPostProcessor.cs handles VSTest TRX -> environment.md
  CSV; xUnit traits are not propagated by the TRX logger so the converter
  reflects them out of the test DLL via GetCustomAttributesData
- Reporting.Cli/ is a separate console csproj that links the converter
  source files (test project excludes Reporting.Cli/** from compile)
- Dockerfile + entrypoint.sh wire dotnet test -> trx -> csv inside the
  e2e-consumer container the compose file already references

Local verification: 13 pass, 3 skip (with explicit reasons), 0 fail.
End-to-end TRX->CSV manually verified against environment.md header spec.
Docker stack build is handed off to autodev Step 7 (test-run skill).

Reports under _docs/03_implementation/.
AZ-576 task spec moved to _docs/tasks/done/.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-15 06:57:40 +03:00

103 lines
3.4 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";
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.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? Subject,
string? AlgOverride,
string? KidOverride);
public sealed record SignResult(string Token, string Kid);