mirror of
https://github.com/azaion/missions.git
synced 2026-06-22 12:41:07 +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,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