Files
DodoSSH/src/DodoSSH.Api/Setup/DodoOptions.cs
T
jaap-jan 4b706bc3c3 Say when a vault has moved, so nobody waits out the minute
The delta pull was cheap enough to run on a timer and the client did, once a
minute. That is fine for a machine and wrong for two people: an edit a colleague
makes is up to a minute stale, which is long enough for both of them to make it
and produce a conflict neither needed to have. Shortening the interval is the
obvious answer and the wrong one — it costs a request per client per interval
whether or not anything happened, and it converges on a busier server that is
still late.

So the server now says so. A client holds a WebSocket open at GET /api/v1/events,
subprotocol dodossh.events.v1, and gets a line down it when something it can read
has changed. ADR 0012 has the reasoning; three parts of it are worth repeating
here, because they are what everything else rests on.

**What crosses the socket is a notice, never data.** A frame names a vault and
how far its change log has got. No item, no ciphertext, not even which item it
was. The client's answer is the delta pull it would have run anyway, so there is
still exactly one code path that applies a change to a keychain, and it is not
this one. Pushing the items themselves would save a round trip and fork that path
in two, with the cursor, the merge and the tombstone rules duplicated across both
— ADR 0003 put every mutation through one write path for that reason, and this
keeps every read on one for the same one. It also makes a dropped notice
harmless, which is what lets the fan-out below be as simple as it is.

**Polling stays, and is what guarantees a pass.** The minute timer is unchanged.
A network that eats WebSockets, a server with Events:Enabled off, an older
server, a proxy that will not upgrade, a notice dropped under backpressure —
every one of those leaves a client behaving exactly as it did before this commit.
Nothing is reachable only over the socket and nothing is meant to become so;
VaultViewModel's AutoSyncInterval remark now says that where somebody changing it
will read it.

**The bearer token authorises the upgrade, unlike the relay's ticket.** Not an
inconsistency with ADR 0004: the relay's socket is a byte pipe whose whole
authorization decision — which host, which IPs, which port — is made before it
opens and never revisited, and it is the extraction seam for a process that must
hold no ACL code. This one is a view of the caller's own vault list and has to
keep answering "what may this account read" for as long as it is held. A ticket
would carry that answer in a token and be wrong the moment the account's access
changed. The two bounds that arrangement needs are met rather than waved at: the
socket is closed at the token's exp with close code 4401 and the client comes
straight back with a fresh one, and the vault set is re-resolved every few
minutes as well as on the changes known to affect it. Both bound *metadata*,
because a notice contains nothing else and reading a vault still needs a key this
server has never held.

**The fan-out.** VaultEventHub is a singleton holding the sockets this node
accepted; publishing walks them and asks each whether it cares, rather than
keeping a vault-to-subscriber index that every re-subscription would have to move
entries between under a lock publishing also takes. At a few hundred sockets per
node and an event rate bounded by how often people edit keychains, the walk is
not measurable and its races are obvious. Per-connection queues are bounded and
drop the *oldest*: a notice means "pull vault X, which is at least at sequence
N", so the newest subsumes what it displaces and the client's answer is identical
either way — which is what lets the publish path be void, never block, and never
fail.

Announced from the endpoint rather than from SyncService, and that placement is
the point: by then the push has committed and released the per-vault advisory
lock. From inside it would name a sequence no reader can see yet and would hold
the lock that serialises writers across a socket write. Only the highest
*applied* sequence, so a batch of pure conflicts announces nothing, and a
duplicate — already announced when it first landed — announces nothing either.

Grants and membership publish too, and those take the *recipient* rather than the
actor. This is what AdmitNewVaultsAsync has been apologising for since sharing
shipped — "the recipient is handed nothing, there is no push channel" — and the
README with it. A vault shared with somebody now turns up as it is shared. The
comment and the README paragraph both say what is true now, and both keep saying
that the pass is what *discovers* the vault, because a client with no socket has
to arrive at the same place.

