Add HTTP integration harness and the sync authorization matrix (M1)
ci / build and test (ubuntu) (push) Has been cancelled
ci / build (windows) (push) Has been cancelled

27 end-to-end tests over the real HTTP pipeline, against a PostgreSQL container and a
stubbed identity provider. This closes the gap the previous commit flagged.

Authentication is genuinely exercised, not bypassed. StubIdentityProvider serves real OIDC
discovery and JWKS via WireMock and signs tokens with a real RSA key, so the application's
own JwtBearer pipeline validates issuer, audience, signature, lifetime and claims. A
TestAuthHandler that short-circuits authentication would hide exactly the claim-mapping
mistakes that cause real authorization holes. Proven by rejecting: no token, a foreign
signing key, the wrong audience, the wrong issuer, and an expired token.

Authorization denials — the tests that matter most:
- Another user's vault is 404, not 403, for both pull and push. A distinct
  "exists but forbidden" answer is an existence oracle for other tenants' vault ids.
- A denied push writes nothing: no host row and no change-log entry. A denial that still
  mutated state would be worse than no check at all.
- A team vault is denied until M3 rather than falling through to a permissive default.

Behaviour covered: push/pull round trip, cursor advance (and that an empty pull does not
rewind the cursor, which would replay history), tampered cursor rejection, stale-version
conflict returning server state without overwriting, operation-id replay reported Duplicate
and applied once, a mixed batch applying the good and reporting the bad, relay field
enforcement both ways, delete clearing the relay address, tombstones carrying no payload,
and JIT provisioning happening exactly once.

Two configuration problems found by running it:
- appsettings.json carried empty-string placeholders for the connection string and OIDC
  authority. Under minimal hosting those beat anything a test registers via
  ConfigureAppConfiguration, because Program.cs adds its own sources after that callback
  runs. Removed them outright — an empty placeholder turns "not configured" into
  "configured as empty", which defeats failing fast. Tests now use DODOSSH_ environment
  variables, which Program.cs adds last.
- My first fix for minting an expired test token derived notBefore from the expiry, which
  put nbf fourteen minutes in the future for normal tokens and made every valid token 401.
  It needs the earlier of now-1min and exp-1min.

