Files
DodoSSH/src/DodoSSH.Infrastructure/Configurations/HostAndSyncConfigurations.cs
T
jaap-jan e93acc856f Sync SSH keys as a vault item type, over a shared write path
The private key now lives in the vault as ciphertext, syncs between a user's
machines, and is stored on the server so it can later be shared — sharing
itself needs M3's signed grants; this is the storage that makes it possible.

More was already reserved than expected: SyncEntityType.SshKey,
CryptoSpec.AadResourceType.SshKey, ChangeEntityType.SshKey,
SyncPlaintextFields.PublicKeyFingerprint, and SshPrivateKeyCredential wired
through PrivateKeyFile over a MemoryStream so a key never touches disk. The
frozen contract and crypto spec needed no change at all.

What was missing was the server. Rather than copy the push path per item type
— version check, change-log append, exactly-once receipt, advisory lock — it
is now written once over IVaultItem, with everything type-specific behind
IItemKind: which table, which plaintext columns, and what those columns must
satisfy. Ten copies of that logic by M5, with a fix applied to nine, is the
outcome this avoids. The refactor landed first with no behaviour change, so
all 66 existing Host tests were the regression net, and they stayed green.

An interface rather than a base class, deliberately: EF Core maps an
inheritance hierarchy when it can see one, so a mapped base would quietly
become a table-per-hierarchy discriminator across item types — the very
arrangement per-type tables exist to avoid.

ssh_key mirrors host and pointedly has no relay trio. That is the argument
for separate tables rather than one wide item table: the columns a host needs
are columns a key must never have, and a shared table could only make them
nullable and trust the code. A key carrying a relay target is refused with a
reason rather than silently dropped.

A key hydrates PlaintextFields as null, not an empty instance — the
difference is visible on the wire, because an all-defaults instance still
serialises "relayEnabled": false and invites a reader to believe the setting
exists and is off. It has none.

Two things now defended by tests rather than by comments. Each kind states
its own ChangeEntityType instead of casting: the two enums agree numerically
but do not even share member names (Host against SshHost), and filing key
changes under the host type is silent sync corruption — sabotaging it fails
three tests. And EntityTypeAlignmentTests asserts the two enums stay aligned
in both directions and in count, which nothing did before.

The client half is next: SshKeySecret, its codec and merge, the cipher, a
repository, and the UI. Note for that work — SyncEntityType.SshKey is 3 while
AadResourceType.SshKey is 6, so a cast between them would seal key ciphertext
as a vault and nothing would fail.
2026-07-29 15:14:06 +02:00

134 lines
5.0 KiB
C#

using DodoSSH.Domain;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace DodoSSH.Infrastructure.Configurations;
/// <summary>Maps <see cref="SshHost"/>.</summary>
public sealed class HostConfiguration : IEntityTypeConfiguration<SshHost>
{
/// <inheritdoc />
public void Configure(EntityTypeBuilder<SshHost> 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="VaultSshKey"/>.</summary>
/// <remarks>
/// Mirrors <see cref="HostConfiguration"/> in everything the two types share, and deliberately has no
/// analogue of the relay CHECK: a key carries no address, which is the reason it is its own table.
/// </remarks>
public sealed class SshKeyConfiguration : IEntityTypeConfiguration<VaultSshKey>
{
/// <inheritdoc />
public void Configure(EntityTypeBuilder<VaultSshKey> builder)
{
ArgumentNullException.ThrowIfNull(builder);
builder.ToTable("ssh_key");
builder.HasKey(k => k.Id);
// Client-generated UUIDv7: keys must be creatable offline, with their ids.
builder.Property(k => k.Id).ValueGeneratedNever();
builder.UseXminConcurrencyToken();
builder.Property(k => k.Payload).IsRequired();
// SHA256:base64 of a 32-byte digest is 50 characters; the ceiling leaves room for another
// algorithm without a migration, and refuses anything that is plainly not a fingerprint.
builder.Property(k => k.PublicKeyFingerprint).HasMaxLength(128);
builder.HasIndex(k => new { k.VaultId, k.ChangeSequence });
builder.HasIndex(k => k.VaultId)
.HasFilter("deleted_at_utc IS NULL")
.HasDatabaseName("ix_ssh_key_vault_live");
builder.ToTable(t => t.HasCheckConstraint(
"ck_ssh_key_version",
"version >= 1"));
}
}
/// <summary>Maps <see cref="VaultChange"/>.</summary>
public sealed class SyncChangeConfiguration : IEntityTypeConfiguration<VaultChange>
{
/// <inheritdoc />
public void Configure(EntityTypeBuilder<VaultChange> 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 });
}
}