using System.Diagnostics;
using System.Globalization;
using System.Net;
namespace Azaion.Missions.E2E.Helpers;
///
/// Spawns standalone azaion/missions:test containers via docker run
/// (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.
///
///
/// Like , this helper is gated on
/// COMPOSE_RESTART_ENABLED=1 and a docker CLI on PATH; tests using it
/// must when the gate fails so
/// CI environments without Docker access skip with an explicit reason
/// instead of silently passing.
///
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;
///
/// Runs docker run --rm --name <name> --network <net> <env> <image>,
/// waits for the container to exit (up to ),
/// 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).
///
public static RunResult RunUntilExit(
string containerName,
IReadOnlyDictionary 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}");
}
///
/// Captures docker inspect --format '{{.State.StartedAt}}' 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.
///
public static string GetStartedAt(string containerName)
{
Run("docker",
$"inspect --format '{{{{.State.StartedAt}}}}' {containerName}",
out var stdout, out _);
return stdout.Trim().Trim('\'');
}
///
/// Starts a missions container detached (-d) and polls its /health
/// endpoint over the shared e2e network until it responds 200 (or
/// 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 docker logs for log-line assertions.
///
public static async Task StartAndWaitForHealthAsync(
string containerName,
IReadOnlyDictionary 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 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);
}