Verified: 0 warnings on a clean rebuild, 173 tests pass (up from 146), format clean.
This commit is contained in:
2026-07-28 15:11:43 +02:00
parent 3829217e8a
commit 98d29bff37
8 changed files with 2834 additions and 4 deletions
+7
View File
@@ -87,6 +87,13 @@
<PackageVersion Include="NSubstitute" Version="6.0.0" /> <PackageVersion Include="NSubstitute" Version="6.0.0" />
<PackageVersion Include="Testcontainers.PostgreSql" Version="4.13.0" /> <PackageVersion Include="Testcontainers.PostgreSql" Version="4.13.0" />
<PackageVersion Include="Respawn" Version="7.0.0" /> <PackageVersion Include="Respawn" Version="7.0.0" />
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.10" />
<!--
Stands in for the identity provider so integration tests exercise the real JwtBearer
pipeline. A TestAuthHandler that bypasses it would hide exactly the claim-mapping
mistakes that cause real authorization holes.
-->
<PackageVersion Include="WireMock.Net" Version="2.13.0" />
</ItemGroup> </ItemGroup>
</Project> </Project>
+1
View File
@@ -19,6 +19,7 @@
</Folder> </Folder>
<Folder Name="/tests/"> <Folder Name="/tests/">
<Project Path="tests/DodoSSH.Api.Tests/DodoSSH.Api.Tests.csproj" />
<Project Path="tests/DodoSSH.Contracts.Tests/DodoSSH.Contracts.Tests.csproj" /> <Project Path="tests/DodoSSH.Contracts.Tests/DodoSSH.Contracts.Tests.csproj" />
<Project Path="tests/DodoSSH.Crypto.Tests/DodoSSH.Crypto.Tests.csproj" /> <Project Path="tests/DodoSSH.Crypto.Tests/DodoSSH.Crypto.Tests.csproj" />
<Project Path="tests/DodoSSH.Domain.Tests/DodoSSH.Domain.Tests.csproj" /> <Project Path="tests/DodoSSH.Domain.Tests/DodoSSH.Domain.Tests.csproj" />
-4
View File
@@ -7,14 +7,10 @@
} }
}, },
"AllowedHosts": "*", "AllowedHosts": "*",
"ConnectionStrings": {
"Postgres": ""
},
"Server": { "Server": {
"PublicBaseUrl": "http://localhost:5233" "PublicBaseUrl": "http://localhost:5233"
}, },
"Oidc": { "Oidc": {
"Authority": "",
"Audience": "dodossh-api", "Audience": "dodossh-api",
"ClientId": "dodossh-desktop", "ClientId": "dodossh-desktop",
"LoopbackRedirectPattern": "http://127.0.0.1:*/callback", "LoopbackRedirectPattern": "http://127.0.0.1:*/callback",
+112
View File
@@ -0,0 +1,112 @@
using System.Net.Http.Headers;
using DodoSSH.Infrastructure;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Testcontainers.PostgreSql;
using Xunit;
namespace DodoSSH.Api.Tests;
/// <summary>
/// Hosts the API in-process against a real PostgreSQL container and a stubbed identity provider.
/// </summary>
/// <remarks>
/// One container and one host per assembly. Tests therefore use distinct users and vaults rather
/// than assuming an empty database.
/// </remarks>
public sealed class ApiFixture : WebApplicationFactory<Program>, IAsyncLifetime
{
private readonly PostgreSqlContainer container = new PostgreSqlBuilder("postgres:18-alpine")
.WithDatabase("dodossh")
.WithUsername("postgres")
.WithPassword("test")
.Build();
/// <summary>The stubbed identity provider.</summary>
public StubIdentityProvider IdentityProvider { get; } = new();
/// <inheritdoc />
public async ValueTask InitializeAsync()
{
await container.StartAsync();
await using var scope = Services.CreateAsyncScope();
var database = scope.ServiceProvider.GetRequiredService<DodoDbContext>();
await database.Database.MigrateAsync();
}
/// <inheritdoc />
public override async ValueTask DisposeAsync()
{
await base.DisposeAsync();
await container.DisposeAsync();
IdentityProvider.Dispose();
}
/// <inheritdoc />
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
ArgumentNullException.ThrowIfNull(builder);
builder.UseEnvironment("Testing");
// Environment variables rather than ConfigureAppConfiguration. Under minimal hosting the
// application's own configuration sources are added inside Program.cs after this callback
// runs, so an appsettings.json value would win over anything registered here. Program.cs
// adds AddEnvironmentVariables("DODOSSH_") last, which makes these authoritative.
var settings = new Dictionary<string, string?>(StringComparer.Ordinal)
{
["DODOSSH_ConnectionStrings__Postgres"] = container.GetConnectionString(),
["DODOSSH_Server__PublicBaseUrl"] = "http://localhost",
["DODOSSH_Oidc__Authority"] = IdentityProvider.Authority,
["DODOSSH_Oidc__Audience"] = StubIdentityProvider.Audience,
["DODOSSH_Oidc__ClientId"] = "dodossh-desktop",
// The stub serves plaintext HTTP on a loopback port.
["DODOSSH_Oidc__RequireHttpsMetadata"] = "false",
["DODOSSH_Relay__Enabled"] = "false",
// Fixed so cursors stay valid for the lifetime of the test host.
["DODOSSH_Sync__CursorSigningKey"] = Convert.ToBase64String(new byte[32]),
};
foreach (var (name, value) in settings)
{
Environment.SetEnvironmentVariable(name, value);
}
}
/// <summary>Creates a client carrying a valid token for the given subject.</summary>
public HttpClient CreateClientFor(string subject, string? email = null)
{
var client = CreateClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Bearer",
IdentityProvider.MintToken(subject, email));
return client;
}
/// <summary>Creates a client carrying the supplied raw token.</summary>
public HttpClient CreateClientWithToken(string token)
{
var client = CreateClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
return client;
}
/// <summary>Opens a database scope for arranging state and asserting on it.</summary>
public AsyncServiceScope CreateScope() => Services.CreateAsyncScope();
}
/// <summary>Shares one host and container across every test class in the assembly.</summary>
[CollectionDefinition(Name)]
public sealed class ApiCollection : ICollectionFixture<ApiFixture>
{
/// <summary>Collection name.</summary>
public const string Name = "api";
}
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
End-to-end HTTP tests against a real PostgreSQL container and a stubbed identity provider.
The full JwtBearer pipeline runs, including issuer, audience, signature and claim handling.
-->
<ItemGroup>
<ProjectReference Include="../../src/DodoSSH.Api/DodoSSH.Api.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" />
<PackageReference Include="Testcontainers.PostgreSql" />
<PackageReference Include="WireMock.Net" />
</ItemGroup>
</Project>
@@ -0,0 +1,171 @@
using System.IdentityModel.Tokens.Jwt;
using System.Security.Cryptography;
using System.Text.Json;
using Microsoft.IdentityModel.Tokens;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
using WireMock.Server;
namespace DodoSSH.Api.Tests;
/// <summary>
/// A stand-in identity provider: OIDC discovery, JWKS, and token minting.
/// </summary>
/// <remarks>
/// Deliberately not a <c>TestAuthHandler</c> that short-circuits authentication. Tokens are signed
/// with a real RSA key and validated by the application's own JwtBearer pipeline, so issuer,
/// audience, signature, lifetime and claim handling are all genuinely exercised. Bypassing that
/// would hide precisely the claim-mapping mistakes that cause real authorization holes.
/// </remarks>
public sealed class StubIdentityProvider : IDisposable
{
private const string KeyId = "dodossh-test-key";
private readonly WireMockServer server;
private readonly RsaSecurityKey signingKey;
public StubIdentityProvider()
{
var rsa = RSA.Create(2048);
signingKey = new RsaSecurityKey(rsa) { KeyId = KeyId };
server = WireMockServer.Start();
Authority = server.Url!.TrimEnd('/');
StubDiscovery();
StubJwks();
}
/// <summary>Issuer URL, matching what the tokens claim.</summary>
public string Authority { get; }
/// <summary>Audience the API is configured to expect.</summary>
public static string Audience => "dodossh-api";
/// <summary>
/// Mints a signed access token.
/// </summary>
/// <param name="subject">The <c>sub</c> claim — the stable user identifier.</param>
/// <param name="email">Optional email claim.</param>
/// <param name="name">Optional display name claim.</param>
/// <param name="audience">Override the audience, to test rejection.</param>
/// <param name="issuer">Override the issuer, to test rejection.</param>
/// <param name="expires">Override expiry, to test rejection.</param>
public string MintToken(
string subject,
string? email = null,
string? name = null,
string? audience = null,
string? issuer = null,
DateTime? expires = null)
{
var now = TimeProvider.System.GetUtcNow().UtcDateTime;
var claims = new List<System.Security.Claims.Claim>
{
new("sub", subject),
};
if (email is not null)
{
claims.Add(new System.Security.Claims.Claim("email", email));
}
if (name is not null)
{
claims.Add(new System.Security.Claims.Claim("name", name));
}
var expiry = expires ?? now.AddMinutes(15);
// The earlier of now-1min and exp-1min. A fixed now-1min would sit after the expiry of a
// deliberately-expired test token (rejected at construction), while exp-1min alone would
// put nbf in the future for a normal token and make every valid token unauthorized.
var notBefore = expiry < now ? expiry.AddMinutes(-1) : now.AddMinutes(-1);
var token = new JwtSecurityToken(
issuer: issuer ?? Authority,
audience: audience ?? Audience,
claims: claims,
notBefore: notBefore,
expires: expiry,
signingCredentials: new SigningCredentials(signingKey, SecurityAlgorithms.RsaSha256));
return new JwtSecurityTokenHandler().WriteToken(token);
}
/// <summary>Mints a token signed by a different key, which must be rejected.</summary>
public string MintTokenWithForeignKey(string subject)
{
var foreign = new RsaSecurityKey(RSA.Create(2048)) { KeyId = KeyId };
var now = TimeProvider.System.GetUtcNow().UtcDateTime;
var token = new JwtSecurityToken(
issuer: Authority,
audience: Audience,
claims: [new System.Security.Claims.Claim("sub", subject)],
notBefore: now.AddMinutes(-1),
expires: now.AddMinutes(15),
signingCredentials: new SigningCredentials(foreign, SecurityAlgorithms.RsaSha256));
return new JwtSecurityTokenHandler().WriteToken(token);
}
private void StubDiscovery()
{
var document = new Dictionary<string, object>(StringComparer.Ordinal)
{
["issuer"] = Authority,
["jwks_uri"] = $"{Authority}/.well-known/jwks.json",
["authorization_endpoint"] = $"{Authority}/connect/authorize",
["token_endpoint"] = $"{Authority}/connect/token",
["response_types_supported"] = new[] { "code" },
["subject_types_supported"] = new[] { "public" },
["id_token_signing_alg_values_supported"] = new[] { "RS256" },
["code_challenge_methods_supported"] = new[] { "S256" },
};
server
.Given(Request.Create().WithPath("/.well-known/openid-configuration").UsingGet())
.RespondWith(Response.Create()
.WithStatusCode(200)
.WithHeader("Content-Type", "application/json")
.WithBody(JsonSerializer.Serialize(document)));
}
private void StubJwks()
{
var parameters = signingKey.Rsa.ExportParameters(includePrivateParameters: false);
var jwks = new
{
keys = new[]
{
new
{
kty = "RSA",
use = "sig",
kid = KeyId,
alg = "RS256",
n = Base64UrlEncoder.Encode(parameters.Modulus),
e = Base64UrlEncoder.Encode(parameters.Exponent),
},
},
};
server
.Given(Request.Create().WithPath("/.well-known/jwks.json").UsingGet())
.RespondWith(Response.Create()
.WithStatusCode(200)
.WithHeader("Content-Type", "application/json")
.WithBody(JsonSerializer.Serialize(jwks)));
}
/// <inheritdoc />
public void Dispose()
{
server.Stop();
server.Dispose();
signingKey.Rsa.Dispose();
}
}
@@ -0,0 +1,716 @@
using System.Net;
using System.Net.Http.Json;
using DodoSSH.Contracts;
using DodoSSH.Domain;
using DodoSSH.Infrastructure;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
namespace DodoSSH.Api.Tests;
/// <summary>
/// End-to-end sync behaviour over HTTP, and the authorization denials.
/// </summary>
/// <remarks>
/// The denial tests are the most important thing here. Every one of them asserts that a caller who
/// should not reach a vault does not, through the real authentication pipeline rather than a
/// bypassed one.
/// </remarks>
[Collection(ApiCollection.Name)]
public sealed class SyncEndpointTests(ApiFixture fixture)
{
private static readonly DateTimeOffset Now = new(2026, 7, 28, 12, 0, 0, TimeSpan.Zero);
// ---- Authentication ----
[Fact]
public async Task Pull_WithoutAToken_Is401()
{
var client = fixture.CreateClient();
var response = await client.PostAsJsonAsync(
PullUrl(Guid.CreateVersion7()),
new SyncPullRequest(null, null, null));
response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
}
[Fact]
public async Task Push_WithoutAToken_Is401()
{
var client = fixture.CreateClient();
var response = await client.PostAsJsonAsync(
PushUrl(Guid.CreateVersion7()),
new SyncPushRequest([]));
response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
}
[Fact]
public async Task ATokenSignedByAnotherKey_Is401()
{
// Proves signature validation is genuinely running, not stubbed out.
var client = fixture.CreateClientWithToken(
fixture.IdentityProvider.MintTokenWithForeignKey(NewSubject()));
var response = await client.PostAsJsonAsync(
PullUrl(Guid.CreateVersion7()),
new SyncPullRequest(null, null, null));
response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
}
[Fact]
public async Task ATokenForAnotherAudience_Is401()
{
var client = fixture.CreateClientWithToken(
fixture.IdentityProvider.MintToken(NewSubject(), audience: "some-other-api"));
var response = await client.PostAsJsonAsync(
PullUrl(Guid.CreateVersion7()),
new SyncPullRequest(null, null, null));
response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
}
[Fact]
public async Task ATokenFromAnotherIssuer_Is401()
{
var client = fixture.CreateClientWithToken(
fixture.IdentityProvider.MintToken(NewSubject(), issuer: "https://evil.example"));
var response = await client.PostAsJsonAsync(
PullUrl(Guid.CreateVersion7()),
new SyncPullRequest(null, null, null));
response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
}
[Fact]
public async Task AnExpiredToken_Is401()
{
var client = fixture.CreateClientWithToken(fixture.IdentityProvider.MintToken(
NewSubject(),
expires: TimeProvider.System.GetUtcNow().UtcDateTime.AddMinutes(-10)));
var response = await client.PostAsJsonAsync(
PullUrl(Guid.CreateVersion7()),
new SyncPullRequest(null, null, null));
response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
}
// ---- Authorization: the wrong user must be denied ----
[Fact]
public async Task Pull_AnotherUsersVault_Is404()
{
// 404 rather than 403: a distinct "exists but forbidden" answer would let a caller
// enumerate other tenants' vault ids.
var (_, vaultId) = await SeedUserWithVaultAsync();
var intruder = fixture.CreateClientFor(NewSubject());
var response = await intruder.PostAsJsonAsync(
PullUrl(vaultId),
new SyncPullRequest(null, null, null));
response.StatusCode.ShouldBe(HttpStatusCode.NotFound);
}
[Fact]
public async Task Push_AnotherUsersVault_Is404()
{
var (_, vaultId) = await SeedUserWithVaultAsync();
var intruder = fixture.CreateClientFor(NewSubject());
var response = await intruder.PostAsJsonAsync(PushUrl(vaultId), NewCreateBatch());
response.StatusCode.ShouldBe(HttpStatusCode.NotFound);
}
[Fact]
public async Task Push_AnotherUsersVault_WritesNothing()
{
// A denial that still mutated state would be worse than no check at all.
var (_, vaultId) = await SeedUserWithVaultAsync();
var intruder = fixture.CreateClientFor(NewSubject());
var batch = NewCreateBatch();
await intruder.PostAsJsonAsync(PushUrl(vaultId), batch);
await using var scope = fixture.CreateScope();
var database = scope.ServiceProvider.GetRequiredService<DodoDbContext>();
(await database.Hosts.AnyAsync(h => h.VaultId == vaultId)).ShouldBeFalse();
(await database.VaultChanges.AnyAsync(c => c.VaultId == vaultId)).ShouldBeFalse();
}
[Fact]
public async Task Pull_ANonexistentVault_Is404()
{
var client = fixture.CreateClientFor(NewSubject());
var response = await client.PostAsJsonAsync(
PullUrl(Guid.CreateVersion7()),
new SyncPullRequest(null, null, null));
response.StatusCode.ShouldBe(HttpStatusCode.NotFound);
}
[Fact]
public async Task ATeamVault_IsDeniedUntilTeamsShip()
{
// Failing closed on an unimplemented path, rather than falling through to a default.
var vaultId = await SeedTeamVaultAsync();
var client = fixture.CreateClientFor(NewSubject());
var response = await client.PostAsJsonAsync(
PullUrl(vaultId),
new SyncPullRequest(null, null, null));
response.StatusCode.ShouldBe(HttpStatusCode.NotFound);
}
// ---- Round trip ----
[Fact]
public async Task Push_ThenPull_ReturnsTheItem()
{
var (subject, vaultId) = await SeedUserWithVaultAsync();
var client = fixture.CreateClientFor(subject);
var batch = NewCreateBatch();
var push = await client.PostAsJsonAsync(PushUrl(vaultId), batch);
push.EnsureSuccessStatusCode();
var pushed = await push.Content.ReadFromJsonAsync<SyncPushResponse>();
pushed.ShouldNotBeNull();
pushed.Results.Count.ShouldBe(1);
pushed.Results[0].Status.ShouldBe(SyncOperationStatus.Applied);
pushed.Results[0].Version.ShouldBe(1);
var pull = await client.PostAsJsonAsync(
PullUrl(vaultId),
new SyncPullRequest(null, null, null));
pull.EnsureSuccessStatusCode();
var pulled = await pull.Content.ReadFromJsonAsync<SyncPullResponse>();
pulled.ShouldNotBeNull();
pulled.Changes.Count.ShouldBe(1);
var change = pulled.Changes[0];
change.EntityId.ShouldBe(batch.Operations[0].EntityId);
change.Operation.ShouldBe(SyncOperation.Upsert);
change.Payload.ShouldNotBeNull();
change.Payload.Envelope.ShouldBe(batch.Operations[0].Payload!.Envelope);
}
[Fact]
public async Task Pull_WithACursor_ReturnsOnlyNewerChanges()
{
var (subject, vaultId) = await SeedUserWithVaultAsync();
var client = fixture.CreateClientFor(subject);
await client.PostAsJsonAsync(PushUrl(vaultId), NewCreateBatch());
var first = await (await client.PostAsJsonAsync(
PullUrl(vaultId),
new SyncPullRequest(null, null, null))).Content.ReadFromJsonAsync<SyncPullResponse>();
first.ShouldNotBeNull();
// Nothing new since that cursor.
var empty = await (await client.PostAsJsonAsync(
PullUrl(vaultId),
new SyncPullRequest(first.NextCursor, null, null)))
.Content.ReadFromJsonAsync<SyncPullResponse>();
empty.ShouldNotBeNull();
empty.Changes.ShouldBeEmpty();
// The cursor must not have rewound, or the next poll would replay history.
empty.NextCursor.ShouldBe(first.NextCursor);
await client.PostAsJsonAsync(PushUrl(vaultId), NewCreateBatch());
var second = await (await client.PostAsJsonAsync(
PullUrl(vaultId),
new SyncPullRequest(first.NextCursor, null, null)))
.Content.ReadFromJsonAsync<SyncPullResponse>();
second.ShouldNotBeNull();
second.Changes.Count.ShouldBe(1);
}
[Fact]
public async Task Pull_WithACursorFromAnotherVault_Is400()
{
var (subject, firstVault) = await SeedUserWithVaultAsync();
var (_, otherVault) = await SeedUserWithVaultAsync();
var client = fixture.CreateClientFor(subject);
var pull = await client.PostAsJsonAsync(
PullUrl(firstVault),
new SyncPullRequest(null, null, null));
var cursor = (await pull.Content.ReadFromJsonAsync<SyncPullResponse>())!.NextCursor;
// Correctly signed, but issued for a different vault.
var response = await client.PostAsJsonAsync(
PullUrl(otherVault),
new SyncPullRequest(cursor, null, null));
// 404 first, because this caller cannot see the other vault at all.
response.StatusCode.ShouldBe(HttpStatusCode.NotFound);
}
[Fact]
public async Task Pull_WithATamperedCursor_Is400()
{
var (subject, vaultId) = await SeedUserWithVaultAsync();
var client = fixture.CreateClientFor(subject);
var response = await client.PostAsJsonAsync(
PullUrl(vaultId),
new SyncPullRequest("bm90LWEtcmVhbC1jdXJzb3I", null, null));
response.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
var problem = await response.Content.ReadFromJsonAsync<JsonProblem>();
problem.ShouldNotBeNull();
problem.Code.ShouldBe(ProblemCodes.InvalidCursor);
}
// ---- Conflict and idempotency ----
[Fact]
public async Task Push_WithAStaleVersion_ReportsConflictAndReturnsServerState()
{
var (subject, vaultId) = await SeedUserWithVaultAsync();
var client = fixture.CreateClientFor(subject);
var create = NewCreateBatch();
var entityId = create.Operations[0].EntityId;
await client.PostAsJsonAsync(PushUrl(vaultId), create);
// Update to version 2.
await client.PostAsJsonAsync(PushUrl(vaultId), new SyncPushRequest(
[
NewOperation(entityId, expectedVersion: 1, envelope: [9, 9, 9]),
]));
// A second client still believes it is on version 1.
var stale = await client.PostAsJsonAsync(PushUrl(vaultId), new SyncPushRequest(
[
NewOperation(entityId, expectedVersion: 1, envelope: [7, 7, 7]),
]));
stale.EnsureSuccessStatusCode();
var body = await stale.Content.ReadFromJsonAsync<SyncPushResponse>();
body.ShouldNotBeNull();
body.Results[0].Status.ShouldBe(SyncOperationStatus.Conflict);
body.Results[0].Version.ShouldBe(2);
// The server's current state comes back so the client can merge rather than guess.
body.Results[0].ServerEntity.ShouldNotBeNull();
body.Results[0].ServerEntity!.Payload!.Envelope.ShouldBe([9, 9, 9]);
}
[Fact]
public async Task Push_WithAConflict_DoesNotOverwrite()
{
var (subject, vaultId) = await SeedUserWithVaultAsync();
var client = fixture.CreateClientFor(subject);
var create = NewCreateBatch();
var entityId = create.Operations[0].EntityId;
await client.PostAsJsonAsync(PushUrl(vaultId), create);
await client.PostAsJsonAsync(PushUrl(vaultId), new SyncPushRequest(
[
NewOperation(entityId, expectedVersion: 1, envelope: [9, 9, 9]),
]));
await client.PostAsJsonAsync(PushUrl(vaultId), new SyncPushRequest(
[
NewOperation(entityId, expectedVersion: 1, envelope: [7, 7, 7]),
]));
await using var scope = fixture.CreateScope();
var database = scope.ServiceProvider.GetRequiredService<DodoDbContext>();
var stored = await database.Hosts.SingleAsync(h => h.Id == entityId);
// Never last-writer-wins.
stored.Payload.ShouldBe([9, 9, 9]);
stored.Version.ShouldBe(2);
}
[Fact]
public async Task Push_ReplayingAnOperationId_IsReportedDuplicateAndAppliedOnce()
{
var (subject, vaultId) = await SeedUserWithVaultAsync();
var client = fixture.CreateClientFor(subject);
var batch = NewCreateBatch();
var first = await client.PostAsJsonAsync(PushUrl(vaultId), batch);
first.EnsureSuccessStatusCode();
// Exactly the same batch again, as a retry after a timeout would be.
var replay = await client.PostAsJsonAsync(PushUrl(vaultId), batch);
replay.EnsureSuccessStatusCode();
var body = await replay.Content.ReadFromJsonAsync<SyncPushResponse>();
body.ShouldNotBeNull();
body.Results[0].Status.ShouldBe(SyncOperationStatus.Duplicate);
await using var scope = fixture.CreateScope();
var database = scope.ServiceProvider.GetRequiredService<DodoDbContext>();
var stored = await database.Hosts.SingleAsync(h => h.Id == batch.Operations[0].EntityId);
stored.Version.ShouldBe(1);
(await database.VaultChanges.CountAsync(c => c.EntityId == stored.Id)).ShouldBe(1);
}
[Fact]
public async Task Push_AMixedBatch_AppliesTheGoodAndReportsTheBad()
{
// One stale item must not block everything else a client queued while offline.
var (subject, vaultId) = await SeedUserWithVaultAsync();
var client = fixture.CreateClientFor(subject);
var existing = NewCreateBatch();
await client.PostAsJsonAsync(PushUrl(vaultId), existing);
var goodId = Guid.CreateVersion7();
var mixed = new SyncPushRequest(
[
NewOperation(existing.Operations[0].EntityId, expectedVersion: 99, envelope: [1]),
NewOperation(goodId, expectedVersion: null, envelope: [2, 2]),
]);
var response = await client.PostAsJsonAsync(PushUrl(vaultId), mixed);
// 200 despite a failed operation: per-operation status carries the detail.
response.StatusCode.ShouldBe(HttpStatusCode.OK);
var body = await response.Content.ReadFromJsonAsync<SyncPushResponse>();
body.ShouldNotBeNull();
body.Results[0].Status.ShouldBe(SyncOperationStatus.Conflict);
body.Results[1].Status.ShouldBe(SyncOperationStatus.Applied);
await using var scope = fixture.CreateScope();
var database = scope.ServiceProvider.GetRequiredService<DodoDbContext>();
(await database.Hosts.AnyAsync(h => h.Id == goodId)).ShouldBeTrue();
}
// ---- Relay field enforcement, ADR 0004 ----
[Fact]
public async Task Push_ARelayAddressWithoutEnablingRelay_IsRejected()
{
// Prevents the server quietly learning an address the user never opted into exposing.
var (subject, vaultId) = await SeedUserWithVaultAsync();
var client = fixture.CreateClientFor(subject);
var response = await client.PostAsJsonAsync(PushUrl(vaultId), new SyncPushRequest(
[
new SyncPushOperation(
Guid.CreateVersion7(),
SyncEntityType.Host,
Guid.CreateVersion7(),
SyncOperation.Upsert,
null,
new EncryptedPayload([1, 2, 3], 1, 1),
new SyncPlaintextFields(RelayEnabled: false, Hostname: "secret.internal", Port: 22)),
]));
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadFromJsonAsync<SyncPushResponse>();
body!.Results[0].Status.ShouldBe(SyncOperationStatus.Invalid);
}
[Fact]
public async Task Push_RelayEnabledWithoutAnAddress_IsRejected()
{
var (subject, vaultId) = await SeedUserWithVaultAsync();
var client = fixture.CreateClientFor(subject);
var response = await client.PostAsJsonAsync(PushUrl(vaultId), new SyncPushRequest(
[
new SyncPushOperation(
Guid.CreateVersion7(),
SyncEntityType.Host,
Guid.CreateVersion7(),
SyncOperation.Upsert,
null,
new EncryptedPayload([1, 2, 3], 1, 1),
new SyncPlaintextFields(RelayEnabled: true)),
]));
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadFromJsonAsync<SyncPushResponse>();
body!.Results[0].Status.ShouldBe(SyncOperationStatus.Invalid);
}
[Fact]
public async Task Delete_ClearsTheRelayAddress()
{
// Leaving it would keep the server able to resolve a host the user believes is gone.
var (subject, vaultId) = await SeedUserWithVaultAsync();
var client = fixture.CreateClientFor(subject);
var entityId = Guid.CreateVersion7();
await client.PostAsJsonAsync(PushUrl(vaultId), new SyncPushRequest(
[
new SyncPushOperation(
Guid.CreateVersion7(),
SyncEntityType.Host,
entityId,
SyncOperation.Upsert,
null,
new EncryptedPayload([1, 2, 3], 1, 1),
new SyncPlaintextFields(RelayEnabled: true, Hostname: "bastion.internal", Port: 22)),
]));
await client.PostAsJsonAsync(PushUrl(vaultId), new SyncPushRequest(
[
new SyncPushOperation(
Guid.CreateVersion7(),
SyncEntityType.Host,
entityId,
SyncOperation.Delete,
ExpectedVersion: 1,
Payload: null,
PlaintextFields: null),
]));
await using var scope = fixture.CreateScope();
var database = scope.ServiceProvider.GetRequiredService<DodoDbContext>();
var stored = await database.Hosts.SingleAsync(h => h.Id == entityId);
stored.DeletedAtUtc.ShouldNotBeNull();
stored.RelayEnabled.ShouldBeFalse();
stored.Hostname.ShouldBeNull();
stored.Port.ShouldBeNull();
}
[Fact]
public async Task Pull_ADeletedItem_ReturnsATombstoneWithNoPayload()
{
var (subject, vaultId) = await SeedUserWithVaultAsync();
var client = fixture.CreateClientFor(subject);
var create = NewCreateBatch();
var entityId = create.Operations[0].EntityId;
await client.PostAsJsonAsync(PushUrl(vaultId), create);
await client.PostAsJsonAsync(PushUrl(vaultId), new SyncPushRequest(
[
new SyncPushOperation(
Guid.CreateVersion7(),
SyncEntityType.Host,
entityId,
SyncOperation.Delete,
ExpectedVersion: 1,
Payload: null,
PlaintextFields: null),
]));
var pull = await client.PostAsJsonAsync(
PullUrl(vaultId),
new SyncPullRequest(null, null, null));
var body = await pull.Content.ReadFromJsonAsync<SyncPullResponse>();
body.ShouldNotBeNull();
var tombstone = body.Changes.Last(c => c.EntityId == entityId);
tombstone.Operation.ShouldBe(SyncOperation.Delete);
tombstone.Payload.ShouldBeNull();
tombstone.PlaintextFields.ShouldBeNull();
}
// ---- Batch limits ----
[Fact]
public async Task Push_AnEmptyBatch_Is400()
{
var (subject, vaultId) = await SeedUserWithVaultAsync();
var client = fixture.CreateClientFor(subject);
var response = await client.PostAsJsonAsync(PushUrl(vaultId), new SyncPushRequest([]));
response.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
}
[Fact]
public async Task Push_AnUnsupportedEntityType_IsInvalidNotAFailedBatch()
{
// A newer client asking for something this server does not do yet gets a precise
// per-operation answer rather than a whole-batch rejection.
var (subject, vaultId) = await SeedUserWithVaultAsync();
var client = fixture.CreateClientFor(subject);
var response = await client.PostAsJsonAsync(PushUrl(vaultId), new SyncPushRequest(
[
new SyncPushOperation(
Guid.CreateVersion7(),
SyncEntityType.Credential,
Guid.CreateVersion7(),
SyncOperation.Upsert,
null,
new EncryptedPayload([1], 1, 1),
null),
]));
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadFromJsonAsync<SyncPushResponse>();
body!.Results[0].Status.ShouldBe(SyncOperationStatus.Invalid);
}
// ---- JIT provisioning ----
[Fact]
public async Task AFirstRequest_ProvisionsTheUser()
{
var subject = NewSubject();
var email = $"{subject}@example.com";
var client = fixture.CreateClientFor(subject, email);
// Any authenticated call is enough to trigger provisioning.
await client.PostAsJsonAsync(
PullUrl(Guid.CreateVersion7()),
new SyncPullRequest(null, null, null));
await using var scope = fixture.CreateScope();
var database = scope.ServiceProvider.GetRequiredService<DodoDbContext>();
var user = await database.Users.SingleOrDefaultAsync(u => u.Subject == subject);
user.ShouldNotBeNull();
user.Issuer.ShouldBe(fixture.IdentityProvider.Authority);
user.Email.ShouldBe(email);
user.Status.ShouldBe(UserStatus.Active);
}
[Fact]
public async Task RepeatedRequests_ProvisionOnlyOnce()
{
var subject = NewSubject();
var client = fixture.CreateClientFor(subject);
for (var i = 0; i < 3; i++)
{
await client.PostAsJsonAsync(
PullUrl(Guid.CreateVersion7()),
new SyncPullRequest(null, null, null));
}
await using var scope = fixture.CreateScope();
var database = scope.ServiceProvider.GetRequiredService<DodoDbContext>();
(await database.Users.CountAsync(u => u.Subject == subject)).ShouldBe(1);
}
// ---- Helpers ----
private static string PullUrl(Guid vaultId) => $"/api/v1/vaults/{vaultId}/sync/pull";
private static string PushUrl(Guid vaultId) => $"/api/v1/vaults/{vaultId}/sync/push";
private static string NewSubject() => $"user-{Guid.CreateVersion7():N}";
private static SyncPushOperation NewOperation(Guid entityId, int? expectedVersion, byte[] envelope) =>
new(
Guid.CreateVersion7(),
SyncEntityType.Host,
entityId,
SyncOperation.Upsert,
expectedVersion,
new EncryptedPayload(envelope, 1, 1),
new SyncPlaintextFields());
private static SyncPushRequest NewCreateBatch() =>
new([NewOperation(Guid.CreateVersion7(), expectedVersion: null, envelope: [1, 2, 3, 4])]);
private async Task<(string Subject, Guid VaultId)> SeedUserWithVaultAsync()
{
var subject = NewSubject();
await using var scope = fixture.CreateScope();
var database = scope.ServiceProvider.GetRequiredService<DodoDbContext>();
var user = new UserAccount
{
Id = Guid.CreateVersion7(),
Issuer = fixture.IdentityProvider.Authority,
Subject = subject,
Status = UserStatus.Active,
CreatedAtUtc = Now,
UpdatedAtUtc = Now,
};
var vault = new Vault
{
Id = Guid.CreateVersion7(),
Name = "Personal",
OwnerKind = VaultOwnerKind.Personal,
OwnerUserId = user.Id,
KeyGeneration = 1,
CreatedAtUtc = Now,
UpdatedAtUtc = Now,
};
database.Users.Add(user);
database.Vaults.Add(vault);
await database.SaveChangesAsync();
return (subject, vault.Id);
}
private async Task<Guid> SeedTeamVaultAsync()
{
await using var scope = fixture.CreateScope();
var database = scope.ServiceProvider.GetRequiredService<DodoDbContext>();
var owner = new UserAccount
{
Id = Guid.CreateVersion7(),
Issuer = fixture.IdentityProvider.Authority,
Subject = NewSubject(),
Status = UserStatus.Active,
CreatedAtUtc = Now,
UpdatedAtUtc = Now,
};
var team = new Team
{
Id = Guid.CreateVersion7(),
Name = "Team",
Slug = $"team-{Guid.CreateVersion7():N}",
CreatedByUserId = owner.Id,
CreatedAtUtc = Now,
};
var vault = new Vault
{
Id = Guid.CreateVersion7(),
Name = "Shared",
OwnerKind = VaultOwnerKind.Team,
TeamId = team.Id,
KeyGeneration = 1,
CreatedAtUtc = Now,
UpdatedAtUtc = Now,
};
database.Users.Add(owner);
database.Teams.Add(team);
database.Vaults.Add(vault);
await database.SaveChangesAsync();
return vault.Id;
}
/// <summary>Minimal ProblemDetails shape, for asserting on the code extension.</summary>
private sealed record JsonProblem(string? Type, string? Detail, string? Code);
}
File diff suppressed because it is too large Load Diff