Add data model, DbContext and initial migration (M1)

Schema for identity, vaults, grants, hosts and the sync change log, verified against a
real PostgreSQL 18 container rather than an in-memory provider: partial unique indexes,
CHECK constraints, citext and identity-always columns are all provider behaviour that an
in-memory fake would not exercise.

Invariants pushed into the database, so they hold even when application code has a bug:
- ck_host_relay_target is a security boundary, not tidiness. A host may carry a plaintext
  hostname and port ONLY when relay is deliberately enabled. Both directions are tested;
  the important one is that relay-disabled hosts cannot carry an address, since otherwise
  a bug would silently give the server infrastructure visibility it was never granted.
- ck_vault_owner: exactly one of owner_user_id or team_id, or permission resolution would
  have no defined answer.
- ck_vault_key_grant_recipient: member grants name a user; recovery and escrow grants are
  wrapped to a key and must not.
- ck_user_key_wrap_kdf: a password-derived wrap without its parameters is permanently
  unopenable, so a partial write is rejected outright.

Present from the first migration on purpose:
- GrantKind (Member/Recovery/Escrow). Recovery cannot be bolted on later — every vault
  created before it existed would be unrecoverable by design.
- team and team_membership, though team features are M3. Adding them later would mean
  introducing a foreign key on a live vault table.
- Host.ContentKeyId, reserved for per-item content keys wrapped to individual users.
- user_key as its own table, so key rotation does not require altering the user row.

Two things verified rather than assumed:
- Npgsql's UseXminAsConcurrencyToken helper no longer exists in EF 10, so xmin is mapped
  directly in XminConcurrency. The generated migration *looks* like it creates an xmin
  column; it does not. Confirmed by inspecting pg_attribute (attnum -2, a system column)
  and by grepping the emitted DDL. A test pins both, because had it created a real column
  PostgreSQL would have rejected the name.
- EF Core is now pinned centrally. The Npgsql provider asks for 10.0.4 while
  EntityFrameworkCore.Design pulls 10.0.10, and because Design is PrivateAssets=all that
  higher version does not flow to referencing projects — producing a CS1705 in any test
  project referencing Infrastructure.

Also commits artifacts/schema/v0.1.sql, the idempotent script, as the baseline for future
upgrade tests.

