Files
Oleksandr Bezdieniezhnykh 24c4561bef [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>
2026-05-15 08:58:59 +03:00

116 lines
4.7 KiB
C#

using System.Net;
using System.Net.Http.Headers;
using Azaion.Missions.E2E.Fixtures;
using Azaion.Missions.E2E.Helpers;
using Npgsql;
using Xunit;
namespace Azaion.Missions.E2E.Tests.Resilience;
/// <summary>
/// NFT-RES-02 — waypoint cascade NOT transaction-wrapped, mirror of
/// NFT-RES-01. The spec expects a partial-state observation (detection=0,
/// waypoint=1) but the actual <see cref="Services.WaypointService"/> walk
/// makes the media SELECT the FIRST cross-table read after the waypoint
/// lookup — so a pre-request <c>DROP TABLE media</c> aborts the cascade
/// before any DELETE commits.
/// Traces: AC-4.6, AC-3.3.
/// </summary>
/// <remarks>
/// Carry-forward (spec-vs-code) marked with
/// <c>[Trait("carry_forward","AC-4.6/walk-order")]</c>: if the production
/// cascade is later refactored to commit detections/annotations BEFORE the
/// media lookup, the second assertion flips and this test fails loudly —
/// at which point the spec assertion should be restored.
/// </remarks>
[Collection("ResCascadeF4")]
[Trait("Category", "Res")]
[Trait("db_access", "seed-or-assert-only")]
public sealed class CascadeF4Tests : TestBase, IClassFixture<ComposeRestartFixture>
{
private readonly ComposeRestartFixture _restart;
public CascadeF4Tests(ComposeRestartFixture restart) => _restart = restart;
[SkippableFact]
[Trait("Traces", "AC-4.6,AC-3.3")]
[Trait("max_ms", "10000")]
[Trait("carry_forward", "AC-4.6/walk-order")]
public async Task NFT_RES_02_waypoint_cascade_aborts_at_media_lookup_with_no_partial_state_today()
{
Skip.IfNot(_restart.Enabled,
"ComposeRestartFixture disabled (COMPOSE_RESTART_ENABLED!=1). " +
"NFT-RES-02 drops the media table and needs a full stack restart.");
// Arrange — fresh F4 fixture; capture target waypoint id + its
// chained detection id so the post-state probe is deterministic.
DbResetFixture.ResetDatabase(TestEnvironment.DbSideChannel);
StubSchema.EnsureCreated();
Seeds.Apply(FixtureSql.Load("fixture_cascade_F4"));
var missionId = CascadeF4Fixture.MissionId;
var targetWaypointId = CascadeF4Fixture.TargetWaypointId;
var targetAnnotationId = CascadeF4Fixture.TargetAnnotationId;
DropMediaTable();
var requestStart = DateTime.UtcNow;
var token = await Tokens.MintDefaultAsync();
try
{
// Act
using var req = new HttpRequestMessage(
HttpMethod.Delete, $"/missions/{missionId}/waypoints/{targetWaypointId}");
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.Jwt);
using var response = await Missions.SendAsync(req);
// Assert — 500 (PostgresException 42P01 bubbles to generic catch).
await HttpAssertions.AssertProblemEnvelopeAsync(
response, HttpStatusCode.InternalServerError);
// Carry-forward: today the media SELECT fires BEFORE any DELETE,
// so nothing commits. detection (target row) is unchanged.
var targetDetectionCount = DbAssertions.ScalarCount(
"SELECT COUNT(*) FROM detection WHERE annotation_id = @aid",
("aid", targetAnnotationId));
Assert.Equal(1, targetDetectionCount); // spec says 0 — flip when walk is reordered.
// The waypoint row is uncommitted (matches spec).
var waypointCount = DbAssertions.ScalarCount(
"SELECT COUNT(*) FROM waypoints WHERE id = @id",
("id", targetWaypointId));
Assert.Equal(1, waypointCount);
// Log line must still mention the missing media table.
var deadline = DateTime.UtcNow.AddSeconds(2);
var sawLog = false;
while (DateTime.UtcNow < deadline)
{
var logs = DockerLogs.Read("missions-sut", requestStart);
if (logs.Contains("Unhandled exception", StringComparison.Ordinal)
&& logs.Contains("media", StringComparison.OrdinalIgnoreCase))
{
sawLog = true;
break;
}
await Task.Delay(100);
}
Assert.True(sawLog,
"expected 'Unhandled exception' mentioning 'media' in logs within 2s");
}
finally
{
_restart.RestartStack();
}
}
private static void DropMediaTable()
{
using var conn = new NpgsqlConnection(TestEnvironment.DbSideChannel);
conn.Open();
using var cmd = conn.CreateCommand();
cmd.CommandText = "DROP TABLE IF EXISTS media CASCADE;";
cmd.ExecuteNonQuery();
}
}