Let an already-enrolled account register a device key

The first of the three pieces ADR 0007 needs, and the one that was a discovery
rather than a plan. EnrollmentService.AddDevice runs only during enrollment, so
without an endpoint the device-unlock feature would have reached accounts created
after it shipped and no others — which is to say none of the ones that exist. The
code even said so: "the devices endpoint sets it properly when it lands."

POST /api/v1/me/devices takes a name, an X25519 public key and the bundle sealed
to it, and writes a device row plus a UserKeyWrapKind.Device wrap.

Possession is proved by construction, so there is no challenge. The wrap is the
secret bundle sealed to the supplied public key, and only something that has
opened that bundle can produce it. A caller who seals the wrong bytes registers a
device that cannot unlock, which harms nobody else; the server cannot tell the
difference and must not pretend to, because it holds no key that opens either.
That is also why the client must be unlocked to call this at all.

It is the one endpoint in the /me group that requires enrollment, and it says so
itself rather than relying on the group. The group deliberately does not: GET /
and POST /enrollment are how a client discovers it needs to enroll and then does
so, and gating those on enrollment would make enrollment unreachable. Adding the
stricter policy to this route alone means an unenrolled caller is told
"enrollment-required" by the authorization handler rather than getting a 400 about
the shape of a request that was fine.

Idempotent on the public key, and 200 rather than 201 for the reason enrollment
gives: a retry of an identical request returns the same body, so there is no
single moment of creation to point a Location header at. A second row for one key
would mean a device list with a duplicate in it and two wraps to revoke instead
of one. Mutation tested — removing the lookup fails
RegisterDevice_TwiceWithTheSameKey_ReturnsTheSameDeviceAndAddsNoSecondWrap and
nothing else.

That test also found a real defect, in the way these usually surface: two
timestamps that print identically and are not equal. TimeProvider reports
100-nanosecond ticks and PostgreSQL's timestamp with time zone keeps microseconds,
so the first call returned a value that no later read of the row would ever
produce, and the idempotent retry answered with a different timestamp for the same
device. Nothing breaks, which is what makes it worth fixing: the service now
truncates to the precision the column actually holds, so the response is the same
value every time it is asked for. The repo already had a precedent for this class
of thing in KeyLogChain.TruncateTimestamp; it just had not been applied here.

The platform is deliberately not carried on the wire, which leaves
Device.Platform unreported and the stale comment corrected rather than fulfilled.
It would be a display-only field, and a Contracts enum mirroring the domain's
DevicePlatform is exactly the shape of duplication that has produced three
self-consistent bugs in this repository. A device list that wants it can add a
mapping table and a test pinning the two together, which is what the sync entity
types already do.

Its own problem code and exception rather than reusing enrollment's, whose rules
it largely shares. Registering a device is not enrolling, and a client showing
"your enrollment was rejected" because somebody set up a fingerprint reader would
be describing the wrong thing. The validation shares the limit constants —
MaximumWrapBytes, MaximumDeviceNameLength, PublicKeySize — and not the four-line
guards, which would have had to be parameterised over which exception to throw for
less than they cost.

Both in-memory fakes implement it properly rather than throwing: they record the
wrap so a test can assert it arrived, and refuse before enrollment as the real
endpoint's policy does. A fake that answered where the server refuses is a fake
that can make a real bug pass.

866 tests green, 8 of them new. Zero warnings, dotnet format clean.