**On the client**, VaultEventStream is really a reconnection policy wrapped round
a ClientWebSocket: a dropped socket is the ordinary case here — laptops sleep,
proxies time out, tokens expire, servers are redeployed — so nothing in it treats
a failure as exceptional, and every path ends in "wait, then dial again". A
connection that lived long enough to say hello resets the backoff, so a laptop
that woke, worked, and lost its network an hour later does not inherit a
minute-long wait it has already proved it need not take. A 4401 close skips the
backoff entirely and asks the token provider again, which is the whole reason
that close code is distinct. A server that does not advertise the events feature
gets IdleVaultEventStream, which never delivers — so IVaultServer.Events is never
null and every caller stays on one shape, because the correct behaviour without a
socket is the behaviour with a silent one.

The shell's background loop now selects between the timer and a notice, and both
waits are held across iterations. That is load-bearing rather than tidy:
PeriodicTimer permits one outstanding WaitForNextTickAsync and throws on a
second, and an abandoned channel read stays registered and consumes the next
notice written. Either defect leaves the first notice working and every one after
it silently lost, which is why NoticesKeepWakingTheLoop_NotJustTheFirst pushes
three and not one. Notices are coalesced over a quarter of a second, so one
person's save — a host and its log entry are two items — and a colleague clearing
a folder each cost one pass rather than a dozen.

**The kind is a string, not an enum**, and that is a compatibility decision.
UseStringEnumConverter throws on a value it does not know, so a newer server
sending a kind an older client had never heard of would not add an unreadable
frame — it would break that client's socket outright. A string is ignored
instead. ProblemCodes is the same shape for the same reason.

**Tested on both sides, through the real pipeline.** The endpoint suite opens a
genuine socket against TestServer and proves a push produces a notice, that
another account's push does not reach it, that a ping is answered, and that a
frame this server cannot parse does not end the connection. Two of those assert
on *ordering* rather than on absence within a timeout — the stranger's write goes
first, so a socket that leaked would have announced it before the one the test
waits for — because "nothing arrived in two seconds" is a test that passes on a
slow machine for the wrong reason. And ANoticeCarriesNoCiphertext asserts on the
bytes that crossed the wire rather than on the record's fields, since the latter
would only prove that this type has no payload member, which is a tautology; the
former is what catches a field added later without anybody thinking about
disclosure.

The client suite drives VaultEventStream through an injected connector, because
the one thing a test cannot do to a real network is make it fail on cue — and
failure is the entire subject. The shell suite proves a notice produces a pull
inside ten seconds against a sixty-second timer, so the timer cannot be what
caused it.

**Two limits, stated rather than left to be discovered.** Fan-out is in-process,
so a deployment running more than one API replica only pushes for writes its own
replica handled and the rest arrive on the timer. IVaultEventPublisher is the
seam a PostgreSQL LISTEN/NOTIFY backplane implements and it is deliberately not
implemented: an untested backplane is worse than a documented gap, and multiple
replicas degrade to the behaviour before this commit rather than breaking. And a
client is notified of its own writes; it pushed, so it already pulled, and the
extra pass finds nothing. Suppressing that echo correctly needs a per-device
identity on the socket, and the same user's other machines must still be told.

Manual checks phase 15 covers what no test here can reach, which is the network
in between: a proxy that will not upgrade, one that drops an idle socket without
telling either end, a laptop lid, a token expiring. Every one of those is
invisible inside a test host, and every check there passes only if the change
arrives quickly *and* still arrives with the socket taken away.

ADR 0012 also fixes one thing about the shared terminal session this is the
transport for, so it need not be renegotiated later: session data will be binary
frames on this same socket, because base64 in a JSON envelope is the wrong shape
for the one payload here that is continuous rather than occasional. Two questions
it explicitly does not answer by implication — whether those bytes go through the
API at all, and what end-to-end encryption means when the second party watches a
stream rather than holding a key — are ADR 0001 questions and get their own
decision.

1512 tests pass. DodoSSH.SystemTests was not run — it needs the whole compose
stack — so the end-to-end path is unverified for this change beyond what the
manual checks describe.
2026-08-04 16:37:41 +02:00

