Files
DodoSSH/src/DodoSSH.Client.Sync/VaultKeyring.cs
T
jaap-jan 95816de0c5 Share a vault with a team, without the server holding a key
M3's teams, sharing and ACLs. Teams with roles, a public-key directory, the
append-only key log served for clients to check it against, team-owned vaults,
and vault key grants wrapped by a client and stored opaquely by the server.
VaultAccessService resolves team membership to PermissionFlags, so a viewer may
pull and may not push; the desktop client reads and syncs every vault it holds
a key for, and a real TEAMS screen replaces the one that said it did not exist.
No migration: team, team_membership, vault.team_id and vault_key_grant have all
been there since the first one, which is what carrying two unused tables bought.

Membership is authorisation. A grant is access. The obvious model is one
concept — "access", with a role attached, handed out by the server — and this
architecture cannot implement it: a vault key is sealed to each member's X25519
key, and only a client holding the plaintext can seal it for somebody else. So
"give Bob access" decomposes into a database write and a wrap, which happen on
different machines. Adding a member makes the server serve them the vault; it
cannot make it readable. VaultSummary.WrappedVaultKey is null in the meantime
and the vault appears in their list saying it is waiting for a key, because
hiding it until a grant existed would have been tidier and would have implied
the server was the thing granting access. The screen says the same thing after
every add, in the status line. ADR 0009 records the whole decision.

Sharing verifies or refuses. A directory lookup is a claim by the server about
a third party's public key, and wrapping to an unverified claim hands the vault
to whoever made it — no amount of transport security helps, because the server
is inside the threat model. KeyLogAudit reads the whole log, recomputes every
entry's hash from its own contents, checks the chain from genesis, and refuses
unless the offered key appears in it unchanged. There is no override flag: one
that exists gets used on the day the log is briefly unreachable, and the
resulting grant is indistinguishable from a correct one afterwards. What it
still cannot promise is that the key is the right person's, so the fingerprint
comes back for an out-of-band comparison and the success message says so every
time. A test corrupts the fake server's log by one byte and watches the client
refuse rather than warn.

The roles are only the ones that are enforceable. There is no ConnectOnly,
despite the design asking for one and TeamRole having room: SSH terminates on
the client, so a session needs the credential's plaintext on that machine, and
"may connect but may not read the key" cannot be enforced here. Shipping it as
an option in a dropdown would have been a lie. Connect rides along with Read
and is documented as an interface hint. Removal is named for what it does — it
revokes grants and flags the vault for rekey, and claims nothing about what is
already on somebody's laptop.

Three things are deliberately absent, and each is a refusal rather than an
omission. The rekey itself, because re-wrapping every item's data key under a
new vault key needs a client holding the current one; the server records that a
rotation is owed and the interface reports it, which is more honest than a
button that only appears to do it. Ownership transfer, because allowing an
owner to be removed without one leaves a team nobody can administer. And
cross-vault host key trust: a pin in a team vault is listed but not consulted
at connect time, because any member with Write could otherwise pre-approve a
fingerprint another member's client then trusts silently for a host in their
own vault. Scoping trust properly needs a scope on the SSH connect path, which
IKnownHostStore has not got; until then the narrow direction is the safe one
and the cost is in the README rather than hidden.

Reading now spans vaults and writing still does not. Every list on the vault
and hosts screens covers each vault the keyring opened, rows carry the vault
they came from, and an edit goes back to that vault rather than to the active
one — writing it to the active vault would fork the item and only show up when
a colleague wondered why their change never arrived. A new item goes wherever a
picker says, defaulting to the personal vault and never moving on its own,
because an item filed into a team's vault is visible to that team and moving it
back means deleting and retyping. The sidebar heading stops naming one vault
once there are two, and each row names its own.

The server checks what it can and nothing it cannot. It will not record a grant
for a key its recipient no longer holds, for a superseded generation, or for
somebody who is not in the team — each of those would otherwise surface days
later at the far end as a tag failure indistinguishable from corruption. It
does not verify the wrap or the signature, and the grant service says so: that
would be a convenience and never the boundary, and would put an asymmetric
implementation on a machine that is supposed to hold no keys.

