Add /me and enrollment with the identity-provider key binding (M1)

The last backend piece of M1. A client can now log in, discover it must
enroll, publish its identity key, and get a usable personal vault.

Enrollment is one indivisible act. One transaction writes the key, its
wraps, the device, the key log entry, the vault and the vault key grant,
because none of them is useful alone: a key with no vault leaves a user
unable to store anything, and a vault with no grant is a container nobody
can ever open -- including its owner, since only the client can wrap the
key and it has already moved on.

Two independent checks run, and neither substitutes for the other. The
Ed25519 self-signature proves possession of the private key. The
identity-provider binding proves whose key it is: the client hashed its
statement, used the hash as an OIDC nonce, and the resulting ID token is
the provider's signature over exactly those public keys. This server
cannot mint that signature, so it cannot invent a key for a user who never
enrolled -- which is the attack that would otherwise let an operator read
every vault by publishing its own key as yours.

The binding token is stored verbatim, not just summarised. Clients must
repeat the check against the provider's JWKS fetched directly, and storing
only our conclusion would ask them to trust the server about the one
question the design exists to avoid trusting it about.

Key log appends take a deployment-wide advisory lock. The falsification
matters more than the passing test: with the lock removed,
Enroll_ConcurrentEnrollmentsByDifferentUsers_LeaveAnUnbrokenChain fails
with entry 11 linked to the wrong predecessor. Different users trip no
unique index, so without serialising they all read the same head and the
chain forks -- indistinguishable from the key substitution the log exists
to make detectable, and permanent, because the log is append-only.

Enrollment is idempotent. Vault ids and keys are client-chosen, so a
client whose response was lost re-sends the identical body and gets the
identical result. Without that, a lost response leaves a user enrolled
against a vault they never learned the id of.

Contract change, breaking the v0.1 freeze deliberately. EnrollmentRequest
had DevicePublicKey but no wrap to go with it, which is unsatisfiable:
only the holder of the secret bundle can seal it, so the server could
never fill the gap. Added DeviceWrappedPrivateKey, and PersonalVault so
enrollment can be atomic rather than leaving an unopenable vault behind
two endpoints that do not exist yet. No client exists and no package is
published, which is exactly when PublicAPI.Unshipped.txt expects this.

Sync now requires the Enrolled policy, which until now was a stub whose
name promised a check it never made. The sync denial tests use enrolled
intruders instead of unenrolled ones -- an unenrolled caller is stopped
before the vault check runs, which would have left those tests passing
without exercising the thing they exist to prove.

Also fixed: omitting kdfParameters from the JSON body was a 500. A
record's non-nullable parameters are a compile-time promise, not a runtime
one.

268 tests pass, zero warnings on a clean rebuild, format clean.
This commit is contained in:
2026-07-28 16:06:35 +02:00
parent d2a2ed8a29
commit a628762cd1
25 changed files with 2863 additions and 82 deletions
@@ -1,3 +1,4 @@
using System.Globalization;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Cryptography;
using System.Text.Json;
@@ -39,9 +40,19 @@ public sealed class StubIdentityProvider : IDisposable
/// <summary>Issuer URL, matching what the tokens claim.</summary>
public string Authority { get; }
/// <summary>Audience the API is configured to expect.</summary>
/// <summary>Audience the API is configured to expect on access tokens.</summary>
public static string Audience => "dodossh-api";
/// <summary>
/// The public client identifier, and therefore the audience of an ID token.
/// </summary>
/// <remarks>
/// Distinct from <see cref="Audience"/> on purpose. An ID token is audienced to the client that
/// requested it, never to the API — validating a binding token against the API audience would
/// reject every genuine enrollment, and a test that used one audience for both would not notice.
/// </remarks>
public static string ClientId => "dodossh-desktop";
/// <summary>
/// Mints a signed access token.
/// </summary>
@@ -94,6 +105,89 @@ public sealed class StubIdentityProvider : IDisposable
return new JwtSecurityTokenHandler().WriteToken(token);
}
/// <summary>
/// Mints an ID token carrying a key-binding nonce.
/// </summary>
/// <remarks>
/// This is the artefact the whole public-key trust model rests on: an identity-provider
/// signature over the hash of a key statement. Signed with the same real RSA key the JWKS
/// endpoint publishes, so the server's verification genuinely runs.
/// </remarks>
/// <param name="subject">The <c>sub</c> claim.</param>
/// <param name="nonce">The key statement binding, from <c>KeyStatementCodec.ComputeNonce</c>.</param>
/// <param name="email">Optional email claim.</param>
/// <param name="audience">Override the audience, to test rejection. Defaults to the client id.</param>
/// <param name="issuer">Override the issuer, to test rejection.</param>
/// <param name="expires">Override expiry, to test rejection.</param>
/// <param name="omitNonce">Omit the nonce entirely, to test rejection.</param>
public string MintIdToken(
string subject,
string nonce,
string? email = null,
string? audience = null,
string? issuer = null,
DateTime? expires = null,
bool omitNonce = false)
{
var now = TimeProvider.System.GetUtcNow().UtcDateTime;
// Integer64, so the handler writes a JSON number rather than a string. A provider that
// emitted a string here would be unusual, and the server reads auth_time as a number.
var claims = new List<System.Security.Claims.Claim>
{
new("sub", subject),
new(
"auth_time",
new DateTimeOffset(now, TimeSpan.Zero).ToUnixTimeSeconds()
.ToString(CultureInfo.InvariantCulture),
System.Security.Claims.ClaimValueTypes.Integer64),
};
if (!omitNonce)
{
claims.Add(new System.Security.Claims.Claim("nonce", nonce));
}
if (email is not null)
{
claims.Add(new System.Security.Claims.Claim("email", email));
}
var expiry = expires ?? now.AddMinutes(5);
var notBefore = expiry < now ? expiry.AddMinutes(-1) : now.AddMinutes(-1);
var token = new JwtSecurityToken(
issuer: issuer ?? Authority,
audience: audience ?? ClientId,
claims: claims,
notBefore: notBefore,
expires: expiry,
signingCredentials: new SigningCredentials(signingKey, SecurityAlgorithms.RsaSha256));
return new JwtSecurityTokenHandler().WriteToken(token);
}
/// <summary>Mints an ID token signed by a key the provider does not publish.</summary>
public string MintIdTokenWithForeignKey(string subject, string nonce)
{
var foreign = new RsaSecurityKey(RSA.Create(2048)) { KeyId = KeyId };
var now = TimeProvider.System.GetUtcNow().UtcDateTime;
var token = new JwtSecurityToken(
issuer: Authority,
audience: ClientId,
claims:
[
new System.Security.Claims.Claim("sub", subject),
new System.Security.Claims.Claim("nonce", nonce),
],
notBefore: now.AddMinutes(-1),
expires: now.AddMinutes(5),
signingCredentials: new SigningCredentials(foreign, SecurityAlgorithms.RsaSha256));
return new JwtSecurityTokenHandler().WriteToken(token);
}
/// <summary>Mints a token signed by a different key, which must be rejected.</summary>
public string MintTokenWithForeignKey(string subject)
{