299 lines
13 KiB
C#

using System.ComponentModel.DataAnnotations;
namespace DodoSSH.Api.Setup;
/// <summary>Identity provider settings.</summary>
/// <remarks>
/// Provider-agnostic by design. Claim names differ between providers — Keycloak nests roles at
/// <c>realm_access.roles</c>, Entra uses <c>roles</c> and <c>groups</c>, Auth0 namespaces them,
/// Authentik uses <c>groups</c> — so the mapping is configuration rather than code.
/// </remarks>
public sealed class OidcOptions
{
/// <summary>Configuration section name.</summary>
public const string SectionName = "Oidc";
/// <summary>Issuer URL. Discovery and JWKS are fetched from here.</summary>
[Required]
[Url]
public string Authority { get; set; } = string.Empty;
/// <summary>Expected audience of access tokens.</summary>
[Required]
public string Audience { get; set; } = string.Empty;
/// <summary>Public client identifier the desktop app uses.</summary>
[Required]
public string ClientId { get; set; } = string.Empty;
/// <summary>Scopes the client should request.</summary>
public IList<string> Scopes { get; } = ["openid", "profile", "email", "offline_access"];
/// <summary>
/// Registered loopback redirect pattern. RFC 8252: a native client uses a loopback redirect on
/// an ephemeral port with the system browser, never a custom scheme and never an embedded
/// browser, so the user can see the real address bar.
/// </summary>
/// <remarks>
/// No wildcard in the port. RFC 8252 requires a native client to use an ephemeral loopback port, and
/// providers implement that by ignoring the port when the host is a loopback literal — Keycloak
/// included. Writing <c>http://127.0.0.1:*/callback</c> looks more explicit and is worse: Keycloak
/// parses the <c>*</c> as a literal port and rejects every real redirect with "Invalid parameter:
/// redirect_uri". Pinning the path is the part that matters, since it stops another local process
/// having a code delivered somewhere else.
/// </remarks>
public string LoopbackRedirectPattern { get; set; } = "http://127.0.0.1/callback";
/// <summary>Whether HTTPS metadata is required. Only ever false for local development.</summary>
public bool RequireHttpsMetadata { get; set; } = true;
/// <summary>
/// Whether a new identity-provider subject may be linked to an existing account by matching
/// email.
/// </summary>
/// <remarks>
/// Defaults to false, and must stay that way. If an attacker can obtain a token from any
/// configured provider carrying a victim's email address, email linking hands them the
/// victim's account.
/// </remarks>
public bool AllowEmailLinking { get; set; }
/// <summary>Claim type holding the user's email.</summary>
public string EmailClaim { get; set; } = "email";
/// <summary>Claim type holding the user's display name.</summary>
public string NameClaim { get; set; } = "name";
/// <summary>
/// Claim type asserting that the provider has verified the user's email.
/// </summary>
/// <remarks>
/// <para>
/// Read for exactly one purpose: deciding whether a pending team invitation addressed to that
/// email may be claimed. Nothing else in this server trusts the email claim for anything, and
/// <see cref="AllowEmailLinking"/> records why — a token from any configured provider carrying a
/// victim's address must not confer access to anything of theirs. An invitation is access, so it
/// needs the same bar.
/// </para>
/// <para>
/// <b>Absence is a refusal, not a default.</b> A provider that does not send this claim leaves
/// every invitation pending for ever, which is visible on the teams screen and diagnosable in the
/// log. There is deliberately no option to trust an unverified address instead: a flag that exists
/// is a flag somebody turns on for the afternoon their provider is misconfigured, and this is the
/// one it must not be possible to turn on.
/// </para>
/// </remarks>
public string EmailVerifiedClaim { get; set; } = "email_verified";
}
/// <summary>Schema management.</summary>
public sealed class DatabaseOptions
{
/// <summary>Configuration section name.</summary>
public const string SectionName = "Database";
/// <summary>
/// Whether the API applies pending migrations as it starts.
/// </summary>
/// <remarks>
/// <para>
/// On by default, because the alternative asks every self-hosted operator to run a second thing in
/// the right order and gives them an instance that boots and then fails readiness when they do not.
/// The schema and the code that expects it ship in the same image, so the image is the natural place
/// for the two to be reconciled.
/// </para>
/// <para>
/// Turn it off where the deployment already owns schema changes: a migrator job in the release
/// pipeline, a rollout where the new code must run against the old schema first, or a database user
/// that is deliberately denied DDL. With it off the behaviour is exactly what it was before this
/// setting existed — pending migrations fail readiness and say which, and nothing repairs itself.
/// </para>
/// </remarks>
public bool AutoMigrate { get; set; } = true;
}
/// <summary>Relay settings. See ADR 0004.</summary>
public sealed class RelayOptions
{
/// <summary>Configuration section name.</summary>
public const string SectionName = "Relay";
/// <summary>Whether this deployment offers a relay at all.</summary>
public bool Enabled { get; set; }
/// <summary>Public WebSocket URL clients should dial. Required when enabled.</summary>
public string? WebSocketUrl { get; set; }
/// <summary>
/// Whether RFC1918 and other private ranges may be dialled.
/// </summary>
/// <remarks>
/// Defaults to true, unlike a typical SSRF allow-list, because reaching private
/// infrastructure is the entire purpose of a self-hosted SSH tool. The control that matters is
/// the ACL: only hosts in a vault the caller holds Connect on can be dialled at all. Loopback,
/// link-local and cloud metadata ranges are denied unconditionally and are not configurable.
/// </remarks>
public bool AllowPrivateNetworks { get; set; } = true;
/// <summary>Maximum concurrent sessions per user.</summary>
[Range(1, 1000)]
public int MaxConcurrentSessionsPerUser { get; set; } = 10;
/// <summary>Maximum concurrent sessions per node.</summary>
[Range(1, 100_000)]
public int MaxConcurrentSessionsTotal { get; set; } = 200;
/// <summary>Maximum session lifetime.</summary>
public TimeSpan MaxSessionDuration { get; set; } = TimeSpan.FromHours(12);
/// <summary>Idle timeout.</summary>
public TimeSpan IdleTimeout { get; set; } = TimeSpan.FromMinutes(10);
/// <summary>Timeout for the outbound TCP connect.</summary>
public TimeSpan ConnectTimeout { get; set; } = TimeSpan.FromSeconds(5);
/// <summary>Ticket lifetime. Deliberately tiny: single-use and single-host.</summary>
public TimeSpan TicketLifetime { get; set; } = TimeSpan.FromSeconds(30);
/// <summary>How long to keep draining live sessions during shutdown.</summary>
public TimeSpan DrainTimeout { get; set; } = TimeSpan.FromSeconds(30);
}
/// <summary>Realtime push settings. See ADR 0012.</summary>
/// <remarks>
/// Every one of these bounds a socket rather than a feature: with the whole thing off, or every cap
/// met, clients synchronise on their timer exactly as they did before this existed. That is what
/// makes it safe for an operator to turn any of them down.
/// </remarks>
public sealed class EventsOptions
{
/// <summary>Configuration section name.</summary>
public const string SectionName = "Events";
/// <summary>
/// Whether this deployment pushes vault changes at all.
/// </summary>
/// <remarks>
/// On by default, unlike the relay: this needs no outbound network, no target resolution and no
/// new trust, and a deployment behind a proxy that will not upgrade should say so here rather than
/// have every client discover it by failing.
/// </remarks>
public bool Enabled { get; set; } = true;
/// <summary>Maximum concurrent sockets per node.</summary>
[Range(1, 100_000)]
public int MaxConnectionsTotal { get; set; } = 500;
/// <summary>
/// Maximum concurrent sockets per account.
/// </summary>
/// <remarks>
/// Per account rather than per device, because the server cannot see a device here. Eight is a
/// laptop, a desktop, a phone and room to reconnect before the old socket has been reaped.
/// </remarks>
[Range(1, 1000)]
public int MaxConnectionsPerUser { get; set; } = 8;
/// <summary>
/// How many notices may be queued for one socket before the oldest are dropped.
/// </summary>
/// <remarks>
/// A notice names a vault and a position, so a newer one subsumes the one it replaces. The depth
/// therefore buys smoothness over a brief stall and nothing else — losing the tail of a burst
/// costs a client nothing, because the newest notice still says to pull.
/// </remarks>
[Range(1, 10_000)]
public int OutboundQueueDepth { get; set; } = 64;
/// <summary>
/// How often the server pings an idle socket.
/// </summary>
/// <remarks>
/// Below the sixty seconds most reverse proxies idle out at, because a silent socket that a proxy
/// has quietly dropped is indistinguishable from a quiet one until something is sent down it.
/// </remarks>
public TimeSpan HeartbeatInterval { get; set; } = TimeSpan.FromSeconds(30);
/// <summary>
/// How often an open socket re-reads which vaults its account may follow.
/// </summary>
/// <remarks>
/// The backstop for a grant withdrawn mid-connection. Grants and membership changes publish
/// immediately, so this is what covers the paths that do not — and what bounds the window if one
/// is ever added without remembering to.
/// </remarks>
public TimeSpan AccessRefreshInterval { get; set; } = TimeSpan.FromMinutes(5);
/// <summary>
/// The longest any one socket may live, regardless of its token.
/// </summary>
/// <remarks>
/// A socket normally ends at its access token's expiry, which is far shorter. This is the bound
/// for a provider that issues long-lived tokens, and it is what makes "no connection is older than
/// this" a property of the server rather than of the identity provider's configuration.
/// </remarks>
public TimeSpan MaxConnectionDuration { get; set; } = TimeSpan.FromHours(12);
}
/// <summary>Sync protocol limits.</summary>
public sealed class SyncOptions
{
/// <summary>Configuration section name.</summary>
public const string SectionName = "Sync";
/// <summary>Maximum operations in one push. Enforced before the transaction opens.</summary>
[Range(1, 10_000)]
public int MaxOperationsPerPush { get; set; } = 500;
/// <summary>Maximum total ciphertext in one push.</summary>
[Range(1024, 1024L * 1024 * 1024)]
public long MaxPayloadBytes { get; set; } = 8L * 1024 * 1024;
/// <summary>Maximum ciphertext for a single item.</summary>
[Range(1024, 1024L * 1024 * 1024)]
public long MaxItemPayloadBytes { get; set; } = 256L * 1024;
/// <summary>Default page size for a pull.</summary>
[Range(1, 10_000)]
public int DefaultPullLimit { get; set; } = 200;
/// <summary>Maximum page size for a pull.</summary>
[Range(1, 10_000)]
public int MaxPullLimit { get; set; } = 1000;
/// <summary>How long tombstones are retained before collection.</summary>
[Range(1, 3650)]
public int TombstoneRetentionDays { get; set; } = 90;
/// <summary>
/// Key used to sign sync cursors, base64.
/// </summary>
/// <remarks>
/// Cursors are integrity-tagged so a tampered one is rejected rather than silently
/// mis-serving. Generated per deployment; losing it only invalidates in-flight cursors, since
/// clients simply resync from the beginning.
/// </remarks>
public string? CursorSigningKey { get; set; }
}
/// <summary>Server identity and client compatibility.</summary>
public sealed class ServerOptions
{
/// <summary>Configuration section name.</summary>
public const string SectionName = "Server";
/// <summary>Public base URL clients should use for API calls.</summary>
[Required]
[Url]
public string PublicBaseUrl { get; set; } = string.Empty;
/// <summary>
/// Oldest client version this server will serve.
/// </summary>
/// <remarks>
/// Self-hosted means version skew is normal, not exceptional. A client below this must be
/// shown a clear remediation screen rather than failing obscurely mid-sync.
/// </remarks>
public string? MinClientVersion { get; set; }
}