Two bugs the tests found. TeamsViewModel's busy gate blocked its own reload, so
a team created a moment earlier was missing from the list it had just been
added to. And syncing every vault turned a failure from an exception into a
report, which made a background pass announce an unreachable vault once a
minute — the exact behaviour AnAutomaticPassThatFails_LeavesTheStatusAlone
exists to prevent. The fact is recorded and the message swallowed, as it was
before; pressing Sync still names the vault and the reason.

Also fixes a build break this branch started with: QuickConnectTests was never
updated when M2 added ISftpSessionFactory to the shell's constructor, so
nothing built at all.
2026-07-31 12:18:28 +02:00

237 lines
8.0 KiB
C#

using System.Diagnostics.CodeAnalysis;
using System.Security.Cryptography;
using DodoSSH.Client.Storage;
using DodoSSH.Crypto;
namespace DodoSSH.Client.Sync;
/// <summary>
/// The vault keys held for the duration of an unlocked session.
/// </summary>
/// <remarks>
/// <para>
/// One place that holds plaintext vault keys, so there is one place that clears them. Every store and
/// every cipher call borrows a key from here rather than keeping a copy, which is what makes
/// "the keys exist only while unlocked" a property of the code and not of everyone's discipline.
/// </para>
/// <para>
/// A grant that will not open is not an error: it means the vault has been rekeyed and this client's
/// grant has not been re-wrapped yet, or the grant was fabricated. Both leave the vault temporarily
/// unreadable and both are reported rather than thrown, so one bad grant does not take the other vaults
/// down with it.
/// </para>
/// </remarks>
public sealed class VaultKeyring : IDisposable
{
private readonly Dictionary<Guid, byte[]> keys = [];
private readonly Dictionary<Guid, uint> generations = [];
private bool disposed;
private VaultKeyring()
{
}
/// <summary>Vaults whose grant could not be opened, and which are therefore unreadable.</summary>
public IReadOnlyList<Guid> Unopened { get; private set; } = [];
/// <summary>
/// Opens every grant the bundle can.
/// </summary>
/// <param name="bundle">The unlocked identity keys.</param>
/// <param name="vaults">The cached vault list, each with its wrapped key.</param>
public static VaultKeyring Open(UserSecretBundle bundle, IReadOnlyList<StoredVault> vaults)
{
ArgumentNullException.ThrowIfNull(bundle);
ArgumentNullException.ThrowIfNull(vaults);
var keyring = new VaultKeyring();
var unopened = new List<Guid>();
try
{
foreach (var vault in vaults)
{
if (vault.WrappedVaultKey is null)
{
// The server said so itself: a grant awaiting re-wrap after a rekey.
unopened.Add(vault.VaultId);
continue;
}
var key = VaultKeys.TryUnwrap(
bundle.EncryptionKey,
vault.WrappedVaultKey,
vault.VaultId,
vault.KeyGeneration);
if (key is null)
{
unopened.Add(vault.VaultId);
continue;
}
keyring.keys[vault.VaultId] = key;
keyring.generations[vault.VaultId] = vault.KeyGeneration;
}
keyring.Unopened = unopened;
return keyring;
}
catch
{
keyring.Dispose();
throw;
}
}
/// <summary>
/// Takes a vault key this session has just generated.
/// </summary>
/// <param name="vaultId">The vault.</param>
/// <param name="vaultKey">
/// The plaintext key. <b>The keyring takes ownership</b> and zeroes it on disposal; the caller must
/// not keep a reference or zero it itself.
/// </param>
/// <param name="keyGeneration">The generation this key is for.</param>
/// <remarks>
/// Creating a team vault is the only case: the client generates the key, wraps it to itself and
/// sends the wrap, so the plaintext is already here and unwrapping the server's copy back would be
/// a round trip to learn something this process just chose. Adopting it also means the new vault is
/// usable immediately rather than at the next unlock, which is what somebody who just pressed
/// "create" expects.
/// </remarks>
public void Adopt(Guid vaultId, byte[] vaultKey, uint keyGeneration)
{
ObjectDisposedException.ThrowIf(disposed, this);
ArgumentNullException.ThrowIfNull(vaultKey);
if (keys.TryGetValue(vaultId, out var previous))
{
CryptographicOperations.ZeroMemory(previous);
}
keys[vaultId] = vaultKey;
generations[vaultId] = keyGeneration;
Unopened = [.. Unopened.Where(id => id != vaultId)];
}
/// <summary>
/// Tries to open a vault that has become readable since the session was unlocked.
/// </summary>
/// <returns>Whether the grant opened.</returns>
/// <remarks>
/// What a share looks like from the receiving end: the vault was in the list all along, listed and
/// unreadable, and a member holding Share has now wrapped its key. Re-opening it here rather than
/// waiting for a relock is the difference between "someone shared a vault with you" arriving and
/// arriving tomorrow.
/// </remarks>
public bool TryAdmit(UserSecretBundle bundle, StoredVault vault)
{
ObjectDisposedException.ThrowIf(disposed, this);
ArgumentNullException.ThrowIfNull(bundle);
ArgumentNullException.ThrowIfNull(vault);
if (vault.WrappedVaultKey is null)
{
return false;
}
if (keys.ContainsKey(vault.VaultId) && generations[vault.VaultId] == vault.KeyGeneration)
{
return true;
}
var key = VaultKeys.TryUnwrap(
bundle.EncryptionKey, vault.WrappedVaultKey, vault.VaultId, vault.KeyGeneration);
if (key is null)
{
return false;
}
Adopt(vault.VaultId, key, vault.KeyGeneration);
return true;
}
/// <summary>Records that a vault cannot be read, so the interface can say so.</summary>
/// <remarks>
/// The counterpart of <see cref="TryAdmit"/> for the case where the grant did not open. Kept
/// explicit rather than inferred from the absence of a key, because "no key" is also what a vault
/// this session has never heard of looks like.
/// </remarks>
public void MarkUnreadable(Guid vaultId)
{
ObjectDisposedException.ThrowIf(disposed, this);
if (!Unopened.Contains(vaultId))
{
Unopened = [.. Unopened, vaultId];
}
}
/// <summary>
/// Borrows a vault's key.
/// </summary>
/// <remarks>
/// The returned memory is the keyring's own buffer, not a copy, and is zeroed when the keyring is
/// disposed. Callers must not retain it past the operation they borrowed it for.
/// </remarks>
public bool TryGet(Guid vaultId, out ReadOnlyMemory<byte> vaultKey, out uint keyGeneration)
{
ObjectDisposedException.ThrowIf(disposed, this);
if (keys.TryGetValue(vaultId, out var key))
{
vaultKey = key;
keyGeneration = generations[vaultId];
return true;
}
vaultKey = default;
keyGeneration = 0;
return false;
}
/// <summary>Whether this vault can be read at all.</summary>
public bool CanRead(Guid vaultId) => !disposed && keys.ContainsKey(vaultId);
/// <inheritdoc />
public void Dispose()
{
if (disposed)
{
return;
}
disposed = true;
foreach (var key in keys.Values)
{
CryptographicOperations.ZeroMemory(key);
}
keys.Clear();
generations.Clear();
}
}
/// <summary>Thrown when an operation needs a vault key the keyring does not hold.</summary>
/// <remarks>
/// An exception rather than a silent no-op, because every caller that reaches this point has already
/// been given the chance to check <see cref="VaultKeyring.CanRead"/>. Continuing without the key would
/// mean writing an item nobody can open.
/// </remarks>
[SuppressMessage(
"Design",
"CA1032:Implement standard exception constructors",
Justification = "The vault id is required context; a message-only constructor would lose it.")]
public sealed class VaultUnreadableException(Guid vaultId)
: InvalidOperationException(
$"Vault {vaultId} has no usable key. Its grant is missing or awaiting re-wrap after a rekey.")
{
/// <summary>The vault that cannot be read.</summary>
public Guid VaultId { get; } = vaultId;
}