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
@@ -0,0 +1,137 @@
using DodoSSH.Contracts;
using DodoSSH.Crypto;
using DodoSSH.Domain;
using DodoSSH.Infrastructure;
using Microsoft.EntityFrameworkCore;
namespace DodoSSH.Api.Features.Identity;
/// <summary>
/// Registers a device key against an account that is already enrolled.
/// </summary>
/// <remarks>
/// <para>
/// The counterpart to <see cref="EnrollmentService"/>'s device handling, which only ever runs during
/// enrollment. Every account that existed before a keystore was wired up needs this, which is all of
/// them.
/// </para>
/// <para>
/// There is nothing to verify beyond shape. The wrap is the bundle sealed to the supplied public key, and
/// only somebody who has opened that bundle can produce it — so possession is proved by construction and
/// no challenge is needed. A caller who seals the wrong bytes registers a device that cannot unlock,
/// which is their own problem and nobody else's. The server cannot tell the difference and must not
/// pretend to: it holds no key that opens either.
/// </para>
/// </remarks>
internal sealed class DeviceService(DodoDbContext database, TimeProvider clock)
{
/// <summary>Registers a device, or returns the one already registered for this public key.</summary>
/// <exception cref="DeviceRegistrationInvalidException">The request is malformed.</exception>
internal async Task<RegisterDeviceResponse> RegisterAsync(
UserAccount user,
RegisterDeviceRequest request,
CancellationToken cancellationToken)
{
Validate(request);
var existing = await database.Devices
.Where(device => device.UserId == user.Id && device.PublicKey == request.PublicKey)
.Select(device => new { device.Id, device.EnrolledAtUtc })
.FirstOrDefaultAsync(cancellationToken)
.ConfigureAwait(false);
if (existing is not null)
{
// Idempotent, as enrollment is. A dropped response must not leave the caller unable to retry,
// and a second row for the same key would be a device list with a duplicate in it and two
// wraps to revoke instead of one.
return new RegisterDeviceResponse(existing.Id, existing.EnrolledAtUtc);
}
var now = ToStorablePrecision(clock.GetUtcNow());
var registered = new Device
{
Id = Guid.CreateVersion7(),
UserId = user.Id,
Name = request.Name,
// Unreported, deliberately: the contract does not carry a platform. See RegisterDeviceRequest
// for why a wire enum mirroring this one was not worth the hazard.
Platform = DevicePlatform.Unspecified,
PublicKey = request.PublicKey,
EnrolledAtUtc = now,
LastSeenAtUtc = now,
};
database.Devices.Add(registered);
database.UserKeyWraps.Add(new UserKeyWrap
{
Id = Guid.CreateVersion7(),
UserId = user.Id,
Kind = UserKeyWrapKind.Device,
DeviceId = registered.Id,
Wrap = request.WrappedPrivateKey,
WrapVersion = 1,
CreatedAtUtc = now,
});
await database.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
return new RegisterDeviceResponse(registered.Id, now);
}
/// <summary>Rounds a timestamp down to what the database can actually hold.</summary>
/// <remarks>
/// <see cref="TimeProvider"/> reports 100-nanosecond ticks and PostgreSQL's <c>timestamp with time
/// zone</c> keeps microseconds, so storing the raw value means the row holds something slightly
/// different from what was returned. Nothing breaks, and that is the problem: the first call would
/// report a timestamp that no later read of the same row ever produces, and the idempotent retry would
/// answer with a different one for the same device. Truncating here makes the response the same value
/// every time it is asked for.
/// </remarks>
private static DateTimeOffset ToStorablePrecision(DateTimeOffset value) =>
new(value.Ticks - (value.Ticks % TimeSpan.TicksPerMicrosecond), value.Offset);
/// <remarks>
/// The same rules <see cref="EnrollmentValidation"/> applies to a device supplied at enrollment, and
/// the limits are the shared constants rather than repeated numbers. The four-line guards are not
/// shared: they would have to be parameterised over which exception to throw, which is more
/// indirection than four lines of <c>if</c> is worth.
/// </remarks>
private static void Validate(RegisterDeviceRequest request)
{
if (request is null)
{
throw new DeviceRegistrationInvalidException("A device registration is required.");
}
if (string.IsNullOrWhiteSpace(request.Name))
{
throw new DeviceRegistrationInvalidException("The device name is required.");
}
if (request.Name.Length > EnrollmentLimits.MaximumDeviceNameLength)
{
throw new DeviceRegistrationInvalidException(
$"The device name exceeds {EnrollmentLimits.MaximumDeviceNameLength} characters.");
}
if (request.PublicKey is null || request.PublicKey.Length != CryptoSpec.PublicKeySize)
{
throw new DeviceRegistrationInvalidException(
$"The device public key must be exactly {CryptoSpec.PublicKeySize} bytes.");
}
if (request.WrappedPrivateKey is null or { Length: 0 })
{
throw new DeviceRegistrationInvalidException("The device wrap is required.");
}
if (request.WrappedPrivateKey.Length > EnrollmentLimits.MaximumWrapBytes)
{
throw new DeviceRegistrationInvalidException(
$"The device wrap exceeds {EnrollmentLimits.MaximumWrapBytes} bytes.");
}
}
}
@@ -12,6 +12,16 @@ internal sealed class EnrollmentInvalidException(string message) : Exception(mes
/// <summary>The identity-provider token did not bind the supplied keys.</summary>
internal sealed class IdentityBindingInvalidException(string message) : Exception(message);
/// <summary>
/// The device registration request was structurally unacceptable.
/// </summary>
/// <remarks>
/// Its own type rather than <see cref="EnrollmentInvalidException"/>, whose rules it largely shares.
/// Registering a device is not enrolling, and the problem code a client switches on should not claim it
/// was. As with enrollment, the message reaches the caller: keep it about the shape of their request.
/// </remarks>
internal sealed class DeviceRegistrationInvalidException(string message) : Exception(message);
/// <summary>
/// The caller already holds a current identity key that is not the one being enrolled.
/// </summary>
@@ -9,9 +9,10 @@ namespace DodoSSH.Api.Features.Identity;
/// The caller's own identity: profile, unlock state and enrollment.
/// </summary>
/// <remarks>
/// Both endpoints run under <see cref="Auth.AuthenticatedPolicy"/> rather than
/// <see cref="Auth.EnrolledPolicy"/>, and must. They are how a client discovers that it needs to
/// enroll and then does so; gating them on enrollment would make enrollment unreachable.
/// The group runs under <see cref="Auth.AuthenticatedPolicy"/> rather than
/// <see cref="Auth.EnrolledPolicy"/>, and must: <c>GET /</c> and <c>POST /enrollment</c> are how a client
/// discovers that it needs to enroll and then does so, so gating them on enrollment would make enrollment
/// unreachable. <c>POST /devices</c> is the exception and adds the stricter policy itself.
/// </remarks>
internal static class IdentityEndpoints
{
@@ -29,6 +30,15 @@ internal static class IdentityEndpoints
.WithName("Enroll")
.WithSummary("Publishes the caller's first identity key and creates their personal vault.");
// The one endpoint in this group that does require enrollment, and it says so itself rather than
// relying on the group. You cannot wrap a bundle to a device before you have a bundle, and the
// authorization handler turns the unmet requirement into "enrollment-required" — a better answer
// than a 400 from validation about state the caller could not have known.
group.MapPost("/devices", RegisterDeviceAsync)
.RequireAuthorization(Auth.EnrolledPolicy)
.WithName("RegisterDevice")
.WithSummary("Registers a device key so this machine can unlock without the passphrase.");
return app;
}
@@ -87,6 +97,34 @@ internal static class IdentityEndpoints
}
}
/// <remarks>
/// 200 rather than 201, for the reason enrollment gives: re-registering the same public key returns the
/// existing device, so there is no single moment of creation to point a Location header at.
/// </remarks>
private static async Task<Results<Ok<RegisterDeviceResponse>, ProblemHttpResult>> RegisterDeviceAsync(
RegisterDeviceRequest request,
ICurrentUserContext currentUser,
DeviceService devices,
CancellationToken cancellationToken)
{
var user = await currentUser.GetOrProvisionAsync(cancellationToken).ConfigureAwait(false);
try
{
var response = await devices.RegisterAsync(user, request, cancellationToken)
.ConfigureAwait(false);
return TypedResults.Ok(response);
}
catch (DeviceRegistrationInvalidException exception)
{
return Problem(
StatusCodes.Status400BadRequest,
ProblemCodes.InvalidDeviceRegistration,
exception.Message);
}
}
private static ProblemHttpResult Problem(int statusCode, string code, string detail) =>
TypedResults.Problem(
detail: detail,
+1
View File
@@ -28,6 +28,7 @@ builder.Services.AddScoped<IVaultAccessService, VaultAccessService>();
builder.Services.AddScoped<SyncService>();
builder.Services.AddScoped<IdentityService>();
builder.Services.AddScoped<EnrollmentService>();
builder.Services.AddScoped<DeviceService>();
builder.Services.AddScoped<IIdentityBindingVerifier, IdentityBindingVerifier>();
builder.Services.AddSingleton<ICursorKeyProvider, CursorKeyProvider>();