Files
DodoSSH/tests/DodoSSH.Client.Session.Tests/FakeAccountServer.cs
T
jaap-jan f86791e817 Finish revoking a device, instead of half of it
ForgetDeviceAsync stopped this machine unlocking without a passphrase and left
the server's row exactly where it was, so the account went on listing a device
nobody could account for. ADR 0007 recorded that as a deliberate gap needing an
endpoint. This is the endpoint, and the two things that turned up behind it.

DELETE /api/v1/me/devices/{id}. The device row is not the dangerous half: a
kind=device wrap is the user's identity bundle sealed to a key somebody may be
holding, and that is what has to go. It goes on the foreign key's cascade rather
than a second statement, and RevokeDevice_TakesItsWrapWithIt asserts the cascade
rather than trusting the configuration to keep saying so.

Scoped to the caller's own account, which is the only authorisation check there
is. The id is an unguessable v7 GUID, but unguessable is not a permission —
without the scope one user could withdraw another's device key by pasting an id
they saw once, and the victim's next launch would ask for a passphrase with no
explanation. 404 rather than 403 for somebody else's device, so a stranger does
not learn the id exists.

Never refused for being the last device. ADR 0001 makes an enrolled device a
recovery path, so removing the last one does cost the user something — but the
machine being revoked is most likely the one they have just lost, and a server
that argued about it would be refusing the one request that has to work
immediately. The passphrase wrap is untouched either way, which
RevokeDevice_LeavesThePassphraseWrapAlone pins.

--- Two things found on the way ---

Registering twice from one machine left two devices on the account. The server
is idempotent on the public key, but the client generates a fresh key pair every
call and the keystore holds one — so the second registration orphaned a wrap
whose private half had just been overwritten, which is precisely the leftover
this change exists to remove. Registering now withdraws the previous device.
Found by a test that asserted the property and failed.

And the fakes were lying about it. FakeAccountServer's comment claimed the real
service's idempotence while handing back a fresh Guid on every call, which is
invisible until something revokes by id — at which point a test would be
revoking an id the server never issued, and passing. Both fakes now issue one id
per public key and drop the wrap with the device, as the cascade does.

--- Reachable at all ---

ForgetDeviceAsync had exactly one caller and it was a test, so "Stop unlocking
here" now sits in the account bar where "Use Windows Hello here" was. Its own
flag rather than the negation of that one: a machine with no TPM and a machine
that is already registered are both "cannot register", and only the second has
anything to take back.

No confirmation prompt, deliberately. The cost of pressing it by accident is one
passphrase and one re-registration; the cost of a dialog is a moment's
hesitation at the point somebody has realised a machine is in the wrong hands.

Offline it does the local half and says so rather than refusing. Whether this
machine may unlock itself is decided entirely by the local cache and the local
keystore — the unlock path never asks the server — so forgetting here is what
actually revokes, and "you are offline, so this machine will go on unlocking
itself" would be the worst available answer. DeviceRevocation.LocalOnly is what
the interface reports and the status line explains what is left to do.

The local half runs first for the same reason, and the keystore call is the
first thing in the method that can yield: on Windows it raises a consent dialog,
and a dialog wants the thread it was called from. That ordering is currently
load-bearing and shakier than it looks — see the open device-unlock hang.

Four mutations, all caught: dropping the user scope from the server query
(1 test), skipping the stale-device revoke on re-registration (2), skipping the
server call in ForgetDeviceAsync (2), and the earlier version of the client that
never called it at all.

930 tests green across 16 projects, 13 of them new. Zero warnings, format clean.
2026-07-30 17:33:31 +02:00

237 lines
8.8 KiB
C#