Still to come: the protector seam with the wrap cached locally so device unlock
works offline, then the Windows Hello implementation and the unlock-screen UI —
which is where the Windows target framework lands and where automated testing
stops.
This commit is contained in:
2026-07-30 13:18:09 +02:00
parent 7016ce36f1
commit db4a8ed3d3
12 changed files with 558 additions and 19 deletions
@@ -22,6 +22,7 @@ public sealed class IdentityEndpointTests(ApiFixture fixture)
{
private const string MeUrl = "/api/v1/me";
private const string EnrollUrl = "/api/v1/me/enrollment";
private const string DevicesUrl = "/api/v1/me/devices";
// ---- Provisioning and /me ----
@@ -839,6 +840,150 @@ public sealed class IdentityEndpointTests(ApiFixture fixture)
response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
}
// ---- Registering a device after enrollment ----
[Fact]
public async Task RegisterDevice_AddsADeviceAndAWrapThatOnlyThatDeviceCanOpen()
{
// The gap this endpoint closes. EnrollmentService.AddDevice only ever runs during enrollment, so
// without this every account that existed before a keystore was wired up could never turn the
// feature on — which is all of them.
using var enrollment = NewEnrollment();
var client = enrollment.CreateClient(fixture);
var enrolled = await EnrollAsync(client, enrollment.Build());
var publicKey = DeviceKey();
var registered = await RegisterDeviceAsync(
client,
new RegisterDeviceRequest("a second laptop", publicKey, Wrap()));
registered.DeviceId.ShouldNotBe(Guid.Empty);
await using var scope = fixture.CreateScope();
var database = scope.ServiceProvider.GetRequiredService<DodoDbContext>();
var device = await database.Devices.SingleAsync(d => d.Id == registered.DeviceId);
device.UserId.ShouldBe(enrolled.UserId);
device.Name.ShouldBe("a second laptop");
device.PublicKey.ShouldBe(publicKey);
var wrap = await database.UserKeyWraps.SingleAsync(w => w.DeviceId == registered.DeviceId);
wrap.Kind.ShouldBe(UserKeyWrapKind.Device);
wrap.UserId.ShouldBe(enrolled.UserId);
}
[Fact]
public async Task RegisterDevice_BeforeEnrolling_AsksForEnrollmentRatherThanRejectingTheShape()
{
// You cannot wrap a bundle to a device before you have a bundle. The distinction that matters is
// which answer the client gets: "enroll first" is actionable, and a 400 about the request's shape
// would send somebody looking at their key length.
var subject = NewSubject();
var client = fixture.CreateClientFor(subject, $"{subject}@example.com");
var response = await client.PostContractAsync(
DevicesUrl,
new RegisterDeviceRequest("a laptop", DeviceKey(), Wrap()));
await ShouldBeProblemAsync(
response,
HttpStatusCode.Forbidden,
ProblemCodes.EnrollmentRequired);
}
[Fact]
public async Task RegisterDevice_TwiceWithTheSameKey_ReturnsTheSameDeviceAndAddsNoSecondWrap()
{
// Idempotent, as enrollment is. A dropped response must leave a retry safe, and a second row for
// one key would mean a device list with a duplicate and two wraps to revoke instead of one.
using var enrollment = NewEnrollment();
var client = enrollment.CreateClient(fixture);
await EnrollAsync(client, enrollment.Build());
var publicKey = DeviceKey();
var request = new RegisterDeviceRequest("a laptop", publicKey, Wrap());
var first = await RegisterDeviceAsync(client, request);
var second = await RegisterDeviceAsync(client, request);
second.DeviceId.ShouldBe(first.DeviceId);
second.EnrolledAt.ShouldBe(first.EnrolledAt);
await using var scope = fixture.CreateScope();
var database = scope.ServiceProvider.GetRequiredService<DodoDbContext>();
(await database.Devices.CountAsync(d => d.PublicKey == publicKey)).ShouldBe(1);
(await database.UserKeyWraps.CountAsync(w => w.DeviceId == first.DeviceId)).ShouldBe(1);
}
[Theory]
[InlineData(31)]
[InlineData(33)]
public async Task RegisterDevice_WithAPublicKeyOfTheWrongLength_IsRejected(int length)
{
// The same rule enrollment applies. A key that is not an X25519 public key is one nothing can ever
// seal to, so the row would be permanently useless.
using var enrollment = NewEnrollment();
var client = enrollment.CreateClient(fixture);
await EnrollAsync(client, enrollment.Build());
var response = await client.PostContractAsync(
DevicesUrl,
new RegisterDeviceRequest("a laptop", new byte[length], Wrap()));
await ShouldBeProblemAsync(
response,
HttpStatusCode.BadRequest,
ProblemCodes.InvalidDeviceRegistration);
}
[Fact]
public async Task RegisterDevice_WithNoWrap_IsRejected()
{
// A device key with no wrap registers a device that can never unlock anything, and the server
// cannot fill the gap in — only the holder of the bundle can seal it.
using var enrollment = NewEnrollment();
var client = enrollment.CreateClient(fixture);
await EnrollAsync(client, enrollment.Build());
var response = await client.PostContractAsync(
DevicesUrl,
new RegisterDeviceRequest("a laptop", DeviceKey(), []));
await ShouldBeProblemAsync(
response,
HttpStatusCode.BadRequest,
ProblemCodes.InvalidDeviceRegistration);
}
[Fact]
public async Task RegisterDevice_WithABlankName_IsRejected()
{
using var enrollment = NewEnrollment();
var client = enrollment.CreateClient(fixture);
await EnrollAsync(client, enrollment.Build());
var response = await client.PostContractAsync(
DevicesUrl,
new RegisterDeviceRequest(" ", DeviceKey(), Wrap()));
await ShouldBeProblemAsync(
response,
HttpStatusCode.BadRequest,
ProblemCodes.InvalidDeviceRegistration);
}
[Fact]
public async Task RegisterDevice_WithoutAToken_Is401()
{
var response = await fixture.CreateClient().PostContractAsync(
DevicesUrl,
new RegisterDeviceRequest("a laptop", DeviceKey(), Wrap()));
response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
}
// ---- Helpers ----
private static string NewSubject() => $"user-{Guid.CreateVersion7():N}";
@@ -871,6 +1016,31 @@ public sealed class IdentityEndpointTests(ApiFixture fixture)
return body;
}
private static async Task<RegisterDeviceResponse> RegisterDeviceAsync(
HttpClient client,
RegisterDeviceRequest request)
{
var response = await client.PostContractAsync(DevicesUrl, request);
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadContractAsync<RegisterDeviceResponse>();
body.ShouldNotBeNull();
return body;
}
/// <remarks>
/// A distinct 32 bytes per call, because the endpoint is idempotent on the public key and two tests
/// sharing one would silently be asserting about each other's device.
/// </remarks>
private static byte[] DeviceKey() => Guid.CreateVersion7().ToByteArray().Concat(
Guid.CreateVersion7().ToByteArray()).ToArray();
/// <remarks>
/// Not a real envelope. The server treats a wrap as opaque bytes and validates only that it is present
/// and bounded, which is the whole of what it is allowed to know.
/// </remarks>
private static byte[] Wrap() => [1, 2, 3, 4];
private static Task ShouldBeBindingRejectedAsync(HttpResponseMessage response) =>
ShouldBeProblemAsync(
response,
@@ -43,6 +43,9 @@ internal sealed class FakeVaultServer : IVaultServer, IAccountApi, ISyncApi, IKe
internal int LiveRowCount => rows.Values.Count(row => row.Operation != SyncOperation.Delete);
/// <summary>Device wraps registered after enrollment, keyed on the device public key.</summary>
internal Dictionary<string, byte[]> RegisteredDevices { get; } = new(StringComparer.Ordinal);
/// <summary>When set, the next sign-in throws — how an unreachable server is exercised.</summary>
internal Exception? SignInFailure { get; set; }
@@ -130,6 +133,30 @@ internal sealed class FakeVaultServer : IVaultServer, IAccountApi, ISyncApi, IKe
KeyLogSequence: 1));
}
/// <inheritdoc />
/// <remarks>
/// Records the wrap so a test can assert it reached the server, and refuses before enrollment as the
/// real endpoint's <c>Auth.EnrolledPolicy</c> does.
/// </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.");
}
RegisteredDevices[Convert.ToHexString(request.PublicKey)] = request.WrappedPrivateKey;
return Task.FromResult(new RegisterDeviceResponse(
DeviceId: Guid.CreateVersion7(),
EnrolledAt: DateTimeOffset.UnixEpoch));
}
// ---- Sync ----
/// <inheritdoc />
@@ -40,6 +40,16 @@ internal sealed class FakeAccountServer : IAccountApi
/// <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);
/// <inheritdoc />
public Task<MeResponse> GetMeAsync(CancellationToken cancellationToken)
{
@@ -100,6 +110,36 @@ internal sealed class FakeAccountServer : IAccountApi
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);
if (!RegisteredDevices.TryAdd(key, request.WrappedPrivateKey))
{
RegisteredDevices[key] = request.WrappedPrivateKey;
}
return Task.FromResult(new RegisterDeviceResponse(
DeviceId: Guid.CreateVersion7(),
EnrolledAt: DateTimeOffset.UnixEpoch));
}
/// <summary>Drops the vault grant, as a rekey does until it is re-issued.</summary>
internal void RevokeVaultGrant() =>
personalVault = personalVault is null