Public Access
A fingerprint approved once is now approved on every machine and survives a
restart, because host key trust is a vault item type rather than a dictionary
that dies with the process. InMemoryKnownHostStore was what shipped, so the user
was asked to verify a fingerprint on every single connection — which is the gap
most likely to train somebody to click through the one warning that actually
matters. A warning that appears when nothing is wrong teaches that nothing is
ever wrong.
The fourth item type, and like the third it cost no sync logic: a row, an EF
configuration, a migration, a server kind; a secret, a codec, a merge, a cipher,
a repository facade and a session property. One row in the client registry. The
reconciler, the mirror, the repository, the outbox and the pull filter were not
touched. SyncEntityType.KnownHostKey and AadResourceType.KnownHostKey were
already reserved, so neither the contract nor docs/crypto.md changed.
One item per (host, port, algorithm), because a server legitimately offers
several host keys and which one gets negotiated is not ours to predict. Pinning
per endpoint would make an algorithm change indistinguishable from an attack.
The label is derived rather than stored, which is the one place this type
departs from the other three. A user never names a pin — there is nothing to
name it after but the three fields it already has — and a stored label is a
second copy of data that can disagree with the first after a merge. Relabel
returns the secret unchanged, and says why.
The store answers the handshake without touching the disk. SshNetConnectionFactory
calls FindAsync from inside SSH.NET's synchronous HostKeyReceived event, over
.GetAwaiter().GetResult(), which cannot be avoided; doing SQLite I/O plus an AEAD
open per lookup there would put the handshake behind the cache. So decryption
happens in OpenAsync and RefreshAsync — on unlock and after each sync pass,
exactly where the host and key lists already reload — and FindAsync is a
dictionary read under a lock with no await inside it.
That snapshot is where the one real bug in this change lived. Install originally
merged the live pins over the freshly loaded snapshot, to protect a TrustAsync
that had landed while the read was in flight. It would also have resurrected
every pin the user had just forgotten, and stopped a withdrawal made on another
machine from ever taking effect — the store would have healed the deletion back
into existence on every refresh. Replacing wholesale and discarding the read
instead is correct because writes are the rare case: every write bumps a
generation counter, and a refresh whose stamp is stale throws itself away rather
than winning. Nothing found this but reading the method again; it is the kind of
mistake that passes every test written before it, because the test that catches
it is the one the bug tells you to write.
Forgetting is new, and persistence is what made it mandatory rather than
convenient. A mismatch is a hard refusal with no way to continue — deliberately,
and that stays — so pinning a key permanently is also a way to make a
legitimately rebuilt server permanently unreachable. Before this change the pin
died at exit and the problem solved itself; now it does not.
ForgetAsync drops every algorithm for an endpoint, and it is reachable from the
host editor rather than from the warning. Putting it on the mismatch banner would
have made it two clicks from "this may be an attack" to "connect anyway", which
is the affordance the hard refusal exists to deny. The banner already promised
the key could be removed in the host's settings; that promise is now true and
points at the button.
Trust recorded on another machine becomes visible at the next sync pass, not
immediately, and that is a decision rather than an oversight. The failure it
produces is a first-contact prompt for a host a colleague approved a minute ago:
answerable, and self-correcting on the next pass. The opposite trade — polling
the vault on the handshake thread to close a one-minute window — buys nothing
and costs the property above. The dangerous direction is not reachable at all: a
pin recorded here enters the snapshot as part of recording it, so a refresh can
never discard a local trust decision.
The server learns nothing, and this is the item type where the temptation was
real. A plaintext host column would let a known-hosts screen sort and page
without decrypting anything, and it would hand the operator the map of every
user's estate — assembled, as these things are, out of facts that are each
individually harmless. A host row concedes an address only when relay is
switched on and the database refuses to store one otherwise (ADR 0004); there is
no equivalent excuse here. The table has no column to put one in, and the EF
configuration says so where somebody adding it would be standing.
Two things about the migration in this commit are worth knowing, because both
came out of getting it wrong.
It was hand-written first, including its .Designer.cs, and that version is not
what is here. Verifying it turned up something that had been quietly assumed:
Migration_AppliedCleanly_WithNoPendingModelChanges does not check the model
snapshot. It asserts that migrations applied and that none are pending, which a
wrong snapshot satisfies perfectly — the snapshot only matters as the diff base
for the *next* migrations add, so an incorrect one passes the whole suite and
corrupts the following migration instead. The real check is to generate a
throwaway migration and confirm its Up and Down come out empty. They did, and
the generated designer was byte-identical to the transcribed one across all 1255
lines, so the hand-written work was in fact correct.
Then dotnet ef migrations remove --no-build deleted the wrong migration. With
--no-build the tool reads the previously compiled assembly rather than the files
on disk, and the probe had just changed which migration was last, so it removed
AddKnownHostKeyItem and reverted the snapshot. That turned out to leave exactly
the right diff base, so the migration here is EF's own output rather than a
transcription — a better outcome than the one that was interrupted, arrived at
by accident. Never pass --no-build to migrations remove.
Mutation tested, all three sabotages detected: dropping the algorithm from
KnownHostIdentity.For, merging instead of replacing in Install, and pointing
KnownHostKeyCipher at PortForward — which is what a cast from the wire enum's 10
would silently produce. Each is caught both by an assertion about the mechanism
and by a behavioural test that never mentions it; the resource-type sabotage is
caught by the table from d10a38d and nothing else, which is what that table is
for.
The end-to-end slice now approves the real sshd's host key through the vault,
pushes it, and reads it back on the second simulated machine — including a check
that the server learned no address, and that the second machine answers null for
an algorithm never offered.
845 tests green. Zero warnings, dotnet format clean.
Three things are deliberately not fixed. A tombstone queued over a create that
was never pushed is refused by the server as Invalid and parked; that is
pre-existing for all four item types, and the fix belongs in
VaultItemRepository.DeleteAsync rather than here. Deleting a host, or changing
its address, orphans its pins — both are correct as trust decisions, since a pin
describes an endpoint and not a bookmark, but nothing surfaces the leftovers.
And there is no interface listing pins at all: trust is created at the connect
prompt and withdrawn in the host editor. A known-hosts list is where the orphans
would become visible, and it wants the vault column rework first, for the same
reason the credential editor does.
1130 lines
42 KiB
C#
1130 lines
42 KiB
C#
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.PostContractAsync(
|
|
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.PostContractAsync(
|
|
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.PostContractAsync(
|
|
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.PostContractAsync(
|
|
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.PostContractAsync(
|
|
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.PostContractAsync(
|
|
PullUrl(Guid.CreateVersion7()),
|
|
new SyncPullRequest(null, null, null));
|
|
|
|
response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
|
|
}
|
|
|
|
// ---- Authorization: the caller must have enrolled ----
|
|
|
|
[Fact]
|
|
public async Task Pull_BeforeEnrolling_Is403WithAnActionableCode()
|
|
{
|
|
// Not a confidentiality boundary — an unenrolled user owns no vault anyway. The value is
|
|
// that the client is told what to do instead of receiving an empty 403 or, worse,
|
|
// ciphertext it has no key for.
|
|
var client = fixture.CreateClientFor(NewSubject());
|
|
|
|
var response = await client.PostContractAsync(
|
|
PullUrl(Guid.CreateVersion7()),
|
|
new SyncPullRequest(null, null, null));
|
|
|
|
response.StatusCode.ShouldBe(HttpStatusCode.Forbidden);
|
|
|
|
var problem = await response.Content.ReadProblemAsync();
|
|
problem.ShouldNotBeNull();
|
|
problem.Code.ShouldBe(ProblemCodes.EnrollmentRequired);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Push_BeforeEnrolling_Is403AndWritesNothing()
|
|
{
|
|
var (_, vaultId) = await SeedUserWithVaultAsync();
|
|
var client = fixture.CreateClientFor(NewSubject());
|
|
|
|
var response = await client.PostContractAsync(PushUrl(vaultId), NewCreateBatch());
|
|
|
|
response.StatusCode.ShouldBe(HttpStatusCode.Forbidden);
|
|
|
|
await using var scope = fixture.CreateScope();
|
|
var database = scope.ServiceProvider.GetRequiredService<DodoDbContext>();
|
|
(await database.VaultChanges.AnyAsync(c => c.VaultId == vaultId)).ShouldBeFalse();
|
|
}
|
|
|
|
// ---- 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(await SeedEnrolledUserAsync());
|
|
|
|
var response = await intruder.PostContractAsync(
|
|
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(await SeedEnrolledUserAsync());
|
|
|
|
var response = await intruder.PostContractAsync(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(await SeedEnrolledUserAsync());
|
|
var batch = NewCreateBatch();
|
|
|
|
await intruder.PostContractAsync(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(await SeedEnrolledUserAsync());
|
|
|
|
var response = await client.PostContractAsync(
|
|
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(await SeedEnrolledUserAsync());
|
|
|
|
var response = await client.PostContractAsync(
|
|
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.PostContractAsync(PushUrl(vaultId), batch);
|
|
push.EnsureSuccessStatusCode();
|
|
|
|
var pushed = await push.Content.ReadContractAsync<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.PostContractAsync(
|
|
PullUrl(vaultId),
|
|
new SyncPullRequest(null, null, null));
|
|
pull.EnsureSuccessStatusCode();
|
|
|
|
var pulled = await pull.Content.ReadContractAsync<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.PostContractAsync(PushUrl(vaultId), NewCreateBatch());
|
|
|
|
var first = await (await client.PostContractAsync(
|
|
PullUrl(vaultId),
|
|
new SyncPullRequest(null, null, null))).Content.ReadContractAsync<SyncPullResponse>();
|
|
first.ShouldNotBeNull();
|
|
|
|
// Nothing new since that cursor.
|
|
var empty = await (await client.PostContractAsync(
|
|
PullUrl(vaultId),
|
|
new SyncPullRequest(first.NextCursor, null, null)))
|
|
.Content.ReadContractAsync<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.PostContractAsync(PushUrl(vaultId), NewCreateBatch());
|
|
|
|
var second = await (await client.PostContractAsync(
|
|
PullUrl(vaultId),
|
|
new SyncPullRequest(first.NextCursor, null, null)))
|
|
.Content.ReadContractAsync<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.PostContractAsync(
|
|
PullUrl(firstVault),
|
|
new SyncPullRequest(null, null, null));
|
|
var cursor = (await pull.Content.ReadContractAsync<SyncPullResponse>())!.NextCursor;
|
|
|
|
// Correctly signed, but issued for a different vault.
|
|
var response = await client.PostContractAsync(
|
|
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.PostContractAsync(
|
|
PullUrl(vaultId),
|
|
new SyncPullRequest("bm90LWEtcmVhbC1jdXJzb3I", null, null));
|
|
|
|
response.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
|
|
|
|
var problem = await response.Content.ReadProblemAsync();
|
|
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.PostContractAsync(PushUrl(vaultId), create);
|
|
|
|
// Update to version 2.
|
|
await client.PostContractAsync(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.PostContractAsync(PushUrl(vaultId), new SyncPushRequest(
|
|
[
|
|
NewOperation(entityId, expectedVersion: 1, envelope: [7, 7, 7]),
|
|
]));
|
|
|
|
stale.EnsureSuccessStatusCode();
|
|
|
|
var body = await stale.Content.ReadContractAsync<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.PostContractAsync(PushUrl(vaultId), create);
|
|
await client.PostContractAsync(PushUrl(vaultId), new SyncPushRequest(
|
|
[
|
|
NewOperation(entityId, expectedVersion: 1, envelope: [9, 9, 9]),
|
|
]));
|
|
|
|
await client.PostContractAsync(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.PostContractAsync(PushUrl(vaultId), batch);
|
|
first.EnsureSuccessStatusCode();
|
|
|
|
// Exactly the same batch again, as a retry after a timeout would be.
|
|
var replay = await client.PostContractAsync(PushUrl(vaultId), batch);
|
|
replay.EnsureSuccessStatusCode();
|
|
|
|
var body = await replay.Content.ReadContractAsync<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.PostContractAsync(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.PostContractAsync(PushUrl(vaultId), mixed);
|
|
|
|
// 200 despite a failed operation: per-operation status carries the detail.
|
|
response.StatusCode.ShouldBe(HttpStatusCode.OK);
|
|
|
|
var body = await response.Content.ReadContractAsync<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.PostContractAsync(PushUrl(vaultId), new SyncPushRequest(
|
|
[
|
|
new SyncPushOperation(
|
|
Guid.CreateVersion7(),
|
|
SyncEntityType.Host,
|
|
Guid.CreateVersion7(),
|
|
SyncOperation.Upsert,
|
|
null,
|
|
Payload([1, 2, 3]),
|
|
new SyncPlaintextFields(RelayEnabled: false, Hostname: "secret.internal", Port: 22)),
|
|
]));
|
|
|
|
response.EnsureSuccessStatusCode();
|
|
|
|
var body = await response.Content.ReadContractAsync<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.PostContractAsync(PushUrl(vaultId), new SyncPushRequest(
|
|
[
|
|
new SyncPushOperation(
|
|
Guid.CreateVersion7(),
|
|
SyncEntityType.Host,
|
|
Guid.CreateVersion7(),
|
|
SyncOperation.Upsert,
|
|
null,
|
|
Payload([1, 2, 3]),
|
|
new SyncPlaintextFields(RelayEnabled: true)),
|
|
]));
|
|
|
|
response.EnsureSuccessStatusCode();
|
|
|
|
var body = await response.Content.ReadContractAsync<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.PostContractAsync(PushUrl(vaultId), new SyncPushRequest(
|
|
[
|
|
new SyncPushOperation(
|
|
Guid.CreateVersion7(),
|
|
SyncEntityType.Host,
|
|
entityId,
|
|
SyncOperation.Upsert,
|
|
null,
|
|
Payload([1, 2, 3]),
|
|
new SyncPlaintextFields(RelayEnabled: true, Hostname: "bastion.internal", Port: 22)),
|
|
]));
|
|
|
|
await client.PostContractAsync(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.PostContractAsync(PushUrl(vaultId), create);
|
|
|
|
await client.PostContractAsync(PushUrl(vaultId), new SyncPushRequest(
|
|
[
|
|
new SyncPushOperation(
|
|
Guid.CreateVersion7(),
|
|
SyncEntityType.Host,
|
|
entityId,
|
|
SyncOperation.Delete,
|
|
ExpectedVersion: 1,
|
|
Payload: null,
|
|
PlaintextFields: null),
|
|
]));
|
|
|
|
var pull = await client.PostContractAsync(
|
|
PullUrl(vaultId),
|
|
new SyncPullRequest(null, null, null));
|
|
|
|
var body = await pull.Content.ReadContractAsync<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.PostContractAsync(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.
|
|
//
|
|
// The type is taken from the server's own registry rather than named, and that is not fussiness. This
|
|
// test used to name Credential, and implementing credentials turned it into a test asserting the
|
|
// opposite of the truth — it failed loudly, but a differently-shaped test would have gone quiet
|
|
// instead. Asking the registry what is still missing keeps it aimed at the branch it was written for.
|
|
var unsupported = Enum.GetValues<SyncEntityType>()
|
|
.Where(type => type != SyncEntityType.Unspecified)
|
|
.FirstOrDefault(type => Features.Sync.ItemKinds.For(type) is null);
|
|
|
|
Assert.SkipWhen(
|
|
unsupported == SyncEntityType.Unspecified,
|
|
"Every entity type in the contract is implemented, so this branch is no longer reachable.");
|
|
|
|
var (subject, vaultId) = await SeedUserWithVaultAsync();
|
|
var client = fixture.CreateClientFor(subject);
|
|
|
|
var response = await client.PostContractAsync(PushUrl(vaultId), new SyncPushRequest(
|
|
[
|
|
new SyncPushOperation(
|
|
Guid.CreateVersion7(),
|
|
unsupported,
|
|
Guid.CreateVersion7(),
|
|
SyncOperation.Upsert,
|
|
null,
|
|
Payload([1]),
|
|
null),
|
|
]));
|
|
|
|
response.EnsureSuccessStatusCode();
|
|
|
|
var body = await response.Content.ReadContractAsync<SyncPushResponse>();
|
|
body!.Results[0].Status.ShouldBe(SyncOperationStatus.Invalid);
|
|
}
|
|
|
|
// Just-in-time provisioning is covered by IdentityEndpointTests, against /me — the endpoint a
|
|
// client actually calls first, and the only one reachable before enrollment.
|
|
|
|
// ---- SSH keys ----
|
|
|
|
[Fact]
|
|
public async Task AnSshKey_RoundTripsWithNoPlaintextFields()
|
|
{
|
|
var (subject, vaultId) = await SeedUserWithVaultAsync();
|
|
var client = fixture.CreateClientFor(subject);
|
|
|
|
var keyId = Guid.CreateVersion7();
|
|
|
|
var pushed = await client.PostContractAsync(
|
|
PushUrl(vaultId),
|
|
new SyncPushRequest([KeyOperation(keyId, expectedVersion: null, envelope: [9, 8, 7])]));
|
|
|
|
var results = await pushed.Content.ReadContractAsync<SyncPushResponse>();
|
|
results!.Results.ShouldHaveSingleItem().Status.ShouldBe(SyncOperationStatus.Applied);
|
|
|
|
var pulled = await client.PostContractAsync(
|
|
PullUrl(vaultId),
|
|
new SyncPullRequest(null, null, [SyncEntityType.SshKey]));
|
|
|
|
var page = await pulled.Content.ReadContractAsync<SyncPullResponse>();
|
|
var change = page!.Changes.ShouldHaveSingleItem();
|
|
|
|
change.EntityType.ShouldBe(SyncEntityType.SshKey);
|
|
change.EntityId.ShouldBe(keyId);
|
|
change.Payload.ShouldNotBeNull().Envelope.ShouldBe(new byte[] { 9, 8, 7 });
|
|
|
|
// The point of the type. A key has no relay, so it has no plaintext columns at all — and null
|
|
// rather than an all-defaults instance, which would still put "relayEnabled": false on the wire and
|
|
// invite a reader to think the setting exists and is off.
|
|
change.PlaintextFields.ShouldBeNull();
|
|
}
|
|
|
|
[Fact]
|
|
public async Task AnSshKeyCarryingARelayTarget_IsRefused()
|
|
{
|
|
var (subject, vaultId) = await SeedUserWithVaultAsync();
|
|
var client = fixture.CreateClientFor(subject);
|
|
|
|
var operation = KeyOperation(Guid.CreateVersion7(), null, [1])
|
|
with
|
|
{ PlaintextFields = new SyncPlaintextFields(RelayEnabled: true, Hostname: "db.internal", Port: 22) };
|
|
|
|
var pushed = await client.PostContractAsync(PushUrl(vaultId), new SyncPushRequest([operation]));
|
|
|
|
var result = (await pushed.Content.ReadContractAsync<SyncPushResponse>())!.Results.ShouldHaveSingleItem();
|
|
|
|
result.Status.ShouldBe(SyncOperationStatus.Invalid);
|
|
result.Detail.ShouldNotBeNull().ShouldContain("no relay target");
|
|
}
|
|
|
|
/// <remarks>
|
|
/// The path most likely to break: a page of changes mixing item types has to load each type's rows
|
|
/// separately and then put them back in the log's order, because a client's cursor cannot resume from a
|
|
/// sequence that was regrouped.
|
|
/// </remarks>
|
|
[Fact]
|
|
public async Task ACredential_RoundTripsAsCiphertextWithNoPlaintextAtAll()
|
|
{
|
|
var (subject, vaultId) = await SeedUserWithVaultAsync();
|
|
var client = fixture.CreateClientFor(subject);
|
|
|
|
var credentialId = Guid.CreateVersion7();
|
|
|
|
var pushed = await client.PostContractAsync(
|
|
PushUrl(vaultId),
|
|
new SyncPushRequest(
|
|
[CredentialOperation(credentialId, expectedVersion: null, envelope: [7, 7, 7])]));
|
|
|
|
var results = await pushed.Content.ReadContractAsync<SyncPushResponse>();
|
|
results!.Results.ShouldHaveSingleItem().Status.ShouldBe(SyncOperationStatus.Applied);
|
|
|
|
var pulled = await client.PostContractAsync(
|
|
PullUrl(vaultId),
|
|
new SyncPullRequest(null, null, [SyncEntityType.Credential]));
|
|
|
|
var page = await pulled.Content.ReadContractAsync<SyncPullResponse>();
|
|
var change = page!.Changes.ShouldHaveSingleItem();
|
|
|
|
change.EntityType.ShouldBe(SyncEntityType.Credential);
|
|
change.EntityId.ShouldBe(credentialId);
|
|
change.Payload.ShouldNotBeNull().Envelope.ShouldBe([7, 7, 7]);
|
|
|
|
change.PlaintextFields.ShouldBeNull(
|
|
"a credential has no plaintext columns, so a pull has nothing to hydrate");
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ACredentialCarryingPlaintextFields_IsRejected()
|
|
{
|
|
// Refused rather than dropped. A client that thinks it is storing something and is not will be
|
|
// surprised later, and for this type "something" would be a detail about a password.
|
|
var (subject, vaultId) = await SeedUserWithVaultAsync();
|
|
var client = fixture.CreateClientFor(subject);
|
|
|
|
var operation = new SyncPushOperation(
|
|
Guid.CreateVersion7(),
|
|
SyncEntityType.Credential,
|
|
Guid.CreateVersion7(),
|
|
SyncOperation.Upsert,
|
|
null,
|
|
Payload([1, 2, 3]),
|
|
new SyncPlaintextFields(RelayEnabled: true, Hostname: "db.internal", Port: 22));
|
|
|
|
var pushed = await client.PostContractAsync(PushUrl(vaultId), new SyncPushRequest([operation]));
|
|
|
|
var result = (await pushed.Content.ReadContractAsync<SyncPushResponse>())!.Results
|
|
.ShouldHaveSingleItem();
|
|
|
|
result.Status.ShouldBe(SyncOperationStatus.Invalid);
|
|
result.Detail.ShouldNotBeNull().ShouldContain("no relay target");
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ACredentialWithAFingerprint_IsRejected()
|
|
{
|
|
// The one plaintext field a key may carry, refused here. A password has no public half, so a client
|
|
// sending one is confused about what it is storing.
|
|
var (subject, vaultId) = await SeedUserWithVaultAsync();
|
|
var client = fixture.CreateClientFor(subject);
|
|
|
|
var operation = new SyncPushOperation(
|
|
Guid.CreateVersion7(),
|
|
SyncEntityType.Credential,
|
|
Guid.CreateVersion7(),
|
|
SyncOperation.Upsert,
|
|
null,
|
|
Payload([1, 2, 3]),
|
|
new SyncPlaintextFields(PublicKeyFingerprint: "SHA256:whatever"));
|
|
|
|
var pushed = await client.PostContractAsync(PushUrl(vaultId), new SyncPushRequest([operation]));
|
|
|
|
var result = (await pushed.Content.ReadContractAsync<SyncPushResponse>())!.Results
|
|
.ShouldHaveSingleItem();
|
|
|
|
result.Status.ShouldBe(SyncOperationStatus.Invalid);
|
|
result.Detail.ShouldNotBeNull().ShouldContain("no public key");
|
|
}
|
|
|
|
[Fact]
|
|
public async Task AKnownHostKey_RoundTripsAsCiphertextWithNoPlaintextAtAll()
|
|
{
|
|
var (subject, vaultId) = await SeedUserWithVaultAsync();
|
|
var client = fixture.CreateClientFor(subject);
|
|
|
|
var pinId = Guid.CreateVersion7();
|
|
|
|
var pushed = await client.PostContractAsync(
|
|
PushUrl(vaultId),
|
|
new SyncPushRequest(
|
|
[KnownHostOperation(pinId, expectedVersion: null, envelope: [4, 2])]));
|
|
|
|
var results = await pushed.Content.ReadContractAsync<SyncPushResponse>();
|
|
results!.Results.ShouldHaveSingleItem().Status.ShouldBe(SyncOperationStatus.Applied);
|
|
|
|
var pulled = await client.PostContractAsync(
|
|
PullUrl(vaultId),
|
|
new SyncPullRequest(null, null, [SyncEntityType.KnownHostKey]));
|
|
|
|
var page = await pulled.Content.ReadContractAsync<SyncPullResponse>();
|
|
var change = page!.Changes.ShouldHaveSingleItem();
|
|
|
|
change.EntityType.ShouldBe(SyncEntityType.KnownHostKey);
|
|
change.EntityId.ShouldBe(pinId);
|
|
change.Payload.ShouldNotBeNull().Envelope.ShouldBe([4, 2]);
|
|
|
|
change.PlaintextFields.ShouldBeNull(
|
|
"which endpoints a user has approved is not something this server keeps");
|
|
}
|
|
|
|
[Fact]
|
|
public async Task AKnownHostKeyCarryingItsAddressInTheClear_IsRejected()
|
|
{
|
|
// The refusal that matters most of the four types, because this is the one item that genuinely holds
|
|
// an address: a client that put it in the relay columns would be handing the operator a list of the
|
|
// endpoints every user connects to, and it would look like an ordinary field while doing it.
|
|
var (subject, vaultId) = await SeedUserWithVaultAsync();
|
|
var client = fixture.CreateClientFor(subject);
|
|
|
|
var operation = KnownHostOperation(Guid.CreateVersion7(), null, [1])
|
|
with
|
|
{ PlaintextFields = new SyncPlaintextFields(RelayEnabled: true, Hostname: "db.internal", Port: 22) };
|
|
|
|
var pushed = await client.PostContractAsync(PushUrl(vaultId), new SyncPushRequest([operation]));
|
|
|
|
var result = (await pushed.Content.ReadContractAsync<SyncPushResponse>())!.Results
|
|
.ShouldHaveSingleItem();
|
|
|
|
result.Status.ShouldBe(SyncOperationStatus.Invalid);
|
|
result.Detail.ShouldNotBeNull().ShouldContain("stays encrypted");
|
|
}
|
|
|
|
[Fact]
|
|
public async Task AKnownHostKeyWithAFingerprintColumn_IsRejected()
|
|
{
|
|
// A pin is nothing but a fingerprint, so this is the field a client would most plausibly think it
|
|
// should send. The column exists for SSH keys, this client leaves even that one null, and a
|
|
// fingerprint here would identify the server rather than the user's own key.
|
|
var (subject, vaultId) = await SeedUserWithVaultAsync();
|
|
var client = fixture.CreateClientFor(subject);
|
|
|
|
var operation = KnownHostOperation(Guid.CreateVersion7(), null, [1])
|
|
with
|
|
{ PlaintextFields = new SyncPlaintextFields(PublicKeyFingerprint: "SHA256:whatever") };
|
|
|
|
var pushed = await client.PostContractAsync(PushUrl(vaultId), new SyncPushRequest([operation]));
|
|
|
|
var result = (await pushed.Content.ReadContractAsync<SyncPushResponse>())!.Results
|
|
.ShouldHaveSingleItem();
|
|
|
|
result.Status.ShouldBe(SyncOperationStatus.Invalid);
|
|
result.Detail.ShouldNotBeNull().ShouldContain("inside its payload");
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ThreeItemTypesWithOneId_AreThreeSeparateItems()
|
|
{
|
|
// The tables are separate, so one id may name a host, a key and a credential at once. Not something a
|
|
// client would do — ids are UUIDv7 — but if the write path ever confused two types, this is the test
|
|
// that says so rather than a mystery about a missing item.
|
|
var (subject, vaultId) = await SeedUserWithVaultAsync();
|
|
var client = fixture.CreateClientFor(subject);
|
|
|
|
var sharedId = Guid.CreateVersion7();
|
|
|
|
var pushed = await client.PostContractAsync(
|
|
PushUrl(vaultId),
|
|
new SyncPushRequest(
|
|
[
|
|
NewOperation(sharedId, expectedVersion: null, envelope: [1, 1]),
|
|
KeyOperation(sharedId, expectedVersion: null, envelope: [2, 2]),
|
|
CredentialOperation(sharedId, expectedVersion: null, envelope: [3, 3]),
|
|
]));
|
|
|
|
(await pushed.Content.ReadContractAsync<SyncPushResponse>())!.Results
|
|
.ShouldAllBe(result => result.Status == SyncOperationStatus.Applied);
|
|
|
|
var pulled = await client.PostContractAsync(
|
|
PullUrl(vaultId),
|
|
new SyncPullRequest(null, null, null));
|
|
|
|
var page = await pulled.Content.ReadContractAsync<SyncPullResponse>();
|
|
|
|
page!.Changes.Count.ShouldBe(3);
|
|
page.Changes.ShouldAllBe(change => change.EntityId == sharedId);
|
|
|
|
page.Changes.Select(change => change.EntityType).Order().ShouldBe(
|
|
[SyncEntityType.Host, SyncEntityType.Credential, SyncEntityType.SshKey]);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task APullMixingHostsAndKeys_ReturnsBothInLogOrder()
|
|
{
|
|
var (subject, vaultId) = await SeedUserWithVaultAsync();
|
|
var client = fixture.CreateClientFor(subject);
|
|
|
|
var hostId = Guid.CreateVersion7();
|
|
var keyId = Guid.CreateVersion7();
|
|
|
|
var pushed = await client.PostContractAsync(
|
|
PushUrl(vaultId),
|
|
new SyncPushRequest(
|
|
[
|
|
NewOperation(hostId, expectedVersion: null, envelope: [1, 1]),
|
|
KeyOperation(keyId, expectedVersion: null, envelope: [2, 2]),
|
|
]));
|
|
|
|
(await pushed.Content.ReadContractAsync<SyncPushResponse>())!.Results
|
|
.ShouldAllBe(result => result.Status == SyncOperationStatus.Applied);
|
|
|
|
var pulled = await client.PostContractAsync(
|
|
PullUrl(vaultId),
|
|
new SyncPullRequest(null, null, null));
|
|
|
|
var page = await pulled.Content.ReadContractAsync<SyncPullResponse>();
|
|
|
|
page!.Changes.Count.ShouldBe(2);
|
|
page.Changes.Select(change => change.ChangeSequence)
|
|
.ShouldBeInOrder(Shouldly.SortDirection.Ascending);
|
|
|
|
var host = page.Changes.Single(change => change.EntityId == hostId);
|
|
var key = page.Changes.Single(change => change.EntityId == keyId);
|
|
|
|
host.EntityType.ShouldBe(SyncEntityType.Host);
|
|
host.Payload.ShouldNotBeNull().Envelope.ShouldBe(new byte[] { 1, 1 });
|
|
host.PlaintextFields.ShouldNotBeNull();
|
|
|
|
key.EntityType.ShouldBe(SyncEntityType.SshKey);
|
|
key.Payload.ShouldNotBeNull().Envelope.ShouldBe(new byte[] { 2, 2 });
|
|
key.PlaintextFields.ShouldBeNull();
|
|
}
|
|
|
|
[Fact]
|
|
public async Task DeletingAnSshKey_TombstonesItWithoutAPayload()
|
|
{
|
|
var (subject, vaultId) = await SeedUserWithVaultAsync();
|
|
var client = fixture.CreateClientFor(subject);
|
|
|
|
var keyId = Guid.CreateVersion7();
|
|
|
|
await client.PostContractAsync(
|
|
PushUrl(vaultId),
|
|
new SyncPushRequest([KeyOperation(keyId, null, [5])]));
|
|
|
|
var deleted = await client.PostContractAsync(
|
|
PushUrl(vaultId),
|
|
new SyncPushRequest(
|
|
[
|
|
new SyncPushOperation(
|
|
Guid.CreateVersion7(),
|
|
SyncEntityType.SshKey,
|
|
keyId,
|
|
SyncOperation.Delete,
|
|
ExpectedVersion: 1,
|
|
Payload: null,
|
|
PlaintextFields: null),
|
|
]));
|
|
|
|
(await deleted.Content.ReadContractAsync<SyncPushResponse>())!.Results
|
|
.ShouldHaveSingleItem().Status.ShouldBe(SyncOperationStatus.Applied);
|
|
|
|
var pulled = await client.PostContractAsync(
|
|
PullUrl(vaultId),
|
|
new SyncPullRequest(null, null, [SyncEntityType.SshKey]));
|
|
|
|
var page = await pulled.Content.ReadContractAsync<SyncPullResponse>();
|
|
var last = page!.Changes[^1];
|
|
|
|
last.Operation.ShouldBe(SyncOperation.Delete);
|
|
last.Payload.ShouldBeNull("a tombstone must not ship the key material it replaced");
|
|
}
|
|
|
|
// ---- 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}";
|
|
|
|
/// <summary>
|
|
/// A structurally valid payload. The bytes are meaningless on purpose: the server cannot read
|
|
/// any of them, and a test that pretended otherwise would be testing the wrong thing.
|
|
/// </summary>
|
|
private static EncryptedPayload Payload(byte[] envelope) =>
|
|
new(envelope, WrappedDataKey: [0xD, 0xE], DataKeyId: Guid.CreateVersion7(), 1, 1);
|
|
|
|
private static SyncPushOperation NewOperation(Guid entityId, int? expectedVersion, byte[] envelope) =>
|
|
new(
|
|
Guid.CreateVersion7(),
|
|
SyncEntityType.Host,
|
|
entityId,
|
|
SyncOperation.Upsert,
|
|
expectedVersion,
|
|
Payload(envelope),
|
|
new SyncPlaintextFields());
|
|
|
|
/// <remarks>
|
|
/// <c>PlaintextFields: null</c> rather than an empty instance, which is what a real client sends for a
|
|
/// type with no plaintext columns — and what the server must accept without inventing defaults.
|
|
/// </remarks>
|
|
/// <remarks>
|
|
/// Like <see cref="KeyOperation"/> with even less: a credential has no plaintext column at all, not even
|
|
/// the fingerprint a key may carry, so this is the narrowest an operation gets.
|
|
/// </remarks>
|
|
private static SyncPushOperation CredentialOperation(
|
|
Guid entityId,
|
|
int? expectedVersion,
|
|
byte[] envelope) =>
|
|
new(
|
|
Guid.CreateVersion7(),
|
|
SyncEntityType.Credential,
|
|
entityId,
|
|
SyncOperation.Upsert,
|
|
expectedVersion,
|
|
Payload(envelope),
|
|
PlaintextFields: null);
|
|
|
|
private static SyncPushOperation KeyOperation(Guid entityId, int? expectedVersion, byte[] envelope) =>
|
|
new(
|
|
Guid.CreateVersion7(),
|
|
SyncEntityType.SshKey,
|
|
entityId,
|
|
SyncOperation.Upsert,
|
|
expectedVersion,
|
|
Payload(envelope),
|
|
PlaintextFields: null);
|
|
|
|
/// <remarks>
|
|
/// As narrow as <see cref="CredentialOperation"/>, and worth stating why for a type that is nothing but an
|
|
/// address and a fingerprint: both stay inside the envelope, so there is no field here either.
|
|
/// </remarks>
|
|
private static SyncPushOperation KnownHostOperation(
|
|
Guid entityId,
|
|
int? expectedVersion,
|
|
byte[] envelope) =>
|
|
new(
|
|
Guid.CreateVersion7(),
|
|
SyncEntityType.KnownHostKey,
|
|
entityId,
|
|
SyncOperation.Upsert,
|
|
expectedVersion,
|
|
Payload(envelope),
|
|
PlaintextFields: null);
|
|
|
|
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 = NewUser(subject);
|
|
|
|
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.UserKeys.Add(Seed.CurrentKey(user.Id, Now));
|
|
database.Vaults.Add(vault);
|
|
await database.SaveChangesAsync();
|
|
|
|
return (subject, vault.Id);
|
|
}
|
|
|
|
/// <summary>
|
|
/// An enrolled user with no vault of their own: the realistic intruder.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// The denial tests use one of these rather than an unenrolled caller. An unenrolled caller is
|
|
/// stopped by the enrolled policy before the vault check runs at all, which would leave the
|
|
/// authorization tests passing without ever exercising the thing they exist to prove.
|
|
/// </remarks>
|
|
private async Task<string> SeedEnrolledUserAsync()
|
|
{
|
|
var subject = NewSubject();
|
|
|
|
await using var scope = fixture.CreateScope();
|
|
var database = scope.ServiceProvider.GetRequiredService<DodoDbContext>();
|
|
|
|
var user = NewUser(subject);
|
|
database.Users.Add(user);
|
|
database.UserKeys.Add(Seed.CurrentKey(user.Id, Now));
|
|
await database.SaveChangesAsync();
|
|
|
|
return subject;
|
|
}
|
|
|
|
private UserAccount NewUser(string subject) =>
|
|
new()
|
|
{
|
|
Id = Guid.CreateVersion7(),
|
|
Issuer = fixture.IdentityProvider.Authority,
|
|
Subject = subject,
|
|
Status = UserStatus.Active,
|
|
CreatedAtUtc = Now,
|
|
UpdatedAtUtc = Now,
|
|
};
|
|
|
|
private async Task<Guid> SeedTeamVaultAsync()
|
|
{
|
|
await using var scope = fixture.CreateScope();
|
|
var database = scope.ServiceProvider.GetRequiredService<DodoDbContext>();
|
|
|
|
var owner = NewUser(NewSubject());
|
|
|
|
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;
|
|
}
|
|
}
|