gunnar_ssh/server.rs
1//! The russh server: authentication, the exec dispatch, and the channel
2//! hand-off (the ACL model, the two-listener split).
3//!
4//! # The shape of a connection
5//!
6//! 0. **`auth_none`**, the anonymous read path, and the only place
7//! gunnar reads the SSH username. See below.
8//! 1. **`auth_publickey`**: russh has already verified that the client owns the
9//! offered key. gunnar fingerprints it (SHA-256 over the wire blob, OpenSSH's
10//! printed form, [`crate::access::fingerprint_of_key`]) and asks
11//! `gunnar-core`'s identity table through [`Control`]. The SSH *username* is
12//! logged and otherwise ignored: identity comes from the key, so
13//! `git@host:ns/repo.git` works and `git` means nothing (the ACL model).
14//! 2. **`channel_open_session`**. The channel is kept, because the exec request
15//! arrives as a separate message that only carries a [`ChannelId`], and the
16//! stream can only be taken from the `Channel` itself. A watchdog is armed
17//! here so a session that authenticates and then never execs cannot sit on
18//! the connection.
19//! 3. **`env_request`**, answered against [`ENV_ALLOWLIST`], which holds
20//! exactly one name: `GIT_PROTOCOL`. Everything else is refused. See below.
21//! 4. **`exec_request`**: [`Dispatch::authorise`] parses, resolves and checks
22//! the grant. Only then is the channel's stream handed to [`GitTransport`].
23//! 5. **everything else**. `shell_request`, `subsystem_request`,
24//! `pty_request` and `x11_request` are answered with a channel failure.
25//! **No shell, ever.**
26//!
27//! # Why the transport is spawned and not awaited
28//!
29//! russh calls handler methods from the session's own read loop (see
30//! `russh::server::Session::run`). Awaiting a whole clone inside `exec_request`
31//! would stop the loop that has to deliver the client's bytes to the channel;
32//! the transfer would deadlock on its first read. russh's own `sftp_server`
33//! example awaits inline; gunnar does not.
34//!
35//! # The exit status, and why the channel is split rather than consumed
36//!
37//! `Channel::into_stream()` wraps the channel in russh's `ChannelCloseOnDrop`,
38//! which spawns a task sending `ChannelMsg::Close` when the transport lets the
39//! stream go. That `Close` raced the `exit-status` the server sent next, and
40//! won often enough that a *successful* push reported failure. Measured
41//! 2026-08-03: a complete 244-byte advertisement delivered with `ssh` exiting
42//! **255**. See [`crate::channel`].
43//!
44//! The channel is therefore `split()` instead. The read half becomes an owned
45//! [`ChannelReader`], the write half stays with the server, and `exit-status`
46//! and `close` go out through **the same sender the data went through**, in
47//! order, after the transport has finished with it. Nothing sleeps and nothing
48//! races.
49//!
50//! # One span per connection, and what hangs off it
51//!
52//! ```text
53//! ssh.connection { conn, peer, principal, repo } gunnar::ssh
54//! └── git.transfer { service, access } gunnar::git
55//! ├── git.upload_pack | git.receive_pack gunnar::git
56//! └── policy.gate { ref_name } gunnar::policy
57//! ```
58//!
59//! `principal` and `repo` are declared empty when the connection opens and
60//! **recorded** when `auth_publickey` and `exec_request` learn them, so a line
61//! emitted at any depth carries all four fields without any call site restating
62//! them. That is the difference from what was here before: connection identity
63//! was an ad-hoc `?self.peer` copy-pasted to fourteen call sites, there was no
64//! id at all, and two lines from the same connection could not be tied
65//! together.
66//!
67//! Two hand-offs would drop the span if they were not made explicit, and each
68//! is a place where an operator would silently lose half a connection:
69//!
70//! * `tokio::spawn`: the exec watchdog and the transfer task both take
71//! `.instrument(span)`, because a spawned task does not inherit a
72//! thread-local span;
73//! * `spawn_blocking`: `gunnar-cli`'s `WireTransport::serve` captures
74//! `Span::current()` and enters it on the blocking thread, which is where the
75//! whole git conversation actually happens.
76//!
77//! # How an anonymous session arrives, and why it is `auth_none` on one
78//! # username
79//!
80//! SSH has no unauthenticated mode: a client must complete *some* userauth
81//! method before it may open a channel. Three shapes were available.
82//!
83//! | | why not |
84//! |---|---|
85//! | accept `none` for **every** username | **This is the one that would break the server.** OpenSSH's client always sends a `none` request first, to learn the method list. A server that answers it with SUCCESS authenticates *every* stock client as anonymous before it ever offers its key, so every existing push would start failing, and every existing user would silently lose their identity. Measured against the russh dispatch: `server/encrypted.rs` calls `auth_none` on that first probe regardless of the advertised `methods`. |
86//! | a **well-known published key** | The anonymous-FTP shape. It works, but a stranger has to obtain a key file before they can clone, which is worse than the problem it solves, and gunnar would then hold a key whose private half is public in the same table that authenticates real users. |
87//! | **`none`, on one reserved username** | Taken. |
88//!
89//! `ssh://anonymous@host/ns/repo.git` gets the `none` method accepted and a
90//! session whose principal is
91//! [`Principal::anonymous`](gunnar_core::Principal::anonymous). Every other
92//! username gets `none` refused, exactly as russh's default handler refused it
93//! before this existed, and the client falls through to publickey unchanged.
94//!
95//! **Why it cannot become a bypass**, in the order the objections come:
96//!
97//! * *Does it weaken private repositories?* No. The username selects the
98//! authentication method; the **authorisation** answer still comes from
99//! `AuthTable::may` (the ACL model), where the anonymous principal is one rule, `Read` on
100//! `Public`, and is refused everything else including `may_namespace` and
101//! `may_server`. There is no second ACL (one implementation).
102//! * *Can a caller claim to be someone by picking a username?* No. The
103//! anonymous principal is the **only** identity a username can select, it is
104//! never in the identity table, [`Principal::new`] and
105//! `AuthTable::add_principal` refuse its id, so no key and no grant can ever
106//! attach to it.
107//! * *Can an authenticated user be silently downgraded?* No. `none` is refused
108//! for their username, so nothing changes for them; and a user who *does*
109//! type `anonymous@` asked for strictly less access, which is not an
110//! escalation.
111//! * *Does the username now reach an authorisation decision, against the ACL model?* It
112//! reaches exactly one, in the direction of *removing* everything. The ACL model's
113//! rule exists so that a username cannot be used to become somebody; this
114//! uses it to become nobody.
115//!
116//! **`none` is not advertised** in [`RusshConfig::methods`], which stays
117//! publickey-only. Advertising it would tell every client that `none` is
118//! available when it is available only for one name (the failure list is
119//! supposed to be true), and russh calls `auth_none` on the client's opening
120//! probe either way, which is the only place it is ever needed.
121//!
122//! [`SshConfig::allow_anonymous`](crate::SshConfig::allow_anonymous) closes the
123//! whole path at the listener for an appliance that wants it shut.
124//!
125//! # `GIT_PROTOCOL`, and why it is an allowlist of one
126//!
127//! A git client announces protocol v2 over SSH by sending
128//! `GIT_PROTOCOL=version=2` as a channel environment request. Refusing every
129//! `env_request`, which this server used to do, meant every session fell back
130//! to v0. Stock `git` copes; `gix`'s blocking v0 client does not, because it
131//! requires `multi_ack_detailed` and `gunnar_wire::caps` correctly declines to
132//! advertise a capability it does not implement. The measured consequence was
133//! that `gunnar clone` could not clone from `gunnar serve` at all.
134//!
135//! Accepting the variable is **not** the same as accepting an environment. An
136//! SSH server that passes arbitrary client-supplied names through has handed
137//! the client `LD_PRELOAD`, `PATH` and every other lever there is. [`ENV_ALLOWLIST`]
138//! names the one variable gunnar reads; every other name is refused with a
139//! channel failure, exactly as before. The accepted value is not an input to
140//! any authorisation decision: it reaches [`ServiceRequest::git_protocol`] and
141//! nothing else, and it only ever selects the *framing* the wire answers in.
142
143use std::collections::HashMap;
144use std::net::SocketAddr;
145use std::sync::atomic::{AtomicBool, Ordering};
146use std::sync::Arc;
147use std::time::Duration;
148
149/// How long [`BoundServer::shutdown`] waits for sessions to answer the
150/// disconnect before it aborts the listener. Longer than the gRPC grace (2 s):
151/// a git transfer mid-pack deserves a moment to finish its write.
152pub const SSH_SHUTDOWN_GRACE: Duration = Duration::from_secs(10);
153
154use russh::keys::ssh_key::PublicKey;
155use russh::server::{Auth, Config as RusshConfig, Handler, Msg, Server, Session};
156use russh::{Channel, ChannelId, Disconnect, MethodKind, MethodSet};
157use tokio::net::TcpListener;
158use tokio::task::JoinHandle;
159use tracing::Instrument;
160
161use gunnar_core::observe::{RequestId, ServerMetrics, TARGET_GIT, TARGET_SSH};
162use gunnar_core::RepoRef;
163
164use crate::access::{fingerprint_of_key, Access, Fingerprint, Principal};
165use crate::admission::{Admission, AdmissionStats};
166use crate::channel::{serve_until_session_ends, session_ended_error, session_over, ChannelReader, SessionBound};
167use crate::command::GitService;
168use crate::command::{self, CommandError};
169use crate::config::{SshConfig, ANONYMOUS_SSH_USER};
170use crate::control::Control;
171use crate::governor::OpClass;
172use crate::seam::{Delivery, GitTransport, ServiceRequest};
173
174// ───────────────────────────────────────────────────────────────────────────
175// The authorisation decision, without any SSH in it
176// ───────────────────────────────────────────────────────────────────────────
177
178/// Why an exec request was not served.
179#[derive(Debug, thiserror::Error)]
180pub enum DispatchError {
181 /// The command did not parse. **The `bash` case, and every other one.**
182 #[error("{0}")]
183 Command(#[from] CommandError),
184 /// The repository does not exist.
185 #[error("no such repository: {0}")]
186 NoSuchRepo(RepoRef),
187 /// The principal does not hold enough access.
188 #[error("{principal} holds {held} on {repo}, needs {needed}")]
189 Denied {
190 /// Who asked.
191 principal: String,
192 /// What they asked for.
193 repo: RepoRef,
194 /// What the command requires.
195 needed: Access,
196 /// What they actually hold, rendered as `none` when they hold nothing.
197 held: String,
198 },
199 /// **This box is a read-only STANDBY** and the write is refused.
200 ///
201 /// A distinct arm, not a [`DispatchError::Denied`]: the writer holds the
202 /// grant — on a primary this push would land — so "you do not have access"
203 /// would be a lie that sends them to an administrator about permissions.
204 /// The honest sentence is that this box does not take client writes; push
205 /// to the primary. It is only ever reached by a principal who already
206 /// passed the grant check, so it leaks no repository the writer could not
207 /// already see.
208 #[error("{principal}: this box is a standby; writes go to the primary ({repo})")]
209 Standby {
210 /// Who asked.
211 principal: String,
212 /// The repository they tried to write.
213 repo: RepoRef,
214 /// The box is a browse replica, so the
215 /// refusal says so: a stranger who found a public repository here and
216 /// tried to push to it should learn what this box is, not merely that
217 /// it is frozen.
218 browse: bool,
219 },
220 /// **This box is a TWIN and serves no git at all** — not a read, not a
221 /// write, not to anybody (2026-09-21, lane T4).
222 ///
223 /// Its own arm and not a [`DispatchError::Standby`], because a standby is a
224 /// box that serves reads and refuses writes, and a twin is a box that
225 /// serves NEITHER: `serve.rs` says why in one line — *a read would grow the
226 /// caches the twin must not hold* — and the twin's whole value is that its
227 /// disk holds the primary's log and nothing derived.
228 ///
229 /// **Why this exists at the door rather than only at the bind.** The bind
230 /// is chosen ONCE, in `serve::start`, from `stores.is_twin()` at that
231 /// instant. A box becomes a twin over the wire, through
232 /// `Bootstrap.BecomeTwin`, long after that — and the owner's one-medium
233 /// ruling makes that the ONLY way it happens, because a twin is now
234 /// installed from the same image as a main with no per-box parameter to
235 /// say which it is. MEASURED under KVM by lane T3, 2026-09-21: a box
236 /// conferred at runtime kept `0.0.0.0:2222` bound for the rest of its life,
237 /// the `this box is a TWIN` warning never printed, and its volume ended up
238 /// holding five `objects.exploded` cache files. A socket that cannot be
239 /// moved without a restart is not a reason to serve git from it in the
240 /// meantime.
241 #[error("{principal}: this box is a TWIN; it serves no git to anyone — clone and push to the primary it follows ({repo})")]
242 Twin {
243 /// Who asked.
244 principal: String,
245 /// What they asked for.
246 repo: RepoRef,
247 },
248 /// **Anonymous reads are not served here** (`--anonymous refuse`); the
249 /// browse replica serves them, and `browse_host` names it when the
250 /// operator did. Raised before the repository is even looked up, so a
251 /// stranger learns nothing about what exists on the primary.
252 #[error("anonymous reads are refused on this box ({repo}); browse host: {browse_host:?}")]
253 AnonymousElsewhere {
254 /// The repository the stranger asked for.
255 repo: RepoRef,
256 /// Where anonymous reads are served, when the operator named it.
257 browse_host: Option<String>,
258 },
259 /// **The gate chain refuses this**: the disk is under its floor (every
260 /// build), or (`metered`) a Suspended or Retention tenant's push or LFS
261 /// upload, an anonymous read of a lapsed tenant's public repository, or a
262 /// push at the pack quota.
263 ///
264 /// Its own arm for the same reason [`DispatchError::Standby`] is one: the
265 /// caller holds the grant, so "you do not have access" would be a lie
266 /// that sends a paying customer to an administrator about permissions.
267 /// The honest sentence names the fact — free bytes and the floor, or the
268 /// state, the date and where to renew — and it is only ever reached AFTER
269 /// the grant check admitted the request, so it leaks nothing about a
270 /// repository the caller could not already see.
271 #[error("{namespace}: {line}")]
272 Plan {
273 /// The tenant.
274 namespace: String,
275 /// What the client is told, verbatim.
276 line: String,
277 },
278 /// The identity table or the catalog could not be read.
279 ///
280 /// **Deliberately not folded into [`DispatchError::Denied`].** The tables
281 /// live in storage (the Arrow-IPC ref log) and a read can fail; answering a storage
282 /// fault with "you do not have access" would turn an outage into a silent,
283 /// convincing permission denial that nobody would think to investigate.
284 /// The ACL model is explicit that `may(...)` returns `Result<bool>` for this
285 /// reason, and this variant is where that `Result` lands.
286 #[error("the control plane could not answer: {0}")]
287 Store(#[from] gunnar_core::Error),
288}
289
290impl DispatchError {
291 /// What the client is told.
292 ///
293 /// `None` means "answer with a channel failure and say nothing": the
294 /// request was not even a git command, so there is no git client on the
295 /// other end that would understand a pkt-line.
296 ///
297 /// **"No such repository" and "no permission" produce the same string on
298 /// purpose.** A client that could tell them apart could enumerate private
299 /// repositories one guess at a time. The server log keeps the distinction;
300 /// the wire does not.
301 ///
302 /// Those two arms are **one arm**, and were two identical `format!`s until
303 /// 2026-08-05. That is the twinning one implementation forbids, and this is the case it
304 /// forbids it for: the property is that the two strings are equal, so two
305 /// copies of the string put the property one careless edit away from being
306 /// false, in the direction where the wire starts leaking which private
307 /// repositories exist.
308 /// `a_missing_repository_and_a_forbidden_one_are_one_string_to_the_client`
309 /// guards it from the far side of a real session; this makes the guard hard
310 /// to need.
311 pub fn client_message(&self) -> Option<String> {
312 match self {
313 // A verb gunnar knows and refuses BY NAME gets its sentence; the
314 // rest of the parse failures are not git clients at all.
315 DispatchError::Command(CommandError::NotServed { verb, why }) => {
316 Some(format!("{verb}: {why}"))
317 }
318 DispatchError::Command(_) => None,
319 DispatchError::NoSuchRepo(repo) | DispatchError::Denied { repo, .. } => Some(format!(
320 "repository not found, or you do not have access: {repo}"
321 )),
322 // A standby refusal is told plainly — the writer is authorised, so
323 // there is no repository to hide from them, and "push to the
324 // primary" is the one thing they need to hear to succeed.
325 // A twin refusal is told plainly for the same reason, and it is told
326 // to EVERYONE including a stranger: it names no repository and
327 // reveals nothing this box holds — "this is a twin" is a fact about
328 // the box, not about its contents.
329 DispatchError::Twin { .. } => Some(
330 "this box is a TWIN: it holds a copy of the primary's transaction log and serves \
331 no git to anyone, read or write. Clone and push to the primary it follows"
332 .to_string(),
333 ),
334 DispatchError::Standby { browse: false, .. } => {
335 Some("this box is a standby; push to the primary".to_string())
336 }
337 DispatchError::Standby { browse: true, .. } => Some(
338 "this box is a browse replica: it serves public repositories read-only and \
339 takes no writes; push to the primary"
340 .to_string(),
341 ),
342 DispatchError::AnonymousElsewhere {
343 browse_host: Some(host),
344 repo,
345 } => Some(format!(
346 "anonymous reads are served by the browse replica, not here: clone \
347 {repo} from {host} (or authenticate with a registered key)"
348 )),
349 DispatchError::AnonymousElsewhere {
350 browse_host: None, ..
351 } => Some(
352 "this server does not serve anonymous reads; authenticate with a registered \
353 key, or use the browse replica"
354 .to_string(),
355 ),
356 // The gate's refusal is told in full: the state, the date and the
357 // URL are the three things a lapsed tenant needs to get going again,
358 // and the free bytes and the floor are what a full box's operator
359 // needs; hiding any of them would turn a fact into a support ticket.
360 DispatchError::Plan { line, .. } => Some(line.clone()),
361 // A fault, not a decision. The client is told the server broke,
362 // because telling it "you do not have access" would be a lie that
363 // sends the user to their administrator about permissions.
364 DispatchError::Store(_) => {
365 Some("the gunnar control plane is unavailable; try again".to_string())
366 }
367 }
368 }
369}
370
371/// Parse → resolve → check, with no SSH anywhere in it.
372///
373/// Kept separate from the [`Handler`] so the security decision can be tested
374/// directly, exhaustively and without a handshake, and so there is exactly one
375/// place where it is made.
376#[derive(Clone, Debug)]
377pub struct Dispatch {
378 control: Control,
379}
380
381impl Dispatch {
382 /// Build a dispatch over the control plane.
383 pub fn new(control: Control) -> Self {
384 Dispatch { control }
385 }
386
387 /// The control plane this dispatch authenticates and authorises against.
388 pub fn control(&self) -> &Control {
389 &self.control
390 }
391
392 /// Decide whether `principal` may run `raw` on this server.
393 ///
394 /// Parse (which includes the sandbox), resolve, then check the grant. A
395 /// storage failure at either lookup comes back as
396 /// [`DispatchError::Store`] rather than as a denial. See
397 /// [`crate::control`].
398 ///
399 /// **The client's environment is not a parameter here, and must not
400 /// become one.** The returned [`ServiceRequest`] carries
401 /// `git_protocol: None`; the handler attaches the allowlisted value with
402 /// [`ServiceRequest::with_git_protocol`] *after* this decision has already
403 /// been made, so there is no path by which anything the client typed into
404 /// its environment can reach the grant check.
405 pub fn authorise(
406 &self,
407 principal: &Principal,
408 key_fingerprint: Option<&Fingerprint>,
409 raw: &[u8],
410 ) -> Result<ServiceRequest, DispatchError> {
411 let parsed = command::parse(raw)?;
412 self.authorise_service(principal, key_fingerprint, parsed.service, parsed.repo)
413 }
414
415 /// The same decision, entered from a **URL path** rather than an exec line.
416 ///
417 /// Smart HTTP does not send `git-upload-pack '<path>'`; it sends
418 /// `POST /<path>/git-upload-pack`. The verb and the path arrive already
419 /// separated, and the path has no shell quoting on it, so there is nothing
420 /// for [`command::parse`] to do — but everything **after** the parse is
421 /// identical and must stay identical: resolve, ask the ACL, and refuse in
422 /// the one way that does not tell a caller whether a repository exists.
423 ///
424 /// So this is where that decision lives and [`Dispatch::authorise`] is now
425 /// a parser in front of it. Two entry points, one answer (one implementation). A second
426 /// copy of this in `gunnar-http` is precisely the thing that ends with SSH
427 /// and HTTP disagreeing about who may push, and the disagreement being
428 /// found by whoever pushes.
429 ///
430 /// `repo` is a [`RepoRef`], which is to say it has already been through
431 /// [`gunnar_core::resolve_repo_path`]. The sandbox is not optional on this
432 /// path either: the caller cannot construct a `RepoRef` without it.
433 pub fn authorise_service(
434 &self,
435 principal: &Principal,
436 key_fingerprint: Option<&Fingerprint>,
437 service: GitService,
438 path: RepoRef,
439 ) -> Result<ServiceRequest, DispatchError> {
440 let required = service.required_access();
441 // **A TWIN serves no git**, before anything else is asked — before the
442 // anonymous policy, before the catalog, before the grant. A read on a
443 // twin grows exactly the caches the twin exists not to hold, and the
444 // box's own `browse` flag (which `become_twin` sets) would otherwise
445 // OVERRIDE `--anonymous refuse` and serve a stranger. This is a live
446 // read of the same flag `ServerStores` flips, so the refusal begins the
447 // instant `Bootstrap.BecomeTwin` returns and does not wait for a
448 // restart to move the listener.
449 if self.control.is_twin() {
450 return Err(DispatchError::Twin { principal: principal.id.clone(), repo: path });
451 }
452 // **`--anonymous refuse`** (the browse replica), before the catalog is consulted:
453 // a stranger on a primary that has a browse replica is sent there, and
454 // learns nothing about what this box holds on the way.
455 if principal.id == gunnar_core::ANONYMOUS_PRINCIPAL_ID && self.control.refuses_anonymous() {
456 return Err(DispatchError::AnonymousElsewhere {
457 repo: path,
458 browse_host: self.control.browse_host().map(str::to_owned),
459 });
460 }
461 let (repo, prospective) = match self.control.resolve(&path)? {
462 Some(repo) => (repo, false),
463 // The repository does not exist. For exactly one shape of request
464 // — a PUSH, by a principal the control plane already permits to
465 // create repositories here — absence is the first-repository door
466 // rather than a refusal: the repository is created and the push
467 // proceeds through the unchanged grant check below.
468 //
469 // # Why a door here, and not a fourth verb or the control plane
470 //
471 // The shipped appliance runs `--no-grpc` (gRPC v1 is
472 // unauthenticated, loopback-only), has no shell by construction,
473 // and its exec surface is three git verbs that all want a
474 // repository — so after `--admin-key` enrolled the bootstrap
475 // admin (a8ba0665), the admin could authenticate and then do
476 // NOTHING, forever (measured under KVM, 2026-08-25). The
477 // alternatives lost on the code, not on taste:
478 //
479 // * **a create verb** would be a wire surface no git client
480 // speaks, would need its own client incantation, and does not
481 // fit the dispatch's own shape: `SERVICES` carries per-service
482 // *repo grant levels* and this decision compares levels — a
483 // verb whose target does not exist has no repo to hold a level
484 // on, so it would be a special case beside the table, and a
485 // probe-discoverable one for every stranger;
486 // * **turning gRPC on** is the door the unauthenticated v1 and
487 // `gunnar-grpc/tests/loopback_default.rs` exist to keep shut on
488 // a mailed medium: `Bootstrap.Enroll` with no credential is a
489 // race between the customer and whoever else finds the box.
490 //
491 // Push-to-create adds no verb, no parse production and no
492 // vocabulary: `Control::create_for_push` asks the exact two
493 // questions `Repos.CreateNamespace`/`Repos.Create` gate on, so
494 // this door and the RPC door can never disagree (one implementation) — and it
495 // sits HERE, where the two entry points (exec line, smart-HTTP
496 // URL) have already fanned in, so SSH and HTTP answer a push to a
497 // missing repository identically.
498 //
499 // Only a WRITE: ReceivePack, and (2026-09-28) an LFS upload.
500 // Reading never creates: a `git clone` of a typo, or an LFS
501 // download, stays an error.
502 //
503 // **Why the LFS upload too.** git-lfs's pre-push hook runs AFTER
504 // git has taken receive-pack's advertisement and BEFORE it sends
505 // a command, and it asks `git-lfs-transfer <repo> upload` first.
506 // MEASURED 2026-09-28 (git-lfs 3.8.0, and on a real box): into a
507 // repository that did not exist yet that exec was the fused
508 // not-found, the hook died — `batch request: exec request failed
509 // on channel 0: exit status 255` — and the push that would have
510 // created the repository never sent its commands. The upload is
511 // the same act as the push (it puts content in the repository),
512 // by the same principal, and it is asked the same two questions
513 // (`push_create_spec`), so it opens the same door and nobody else
514 // learns anything new. Nothing is written here either: the
515 // transport creates the repository when the first OBJECT arrives
516 // (`gunnar-server` `ProspectiveLfs`), so a client that only
517 // batches, or hangs up, leaves nothing.
518 //
519 // For everyone `create_for_push` answers `None` for, the refusal
520 // below is bit-identical to what it always was — the one fused
521 // "repository not found, or you do not have access" — so the
522 // door's existence is not observable to a key it does not admit.
523 //
524 // **Nothing is written here.** The door answers with the
525 // repository it WOULD create (`prospective`), the transport
526 // advertises that, and the catalog row and the store are made
527 // only once the client has sent commands that pass the hash
528 // check — see `Control::push_create_spec` for the ghost
529 // repository this order closes.
530 None if service == GitService::ReceivePack
531 || service == GitService::LfsTransfer(crate::command::Operation::Upload) =>
532 {
533 match self.control.push_create_spec(principal, &path)? {
534 Some(spec) => {
535 // The name filter (2026-10-05) — asked only of a
536 // pusher the door admits, so its sentence tells
537 // nobody else anything.
538 if let Some(line) = self.control.push_create_name_refusal(principal, &path) {
539 return Err(DispatchError::Plan {
540 namespace: path.namespace().to_owned(),
541 line,
542 });
543 }
544 (spec.prospect()?, true)
545 }
546 None => return Err(DispatchError::NoSuchRepo(path)),
547 }
548 }
549 None => return Err(DispatchError::NoSuchRepo(path)),
550 };
551 let held = self.control.access_for(principal, &repo)?;
552 match held {
553 // **The standby freeze.** Checked here, INSIDE the authorised arm,
554 // so it is only ever reached by a writer the grant check already
555 // admitted — an unauthorised push still gets the fused not-found and
556 // learns nothing new. A write-requiring service by a non-`Machine`
557 // principal on a frozen box is refused: this box has abdicated or is
558 // a configured standby, and a client write here would be a split
559 // the primary never sees. The primary's own replication push is a
560 // `Machine` identity and sails through — that is what a standby is
561 // for.
562 Some(level)
563 if level.permits(required)
564 && required.permits(Access::Write)
565 && self.control.write_frozen_for(principal) =>
566 {
567 Err(DispatchError::Standby {
568 principal: principal.id.clone(),
569 repo: path,
570 browse: self.control.is_browse(),
571 })
572 }
573 // **An encrypted repository takes no LFS upload** (wiring tracer B
574 // 2026-10-08). git-lfs uploads in the pre-push hook, BEFORE the
575 // pack the encrypted gate reads, and an LFS object is the
576 // plaintext of a `filter=lfs` file that never went through
577 // `filter=gunnar-crypt`: refused here, for SSH and smart HTTP
578 // alike, before a byte is stored. Asked inside the authorised arm,
579 // so a stranger still gets the fused not-found. A download is never
580 // refused.
581 Some(level)
582 if level.permits(required)
583 && repo.encrypted
584 && service == GitService::LfsTransfer(crate::command::Operation::Upload) =>
585 {
586 Err(DispatchError::Plan {
587 namespace: path.namespace().to_owned(),
588 line: format!(
589 "{path} is encrypted, so it takes no LFS objects: LFS stores files as \
590 they are, outside your members' encryption. Track the file with \
591 `filter=gunnar-crypt` instead of `filter=lfs`"
592 ),
593 })
594 }
595 Some(level) if level.permits(required) => {
596 // **The gate chain**, asked LAST: after the grant (so a
597 // refusal leaks nothing to a stranger) and after the standby
598 // freeze (so a standby stays one whatever the gates say). A
599 // write asks `Write`; an anonymous read asks `AnonymousRead`;
600 // an authenticated read asks nothing at all, because the
601 // owner's clone is allowed in every state — data is never held
602 // hostage. See `crate::plan`.
603 let PlanOutcome {
604 notice: plan_notice,
605 ceiling: pack_ceiling,
606 pack_mark,
607 allowance: lfs_allowance,
608 } = self.ask_plan(principal, service, required, &repo)?;
609 Ok(ServiceRequest {
610 service,
611 repo,
612 prospective,
613 principal: principal.clone(),
614 access: level,
615 // The key that authenticated this session, carried
616 // rather than guessed back out of the identity table. A
617 // parameter and not a builder, so it cannot be forgotten into
618 // `None`.
619 key_fingerprint: key_fingerprint.cloned(),
620 git_protocol: None,
621 delivery: Delivery::Session,
622 // Derived from `key_fingerprint` by the transport rather
623 // than spelled here: see `ServiceRequest::credential`.
624 credential: None,
625 plan_notice,
626 pack_ceiling,
627 pack_mark,
628 lfs_allowance,
629 cancel: crate::channel::Cancel::new(),
630 })
631 }
632 other => Err(DispatchError::Denied {
633 principal: principal.id.clone(),
634 repo: path,
635 needed: required,
636 held: match other {
637 Some(level) => level.to_string(),
638 None => "none".to_string(),
639 },
640 }),
641 }
642 }
643
644 /// **Ask the gate chain**, for a request the grant check already admitted.
645 /// `Ok(Some(line))` is an allowed request that carries a warning (Grace);
646 /// `Err(Plan)` is the refusal, with the line the client is told.
647 ///
648 /// The three shapes, and why each asks what it asks:
649 ///
650 /// * a **write** (`git-receive-pack`, LFS upload) asks
651 /// [`PlanAction::Write`](crate::plan::PlanAction::Write), and if that is
652 /// allowed asks [`PlanGate::pack_quota`](crate::plan::PlanGate::pack_quota)
653 /// — both before a single pack byte is read;
654 /// * an **anonymous read** asks
655 /// [`PlanAction::AnonymousRead`](crate::plan::PlanAction::AnonymousRead):
656 /// a lapsed tenant's public surface is what costs the provider and earns
657 /// nothing;
658 /// * an **authenticated read** asks nothing. The owner clones their own
659 /// repositories in every state, and so does anyone they granted. That is
660 /// rule 1 of `gunnar_core::entitlement`, and it is enforced here by the
661 /// absence of a question rather than by an answer.
662 ///
663 /// **The chain.** Gates are asked in the order `Control::with_plan_gate`
664 /// added them — disk first — and the FIRST `Refuse` is the answer; a later
665 /// gate is not consulted, so a full box is told it is full and not also
666 /// that its plan lapsed. Each gate is asked BOTH its questions before the
667 /// next gate is asked anything: its ladder (`verdict`), then, for a write
668 /// that grows data, its quota (`pack_quota`). Within one gate that order is
669 /// what tells a Suspended tenant they are suspended rather than also full;
670 /// across gates it is what makes "disk first" mean disk first — the disk
671 /// gate only ever refuses from `pack_quota`, and a chain that asked every
672 /// ladder before any quota would let a plan's ladder outrank it whatever
673 /// the order (`tests/disk_headroom.rs` caught exactly that, red first).
674 /// Warnings from every allowing gate are joined.
675 ///
676 /// With no gate wired (`Control::with_plan_gate` never called) every
677 /// namespace is Free and this is a no-op. A `Machine` principal —
678 /// replication, the primary's copy arriving — is asked only of the gates
679 /// that say they apply to it ([`PlanGate::applies_to_machine`]): the disk
680 /// does, a plan does not, because refusing a lapsed tenant's replication
681 /// would make their standby diverge from the primary.
682 fn ask_plan(
683 &self,
684 principal: &Principal,
685 service: GitService,
686 required: Access,
687 repo: &gunnar_core::Repo,
688 ) -> Result<PlanOutcome, DispatchError> {
689 use crate::plan::{PlanAction, PlanVerdict};
690 let machine = principal.kind == gunnar_core::PrincipalKind::Machine;
691 let gates: Vec<_> = self
692 .control
693 .plan_gates()
694 .iter()
695 .filter(|gate| !machine || gate.applies_to_machine())
696 .collect();
697 if gates.is_empty() {
698 return Ok(PlanOutcome::default());
699 }
700 let anonymous = principal.id == gunnar_core::ANONYMOUS_PRINCIPAL_ID;
701 let action = if required.permits(Access::Write) {
702 PlanAction::Write
703 } else if anonymous {
704 PlanAction::AnonymousRead
705 } else {
706 return Ok(PlanOutcome::default());
707 };
708 let refused = |line: String| DispatchError::Plan {
709 namespace: repo.namespace.clone(),
710 line,
711 };
712 // `service` is named here so a future fourth write-shaped verb has to
713 // decide whether it grows the tenant's data.
714 let grows_data = matches!(
715 service,
716 GitService::ReceivePack | GitService::LfsTransfer(crate::command::Operation::Upload)
717 );
718 let mut notices: Vec<String> = Vec::new();
719 let mut ceiling: Option<crate::plan::PackCeiling> = None;
720 let mut allowance: Option<gunnar_lfs::Allowance> = None;
721 // **Marked BEFORE any gate walks the disk, and that ordering is the
722 // contract**, not an accident of where the line sits. A gate's
723 // `lfs_allowance` measures the namespace's bytes off the disk; an upload
724 // admitted DURING that walk may or may not have landed bytes for the
725 // walk to see. Taking the mark first puts such an admission after the
726 // mark, so it is charged — and charged twice if the walk saw it too,
727 // which refuses a shade early. Taking the mark after the walk would put
728 // it before the mark and possibly outside the walk, which admits too
729 // much. Only one of those two roundings is a quota that leaks. See
730 // `gunnar_lfs::ledger`.
731 let mark = gunnar_lfs::AllowanceLedger::shared().mark(&repo.namespace);
732 // …and the same standing in the PACK meter, taken in the same breath and
733 // for the same reason: `pack_ceiling` below measures the namespace's
734 // packfile bytes off the disk, and a push admitted during that walk has
735 // to land after this mark to be counted.
736 //
737 // **Two marks and not one, because they are two meters.**
738 // `caps["pack_bytes"]` and `caps["lfs_bytes"]` are capped separately on
739 // the signed fact and reported separately by `Usage.Read`, and the two
740 // numbers these marks are judged against are computed from different
741 // caps. One shared counter would charge an LFS upload against a push's
742 // ceiling — cutting a push mid-transfer over room its own cap never
743 // lost — which is a quota that refuses wrongly, the same defect as one
744 // that admits wrongly. They share a disk; they do not share a cap. See
745 // `gunnar_lfs::AllowanceLedger::shared_pack`.
746 let pack_mark = gunnar_lfs::AllowanceLedger::shared_pack().mark(&repo.namespace);
747 for gate in &gates {
748 match gate.verdict(&repo.namespace, action) {
749 PlanVerdict::Allow => {}
750 PlanVerdict::Warn(line) => notices.push(line),
751 PlanVerdict::Refuse(line) => return Err(refused(line)),
752 }
753 // The quota, only for a write this gate's ladder allowed.
754 if action == PlanAction::Write && grows_data {
755 if let PlanVerdict::Refuse(line) = gate.pack_quota(&repo.namespace) {
756 return Err(refused(line));
757 }
758 // **The smallest ceiling in the chain wins**, which is the
759 // byte-wise spelling of first-`Refuse`-wins one line above: a
760 // push has to satisfy every gate, so it is held to the
761 // tightest one, and the line the client reads is that gate's
762 // own. Asked only where `pack_quota` is asked, so a read and a
763 // deletion are never given a ceiling to trip over.
764 if let Some(asked) = gate.pack_ceiling(&repo.namespace) {
765 let tighter = match &ceiling {
766 Some(held) => asked.bytes < held.bytes,
767 None => true,
768 };
769 if tighter {
770 ceiling = Some(asked);
771 }
772 }
773 // …and the same tightest-wins rule for the LFS wire, for the
774 // same reason: a transfer has to satisfy every gate, so it is
775 // held to the smallest room any of them will admit, and the
776 // sentence the tenant reads is that gate's own.
777 if let Some(asked) = gate.lfs_allowance(&repo.namespace) {
778 let tighter = match &allowance {
779 Some(held) => asked.bytes < held.bytes,
780 None => true,
781 };
782 if tighter {
783 allowance = Some(asked);
784 }
785 }
786 }
787 }
788 Ok(PlanOutcome {
789 notice: (!notices.is_empty()).then(|| notices.join("; ")),
790 // The tightest gate's number and the standing taken before any gate
791 // looked, carried side by side rather than folded into one type:
792 // see `ServiceRequest::pack_mark` for why the ceiling stays exactly
793 // what `PlanGate::pack_ceiling` returned.
794 pack_mark: ceiling.is_some().then_some(pack_mark),
795 ceiling,
796 // The tightest gate's number, bound to the standing taken above it.
797 // `mark` is dropped unused when no gate asked for an allowance,
798 // which costs one map read and holds nothing: there is no
799 // reservation in a mark to leak.
800 allowance: allowance
801 .map(|allowance| gunnar_lfs::NamespaceAllowance::new(mark, allowance)),
802 })
803 }
804}
805
806/// What [`Dispatch::ask_plan`] learned: everything the gate chain wants carried
807/// into the transfer, as opposed to the refusals, which are returned as errors
808/// and never reach here.
809///
810/// A struct and not a tuple because both fields are `Option` and both are
811/// about the plan: a `(Option<String>, Option<PackCeiling>)` at the call site
812/// is two anonymous maybes that the next field added would make three.
813#[derive(Default)]
814struct PlanOutcome {
815 /// See [`crate::ServiceRequest::plan_notice`].
816 notice: Option<String>,
817 /// See [`crate::ServiceRequest::pack_ceiling`].
818 ceiling: Option<crate::plan::PackCeiling>,
819 /// See [`crate::ServiceRequest::pack_mark`]. `Some` exactly when `ceiling`
820 /// is: a mark with no number to be judged against is bookkeeping nobody
821 /// reads, and a number with no mark is the bug this closed.
822 pack_mark: Option<gunnar_lfs::Mark>,
823 /// See [`crate::ServiceRequest::lfs_allowance`]. A third `Option` on this
824 /// struct, and the reason the struct exists rather than a tuple.
825 allowance: Option<gunnar_lfs::NamespaceAllowance>,
826}
827
828// ───────────────────────────────────────────────────────────────────────────
829// The server
830// ───────────────────────────────────────────────────────────────────────────
831
832struct Shared {
833 dispatch: Dispatch,
834 transport: Arc<dyn GitTransport>,
835 exec_grace: Option<Duration>,
836 /// Whether `auth_none` on [`ANONYMOUS_SSH_USER`] is accepted.
837 allow_anonymous: bool,
838 admission: Arc<Admission>,
839 metrics: Arc<ServerMetrics>,
840 /// **Are the stores open?** See [`GunnarSsh::with_readiness`].
841 ready: Arc<std::sync::atomic::AtomicBool>,
842 /// [`SshConfig::max_auth_attempts`], carried here because the CONNECTION
843 /// enforces it and russh 0.61.2 does not. See
844 /// [`Connection::auth_attempts`].
845 config_max_auth_attempts: usize,
846 /// [`SshConfig::session_end_grace`] and
847 /// [`SshConfig::session_end_grace_crowded`].
848 session_end_grace: (Duration, Duration),
849 /// The sealed box's tunnel-address door ([`TUNNEL_ADDRESS_VERB`]), or
850 /// `None` on a build with no WireGuard tunnel.
851 tunnel_door: Option<TunnelAddressDoor>,
852 /// The repository-settings door ([`REPO_VERB`]), or `None` on a server
853 /// with no control plane (`serve --no-grpc`).
854 repo_door: Option<RepoDoor>,
855}
856
857/// **The one control verb on this listener** (2026-09-21, T17):
858/// `gunnar-tunnel-address [a.b.c.d/prefix]`.
859///
860/// The sealed installer runs `serve --no-grpc`, so its SSH door is its only
861/// door, and a box's WireGuard tunnel address is per box and not on the
862/// medium. So it arrives here, held to **server-wide Admin** and answered by
863/// the closure `gunnar-server` injects — the SAME function the gRPC doors call.
864/// No argument is a read. Output is `key value` lines on stdout, exit 0; a
865/// refusal is `error: <why>` on stdout, exit 1 (stdout and not stderr, so a
866/// client reading only the data band still gets the sentence). Not a git
867/// verb, so it never enters [`Dispatch::authorise`] or the transfer path.
868pub const TUNNEL_ADDRESS_VERB: &str = "gunnar-tunnel-address";
869
870/// **The operator's fire drill** (stinkies ssh-double-exec-error, 2026-09-30): ONE exec
871/// verb, held to server-wide Admin like [`TUNNEL_ADDRESS_VERB`], that says exactly one
872/// ERROR naming itself a drill and who asked — what the estate's watch raises on purpose
873/// to prove its alert path end to end. Nothing is wrong when it is said; no other caller
874/// can raise the server's ERROR at will.
875pub const FIRE_DRILL_VERB: &str = "gunnar-fire-drill";
876
877/// **A member's SSH public keys, for an encrypted repository's key ring**
878/// (2026-10-06): `gunnar-recipient-keys '<namespace>/<repository>' '<member>'`.
879///
880/// What `gunnar crypt add-member NAME --from-server` asks when it is given no
881/// control address — on an installed estate the forge's SSH door (tcp/2222
882/// through the front) is the one door a member's key opens; the control plane
883/// is bound to the WireGuard overlay. The SAME rule as `Repos.RecipientKeys`:
884/// the caller reads the repository (otherwise it is told what a stranger is
885/// told, the one "not found, or no access" sentence), and so must the person
886/// named — gunnar hands out keys only for someone who could read it anyway,
887/// never a directory of everybody's keys. Output is one OpenSSH public key
888/// line per key on stdout, exit 0; a refusal is `error: <why>` on stdout,
889/// exit [`EXIT_DENIED`] (stdout, like [`TUNNEL_ADDRESS_VERB`]'s). An anonymous
890/// session is refused the channel. Not a git verb: it never enters
891/// [`Dispatch::authorise`] or the transfer path, and it changes nothing.
892pub const RECIPIENT_KEYS_VERB: &str = "gunnar-recipient-keys";
893
894/// **Who this key is** (wiring tracer B 2026-10-08): `gunnar-whoami` answers the principal id
895/// the session authenticated as, one line, exit 0 — what `gunnar crypt init` names its first
896/// member by (the account name `add-member --from-server` looks members up by). Reveals nothing
897/// the key's holder does not already know. An anonymous session is refused the channel. Not a
898/// git verb.
899pub const WHOAMI_VERB: &str = "gunnar-whoami";
900
901/// **git-lfs's fallback verb**, answered with a sentence instead of a channel
902/// failure. Gunnar serves Git LFS over pure SSH only (`git-lfs-transfer`,
903/// git-lfs >= 3.0); git-lfs asks this verb only when a pure-SSH session failed
904/// or was refused, and then prints what is on stderr after `batch request:`.
905pub const LFS_AUTHENTICATE_VERB: &str = "git-lfs-authenticate";
906
907/// What [`LFS_AUTHENTICATE_VERB`] answers, on stderr with exit 1. It must never
908/// say `not found` / `no such file`: git-lfs reads those as "no such verb" and
909/// goes on to a guessed HTTPS endpoint, which Gunnar does not serve.
910pub const LFS_AUTHENTICATE_MESSAGE: &str = "Gunnar serves Git LFS over pure SSH only (git-lfs-transfer, \
911git-lfs 3.0 or newer); there is no HTTPS LFS endpoint. The pure SSH transfer just failed or was \
912refused (the server was busy or restarting): run the same command again.\n";
913
914/// **A repository's settings, over the forge's door** (owner, 2026-10-14):
915/// `gunnar-repo show '<namespace>/<repository>'`,
916/// `gunnar-repo visibility '<namespace>/<repository>' public|private`,
917/// `gunnar-repo default-branch '<namespace>/<repository>' '<refs/heads/…>'`.
918///
919/// What the client `gunnar repo show|visibility|default-branch` asks. On an
920/// installed estate the forge's SSH door (tcp/2222 through the front) is the
921/// one door a person's key opens; the control plane is bound to the WireGuard
922/// overlay. The verb decides NOTHING itself: it hands the authenticated
923/// principal and the ask to [`RepoDoor`], which `gunnar-server` answers with
924/// the SAME `Repos.Get` / `Repos.SetVisibility` / `Repos.SetDefaultBranch`
925/// handlers the control plane mounts — so the account-admin rule for
926/// visibility, the repository-Admin rule for the default branch, the audit
927/// event and the browse replica's notice are the gRPC door's, not a copy.
928/// Output is `key value` lines on stdout, exit 0; a refusal is
929/// `error: <why>` on stdout, exit [`EXIT_DENIED`]. An anonymous session is
930/// refused the channel. Not a git verb: it never enters
931/// [`Dispatch::authorise`] or the transfer path.
932pub const REPO_VERB: &str = "gunnar-repo";
933
934/// What a [`REPO_VERB`] line asks.
935#[derive(Debug, Clone, PartialEq, Eq)]
936pub enum RepoAction {
937 /// `Repos.Get`.
938 Show,
939 /// `Repos.SetVisibility`: `true` is public.
940 Visibility(bool),
941 /// `Repos.SetDefaultBranch`, the branch exactly as sent (the server
942 /// validates it; the client expands a short name).
943 DefaultBranch(String),
944 /// `Repos.Create` of an empty repository in this object format (`true`
945 /// is sha256): what a client that knows its own format asks before its
946 /// first push, since a push-made repository can only be sha1.
947 Create {
948 /// `true`: a sha256 repository; `false`: sha1.
949 sha256: bool,
950 },
951}
952
953/// One [`REPO_VERB`] ask, with who asked: the principal the session's key
954/// authenticated as (re-read at the exec, never cached) and that key's
955/// fingerprint.
956#[derive(Debug, Clone, PartialEq, Eq)]
957pub struct RepoAsk {
958 /// The principal the session's key authenticated as.
959 pub principal: String,
960 /// That key's fingerprint.
961 pub fingerprint: String,
962 /// The repository the verb names.
963 pub repo: RepoRef,
964 /// The verb itself.
965 pub action: RepoAction,
966}
967
968/// What answers [`REPO_VERB`]: the ask in, the `key value` lines or the
969/// refusal's sentence out.
970pub type RepoDoor = Arc<
971 dyn Fn(RepoAsk) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<String, String>> + Send>>
972 + Send
973 + Sync,
974>;
975
976/// Parse a [`REPO_VERB`] exec line. `None`: not this verb. `Some(Err)`: this
977/// verb, malformed. Each argument may be single-quoted the way git quotes a
978/// path; the path goes through the one sandbox
979/// ([`gunnar_core::resolve_repo_path`]).
980pub fn parse_repo_verb(raw: &[u8]) -> Option<Result<(RepoRef, RepoAction), String>> {
981 let text = std::str::from_utf8(raw).ok()?;
982 let mut tokens = text.split(' ').filter(|t| !t.is_empty());
983 if tokens.next()? != REPO_VERB {
984 return None;
985 }
986 let usage = || {
987 format!(
988 "the line is not `{REPO_VERB} show <namespace>/<repository>`, \
989 `{REPO_VERB} visibility <namespace>/<repository> public|private` or \
990 `{REPO_VERB} default-branch <namespace>/<repository> <branch>` or \
991 `{REPO_VERB} create <namespace>/<repository> sha1|sha256`"
992 )
993 };
994 if raw.len() > crate::command::MAX_EXEC_LEN || raw.iter().any(|b| *b < 0x20 || *b == 0x7f) {
995 return Some(Err(usage()));
996 }
997 let mut args = Vec::new();
998 for token in tokens {
999 match crate::command::unquote(token) {
1000 Ok(arg) => args.push(arg),
1001 Err(_) => return Some(Err(usage())),
1002 }
1003 }
1004 let (sub, path, value) = match args.as_slice() {
1005 [sub, path] => (sub.as_str(), path.as_str(), None),
1006 [sub, path, value] => (sub.as_str(), path.as_str(), Some(value.as_str())),
1007 _ => return Some(Err(usage())),
1008 };
1009 let action = match (sub, value) {
1010 ("show", None) => RepoAction::Show,
1011 ("visibility", Some("public")) => RepoAction::Visibility(true),
1012 ("visibility", Some("private")) => RepoAction::Visibility(false),
1013 ("visibility", Some(other)) => {
1014 return Some(Err(format!("visibility is `public` or `private`, not `{}`", other.escape_default())))
1015 }
1016 ("default-branch", Some(branch)) if !branch.is_empty() => RepoAction::DefaultBranch(branch.to_string()),
1017 ("create", Some("sha256")) => RepoAction::Create { sha256: true },
1018 ("create", Some("sha1")) => RepoAction::Create { sha256: false },
1019 ("create", Some(other)) => {
1020 return Some(Err(format!("an object format is `sha1` or `sha256`, not `{}`", other.escape_default())))
1021 }
1022 _ => return Some(Err(usage())),
1023 };
1024 let repo = match gunnar_core::resolve_repo_path(path) {
1025 Ok(repo) => repo,
1026 Err(err) => return Some(Err(err.to_string())),
1027 };
1028 Some(Ok((repo, action)))
1029}
1030
1031/// Parse a [`RECIPIENT_KEYS_VERB`] exec line. `None`: not this verb.
1032/// `Some(Err)`: this verb, malformed. The path and the member may each be
1033/// single-quoted the way git quotes a path; the path goes through the one
1034/// sandbox ([`gunnar_core::resolve_repo_path`]) and the member through the
1035/// principal id rule.
1036pub fn parse_recipient_keys_verb(raw: &[u8]) -> Option<Result<(RepoRef, String), String>> {
1037 let text = std::str::from_utf8(raw).ok()?;
1038 let (verb, rest) = text.split_once(' ').unwrap_or((text, ""));
1039 if verb != RECIPIENT_KEYS_VERB {
1040 return None;
1041 }
1042 let usage = || format!("the line is not `{RECIPIENT_KEYS_VERB} <namespace>/<repository> <member>`");
1043 if raw.len() > crate::command::MAX_EXEC_LEN || raw.iter().any(|b| *b < 0x20 || *b == 0x7f) {
1044 return Some(Err(usage()));
1045 }
1046 let Some((path, member)) = rest.trim().rsplit_once(' ') else {
1047 return Some(Err(usage()));
1048 };
1049 let (Ok(path), Ok(member)) = (crate::command::unquote(path.trim()), crate::command::unquote(member.trim())) else {
1050 return Some(Err(usage()));
1051 };
1052 let repo = match gunnar_core::resolve_repo_path(&path) {
1053 Ok(repo) => repo,
1054 Err(err) => return Some(Err(err.to_string())),
1055 };
1056 if gunnar_core::Principal::new(member.clone(), member.clone(), gunnar_core::PrincipalKind::User).is_err() {
1057 return Some(Err(format!("`{}` is not an account name", member.escape_default())));
1058 }
1059 Some(Ok((repo, member)))
1060}
1061
1062/// **The answer to [`RECIPIENT_KEYS_VERB`]** for `caller`: `(exit status,
1063/// stdout)`. Reads the identity table and the catalog; changes nothing.
1064pub fn recipient_keys_answer(control: &Control, caller: &str, repo: &RepoRef, member: &str) -> (u32, String) {
1065 if control.is_twin() {
1066 let said = DispatchError::Twin { principal: caller.to_string(), repo: repo.clone() }.client_message().unwrap_or_default();
1067 return (EXIT_DENIED, format!("error: {said}\n"));
1068 }
1069 let hidden = || {
1070 let said = DispatchError::NoSuchRepo(repo.clone()).client_message().unwrap_or_default();
1071 (EXIT_DENIED, format!("error: {said}\n"))
1072 };
1073 // The member is told Gunnar could not answer; what broke is the operator's (the journal).
1074 let fault = |err: gunnar_core::Error| {
1075 tracing::error!(target: "gunnar::ssh", event = "ssh.recipient_keys.fault", %err, "gunnar-recipient-keys: the identity table or the catalog could not be read");
1076 (EXIT_DENIED, "error: Gunnar could not answer this just now; try again in a while\n".to_string())
1077 };
1078 let entry = match control.catalog().get(repo) {
1079 Ok(Some(entry)) => entry,
1080 Ok(None) => return hidden(),
1081 Err(err) => return fault(err),
1082 };
1083 match control.auth().may(caller, &entry, gunnar_core::Level::Read) {
1084 Ok(true) => {}
1085 Ok(false) => return hidden(),
1086 Err(err) => return fault(err),
1087 }
1088 match control.auth().may(member, &entry, gunnar_core::Level::Read) {
1089 Ok(true) => {}
1090 Ok(false) => {
1091 return (
1092 EXIT_DENIED,
1093 format!(
1094 "error: {member} cannot read {}/{}: grant them access before adding them as a member of its key ring\n",
1095 repo.namespace(),
1096 repo.name()
1097 ),
1098 )
1099 }
1100 Err(err) => return fault(err),
1101 }
1102 // **The member's ONE encryption key** (CRYPT-YUBI 2026-10-26): a ring is wrapped to the
1103 // person's encryption public key, never to an SSH key.
1104 let Some(keys) = control.encryption_keys() else {
1105 return (EXIT_DENIED, "error: this Gunnar keeps no encryption keys\n".to_string());
1106 };
1107 match keys.public_of(member) {
1108 Ok(Some(public)) => (0, format!("{}\n", public.trim())),
1109 Ok(None) => (
1110 EXIT_DENIED,
1111 format!(
1112 "error: {member} has no encryption key yet: {member} makes one with `gunnar crypt key new` \
1113 (or by adding a security key on their Account page), then the ring can be wrapped to it\n"
1114 ),
1115 ),
1116 Err(gunnar_core::encryption_key::KeyRefusal::Store(err)) => fault(err),
1117 Err(other) => (EXIT_DENIED, format!("error: {other}\n")),
1118 }
1119}
1120
1121/// **The answer to [`gunnar_crypt::door::VERB`]** (`gunnar-user-key`, CRYPT-YUBI) for
1122/// `caller`, the session's own principal: `(exit status, stdout)`. Reads or changes the
1123/// caller's own encryption key only; there is no name to give.
1124pub fn user_key_answer(control: &Control, principal: &gunnar_core::Principal, request: gunnar_crypt::door::Request) -> (u32, String) {
1125 let caller = principal.id.as_str();
1126 use gunnar_core::encryption_key::{KeyRefusal, UnlockMethod};
1127 use gunnar_crypt::door::Request;
1128 if control.is_twin() {
1129 return (EXIT_DENIED, "error: this is a twin; ask the primary\n".to_string());
1130 }
1131 let Some(keys) = control.encryption_keys() else {
1132 return (EXIT_DENIED, "error: this Gunnar keeps no encryption keys\n".to_string());
1133 };
1134 let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0);
1135 let said = |r: Result<gunnar_core::encryption_key::EncryptionKey, KeyRefusal>| match r {
1136 Ok(key) => (0, key.to_answer().text()),
1137 Err(KeyRefusal::Store(err)) => {
1138 tracing::error!(target: "gunnar::ssh", event = "ssh.user_key.fault", %err, "gunnar-user-key: the store could not be read or written");
1139 (EXIT_DENIED, "error: Gunnar could not answer this just now; try again in a while\n".to_string())
1140 }
1141 Err(other) => (EXIT_DENIED, format!("error: {other}\n")),
1142 };
1143 match request {
1144 Request::Get => match keys.get(caller) {
1145 Ok(Some(key)) => (0, key.to_answer().text()),
1146 Ok(None) => (0, String::new()),
1147 Err(e) => said(Err(e)),
1148 },
1149 // The account's audit, the same kinds the gRPC door writes (RA4-3).
1150 Request::Create { public_key, method } => {
1151 let kind = method.kind.clone();
1152 let r = UnlockMethod::from_line(method).and_then(|m| keys.create(caller, &public_key, m, now));
1153 if r.is_ok() {
1154 control.encryption_key_event(principal, "encryption-key.created", &format!("first method {kind}"));
1155 tracing::info!(target: "gunnar::audit", event = "access.encryption_key_created", principal = %caller, method = %kind, "an encryption key was created");
1156 }
1157 said(r)
1158 }
1159 Request::Add(method) => {
1160 let kind = method.kind.clone();
1161 let r = UnlockMethod::from_line(method).and_then(|m| keys.add_method(caller, m, now));
1162 if r.is_ok() {
1163 control.encryption_key_event(principal, "encryption-key.method-added", &kind);
1164 tracing::info!(target: "gunnar::audit", event = "access.unlock_method_added", principal = %caller, method = %kind, "an unlock method was added");
1165 }
1166 said(r)
1167 }
1168 Request::Remove(id) => {
1169 let r = keys.remove_method(caller, &id);
1170 if r.is_ok() {
1171 control.encryption_key_event(principal, "encryption-key.method-removed", &id);
1172 tracing::info!(target: "gunnar::audit", event = "access.unlock_method_removed", principal = %caller, method_id = %id, "an unlock method was removed");
1173 }
1174 said(r)
1175 }
1176 }
1177}
1178
1179/// What answers [`TUNNEL_ADDRESS_VERB`]: the address (empty = a read) in, the
1180/// answer's lines or the refusal out.
1181pub type TunnelAddressDoor = Arc<dyn Fn(&str) -> Result<String, String> + Send + Sync>;
1182
1183/// Parse a [`TUNNEL_ADDRESS_VERB`] exec line. `None`: not this verb. `Some(Err)`:
1184/// this verb, malformed. Printable ASCII only, at most one argument, short.
1185pub fn parse_tunnel_address_verb(raw: &[u8]) -> Option<Result<String, String>> {
1186 let text = std::str::from_utf8(raw).ok()?;
1187 let mut tokens = text.split(' ').filter(|t| !t.is_empty());
1188 if tokens.next()? != TUNNEL_ADDRESS_VERB {
1189 return None;
1190 }
1191 if raw.len() > 64 || !raw.iter().all(|b| (0x20..0x7f).contains(b)) {
1192 return Some(Err("the line is not `gunnar-tunnel-address [a.b.c.d/prefix]`".to_string()));
1193 }
1194 let address = tokens.next().unwrap_or("").to_string();
1195 if tokens.next().is_some() {
1196 return Some(Err("one argument at most: `gunnar-tunnel-address [a.b.c.d/prefix]`".to_string()));
1197 }
1198 Some(Ok(address))
1199}
1200
1201/// **The key exchanges gunnar's SSH door offers, post-quantum FIRST**
1202/// (2026-10-06, the PQ transport lane).
1203///
1204/// `mlkem768x25519-sha256` (draft-ietf-sshm-mlkem-hybrid-kex: ML-KEM-768 and
1205/// X25519, the session key from both) is what OpenSSH ≥ 9.9 offers first and
1206/// 10.0 makes its default — russh 0.63 runs it on RustCrypto's `ml-kem`. The
1207/// classical exchanges stay after it, so an older client still connects
1208/// (preferred, never required). `sntrup761x25519-sha512` is not here: russh
1209/// does not implement it.
1210///
1211/// **gunnar's own list, not russh's default**, though the two agree today:
1212/// a russh bump that reorders or drops its `Preferred::DEFAULT` must not
1213/// change what this door offers without a red test here. SSH lets the
1214/// CLIENT's order decide; the server's job is to offer the hybrid at all.
1215pub static KEX_ORDER: &[russh::kex::Name] = &[
1216 russh::kex::MLKEM768X25519_SHA256,
1217 russh::kex::CURVE25519,
1218 russh::kex::CURVE25519_PRE_RFC_8731,
1219 russh::kex::DH_GEX_SHA256,
1220 russh::kex::DH_G18_SHA512,
1221 russh::kex::DH_G17_SHA512,
1222 russh::kex::DH_G16_SHA512,
1223 russh::kex::DH_G15_SHA512,
1224 russh::kex::DH_G14_SHA256,
1225 russh::kex::EXTENSION_SUPPORT_AS_CLIENT,
1226 russh::kex::EXTENSION_SUPPORT_AS_SERVER,
1227 russh::kex::EXTENSION_OPENSSH_STRICT_KEX_AS_CLIENT,
1228 russh::kex::EXTENSION_OPENSSH_STRICT_KEX_AS_SERVER,
1229];
1230
1231/// russh's algorithm preferences with gunnar's [`KEX_ORDER`]; ciphers, MACs
1232/// and host-key algorithms stay russh's.
1233pub fn preferred() -> russh::Preferred {
1234 russh::Preferred { kex: std::borrow::Cow::Borrowed(KEX_ORDER), ..russh::Preferred::DEFAULT }
1235}
1236
1237/// gunnar's SSH listener.
1238pub struct GunnarSsh {
1239 config: SshConfig,
1240 shared: Arc<Shared>,
1241 /// **A connection that arrives at a refused LOCAL address is dropped**
1242 /// before a byte is spoken (`gunnar serve --wg-only`: the utility
1243 /// network's address — every box-to-box connection runs over the tunnel).
1244 refused_local: Option<RefusedLocal>,
1245}
1246
1247/// Is a connection that arrived at this local address refused?
1248pub type RefusedLocal = Arc<dyn Fn(std::net::IpAddr) -> bool + Send + Sync>;
1249
1250impl GunnarSsh {
1251 /// Build a server over the control plane and the wire seam.
1252 pub fn new(config: SshConfig, control: Control, transport: Arc<dyn GitTransport>) -> Self {
1253 let exec_grace = config.exec_grace;
1254 let allow_anonymous = config.allow_anonymous;
1255 let config_max_auth_attempts = config.max_auth_attempts;
1256 let session_end_grace = (config.session_end_grace, config.session_end_grace_crowded);
1257 // The memory budget travels with the two concurrency numbers: one
1258 // constructor, so a configuration cannot arrive with a governed
1259 // concurrency limit and an unmetered budget. `None` falls back to the
1260 // shipped constant rather than to "unlimited" — an operator who did not
1261 // set a budget wants the default, not the removal of a gate.
1262 let budget = config
1263 .memory_budget_bytes
1264 .unwrap_or(crate::governor::DEFAULT_MEMORY_BUDGET_BYTES);
1265 let wait = config
1266 .admission_wait
1267 .unwrap_or(crate::governor::DEFAULT_ADMISSION_WAIT);
1268 let admission = Arc::new(
1269 if config.per_principal_limit_is_hard {
1270 Admission::hard_capped(
1271 config.max_concurrent_transfers,
1272 config.max_transfers_per_principal,
1273 )
1274 .with_budget(budget)
1275 } else {
1276 Admission::with_memory_budget(
1277 config.max_concurrent_transfers,
1278 config.max_transfers_per_principal,
1279 budget,
1280 )
1281 }
1282 // The anonymous door and its width are configured together, so
1283 // an appliance that opens the door cannot forget the ceiling.
1284 .with_anonymous_ceiling(config.max_anonymous_transfers)
1285 .with_wait(wait)
1286 .with_keyed_wait(config.keyed_admission_wait),
1287 );
1288 // The usage share (`admit-share`): the configured policy, unseeded
1289 // until `with_flow` hands it the durable ledger to seed from.
1290 #[cfg(feature = "admit-share")]
1291 let admission = Arc::new(
1292 Arc::try_unwrap(admission)
1293 .expect("the gate is not shared yet")
1294 .with_policy(config.admit.build()),
1295 );
1296 GunnarSsh {
1297 config,
1298 refused_local: None,
1299 shared: Arc::new(Shared {
1300 dispatch: Dispatch::new(control),
1301 transport,
1302 exec_grace,
1303 allow_anonymous,
1304 admission,
1305 metrics: Arc::new(ServerMetrics::new()),
1306 // Ready unless somebody hands us a flag to watch. A listener
1307 // built by a test has nothing to wait for, and a default of
1308 // "not ready" would make every such test hang on a sentence
1309 // about a boot that never happened.
1310 ready: Arc::new(std::sync::atomic::AtomicBool::new(true)),
1311 config_max_auth_attempts,
1312 session_end_grace,
1313 tunnel_door: None,
1314 repo_door: None,
1315 }),
1316 }
1317 }
1318
1319 /// **Watch a readiness flag**, and answer git traffic with a *retryable*
1320 /// sentence until it is set.
1321 ///
1322 /// # The boot window — MEASURED 2026-08-30
1323 ///
1324 /// After a power cut the appliance answered ssh :2222 and grpc :50051
1325 /// **0.6–0.7 s before its stores had finished their post-crash open**, and
1326 /// a read in that window came back `the repository is unavailable; try
1327 /// again`. That sentence is `gunnar_wire::Error::Store`'s, it arrives with
1328 /// a *denial* exit status, and it is what a client is told when a
1329 /// repository is genuinely broken — so a harness could not tell "not yet"
1330 /// from "gone". The first power-cut door reported **64 acked pushes
1331 /// missing**; a boot one second later found every one of them, and the same
1332 /// window wedged a whole bench run's clone and fetch phases.
1333 ///
1334 /// The fix is not to bind later — PID 1 must answer quickly or an operator
1335 /// watching a console sees a dead box — but to answer **honestly**. While
1336 /// the flag is clear every git exec is refused in git's own protocol with
1337 /// [`EXIT_BUSY`] (75, EX_TEMPFAIL — the same status the admission gate
1338 /// uses, which is the status that means *retry*) and a sentence containing
1339 /// the word **starting**, which is the word a script may key on. Nothing is
1340 /// served, nothing is opened, and nothing looks like a missing repository.
1341 ///
1342 /// A flag and not a trait: `gunnar-ssh` may not read the operating system,
1343 /// and "have the stores finished opening" is `gunnar-server`'s fact to
1344 /// publish, not this crate's to discover.
1345 pub fn with_readiness(mut self, ready: Arc<std::sync::atomic::AtomicBool>) -> Self {
1346 // `Arc::get_mut` cannot be used: `bind` has not run, but `Shared` is
1347 // already behind an `Arc`. Rebuilding it is one allocation at start-up
1348 // and keeps every field in one place.
1349 let shared = Arc::try_unwrap(self.shared).unwrap_or_else(|shared| {
1350 panic!(
1351 "readiness must be set before the listener is shared: {} strong refs",
1352 Arc::strong_count(&shared)
1353 )
1354 });
1355 self.shared = Arc::new(Shared { ready, ..shared });
1356 self
1357 }
1358
1359 /// **Refuse every connection that arrives at a local address `refused`
1360 /// names** — closed at accept, nothing said, logged once per peer at
1361 /// debug. `gunnar serve --wg-only` names the utility address: the public's
1362 /// git clients still reach SSH, a box over plain IP does not.
1363 pub fn with_refused_local(mut self, refused: RefusedLocal) -> Self {
1364 self.refused_local = Some(refused);
1365 self
1366 }
1367
1368 /// **Answer [`TUNNEL_ADDRESS_VERB`]** with `door` — `gunnar-server` hands in
1369 /// its `appliance::tunnel_address_answer`, the function both gRPC doors
1370 /// call. Without one the verb is answered "no WireGuard tunnel".
1371 pub fn with_tunnel_address_door(mut self, door: TunnelAddressDoor) -> Self {
1372 let shared = Arc::try_unwrap(self.shared).unwrap_or_else(|shared| {
1373 panic!(
1374 "the tunnel door must be set before the listener is shared: {} strong refs",
1375 Arc::strong_count(&shared)
1376 )
1377 });
1378 self.shared = Arc::new(Shared { tunnel_door: Some(door), ..shared });
1379 self
1380 }
1381
1382 /// **Answer [`REPO_VERB`]** with `door` — `gunnar-server` hands in the
1383 /// control plane's own `Repos` handlers. Without one the verb is answered
1384 /// "this server answers repository settings only on its control plane".
1385 pub fn with_repo_door(mut self, door: RepoDoor) -> Self {
1386 let shared = Arc::try_unwrap(self.shared).unwrap_or_else(|shared| {
1387 panic!(
1388 "the repository door must be set before the listener is shared: {} strong refs",
1389 Arc::strong_count(&shared)
1390 )
1391 });
1392 self.shared = Arc::new(Shared { repo_door: Some(door), ..shared });
1393 self
1394 }
1395
1396 /// **Give the admission gate the per-namespace flow ledger.**
1397 ///
1398 /// The gate is what all three front doors — this exec line, smart HTTP and
1399 /// the gRPC transfer gate — ask before a transfer, so it is the one place a
1400 /// refusal can be charged to a tenant once rather than three times. The
1401 /// exec line's own `no-grant` denial reaches the same ledger back through
1402 /// `Admission::flow`.
1403 ///
1404 /// A listener built without one refuses exactly as it always did and counts
1405 /// the refusal only in its own `AdmissionStats`, which is what a test that
1406 /// drives `gunnar-ssh` alone wants — and what every build before the ledger
1407 /// existed did.
1408 ///
1409 /// The gate is rebuilt rather than mutated for the reason
1410 /// [`Self::with_readiness`] rebuilds `Shared`: `bind` has not run, but the
1411 /// `Arc` is already there.
1412 pub fn with_flow(mut self, flow: Arc<gunnar_core::FlowLedger>) -> Self {
1413 let shared =
1414 Arc::get_mut(&mut self.shared).expect("the shared state is not published until `bind`");
1415 let gate = Arc::try_unwrap(std::mem::replace(
1416 &mut shared.admission,
1417 Arc::new(Admission::unlimited()),
1418 ))
1419 .unwrap_or_else(|gate| {
1420 panic!(
1421 "the flow ledger must be set before the gate is shared: {} strong refs",
1422 Arc::strong_count(&gate)
1423 )
1424 });
1425 // admit-share: the policy is rebuilt SEEDED from this ledger — its
1426 // table is then a cache of the ledger, filled once per namespace.
1427 #[cfg(feature = "admit-share")]
1428 let gate = gate.with_policy(
1429 self.config
1430 .admit
1431 .build_seeded(Some(Admission::flow_seed(Arc::clone(&flow)))),
1432 );
1433 shared.admission = Arc::new(gate.with_flow(flow));
1434 self
1435 }
1436
1437 /// Share the server-wide counters with the rest of the process.
1438 ///
1439 /// **Not a second set of counters.** `gunnar serve` mints one
1440 /// [`ServerMetrics`] and hands the same `Arc` to this listener and to the
1441 /// git transport, so "connections refused" and "pushes rejected by gate"
1442 /// are numbers about one server rather than two crates' private tallies.
1443 /// A listener built without this one still counts, into a set nobody else
1444 /// can read, which is what a test that only drives `gunnar-ssh` wants.
1445 pub fn with_metrics(mut self, metrics: Arc<ServerMetrics>) -> Self {
1446 let shared =
1447 Arc::get_mut(&mut self.shared).expect("the shared state is not published until `bind`");
1448 shared.metrics = metrics;
1449 self
1450 }
1451
1452 /// The counters this listener writes to.
1453 pub fn metrics(&self) -> &Arc<ServerMetrics> {
1454 &self.shared.metrics
1455 }
1456
1457 /// The russh configuration this server runs with.
1458 ///
1459 /// `methods` is publickey **only**, and stays that way even with the
1460 /// anonymous path open: `none` is available for exactly one username,
1461 /// so advertising it to everybody would make the failure list a lie and
1462 /// invite every client to try something that will not work. russh calls
1463 /// [`Handler::auth_none`] on the client's opening probe regardless of what
1464 /// is advertised, which is the only place it is needed.
1465 ///
1466 /// `password` is not offered and there is no handler for it, so the
1467 /// rejecting default is never the last line of defence.
1468 fn russh_config(&self, host_key: russh::keys::PrivateKey) -> RusshConfig {
1469 RusshConfig {
1470 server_id: russh::SshId::Standard(self.config.server_id.clone().into()),
1471 preferred: preferred(),
1472 methods: MethodSet::from(&[MethodKind::PublicKey][..]),
1473 auth_rejection_time: self.config.auth_rejection_time,
1474 auth_rejection_time_initial: Some(Duration::ZERO),
1475 keys: vec![host_key],
1476 max_auth_attempts: self.config.max_auth_attempts,
1477 inactivity_timeout: self.config.inactivity_timeout,
1478 keepalive_interval: self.config.keepalive_interval,
1479 nodelay: true,
1480 ..RusshConfig::default()
1481 }
1482 }
1483
1484 /// Bind the listener and start accepting.
1485 ///
1486 /// Returns once the socket is bound, so a caller (or a test) knows the
1487 /// real address before the first client connects. That matters for
1488 /// [`SshConfig::ephemeral_loopback`], where the port is chosen by the
1489 /// kernel.
1490 pub async fn bind(self, host_key: russh::keys::PrivateKey) -> std::io::Result<BoundServer> {
1491 let listener = TcpListener::bind(self.config.bind).await?;
1492 let local_addr = listener.local_addr()?;
1493 let russh_config = Arc::new(self.russh_config(host_key));
1494 let shared = self.shared.clone();
1495 let admission = Arc::clone(&self.shared.admission);
1496 let metrics = Arc::clone(&self.shared.metrics);
1497 let (handle, _) = tokio::sync::broadcast::channel::<String>(1);
1498
1499 let join = tokio::spawn(accept_loop(
1500 listener,
1501 russh_config,
1502 Factory { shared },
1503 handle.clone(),
1504 self.refused_local.clone(),
1505 ));
1506
1507 tracing::info!(
1508 target: TARGET_SSH,
1509 %local_addr,
1510 max_concurrent_transfers = ?admission.max_concurrent(),
1511 max_transfers_per_principal = ?admission.max_per_principal(),
1512 per_principal_is_hard = admission.per_principal_is_hard(),
1513 "gunnar ssh listener bound"
1514 );
1515 Ok(BoundServer {
1516 local_addr,
1517 handle,
1518 join,
1519 admission,
1520 metrics,
1521 })
1522 }
1523}
1524
1525/// How long the accept loop waits after the kernel refused it a descriptor,
1526/// before it asks again. A session ending in that window frees what the next
1527/// `accept` needs; nothing shorter gains anything, nothing longer is felt.
1528pub const ACCEPT_BACKOFF: Duration = Duration::from_millis(100);
1529
1530/// Is this `accept` failure the kind the loop must outlive?
1531///
1532/// The resource ones — no descriptor left in the process (`EMFILE`) or in the
1533/// system (`ENFILE`), no buffer or memory for the socket — and the one the
1534/// client causes, `ECONNABORTED` (it hung up between SYN and `accept`).
1535/// Everything else (`EBADF`, `EINVAL`, a closed listener) is the listener
1536/// itself being gone, and the loop must return that.
1537pub fn accept_error_is_transient(err: &std::io::Error) -> bool {
1538 // Linux errno values, spelled here rather than through a `libc` crate this
1539 // crate does not otherwise carry: ENOMEM 12, ENFILE 23, EMFILE 24,
1540 // ECONNABORTED 103, ENOBUFS 105.
1541 matches!(err.raw_os_error(), Some(12 | 23 | 24 | 103 | 105))
1542 || matches!(
1543 err.kind(),
1544 std::io::ErrorKind::ConnectionAborted | std::io::ErrorKind::OutOfMemory
1545 )
1546}
1547
1548/// **The accept loop, owned here so that it cannot die of `EMFILE`.**
1549///
1550/// russh's `run_on_socket` is the same loop with one difference that cost a
1551/// whole appliance: its `Err(e) => return Err(e)` on `accept`. MEASURED
1552/// 2026-08-29 on the rig: the 202nd repository touched since boot ran the
1553/// process out of descriptors, the next `accept` failed with `EMFILE`, the
1554/// loop returned, and every later client got `kex_exchange_identification:
1555/// read: Connection reset by peer` until reboot — the kernel kept completing
1556/// handshakes into a backlog nobody drained — while gRPC on its own listener
1557/// answered as if nothing were wrong. A server that has no descriptor for the
1558/// next client must say so and try again in a moment, not resign.
1559///
1560/// So on a transient failure ([`accept_error_is_transient`]) it logs a WARN
1561/// on `gunnar::ssh` — a row on the appliance dashboard — sleeps
1562/// [`ACCEPT_BACKOFF`] and continues. Everything else is what russh did: one
1563/// task per connection, `set_nodelay`, `run_stream`, the session raced against
1564/// the shutdown broadcast so `BoundServer::shutdown` still disconnects every
1565/// live session by application, and session errors go through
1566/// [`note_session_end`] exactly as `Server::handle_session_error` did.
1567async fn accept_loop(
1568 listener: TcpListener,
1569 config: Arc<RusshConfig>,
1570 mut factory: Factory,
1571 shutdown: tokio::sync::broadcast::Sender<String>,
1572 refused_local: Option<RefusedLocal>,
1573) -> std::io::Result<()> {
1574 let mut shutdown_rx = shutdown.subscribe();
1575 let mut refused_in_a_row: u32 = 0;
1576 loop {
1577 tokio::select! {
1578 _ = shutdown_rx.recv() => {
1579 tracing::debug!(target: TARGET_SSH, "ssh listener shutdown requested");
1580 return Ok(());
1581 }
1582 accepted = listener.accept() => {
1583 let (socket, peer) = match accepted {
1584 Ok(pair) => pair,
1585 Err(err) if accept_error_is_transient(&err) => {
1586 refused_in_a_row += 1;
1587 tracing::warn!(
1588 target: TARGET_SSH,
1589 event = "ssh.accept.refused",
1590 error = %err,
1591 refused_in_a_row,
1592 "ssh accept failed: {err}; the listener stays up and retries in {} ms",
1593 ACCEPT_BACKOFF.as_millis()
1594 );
1595 tokio::time::sleep(ACCEPT_BACKOFF).await;
1596 continue;
1597 }
1598 Err(err) => {
1599 tracing::error!(
1600 target: TARGET_SSH,
1601 event = "ssh.accept.failed",
1602 error = %err,
1603 "ssh accept failed with an error the listener cannot outlive"
1604 );
1605 return Err(err);
1606 }
1607 };
1608 if let (Some(refused), Ok(local)) = (&refused_local, socket.local_addr()) {
1609 if refused(local.ip()) {
1610 tracing::debug!(target: TARGET_SSH, event = "ssh.accept.plain_ip_refused", %peer, %local, "a connection at the utility address is refused (--wg-only): boxes speak over the tunnel");
1611 drop(socket);
1612 continue;
1613 }
1614 }
1615 if refused_in_a_row > 0 {
1616 tracing::info!(
1617 target: TARGET_SSH,
1618 event = "ssh.accept.recovered",
1619 refused_in_a_row,
1620 "ssh accept works again"
1621 );
1622 refused_in_a_row = 0;
1623 }
1624 let handler = factory.new_client(Some(peer));
1625 let config = Arc::clone(&config);
1626 let mut session_shutdown = shutdown.subscribe();
1627 tokio::spawn(async move {
1628 if config.nodelay {
1629 if let Err(err) = socket.set_nodelay(true) {
1630 tracing::debug!(target: TARGET_SSH, %err, "set_nodelay failed");
1631 }
1632 }
1633 let session = match russh::server::run_stream(config, socket, handler).await {
1634 Ok(session) => session,
1635 Err(err) => {
1636 note_session_end(&err);
1637 return;
1638 }
1639 };
1640 let handle = session.handle();
1641 tokio::select! {
1642 reason = session_shutdown.recv() => {
1643 let reason = reason.unwrap_or_default();
1644 let _ = handle
1645 .disconnect(russh::Disconnect::ByApplication, reason, String::new())
1646 .await;
1647 }
1648 ended = session => {
1649 if let Err(err) = ended {
1650 note_session_end(&err);
1651 }
1652 }
1653 }
1654 });
1655 }
1656 }
1657 }
1658}
1659
1660/// A bound, running listener.
1661pub struct BoundServer {
1662 local_addr: SocketAddr,
1663 /// The shutdown broadcast every live session and the accept loop listen on.
1664 handle: tokio::sync::broadcast::Sender<String>,
1665 join: JoinHandle<std::io::Result<()>>,
1666 admission: Arc<Admission>,
1667 metrics: Arc<ServerMetrics>,
1668}
1669
1670impl BoundServer {
1671 /// The address actually bound, with the kernel's choice of port filled in.
1672 pub fn local_addr(&self) -> SocketAddr {
1673 self.local_addr
1674 }
1675
1676 /// What the admission gate has done since this listener started.
1677 ///
1678 /// This is the visibility half of the fix. A limit whose saturation cannot
1679 /// be read is the same undiagnosable "git is slow" the accidental 512-thread
1680 /// ceiling produced; `admitted`, `refused_*` and `peak_in_flight` are what
1681 /// an operator, or a test, looks at instead.
1682 pub fn admission(&self) -> AdmissionStats {
1683 self.admission.stats()
1684 }
1685
1686 /// The admission gate itself, so a **second transport can route through the
1687 /// SAME one** (one implementation).
1688 ///
1689 /// `gunnar-http` is a second front door onto the same server, and a git
1690 /// transfer over HTTP has to count against the same server-wide and
1691 /// per-principal ceilings — and the same memory budget — as one over SSH,
1692 /// or an appliance's real concurrency is silently twice the number written
1693 /// on the box. Handing out the `Arc` (rather than rebuilding a gate from
1694 /// the same numbers) is what makes it one gate with one set of counters,
1695 /// not two that happen to agree: on 2026-08-31 the HTTP front was found with no gate
1696 /// at all, and two gates would have been the next-worst answer.
1697 pub fn admission_gate(&self) -> Arc<Admission> {
1698 Arc::clone(&self.admission)
1699 }
1700
1701 /// The server-wide counters.
1702 pub fn metrics(&self) -> gunnar_core::observe::MetricsSnapshot {
1703 self.metrics.snapshot()
1704 }
1705
1706 /// The counter block itself, for a caller that wants to keep reading it
1707 /// after this listener is consumed by [`BoundServer::shutdown`].
1708 pub fn metrics_handle(&self) -> &Arc<ServerMetrics> {
1709 &self.metrics
1710 }
1711
1712 /// Ask every session to disconnect, then wait for the accept loop to stop
1713 /// — for at most [`SSH_SHUTDOWN_GRACE`].
1714 ///
1715 /// **Bounded, the way the gRPC half already is** (`GRPC_SHUTDOWN_GRACE` in
1716 /// gunnar-server): the accept loop only ends when its sessions do, and a
1717 /// session whose peer never answers the disconnect — MEASURED 2026-09-28 on
1718 /// loki, a primary's replication session into a standby being stopped, 1 run
1719 /// in 17 under a parallel test binary — held `shutdown` for an hour. A
1720 /// shutdown that can hang forever is a restart, a drain or a growth that can
1721 /// hang forever. Past the grace the listener task is aborted and the reason
1722 /// is logged; the sessions go with the process.
1723 pub async fn shutdown(self, reason: &str) -> std::io::Result<()> {
1724 self.shutdown_within(reason, SSH_SHUTDOWN_GRACE).await
1725 }
1726
1727 /// [`Self::shutdown`] with an explicit grace (tests use a short one).
1728 pub async fn shutdown_within(self, reason: &str, grace: Duration) -> std::io::Result<()> {
1729 let _ = self.handle.send(reason.to_string());
1730 let abort = self.join.abort_handle();
1731 match tokio::time::timeout(grace, self.join).await {
1732 Ok(Ok(result)) => result,
1733 Ok(Err(err)) if err.is_cancelled() => Ok(()),
1734 Ok(Err(err)) => Err(std::io::Error::other(err)),
1735 Err(_elapsed) => {
1736 tracing::warn!(
1737 target: TARGET_SSH,
1738 ?grace,
1739 "the SSH listener did not stop within its grace: a session did not \
1740 answer the disconnect. Aborting the listener so the shutdown completes."
1741 );
1742 abort.abort();
1743 Ok(())
1744 }
1745 }
1746 }
1747}
1748
1749struct Factory {
1750 shared: Arc<Shared>,
1751}
1752
1753impl Server for Factory {
1754 type Handler = Connection;
1755
1756 fn new_client(&mut self, peer_addr: Option<SocketAddr>) -> Connection {
1757 // ── ONE span per connection, and one id ────────────────────────────
1758 //
1759 // `principal` and `repo` are declared `Empty` and filled in by
1760 // `auth_publickey` and `exec_request` as they become known, so every
1761 // line emitted under this connection carries all three WITHOUT the
1762 // call site repeating them. Before this, connection identity in the
1763 // SSH logs was an ad-hoc `?self.peer` copy-pasted to fourteen call
1764 // sites, and there was no way at all to tie two lines together.
1765 let conn = RequestId::next();
1766 let span = tracing::info_span!(
1767 target: TARGET_SSH,
1768 "ssh.connection",
1769 %conn,
1770 peer = tracing::field::Empty,
1771 principal = tracing::field::Empty,
1772 repo = tracing::field::Empty,
1773 );
1774 if let Some(peer) = peer_addr {
1775 span.record("peer", tracing::field::display(peer));
1776 }
1777 self.shared.metrics.add_connections_opened(1);
1778 span.in_scope(|| tracing::debug!(target: TARGET_SSH, "ssh connection accepted"));
1779 Connection {
1780 shared: self.shared.clone(),
1781 span,
1782 principal: None,
1783 key_fingerprint: None,
1784 channels: HashMap::new(),
1785 exec_seen: Arc::new(AtomicBool::new(false)),
1786 misuse_said: false,
1787 auth_attempts: 0,
1788 session_over: tokio::sync::watch::channel(false).0,
1789 }
1790 }
1791
1792 /// The session loop stopped. Usually because the client hung up, which is
1793 /// how every git client ends a transfer and is not news.
1794 ///
1795 /// A free function does the deciding, for the same reason
1796 /// [`note_teardown`] is one: the rule can then be asserted without standing
1797 /// up a russh session, and what is asserted is the line an operator reads.
1798 fn handle_session_error(&mut self, error: anyhow::Error) {
1799 note_session_end(&error);
1800 }
1801}
1802
1803/// One open session channel, before its exec request arrives.
1804struct OpenChannel {
1805 /// The channel itself. The exec request carries only a [`ChannelId`], and
1806 /// the byte stream can only be taken from the `Channel`.
1807 channel: Channel<Msg>,
1808 /// The value of `GIT_PROTOCOL`, if the client sent it and
1809 /// [`ENV_ALLOWLIST`] accepted the name. Kept beside the channel it was sent
1810 /// on so that it cannot outlive it or be read for a different one.
1811 git_protocol: Option<String>,
1812}
1813
1814/// One client connection.
1815struct Connection {
1816 shared: Arc<Shared>,
1817 /// The `ssh.connection` span every line from this connection is emitted
1818 /// under. Cloned (cheap: it is an id, not the data) rather than borrowed
1819 /// at each entry point, because entering it borrows `self` immutably while
1820 /// every handler needs `&mut self`.
1821 span: tracing::Span,
1822 /// Set by `auth_publickey`, and the only thing that authorises anything.
1823 principal: Option<Principal>,
1824 /// The key `auth_publickey` authenticated this session with.
1825 ///
1826 /// Beside `principal` rather than inside it, because a principal is a
1827 /// server-side identity that may hold several keys and this is the one that
1828 /// made *this* connection. Stays `None` for the anonymous path, which
1829 /// authenticated with no key at all.
1830 key_fingerprint: Option<Fingerprint>,
1831 channels: HashMap<ChannelId, OpenChannel>,
1832 exec_seen: Arc<AtomicBool>,
1833 /// A request for a channel this connection does not hold open (a client's second
1834 /// `exec` on one channel) was said already: WARN once per connection, then quiet —
1835 /// a client's protocol misuse is never the server's ERROR (stinkies ssh-double-exec-error).
1836 misuse_said: bool,
1837 /// **How many publickey offers this connection has had refused.**
1838 ///
1839 /// Counted here because russh does not count it. `SshConfig:: /// max_auth_attempts` is handed to russh 0.61.2's `Config`, which declares
1840 /// the field, defaults it to 10 and `Debug`-prints it — and never compares
1841 /// it to anything. VERIFIED by reading the whole of that crate's source:
1842 /// the only three occurrences are the declaration, the default and the
1843 /// `Debug` impl. (russh 0.63 does compare it, and carries tests named for
1844 /// exactly this; gunnar is pinned to 0.61.2 through an exact `ssh-key`
1845 /// dependency, and a limit that works is not worth an SSH-stack bump to
1846 /// obtain.)
1847 ///
1848 /// So until 2026-09-11 a connection could offer keys without bound: a
1849 /// dictionary of public keys against the identity table, at
1850 /// `auth_rejection_time` apiece, on one TCP connection that never had to be
1851 /// re-established.
1852 auth_attempts: usize,
1853 /// **Set when this session ends** — by `Drop`, because russh drops the
1854 /// handler on every way a session ends (hang-up, unanswered keepalives,
1855 /// inactivity, protocol error, shutdown). Every transfer's writer watches
1856 /// it ([`SessionBound`]): russh's own writer parks on the SSH window and
1857 /// nothing wakes it when the session dies, which left a fetch to a dead
1858 /// client holding its fan worker and admission slot forever (cov-13
1859 /// finding 4, 2026-10-06).
1860 session_over: tokio::sync::watch::Sender<bool>,
1861}
1862
1863impl Drop for Connection {
1864 fn drop(&mut self) {
1865 self.session_over.send_replace(true);
1866 }
1867}
1868
1869/// Why a session that authenticated may no longer act.
1870///
1871/// Two variants and not a `bool`, for [`Control::principal_for_key`]'s reason:
1872/// "nobody holds this key any more" and "the identity table could not be read"
1873/// call for entirely different operator action, and both refuse.
1874#[derive(Debug)]
1875enum Stale {
1876 /// The key that opened this session no longer resolves to anyone, or
1877 /// resolves to somebody else. Revoked, expired, or re-registered.
1878 Revoked,
1879 /// The identity table could not be read. Refused, because failing open is
1880 /// not on the table — the same answer `auth_publickey` gives.
1881 Unreadable(gunnar_core::Error),
1882}
1883
1884impl Connection {
1885 /// **Who this session may act as right now — asked again, per exec.**
1886 ///
1887 /// `auth_publickey` caches the principal, and until 2026-09-11 every exec
1888 /// on the connection was authorised out of that cache. Revocation
1889 /// therefore took effect immediately for a NEW connection and never for an
1890 /// open one: `DocRef::read` caches nothing, so the identity table was
1891 /// current the whole time and nothing asked it. A long-lived session — and
1892 /// git over SSH holds one open for as long as a client wants to keep
1893 /// pushing — outlived the credential that opened it, for as long as it
1894 /// liked. An operator who revokes a leaked key and sees the revocation take
1895 /// effect on their own next connection has every reason to believe it took
1896 /// effect everywhere.
1897 ///
1898 /// Cheap enough to do per exec: it is the same single
1899 /// `principal_by_fingerprint` lookup the connection already pays once at
1900 /// auth, and an exec is about to fork a git process and move a pack.
1901 ///
1902 /// A key that now belongs to a DIFFERENT identity is refused rather than
1903 /// adopted. This session authenticated as somebody; if the key has since
1904 /// been registered to somebody else, this is not that session, and
1905 /// continuing as the new holder would make re-registration a way to inherit
1906 /// an open connection.
1907 ///
1908 /// The anonymous path has no fingerprint — it authenticated with no key at
1909 /// all — so there is nothing to re-read, and `Principal::anonymous()` is not
1910 /// in the identity table to be revoked from. It keeps the cached value, and
1911 /// what anonymity may DO is still `Dispatch::authorise`'s answer.
1912 fn live_principal(&self) -> Result<Principal, Stale> {
1913 let Some(cached) = self.principal.clone() else {
1914 return Err(Stale::Revoked);
1915 };
1916 let Some(fingerprint) = self.key_fingerprint.as_ref() else {
1917 return Ok(cached);
1918 };
1919 match self
1920 .shared
1921 .dispatch
1922 .control()
1923 .principal_for_key(fingerprint)
1924 {
1925 Ok(Some(now)) if now.id == cached.id => Ok(now),
1926 Ok(_) => Err(Stale::Revoked),
1927 Err(err) => Err(Stale::Unreadable(err)),
1928 }
1929 }
1930
1931 /// **Count a refused publickey offer, and say whether this connection has
1932 /// had its last one.**
1933 ///
1934 /// One place, called from every refusing arm of `auth_publickey`, so a new
1935 /// refusal reason cannot arrive uncounted — which is how a limit stops
1936 /// applying to exactly the case somebody added last.
1937 ///
1938 /// `0` is no limit, which is russh's own reading of the same field and the
1939 /// reading an operator who writes `0` expects.
1940 ///
1941 /// The `none` probe is deliberately NOT counted. Every OpenSSH client opens
1942 /// with one to learn the method list, so counting it would spend one of the
1943 /// six on the ordinary first packet of an ordinary session — and it carries
1944 /// no key, so it cannot be the dictionary attempt the limit is for.
1945 fn refused_auth(&mut self) -> bool {
1946 self.auth_attempts += 1;
1947 let max = self.shared.config_max_auth_attempts;
1948 max > 0 && self.auth_attempts >= max
1949 }
1950
1951 /// The error that ends a connection which has offered too many keys.
1952 ///
1953 /// An `Err` out of a handler, because russh 0.61.2's `auth_publickey` is
1954 /// handed no session and no handle, so there is nothing to call
1955 /// `disconnect` on — and the run loop treating a handler error as the end
1956 /// of the session is exactly the outcome wanted. It is a `warn!`, not a
1957 /// `debug!`: one of these is a client with a full agent, and a hundred is
1958 /// somebody reading the identity table one key at a time.
1959 fn too_many_auth_attempts(&self) -> anyhow::Error {
1960 tracing::warn!(
1961 target: TARGET_SSH,
1962 event = "ssh.auth.too_many",
1963 attempts = self.auth_attempts,
1964 max = self.shared.config_max_auth_attempts,
1965 "disconnecting: too many refused publickey offers on one connection"
1966 );
1967 self.shared.metrics.add_connections_refused(1);
1968 anyhow::anyhow!(
1969 "too many authentication failures ({} refused publickey offers)",
1970 self.auth_attempts
1971 )
1972 }
1973}
1974
1975impl Handler for Connection {
1976 type Error = anyhow::Error;
1977
1978 /// **The anonymous read path.** Accept the `none` method for exactly
1979 /// one username, and refuse it for every other.
1980 ///
1981 /// The refusing branch is byte-for-byte what russh's default handler did
1982 /// before this method existed: `Auth::reject()`, which makes russh drop
1983 /// `MethodKind::None` from the advertised set and let the client proceed to
1984 /// publickey. So a client that does not ask for anonymity is on exactly the
1985 /// path it was on yesterday.
1986 ///
1987 /// The accepting branch does **not** consult the catalog, the repository or
1988 /// the ACL: it establishes *who* is asking (nobody), and *what nobody may
1989 /// do* is `Dispatch::authorise`'s answer, through
1990 /// [`AuthTable::may`](gunnar_core::AuthTable::may), like everyone else.
1991 /// Deciding here would be a second ACL.
1992 async fn auth_none(&mut self, user: &str) -> Result<Auth, Self::Error> {
1993 let span = self.span.clone();
1994 let _entered = span.enter();
1995 if !self.shared.allow_anonymous || user != ANONYMOUS_SSH_USER {
1996 // Not a refusal worth a `warn!`: EVERY OpenSSH client opens with a
1997 // `none` probe to learn the method list, so this is the ordinary
1998 // first packet of an ordinary authenticated session.
1999 tracing::debug!(
2000 target: TARGET_SSH,
2001 event = "ssh.auth.none.refused",
2002 reason = if self.shared.allow_anonymous {
2003 "not-the-anonymous-user"
2004 } else {
2005 "anonymous-access-disabled"
2006 },
2007 decorative_ssh_user = %user,
2008 "the none method is refused; publickey is the only way in"
2009 );
2010 return Ok(Auth::reject());
2011 }
2012
2013 let anonymous = Principal::anonymous();
2014 span.record("principal", tracing::field::display(&anonymous.id));
2015 self.shared.metrics.add_connections_anonymous(1);
2016 tracing::info!(
2017 target: TARGET_SSH,
2018 event = "ssh.auth.anonymous",
2019 // Named so nobody later reads this line as "a key was accepted".
2020 // It is on `gunnar::ssh` at `info` because "who is reading my
2021 // public repositories" must be answerable from a production log.
2022 authenticated = false,
2023 "anonymous session accepted: no key, public repositories only"
2024 );
2025 self.principal = Some(anonymous);
2026 Ok(Auth::Accept)
2027 }
2028
2029 async fn auth_publickey(
2030 &mut self,
2031 user: &str,
2032 public_key: &PublicKey,
2033 ) -> Result<Auth, Self::Error> {
2034 let span = self.span.clone();
2035 let _entered = span.enter();
2036 // Over the key's WIRE BLOB, not over its type: russh's `ssh-key` is
2037 // 0.7.0-rc.10 and `gunnar-core`'s is 0.6.7, so this is the only value
2038 // that can reach the identity table. It is byte-for-byte the
2039 // string `ssh-keygen -lf` prints for the same key.
2040 //
2041 // `None` means the key would not re-encode. That used to be an
2042 // `expect()`, a panic in the auth handler, over client-supplied bytes.
2043 // It is a refusal now; `fingerprint_of_key` has already
2044 // logged why.
2045 let Some(fingerprint) = fingerprint_of_key(public_key) else {
2046 let refusal = refuse_unencodable_key(&self.shared.metrics, user);
2047 if self.refused_auth() {
2048 return Err(self.too_many_auth_attempts());
2049 }
2050 return Ok(refusal);
2051 };
2052 let started = std::time::Instant::now();
2053 // `peer` is a field of the enclosing span from here down, so it is not
2054 // repeated on any line below (one implementation, and the whole point of the span).
2055 match self
2056 .shared
2057 .dispatch
2058 .control()
2059 .principal_for_key(&fingerprint)
2060 {
2061 Ok(Some(principal)) => {
2062 span.record("principal", tracing::field::display(&principal.id));
2063 self.shared.metrics.add_connections_accepted(1);
2064 tracing::info!(
2065 target: TARGET_SSH,
2066 event = "ssh.auth.accepted",
2067 %fingerprint,
2068 // Logged so an operator can see what was sent, and named so
2069 // nobody later mistakes it for an input to the decision.
2070 decorative_ssh_user = %user,
2071 elapsed_ms = started.elapsed().as_millis() as u64,
2072 "publickey accepted"
2073 );
2074 self.principal = Some(principal);
2075 // Kept, not recomputed and not dropped. This is the
2076 // value the identity table was probed with one line above, so
2077 // it is the key that authenticated, by construction.
2078 self.key_fingerprint = Some(fingerprint);
2079 Ok(Auth::Accept)
2080 }
2081 Ok(None) => {
2082 self.shared.metrics.add_connections_refused(1);
2083 tracing::warn!(
2084 target: TARGET_SSH,
2085 event = "ssh.auth.refused",
2086 reason = "unknown-key",
2087 %fingerprint,
2088 decorative_ssh_user = %user,
2089 elapsed_ms = started.elapsed().as_millis() as u64,
2090 "publickey refused: no principal holds this key"
2091 );
2092 if self.refused_auth() {
2093 return Err(self.too_many_auth_attempts());
2094 }
2095 Ok(Auth::reject())
2096 }
2097 // The key is still refused, since failing open is not on the table, but
2098 // this is a FAULT, not "unknown key", and the log has to say so.
2099 // An identity table that has become unreadable looks exactly like
2100 // an empty one from the client's side (the ACL model).
2101 Err(err) => {
2102 self.shared.metrics.add_connections_refused(1);
2103 self.shared.metrics.add_auth_faults(1);
2104 tracing::error!(
2105 target: TARGET_SSH,
2106 event = "ssh.auth.refused",
2107 reason = "identity-table-unreadable",
2108 %fingerprint,
2109 decorative_ssh_user = %user,
2110 elapsed_ms = started.elapsed().as_millis() as u64,
2111 %err,
2112 "publickey refused: the identity table could not be read"
2113 );
2114 if self.refused_auth() {
2115 return Err(self.too_many_auth_attempts());
2116 }
2117 Ok(Auth::reject())
2118 }
2119 }
2120 }
2121
2122 async fn channel_open_session(
2123 &mut self,
2124 channel: Channel<Msg>,
2125 // russh 0.63 (2026-10-03): the open is answered through this handle, not
2126 // a returned bool; dropping it unanswered would refuse the channel.
2127 reply: russh::server::ChannelOpenHandle,
2128 session: &mut Session,
2129 ) -> Result<(), Self::Error> {
2130 // The exec request arrives later, carrying only a `ChannelId`, and the
2131 // byte stream can only be taken from the `Channel` itself, so it is
2132 // kept here. russh's own sftp example does the same.
2133 self.channels.insert(
2134 channel.id(),
2135 OpenChannel {
2136 channel,
2137 git_protocol: None,
2138 },
2139 );
2140
2141 // A session that authenticates, opens a channel and then does nothing is
2142 // not idle, because it answers keepalives, so the inactivity timeout never
2143 // fires and the connection would be held indefinitely. Arm a watchdog.
2144 if let Some(grace) = self.shared.exec_grace {
2145 let handle = session.handle();
2146 let exec_seen = self.exec_seen.clone();
2147 // `.instrument`, not a captured `peer`: a spawned task does NOT
2148 // inherit the thread-local span, so the watchdog's line would
2149 // otherwise be the one line in the whole connection that could not
2150 // be tied back to it.
2151 let span = self.span.clone();
2152 tokio::spawn(
2153 async move {
2154 tokio::time::sleep(grace).await;
2155 if !exec_seen.load(Ordering::SeqCst) {
2156 tracing::info!(
2157 target: TARGET_SSH,
2158 event = "ssh.watchdog.disconnect",
2159 ?grace,
2160 "disconnecting: authenticated but never asked for a git command"
2161 );
2162 note_teardown(
2163 "watchdog-disconnect",
2164 handle
2165 .disconnect(
2166 Disconnect::ByApplication,
2167 "no git command requested".to_string(),
2168 String::new(),
2169 )
2170 .await,
2171 );
2172 }
2173 }
2174 .instrument(span),
2175 );
2176 }
2177 reply.accept().await;
2178 Ok(())
2179 }
2180
2181 async fn exec_request(
2182 &mut self,
2183 channel: ChannelId,
2184 data: &[u8],
2185 session: &mut Session,
2186 ) -> Result<(), Self::Error> {
2187 self.exec_seen.store(true, Ordering::SeqCst);
2188 let span = self.span.clone();
2189 let _entered = span.enter();
2190
2191 // **The credential is re-read here, not remembered.** See
2192 // [`Connection::live_principal`]: russh will not dispatch an exec
2193 // before authentication succeeds, so an unauthenticated session is
2194 // unreachable rather than checked — but a session whose key was
2195 // REVOKED while it was open is entirely reachable, and until
2196 // 2026-09-11 it was authorised out of a cache filled at auth time.
2197 let principal = match self.live_principal() {
2198 Ok(principal) => principal,
2199 Err(stale) => {
2200 self.shared.metrics.add_exec_refused(1);
2201 let (reason, detail) = match &stale {
2202 Stale::Revoked => ("key-revoked", String::new()),
2203 Stale::Unreadable(err) => ("identity-table-unreadable", format!("{err}")),
2204 };
2205 tracing::warn!(
2206 target: TARGET_SSH,
2207 event = "ssh.exec.denied",
2208 reason,
2209 fingerprint = self.key_fingerprint.as_ref().map(tracing::field::display),
2210 detail = %detail,
2211 "exec denied: the key that opened this session no longer authorises it"
2212 );
2213 // Answered in git's own protocol, like every other denial on
2214 // this path: an `ERR ` pkt-line is what `git` prints verbatim
2215 // after `remote: `. A bare `channel_failure` here would put the
2216 // client back on "Could not read from remote repository", which
2217 // is the failure `report_error` was found unused for.
2218 session.channel_success(channel)?;
2219 session.data(channel, err_packet(REVOKED_MESSAGE)?)?;
2220 session.exit_status_request(channel, EXIT_DENIED)?;
2221 session.close(channel)?;
2222 // And the session goes with it. Refusing the one exec would
2223 // leave the connection open for the next one, which is the
2224 // finding restated a request later: a revoked key must not keep
2225 // a channel it can keep asking on.
2226 note_teardown(
2227 "revoked-key-disconnect",
2228 session
2229 .handle()
2230 .disconnect(
2231 Disconnect::ByApplication,
2232 "the key that opened this session no longer authorises it".to_string(),
2233 String::new(),
2234 )
2235 .await,
2236 );
2237 return Ok(());
2238 }
2239 };
2240
2241 // ── the operator's fire drill: ONE ERROR on purpose ─────────────
2242 //
2243 // What the estate's watch raises to prove its alert path end to end (estate-box
2244 // 8A). Held to server-wide Admin before it says anything; an anonymous session
2245 // is refused the channel like the tunnel verb below.
2246 if std::str::from_utf8(data).map(str::trim) == Ok(FIRE_DRILL_VERB) {
2247 if self.key_fingerprint.is_none() {
2248 tracing::warn!(target: TARGET_SSH, event = "ssh.exec.refused", reason = "anonymous-control-verb", "exec refused: {FIRE_DRILL_VERB} needs a key");
2249 session.channel_failure(channel)?;
2250 return Ok(());
2251 }
2252 let (exit, out) = match self.shared.dispatch.control().auth().may_server(&principal.id, gunnar_core::Level::Admin) {
2253 Ok(true) => {
2254 tracing::error!(
2255 target: TARGET_SSH,
2256 event = "ssh.fire_drill",
2257 principal = %principal.id,
2258 "fire drill: {} asked for this ERROR to prove the alert path end to end — nothing is wrong",
2259 principal.id
2260 );
2261 (0, "fire drill: one ERROR said on this server's log (nothing is wrong)\n".to_string())
2262 }
2263 Ok(false) => {
2264 tracing::warn!(target: TARGET_SSH, event = "ssh.exec.denied", reason = "not-server-admin", principal = %principal.id, "{FIRE_DRILL_VERB} refused");
2265 (EXIT_DENIED, format!("error: {FIRE_DRILL_VERB} needs server-wide Admin, which {} does not hold\n", principal.id))
2266 }
2267 Err(err) => (EXIT_DENIED, format!("error: the identity table could not be read: {err}\n")),
2268 };
2269 session.channel_success(channel)?;
2270 session.data(channel, out.into_bytes())?;
2271 session.exit_status_request(channel, exit)?;
2272 session.close(channel)?;
2273 return Ok(());
2274 }
2275
2276 // ── git-lfs's fallback: answered, never a channel failure (2026-10-25) ──
2277 if std::str::from_utf8(data).ok().and_then(|l| l.split_whitespace().next()) == Some(LFS_AUTHENTICATE_VERB) {
2278 tracing::info!(
2279 target: TARGET_SSH,
2280 event = "ssh.lfs_authenticate.answered",
2281 principal = %principal.id,
2282 command = %String::from_utf8_lossy(data),
2283 "git-lfs asked for its HTTPS fallback: its pure-SSH transfer failed or was refused just before"
2284 );
2285 session.channel_success(channel)?;
2286 session.extended_data(channel, 1, LFS_AUTHENTICATE_MESSAGE.as_bytes().to_vec())?;
2287 session.exit_status_request(channel, 1)?;
2288 session.close(channel)?;
2289 return Ok(());
2290 }
2291
2292 // ── who this key is (wiring tracer B 2026-10-08) ──
2293 if std::str::from_utf8(data).map(str::trim) == Ok(WHOAMI_VERB) {
2294 if self.key_fingerprint.is_none() {
2295 tracing::warn!(target: TARGET_SSH, event = "ssh.exec.refused", reason = "anonymous-control-verb", "exec refused: {WHOAMI_VERB} needs a key");
2296 session.channel_failure(channel)?;
2297 return Ok(());
2298 }
2299 session.channel_success(channel)?;
2300 session.data(channel, format!("{}\n", principal.id).into_bytes())?;
2301 session.exit_status_request(channel, 0)?;
2302 session.close(channel)?;
2303 return Ok(());
2304 }
2305
2306 // ── a repository's settings (owner, 2026-10-14) ──
2307 //
2308 // Decided by the control plane's own `Repos` handlers through
2309 // [`RepoDoor`]: this listener only proves who asks (the key, re-read
2310 // above) and carries the answer. An anonymous session is refused the
2311 // channel, before the pause and the plan gates (not a transfer).
2312 if let Some(parsed) = parse_repo_verb(data) {
2313 let Some(fingerprint) = self.key_fingerprint.as_ref().map(|f| f.to_string()) else {
2314 tracing::warn!(target: TARGET_SSH, event = "ssh.exec.refused", reason = "anonymous-control-verb", "exec refused: {REPO_VERB} needs a key");
2315 session.channel_failure(channel)?;
2316 return Ok(());
2317 };
2318 let (exit, out) = match parsed {
2319 Err(why) => (1, format!("error: {why}\n")),
2320 Ok((repo, action)) => match self.shared.repo_door.clone() {
2321 None => (
2322 1,
2323 "error: this server answers repository settings only on its control plane\n".to_string(),
2324 ),
2325 Some(door) => {
2326 let ask = RepoAsk { principal: principal.id.clone(), fingerprint, repo: repo.clone(), action: action.clone() };
2327 let answer = door(ask).await;
2328 tracing::info!(
2329 target: TARGET_SSH,
2330 event = "ssh.control",
2331 verb = REPO_VERB,
2332 principal = %principal.id,
2333 repo = %repo,
2334 action = ?action,
2335 decision = if answer.is_ok() { "allow" } else { "deny" },
2336 "repository settings asked over the forge's door"
2337 );
2338 match answer {
2339 Ok(said) => (0, if said.ends_with('\n') { said } else { format!("{said}\n") }),
2340 Err(why) => (EXIT_DENIED, format!("error: {why}\n")),
2341 }
2342 }
2343 },
2344 };
2345 session.channel_success(channel)?;
2346 session.data(channel, out.into_bytes())?;
2347 session.exit_status_request(channel, exit)?;
2348 session.close(channel)?;
2349 return Ok(());
2350 }
2351
2352 // ── a member's keys for an encrypted repository's ring (2026-10-06) ──
2353 //
2354 // A read of the identity table, held to the same rule as
2355 // `Repos.RecipientKeys` (see [`recipient_keys_answer`]). Before the
2356 // pause and the plan gates for the tunnel verb's reason: not a
2357 // transfer. An anonymous session is refused the channel.
2358 if let Some(parsed) = parse_recipient_keys_verb(data) {
2359 if self.key_fingerprint.is_none() {
2360 tracing::warn!(target: TARGET_SSH, event = "ssh.exec.refused", reason = "anonymous-control-verb", "exec refused: {RECIPIENT_KEYS_VERB} needs a key");
2361 session.channel_failure(channel)?;
2362 return Ok(());
2363 }
2364 let (exit, out) = match parsed {
2365 Err(why) => (1, format!("error: {why}\n")),
2366 Ok((repo, member)) => {
2367 let (exit, out) = recipient_keys_answer(self.shared.dispatch.control(), &principal.id, &repo, &member);
2368 tracing::info!(
2369 target: TARGET_SSH,
2370 event = "ssh.control",
2371 verb = RECIPIENT_KEYS_VERB,
2372 principal = %principal.id,
2373 repo = %repo,
2374 member = %member,
2375 decision = if exit == 0 { "allow" } else { "deny" },
2376 "recipient keys asked over the forge's door"
2377 );
2378 (exit, out)
2379 }
2380 };
2381 session.channel_success(channel)?;
2382 session.data(channel, out.into_bytes())?;
2383 session.exit_status_request(channel, exit)?;
2384 session.close(channel)?;
2385 return Ok(());
2386 }
2387
2388 // ── the caller's own encryption key (CRYPT-YUBI 2026-10-26) ──────
2389 //
2390 // The session's principal reads or changes ITS OWN key and methods: the
2391 // public half, and wraps that are ciphertext to this server. Not a
2392 // transfer; an anonymous session is refused the channel.
2393 if let Some(parsed) = gunnar_crypt::door::parse_request(data) {
2394 if self.key_fingerprint.is_none() {
2395 tracing::warn!(target: TARGET_SSH, event = "ssh.exec.refused", reason = "anonymous-control-verb", "exec refused: {} needs a key", gunnar_crypt::door::VERB);
2396 session.channel_failure(channel)?;
2397 return Ok(());
2398 }
2399 let (exit, out) = match parsed {
2400 Err(why) => (1, format!("error: {why}\n")),
2401 Ok(request) => {
2402 let verb = match &request {
2403 gunnar_crypt::door::Request::Get => "get",
2404 gunnar_crypt::door::Request::Create { .. } => "create",
2405 gunnar_crypt::door::Request::Add(_) => "add",
2406 gunnar_crypt::door::Request::Remove(_) => "remove",
2407 };
2408 let (exit, out) = user_key_answer(self.shared.dispatch.control(), &principal, request);
2409 tracing::info!(
2410 target: TARGET_SSH,
2411 event = "ssh.control",
2412 verb = gunnar_crypt::door::VERB,
2413 action = verb,
2414 principal = %principal.id,
2415 decision = if exit == 0 { "allow" } else { "deny" },
2416 "own encryption key over the forge's door"
2417 );
2418 (exit, out)
2419 }
2420 };
2421 session.channel_success(channel)?;
2422 session.data(channel, out.into_bytes())?;
2423 session.exit_status_request(channel, exit)?;
2424 session.close(channel)?;
2425 return Ok(());
2426 }
2427
2428 // ── the ONE control verb: the tunnel address (T17) ─────────────
2429 //
2430 // Before the pause and the plan gates: those are about transfers, and
2431 // this is not one. Never through `Dispatch::authorise`, which knows
2432 // only git verbs. An anonymous session gets the channel refused like a
2433 // shell would; everyone else is held to server-wide Admin BEFORE the
2434 // door runs.
2435 if let Some(parsed) = parse_tunnel_address_verb(data) {
2436 if self.key_fingerprint.is_none() {
2437 tracing::warn!(target: TARGET_SSH, event = "ssh.exec.refused", reason = "anonymous-control-verb", "exec refused: {TUNNEL_ADDRESS_VERB} needs a key");
2438 session.channel_failure(channel)?;
2439 return Ok(());
2440 }
2441 let (exit, out) = match self
2442 .shared
2443 .dispatch
2444 .control()
2445 .auth()
2446 .may_server(&principal.id, gunnar_core::Level::Admin)
2447 {
2448 Ok(false) => {
2449 tracing::warn!(target: TARGET_SSH, event = "ssh.exec.denied", reason = "not-server-admin", principal = %principal.id, "{TUNNEL_ADDRESS_VERB} refused");
2450 (EXIT_DENIED, format!("error: {TUNNEL_ADDRESS_VERB} needs server-wide Admin, which {} does not hold\n", principal.id))
2451 }
2452 Err(err) => (EXIT_DENIED, format!("error: the identity table could not be read: {err}\n")),
2453 Ok(true) => match parsed {
2454 Err(why) => (1, format!("error: {why}\n")),
2455 Ok(address) => match &self.shared.tunnel_door {
2456 None => (1, "error: this box has no WireGuard tunnel (built without wg-client)\n".to_string()),
2457 Some(door) => match door(&address) {
2458 Ok(answer) => {
2459 tracing::warn!(target: TARGET_SSH, event = "ssh.control", verb = TUNNEL_ADDRESS_VERB, principal = %principal.id, address = %address, decision = "allow", "tunnel address door answered");
2460 (0, if answer.ends_with('\n') { answer } else { format!("{answer}\n") })
2461 }
2462 Err(why) => {
2463 tracing::warn!(target: TARGET_SSH, event = "ssh.control", verb = TUNNEL_ADDRESS_VERB, principal = %principal.id, address = %address, decision = "deny", reason = %why, "tunnel address door refused");
2464 (1, format!("error: {why}\n"))
2465 }
2466 },
2467 },
2468 },
2469 };
2470 session.channel_success(channel)?;
2471 session.data(channel, out.into_bytes())?;
2472 session.exit_status_request(channel, exit)?;
2473 session.close(channel)?;
2474 return Ok(());
2475 }
2476
2477 // ── the PAUSED door, before the plan gates ──────────────────────
2478 //
2479 // MEASURED under KVM (bench R1, 2026-09-15): with the gate paused for
2480 // a growth and `/data` already unmounted, a push knocked, the plan
2481 // gates ran FIRST, and the disk-floor check statvfs'd the read-only
2482 // guard tmpfs under the mountpoint — the client was told "/data has
2483 // 64.0 KiB free … no push until space is reclaimed (`gunnar control
2484 // repo delete --purge`)". The wrong sentence, with advice to delete
2485 // repositories, on a box that is growing. The pause is the box's own
2486 // state and says nothing about any repository, so it is answered
2487 // before the command is even resolved: the same words and the same
2488 // EX_TEMPFAIL for every principal and every path.
2489 if let Some(pause) = self.shared.admission.paused() {
2490 self.shared.admission.note_refused_paused();
2491 tracing::info!(
2492 target: TARGET_GIT,
2493 event = "git.transfer.refused",
2494 reason = pause.reason(),
2495 command = %String::from_utf8_lossy(data),
2496 "transfer REFUSED: the admission gate is paused"
2497 );
2498 session.channel_success(channel)?;
2499 session.data(channel, err_packet(pause.words())?)?;
2500 session.exit_status_request(channel, EXIT_BUSY)?;
2501 session.close(channel)?;
2502 return Ok(());
2503 }
2504
2505 let request =
2506 match self
2507 .shared
2508 .dispatch
2509 .authorise(&principal, self.key_fingerprint.as_ref(), data)
2510 {
2511 Ok(request) => request,
2512 Err(err) => {
2513 self.shared.metrics.add_exec_refused(1);
2514 // **THE counting point for a tenant's `auth_failures`**: a
2515 // principal that authenticated and then held no grant on
2516 // the repository it named.
2517 //
2518 // Only `Denied`, and deliberately only `Denied`. The other
2519 // arms are a different sentence: `NoSuchRepo` hides a
2520 // typo behind the same wire message on purpose and would
2521 // charge a namespace that may not exist; `Standby` and
2522 // `Plan` are the box and the plan refusing, not the
2523 // credential; `Command` never named a repository at all.
2524 // And the OTHER half of "authentication failed" — a key
2525 // that resolves to nobody — happens before any exec line
2526 // and belongs to no namespace, so it stays where it is, on
2527 // the box's own `connections_refused`.
2528 if let (DispatchError::Denied { repo, .. }, Some(flow)) =
2529 (&err, self.shared.admission.flow())
2530 {
2531 flow.auth_failure(repo.namespace(), gunnar_core::now_ms());
2532 }
2533 let raw = String::from_utf8_lossy(data);
2534 match err.client_message() {
2535 // Not a git command at all: `bash`, `scp`, an empty
2536 // string. Refuse the channel request itself; the client is
2537 // not speaking a protocol that could read a reply.
2538 // git-lfs asks SSH for its credentials (`git-lfs-authenticate`,
2539 // `git-lfs-transfer`) before every transfer and goes to its
2540 // https endpoint when refused: a client's known first step,
2541 // said at INFO (RUN A 2026-10-08: seven a minute during one LFS
2542 // push failed the log gate as WARN spam). Anything else stays WARN.
2543 None if is_lfs_over_ssh(&raw) => {
2544 tracing::info!(
2545 target: TARGET_SSH,
2546 event = "ssh.exec.refused",
2547 reason = "lfs-over-ssh",
2548 command = %raw,
2549 "exec refused: git-lfs asks SSH first and uses its https endpoint"
2550 );
2551 session.channel_failure(channel)?;
2552 }
2553 None => {
2554 tracing::warn!(
2555 target: TARGET_SSH,
2556 event = "ssh.exec.refused",
2557 reason = "not-a-git-command",
2558 command = %raw,
2559 %err,
2560 "exec refused"
2561 );
2562 session.channel_failure(channel)?;
2563 }
2564 // A git client asked for something it may not have. Accept
2565 // the channel and answer in its own protocol, so it prints
2566 // the reason instead of "Could not read from remote
2567 // repository".
2568 Some(message) => {
2569 tracing::warn!(
2570 target: TARGET_SSH,
2571 event = "ssh.exec.denied",
2572 // The distinction the *wire* deliberately hides:
2573 // "no such repository" and "no permission" are one
2574 // string to the client so a caller cannot enumerate
2575 // private repositories. The log keeps it.
2576 reason = match &err {
2577 DispatchError::NoSuchRepo(_) => "no-such-repository",
2578 DispatchError::Denied { .. } => "no-grant",
2579 DispatchError::Standby { .. } => "standby-read-only",
2580 DispatchError::Twin { .. } => "twin-serves-no-git",
2581 DispatchError::AnonymousElsewhere { .. } => {
2582 "anonymous-elsewhere"
2583 }
2584 DispatchError::Plan { .. } => "gate-refused",
2585 DispatchError::Store(_) => "control-plane-unavailable",
2586 DispatchError::Command(_) => "not-a-git-command",
2587 },
2588 command = %raw,
2589 %err,
2590 "exec denied"
2591 );
2592 session.channel_success(channel)?;
2593 session.data(channel, err_packet(&message)?)?;
2594 session.exit_status_request(channel, EXIT_DENIED)?;
2595 session.close(channel)?;
2596 }
2597 }
2598 return Ok(());
2599 }
2600 };
2601
2602 let Some(open) = self.channels.remove(&channel) else {
2603 // The CLIENT's misuse (a second exec on one channel, or a channel never
2604 // opened): refused, said at WARN once per connection — any caller that may
2605 // run one git command could otherwise raise the server's ERROR at will.
2606 if std::mem::replace(&mut self.misuse_said, true) {
2607 tracing::debug!(target: TARGET_SSH, ?channel, "exec request for a channel that is not open (said already on this connection)");
2608 } else {
2609 tracing::warn!(
2610 target: TARGET_SSH,
2611 event = "ssh.exec.misuse",
2612 ?channel,
2613 "exec request for a channel that is not open (a second exec on one channel, or one never opened) — refused; said once per connection"
2614 );
2615 }
2616 session.channel_failure(channel)?;
2617 return Ok(());
2618 };
2619
2620 // The repository is known from here on, so it goes on the CONNECTION
2621 // span: every line the transfer emits underneath inherits it, and the
2622 // "which repository was that connection touching" question is answered
2623 // even for a line that has nothing to do with git.
2624 span.record("repo", tracing::field::display(&request.repo));
2625
2626 // Attached *after* the decision above, never before it: an environment
2627 // variable selects the framing of the answer and nothing else.
2628 let request = request.with_git_protocol(open.git_protocol);
2629
2630 // ── the explicit ceiling ───────────────────────────────────────────
2631 //
2632 // After authorisation, deliberately. "The server is busy" is a fact
2633 // about the server, and telling it to a client that may not touch this
2634 // repository at all would leak that the repository exists. The order
2635 // also means the gate meters *transfers gunnar was going to serve*,
2636 // which is what the counter is supposed to mean.
2637 //
2638 // It refuses rather than queues; `crate::admission` sets out why at
2639 // length. In one line: a git client retries, and a fast refusal with a
2640 // sentence in it beats a socket that goes quiet while still holding the
2641 // session, the channel and a slot.
2642 // The class the governor meters this operation as. `git-upload-pack` is
2643 // clone, fetch AND ls-remote on the wire and cannot be told apart before
2644 // the stream is open, which is *after* this decision by design; see
2645 // `OpClass::for_ssh_service` for what that costs and why the middle
2646 // class is the right guess.
2647 // ── the BOOT WINDOW door, before admission ─────────────────────────
2648 //
2649 // After the repository is known and authorised, so a stranger cannot
2650 // learn from this whether a repository exists, and before a slot is
2651 // taken, so a boot does not spend its gate on requests it cannot serve.
2652 // See `GunnarSsh::with_readiness` for what was measured.
2653 // A KEYED caller is queued for the stores to open, up to its keyed
2654 // wait: a restart (a release, an upgrade) lasts seconds, and git-lfs's
2655 // pure-SSH transfer cannot retry a refusal — it falls back to
2656 // `git-lfs-authenticate` and fails the push (gunnar.rs 2026-10-25). A
2657 // stranger is still answered at once.
2658 if !self.shared.ready.load(std::sync::atomic::Ordering::Relaxed)
2659 && request.principal.id != gunnar_core::ANONYMOUS_PRINCIPAL_ID
2660 {
2661 let until = std::time::Instant::now() + self.shared.admission.wait_for(&request.principal.id);
2662 while !self.shared.ready.load(std::sync::atomic::Ordering::Relaxed) && std::time::Instant::now() < until {
2663 tokio::time::sleep(std::time::Duration::from_millis(100)).await;
2664 }
2665 }
2666 if !self.shared.ready.load(std::sync::atomic::Ordering::Relaxed) {
2667 tracing::info!(
2668 target: TARGET_GIT,
2669 event = "git.transfer.refused",
2670 reason = "starting",
2671 service = %request.service,
2672 "transfer REFUSED: the stores are still opening after a restart"
2673 );
2674 session.channel_success(channel)?;
2675 session.data(channel, err_packet(STARTING_MESSAGE)?)?;
2676 session.exit_status_request(channel, EXIT_BUSY)?;
2677 session.close(channel)?;
2678 return Ok(());
2679 }
2680
2681 let class = OpClass::for_ssh_service(request.service);
2682 // `admit_within`, not `try_admit`: over the limit the transfer parks for
2683 // a bounded moment instead of being refused on the spot. A refused
2684 // client reconnects, and a reconnect is a whole SSH handshake — more
2685 // than the wait costs. `crate::governor::DEFAULT_ADMISSION_WAIT` has the
2686 // measurement; `--admission-wait-ms 0` is the old behaviour exactly.
2687 let admitted = match self
2688 .shared
2689 .admission
2690 .admit_within(&request.principal.id, &request.repo.namespace, class)
2691 .await
2692 {
2693 Ok((guard, waited)) => {
2694 // AGGREGATE, at most once a second. A row per waiting client is
2695 // the appliance's whole twenty-row console under load (the
2696 // measured 5411 in one 256-client run); a row per second
2697 // carrying the totals is the same fact, readable.
2698 if !waited.is_zero() && self.shared.admission.wait_row_due() {
2699 let stats = self.shared.admission.stats();
2700 tracing::info!(
2701 target: TARGET_GIT,
2702 event = "git.transfer.waited",
2703 class = class.name(),
2704 waited_ms = waited.as_millis() as u64,
2705 waited_total = stats.admitted_after_wait,
2706 mean_wait_ms = stats.mean_wait_ms(),
2707 peak_wait_ms = stats.peak_wait_ms,
2708 in_flight = stats.in_flight,
2709 limit = stats.limit,
2710 "transfers are WAITING for a slot and are then served: {} so far, mean \
2711 {} ms, worst {} ms against a bound of {} ms",
2712 stats.admitted_after_wait,
2713 stats.mean_wait_ms(),
2714 stats.peak_wait_ms,
2715 self.shared.admission.wait().as_millis() as u64
2716 );
2717 }
2718 guard
2719 }
2720 Err(refusal) => {
2721 let stats = self.shared.admission.stats();
2722 tracing::warn!(
2723 target: TARGET_GIT,
2724 event = "git.transfer.refused",
2725 // Which gate, not just "a gate": the anonymous ceiling
2726 // fires with the box nearly empty, and a line that
2727 // still said `admission-gate-full` there would send an
2728 // operator to raise a limit that was never reached.
2729 reason = refusal.reason(),
2730 service = %request.service,
2731 class = class.name(),
2732 %refusal,
2733 in_flight = stats.in_flight,
2734 peak_in_flight = stats.peak_in_flight,
2735 // The governed limit, so a log line says what was actually
2736 // in force rather than what was configured. Without it the
2737 // shed is invisible again.
2738 limit = stats.limit,
2739 reserved_bytes = stats.reserved_bytes,
2740 refused_total = stats.refused(),
2741 // The bound the transfer waited out before this. Without it
2742 // a reader cannot tell an instant refusal from one the
2743 // server spent two seconds trying to avoid.
2744 waited_ms = self.shared.admission.wait().as_millis() as u64,
2745 peak_wait_ms = stats.peak_wait_ms,
2746 "transfer REFUSED by the admission gate"
2747 );
2748 // Answered in the client's own protocol, like a denial, so git
2749 // prints the reason instead of "Could not read from remote
2750 // repository". Saturation the operator can see and the user
2751 // cannot is only half a fix.
2752 session.channel_success(channel)?;
2753 session.data(channel, err_packet(&refusal.client_message())?)?;
2754 session.exit_status_request(channel, EXIT_BUSY)?;
2755 session.close(channel)?;
2756 return Ok(());
2757 }
2758 };
2759
2760 // ── the span the whole transfer runs under ─────────────────────────
2761 //
2762 // A CHILD of `ssh.connection`, so it inherits `conn`, `peer`,
2763 // `principal` and `repo` and states none of them again. `service` is
2764 // the one thing that is new. Everything `gunnar-cli`'s transport and
2765 // `gunnar-policy`'s gate emit lands underneath it, in the same
2766 // process, without either of them being handed an id to repeat.
2767 let transfer = tracing::info_span!(
2768 target: TARGET_GIT,
2769 "git.transfer",
2770 service = %request.service,
2771 access = %request.access,
2772 );
2773 transfer.in_scope(|| {
2774 tracing::info!(
2775 target: TARGET_GIT,
2776 event = "git.transfer.started",
2777 git_protocol = ?request.git_protocol,
2778 "serving"
2779 )
2780 });
2781 let in_flight = self.shared.metrics.transfer_started();
2782 let metrics = Arc::clone(&self.shared.metrics);
2783 let started = std::time::Instant::now();
2784
2785 session.channel_success(channel)?;
2786
2787 let transport = self.shared.transport.clone();
2788 // Split, NOT `into_stream()`. `into_stream` wraps the channel in
2789 // russh's `ChannelCloseOnDrop`, which spawns a `Close` the instant the
2790 // transport lets the stream go, and that `Close` raced (and beat) the
2791 // `exit-status` sent next, which is how a successful push came to
2792 // report failure. Neither half closes the channel on drop, so the two
2793 // messages below are ordered by the sender's own queue.
2794 let (read_half, write_half) = open.channel.split();
2795 // METERED, so the memory ledger learns this transfer's real size as it
2796 // happens rather than being charged a flat per-class constant at
2797 // admission. `crate::admission::Metered` is the only place a byte count
2798 // reaches the governor, and it wraps the duplex the transport was
2799 // already going to be handed — no second copy, no second truth.
2800 let admitted = Arc::new(admitted);
2801 let stream = crate::admission::Metered::new(
2802 tokio::io::join(
2803 ChannelReader::new(read_half),
2804 // Bound to the session: a write parked on the SSH window ends
2805 // with an error when the session does (see `SessionBound`).
2806 SessionBound::new(write_half.make_writer(), self.session_over.subscribe()),
2807 ),
2808 Arc::clone(&admitted),
2809 );
2810 // Spawned, not awaited: see the module docs. Awaiting here would stop
2811 // the session loop that has to feed this very stream.
2812 // ── THE STANDING FAN, not a fresh thread ────────────────────────
2813 //
2814 // This used to be `tokio::spawn` alone, and the task itself was never
2815 // the cost — tasks are cheap. The cost is behind it: `SyncIoBridge`
2816 // hands the transfer to tokio's BLOCKING pool, which spawns an OS
2817 // thread on demand, per operation, up to 512 of them. That is
2818 // per-request initialisation, and it is what the fans replace.
2819 //
2820 // The future is driven by `Handle::block_on` on a worker that was
2821 // already alive and parked before this client connected. A full queue
2822 // refuses here, which is the only place a refusal is free.
2823 let handle = tokio::runtime::Handle::current();
2824 let pipelines = crate::pipeline::fans();
2825 let over = self.session_over.subscribe();
2826 let (calm_grace, crowded_grace) = self.shared.session_end_grace;
2827 let body = async move {
2828 // ── the CoDel dequeue ──────────────────────────────────────
2829 //
2830 // The FIRST line of the task, deliberately. Everything between
2831 // `try_admit` above and this point is the transfer WAITING:
2832 // tokio's ready queue, and behind it the blocking-pool handoff
2833 // that `SyncIoBridge` needs before a single byte moves. That
2834 // wait is the queue the record called invisible, and this call is
2835 // what makes the governor able to see it. Measured here rather
2836 // than at the end because sojourn is wait time; service time
2837 // filed as sojourn would make every large clone look like a
2838 // standing queue.
2839 admitted.entered_service();
2840 // ★ The WHOLE transfer is bound to the session, not only its writes
2841 // (`SessionBound`): a client that goes silent while main is still
2842 // building the pack has no write parked on the window to wake, and
2843 // the build can take minutes (the UpCloud mockup's LD1/LD2,
2844 // 2026-10-09: 2 min 10 s on TCG). When the session ends — the
2845 // keepalives unanswered, a hang-up — the transfer ends with it and
2846 // gives back its fan worker, admission slot and store handle.
2847 let cancel = request.cancel.clone();
2848 let served = serve_until_session_ends(transport.serve(request, Box::new(stream)), over.clone(), &cancel, || {
2849 // Stinky row 19 (2026-10-10): a hung-up client's worker is one
2850 // a queued client waits for, so the grace is short when any do.
2851 crate::channel::grace_for(calm_grace, crowded_grace, pipelines.queued(class))
2852 }, || {
2853 crate::seam::TransportError::Io(session_ended_error())
2854 })
2855 .await;
2856 let status = match served {
2857 Ok(()) => 0,
2858 Err(err) => {
2859 metrics.add_transfers_failed(1);
2860 // ── the refusal the client used to never hear ───────
2861 //
2862 // Until 2026-08-05 this arm logged the whole reason and
2863 // sent the client an exit status and nothing else, so
2864 // every post-authorisation refusal — the repository's
2865 // store lock held by a `gunnar gc`, a storage fault on
2866 // open, an unwired service — reached the user as
2867 // `fatal: the remote end hung up unexpectedly`. The two
2868 // gates ABOVE this one, in this same function, both
2869 // answer in the client's own protocol; this one did not,
2870 // and the asymmetry is what made it invisible.
2871 //
2872 // `client_message()` is `None` whenever bytes may
2873 // already have gone out, so this cannot append a
2874 // pkt-line to a half-written pack — see
2875 // `TransportError::client_message`.
2876 let told = err.client_message();
2877 tracing::warn!(
2878 target: TARGET_GIT,
2879 event = "git.transfer.failed",
2880 %err,
2881 // Whether the user was given a reason, said in the
2882 // log, because "the client was told" and "the client
2883 // saw a dead socket" must not be the same line.
2884 client_told = told.is_some(),
2885 "transport ended with an error"
2886 );
2887 if let Some(message) = told {
2888 match err_packet(&message) {
2889 Ok(packet) => {
2890 // Raced against the session's end: `data_bytes`
2891 // waits for SSH window like the stream does.
2892 let sent = tokio::select! {
2893 sent = write_half.data_bytes(packet) => sent,
2894 () = session_over(over.clone()) => Err(russh::Error::IO(session_ended_error())),
2895 };
2896 note_teardown("refusal-packet", sent)
2897 }
2898 Err(err) => tracing::error!(
2899 target: TARGET_GIT,
2900 %err,
2901 "the refusal could not be encoded, so the client is \
2902 getting only an exit status"
2903 ),
2904 }
2905 }
2906 EXIT_TRANSPORT_FAILED
2907 }
2908 };
2909 // The channel is still open here, nothing has been dropped that
2910 // could have closed it, so the status arrives before the close,
2911 // through the same sender the data went through.
2912 if write_half.exit_status(status).await.is_err() {
2913 // WARN only when the client missed a verdict it needed. A
2914 // client that took everything it asked for and hung up
2915 // before the `exit-status` has lost nothing — it is how
2916 // `ls-remote` and `fetch` end — and warning about it made
2917 // `grep -i error` useless on a completely healthy server:
2918 // MEASURED 2026-08-06, 9 successful transfers, 9 of these.
2919 // A client that missed a NON-ZERO status did lose
2920 // something: it believes the transfer worked.
2921 if status == 0 {
2922 tracing::debug!(
2923 target: TARGET_GIT,
2924 event = "git.exit_status.undelivered",
2925 ?channel,
2926 status,
2927 "the client hung up before the exit status; it had already \
2928 been served"
2929 );
2930 } else {
2931 tracing::warn!(
2932 target: TARGET_GIT,
2933 event = "git.exit_status.undelivered",
2934 ?channel,
2935 status,
2936 "the client was gone before a NON-ZERO exit status, so it \
2937 does not know this transfer failed"
2938 );
2939 }
2940 }
2941 note_teardown("channel-close", write_half.close().await);
2942 // The duration an operator asked "why was that clone slow"
2943 // about: the WHOLE transfer, from admission to the last byte
2944 // acknowledged, not the state machine's own view of itself.
2945 tracing::info!(
2946 target: TARGET_GIT,
2947 event = "git.transfer.finished",
2948 status,
2949 elapsed_ms = started.elapsed().as_millis() as u64,
2950 "transfer finished"
2951 );
2952 // Moved into this task and dropped here, so the slot is held for the
2953 // whole transfer and released by `Drop` rather than by a call that
2954 // an early return could skip. The in-flight gauge is released the
2955 // same way, and for the same reason.
2956 drop(admitted);
2957 drop(in_flight);
2958 }
2959 .instrument(transfer);
2960
2961 // ── WHAT THE FAN IS ACTUALLY CARRYING ───────────────────────────────
2962 //
2963 // `Pipelines` has counted `served`, `queued` and `workers` since it was
2964 // written and NOTHING reported them, so the only evidence the fans were
2965 // doing anything was the absence of refusals — which is not evidence,
2966 // it is silence. Asked "is the queue filling", the honest answer was an
2967 // inference from the workload's shape.
2968 //
2969 // `submit` already returns the queue depth after the push, so this
2970 // costs one integer. Emitted only when an operation ACTUALLY QUEUED
2971 // (depth > 1, i.e. it did not go straight to a free worker), because a
2972 // line per transfer on a 102-client arm is noise that hides the signal.
2973 // `served` and `workers` ride along so one line answers "how deep, out
2974 // of how many, having done how much".
2975 match pipelines.submit(
2976 class,
2977 Box::new(move || {
2978 handle.block_on(body);
2979 }),
2980 ) {
2981 Ok(depth) if depth > 1 => tracing::info!(
2982 target: TARGET_GIT,
2983 event = "git.pipeline.queued",
2984 class = ?class,
2985 depth,
2986 workers = pipelines.workers(class),
2987 served = pipelines.served(class),
2988 "an operation waited for a worker"
2989 ),
2990 Ok(_) => {}
2991 Err(refused) => {
2992 // The fan is saturated. Say so in the client's own protocol
2993 // rather than dropping the channel — a dead socket is how a
2994 // refusal becomes "the remote end hung up unexpectedly".
2995 tracing::warn!(
2996 target: TARGET_GIT,
2997 event = "git.transfer.refused",
2998 class = ?class,
2999 depth = pipelines.queued(class),
3000 workers = pipelines.workers(class),
3001 served = pipelines.served(class),
3002 %refused,
3003 "the standing fan for this class refused the operation"
3004 );
3005 return Err(anyhow::anyhow!("{refused}"));
3006 }
3007 }
3008 Ok(())
3009 }
3010
3011 // ── everything below is the "no shell, ever" half ──────────────────────
3012 //
3013 // russh's defaults for these return `Ok(())` **without** answering the
3014 // channel request, which leaves a client waiting rather than failing. Each
3015 // one is answered explicitly.
3016
3017 async fn shell_request(
3018 &mut self,
3019 channel: ChannelId,
3020 session: &mut Session,
3021 ) -> Result<(), Self::Error> {
3022 self.refuse(channel, session, "shell").await
3023 }
3024
3025 async fn subsystem_request(
3026 &mut self,
3027 channel: ChannelId,
3028 name: &str,
3029 session: &mut Session,
3030 ) -> Result<(), Self::Error> {
3031 // Includes `sftp`. gunnar serves git and nothing else.
3032 self.span.in_scope(|| {
3033 tracing::warn!(
3034 target: TARGET_SSH,
3035 event = "ssh.request.refused",
3036 subsystem = %name,
3037 "subsystem refused"
3038 )
3039 });
3040 self.refuse(channel, session, "subsystem").await
3041 }
3042
3043 async fn pty_request(
3044 &mut self,
3045 channel: ChannelId,
3046 _term: &str,
3047 _col_width: u32,
3048 _row_height: u32,
3049 _pix_width: u32,
3050 _pix_height: u32,
3051 _modes: &[(russh::Pty, u32)],
3052 session: &mut Session,
3053 ) -> Result<(), Self::Error> {
3054 self.refuse(channel, session, "pty").await
3055 }
3056
3057 async fn x11_request(
3058 &mut self,
3059 channel: ChannelId,
3060 _single_connection: bool,
3061 _x11_auth_protocol: &str,
3062 _x11_auth_cookie: &str,
3063 _x11_screen_number: u32,
3064 session: &mut Session,
3065 ) -> Result<(), Self::Error> {
3066 self.refuse(channel, session, "x11").await
3067 }
3068
3069 async fn env_request(
3070 &mut self,
3071 channel: ChannelId,
3072 variable_name: &str,
3073 variable_value: &str,
3074 session: &mut Session,
3075 ) -> Result<(), Self::Error> {
3076 // An ALLOWLIST, not a filter: everything that is not named here is
3077 // refused, so adding a variable is a deliberate edit to one array and
3078 // the default for anything new is "no". See the module docs for why an
3079 // SSH server that passes an environment through is an attack surface.
3080 let span = self.span.clone();
3081 let _entered = span.enter();
3082 if !ENV_ALLOWLIST.contains(&variable_name) {
3083 // Same refusal, same event, same fields — two levels. See
3084 // [`ENV_ROUTINE`] for the 406-of-406 measurement that split them.
3085 if env_refusal_is_routine(variable_name) {
3086 tracing::debug!(
3087 target: TARGET_SSH,
3088 event = "ssh.env.refused",
3089 reason = "not-allowlisted",
3090 routine = true,
3091 variable = %variable_name,
3092 "env refused: gunnar reads exactly one environment variable"
3093 );
3094 } else {
3095 tracing::warn!(
3096 target: TARGET_SSH,
3097 event = "ssh.env.refused",
3098 reason = "not-allowlisted",
3099 routine = false,
3100 variable = %variable_name,
3101 "env refused: gunnar reads exactly one environment variable"
3102 );
3103 }
3104 session.channel_failure(channel)?;
3105 return Ok(());
3106 }
3107
3108 // A value gunnar will not read is not worth holding. `version=2` is
3109 // nine bytes; the cap is generous and exists so a client cannot make
3110 // the server keep an unbounded string per channel.
3111 if variable_value.len() > MAX_ENV_VALUE {
3112 tracing::warn!(
3113 target: TARGET_SSH,
3114 event = "ssh.env.refused",
3115 reason = "value-too-long",
3116 variable = %variable_name,
3117 length = variable_value.len(),
3118 "env refused: the value is implausibly long"
3119 );
3120 session.channel_failure(channel)?;
3121 return Ok(());
3122 }
3123
3124 let Some(open) = self.channels.get_mut(&channel) else {
3125 tracing::warn!(
3126 target: TARGET_SSH,
3127 ?channel,
3128 "env request for a channel that was never opened"
3129 );
3130 session.channel_failure(channel)?;
3131 return Ok(());
3132 };
3133 if variable_name != ENV_GIT_PROTOCOL {
3134 // `ENV_ALLOWLIST` grew a name and nothing here was taught to carry
3135 // it. Fail closed and say so, rather than quietly filing an unknown
3136 // variable in the `GIT_PROTOCOL` slot.
3137 tracing::error!(
3138 target: TARGET_SSH,
3139 variable = %variable_name,
3140 "env allowlisted but not carried anywhere; refusing"
3141 );
3142 session.channel_failure(channel)?;
3143 return Ok(());
3144 }
3145 tracing::debug!(
3146 target: TARGET_SSH,
3147 variable = %variable_name,
3148 value = %variable_value,
3149 "env accepted"
3150 );
3151 open.git_protocol = Some(variable_value.to_string());
3152 session.channel_success(channel)?;
3153 Ok(())
3154 }
3155
3156 async fn channel_close(
3157 &mut self,
3158 channel: ChannelId,
3159 _session: &mut Session,
3160 ) -> Result<(), Self::Error> {
3161 self.channels.remove(&channel);
3162 Ok(())
3163 }
3164}
3165
3166impl Connection {
3167 async fn refuse(
3168 &mut self,
3169 channel: ChannelId,
3170 session: &mut Session,
3171 what: &'static str,
3172 ) -> Result<(), anyhow::Error> {
3173 self.span.in_scope(|| {
3174 tracing::warn!(
3175 target: TARGET_SSH,
3176 event = "ssh.request.refused",
3177 request = what,
3178 "refused: gunnar has no shell"
3179 )
3180 });
3181 session.channel_failure(channel)?;
3182 Ok(())
3183 }
3184}
3185
3186/// The session loop ended: say so in words an operator's `grep -i error` will
3187/// not find, unless it really was an error.
3188///
3189/// See [`peer_hung_up`]. `error=early eof` fired on **every healthy fetch**
3190/// before this existed.
3191fn note_session_end(error: &anyhow::Error) {
3192 if peer_hung_up(error.as_ref()) {
3193 tracing::debug!(
3194 target: TARGET_SSH,
3195 event = "ssh.session.closed",
3196 reason = "peer-hung-up",
3197 "the client closed the connection"
3198 );
3199 return;
3200 }
3201 tracing::debug!(target: TARGET_SSH, %error, "ssh session ended with an error");
3202}
3203
3204/// Note that a best-effort teardown step did not work.
3205///
3206/// # Best-effort stays best-effort. What changes is that it stops being silent
3207///
3208/// Closing a channel and disconnecting a watchdogged session are both allowed
3209/// to fail: the peer may already be gone, which is the ordinary case and not
3210/// worth an operator's attention. Neither ever became an error, and neither
3211/// should. But a **systemic** failure to tear sessions down, from descriptor
3212/// exhaustion, the failure mode the unbounded handle cache used to
3213/// produce, was previously indistinguishable from a quiet server, because
3214/// `let _ =` leaves nothing behind at any level.
3215///
3216/// `debug!` rather than `warn!`: one of these is normal and a thousand is not,
3217/// and the thing that tells them apart is a count in a journal, not a severity
3218/// on a line that fires every time a client hangs up first.
3219/// The one encoder for a client-visible refusal: `ERR <message>` as a pkt-line.
3220///
3221/// Three call sites now answer a refusal in the client's own protocol — the
3222/// dispatch denial, the admission gate and a transfer refused before its first
3223/// byte — and a fourth is a matter of time. One implementation: the framing is written once,
3224/// so a refusal cannot acquire a subtly different shape depending on which gate
3225/// produced it. `ERR` is git's own out-of-band error line, which every git
3226/// version since 1.6 prints verbatim instead of "Could not read from remote
3227/// repository".
3228fn err_packet(message: &str) -> anyhow::Result<Vec<u8>> {
3229 let mut packet = Vec::new();
3230 gunnar_pktline::write_text(&mut packet, format!("ERR {message}").as_bytes())
3231 .map_err(|e| anyhow::anyhow!("encoding ERR packet: {e}"))?;
3232 Ok(packet)
3233}
3234
3235///
3236/// # …and "the peer is already gone" is not a failure at all
3237///
3238/// Closing a channel whose peer has already hung up returns
3239/// `russh::Error::SendError`, and until 2026-08-06 that was logged as
3240/// `ssh.teardown.failed err=Channel send error` on **every healthy transfer**
3241/// (MEASURED that day: 9 successful transfers, 6 of these). It is the same
3242/// fact `handle_session_error` and the undelivered exit status already report,
3243/// counted a third time in the third set of words with "err" in it. It is
3244/// separated here by [`peer_hung_up`] so the systemic case this function exists
3245/// for — descriptor exhaustion, a wedged sender — is still the only thing that
3246/// says `failed`.
3247fn note_teardown<E: std::error::Error + 'static>(step: &'static str, result: Result<(), E>) {
3248 if let Err(err) = result {
3249 if peer_hung_up(&err) {
3250 tracing::debug!(
3251 target: TARGET_SSH,
3252 event = "ssh.teardown.peer_gone",
3253 step,
3254 "the peer had already gone, so this teardown step had nothing to say \
3255 it to"
3256 );
3257 return;
3258 }
3259 tracing::debug!(
3260 target: TARGET_SSH,
3261 event = "ssh.teardown.failed",
3262 step,
3263 %err,
3264 "a session teardown step did not complete"
3265 );
3266 }
3267}
3268
3269/// **Is this failure just "the peer hung up first"?**
3270///
3271/// The one classifier for that question (one implementation). Three places used to answer it
3272/// independently, and all three answered *"no"*, which is why a completely
3273/// healthy `gunnar ls-remote` left this in the journal:
3274///
3275/// ```text
3276/// DEBUG ssh session ended with an error error=early eof
3277/// WARN the client was gone before the exit status channel=ChannelId(2) status=0
3278/// DEBUG ssh.teardown.failed step="channel-close" err=Channel send error
3279/// INFO transfer finished status=0 elapsed_ms=106
3280/// ```
3281///
3282/// MEASURED on the reference desktop 2026-08-06 from the live server's own journal, at
3283/// `10:55:10`, for a transfer that succeeded. Nothing was damaged — `status=0`,
3284/// `transfer finished` — but three lines carrying `error`, `err` and `failed`
3285/// per healthy call means `grep -i error` finds only noise, and that is the
3286/// first command an operator runs.
3287///
3288/// # Classified on the cause, never on the message text
3289///
3290/// A `contains("early eof")` would be a guard that silently stops matching the
3291/// day tokio rewords its `read_exact`, and the failure would be invisible
3292/// because it fails in the *quiet* direction — back to noise, not to a crash.
3293/// So this walks the source chain and matches concrete things:
3294/// `io::ErrorKind`, and russh's own named variants. `early eof` is
3295/// `ErrorKind::UnexpectedEof` (tokio's `read_exact`) and `Channel send error`
3296/// is `russh::Error::SendError`; neither string appears below.
3297///
3298/// # What it deliberately does NOT swallow
3299///
3300/// Only the socket going away. A key exchange failure, a MAC failure, a
3301/// protocol desync, a decryption failure — every one of those is still an error
3302/// and still logged as one. `tests/teardown_noise.rs` asserts both directions,
3303/// because a classifier that answered `true` for everything would produce a
3304/// beautifully quiet journal for a server that was on fire.
3305fn peer_hung_up(err: &(dyn std::error::Error + 'static)) -> bool {
3306 use std::io::ErrorKind;
3307
3308 let mut cause: Option<&(dyn std::error::Error + 'static)> = Some(err);
3309 while let Some(e) = cause {
3310 if let Some(io) = e.downcast_ref::<std::io::Error>() {
3311 if matches!(
3312 io.kind(),
3313 ErrorKind::UnexpectedEof
3314 | ErrorKind::BrokenPipe
3315 | ErrorKind::ConnectionReset
3316 | ErrorKind::ConnectionAborted
3317 | ErrorKind::NotConnected
3318 ) {
3319 return true;
3320 }
3321 }
3322 if let Some(r) = e.downcast_ref::<russh::Error>() {
3323 if matches!(
3324 r,
3325 // The channel's sender is gone: nothing left to send to.
3326 russh::Error::SendError
3327 // russh's own names for a hung-up peer.
3328 | russh::Error::HUP
3329 | russh::Error::Disconnect
3330 ) {
3331 return true;
3332 }
3333 }
3334 cause = e.source();
3335 }
3336 false
3337}
3338
3339/// Refuse a key that would not re-encode.
3340///
3341/// A free function taking only the counters, so the decision this makes (a
3342/// **rejection**, and a counted one) can be asserted without standing up a
3343/// russh session. The alternative, an `expect()`, aborted the auth handler.
3344///
3345/// `auth_faults` is deliberately **not** moved: that counter means "the
3346/// identity table could not be read", and this key never reached it. The `warn`
3347/// [`crate::access::fingerprint_of_key`] emits carries
3348/// `reason = "key-does-not-re-encode"`, which is what tells the two apart.
3349fn refuse_unencodable_key(metrics: &gunnar_core::observe::ServerMetrics, user: &str) -> Auth {
3350 metrics.add_connections_refused(1);
3351 tracing::warn!(
3352 target: TARGET_SSH,
3353 event = "ssh.auth.refused",
3354 reason = "key-does-not-re-encode",
3355 decorative_ssh_user = %user,
3356 "publickey refused: the offered key did not re-encode"
3357 );
3358 Auth::reject()
3359}
3360
3361/// The one environment variable a git client may send: how it asks for
3362/// protocol v2 over SSH.
3363pub const ENV_GIT_PROTOCOL: &str = "GIT_PROTOCOL";
3364
3365/// **Every** environment variable this server accepts from a client.
3366///
3367/// An allowlist, checked by `env_request`. `LD_PRELOAD`, `PATH`, `GIT_DIR` and
3368/// everything else a client might try is refused with a channel failure, the
3369/// same answer this server gave to *all* environment requests before
3370/// [`ENV_GIT_PROTOCOL`] was needed. Nothing here is ever executed, exported to
3371/// a process or consulted by the grant check; gunnar has no shell and spawns
3372/// nothing, so the only reason an accepted name exists is that the *wire* reads
3373/// it.
3374pub const ENV_ALLOWLIST: [&str; 1] = [ENV_GIT_PROTOCOL];
3375
3376/// The refused names that mean **nothing at all**, because OpenSSH sends them
3377/// on its own without being asked.
3378///
3379/// Still refused — [`ENV_ALLOWLIST`] is unchanged and this list grants nothing.
3380/// What it changes is the *level* the refusal is reported at, and the reason it
3381/// has to exist is a measurement.
3382///
3383/// MEASURED on the reference desktop 2026-08-05, an 18-repository ingest over real SSH with stock
3384/// git 2.53.0 as the client, 203 connections, `RUST_LOG=info`:
3385///
3386/// | WARN lines | of which `ssh.env.refused` for `LANG`/`COLORTERM` |
3387/// |---|---|
3388/// | 406 | **406 (100%)** |
3389///
3390/// Zero warnings of any other kind were emitted in the whole run. OpenSSH's
3391/// shipped `ssh_config` carries `SendEnv LANG LC_*`, and desktop terminals add
3392/// `COLORTERM`, so every `git` over `ssh` produces two of these before it has
3393/// asked for anything. An operator who greps for `WARN` on a live gunnar
3394/// therefore reads noise at a 100% false-positive rate and will not see the
3395/// first real one — which is the same disease as a check that cannot go red,
3396/// wearing the other colour.
3397///
3398/// A client naming something NOT on this list is a different event and keeps
3399/// its `warn`: `LD_PRELOAD`, `PATH`, `GIT_DIR`, `GIT_ALTERNATE_OBJECT_DIRECTORIES`
3400/// are what an attacker tries, and nothing sends them by accident.
3401pub const ENV_ROUTINE: [&str; 4] = ["LANG", "LANGUAGE", "COLORTERM", "TERM"];
3402
3403/// Whether `name` is a routine refusal ([`ENV_ROUTINE`], or any `LC_*`, which
3404/// OpenSSH sends as a glob).
3405pub fn env_refusal_is_routine(name: &str) -> bool {
3406 ENV_ROUTINE.contains(&name) || name.starts_with("LC_")
3407}
3408
3409/// The longest environment value the server will hold.
3410///
3411/// `version=2` is nine bytes. This is a bound on what one channel can make the
3412/// server remember, not a syntax check; the grammar is `gunnar-wire`'s.
3413pub const MAX_ENV_VALUE: usize = 256;
3414
3415/// Exit status reported when access was refused. Matches what `git` itself
3416/// reports for a failed remote helper.
3417pub const EXIT_DENIED: u32 = 128;
3418
3419/// **What a client is told when the key that opened its session stopped
3420/// authorising it.**
3421///
3422/// One string, named here rather than spelled at the refusal site, so the test
3423/// that asserts what reaches the client reads the same constant the server
3424/// sends. It says what happened and what to do, because "denied" on a
3425/// connection that worked a second ago is otherwise indistinguishable from the
3426/// server having broken.
3427///
3428/// It does NOT distinguish a revoked key from an unreadable identity table, for
3429/// the reason the whole of this surface merges "no such repository" with "no
3430/// permission": the difference is operator information, and the log keeps it.
3431pub const REVOKED_MESSAGE: &str =
3432 "the key that opened this session no longer authorises it; reconnect";
3433
3434/// Exit status reported when the wire failed mid-transfer.
3435pub const EXIT_TRANSPORT_FAILED: u32 = 1;
3436
3437/// Exit status reported when the admission gate refused a transfer.
3438///
3439/// `EX_TEMPFAIL` from `sysexits.h`, and deliberately **not** [`EXIT_DENIED`]:
3440/// "try again" and "you may not" are different answers, and a retry script that
3441/// cannot tell them apart either hammers a permission error forever or gives up
3442/// on a transient one.
3443pub const EXIT_BUSY: u32 = 75;
3444
3445/// What a client is told while the server's stores are still opening.
3446///
3447/// **The word `starting` is load-bearing** and is asserted by
3448/// `tests/readiness.rs`: it is what separates this from
3449/// `gunnar_wire::Error::Store`'s `the repository is unavailable; try again`,
3450/// which is what a client hears when a repository is genuinely broken. The
3451/// power-cut door read the second sentence during the first condition and
3452/// reported 64 acked pushes missing that were all present a second later. A
3453/// harness, a CI script and a person all have to be able to tell "not yet" from
3454/// "gone", and the only place that distinction can be made is here, in the
3455/// words.
3456///
3457/// It carries [`EXIT_BUSY`], not [`EXIT_DENIED`], for the same reason: 75 means
3458/// retry.
3459pub const STARTING_MESSAGE: &str =
3460 "the server is starting: its stores are still opening after a restart, and it will serve \
3461 this in a moment; retry";
3462
3463#[cfg(test)]
3464mod tests {
3465 use super::*;
3466
3467 /// `gunnar-recipient-keys`: the path through the one sandbox (git's
3468 /// quoting taken off), the member through the principal id rule, and
3469 /// nothing else on the line; another verb is not this one.
3470 #[test]
3471 fn the_recipient_keys_line_takes_a_sandboxed_path_and_an_account_name() {
3472 let ok = |line: &str| parse_recipient_keys_verb(line.as_bytes()).expect("this verb").expect("well formed");
3473 let (repo, member) = ok("gunnar-recipient-keys 'team/vault.git' 'bob'");
3474 assert_eq!((repo.namespace(), repo.name(), member.as_str()), ("team", "vault", "bob"));
3475 let (repo, member) = ok("gunnar-recipient-keys team/vault bob");
3476 assert_eq!((repo.namespace(), repo.name(), member.as_str()), ("team", "vault", "bob"));
3477 let (repo, _) = ok("gunnar-recipient-keys '/team/vault.git' bob");
3478 assert_eq!(repo.name(), "vault");
3479 assert!(parse_recipient_keys_verb(b"git-upload-pack 'team/vault.git'").is_none());
3480 assert!(parse_recipient_keys_verb(b"gunnar-recipient-keysx a/b c").is_none());
3481 for bad in [
3482 "gunnar-recipient-keys",
3483 "gunnar-recipient-keys 'team/vault.git'",
3484 "gunnar-recipient-keys '../etc/passwd' bob",
3485 "gunnar-recipient-keys team/vault 'bo b'",
3486 "gunnar-recipient-keys team/vault anonymous",
3487 "gunnar-recipient-keys team/vault 'bob",
3488 "gunnar-recipient-keys team/vault bob\u{1}",
3489 ] {
3490 assert!(
3491 matches!(parse_recipient_keys_verb(bad.as_bytes()), Some(Err(_))),
3492 "{bad:?} is refused"
3493 );
3494 }
3495 let long = format!("gunnar-recipient-keys team/vault {}", "b".repeat(600));
3496 assert!(matches!(parse_recipient_keys_verb(long.as_bytes()), Some(Err(_))));
3497 }
3498
3499 /// **The door offers the post-quantum hybrid first**, from gunnar's own
3500 /// list: `mlkem768x25519-sha256`, then the classical fallbacks, and the
3501 /// strict-kex markers (Terrapin) kept.
3502 #[test]
3503 fn the_door_offers_mlkem768x25519_first_from_gunnars_own_list() {
3504 let p = preferred();
3505 assert!(std::ptr::eq(p.kex.as_ref().as_ptr(), KEX_ORDER.as_ptr()), "the server's list is gunnar's KEX_ORDER, not whatever russh defaults to");
3506 let names: Vec<&str> = p.kex.iter().map(|n| n.as_ref()).collect();
3507 assert_eq!(names[..3], ["mlkem768x25519-sha256", "curve25519-sha256", "curve25519-sha256@libssh.org"], "{names:?}");
3508 assert!(names.contains(&"kex-strict-s-v00@openssh.com"), "strict kex stays: {names:?}");
3509 assert_eq!(p.cipher, russh::Preferred::DEFAULT.cipher, "only the key exchange is gunnar's own");
3510 }
3511
3512 /// The accept loop outlives a descriptor shortage and a client that hung
3513 /// up mid-handshake; it returns on a listener that is gone.
3514 #[test]
3515 fn transient_accept_errors_are_named() {
3516 for errno in [24, 23, 105, 12, 103] {
3517 assert!(
3518 accept_error_is_transient(&std::io::Error::from_raw_os_error(errno)),
3519 "errno {errno}"
3520 );
3521 }
3522 for errno in [9, 22, 88] {
3523 assert!(
3524 !accept_error_is_transient(&std::io::Error::from_raw_os_error(errno)),
3525 "errno {errno}"
3526 );
3527 }
3528 assert!(!accept_error_is_transient(&std::io::Error::other("closed")));
3529 }
3530
3531 /// A teardown that fails is **reported**, and one that works is
3532 /// silent.
3533 ///
3534 /// Driven through the helper rather than through a live channel: making
3535 /// `Channel::close()` fail on demand means a peer that has vanished at an
3536 /// exact moment, which is a race to arrange and a race to assert on. What
3537 /// the helper decides is the whole of what changed, `let _ =` against a
3538 /// line in the journal, and both directions are asserted, because a
3539 /// `note_teardown` that logged unconditionally would put a line in an
3540 /// operator's journal on every clean disconnect and make the signal
3541 /// useless.
3542 /// Capture every `tracing` line `emit` produces, rendered as
3543 /// `<target> <field>=<value> …`.
3544 ///
3545 /// One capture for every test in this module that reads the journal (one
3546 /// implementation): there were two copies of this layer forty lines apart, and a second
3547 /// copy of a capture is a second chance to filter out the line under test.
3548 fn captured_lines(emit: impl FnOnce()) -> Vec<String> {
3549 use std::sync::{Arc, Mutex};
3550 use tracing_subscriber::layer::SubscriberExt;
3551 use tracing_subscriber::Layer as _;
3552
3553 #[derive(Clone, Default)]
3554 struct Capture(Arc<Mutex<Vec<String>>>);
3555 struct CaptureLayer(Capture);
3556 impl<S: tracing::Subscriber> tracing_subscriber::Layer<S> for CaptureLayer {
3557 fn on_event(
3558 &self,
3559 event: &tracing::Event<'_>,
3560 _: tracing_subscriber::layer::Context<'_, S>,
3561 ) {
3562 struct Render(String);
3563 impl tracing::field::Visit for Render {
3564 fn record_debug(
3565 &mut self,
3566 field: &tracing::field::Field,
3567 value: &dyn std::fmt::Debug,
3568 ) {
3569 self.0.push_str(&format!("{}={value:?} ", field.name()));
3570 }
3571 }
3572 let mut render = Render(String::new());
3573 event.record(&mut render);
3574 self.0 .0.lock().expect("capture").push(format!(
3575 "{} {}",
3576 event.metadata().target(),
3577 render.0
3578 ));
3579 }
3580 }
3581
3582 let capture = Capture::default();
3583 let subscriber = tracing_subscriber::registry().with(
3584 CaptureLayer(capture.clone())
3585 .with_filter(tracing_subscriber::filter::LevelFilter::TRACE),
3586 );
3587 tracing::subscriber::with_default(subscriber, emit);
3588 let lines = capture.0.lock().expect("capture").clone();
3589 lines
3590 }
3591
3592 #[test]
3593 fn a_failed_teardown_step_is_reported_and_a_clean_one_is_not() {
3594 let lines = captured_lines(|| {
3595 note_teardown::<std::io::Error>("channel-close", Ok(()));
3596 note_teardown(
3597 "watchdog-disconnect",
3598 Err(std::io::Error::other("the peer was already gone")),
3599 );
3600 });
3601
3602 assert_eq!(
3603 lines.len(),
3604 1,
3605 "expected exactly one line — the failure — got {lines:?}"
3606 );
3607 assert!(
3608 lines[0].starts_with(gunnar_core::observe::TARGET_SSH),
3609 "the line is not on the ssh target: {}",
3610 lines[0]
3611 );
3612 assert!(
3613 lines[0].contains("watchdog-disconnect") && lines[0].contains("already gone"),
3614 "the line names neither the step nor the error: {}",
3615 lines[0]
3616 );
3617 }
3618
3619 /// **RED-WHEN-BROKEN: a real failure is still reported as one.**
3620 ///
3621 /// The dangerous direction of [`peer_hung_up`] is not missing a hung-up
3622 /// peer — that only restores the noise. It is answering `true` for
3623 /// everything, which gives a beautifully quiet journal for a server that is
3624 /// on fire, and does it in a way no other test would notice.
3625 ///
3626 /// So every case is asserted in both directions, against **rendered log
3627 /// output** rather than against the predicate, because the predicate is
3628 /// private and the log line is what an operator has.
3629 #[test]
3630 fn a_real_failure_is_still_reported_as_one() {
3631 // Benign: the peer went away. Each of these is a shape MEASURED in the
3632 // live journal on 2026-08-06 for a transfer that succeeded.
3633 let benign: Vec<(&str, Box<dyn std::error::Error + 'static>)> = vec![
3634 // `err=Channel send error` — the channel's sender is gone.
3635 ("russh SendError", Box::new(russh::Error::SendError)),
3636 ("russh HUP", Box::new(russh::Error::HUP)),
3637 ("russh Disconnect", Box::new(russh::Error::Disconnect)),
3638 // `error=early eof` — tokio's `read_exact` on a closed socket.
3639 (
3640 "early eof",
3641 Box::new(std::io::Error::new(
3642 std::io::ErrorKind::UnexpectedEof,
3643 "early eof",
3644 )),
3645 ),
3646 (
3647 "broken pipe",
3648 Box::new(std::io::Error::from(std::io::ErrorKind::BrokenPipe)),
3649 ),
3650 (
3651 "connection reset",
3652 Box::new(std::io::Error::from(std::io::ErrorKind::ConnectionReset)),
3653 ),
3654 ];
3655 for (what, err) in benign {
3656 let lines = captured_lines(|| note_teardown("channel-close", Err(BoxedError(err))));
3657 assert_eq!(lines.len(), 1, "{what}: expected one line, got {lines:?}");
3658 let line = lines[0].to_ascii_lowercase();
3659 assert!(
3660 line.contains("peer_gone"),
3661 "{what} was not classified as a hung-up peer: {}",
3662 lines[0]
3663 );
3664 assert!(
3665 !line.contains("error") && !line.contains("err=") && !line.contains("fail"),
3666 "{what} is benign but its line is still found by `grep -i error`: {}",
3667 lines[0]
3668 );
3669 }
3670
3671 // NOT benign: the protocol itself went wrong. These must keep saying so
3672 // — this is the half that stops the classifier becoming a blanket yes.
3673 let real: Vec<(&str, Box<dyn std::error::Error + 'static>)> = vec![
3674 ("key exchange", Box::new(russh::Error::Kex)),
3675 ("packet auth", Box::new(russh::Error::PacketAuth)),
3676 ("decryption", Box::new(russh::Error::DecryptionError)),
3677 ("inconsistent state", Box::new(russh::Error::Inconsistent)),
3678 ("no common algo", Box::new(russh::Error::WrongChannel)),
3679 (
3680 "permission denied on disk",
3681 Box::new(std::io::Error::from(std::io::ErrorKind::PermissionDenied)),
3682 ),
3683 (
3684 "out of descriptors",
3685 Box::new(std::io::Error::from(std::io::ErrorKind::Other)),
3686 ),
3687 ];
3688 for (what, err) in real {
3689 let lines = captured_lines(|| note_teardown("channel-close", Err(BoxedError(err))));
3690 assert_eq!(lines.len(), 1, "{what}: expected one line, got {lines:?}");
3691 assert!(
3692 lines[0].contains("ssh.teardown.failed"),
3693 "{what} was swallowed as benign, so the classifier is a blanket yes: {}",
3694 lines[0]
3695 );
3696 assert!(
3697 lines[0].contains("err="),
3698 "{what} lost the error itself, so the line names no cause: {}",
3699 lines[0]
3700 );
3701 }
3702 }
3703
3704 /// A boxed error that is still `std::error::Error`, so the table above can
3705 /// hold two concrete types in one `Vec` and still reach the classifier's
3706 /// `downcast_ref` through `source()`.
3707 #[derive(Debug)]
3708 struct BoxedError(Box<dyn std::error::Error + 'static>);
3709
3710 impl std::fmt::Display for BoxedError {
3711 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3712 self.0.fmt(f)
3713 }
3714 }
3715
3716 impl std::error::Error for BoxedError {
3717 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
3718 Some(self.0.as_ref())
3719 }
3720 }
3721
3722 /// The session-level half of the same rule: an ended session says nothing
3723 /// an operator greps for when the client simply hung up, and still says
3724 /// `error` when it did not.
3725 ///
3726 /// Asserted through the real `Handler` method rather than the predicate,
3727 /// because the method is what russh calls.
3728 #[test]
3729 fn a_hung_up_session_is_not_logged_as_an_error() {
3730 let quiet = captured_lines(|| {
3731 note_session_end(&anyhow::Error::new(std::io::Error::new(
3732 std::io::ErrorKind::UnexpectedEof,
3733 "early eof",
3734 )));
3735 });
3736 assert_eq!(quiet.len(), 1, "expected one line, got {quiet:?}");
3737 let line = quiet[0].to_ascii_lowercase();
3738 assert!(
3739 line.contains("peer-hung-up") && !line.contains("error"),
3740 "a client hanging up is still logged as an error: {}",
3741 quiet[0]
3742 );
3743
3744 let loud = captured_lines(|| {
3745 note_session_end(&anyhow::Error::new(russh::Error::Kex));
3746 });
3747 assert_eq!(loud.len(), 1, "expected one line, got {loud:?}");
3748 assert!(
3749 loud[0].to_ascii_lowercase().contains("error"),
3750 "a key-exchange failure was swallowed as a hung-up peer: {}",
3751 loud[0]
3752 );
3753 }
3754
3755 /// An unencodable key is **refused and counted**, never accepted.
3756 ///
3757 /// The assertion is on the applied output, the `Auth` value that goes back
3758 /// to russh and the counter an operator reads, not on "it did not panic".
3759 /// A body that returned `Auth::Accept` would let a key nobody could
3760 /// fingerprint onto the server, which is the one outcome worse than the
3761 /// panic this replaced.
3762 #[test]
3763 fn a_key_that_does_not_re_encode_is_rejected_and_counted() {
3764 let metrics = gunnar_core::observe::ServerMetrics::default();
3765 let auth = refuse_unencodable_key(&metrics, "decorative");
3766
3767 assert!(
3768 matches!(auth, Auth::Reject { .. }),
3769 "an unencodable key must be rejected, got {auth:?}"
3770 );
3771 let snapshot = metrics.snapshot();
3772 assert_eq!(
3773 snapshot.connections_refused, 1,
3774 "the refusal must be visible to an operator"
3775 );
3776 // Not an identity-table fault, and the counters must not blur the two.
3777 assert_eq!(snapshot.auth_faults, 0);
3778 assert_eq!(snapshot.connections_accepted, 0);
3779 }
3780}
3781
3782/// Pure: whether an exec line is git-lfs asking SSH (`git-lfs-authenticate …`,
3783/// `git-lfs-transfer …`) — refused, and said at INFO.
3784pub fn is_lfs_over_ssh(command: &str) -> bool {
3785 let first = command.split_whitespace().next().unwrap_or("");
3786 // The transfer verb is named through the dispatch table's own LFS row, never spelled here
3787 // (`command_parsing::the_dispatch_table_is_the_only_place_a_verb_is_named`).
3788 // `git-lfs-authenticate` is no verb gunnar dispatches: it is git-lfs's own probe.
3789 first == "git-lfs-authenticate"
3790 || crate::command::SERVICES
3791 .iter()
3792 .any(|spec| spec.verb == first && matches!(spec.service, crate::command::GitService::LfsTransfer(_)))
3793}
3794
3795#[cfg(test)]
3796mod lfs_over_ssh_tests {
3797 /// ★ git-lfs's SSH probe is a client's known step, not a defect (RUN A 2026-10-08).
3798 #[test]
3799 fn git_lfs_asking_ssh_is_known_and_anything_else_is_not() {
3800 assert!(super::is_lfs_over_ssh("git-lfs-authenticate /cbc/vault upload"));
3801 assert!(super::is_lfs_over_ssh("git-lfs-transfer 'acme/site' download"));
3802 for other in ["bash", "scp -t /etc", "", "git-lfs-authenticatex /a upload", "echo git-lfs-authenticate"] {
3803 assert!(!super::is_lfs_over_ssh(other), "{other:?}");
3804 }
3805 }
3806}