using DodoSSH.Client.Api;
using DodoSSH.Client.Auth;
using DodoSSH.Contracts;
namespace DodoSSH.Client.Session.Tests;
/// <summary>
/// An in-memory account server: just-in-time provisioning, enrollment, and <c>/me</c>.
/// </summary>
/// <remarks>
/// Stores what a real server stores and reports it back the same way, because that round trip is the
/// thing under test — the provisioner deliberately re-reads <c>/me</c> after enrolling rather than
/// caching what it believes it sent, and a stub that echoed the request would make that check vacuous.
/// <para>
/// It does not verify the identity-provider token or the grant signature. Those are the server's job and
/// are covered against a real JWT pipeline in <c>DodoSSH.Api.Tests</c>; repeating them here would test
/// this file rather than the client.
/// </para>
/// </remarks>
internal sealed class FakeAccountServer : IAccountApi
{
private KeyStatement? statement;
private byte[]? wrappedPrivateKey;
private KdfParameters? kdfParameters;
private VaultSummary? personalVault;
internal Guid UserId { get; } = Guid.Parse("0192f0c8-9999-7aaa-8bbb-cccccccccccc");
internal static string Issuer => "https://idp.example/realms/dodossh";
internal static string Subject => "alice";
/// <summary>The enrollment request as received, so a test can assert what was actually sent.</summary>
internal EnrollmentRequest? LastEnrollment { get; private set; }
internal int EnrollmentCount { get; private set; }
internal int MeCount { get; private set; }
/// <summary>Whether an identity key has been published.</summary>
internal bool IsEnrolled => statement is not null;
/// <summary>
/// Device wraps registered after enrollment, keyed on the device public key.
/// </summary>
/// <remarks>
/// Kept so a test can assert that the wrap the server received is the one the client claimed to send.
/// The server cannot open it and neither does this, which is the point: possession is proved by
/// producing it, not by anything either side checks.
/// </remarks>
internal Dictionary<string, byte[]> RegisteredDevices { get; } = new(StringComparer.Ordinal);
/// <summary>The id issued for each registered public key, so revocation has something to name.</summary>
private readonly Dictionary<string, Guid> deviceIds = new(StringComparer.Ordinal);
/// <inheritdoc />
public Task<MeResponse> GetMeAsync(CancellationToken cancellationToken)
{
MeCount++;
return Task.FromResult(new MeResponse(
UserId,
Issuer,
Subject,
"alice@example.com",
"Alice",
EnrollmentRequired: !IsEnrolled,
KeyGeneration: statement?.KeyGeneration,
WrappedPrivateKey: wrappedPrivateKey,
KdfParameters: kdfParameters,
Vaults: personalVault is null ? [] : [personalVault]));
}
/// <inheritdoc />
public Task<EnrollmentResponse> EnrollAsync(
EnrollmentRequest request,
CancellationToken cancellationToken)
{
EnrollmentCount++;
LastEnrollment = request;
if (IsEnrolled)
{
// The real server answers 409 with ProblemCodes.AlreadyEnrolled. Reproduced because the
// provisioner is supposed to never get here — it reads /me first — and a test that changed
// that should fail loudly rather than quietly enroll twice.
throw new DodoSshApiException(
System.Net.HttpStatusCode.Conflict,
ProblemCodes.AlreadyEnrolled,
"This account already has an identity key.");
}
statement = request.Statement;
wrappedPrivateKey = request.WrappedPrivateKey;
kdfParameters = request.KdfParameters;
personalVault = new VaultSummary(
request.PersonalVault.VaultId,
request.PersonalVault.Name,
IsPersonal: true,
TeamId: null,
KeyGeneration: 1,
Permissions: 31,
request.PersonalVault.WrappedVaultKey,
RekeyRequired: false);
return Task.FromResult(new EnrollmentResponse(
UserId,
KeyGeneration: 1,
Fingerprint: new byte[32],
request.PersonalVault.VaultId,
DeviceId: request.DevicePublicKey is null ? null : Guid.CreateVersion7(),
KeyLogSequence: 1));
}
/// <inheritdoc />
/// <remarks>
/// Refuses before enrollment, as the real endpoint does through <c>Auth.EnrolledPolicy</c>: there is no
/// bundle to have wrapped yet, so a wrap arriving here would be a wrap of something else. Idempotent on
/// the public key, again matching the real one.
/// </remarks>
public Task<RegisterDeviceResponse> RegisterDeviceAsync(
RegisterDeviceRequest request,
CancellationToken cancellationToken)
{
if (!IsEnrolled)
{
throw new DodoSshApiException(
System.Net.HttpStatusCode.Forbidden,
ProblemCodes.EnrollmentRequired,
"This account has no identity key yet.");
}
var key = Convert.ToHexString(request.PublicKey);
RegisteredDevices[key] = request.WrappedPrivateKey;
// The same id for the same public key, which the real service does and this fake used to claim in a
// comment while handing back a fresh Guid every call. That difference is invisible until something
// revokes by id, at which point a test would be revoking an id the server never issued.
if (!deviceIds.TryGetValue(key, out var deviceId))
{
deviceId = Guid.CreateVersion7();
deviceIds[key] = deviceId;
}
return Task.FromResult(new RegisterDeviceResponse(deviceId, DateTimeOffset.UnixEpoch));
}
/// <inheritdoc />
public Task<bool> RevokeDeviceAsync(Guid deviceId, CancellationToken cancellationToken)
{
var key = deviceIds.FirstOrDefault(entry => entry.Value == deviceId).Key;
if (key is null)
{
return Task.FromResult(false);
}
deviceIds.Remove(key);
// The wrap goes with it, as the foreign key's cascade does on the real server. A fake that kept the
// wrap would let a test claiming to prove revocation pass while the dangerous half survived.
RegisteredDevices.Remove(key);
return Task.FromResult(true);
}
/// <summary>Drops the vault grant, as a rekey does until it is re-issued.</summary>
internal void RevokeVaultGrant() =>
personalVault = personalVault is null
? null
: personalVault with { WrappedVaultKey = null, RekeyRequired = true };
}
/// <summary>
/// Stands in for the identity provider's signature over a key statement.
/// </summary>
/// <remarks>
/// Records the nonce it was asked for. That the nonce is the statement's hash is what makes the binding
/// meaningful, and it is asserted in <c>ClientEnrollmentTests</c>; here it only needs to exist.
/// </remarks>
internal sealed class StubKeyBinding : IKeyBindingAuthorizer
{
internal string? RequestedNonce { get; private set; }
public Task<string> AuthorizeKeyBindingAsync(
string bindingNonce,
CancellationToken cancellationToken)
{
RequestedNonce = bindingNonce;
return Task.FromResult("stub-id-token");
}
}
/// <summary>
/// A server with no changes in it.
/// </summary>
/// <remarks>
/// Enough to prove the session composes a working sync engine. The interesting sync behaviour lives in
/// <c>DodoSSH.Client.Sync.Tests</c> against a server that enforces version checks; duplicating that here
/// would be a third implementation of the same decision table.
/// </remarks>
internal sealed class EmptySyncApi : ISyncApi
{
internal int PushCount { get; private set; }
public Task<SyncPullResponse> SyncPullAsync(
Guid vaultId,
SyncPullRequest request,
CancellationToken cancellationToken) =>
Task.FromResult(new SyncPullResponse(
[],
request.Cursor ?? "empty-v1:0",
HasMore: false,
ServerTime: DateTimeOffset.FromUnixTimeSeconds(1_750_000_000),
CurrentKeyGeneration: 1));
public Task<SyncPushResponse> SyncPushAsync(
Guid vaultId,
SyncPushRequest request,
CancellationToken cancellationToken)
{
PushCount++;
return Task.FromResult(new SyncPushResponse(
[.. request.Operations.Select((operation, index) => new SyncPushResult(
operation.OperationId,
SyncOperationStatus.Applied,
Version: (operation.ExpectedVersion ?? 0) + 1,
ChangeSequence: index + 1,
ServerEntity: null,
Detail: null))],
"empty-v1:0"));
}
}