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.
This commit is contained in:
jaap-jan committed 2026-07-31 12:18:28 +02:00
1 parent d1700f5a34
commit 95816de0c5
45 files changed
+6699 -133

No files matched your search

@@ -0,0 +1,162 @@
using DodoSSH.Contracts;
using DodoSSH.Domain;
using DodoSSH.Infrastructure;
using Microsoft.EntityFrameworkCore;
namespace DodoSSH.Api.Features.Identity;
/// <summary>
/// The public-key directory.
/// </summary>
/// <remarks>
/// <para>
/// This is where a client gets the key it is about to wrap a vault key to, so its shape is a security
/// decision rather than a convenience one. Two rules follow from that.
/// </para>
/// <para>
/// <b>Lookup by exact email, never by prefix.</b> There is no search, no wildcard and no listing of
/// everybody. A caller has to already know the address, which keeps this from being a way to
/// enumerate an organisation's staff out of a server that stores their addresses in plaintext.
/// </para>
/// <para>
/// <b>Lookup by id is restricted to people the caller shares a team with.</b> Ids come from a member
/// list the caller can already read, so nothing is hidden that they cannot reach another way — but an
/// unrestricted id lookup would turn a leaked id from any source into a directory hit.
/// </para>
/// <para>
/// What this returns is <em>evidence</em>, not authority. A client must check the identity-provider
/// binding, compare against any fingerprint it has pinned, and confirm the key log head before
/// wrapping anything. Trusting the directory's word is the one mistake that undoes end-to-end
/// encryption entirely; see ADR 0001 and <c>DirectoryEntry</c>'s own remarks.
/// </para>
/// </remarks>
internal sealed class DirectoryService(DodoDbContext database)
{
/// <summary>Looks a user up by exact email address.</summary>
internal async Task<IReadOnlyList<DirectoryEntry>> FindByEmailAsync(
string email,
CancellationToken cancellationToken)
{
var normalised = email.Trim();
if (normalised.Length == 0)
{
return [];
}
// The email column is citext, so this comparison is case-insensitive in the database and the
// partial unique index on it means at most one row can match. Written as a list anyway
// because the response shape must not have to change if a second issuer ever shares one.
var users = await database.Users
.Where(u => u.Email == normalised
&& u.DeletedAtUtc == null
&& u.Status == UserStatus.Active)
.ToListAsync(cancellationToken)
.ConfigureAwait(false);
return await BuildAsync(users, cancellationToken).ConfigureAwait(false);
}
/// <summary>Looks up accounts the caller shares an active team with.</summary>
internal async Task<IReadOnlyList<DirectoryEntry>> FindTeammatesAsync(
Guid callerId,
IReadOnlyList<Guid> userIds,
CancellationToken cancellationToken)
{
if (userIds.Count == 0)
{
return [];
}
var teamIds = await database.TeamMemberships
.Where(m => m.UserId == callerId
&& m.Status == MembershipStatus.Active
&& m.DeletedAtUtc == null)
.Select(m => m.TeamId)
.ToListAsync(cancellationToken)
.ConfigureAwait(false);
if (teamIds.Count == 0)
{
return [];
}
var visible = await database.TeamMemberships
.Where(m => teamIds.Contains(m.TeamId)
&& userIds.Contains(m.UserId)
&& m.Status == MembershipStatus.Active
&& m.DeletedAtUtc == null)
.Select(m => m.UserId)
.Distinct()
.ToListAsync(cancellationToken)
.ConfigureAwait(false);
var users = await database.Users
.Where(u => visible.Contains(u.Id) && u.DeletedAtUtc == null)
.ToListAsync(cancellationToken)
.ConfigureAwait(false);
return await BuildAsync(users, cancellationToken).ConfigureAwait(false);
}
/// <remarks>
/// A user with no current key is dropped rather than returned with empty key fields. The entry
/// exists to be wrapped to, and one carrying no key is something a caller would have to remember
/// to check for — which is the kind of check that gets forgotten exactly once.
/// </remarks>
private async Task<IReadOnlyList<DirectoryEntry>> BuildAsync(
List<UserAccount> users,
CancellationToken cancellationToken)
{
if (users.Count == 0)
{
return [];
}
var userIds = users.Select(u => u.Id).ToArray();
var keys = await database.UserKeys
.Where(k => userIds.Contains(k.UserId) && k.IsCurrent)
.ToListAsync(cancellationToken)
.ConfigureAwait(false);
// The log position of the statement that introduced each key, so a client can compare what
// it is told here against the append-only chain rather than taking this response on trust.
var keyIds = keys.Select(k => k.UserId).ToArray();
var sequences = await database.KeyLog
.Where(e => keyIds.Contains(e.UserId))
.GroupBy(e => new { e.UserId, e.Generation })
.Select(g => new { g.Key.UserId, g.Key.Generation, Sequence = g.Min(e => e.Sequence) })
.ToListAsync(cancellationToken)
.ConfigureAwait(false);
var entries = new List<DirectoryEntry>(users.Count);
foreach (var user in users)
{
var key = keys.Find(k => k.UserId == user.Id);
if (key is null)
{
continue;
}
var sequence = sequences
.Find(s => s.UserId == user.Id && s.Generation == key.Generation)?
.Sequence ?? 0;
entries.Add(new DirectoryEntry(
UserId: user.Id,
Email: user.Email,
DisplayName: user.DisplayName,
EncryptionPublicKey: key.EncryptionPublicKey,
SigningPublicKey: key.SigningPublicKey,
Fingerprint: key.FingerprintSha256,
KeyGeneration: key.Generation,
KeyLogSequence: sequence));
}
return entries;
}
}
@@ -104,6 +104,117 @@ internal sealed class EnrollEndpoint(ICurrentUserContext currentUser, Enrollment
}
}
/// <summary>
/// Looks up the public keys a vault key can be wrapped to.
/// </summary>
/// <remarks>
/// <para>
/// A GET with query parameters rather than a request DTO, because <c>BodyOnlyRequestBinder</c> binds
/// bodies and nothing else — deliberately, so that a query string can never overwrite a body field —
/// and this call has no body to speak of. The parameters are read one at a time, as route values are.
/// </para>
/// <para>
/// Exactly one of <c>email</c> and <c>userId</c> is expected. They are separate parameters rather than
/// one polymorphic term because they answer to different rules: an email may name anybody enrolled
/// here, an id only somebody the caller shares a team with. See <see cref="DirectoryService"/>.
/// </para>
/// </remarks>
internal sealed class LookupDirectoryEndpoint(
ICurrentUserContext currentUser,
DirectoryService directory)
: EndpointWithoutRequest<Results<Ok<IReadOnlyList<DirectoryEntry>>, ProblemHttpResult>>
{
/// <inheritdoc />
public override void Configure()
{
Get("/api/v1/directory");
// Enrolled. The answer exists to be wrapped to, and a caller with no identity key of their
// own has nothing to wrap and no signature to attribute it with.
Policies(Auth.EnrolledPolicy);
Description(b => b
.WithName("LookupDirectory")
.WithSummary("Looks up a user's published identity keys, by exact email or by id.")
.WithTags("Identity"));
}
/// <inheritdoc />
public override async Task<Results<Ok<IReadOnlyList<DirectoryEntry>>, ProblemHttpResult>> ExecuteAsync(
CancellationToken ct)
{
var user = await currentUser.GetOrProvisionAsync(ct).ConfigureAwait(false);
var email = HttpContext.Request.Query["email"].ToString();
var rawUserId = HttpContext.Request.Query["userId"].ToString();
if (!string.IsNullOrWhiteSpace(email))
{
return TypedResults.Ok(await directory.FindByEmailAsync(email, ct).ConfigureAwait(false));
}
if (Guid.TryParse(rawUserId, out var userId))
{
return TypedResults.Ok(
await directory.FindTeammatesAsync(user.Id, [userId], ct).ConfigureAwait(false));
}
// An empty result would be indistinguishable from "nobody has that address", which is a
// different fact and one a client would go on to act on.
return Problems.Coded(
StatusCodes.Status400BadRequest,
ProblemCodes.MalformedRequest,
"Supply either an exact 'email' or a 'userId'. This directory has no search.");
}
}
/// <summary>
/// Serves the append-only key log, so a client can verify a public key rather than trust one.
/// </summary>
/// <remarks>
/// Paged with <c>after</c> and <c>limit</c> on the query string, read one at a time as route values
/// are — see <see cref="LookupDirectoryEndpoint"/> for why this endpoint has no request DTO.
/// </remarks>
internal sealed class ReadKeyLogEndpoint(KeyLogService keyLog)
: EndpointWithoutRequest<Ok<KeyLogPage>>
{
/// <inheritdoc />
public override void Configure()
{
Get("/api/v1/keylog");
// Enrolled rather than authenticated, matching the directory it exists to check. Nothing here
// is secret, but a caller with no key of their own has nothing to verify against.
Policies(Auth.EnrolledPolicy);
Description(b => b
.WithName("ReadKeyLog")
.WithSummary("Reads the append-only key log, with its current head.")
.WithTags("Identity"));
}
/// <inheritdoc />
public override async Task<Ok<KeyLogPage>> ExecuteAsync(CancellationToken ct)
{
// A malformed value reads as "from the beginning" rather than as an error. The log is public
// and ordered, so the worst a bad cursor costs is a larger response — and a 400 here would
// make a client's own paging bug look like a server refusal.
_ = long.TryParse(
HttpContext.Request.Query["after"],
System.Globalization.CultureInfo.InvariantCulture,
out var after);
int? limit = int.TryParse(
HttpContext.Request.Query["limit"],
System.Globalization.CultureInfo.InvariantCulture,
out var parsed)
? parsed
: null;
return TypedResults.Ok(await keyLog.ReadAsync(after, limit, ct).ConfigureAwait(false));
}
}
/// <summary>Registers a device key so this machine can unlock without the passphrase.</summary>
/// <remarks>
/// 200 rather than 201, for the reason enrollment gives: re-registering the same public key returns the
@@ -0,0 +1,87 @@
using DodoSSH.Contracts;
using DodoSSH.Crypto;
using DodoSSH.Infrastructure;
using Microsoft.EntityFrameworkCore;
namespace DodoSSH.Api.Features.Identity;
/// <summary>
/// Serves the append-only key log.
/// </summary>
/// <remarks>
/// <para>
/// Readable by every enrolled caller, in full. That is the point of it: a log only one party can read
/// proves nothing, and the whole mechanism is that independent clients compare what they were shown.
/// Nothing here is secret — public keys, signatures over them, and hashes.
/// </para>
/// <para>
/// The server never edits this table and this service never writes to it. Appends happen in exactly
/// one place, under a deployment-wide advisory lock, inside the enrollment transaction; see
/// <see cref="EnrollmentService"/> and docs/crypto.md §7.2 for why serialising them is load-bearing.
/// </para>
/// </remarks>
internal sealed class KeyLogService(DodoDbContext database)
{
/// <summary>Largest page served, whatever a caller asks for.</summary>
/// <remarks>
/// A client verifying the chain has to read every entry in order, so paging is a transfer-size
/// concern rather than a filter. The cap is generous because skipping entries is not an option:
/// a gap breaks the link and the verification fails, correctly, on data that was fine.
/// </remarks>
private const int MaxPageSize = 500;
/// <summary>Reads entries after a sequence, with the log's current head.</summary>
internal async Task<KeyLogPage> ReadAsync(
long afterSequence,
int? limit,
CancellationToken cancellationToken)
{
var take = Math.Clamp(limit ?? MaxPageSize, 1, MaxPageSize);
var entries = await database.KeyLog
.Where(e => e.Sequence > afterSequence)
.OrderBy(e => e.Sequence)
// One more than asked for, so "is there another page" is answered by what came back
// rather than by a second count that could disagree with it.
.Take(take + 1)
.ToListAsync(cancellationToken)
.ConfigureAwait(false);
var hasMore = entries.Count > take;
if (hasMore)
{
entries.RemoveAt(entries.Count - 1);
}
var head = await database.KeyLog
.OrderByDescending(e => e.Sequence)
.Select(e => new { e.Sequence, e.Hash })
.FirstOrDefaultAsync(cancellationToken)
.ConfigureAwait(false);
return new KeyLogPage(
Entries:
[
.. entries.Select(e => new KeyLogRecord(
e.Sequence,
e.UserId,
e.Generation,
e.EncryptionPublicKey,
e.SigningPublicKey,
e.StatementSignature,
e.PreviousHash,
e.Hash,
e.CreatedAtUtc)),
],
HeadSequence: head?.Sequence ?? 0,
// The genesis predecessor for an empty log, which is the same value the first entry will
// record. A client comparing heads therefore needs no special case for "nothing yet".
Head: head?.Hash ?? KeyLogChain.CreateGenesisPreviousHash(),
HasMore: hasMore);
}
}