mirror of
https://github.com/azaion/missions.git
synced 2026-06-22 17:41:08 +00:00
[AZ-581] [AZ-582] [AZ-583] [AZ-584] Sec+Res NFT tests
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>
This commit is contained in:
@@ -0,0 +1,52 @@
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
|
||||
namespace Azaion.Missions.E2E.Helpers;
|
||||
|
||||
/// <summary>
|
||||
/// Scrapes <c>docker logs</c> from inside the e2e-consumer container, used
|
||||
/// to assert "unhandled exception" and structured log lines emitted by the
|
||||
/// SUT (NFT-SEC-08 stack-not-leaked, NFT-RES-01..04 cascade/migrator log
|
||||
/// invariants, NFT-RES-06 Npgsql 3D000).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Like the docker-compose fixtures, this helper requires docker CLI access
|
||||
/// (and typically a docker socket bind). Tests that depend on it must
|
||||
/// <see cref="Xunit.Skip.IfNot(bool, string)"/> when the CLI is not
|
||||
/// available — silent passing is rejected.
|
||||
/// </remarks>
|
||||
public static class DockerLogs
|
||||
{
|
||||
public static bool Contains(string container, string needle, DateTime sinceUtc)
|
||||
=> Read(container, sinceUtc).Contains(needle, StringComparison.Ordinal);
|
||||
|
||||
/// <summary>Returns the combined stdout+stderr log slice since <paramref name="sinceUtc"/>.</summary>
|
||||
public static string Read(string container, DateTime? sinceUtc = null)
|
||||
{
|
||||
var args = sinceUtc is { } cutoff
|
||||
? $"logs --since {cutoff.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture)} {container}"
|
||||
: $"logs {container}";
|
||||
var psi = new ProcessStartInfo("docker", args)
|
||||
{
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
UseShellExecute = false
|
||||
};
|
||||
try
|
||||
{
|
||||
using var p = Process.Start(psi)
|
||||
?? throw new InvalidOperationException("docker command not available");
|
||||
var stdout = p.StandardOutput.ReadToEnd();
|
||||
var stderr = p.StandardError.ReadToEnd();
|
||||
p.WaitForExit();
|
||||
return stdout + stderr;
|
||||
}
|
||||
catch (System.ComponentModel.Win32Exception)
|
||||
{
|
||||
// No docker CLI in PATH — surface, do not silently pass.
|
||||
throw new InvalidOperationException(
|
||||
$"docker CLI not available; cannot scrape logs for '{container}'. " +
|
||||
"Mount /var/run/docker.sock and install docker-cli in the e2e-consumer image.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace Azaion.Missions.E2E.Helpers;
|
||||
|
||||
/// <summary>
|
||||
/// Test-only ECDSA P-256 signer used by NFT-SEC-02 to mint a token signed by
|
||||
/// a keypair the JWKS endpoint never published. This is the ONE in-test
|
||||
/// signing path allowed by the task spec — every other test mints via the
|
||||
/// jwks-mock <c>POST /sign</c> endpoint.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The private key lives entirely in the test process and is disposed with
|
||||
/// the helper. The wire shape mirrors <c>JwksMock.TokenSigner</c> (JWS-compact
|
||||
/// ES256) so the only thing that differs from a "real" mock-minted token is
|
||||
/// the signing key — defeating any IssuerSigningKeyResolver that fails to
|
||||
/// match <c>kid</c> against the published JWKS.
|
||||
/// </remarks>
|
||||
public sealed class ForeignKeypair : IDisposable
|
||||
{
|
||||
private readonly ECDsa _ec;
|
||||
private readonly string _kid;
|
||||
|
||||
public ForeignKeypair()
|
||||
{
|
||||
_ec = ECDsa.Create(ECCurve.NamedCurves.nistP256);
|
||||
// Deterministic kid that is clearly NOT what jwks-mock issues
|
||||
// (mock kids are base64url SHA-256 hashes; this label is plain ASCII).
|
||||
_kid = "foreign-keypair-not-in-jwks";
|
||||
}
|
||||
|
||||
public string Mint(string issuer, string audience, string permissions, int expOffsetSeconds = 3600)
|
||||
{
|
||||
var nowUnix = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
|
||||
var expUnix = nowUnix + expOffsetSeconds;
|
||||
|
||||
var header = new JsonObject
|
||||
{
|
||||
["alg"] = "ES256",
|
||||
["kid"] = _kid,
|
||||
["typ"] = "JWT"
|
||||
};
|
||||
var payload = new JsonObject
|
||||
{
|
||||
["iss"] = issuer,
|
||||
["aud"] = audience,
|
||||
["iat"] = nowUnix,
|
||||
["exp"] = expUnix,
|
||||
["permissions"] = permissions
|
||||
};
|
||||
|
||||
var headerSeg = Base64UrlEncode(JsonSerializer.SerializeToUtf8Bytes(header));
|
||||
var payloadSeg = Base64UrlEncode(JsonSerializer.SerializeToUtf8Bytes(payload));
|
||||
var signingInput = Encoding.ASCII.GetBytes($"{headerSeg}.{payloadSeg}");
|
||||
var signature = _ec.SignData(signingInput, HashAlgorithmName.SHA256,
|
||||
DSASignatureFormat.IeeeP1363FixedFieldConcatenation);
|
||||
var sigSeg = Base64UrlEncode(signature);
|
||||
return $"{headerSeg}.{payloadSeg}.{sigSeg}";
|
||||
}
|
||||
|
||||
public void Dispose() => _ec.Dispose();
|
||||
|
||||
private static string Base64UrlEncode(ReadOnlySpan<byte> bytes)
|
||||
{
|
||||
var b64 = Convert.ToBase64String(bytes);
|
||||
return b64.Replace('+', '-').Replace('/', '_').TrimEnd('=');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
|
||||
namespace Azaion.Missions.E2E.Helpers;
|
||||
|
||||
/// <summary>
|
||||
/// Spawns standalone <c>azaion/missions:test</c> containers via <c>docker run</c>
|
||||
/// (NOT compose) so startup-time behavior can be exercised independently of
|
||||
/// the long-running compose stack. Used by NFT-SEC-12, NFT-SEC-13,
|
||||
/// NFT-RES-05, NFT-RES-06 — each provides its own env override map and asserts
|
||||
/// against the captured exit code + logs.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Like <see cref="Fixtures.ComposeRestartFixture"/>, this helper is gated on
|
||||
/// <c>COMPOSE_RESTART_ENABLED=1</c> and a docker CLI on PATH; tests using it
|
||||
/// must <see cref="Xunit.Skip.IfNot(bool, string)"/> when the gate fails so
|
||||
/// CI environments without Docker access skip with an explicit reason
|
||||
/// instead of silently passing.
|
||||
/// </remarks>
|
||||
public static class MissionsContainerHelper
|
||||
{
|
||||
public const string MissionsImageEnvVar = "MISSIONS_TEST_IMAGE";
|
||||
public const string DefaultMissionsImage = "azaion/missions:test";
|
||||
public const string NetworkEnvVar = "MISSIONS_TEST_NETWORK";
|
||||
public const string DefaultNetwork = "missions-e2e-net";
|
||||
|
||||
public static bool Enabled =>
|
||||
Environment.GetEnvironmentVariable("COMPOSE_RESTART_ENABLED") == "1";
|
||||
|
||||
public static string Image =>
|
||||
Environment.GetEnvironmentVariable(MissionsImageEnvVar) ?? DefaultMissionsImage;
|
||||
|
||||
public static string Network =>
|
||||
Environment.GetEnvironmentVariable(NetworkEnvVar) ?? DefaultNetwork;
|
||||
|
||||
/// <summary>
|
||||
/// Runs <c>docker run --rm --name <name> --network <net> <env> <image></c>,
|
||||
/// waits for the container to exit (up to <paramref name="timeout"/>),
|
||||
/// and returns its exit code + combined logs. Forces removal of any
|
||||
/// stale container with the same name before starting (an earlier crash
|
||||
/// can leave a stopped container behind).
|
||||
/// </summary>
|
||||
public static RunResult RunUntilExit(
|
||||
string containerName,
|
||||
IReadOnlyDictionary<string, string> envOverrides,
|
||||
TimeSpan timeout)
|
||||
{
|
||||
ForceRemove(containerName);
|
||||
var args = BuildRunArgs(containerName, envOverrides);
|
||||
Run("docker", args, out var runStdout, out var runStderr);
|
||||
|
||||
var deadline = DateTime.UtcNow + timeout;
|
||||
while (DateTime.UtcNow < deadline)
|
||||
{
|
||||
if (TryGetExitCode(containerName, out var exitCode))
|
||||
{
|
||||
var logs = ReadLogs(containerName);
|
||||
ForceRemove(containerName);
|
||||
return new RunResult(exitCode, logs, runStdout, runStderr);
|
||||
}
|
||||
Thread.Sleep(250);
|
||||
}
|
||||
|
||||
var partialLogs = ReadLogs(containerName);
|
||||
ForceRemove(containerName);
|
||||
throw new TimeoutException(
|
||||
$"container '{containerName}' did not exit within {timeout.TotalSeconds:F0}s. " +
|
||||
$"Partial logs:\n{partialLogs}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Captures <c>docker inspect --format '{{.State.StartedAt}}'</c> for a
|
||||
/// running container, returned as a stable ISO-8601 string. Used by
|
||||
/// NFT-RES-07 to assert the missions service did NOT restart during a
|
||||
/// JWKS rotation flow.
|
||||
/// </summary>
|
||||
public static string GetStartedAt(string containerName)
|
||||
{
|
||||
Run("docker",
|
||||
$"inspect --format '{{{{.State.StartedAt}}}}' {containerName}",
|
||||
out var stdout, out _);
|
||||
return stdout.Trim().Trim('\'');
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Starts a missions container detached (<c>-d</c>) and polls its <c>/health</c>
|
||||
/// endpoint over the shared e2e network until it responds 200 (or
|
||||
/// <paramref name="readyTimeout"/> elapses). Used by tests that need a
|
||||
/// running SUT with non-default env (NFT-SEC-12 HTTP-not-HTTPS,
|
||||
/// NFT-SEC-13 CORS preflight) — the test then drives the container
|
||||
/// over the network and reads <c>docker logs</c> for log-line assertions.
|
||||
/// </summary>
|
||||
public static async Task<DetachedContainer> StartAndWaitForHealthAsync(
|
||||
string containerName,
|
||||
IReadOnlyDictionary<string, string> envOverrides,
|
||||
TimeSpan readyTimeout)
|
||||
{
|
||||
ForceRemove(containerName);
|
||||
var args = BuildRunArgs(containerName, envOverrides);
|
||||
Run("docker", args, out _, out _);
|
||||
|
||||
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(2) };
|
||||
var healthUrl = new Uri($"http://{containerName}:8080/health");
|
||||
var deadline = DateTime.UtcNow + readyTimeout;
|
||||
while (DateTime.UtcNow < deadline)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var resp = await http.GetAsync(healthUrl);
|
||||
if (resp.StatusCode == HttpStatusCode.OK)
|
||||
return new DetachedContainer(containerName);
|
||||
}
|
||||
catch (HttpRequestException) { /* container not yet listening */ }
|
||||
catch (TaskCanceledException) { /* slow first response */ }
|
||||
await Task.Delay(500);
|
||||
}
|
||||
|
||||
// Health never came up — capture logs for the failure message before
|
||||
// tearing down, so the test reporter shows why the harness gave up.
|
||||
var logs = ReadLogs(containerName);
|
||||
ForceRemove(containerName);
|
||||
throw new TimeoutException(
|
||||
$"container '{containerName}' did not become healthy within {readyTimeout.TotalSeconds:F0}s. " +
|
||||
$"Logs:\n{logs}");
|
||||
}
|
||||
|
||||
public sealed class DetachedContainer : IDisposable
|
||||
{
|
||||
public string Name { get; }
|
||||
public DetachedContainer(string name) => Name = name;
|
||||
public string ReadLogs() => MissionsContainerHelper.ReadLogs(Name);
|
||||
public void Dispose() => ForceRemove(Name);
|
||||
}
|
||||
|
||||
private static string BuildRunArgs(
|
||||
string containerName,
|
||||
IReadOnlyDictionary<string, string> envOverrides)
|
||||
{
|
||||
var sb = new System.Text.StringBuilder();
|
||||
sb.Append("run --rm -d ");
|
||||
sb.Append("--name ").Append(containerName).Append(' ');
|
||||
sb.Append("--network ").Append(Network).Append(' ');
|
||||
foreach (var (key, value) in envOverrides)
|
||||
{
|
||||
sb.Append("-e ").Append(key).Append('=').Append('"')
|
||||
.Append(value.Replace("\"", "\\\"", StringComparison.Ordinal))
|
||||
.Append("\" ");
|
||||
}
|
||||
sb.Append(Image);
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
private static bool TryGetExitCode(string containerName, out int exitCode)
|
||||
{
|
||||
// `docker inspect` succeeds while the container exists (running OR
|
||||
// exited). Once `--rm` removes it the inspect call fails — but we
|
||||
// already captured exitCode by then.
|
||||
var psi = new ProcessStartInfo("docker",
|
||||
$"inspect --format '{{{{.State.Running}}}} {{{{.State.ExitCode}}}}' {containerName}")
|
||||
{
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
UseShellExecute = false
|
||||
};
|
||||
using var p = Process.Start(psi)
|
||||
?? throw new InvalidOperationException("docker CLI not available");
|
||||
var stdout = p.StandardOutput.ReadToEnd();
|
||||
p.WaitForExit();
|
||||
if (p.ExitCode != 0)
|
||||
{
|
||||
// Container is gone (already removed); treat as "still in flight".
|
||||
exitCode = 0;
|
||||
return false;
|
||||
}
|
||||
var parts = stdout.Trim().Trim('\'').Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (parts.Length < 2 ||
|
||||
!bool.TryParse(parts[0], out var running) ||
|
||||
!int.TryParse(parts[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out exitCode))
|
||||
{
|
||||
exitCode = 0;
|
||||
return false;
|
||||
}
|
||||
return !running;
|
||||
}
|
||||
|
||||
internal static string ReadLogs(string containerName)
|
||||
{
|
||||
var psi = new ProcessStartInfo("docker", $"logs {containerName}")
|
||||
{
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
UseShellExecute = false
|
||||
};
|
||||
using var p = Process.Start(psi);
|
||||
if (p is null) return string.Empty;
|
||||
var stdout = p.StandardOutput.ReadToEnd();
|
||||
var stderr = p.StandardError.ReadToEnd();
|
||||
p.WaitForExit();
|
||||
return stdout + stderr;
|
||||
}
|
||||
|
||||
private static void ForceRemove(string containerName)
|
||||
{
|
||||
var psi = new ProcessStartInfo("docker", $"rm -f {containerName}")
|
||||
{
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
UseShellExecute = false
|
||||
};
|
||||
try
|
||||
{
|
||||
using var p = Process.Start(psi);
|
||||
p?.WaitForExit();
|
||||
}
|
||||
catch (System.ComponentModel.Win32Exception)
|
||||
{
|
||||
// docker CLI absent — let the caller's Enabled check surface the issue.
|
||||
throw new InvalidOperationException(
|
||||
"docker CLI not available in test container; " +
|
||||
"MissionsContainerHelper requires docker access (set COMPOSE_RESTART_ENABLED=1 and mount the socket).");
|
||||
}
|
||||
}
|
||||
|
||||
private static void Run(string file, string args, out string stdout, out string stderr)
|
||||
{
|
||||
var psi = new ProcessStartInfo(file, args)
|
||||
{
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
UseShellExecute = false
|
||||
};
|
||||
using var p = Process.Start(psi)
|
||||
?? throw new InvalidOperationException($"failed to launch `{file} {args}`");
|
||||
stdout = p.StandardOutput.ReadToEnd();
|
||||
stderr = p.StandardError.ReadToEnd();
|
||||
p.WaitForExit();
|
||||
if (p.ExitCode != 0)
|
||||
throw new InvalidOperationException(
|
||||
$"`{file} {args}` exited {p.ExitCode}.\nstdout: {stdout}\nstderr: {stderr}");
|
||||
}
|
||||
|
||||
public sealed record RunResult(int ExitCode, string Logs, string RunStdout, string RunStderr);
|
||||
}
|
||||
Reference in New Issue
Block a user