Public Access
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.
154 lines
6.3 KiB
C#
154 lines
6.3 KiB
C#
using DodoSSH.Contracts;
|
|
using DodoSSH.Crypto;
|
|
using NSec.Cryptography;
|
|
|
|
namespace DodoSSH.Api.Tests;
|
|
|
|
/// <summary>
|
|
/// Builds a genuine enrollment: real X25519 and Ed25519 keys, a real Ed25519 statement signature,
|
|
/// and an ID token whose nonce is the statement's actual canonical hash.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// Nothing here is stubbed. The point is that the server's two independent checks — the statement
|
|
/// self-signature and the identity-provider binding — both run for real, so a change that breaks
|
|
/// either shows up here rather than against a live Keycloak.
|
|
/// </remarks>
|
|
internal sealed class TestEnrollment : IDisposable
|
|
{
|
|
private static readonly DateTimeOffset CreatedAt =
|
|
DateTimeOffset.FromUnixTimeMilliseconds(1_750_000_000_123);
|
|
|
|
private readonly StubIdentityProvider identityProvider;
|
|
private readonly Key encryptionKey;
|
|
private readonly Key signingKey;
|
|
|
|
internal TestEnrollment(StubIdentityProvider identityProvider, string subject, string? email = null)
|
|
{
|
|
this.identityProvider = identityProvider;
|
|
Subject = subject;
|
|
|
|
encryptionKey = Key.Create(KeyAgreementAlgorithm.X25519);
|
|
signingKey = Key.Create(SignatureAlgorithm.Ed25519);
|
|
|
|
Statement = new KeyStatement(
|
|
Version: 1,
|
|
Issuer: identityProvider.Authority,
|
|
Subject: subject,
|
|
Email: email,
|
|
EncryptionPublicKey: encryptionKey.PublicKey.Export(KeyBlobFormat.RawPublicKey),
|
|
SigningPublicKey: signingKey.PublicKey.Export(KeyBlobFormat.RawPublicKey),
|
|
KeyGeneration: 1,
|
|
CreatedAt: CreatedAt,
|
|
DeviceName: "test-device");
|
|
}
|
|
|
|
/// <summary>The OIDC subject this enrollment is for.</summary>
|
|
internal string Subject { get; }
|
|
|
|
/// <summary>The client-chosen personal vault id.</summary>
|
|
internal Guid VaultId { get; } = Guid.CreateVersion7();
|
|
|
|
/// <summary>The default, well-formed statement.</summary>
|
|
internal KeyStatement Statement { get; }
|
|
|
|
/// <summary>The identity fingerprint the server should compute.</summary>
|
|
internal byte[] Fingerprint => DshCrypto.ComputeFingerprint(
|
|
Statement.EncryptionPublicKey,
|
|
Statement.SigningPublicKey);
|
|
|
|
/// <summary>Signs a statement with this enrollment's Ed25519 key.</summary>
|
|
internal byte[] Sign(KeyStatement statement) =>
|
|
DshSignatures.SignKeyStatement(signingKey, KeyStatementCodec.Encode(ToFields(statement)));
|
|
|
|
/// <summary>Mints an ID token whose nonce is the given statement's binding.</summary>
|
|
internal string MintIdToken(
|
|
KeyStatement statement,
|
|
string? subject = null,
|
|
string? audience = null,
|
|
string? issuer = null,
|
|
DateTime? expires = null,
|
|
bool omitNonce = false) =>
|
|
identityProvider.MintIdToken(
|
|
subject ?? Subject,
|
|
KeyStatementCodec.ComputeNonce(ToFields(statement)),
|
|
audience: audience,
|
|
issuer: issuer,
|
|
expires: expires,
|
|
omitNonce: omitNonce);
|
|
|
|
/// <summary>Builds a complete, valid request, with every part overridable for negative tests.</summary>
|
|
internal EnrollmentRequest Build(
|
|
KeyStatement? statement = null,
|
|
byte[]? statementSignature = null,
|
|
string? idToken = null,
|
|
KdfParameters? kdfParameters = null,
|
|
PersonalVaultRequest? personalVault = null,
|
|
bool includeDevice = true,
|
|
bool includeRecovery = true)
|
|
{
|
|
var effective = statement ?? Statement;
|
|
|
|
return new EnrollmentRequest(
|
|
Statement: effective,
|
|
StatementSignature: statementSignature ?? Sign(effective),
|
|
IdentityProviderToken: idToken ?? MintIdToken(effective),
|
|
WrappedPrivateKey: Bytes(220, 0x11),
|
|
KdfParameters: kdfParameters ?? DefaultKdf(),
|
|
DevicePublicKey: includeDevice ? Bytes(32, 0x22) : null,
|
|
DeviceWrappedPrivateKey: includeDevice ? Bytes(240, 0x33) : null,
|
|
RecoveryWrappedPrivateKey: includeRecovery ? Bytes(220, 0x44) : null,
|
|
RecoveryKdfParameters: includeRecovery ? RecoveryKdf() : null,
|
|
PersonalVault: personalVault ?? DefaultVault());
|
|
}
|
|
|
|
/// <summary>The passphrase KDF profile, matching <c>Argon2Profile.PassphraseDefault</c>.</summary>
|
|
internal static KdfParameters DefaultKdf() =>
|
|
new("argon2id", Bytes(16, 0x55), MemoryKibibytes: 256 * 1024, Passes: 4, Parallelism: 1);
|
|
|
|
/// <summary>The recovery KDF profile. Cheaper, because a recovery code carries real entropy.</summary>
|
|
internal static KdfParameters RecoveryKdf() =>
|
|
new("argon2id", Bytes(16, 0x66), MemoryKibibytes: 64 * 1024, Passes: 3, Parallelism: 1);
|
|
|
|
/// <remarks>
|
|
/// The grant signature is a real Ed25519 signature of the right length, but not over the §7
|
|
/// grant tuple: that canonical encoding lands with team sharing in M3, and the server stores
|
|
/// grant signatures opaquely rather than verifying them. Shape is what is under test here.
|
|
/// </remarks>
|
|
internal PersonalVaultRequest DefaultVault(Guid? vaultId = null, string name = "Personal") =>
|
|
new(
|
|
VaultId: vaultId ?? VaultId,
|
|
Name: name,
|
|
WrappedVaultKey: Bytes(80, 0x77),
|
|
GrantSignature: SignatureAlgorithm.Ed25519.Sign(signingKey, Bytes(32, 0x88)),
|
|
GrantedAt: CreatedAt);
|
|
|
|
/// <summary>Bearer client for this enrollment's subject.</summary>
|
|
internal HttpClient CreateClient(ApiFixture fixture) => fixture.CreateClientFor(Subject);
|
|
|
|
/// <inheritdoc />
|
|
public void Dispose()
|
|
{
|
|
encryptionKey.Dispose();
|
|
signingKey.Dispose();
|
|
}
|
|
|
|
private static byte[] Bytes(int length, byte seed) =>
|
|
[.. Enumerable.Range(0, length).Select(i => (byte)(seed + i))];
|
|
|
|
/// <remarks>
|
|
/// Mapped here rather than reusing the server's mapper, so a change to either side's field list
|
|
/// shows up as a failing enrollment instead of two copies of the same mistake agreeing.
|
|
/// </remarks>
|
|
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);
|
|
}
|