Public Access
Add the server client and client-side enrollment
A typed client over DodoSSH.Contracts, and the orchestration that turns a passphrase into an enrolled identity: generate keys, have the identity provider sign over them, wrap the bundle three ways, create the personal vault, publish. Ordering here is forced, not chosen. The secret bundle's AAD binds to the server-assigned user id, so /me has to be read before anything can be wrapped -- which is exactly why /me provisions the account and returns its id even while reporting that enrollment is required. That constraint was designed into the server earlier; this is the first code that depends on it. The grant tuple now has a real canonical encoding (crypto.md 7.3) rather than the placeholder signature I would otherwise have had to invent and then keep. §7 named the tuple without specifying how to encode it; this fills that in with the same conventions as 7.1, and the self-grant at enrollment is already in its final format. The signature covers SHA-256(wrappedKey) rather than the key, so a verifier can check attribution without holding the vault key at all. The most valuable tests are the negative ones about the request body: the server is meant to be unable to read what it stores, and a refactor that put a passphrase or a private key into the enrollment request would be invisible to every other test in the repository. So one asserts the body contains neither the passphrase, the recovery code, nor any private key in base64 or hex. Another opens the same bundle three ways -- passphrase, recovery code and device key -- which is what makes a passphrase change a one-row update. ClientEnrollment depends on IKeyBindingAuthorizer rather than the whole OidcClient. It needs exactly one capability, and depending on the full client would drag discovery and token exchange into every test of key binding. Two things fixed while building it. The recovery code buffer was sized one separator short, so every enrollment threw IndexOutOfRange -- caught immediately because nine of ten tests failed identically. And the crypto enum collided with Domain.GrantKind in the server, so it is GrantPurpose there; the numeric values still have to match, which the doc and a test both say. 448 tests pass, zero warnings on a clean rebuild, format clean.
This commit is contained in:
@@ -0,0 +1,356 @@
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using DodoSSH.Client.Auth;
|
||||
using DodoSSH.Contracts;
|
||||
using DodoSSH.Crypto;
|
||||
|
||||
namespace DodoSSH.Client.Api.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The client half of enrollment: what it sends, and what it keeps to itself.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The most valuable assertions here are the negative ones about the request body. The server is
|
||||
/// supposed to be unable to read anything it stores, and this is where that either holds or quietly
|
||||
/// stops holding — a refactor that put a passphrase or a private key into the request would be
|
||||
/// invisible to every other test in the repository.
|
||||
/// </remarks>
|
||||
public sealed class ClientEnrollmentTests : IDisposable
|
||||
{
|
||||
private const string Passphrase = "correct horse battery staple";
|
||||
private const string EnrollmentPath = "/api/v1/me/enrollment";
|
||||
|
||||
private static readonly Guid UserId = Guid.Parse("0192f0c8-1a2b-7c3d-8e4f-5a6b7c8d9e0f");
|
||||
|
||||
private readonly StubServer server = new();
|
||||
private readonly HttpClient http = new();
|
||||
|
||||
public ClientEnrollmentTests() => http.BaseAddress = server.BaseUrl;
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose()
|
||||
{
|
||||
http.Dispose();
|
||||
server.Dispose();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Enroll_SendsAStatementTheServerCanVerify()
|
||||
{
|
||||
var binding = new CapturingKeyBinding();
|
||||
var outcome = await EnrollAsync(binding);
|
||||
|
||||
using var bundle = outcome.Bundle;
|
||||
|
||||
var request = ReadRequest();
|
||||
|
||||
// The statement must describe the caller, or the server rejects it — and the signature must
|
||||
// verify against the statement's own signing key, which is what proves possession.
|
||||
request.Statement.Issuer.ShouldBe("https://idp.example/realms/dodossh");
|
||||
request.Statement.Subject.ShouldBe("alice");
|
||||
request.Statement.KeyGeneration.ShouldBe(1);
|
||||
request.Statement.EncryptionPublicKey.ShouldBe(bundle.EncryptionPublicKey);
|
||||
request.Statement.SigningPublicKey.ShouldBe(bundle.SigningPublicKey);
|
||||
|
||||
DshSignatures.VerifyKeyStatement(
|
||||
request.Statement.SigningPublicKey,
|
||||
KeyStatementCodec.Encode(ToFields(request.Statement)),
|
||||
request.StatementSignature)
|
||||
.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Enroll_BindsTheKeysWithTheStatementsOwnHash()
|
||||
{
|
||||
// The nonce handed to the identity provider must be this statement's hash and no other,
|
||||
// otherwise the token binds keys nobody is publishing.
|
||||
var binding = new CapturingKeyBinding();
|
||||
var outcome = await EnrollAsync(binding);
|
||||
outcome.Bundle.Dispose();
|
||||
|
||||
var request = ReadRequest();
|
||||
|
||||
binding.RequestedNonce.ShouldBe(
|
||||
KeyStatementCodec.ComputeNonce(ToFields(request.Statement)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Enroll_SendsNothingTheServerCouldUseToOpenTheVault()
|
||||
{
|
||||
var outcome = await EnrollAsync(new CapturingKeyBinding());
|
||||
|
||||
using var bundle = outcome.Bundle;
|
||||
var body = server.LastBody(EnrollmentPath);
|
||||
|
||||
// The passphrase and the recovery code exist only on this machine.
|
||||
body.ShouldNotContain(Passphrase);
|
||||
body.ShouldNotContain(outcome.RecoveryCode);
|
||||
|
||||
// Nor may any private key appear, in any encoding the serialiser might have chosen.
|
||||
body.ShouldNotContain(Convert.ToBase64String(outcome.PersonalVaultKey));
|
||||
body.ShouldNotContain(Convert.ToBase64String(outcome.DevicePrivateKey));
|
||||
body.ShouldNotContain(Convert.ToHexString(outcome.PersonalVaultKey));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Enroll_WrapsTheSameBundleThreeWays()
|
||||
{
|
||||
// One bundle, several wraps, which is what makes a passphrase change a single-row update
|
||||
// rather than a re-encryption of the vault.
|
||||
var outcome = await EnrollAsync(new CapturingKeyBinding());
|
||||
|
||||
using var bundle = outcome.Bundle;
|
||||
var request = ReadRequest();
|
||||
var descriptor = DshAad.UserSecretBundle(UserId);
|
||||
|
||||
using var viaPassphrase = OpenWithPassphrase(request, Passphrase, descriptor);
|
||||
viaPassphrase.ShouldNotBeNull();
|
||||
viaPassphrase.SigningPublicKey.ShouldBe(bundle.SigningPublicKey);
|
||||
|
||||
request.RecoveryWrappedPrivateKey.ShouldNotBeNull();
|
||||
request.RecoveryKdfParameters.ShouldNotBeNull();
|
||||
|
||||
using var viaRecovery = OpenWithRecovery(request, outcome.RecoveryCode, descriptor);
|
||||
viaRecovery.ShouldNotBeNull();
|
||||
viaRecovery.SigningPublicKey.ShouldBe(bundle.SigningPublicKey);
|
||||
|
||||
// The device wrap is sealed to the device key rather than derived, so it opens with the
|
||||
// private half the caller was handed to put in the OS keystore.
|
||||
request.DevicePublicKey.ShouldNotBeNull();
|
||||
request.DeviceWrappedPrivateKey.ShouldNotBeNull();
|
||||
|
||||
using var deviceKey = NSec.Cryptography.Key.Import(
|
||||
NSec.Cryptography.KeyAgreementAlgorithm.X25519,
|
||||
outcome.DevicePrivateKey,
|
||||
NSec.Cryptography.KeyBlobFormat.RawPrivateKey);
|
||||
|
||||
using var viaDevice = UserSecretBundle.TryOpenSealed(
|
||||
deviceKey, request.DeviceWrappedPrivateKey, descriptor);
|
||||
|
||||
viaDevice.ShouldNotBeNull();
|
||||
viaDevice.SigningPublicKey.ShouldBe(bundle.SigningPublicKey);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Enroll_SendsKdfParametersStrongEnoughForTheServerToAccept()
|
||||
{
|
||||
// The server enforces a floor. Sending anything below it fails enrollment against a real
|
||||
// server while passing every stub, so the values are asserted here rather than discovered
|
||||
// later.
|
||||
var outcome = await EnrollAsync(new CapturingKeyBinding());
|
||||
outcome.Bundle.Dispose();
|
||||
|
||||
var request = ReadRequest();
|
||||
|
||||
request.KdfParameters.Algorithm.ShouldBe("argon2id");
|
||||
request.KdfParameters.MemoryKibibytes.ShouldBe(Argon2Profile.PassphraseDefault.MemoryKibibytes);
|
||||
request.KdfParameters.Passes.ShouldBe(Argon2Profile.PassphraseDefault.Passes);
|
||||
request.KdfParameters.Parallelism.ShouldBe(1);
|
||||
request.KdfParameters.Salt.Length.ShouldBe(CryptoSpec.SaltSize);
|
||||
|
||||
// A distinct salt per wrap. Reusing one would let a single cracking effort cover both.
|
||||
request.RecoveryKdfParameters!.Salt.ShouldNotBe(request.KdfParameters.Salt);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Enroll_SignsThePersonalVaultGrantOverTheCanonicalTuple()
|
||||
{
|
||||
var outcome = await EnrollAsync(new CapturingKeyBinding());
|
||||
|
||||
using var bundle = outcome.Bundle;
|
||||
var request = ReadRequest();
|
||||
var vault = request.PersonalVault;
|
||||
|
||||
var fingerprint = DshCrypto.ComputeFingerprint(
|
||||
bundle.EncryptionPublicKey, bundle.SigningPublicKey);
|
||||
|
||||
var grant = GrantStatementCodec.Encode(
|
||||
vault.VaultId,
|
||||
keyGeneration: 1,
|
||||
GrantPurpose.Member,
|
||||
granteeUserId: UserId,
|
||||
granteeKeyFingerprint: fingerprint,
|
||||
wrappedKey: vault.WrappedVaultKey,
|
||||
granterUserId: UserId,
|
||||
granterKeyFingerprint: fingerprint,
|
||||
keyLogHead: default,
|
||||
grantedAt: vault.GrantedAt);
|
||||
|
||||
GrantStatementCodec.Verify(bundle.SigningPublicKey, grant, vault.GrantSignature)
|
||||
.ShouldBeTrue("A grant the granter's own key cannot verify is one no client will accept.");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Enroll_SealsThePersonalVaultKeyToTheEnrollingIdentity()
|
||||
{
|
||||
var outcome = await EnrollAsync(new CapturingKeyBinding());
|
||||
|
||||
using var bundle = outcome.Bundle;
|
||||
var vault = ReadRequest().PersonalVault;
|
||||
|
||||
VaultKeys.TryUnwrap(bundle.EncryptionKey, vault.WrappedVaultKey, vault.VaultId, 1)
|
||||
.ShouldBe(outcome.PersonalVaultKey);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Enroll_ProducesAReadableRecoveryCode()
|
||||
{
|
||||
// Read aloud or copied off a screen, so the alphabet omits the characters that get
|
||||
// mistranscribed.
|
||||
var outcome = await EnrollAsync(new CapturingKeyBinding());
|
||||
outcome.Bundle.Dispose();
|
||||
|
||||
outcome.RecoveryCode.ShouldNotBeNullOrWhiteSpace();
|
||||
outcome.RecoveryCode.ShouldContain("-");
|
||||
|
||||
foreach (var character in outcome.RecoveryCode.Replace("-", string.Empty, StringComparison.Ordinal))
|
||||
{
|
||||
"0123456789ABCDEFGHJKMNPQRSTVWXYZ".ShouldContain(character);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Enroll_DisposesTheBundleWhenTheServerRefuses()
|
||||
{
|
||||
// The caller never receives the bundle on failure, so nothing else could release its guarded
|
||||
// memory.
|
||||
server.StubProblem(
|
||||
EnrollmentPath, "POST", 409, ProblemCodes.AlreadyEnrolled, "Already enrolled.");
|
||||
|
||||
var enrollment = new ClientEnrollment(
|
||||
new DodoSshApiClient(http, new StubTokenProvider()),
|
||||
new CapturingKeyBinding(),
|
||||
TimeProvider.System);
|
||||
|
||||
var exception = await Should.ThrowAsync<DodoSshApiException>(async () =>
|
||||
await enrollment.EnrollAsync(
|
||||
Me(), Passphrase, "laptop", "Personal", TestContext.Current.CancellationToken));
|
||||
|
||||
exception.Code.ShouldBe(ProblemCodes.AlreadyEnrolled);
|
||||
exception.StatusCode.ShouldBe(HttpStatusCode.Conflict);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Enroll_RejectsAnEmptyPassphraseBeforeTouchingTheNetwork()
|
||||
{
|
||||
var binding = new CapturingKeyBinding();
|
||||
|
||||
var enrollment = new ClientEnrollment(
|
||||
new DodoSshApiClient(http, new StubTokenProvider()),
|
||||
binding,
|
||||
TimeProvider.System);
|
||||
|
||||
await Should.ThrowAsync<ArgumentException>(async () =>
|
||||
await enrollment.EnrollAsync(
|
||||
Me(), string.Empty, "laptop", "Personal", TestContext.Current.CancellationToken));
|
||||
|
||||
binding.RequestedNonce.ShouldBeNull("Nothing should reach the identity provider.");
|
||||
}
|
||||
|
||||
// ---- Helpers ----
|
||||
|
||||
private async Task<EnrollmentOutcome> EnrollAsync(CapturingKeyBinding binding)
|
||||
{
|
||||
server.StubEnrollment(new EnrollmentResponse(
|
||||
UserId: UserId,
|
||||
KeyGeneration: 1,
|
||||
Fingerprint: new byte[32],
|
||||
PersonalVaultId: Guid.CreateVersion7(),
|
||||
DeviceId: Guid.CreateVersion7(),
|
||||
KeyLogSequence: 1));
|
||||
|
||||
var enrollment = new ClientEnrollment(
|
||||
new DodoSshApiClient(http, new StubTokenProvider()),
|
||||
binding,
|
||||
TimeProvider.System);
|
||||
|
||||
return await enrollment.EnrollAsync(
|
||||
Me(), Passphrase, "laptop", "Personal", TestContext.Current.CancellationToken);
|
||||
}
|
||||
|
||||
private EnrollmentRequest ReadRequest()
|
||||
{
|
||||
var request = JsonSerializer.Deserialize(
|
||||
server.LastBody(EnrollmentPath),
|
||||
DodoSshJsonContext.Default.EnrollmentRequest);
|
||||
|
||||
request.ShouldNotBeNull();
|
||||
return request;
|
||||
}
|
||||
|
||||
private static MeResponse Me() =>
|
||||
new(
|
||||
UserId: UserId,
|
||||
Issuer: "https://idp.example/realms/dodossh",
|
||||
Subject: "alice",
|
||||
Email: "alice@example.com",
|
||||
DisplayName: "Alice",
|
||||
EnrollmentRequired: true,
|
||||
KeyGeneration: null,
|
||||
WrappedPrivateKey: null,
|
||||
KdfParameters: null,
|
||||
Vaults: []);
|
||||
|
||||
private static UserSecretBundle? OpenWithPassphrase(
|
||||
EnrollmentRequest request,
|
||||
string passphrase,
|
||||
AadDescriptor descriptor)
|
||||
{
|
||||
// Reconstructed from the stored parameters, exactly as a client unlocking on another device
|
||||
// would do after reading them from /me.
|
||||
using var master = MasterKey.Derive(
|
||||
passphrase,
|
||||
request.KdfParameters.Salt,
|
||||
Argon2Profile.FromStoredParameters(
|
||||
request.KdfParameters.MemoryKibibytes,
|
||||
request.KdfParameters.Passes,
|
||||
request.KdfParameters.Parallelism));
|
||||
|
||||
return master.TryOpenBundle(request.WrappedPrivateKey, descriptor);
|
||||
}
|
||||
|
||||
private static UserSecretBundle? OpenWithRecovery(
|
||||
EnrollmentRequest request,
|
||||
string recoveryCode,
|
||||
AadDescriptor descriptor)
|
||||
{
|
||||
var parameters = request.RecoveryKdfParameters!;
|
||||
|
||||
using var master = MasterKey.Derive(
|
||||
recoveryCode,
|
||||
parameters.Salt,
|
||||
Argon2Profile.FromStoredParameters(
|
||||
parameters.MemoryKibibytes, parameters.Passes, parameters.Parallelism));
|
||||
|
||||
return master.TryOpenBundle(request.RecoveryWrappedPrivateKey!, descriptor);
|
||||
}
|
||||
|
||||
private static KeyStatementFields ToFields(KeyStatement statement) =>
|
||||
new(
|
||||
statement.Version,
|
||||
statement.Issuer,
|
||||
statement.Subject,
|
||||
statement.Email,
|
||||
statement.EncryptionPublicKey,
|
||||
statement.SigningPublicKey,
|
||||
statement.KeyGeneration,
|
||||
statement.CreatedAt,
|
||||
statement.DeviceName);
|
||||
|
||||
/// <summary>Records the nonce it was asked to bind, and returns a token carrying it.</summary>
|
||||
private sealed class CapturingKeyBinding : IKeyBindingAuthorizer
|
||||
{
|
||||
internal string? RequestedNonce { get; private set; }
|
||||
|
||||
public Task<string> AuthorizeKeyBindingAsync(
|
||||
string bindingNonce,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
RequestedNonce = bindingNonce;
|
||||
|
||||
// Shape only. The real token's signature and nonce are the server's to verify, and doing
|
||||
// it here would just be testing the stub.
|
||||
return Task.FromResult($"header.{bindingNonce}.signature");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
The client against a stubbed DodoSSH server. Its job is the wire contract and the enrollment
|
||||
orchestration: that requests carry what the server expects, that problem codes survive, and
|
||||
that nothing secret leaves the process.
|
||||
-->
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../../src/DodoSSH.Client.Api/DodoSSH.Client.Api.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="WireMock.Net" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,239 @@
|
||||
using System.Net;
|
||||
using DodoSSH.Contracts;
|
||||
|
||||
namespace DodoSSH.Client.Api.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The wire contract: what goes out, what comes back, and how failures surface.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The problem-code assertions matter most. Those codes are how a client decides what to do next —
|
||||
/// <c>enrollment-required</c> means enroll, <c>vault-conflict</c> means merge and retry — so losing one
|
||||
/// while parsing an error turns an actionable failure into an opaque one.
|
||||
/// </remarks>
|
||||
public sealed class DodoSshApiClientTests : IDisposable
|
||||
{
|
||||
private static readonly Guid VaultId = Guid.Parse("0192f0c8-1a2b-7c3d-8e4f-5a6b7c8d9e0f");
|
||||
|
||||
private readonly StubServer server = new();
|
||||
private readonly HttpClient http = new();
|
||||
|
||||
public DodoSshApiClientTests() => http.BaseAddress = server.BaseUrl;
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose()
|
||||
{
|
||||
http.Dispose();
|
||||
server.Dispose();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Meta_IsFetchedWithoutAToken()
|
||||
{
|
||||
// A client has to be able to ask what a server supports before it can authenticate, so this
|
||||
// one must not require a bearer token.
|
||||
server.StubMeta(new MetaResponse(
|
||||
ServerVersion: "1.2.3",
|
||||
ApiVersions: [1],
|
||||
SyncProtocolVersion: 1,
|
||||
CryptoSpecVersion: 1,
|
||||
Features: ["teams"],
|
||||
MinClientVersion: null,
|
||||
MaxOperationsPerPush: 500,
|
||||
MaxPayloadBytes: 8 * 1024 * 1024,
|
||||
MaxItemPayloadBytes: 256 * 1024));
|
||||
|
||||
var meta = await Client().GetMetaAsync(TestContext.Current.CancellationToken);
|
||||
|
||||
meta.ServerVersion.ShouldBe("1.2.3");
|
||||
meta.MaxOperationsPerPush.ShouldBe(500);
|
||||
|
||||
server.LastAuthorization("/api/v1/meta").ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Me_CarriesTheBearerToken()
|
||||
{
|
||||
server.StubMe(UnenrolledMe());
|
||||
|
||||
var me = await Client().GetMeAsync(TestContext.Current.CancellationToken);
|
||||
|
||||
me.EnrollmentRequired.ShouldBeTrue();
|
||||
server.LastAuthorization("/api/v1/me").ShouldBe("Bearer test-access-token");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Me_RoundTripsVaultSummaries()
|
||||
{
|
||||
// Byte arrays through the source-generated serialiser, which is the one thing most likely to
|
||||
// go wrong silently between the two sides.
|
||||
var wrappedKey = new byte[] { 1, 2, 3, 4, 5 };
|
||||
|
||||
server.StubMe(UnenrolledMe() with
|
||||
{
|
||||
EnrollmentRequired = false,
|
||||
KeyGeneration = 1,
|
||||
WrappedPrivateKey = [9, 8, 7],
|
||||
KdfParameters = new KdfParameters("argon2id", [1, 2, 3], 262144, 4, 1),
|
||||
Vaults =
|
||||
[
|
||||
new VaultSummary(
|
||||
VaultId: VaultId,
|
||||
Name: "Personal",
|
||||
IsPersonal: true,
|
||||
TeamId: null,
|
||||
KeyGeneration: 1,
|
||||
Permissions: 31,
|
||||
WrappedVaultKey: wrappedKey,
|
||||
RekeyRequired: false),
|
||||
],
|
||||
});
|
||||
|
||||
var me = await Client().GetMeAsync(TestContext.Current.CancellationToken);
|
||||
|
||||
var vault = me.Vaults.ShouldHaveSingleItem();
|
||||
vault.WrappedVaultKey.ShouldBe(wrappedKey);
|
||||
vault.KeyGeneration.ShouldBe(1u);
|
||||
me.WrappedPrivateKey.ShouldBe([9, 8, 7]);
|
||||
me.KdfParameters!.MemoryKibibytes.ShouldBe(262144);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AProblemResponse_KeepsItsCode()
|
||||
{
|
||||
server.StubProblem(
|
||||
"/api/v1/me", "GET", 403, ProblemCodes.EnrollmentRequired, "Publish an identity key first.");
|
||||
|
||||
var exception = await Should.ThrowAsync<DodoSshApiException>(async () =>
|
||||
await Client().GetMeAsync(TestContext.Current.CancellationToken));
|
||||
|
||||
exception.Code.ShouldBe(ProblemCodes.EnrollmentRequired);
|
||||
exception.StatusCode.ShouldBe(HttpStatusCode.Forbidden);
|
||||
exception.Message.ShouldContain("Publish an identity key first.");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ANonJsonError_StillReportsItsStatus()
|
||||
{
|
||||
// A reverse proxy in front of a dead server returns HTML. Losing the status code while trying
|
||||
// to parse that as ProblemDetails would replace a diagnosable failure with a parse error.
|
||||
server.StubGatewayError("/api/v1/me", "GET");
|
||||
|
||||
var exception = await Should.ThrowAsync<DodoSshApiException>(async () =>
|
||||
await Client().GetMeAsync(TestContext.Current.CancellationToken));
|
||||
|
||||
exception.StatusCode.ShouldBe(HttpStatusCode.BadGateway);
|
||||
exception.Code.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Push_SendsTheBatchAndReturnsPerOperationStatus()
|
||||
{
|
||||
// A push succeeds with mixed results on purpose, so one stale item cannot block everything
|
||||
// else a client queued while offline. Callers must read the statuses rather than trusting
|
||||
// the 200.
|
||||
var applied = Guid.CreateVersion7();
|
||||
var conflicted = Guid.CreateVersion7();
|
||||
|
||||
server.StubPush(VaultId, new SyncPushResponse(
|
||||
Results:
|
||||
[
|
||||
new SyncPushResult(applied, SyncOperationStatus.Applied, 1, 10, null, null),
|
||||
new SyncPushResult(conflicted, SyncOperationStatus.Conflict, 2, 11, null, null),
|
||||
],
|
||||
Cursor: "next-cursor"));
|
||||
|
||||
var request = new SyncPushRequest(
|
||||
[
|
||||
new SyncPushOperation(
|
||||
applied,
|
||||
SyncEntityType.Host,
|
||||
Guid.CreateVersion7(),
|
||||
SyncOperation.Upsert,
|
||||
null,
|
||||
new EncryptedPayload([1, 2, 3], 1, 1),
|
||||
new SyncPlaintextFields()),
|
||||
]);
|
||||
|
||||
var response = await Client().SyncPushAsync(
|
||||
VaultId, request, TestContext.Current.CancellationToken);
|
||||
|
||||
response.Results.Count.ShouldBe(2);
|
||||
response.Results[0].Status.ShouldBe(SyncOperationStatus.Applied);
|
||||
response.Results[1].Status.ShouldBe(SyncOperationStatus.Conflict);
|
||||
response.Cursor.ShouldBe("next-cursor");
|
||||
|
||||
var body = server.LastBody($"/api/v1/vaults/{VaultId}/sync/push");
|
||||
body.ShouldContain("operations");
|
||||
body.ShouldContain("Upsert");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Pull_RoundTripsChangesAndTheCursor()
|
||||
{
|
||||
var entityId = Guid.CreateVersion7();
|
||||
|
||||
server.StubPull(VaultId, new SyncPullResponse(
|
||||
Changes:
|
||||
[
|
||||
new SyncChange(
|
||||
SyncEntityType.Host,
|
||||
entityId,
|
||||
SyncOperation.Upsert,
|
||||
Version: 1,
|
||||
ChangeSequence: 5,
|
||||
Payload: new EncryptedPayload([4, 5, 6], 1, 1),
|
||||
PlaintextFields: new SyncPlaintextFields(RelayEnabled: false),
|
||||
UpdatedAt: DateTimeOffset.FromUnixTimeSeconds(1_750_000_000)),
|
||||
],
|
||||
NextCursor: "cursor-2",
|
||||
HasMore: false,
|
||||
ServerTime: DateTimeOffset.FromUnixTimeSeconds(1_750_000_001),
|
||||
CurrentKeyGeneration: 1));
|
||||
|
||||
var response = await Client().SyncPullAsync(
|
||||
VaultId,
|
||||
new SyncPullRequest("cursor-1", null, null),
|
||||
TestContext.Current.CancellationToken);
|
||||
|
||||
var change = response.Changes.ShouldHaveSingleItem();
|
||||
change.EntityId.ShouldBe(entityId);
|
||||
change.Payload!.Envelope.ShouldBe([4, 5, 6]);
|
||||
response.NextCursor.ShouldBe("cursor-2");
|
||||
response.HasMore.ShouldBeFalse();
|
||||
|
||||
server.LastBody($"/api/v1/vaults/{VaultId}/sync/pull").ShouldContain("cursor-1");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AConflictOnPush_SurfacesItsCode()
|
||||
{
|
||||
server.StubProblem(
|
||||
$"/api/v1/vaults/{VaultId}/sync/push",
|
||||
"POST",
|
||||
409,
|
||||
ProblemCodes.VaultConflict,
|
||||
"Stale version.");
|
||||
|
||||
var exception = await Should.ThrowAsync<DodoSshApiException>(async () =>
|
||||
await Client().SyncPushAsync(
|
||||
VaultId, new SyncPushRequest([]), TestContext.Current.CancellationToken));
|
||||
|
||||
exception.Code.ShouldBe(ProblemCodes.VaultConflict);
|
||||
}
|
||||
|
||||
private DodoSshApiClient Client() => new(http, new StubTokenProvider());
|
||||
|
||||
private static MeResponse UnenrolledMe() =>
|
||||
new(
|
||||
UserId: Guid.Parse("0192f0c8-9999-7aaa-8bbb-cccccccccccc"),
|
||||
Issuer: "https://idp.example",
|
||||
Subject: "alice",
|
||||
Email: "alice@example.com",
|
||||
DisplayName: "Alice",
|
||||
EnrollmentRequired: true,
|
||||
KeyGeneration: null,
|
||||
WrappedPrivateKey: null,
|
||||
KdfParameters: null,
|
||||
Vaults: []);
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using DodoSSH.Contracts;
|
||||
using WireMock.RequestBuilders;
|
||||
using WireMock.ResponseBuilders;
|
||||
using WireMock.Server;
|
||||
|
||||
namespace DodoSSH.Client.Api.Tests;
|
||||
|
||||
/// <summary>A stand-in DodoSSH server.</summary>
|
||||
/// <remarks>
|
||||
/// Responses are built from the real contract types and the real source-generated serialiser, so the
|
||||
/// client is reading exactly the shape a live server produces rather than hand-written JSON that
|
||||
/// happens to satisfy it.
|
||||
/// </remarks>
|
||||
internal sealed class StubServer : IDisposable
|
||||
{
|
||||
private readonly WireMockServer server = WireMockServer.Start();
|
||||
|
||||
internal Uri BaseUrl => new(server.Url!, UriKind.Absolute);
|
||||
|
||||
/// <summary>Requests received, so tests can assert on what was sent.</summary>
|
||||
internal IReadOnlyList<WireMock.Logging.ILogEntry> Requests => server.LogEntries.ToList();
|
||||
|
||||
internal void StubMe(MeResponse response) =>
|
||||
StubJson("/api/v1/me", "GET", 200, JsonSerializer.Serialize(
|
||||
response, DodoSshJsonContext.Default.MeResponse));
|
||||
|
||||
internal void StubEnrollment(EnrollmentResponse response) =>
|
||||
StubJson("/api/v1/me/enrollment", "POST", 200, JsonSerializer.Serialize(
|
||||
response, DodoSshJsonContext.Default.EnrollmentResponse));
|
||||
|
||||
internal void StubMeta(MetaResponse response) =>
|
||||
StubJson("/api/v1/meta", "GET", 200, JsonSerializer.Serialize(
|
||||
response, DodoSshJsonContext.Default.MetaResponse));
|
||||
|
||||
internal void StubPush(Guid vaultId, SyncPushResponse response) =>
|
||||
StubJson($"/api/v1/vaults/{vaultId}/sync/push", "POST", 200, JsonSerializer.Serialize(
|
||||
response, DodoSshJsonContext.Default.SyncPushResponse));
|
||||
|
||||
internal void StubPull(Guid vaultId, SyncPullResponse response) =>
|
||||
StubJson($"/api/v1/vaults/{vaultId}/sync/pull", "POST", 200, JsonSerializer.Serialize(
|
||||
response, DodoSshJsonContext.Default.SyncPullResponse));
|
||||
|
||||
/// <summary>Stubs an RFC 9457 problem response.</summary>
|
||||
internal void StubProblem(string path, string method, int statusCode, string code, string detail)
|
||||
{
|
||||
var problem = new JsonObject
|
||||
{
|
||||
["type"] = ProblemCodes.TypeBaseUri + code,
|
||||
["title"] = "Request failed",
|
||||
["status"] = statusCode,
|
||||
["detail"] = detail,
|
||||
["code"] = code,
|
||||
};
|
||||
|
||||
StubJson(path, method, statusCode, problem.ToJsonString());
|
||||
}
|
||||
|
||||
/// <summary>Stubs a non-JSON error, as a reverse proxy in front of a dead server would return.</summary>
|
||||
internal void StubGatewayError(string path, string method) =>
|
||||
server
|
||||
.Given(Request.Create().WithPath(path).UsingMethod(method))
|
||||
.RespondWith(Response.Create()
|
||||
.WithStatusCode(502)
|
||||
.WithHeader("Content-Type", "text/html")
|
||||
.WithBody("<html><body><h1>502 Bad Gateway</h1></body></html>"));
|
||||
|
||||
/// <summary>The body of the last request to a path.</summary>
|
||||
internal string LastBody(string path)
|
||||
{
|
||||
var entries = server.LogEntries
|
||||
.Where(e => e.RequestMessage?.Path?.EndsWith(path, StringComparison.Ordinal) == true)
|
||||
.ToList();
|
||||
|
||||
if (entries.Count == 0)
|
||||
{
|
||||
throw new InvalidOperationException($"Nothing was sent to {path}.");
|
||||
}
|
||||
|
||||
return entries[^1].RequestMessage?.Body ?? string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>The Authorization header of the last request to a path.</summary>
|
||||
internal string? LastAuthorization(string path)
|
||||
{
|
||||
var entries = server.LogEntries
|
||||
.Where(e => e.RequestMessage?.Path?.EndsWith(path, StringComparison.Ordinal) == true)
|
||||
.ToList();
|
||||
|
||||
if (entries.Count == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var headers = entries[^1].RequestMessage?.Headers;
|
||||
|
||||
return headers is not null && headers.TryGetValue("Authorization", out var values)
|
||||
? values.FirstOrDefault()
|
||||
: null;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose()
|
||||
{
|
||||
server.Stop();
|
||||
server.Dispose();
|
||||
}
|
||||
|
||||
private void StubJson(string path, string method, int statusCode, string body) =>
|
||||
server
|
||||
.Given(Request.Create().WithPath(path).UsingMethod(method))
|
||||
.RespondWith(Response.Create()
|
||||
.WithStatusCode(statusCode)
|
||||
.WithHeader("Content-Type", "application/json")
|
||||
.WithBody(body));
|
||||
}
|
||||
|
||||
/// <summary>Hands out a fixed token, so tests can assert it reached the wire.</summary>
|
||||
internal sealed class StubTokenProvider(string token = "test-access-token") : IAccessTokenProvider
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public ValueTask<string> GetAccessTokenAsync(CancellationToken cancellationToken) =>
|
||||
ValueTask.FromResult(token);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,223 @@
|
||||
using NSec.Cryptography;
|
||||
|
||||
namespace DodoSSH.Crypto.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The vault key grant tuple and its signature. See docs/crypto.md §7.3.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Sealing a vault key is anonymous-sender, so without this signature a server could fabricate a grant
|
||||
/// containing a key of its own choosing and the recipient would unwrap it happily. Most of these tests
|
||||
/// are therefore about a signature failing to transfer between contexts it should not.
|
||||
/// </remarks>
|
||||
public sealed class GrantStatementCodecTests
|
||||
{
|
||||
private static readonly Guid VaultA = Guid.Parse("0192f0c8-1111-7c3d-8e4f-5a6b7c8d9e0f");
|
||||
private static readonly Guid VaultB = Guid.Parse("0192f0c8-2222-7c3d-8e4f-5a6b7c8d9e0f");
|
||||
private static readonly Guid Alice = Guid.Parse("0192f0c8-3333-7c3d-8e4f-5a6b7c8d9e0f");
|
||||
private static readonly Guid Bob = Guid.Parse("0192f0c8-4444-7c3d-8e4f-5a6b7c8d9e0f");
|
||||
private static readonly DateTimeOffset GrantedAt = DateTimeOffset.FromUnixTimeMilliseconds(1_750_000_000_123);
|
||||
|
||||
[Fact]
|
||||
public void Encode_IsDeterministic()
|
||||
{
|
||||
Encode().ShouldBe(Encode());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Encode_BeginsWithTheDomainLabel()
|
||||
{
|
||||
var encoding = Encode();
|
||||
|
||||
encoding.AsSpan(0, GrantStatementCodec.Label.Length)
|
||||
.SequenceEqual(GrantStatementCodec.Label)
|
||||
.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("vault")]
|
||||
[InlineData("generation")]
|
||||
[InlineData("kind")]
|
||||
[InlineData("grantee")]
|
||||
[InlineData("granteeFingerprint")]
|
||||
[InlineData("wrappedKey")]
|
||||
[InlineData("granter")]
|
||||
[InlineData("granterFingerprint")]
|
||||
[InlineData("keyLogHead")]
|
||||
[InlineData("grantedAt")]
|
||||
public void ChangingAnyField_ChangesTheEncoding(string field)
|
||||
{
|
||||
var baseline = Encode();
|
||||
|
||||
var altered = field switch
|
||||
{
|
||||
"vault" => Encode(vaultId: VaultB),
|
||||
"generation" => Encode(keyGeneration: 2),
|
||||
"kind" => Encode(kind: GrantPurpose.Recovery),
|
||||
"grantee" => Encode(granteeUserId: Bob),
|
||||
"granteeFingerprint" => Encode(granteeFingerprint: Fingerprint(0xB0)),
|
||||
"wrappedKey" => Encode(wrappedKey: Bytes(80, 0x99)),
|
||||
"granter" => Encode(granterUserId: Bob),
|
||||
"granterFingerprint" => Encode(granterFingerprint: Fingerprint(0xC0)),
|
||||
"keyLogHead" => Encode(keyLogHead: Fingerprint(0xD0)),
|
||||
"grantedAt" => Encode(grantedAt: GrantedAt.AddMilliseconds(1)),
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(field), field, "Unknown field."),
|
||||
};
|
||||
|
||||
altered.ShouldNotBe(baseline);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AbsentAndPresentKeyLogHeads_EncodeDifferently()
|
||||
{
|
||||
// The presence byte, without which a grant carrying no head and one carrying 32 zero bytes
|
||||
// would be indistinguishable.
|
||||
Encode(keyLogHead: default).ShouldNotBe(Encode(keyLogHead: new byte[32]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TheSignatureCoversOnlyTheWrappedKeysDigest()
|
||||
{
|
||||
// So a verifier can check who issued a grant without holding the vault key. The encoding is
|
||||
// 32 bytes of digest regardless of how large the wrapped key is.
|
||||
var small = Encode(wrappedKey: Bytes(48, 0x11));
|
||||
var large = Encode(wrappedKey: Bytes(4096, 0x11));
|
||||
|
||||
small.Length.ShouldBe(large.Length);
|
||||
small.ShouldNotBe(large);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AFreshSignature_Verifies()
|
||||
{
|
||||
using var key = CreateSigningKey();
|
||||
var grant = Encode();
|
||||
|
||||
var signature = GrantStatementCodec.Sign(key, grant);
|
||||
|
||||
signature.Length.ShouldBe(CryptoSpec.SignatureSize);
|
||||
GrantStatementCodec.Verify(PublicKeyBytes(key), grant, signature).ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ASignatureOverAnotherGrant_DoesNotVerify()
|
||||
{
|
||||
// The property that matters: a grant for one vault cannot be replayed onto another.
|
||||
using var key = CreateSigningKey();
|
||||
|
||||
var signature = GrantStatementCodec.Sign(key, Encode(vaultId: VaultA));
|
||||
|
||||
GrantStatementCodec.Verify(PublicKeyBytes(key), Encode(vaultId: VaultB), signature)
|
||||
.ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ASignatureFromAnotherGranter_DoesNotVerify()
|
||||
{
|
||||
using var key = CreateSigningKey();
|
||||
using var other = CreateSigningKey();
|
||||
var grant = Encode();
|
||||
|
||||
var signature = GrantStatementCodec.Sign(other, grant);
|
||||
|
||||
GrantStatementCodec.Verify(PublicKeyBytes(key), grant, signature).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AKeyStatementSignature_DoesNotVerifyAsAGrant()
|
||||
{
|
||||
// Context separation. Without it a signature produced in one role could be presented in
|
||||
// another, which is the whole reason each context string exists.
|
||||
using var key = CreateSigningKey();
|
||||
var grant = Encode();
|
||||
|
||||
var wrongContext = DshSignatures.SignKeyStatement(key, grant);
|
||||
|
||||
GrantStatementCodec.Verify(PublicKeyBytes(key), grant, wrongContext).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0)]
|
||||
[InlineData(31)]
|
||||
[InlineData(33)]
|
||||
public void AMalformedPublicKey_ReturnsFalseRatherThanThrowing(int length)
|
||||
{
|
||||
using var key = CreateSigningKey();
|
||||
var grant = Encode();
|
||||
var signature = GrantStatementCodec.Sign(key, grant);
|
||||
|
||||
GrantStatementCodec.Verify(new byte[length], grant, signature).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Encode_RejectsAnUnspecifiedKind()
|
||||
{
|
||||
Should.Throw<ArgumentOutOfRangeException>(() => Encode(kind: GrantPurpose.Unspecified));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Encode_RejectsAnEmptyWrappedKey()
|
||||
{
|
||||
Should.Throw<ArgumentException>(() => Encode(wrappedKey: []));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Encode_RejectsAWrongLengthFingerprint()
|
||||
{
|
||||
Should.Throw<ArgumentException>(() => Encode(granteeFingerprint: new byte[16]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Encode_RejectsAWrongLengthKeyLogHead()
|
||||
{
|
||||
Should.Throw<ArgumentException>(() => Encode(keyLogHead: new byte[16]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ThePurposeValues_MatchTheDomainEnum()
|
||||
{
|
||||
// Covered by the signature, so a renumbering would make every grant of the changed kind fail
|
||||
// verification. Domain cannot be referenced from here, so the values are asserted literally
|
||||
// against docs/crypto.md §7.3.
|
||||
((byte)GrantPurpose.Member).ShouldBe((byte)1);
|
||||
((byte)GrantPurpose.Recovery).ShouldBe((byte)2);
|
||||
((byte)GrantPurpose.Escrow).ShouldBe((byte)3);
|
||||
}
|
||||
|
||||
// ---- Helpers ----
|
||||
|
||||
private static byte[] Encode(
|
||||
Guid? vaultId = null,
|
||||
uint keyGeneration = 1,
|
||||
GrantPurpose kind = GrantPurpose.Member,
|
||||
Guid? granteeUserId = null,
|
||||
byte[]? granteeFingerprint = null,
|
||||
byte[]? wrappedKey = null,
|
||||
Guid? granterUserId = null,
|
||||
byte[]? granterFingerprint = null,
|
||||
byte[]? keyLogHead = null,
|
||||
DateTimeOffset? grantedAt = null) =>
|
||||
GrantStatementCodec.Encode(
|
||||
vaultId ?? VaultA,
|
||||
keyGeneration,
|
||||
kind,
|
||||
granteeUserId ?? Alice,
|
||||
granteeFingerprint ?? Fingerprint(0x40),
|
||||
wrappedKey ?? Bytes(80, 0x77),
|
||||
granterUserId ?? Alice,
|
||||
granterFingerprint ?? Fingerprint(0x60),
|
||||
keyLogHead ?? [],
|
||||
grantedAt ?? GrantedAt);
|
||||
|
||||
private static byte[] Fingerprint(byte seed) => Bytes(CryptoSpec.DigestSize, seed);
|
||||
|
||||
private static byte[] Bytes(int length, byte seed) =>
|
||||
[.. Enumerable.Range(0, length).Select(i => (byte)(seed + i))];
|
||||
|
||||
private static Key CreateSigningKey() =>
|
||||
Key.Create(
|
||||
SignatureAlgorithm.Ed25519,
|
||||
new KeyCreationParameters { ExportPolicy = KeyExportPolicies.AllowPlaintextExport });
|
||||
|
||||
private static byte[] PublicKeyBytes(Key key) => key.PublicKey.Export(KeyBlobFormat.RawPublicKey);
|
||||
}
|
||||
Reference in New Issue
Block a user