Verified: 0 warnings, 122 tests pass (27 new against Postgres), format clean.
This commit is contained in:
2026-07-28 14:17:37 +02:00
parent 06d04b490b
commit eaf68c86b0
24 changed files with 5843 additions and 0 deletions
@@ -0,0 +1,96 @@
using DodoSSH.Domain;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace DodoSSH.Infrastructure.Configurations;
/// <summary>Maps <see cref="Host"/>.</summary>
public sealed class HostConfiguration : IEntityTypeConfiguration<Host>
{
/// <inheritdoc />
public void Configure(EntityTypeBuilder<Host> builder)
{
ArgumentNullException.ThrowIfNull(builder);
builder.ToTable("host");
builder.HasKey(h => h.Id);
// Client-generated UUIDv7: items must be creatable offline, with their ids.
builder.Property(h => h.Id).ValueGeneratedNever();
builder.UseXminConcurrencyToken();
builder.Property(h => h.Payload).IsRequired();
builder.Property(h => h.Hostname).HasMaxLength(255);
builder.HasIndex(h => new { h.VaultId, h.ChangeSequence });
builder.HasIndex(h => h.VaultId)
.HasFilter("deleted_at_utc IS NULL")
.HasDatabaseName("ix_host_vault_live");
// The relay resolves its target from this row, so an address is stored only when relay is
// deliberately enabled for the host. Enforced in the database rather than in application
// code: a bug that let a host carry a plaintext address without opting in would silently
// widen what the server can see. See ADR 0004.
builder.ToTable(t => t.HasCheckConstraint(
"ck_host_relay_target",
"""
(relay_enabled AND hostname IS NOT NULL AND port IS NOT NULL)
OR (NOT relay_enabled AND hostname IS NULL AND port IS NULL)
"""));
builder.ToTable(t => t.HasCheckConstraint(
"ck_host_port_range",
"port IS NULL OR (port BETWEEN 1 AND 65535)"));
builder.ToTable(t => t.HasCheckConstraint(
"ck_host_version",
"version >= 1"));
}
}
/// <summary>Maps <see cref="SyncChange"/>.</summary>
public sealed class SyncChangeConfiguration : IEntityTypeConfiguration<SyncChange>
{
/// <inheritdoc />
public void Configure(EntityTypeBuilder<SyncChange> builder)
{
ArgumentNullException.ThrowIfNull(builder);
builder.ToTable("sync_change");
builder.HasKey(c => c.Sequence);
// Identity ALWAYS rather than BY DEFAULT: nothing may supply its own sequence value, or
// cursor ordering stops meaning anything.
builder.Property(c => c.Sequence).UseIdentityAlwaysColumn();
builder.Property(c => c.EntityType).HasConversion<int>();
builder.Property(c => c.Operation).HasConversion<int>();
// The delta-pull access path: everything after a cursor, for one vault.
builder.HasIndex(c => new { c.VaultId, c.Sequence });
// Latest change for a given entity, used when resolving a conflict.
builder.HasIndex(c => new { c.VaultId, c.EntityId, c.Sequence })
.IsDescending(false, false, true);
}
}
/// <summary>Maps <see cref="SyncOperationReceipt"/>.</summary>
public sealed class SyncOperationReceiptConfiguration : IEntityTypeConfiguration<SyncOperationReceipt>
{
/// <inheritdoc />
public void Configure(EntityTypeBuilder<SyncOperationReceipt> builder)
{
ArgumentNullException.ThrowIfNull(builder);
builder.ToTable("sync_operation_receipt");
// The client-generated operation id is the key, which is what makes a retried push
// exactly-once per operation rather than per batch.
builder.HasKey(r => r.OperationId);
builder.Property(r => r.OperationId).ValueGeneratedNever();
builder.HasIndex(r => new { r.VaultId, r.CreatedAtUtc });
}
}
@@ -0,0 +1,181 @@
using DodoSSH.Domain;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace DodoSSH.Infrastructure.Configurations;
/// <summary>Maps <see cref="UserAccount"/>.</summary>
public sealed class UserAccountConfiguration : IEntityTypeConfiguration<UserAccount>
{
/// <inheritdoc />
public void Configure(EntityTypeBuilder<UserAccount> builder)
{
ArgumentNullException.ThrowIfNull(builder);
builder.ToTable("user_account");
builder.HasKey(u => u.Id);
builder.Property(u => u.Id).ValueGeneratedNever();
builder.UseXminConcurrencyToken();
builder.Property(u => u.Issuer).HasMaxLength(512).IsRequired();
builder.Property(u => u.Subject).HasMaxLength(256).IsRequired();
// citext, so lookups and uniqueness are case-insensitive without lower() everywhere.
builder.Property(u => u.Email).HasColumnType("citext").HasMaxLength(320);
builder.Property(u => u.DisplayName).HasMaxLength(256);
builder.Property(u => u.Status).HasConversion<int>();
// The natural key. Multi-issuer from the start so a second provider does not require a
// schema change; the issuer is part of the identity, not a detail.
builder.HasIndex(u => new { u.Issuer, u.Subject }).IsUnique();
// Email is not unique in general — only among live accounts, and only when present.
builder.HasIndex(u => u.Email)
.IsUnique()
.HasFilter("email IS NOT NULL AND deleted_at_utc IS NULL");
builder.HasMany(u => u.Keys)
.WithOne(k => k.User)
.HasForeignKey(k => k.UserId)
.OnDelete(DeleteBehavior.Cascade);
builder.HasMany(u => u.KeyWraps)
.WithOne(w => w.User)
.HasForeignKey(w => w.UserId)
.OnDelete(DeleteBehavior.Cascade);
builder.HasMany(u => u.Devices)
.WithOne(d => d.User)
.HasForeignKey(d => d.UserId)
.OnDelete(DeleteBehavior.Cascade);
}
}
/// <summary>Maps <see cref="UserKey"/>.</summary>
public sealed class UserKeyConfiguration : IEntityTypeConfiguration<UserKey>
{
/// <inheritdoc />
public void Configure(EntityTypeBuilder<UserKey> builder)
{
ArgumentNullException.ThrowIfNull(builder);
builder.ToTable("user_key");
builder.HasKey(k => k.Id);
builder.Property(k => k.Id).ValueGeneratedNever();
builder.Property(k => k.EncryptionPublicKey).HasMaxLength(32).IsRequired();
builder.Property(k => k.SigningPublicKey).HasMaxLength(32).IsRequired();
builder.Property(k => k.FingerprintSha256).HasMaxLength(32).IsRequired();
builder.Property(k => k.Statement).HasColumnType("jsonb").IsRequired();
builder.Property(k => k.StatementSignature).HasMaxLength(64).IsRequired();
builder.Property(k => k.IdentityProviderBinding).HasColumnType("jsonb");
builder.HasIndex(k => new { k.UserId, k.Generation }).IsUnique();
// Exactly one current generation per user, enforced by the database rather than by
// convention: two "current" keys would make it ambiguous which one to wrap to.
builder.HasIndex(k => k.UserId)
.IsUnique()
.HasFilter("is_current")
.HasDatabaseName("ix_user_key_current");
builder.HasIndex(k => k.FingerprintSha256).IsUnique();
}
}
/// <summary>Maps <see cref="UserKeyWrap"/>.</summary>
public sealed class UserKeyWrapConfiguration : IEntityTypeConfiguration<UserKeyWrap>
{
/// <inheritdoc />
public void Configure(EntityTypeBuilder<UserKeyWrap> builder)
{
ArgumentNullException.ThrowIfNull(builder);
builder.ToTable("user_key_wrap");
builder.HasKey(w => w.Id);
builder.Property(w => w.Id).ValueGeneratedNever();
builder.UseXminConcurrencyToken();
builder.Property(w => w.Kind).HasConversion<int>();
builder.Property(w => w.Wrap).IsRequired();
builder.Property(w => w.KdfAlgorithm).HasMaxLength(64);
builder.Property(w => w.KdfSalt).HasMaxLength(64);
builder.HasOne(w => w.Device)
.WithMany()
.HasForeignKey(w => w.DeviceId)
.OnDelete(DeleteBehavior.Cascade);
// One passphrase wrap and one recovery wrap per user; one device wrap per device.
builder.HasIndex(w => new { w.UserId, w.Kind })
.IsUnique()
.HasFilter("device_id IS NULL")
.HasDatabaseName("ix_user_key_wrap_user_kind");
builder.HasIndex(w => new { w.UserId, w.DeviceId })
.IsUnique()
.HasFilter("device_id IS NOT NULL")
.HasDatabaseName("ix_user_key_wrap_user_device");
// A password-derived wrap is useless without its parameters, and a wrap that is not
// password-derived must not carry them. Enforced here so a partial write cannot leave a
// bundle permanently unopenable.
builder.ToTable(t => t.HasCheckConstraint(
"ck_user_key_wrap_kdf",
"""
(kind IN (1, 3) AND kdf_algorithm IS NOT NULL AND kdf_salt IS NOT NULL
AND kdf_memory_kibibytes IS NOT NULL AND kdf_passes IS NOT NULL
AND kdf_parallelism IS NOT NULL)
OR (kind IN (2, 4) AND kdf_algorithm IS NULL AND kdf_salt IS NULL)
"""));
// A device wrap must name its device; the others must not.
builder.ToTable(t => t.HasCheckConstraint(
"ck_user_key_wrap_device",
"(kind = 2 AND device_id IS NOT NULL) OR (kind <> 2 AND device_id IS NULL)"));
}
}
/// <summary>Maps <see cref="Device"/>.</summary>
public sealed class DeviceConfiguration : IEntityTypeConfiguration<Device>
{
/// <inheritdoc />
public void Configure(EntityTypeBuilder<Device> builder)
{
ArgumentNullException.ThrowIfNull(builder);
builder.ToTable("device");
builder.HasKey(d => d.Id);
builder.Property(d => d.Id).ValueGeneratedNever();
builder.Property(d => d.Name).HasMaxLength(256).IsRequired();
builder.Property(d => d.Platform).HasConversion<int>();
builder.Property(d => d.PublicKey).HasMaxLength(32).IsRequired();
builder.HasIndex(d => d.UserId);
}
}
/// <summary>Maps <see cref="KeyLogEntry"/>.</summary>
public sealed class KeyLogEntryConfiguration : IEntityTypeConfiguration<KeyLogEntry>
{
/// <inheritdoc />
public void Configure(EntityTypeBuilder<KeyLogEntry> builder)
{
ArgumentNullException.ThrowIfNull(builder);
builder.ToTable("key_log");
builder.HasKey(e => e.Sequence);
builder.Property(e => e.Sequence).UseIdentityAlwaysColumn();
builder.Property(e => e.EncryptionPublicKey).HasMaxLength(32).IsRequired();
builder.Property(e => e.SigningPublicKey).HasMaxLength(32).IsRequired();
builder.Property(e => e.StatementSignature).HasMaxLength(64).IsRequired();
builder.Property(e => e.PreviousHash).HasMaxLength(32).IsRequired();
builder.Property(e => e.Hash).HasMaxLength(32).IsRequired();
builder.HasIndex(e => e.UserId);
builder.HasIndex(e => e.Hash).IsUnique();
}
}
@@ -0,0 +1,159 @@
using DodoSSH.Domain;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace DodoSSH.Infrastructure.Configurations;
/// <summary>Maps <see cref="Team"/>.</summary>
public sealed class TeamConfiguration : IEntityTypeConfiguration<Team>
{
/// <inheritdoc />
public void Configure(EntityTypeBuilder<Team> builder)
{
ArgumentNullException.ThrowIfNull(builder);
builder.ToTable("team");
builder.HasKey(t => t.Id);
builder.Property(t => t.Id).ValueGeneratedNever();
builder.UseXminConcurrencyToken();
builder.Property(t => t.Name).HasMaxLength(256).IsRequired();
builder.Property(t => t.Slug).HasColumnType("citext").HasMaxLength(128).IsRequired();
builder.Property(t => t.Description).HasMaxLength(2048);
builder.HasIndex(t => t.Slug)
.IsUnique()
.HasFilter("deleted_at_utc IS NULL");
builder.HasMany(t => t.Memberships)
.WithOne(m => m.Team)
.HasForeignKey(m => m.TeamId)
.OnDelete(DeleteBehavior.Cascade);
}
}
/// <summary>Maps <see cref="TeamMembership"/>.</summary>
public sealed class TeamMembershipConfiguration : IEntityTypeConfiguration<TeamMembership>
{
/// <inheritdoc />
public void Configure(EntityTypeBuilder<TeamMembership> builder)
{
ArgumentNullException.ThrowIfNull(builder);
builder.ToTable("team_membership");
builder.HasKey(m => m.Id);
builder.Property(m => m.Id).ValueGeneratedNever();
builder.UseXminConcurrencyToken();
builder.Property(m => m.Role).HasConversion<int>();
builder.Property(m => m.Status).HasConversion<int>();
builder.HasOne(m => m.User)
.WithMany()
.HasForeignKey(m => m.UserId)
.OnDelete(DeleteBehavior.Cascade);
builder.HasIndex(m => new { m.TeamId, m.UserId })
.IsUnique()
.HasFilter("deleted_at_utc IS NULL");
// Effective-permission resolution starts from the user, so this is the hot direction.
builder.HasIndex(m => m.UserId);
}
}
/// <summary>Maps <see cref="Vault"/>.</summary>
public sealed class VaultConfiguration : IEntityTypeConfiguration<Vault>
{
/// <inheritdoc />
public void Configure(EntityTypeBuilder<Vault> builder)
{
ArgumentNullException.ThrowIfNull(builder);
builder.ToTable("vault");
builder.HasKey(v => v.Id);
builder.Property(v => v.Id).ValueGeneratedNever();
builder.UseXminConcurrencyToken();
builder.Property(v => v.Name).HasMaxLength(256).IsRequired();
builder.Property(v => v.OwnerKind).HasConversion<int>();
builder.Property(v => v.RekeyReason).HasConversion<int>();
builder.HasOne(v => v.OwnerUser)
.WithMany()
.HasForeignKey(v => v.OwnerUserId)
.OnDelete(DeleteBehavior.Restrict);
builder.HasOne(v => v.Team)
.WithMany()
.HasForeignKey(v => v.TeamId)
.OnDelete(DeleteBehavior.Restrict);
builder.HasIndex(v => v.OwnerUserId);
builder.HasIndex(v => v.TeamId);
// Exactly one owner. Without this a vault could end up owned by both or neither, and
// permission resolution would have no defined answer.
builder.ToTable(t => t.HasCheckConstraint(
"ck_vault_owner",
"""
(owner_kind = 1 AND owner_user_id IS NOT NULL AND team_id IS NULL)
OR (owner_kind = 2 AND team_id IS NOT NULL AND owner_user_id IS NULL)
"""));
builder.ToTable(t => t.HasCheckConstraint(
"ck_vault_key_generation",
"key_generation >= 1"));
builder.HasMany(v => v.KeyGrants)
.WithOne(g => g.Vault)
.HasForeignKey(g => g.VaultId)
.OnDelete(DeleteBehavior.Cascade);
builder.HasMany(v => v.Hosts)
.WithOne(h => h.Vault)
.HasForeignKey(h => h.VaultId)
.OnDelete(DeleteBehavior.Cascade);
}
}
/// <summary>Maps <see cref="VaultKeyGrant"/>.</summary>
public sealed class VaultKeyGrantConfiguration : IEntityTypeConfiguration<VaultKeyGrant>
{
/// <inheritdoc />
public void Configure(EntityTypeBuilder<VaultKeyGrant> builder)
{
ArgumentNullException.ThrowIfNull(builder);
builder.ToTable("vault_key_grant");
builder.HasKey(g => g.Id);
builder.Property(g => g.Id).ValueGeneratedNever();
builder.UseXminConcurrencyToken();
builder.Property(g => g.Kind).HasConversion<int>();
builder.Property(g => g.State).HasConversion<int>();
builder.Property(g => g.RecipientKeyFingerprint).HasMaxLength(32).IsRequired();
builder.Property(g => g.WrappedKey).IsRequired();
builder.Property(g => g.GranterKeyFingerprint).HasMaxLength(32).IsRequired();
builder.Property(g => g.KeyLogHead).HasMaxLength(32);
builder.Property(g => g.Signature).HasMaxLength(64).IsRequired();
builder.HasOne(g => g.RecipientUser)
.WithMany()
.HasForeignKey(g => g.RecipientUserId)
.OnDelete(DeleteBehavior.Cascade);
// One live member grant per recipient per generation. Revoked rows are retained, so the
// filter is on revocation rather than on deletion.
builder.HasIndex(g => new { g.VaultId, g.KeyGeneration, g.RecipientUserId })
.IsUnique()
.HasFilter("revoked_at_utc IS NULL AND recipient_user_id IS NOT NULL");
builder.HasIndex(g => g.RecipientUserId);
// A member grant names a user; recovery and escrow grants do not.
builder.ToTable(t => t.HasCheckConstraint(
"ck_vault_key_grant_recipient",
"(kind = 1 AND recipient_user_id IS NOT NULL) OR (kind <> 1 AND recipient_user_id IS NULL)"));
}
}