Skip to main content

arks_server/
ssh_serve.rs

1//! In-process SSH listener for `arks serve` (durable accept + live rebind).
2//!
3//! Evidence: B1/B2 OpenSSH ChaCha wire + `git clone ssh://`
4//! ([[evidence:root/20261110235116-claimed-ssh]]) and B7 SSH dual-bind rebind
5//! ([[evidence:root/20261111092000-claimed-rebind-ssh]]); with both, the IW-SSH-LABEL
6//! drop condition holds and the listener carries no Partial readiness label (queue Q21).
7//!
8//! Max honest wire today (structured stages):
9//! 1. resolve host-key + `authorized_keys` paths (env / options / defaults)
10//! 2. prove TCP bind on the requested listen address
11//! 3. optional RFC 4253 identification exchange
12//! 4. optional SSH_MSG_KEXINIT exchange + peer name-list parse
13//! 5. local curve25519-sha256 ECDH (+ peer ECDH INIT when offered)
14//! 6. host-key **sign** Partial (OpenSSH ed25519 unencrypted) + NEWKEYS when key loads
15//! 7. OpenSSH `chacha20-poly1305@openssh.com` packet protection after NEWKEYS
16//! 8. wire publickey auth verify against `authorized_keys` (Partial; when peer continues)
17//! 9. session channel + `exec` → `git-upload-pack`|`git-receive-pack` dispatch into
18//!    `upload_pack_stream` / `receive_pack_stream` (Partial; when channel opens)
19//!
20//! SoT §17(c)/(d): durable accept + same-process live rebind; bind failure stays
21//! fail-closed and silent degrade is forbidden. Ops SSHD + `arks upload-pack` /
22//! `receive-pack` remains valid. Cite: [[sot:root/arks-self-host-server]]
23
24use crate::error::ServerError;
25use crate::push_policy::Pusher;
26use crate::serve::ListenRebindSlot;
27use crate::ssh_openssh_chacha::OpenSshChaCha;
28use crate::stdio::{receive_pack_stream_as, upload_pack_stream};
29use crate::web_ui::store::ForgeStore;
30use arks_repo::Repository;
31use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
32use sha2::{Digest, Sha256};
33use std::collections::VecDeque;
34use std::io::{Cursor, Read, Write};
35use std::net::{Shutdown, SocketAddr, TcpListener, TcpStream};
36use std::path::{Component, Path, PathBuf};
37use std::sync::Arc;
38use std::sync::atomic::{AtomicBool, Ordering};
39use std::thread;
40use std::time::{Duration, Instant};
41use x25519_dalek::{PublicKey, StaticSecret};
42
43/// RFC 4254 advertised local receive window (2 MiB).
44const SSH_LOCAL_INITIAL_WINDOW: u32 = 2 * 1024 * 1024;
45/// Replenish local receive window via `SSH_MSG_CHANNEL_WINDOW_ADJUST` once consumed >= 512 KiB.
46const SSH_LOCAL_WINDOW_REFILL_THRESHOLD: u32 = 512 * 1024;
47/// RFC 4254 advertised maximum packet size.
48const SSH_LOCAL_MAX_PACKET: u32 = 32_768;
49
50/// Stop flag + join handle of a background listener thread.
51type ListenerThread = thread::JoinHandle<Result<(), ServerError>>;
52
53/// Named fail-closed stages for in-process SSH Partial (not Claimed).
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55#[allow(dead_code)] // IdExchange retained for stage vocabulary / future accept-path notes.
56enum SshStage {
57    IdExchange,
58    KexInit,
59    AlgoSelect,
60    Ecdh,
61    HostKeySign,
62    NewKeys,
63    EncryptedTransport,
64    AuthPublickey,
65    ChannelSession,
66}
67
68impl SshStage {
69    fn as_str(self) -> &'static str {
70        match self {
71            Self::IdExchange => "id_exchange",
72            Self::KexInit => "kexinit",
73            Self::AlgoSelect => "algo_select",
74            Self::Ecdh => "ecdh_curve25519",
75            Self::HostKeySign => "host_key_sign",
76            Self::NewKeys => "newkeys",
77            Self::EncryptedTransport => "encrypted_transport",
78            Self::AuthPublickey => "auth_publickey",
79            Self::ChannelSession => "channel_session",
80        }
81    }
82}
83
84/// Options for the in-process SSH git listener.
85#[derive(Debug, Clone)]
86pub struct ServeSshOptions {
87    pub listen: SocketAddr,
88    /// Repository or base path the listener would serve.
89    pub path: PathBuf,
90    /// Host key path (OpenSSH-format expected when Claimed). Default / env override.
91    pub host_key: PathBuf,
92    /// `authorized_keys` path for public-key auth (when Claimed).
93    pub authorized_keys: PathBuf,
94    /// Optional same-process live rebind target (§17(c); B7 SSH dual-bind drain).
95    pub rebind_desired: Option<ListenRebindSlot>,
96}
97
98impl ServeSshOptions {
99    /// Build options with default key paths under `~/.config/arks/ssh/` (or env).
100    pub fn with_defaults(listen: SocketAddr, path: PathBuf) -> Self {
101        Self {
102            listen,
103            path,
104            host_key: default_host_key_path(),
105            authorized_keys: default_authorized_keys_path(),
106            rebind_desired: None,
107        }
108    }
109}
110
111/// Default host key: `ARKS_SERVE_SSH_HOST_KEY` or `~/.config/arks/ssh/host_key`.
112pub fn default_host_key_path() -> PathBuf {
113    if let Ok(p) = std::env::var("ARKS_SERVE_SSH_HOST_KEY") {
114        if !p.is_empty() {
115            return PathBuf::from(p);
116        }
117    }
118    arks_config_dir().join("ssh").join("host_key")
119}
120
121/// Default authorized_keys: `ARKS_SERVE_SSH_AUTHORIZED_KEYS` or
122/// `~/.config/arks/ssh/authorized_keys`.
123pub fn default_authorized_keys_path() -> PathBuf {
124    if let Ok(p) = std::env::var("ARKS_SERVE_SSH_AUTHORIZED_KEYS") {
125        if !p.is_empty() {
126            return PathBuf::from(p);
127        }
128    }
129    arks_config_dir().join("ssh").join("authorized_keys")
130}
131
132fn arks_config_dir() -> PathBuf {
133    let home = std::env::var_os("HOME")
134        .or_else(|| std::env::var_os("USERPROFILE"))
135        .map(PathBuf::from)
136        .unwrap_or_else(|| PathBuf::from("."));
137    home.join(".config").join("arks")
138}
139
140fn path_status(p: &Path) -> &'static str {
141    if p.is_file() {
142        "present"
143    } else if p.exists() {
144        "exists-not-file"
145    } else {
146        "missing"
147    }
148}
149
150/// Probe host-key bytes for known OpenSSH / PEM markers (auth scaffolding; no load Claimed).
151fn probe_host_key_format(path: &Path) -> String {
152    if !path.is_file() {
153        return "absent".into();
154    }
155    let mut f = match std::fs::File::open(path) {
156        Ok(f) => f,
157        Err(e) => return format!("unreadable ({e})"),
158    };
159    let mut buf = [0u8; 96];
160    let n = f.read(&mut buf).unwrap_or(0);
161    let head = String::from_utf8_lossy(&buf[..n]);
162    if head.starts_with("openssh-key-v1") || head.contains("BEGIN OPENSSH PRIVATE KEY") {
163        "openssh-private-key-marker".into()
164    } else if head.contains("BEGIN RSA PRIVATE KEY")
165        || head.contains("BEGIN EC PRIVATE KEY")
166        || head.contains("BEGIN PRIVATE KEY")
167    {
168        "pem-private-key-marker".into()
169    } else if head.starts_with("ssh-") || head.starts_with("ecdsa-") || head.starts_with("sk-") {
170        "public-key-line-like".into()
171    } else if n == 0 {
172        "empty-file".into()
173    } else {
174        "unknown-bytes".into()
175    }
176}
177
178/// Count non-empty, non-comment lines in authorized_keys (auth scaffolding; no verify Claimed).
179fn probe_authorized_keys(path: &Path) -> String {
180    if !path.is_file() {
181        return "absent".into();
182    }
183    let raw = match std::fs::read_to_string(path) {
184        Ok(s) => s,
185        Err(e) => return format!("unreadable ({e})"),
186    };
187    let mut ed25519 = 0usize;
188    let mut rsa = 0usize;
189    let mut ecdsa = 0usize;
190    let mut total = 0usize;
191    for line in raw
192        .lines()
193        .map(str::trim)
194        .filter(|l| !l.is_empty() && !l.starts_with('#'))
195    {
196        total += 1;
197        let algo = line.split_whitespace().next().unwrap_or("");
198        if algo.contains("ed25519") {
199            ed25519 += 1;
200        } else if algo.starts_with("ssh-rsa") || algo.starts_with("rsa-sha2-") {
201            rsa += 1;
202        } else if algo.starts_with("ecdsa-sha2-") {
203            ecdsa += 1;
204        }
205    }
206    if rsa > 0 || ecdsa > 0 {
207        format!(
208            "lines={total} (ed25519={ed25519}, rsa={rsa}, ecdsa={ecdsa}; note: in-process SSH authenticates ed25519 keys)"
209        )
210    } else {
211        format!("lines={total} (ed25519={ed25519})")
212    }
213}
214
215fn ssh_string(data: &[u8]) -> Vec<u8> {
216    let mut out = Vec::with_capacity(4 + data.len());
217    out.extend_from_slice(&(data.len() as u32).to_be_bytes());
218    out.extend_from_slice(data);
219    out
220}
221
222fn ssh_name_list(names: &[&str]) -> Vec<u8> {
223    let joined = names.join(",");
224    ssh_string(joined.as_bytes())
225}
226
227fn read_ssh_name_list(buf: &[u8], off: &mut usize) -> Option<Vec<String>> {
228    if *off + 4 > buf.len() {
229        return None;
230    }
231    let len = u32::from_be_bytes(buf[*off..*off + 4].try_into().ok()?) as usize;
232    *off += 4;
233    if *off + len > buf.len() {
234        return None;
235    }
236    let s = std::str::from_utf8(&buf[*off..*off + len]).ok()?;
237    *off += len;
238    if s.is_empty() {
239        return Some(Vec::new());
240    }
241    Some(s.split(',').map(|x| x.to_string()).collect())
242}
243
244fn read_ssh_bytes(buf: &[u8], off: &mut usize) -> Option<Vec<u8>> {
245    if *off + 4 > buf.len() {
246        return None;
247    }
248    let len = u32::from_be_bytes(buf[*off..*off + 4].try_into().ok()?) as usize;
249    *off += 4;
250    if *off + len > buf.len() {
251        return None;
252    }
253    let out = buf[*off..*off + len].to_vec();
254    *off += len;
255    Some(out)
256}
257
258/// Host-key material for Partial sign (OpenSSH ed25519 unencrypted only).
259#[derive(Clone)]
260struct HostEd25519 {
261    signing: SigningKey,
262    /// SSH wire blob: string("ssh-ed25519") || string(32-byte pub).
263    public_blob: Vec<u8>,
264}
265
266fn load_host_ed25519(path: &Path) -> Result<HostEd25519, String> {
267    if !path.is_file() {
268        return Err("host_key absent".into());
269    }
270    let raw = std::fs::read(path).map_err(|e| e.to_string())?;
271    let text = String::from_utf8_lossy(&raw);
272    let b64: String = if text.contains("BEGIN OPENSSH PRIVATE KEY") {
273        text.lines()
274            .filter(|l| !l.starts_with("-----") && !l.trim().is_empty())
275            .collect::<String>()
276    } else if raw.starts_with(b"openssh-key-v1\0") {
277        return parse_openssh_ed25519_bin(&raw);
278    } else {
279        return Err("not OpenSSH PEM / openssh-key-v1".into());
280    };
281    let bin = base64::Engine::decode(&base64::engine::general_purpose::STANDARD, b64.trim())
282        .map_err(|e| format!("base64: {e}"))?;
283    parse_openssh_ed25519_bin(&bin)
284}
285
286fn parse_openssh_ed25519_bin(bin: &[u8]) -> Result<HostEd25519, String> {
287    const MAGIC: &[u8] = b"openssh-key-v1\0";
288    if !bin.starts_with(MAGIC) {
289        return Err("missing openssh-key-v1 magic".into());
290    }
291    let mut off = MAGIC.len();
292    let cipher = read_ssh_bytes(bin, &mut off).ok_or("ciphername")?;
293    let kdf = read_ssh_bytes(bin, &mut off).ok_or("kdfname")?;
294    let _kdfopts = read_ssh_bytes(bin, &mut off).ok_or("kdfoptions")?;
295    if cipher.as_slice() != b"none" || kdf.as_slice() != b"none" {
296        return Err("encrypted OpenSSH host key not Partial-wired (none/none only)".into());
297    }
298    let nkeys = read_u32(bin, &mut off).map_err(|_| "num_keys short".to_string())?;
299    if nkeys != 1 {
300        return Err(format!("num_keys={nkeys} (Partial expects 1)"));
301    }
302    let pub_blob = read_ssh_bytes(bin, &mut off).ok_or("public key blob")?;
303    let priv_block = read_ssh_bytes(bin, &mut off).ok_or("private block")?;
304    let mut poff = 0usize;
305    let _c1 = read_u32(&priv_block, &mut poff)?;
306    let _c2 = read_u32(&priv_block, &mut poff)?;
307    let keytype = read_ssh_bytes(&priv_block, &mut poff).ok_or("keytype")?;
308    if keytype.as_slice() != b"ssh-ed25519" {
309        return Err(format!(
310            "host key type {} (Partial ed25519 only)",
311            String::from_utf8_lossy(&keytype)
312        ));
313    }
314    let _pub_in_priv = read_ssh_bytes(&priv_block, &mut poff).ok_or("pubkey in priv")?;
315    let secret = read_ssh_bytes(&priv_block, &mut poff).ok_or("secret")?;
316    // OpenSSH stores 64-byte ed25519 private as seed(32)||public(32).
317    if secret.len() < 32 {
318        return Err(format!("ed25519 secret len {}", secret.len()));
319    }
320    let mut seed = [0u8; 32];
321    seed.copy_from_slice(&secret[..32]);
322    let signing = SigningKey::from_bytes(&seed);
323    // Prefer the public blob from the file header (SSH wire).
324    let public_blob = if pub_blob.starts_with(&[0, 0, 0, 11]) || pub_blob.len() > 4 {
325        pub_blob
326    } else {
327        build_ssh_ed25519_public_blob(signing.verifying_key().as_bytes())
328    };
329    Ok(HostEd25519 {
330        signing,
331        public_blob,
332    })
333}
334
335fn read_u32(buf: &[u8], off: &mut usize) -> Result<u32, String> {
336    let slice = buf
337        .get(*off..off.saturating_add(4))
338        .ok_or_else(|| "u32 short".to_string())?;
339    let bytes: [u8; 4] = slice.try_into().map_err(|_| "u32 short".to_string())?;
340    *off += 4;
341    Ok(u32::from_be_bytes(bytes))
342}
343
344fn build_ssh_ed25519_public_blob(pub32: &[u8; 32]) -> Vec<u8> {
345    let mut out = Vec::new();
346    out.extend(ssh_string(b"ssh-ed25519"));
347    out.extend(ssh_string(pub32));
348    out
349}
350
351fn sign_ssh_ed25519(host: &HostEd25519, data: &[u8]) -> Vec<u8> {
352    let sig = host.signing.sign(data);
353    let mut out = Vec::new();
354    out.extend(ssh_string(b"ssh-ed25519"));
355    out.extend(ssh_string(&sig.to_bytes()));
356    out
357}
358
359/// RFC 4253 SSH_MSG_KEXINIT — advertise curve25519; hostkey ssh-ed25519 when Partial load ok.
360fn build_kexinit_payload(advertise_ed25519: bool) -> Vec<u8> {
361    let mut p = Vec::with_capacity(256);
362    p.push(20); // SSH_MSG_KEXINIT
363    let cookie = StaticSecret::random().to_bytes();
364    p.extend_from_slice(&cookie[..16]);
365    p.extend(ssh_name_list(&[
366        "curve25519-sha256",
367        "curve25519-sha256@libssh.org",
368        "kex-strict-s-v00@openssh.com",
369    ]));
370    if advertise_ed25519 {
371        p.extend(ssh_name_list(&["ssh-ed25519"]));
372    } else {
373        // Honest Missing hostkey name when key unloadable.
374        p.extend(ssh_name_list(&["arks-partial-missing-hostkey-sign"]));
375    }
376    // Only advertise the cipher implemented by this listener. OpenSSH still
377    // negotiates a MAC name for AEAD ciphers, but the selected MAC is implicit
378    // and no separate MAC is placed on the wire.
379    p.extend(ssh_name_list(&["chacha20-poly1305@openssh.com"]));
380    p.extend(ssh_name_list(&["chacha20-poly1305@openssh.com"]));
381    p.extend(ssh_name_list(&["hmac-sha2-256"]));
382    p.extend(ssh_name_list(&["hmac-sha2-256"]));
383    p.extend(ssh_name_list(&["none"]));
384    p.extend(ssh_name_list(&["none"]));
385    p.extend(ssh_name_list(&[]));
386    p.extend(ssh_name_list(&[]));
387    p.push(0); // first_kex_packet_follows = false
388    p.extend_from_slice(&0u32.to_be_bytes());
389    p
390}
391
392/// Write one unencrypted SSH binary packet (no MAC — pre-NEWKEYS / cleartext Partial).
393fn write_ssh_packet(stream: &mut TcpStream, payload: &[u8]) -> std::io::Result<()> {
394    let mut padding_len = 4usize;
395    while (4 + 1 + payload.len() + padding_len) % 8 != 0 {
396        padding_len += 1;
397    }
398    let packet_length = (1 + payload.len() + padding_len) as u32;
399    stream.write_all(&packet_length.to_be_bytes())?;
400    stream.write_all(&[padding_len as u8])?;
401    stream.write_all(payload)?;
402    stream.write_all(&vec![0u8; padding_len])?;
403    Ok(())
404}
405
406fn read_ssh_packet(stream: &mut TcpStream, max_payload: usize) -> std::io::Result<Vec<u8>> {
407    let mut lenbuf = [0u8; 4];
408    stream.read_exact(&mut lenbuf)?;
409    let packet_length = u32::from_be_bytes(lenbuf) as usize;
410    if packet_length < 5 || packet_length > max_payload + 256 {
411        return Err(std::io::Error::new(
412            std::io::ErrorKind::InvalidData,
413            format!("ssh packet_length out of range ({packet_length})"),
414        ));
415    }
416    let mut rest = vec![0u8; packet_length];
417    stream.read_exact(&mut rest)?;
418    let padding_len = rest[0] as usize;
419    if padding_len + 1 > rest.len() {
420        return Err(std::io::Error::new(
421            std::io::ErrorKind::InvalidData,
422            "ssh padding_length invalid",
423        ));
424    }
425    let payload_end = rest.len() - padding_len;
426    Ok(rest[1..payload_end].to_vec())
427}
428
429/// Read identification lines without reading past LF into the first binary
430/// packet. RFC 4253 permits pre-identification banner lines.
431fn read_ssh_identification(stream: &mut TcpStream) -> std::io::Result<String> {
432    for _ in 0..50 {
433        let mut line = Vec::with_capacity(64);
434        loop {
435            let mut byte = [0u8; 1];
436            stream.read_exact(&mut byte)?;
437            line.push(byte[0]);
438            if byte[0] == b'\n' {
439                break;
440            }
441            if line.len() >= 255 {
442                return Err(std::io::Error::new(
443                    std::io::ErrorKind::InvalidData,
444                    "SSH identification line exceeds 255 bytes",
445                ));
446            }
447        }
448        let line = String::from_utf8_lossy(&line)
449            .trim_end_matches(['\r', '\n'])
450            .to_string();
451        if line.starts_with("SSH-") {
452            return Ok(line);
453        }
454    }
455    Err(std::io::Error::new(
456        std::io::ErrorKind::InvalidData,
457        "SSH identification not found",
458    ))
459}
460
461/// Local curve25519 ECDH self-check (Partial crypto evidence; not peer handshake Claimed).
462fn curve25519_ecdh_selfcheck() -> Result<String, String> {
463    let a_secret = StaticSecret::random();
464    let a_public = PublicKey::from(&a_secret);
465    let b_secret = StaticSecret::random();
466    let b_public = PublicKey::from(&b_secret);
467    let shared_a = a_secret.diffie_hellman(&b_public);
468    let shared_b = b_secret.diffie_hellman(&a_public);
469    if shared_a.as_bytes() != shared_b.as_bytes() {
470        return Err("shared secret mismatch".into());
471    }
472    let mut h = Sha256::new();
473    h.update(b"arks-ssh-partial-ecdh");
474    h.update(shared_a.as_bytes());
475    let digest = h.finalize();
476    Ok(format!(
477        "ecdh_selfcheck=ok shared_sha256={:02x}{:02x}…",
478        digest[0], digest[1]
479    ))
480}
481
482/// One authorized `ssh-ed25519` key entry parsed from `authorized_keys`.
483struct AuthorizedEd25519Key {
484    verifying: VerifyingKey,
485    blob: Vec<u8>,
486    /// Username extracted from an immediately preceding `# <user> (<title>)` comment line, if any.
487    comment_user: Option<String>,
488}
489
490/// Authenticated SSH identity captured from `SSH_MSG_USERAUTH_REQUEST` + verified Ed25519 key.
491#[derive(Debug, Clone, PartialEq, Eq)]
492struct SshAuthIdentity {
493    /// Raw username sent in `SSH_MSG_USERAUTH_REQUEST`.
494    request_user: String,
495    /// Username extracted from `# <user> (<title>)` in `authorized_keys`, if present.
496    key_comment_user: Option<String>,
497    /// Verified SSH wire public key blob (`string "ssh-ed25519" || string pub32`).
498    public_blob: Vec<u8>,
499}
500
501/// Extract `<user>` from a `sync_authorized_keys` comment line of the form `# <user> (<title>)`.
502fn parse_authorized_keys_comment_user(comment_line: &str) -> Option<String> {
503    let rest = comment_line.trim().strip_prefix('#')?.trim();
504    let (user_part, title_part) = rest.split_once('(')?;
505    if !title_part.ends_with(')') {
506        return None;
507    }
508    let user = user_part.trim();
509    if user.is_empty()
510        || user.len() > 80
511        || user.starts_with('.')
512        || !user
513            .chars()
514            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
515    {
516        return None;
517    }
518    Some(user.to_string())
519}
520
521/// Parse one OpenSSH `ssh-ed25519` public key line into `(VerifyingKey, wire_blob)`.
522fn parse_authorized_ed25519_line(line: &str) -> Option<(VerifyingKey, Vec<u8>)> {
523    let parts: Vec<&str> = line.split_whitespace().collect();
524    if parts.len() < 2 {
525        return None;
526    }
527    let (alg, b64) = if parts[0].starts_with("ssh-") || parts[0].starts_with("ecdsa-") {
528        (parts[0], parts[1])
529    } else if parts.len() >= 3 && (parts[1].starts_with("ssh-") || parts[1].starts_with("ecdsa-")) {
530        (parts[1], parts[2])
531    } else {
532        return None;
533    };
534    if alg != "ssh-ed25519" {
535        return None;
536    }
537    let blob = base64::Engine::decode(&base64::engine::general_purpose::STANDARD, b64).ok()?;
538    let vk = parse_ssh_ed25519_verifying(&blob)?;
539    Some((vk, blob))
540}
541
542/// Load ssh-ed25519 verifying keys from an OpenSSH `authorized_keys` file, capturing
543/// optional `# <user> (<title>)` comment ownership annotations (`SEC-02`).
544fn load_authorized_ed25519_keys(authorized_keys: &Path) -> Vec<AuthorizedEd25519Key> {
545    let mut out = Vec::new();
546    let Ok(raw) = std::fs::read_to_string(authorized_keys) else {
547        return out;
548    };
549    let mut pending_comment_user: Option<String> = None;
550    for line in raw.lines() {
551        let line = line.trim();
552        if line.is_empty() {
553            pending_comment_user = None;
554            continue;
555        }
556        if line.starts_with('#') {
557            pending_comment_user = parse_authorized_keys_comment_user(line);
558            continue;
559        }
560        let comment_user = pending_comment_user.take();
561        if let Some((verifying, blob)) = parse_authorized_ed25519_line(line) {
562            out.push(AuthorizedEd25519Key {
563                verifying,
564                blob,
565                comment_user,
566            });
567        }
568    }
569    out
570}
571
572/// Verify an ed25519 publickey signature against `authorized_keys`.
573/// Returns `Ok(comment_user)` when authorized and signature verifies.
574fn verify_publickey_against_authorized(
575    authorized_keys: &Path,
576    public_blob: &[u8],
577    challenge: &[u8],
578    signature_blob: &[u8],
579) -> Result<Option<String>, String> {
580    let keys = load_authorized_ed25519_keys(authorized_keys);
581    if keys.is_empty() {
582        return Err("authorized_keys has no ssh-ed25519 lines".into());
583    }
584    let Some(vk) = parse_ssh_ed25519_verifying(public_blob) else {
585        return Err("public blob not ssh-ed25519".into());
586    };
587    let Some(matched) = keys.iter().find(|entry| {
588        entry.verifying.as_bytes() == vk.as_bytes() || entry.blob.as_slice() == public_blob
589    }) else {
590        return Err("public key not in authorized_keys".into());
591    };
592    let mut off = 0usize;
593    let alg = read_ssh_bytes(signature_blob, &mut off).ok_or("sig alg")?;
594    if alg.as_slice() != b"ssh-ed25519" {
595        return Err("signature alg not ssh-ed25519".into());
596    }
597    let sig_bytes = read_ssh_bytes(signature_blob, &mut off).ok_or("sig bytes")?;
598    if sig_bytes.len() != 64 {
599        return Err(format!("sig len {}", sig_bytes.len()));
600    }
601    let mut arr = [0u8; 64];
602    arr.copy_from_slice(&sig_bytes);
603    let sig = Signature::from_bytes(&arr);
604    vk.verify(challenge, &sig)
605        .map_err(|e| format!("ed25519 verify fail: {e}"))?;
606    Ok(matched.comment_user.clone())
607}
608
609/// Resolve the effective authenticated username for an SSH session against `ForgeStore` (`SEC-02`).
610///
611/// Trust precedence prevents login-name spoofing:
612/// 1. Cryptographic match of the verified Ed25519 key against `store.users[*].ssh_keys`.
613/// 2. Key-matched `# <user> (<title>)` annotation from `authorized_keys` (cross-checked against
614///    `store.users` when users are configured).
615/// 3. `SSH_MSG_USERAUTH_REQUEST` username ONLY in single-user mode (`store.users.is_empty()`);
616///    when `ForgeStore` users exist, never fall back to an untrusted `request_user` even for
617///    keyless accounts.
618fn resolve_ssh_identity(store: &ForgeStore, auth: &SshAuthIdentity) -> Option<String> {
619    if store.corrupt {
620        return None;
621    }
622    let presented_vk = parse_ssh_ed25519_verifying(&auth.public_blob);
623
624    // 1. Direct cryptographic key match inside ForgeStore user records.
625    if let Some(ref vk) = presented_vk {
626        for acct in &store.users {
627            for rec in &acct.ssh_keys {
628                if let Some((stored_vk, stored_blob)) =
629                    parse_authorized_ed25519_line(rec.public_key.trim())
630                {
631                    if stored_vk.as_bytes() == vk.as_bytes()
632                        || stored_blob.as_slice() == auth.public_blob.as_slice()
633                    {
634                        return Some(acct.username.clone());
635                    }
636                }
637            }
638        }
639    }
640
641    // 2. `# <user> (<title>)` ownership annotation from `authorized_keys`.
642    if let Some(ref comment_user) = auth.key_comment_user {
643        let cu = comment_user.trim();
644        if !cu.is_empty() {
645            if store.users.is_empty() {
646                return Some(cu.to_string());
647            }
648            if let Some(acct) = store.users.iter().find(|u| u.username == cu) {
649                return Some(acct.username.clone());
650            }
651            // Key explicitly belongs to an unknown user; never fall back to request_user.
652            return None;
653        }
654    }
655
656    // 3. Fallback to SSH `USERAUTH_REQUEST` username ONLY in single-user mode
657    // (`store.users.is_empty()`). When `ForgeStore` accounts exist, fail closed
658    // so an unannotated key cannot impersonate keyless accounts via `request_user`.
659    if !store.users.is_empty() {
660        return None;
661    }
662    let req_user = auth.request_user.trim();
663    if req_user.is_empty() {
664        return None;
665    }
666    Some(req_user.to_string())
667}
668
669/// Enforce `ForgeStore` repository RBAC on SSH `git-upload-pack` / `git-receive-pack` (`SEC-02`).
670///
671/// Mirrors `web_ui::auth_api`:
672/// - Corrupted `ForgeStore` always fails closed for both reads and writes.
673/// - Archived repositories always reject writes (`git-receive-pack`).
674/// - Single-user mode (`store.users.is_empty()`) stays open.
675/// - Public repositories allow reads (`git-upload-pack`) for any authenticated SSH key.
676/// - Private repository reads require an `admin`, `maintainer`, or explicit `store.collaborators`
677///   account; writes always require an `admin` or `maintainer` (matching HTTP parity).
678fn check_ssh_repo_rbac(
679    store: &ForgeStore,
680    effective_user: Option<&str>,
681    is_write: bool,
682) -> Result<(), String> {
683    if store.corrupt {
684        return Err("forge store is corrupted (fail-closed)".into());
685    }
686    if is_write && store.archived {
687        return Err("repository is archived (read-only)".into());
688    }
689    if store.users.is_empty() {
690        return Ok(());
691    }
692    let is_private = store.visibility == "private";
693    if !is_write && !is_private {
694        return Ok(());
695    }
696    let Some(username) = effective_user else {
697        return Err(if is_write {
698            "permission denied: SSH key is not bound to a repository write account".into()
699        } else {
700            "permission denied: private repository requires an authorized SSH user".into()
701        });
702    };
703    let Some(acct) = store.users.iter().find(|u| u.username == username) else {
704        return Err(format!(
705            "permission denied: SSH user '{username}' is not registered"
706        ));
707    };
708    let is_collaborator = store.collaborators.iter().any(|c| c == username);
709    let is_privileged = acct.role == "admin" || acct.role == "maintainer";
710    if is_privileged || (!is_write && is_collaborator) {
711        Ok(())
712    } else if is_write {
713        Err(format!(
714            "permission denied: role '{}' cannot push to this repository",
715            acct.role
716        ))
717    } else {
718        Err(format!(
719            "permission denied: role '{}' cannot read private repository",
720            acct.role
721        ))
722    }
723}
724
725/// Offline publickey verify Partial: parse authorized_keys + ed25519 verify path.
726fn publickey_verify_scaffold(authorized_keys: &Path, host: Option<&HostEd25519>) -> String {
727    let mut notes = Vec::new();
728    let auth_probe = probe_authorized_keys(authorized_keys);
729    notes.push(format!("authorized_keys_probe={auth_probe}"));
730    let keys = load_authorized_ed25519_keys(authorized_keys);
731    notes.push(format!("auth_ed25519_lines={}", keys.len()));
732    if !keys.is_empty() {
733        notes.push("auth_pubkey_line=ssh-ed25519_parse_ok".into());
734    }
735    if let Some(h) = host {
736        let challenge = Sha256::digest(b"arks-ssh-partial-auth-verify-challenge");
737        let sig = h.signing.sign(&challenge);
738        match h.signing.verifying_key().verify(&challenge, &sig) {
739            Ok(()) => notes.push("auth_verify_selfcheck=ok (host key; offline Partial)".into()),
740            Err(e) => notes.push(format!("auth_verify_selfcheck=fail ({e})")),
741        }
742        // If host pubkey is also listed in authorized_keys, prove authorized verify path.
743        let sig_blob = sign_ssh_ed25519(h, &challenge);
744        match verify_publickey_against_authorized(
745            authorized_keys,
746            &h.public_blob,
747            &challenge,
748            &sig_blob,
749        ) {
750            Ok(_) => notes.push("auth_authorized_keys_verify=ok (host key listed; Partial)".into()),
751            Err(e) => notes.push(format!("auth_authorized_keys_verify=skip ({e})")),
752        }
753    } else {
754        notes.push("auth_verify_selfcheck=skipped (no host key)".into());
755    }
756    notes.join("; ")
757}
758
759fn parse_ssh_ed25519_verifying(blob: &[u8]) -> Option<VerifyingKey> {
760    let mut off = 0usize;
761    let alg = read_ssh_bytes(blob, &mut off)?;
762    if alg.as_slice() != b"ssh-ed25519" {
763        return None;
764    }
765    let pub32 = read_ssh_bytes(blob, &mut off)?;
766    if pub32.len() != 32 {
767        return None;
768    }
769    let mut a = [0u8; 32];
770    a.copy_from_slice(&pub32);
771    VerifyingKey::from_bytes(&a).ok()
772}
773
774/// Parse `git-upload-pack '|git-receive-pack` from an SSH `exec` command string (Partial).
775fn parse_git_exec_service(cmd: &str) -> Option<&'static str> {
776    if cmd.contains('\0') {
777        return None;
778    }
779    let c = cmd.trim().trim_matches('\'').trim_matches('"');
780    let first = c.split_whitespace().next().unwrap_or("");
781    let base = first.rsplit('/').next().unwrap_or(first);
782    match base {
783        "git-upload-pack" | "upload-pack" => Some("git-upload-pack"),
784        "git-receive-pack" | "receive-pack" => Some("git-receive-pack"),
785        _ => None,
786    }
787}
788
789fn extract_ssh_exec_path_arg(exec_cmd: &str) -> Result<String, String> {
790    if exec_cmd.contains('\0') {
791        return Err("invalid ssh exec command: NUL byte rejected".into());
792    }
793    let trimmed = exec_cmd.trim();
794    let mut parts = trimmed.splitn(2, char::is_whitespace);
795    let _svc = parts.next().unwrap_or("");
796    let raw = parts.next().unwrap_or("").trim();
797    let unquoted = if (raw.starts_with('\'') && raw.ends_with('\'') && raw.len() >= 2)
798        || (raw.starts_with('"') && raw.ends_with('"') && raw.len() >= 2)
799    {
800        &raw[1..raw.len() - 1]
801    } else {
802        raw
803    };
804    if unquoted.contains('\0') {
805        return Err("invalid multi-repo ssh path: NUL byte rejected".into());
806    }
807    Ok(unquoted.to_string())
808}
809
810/// Resolve a single repository or multi-repo child under `base_path` from an SSH `exec` command.
811///
812/// Multi-repo roots (`INT-S04`) accept `<root>/<repo>.git`, `<root>/<repo>`, or
813/// `<root>/<repo>/.git`, strictly rejecting `..`, NUL, backslashes, hidden segments,
814/// and canonical path escapes (including symlinks outside `base_path`).
815fn open_ssh_repo(base_path: &Path, exec_cmd: &str) -> Result<Repository, String> {
816    if exec_cmd.contains('\0') {
817        return Err("invalid ssh exec command: NUL byte rejected".into());
818    }
819    // Single-repo mode: `base_path` (or `base_path/.git`) is itself a repository.
820    if base_path.join("HEAD").is_file() {
821        return Repository::open(base_path)
822            .map_err(|e| format!("open repo {}: {e}", base_path.display()));
823    }
824    let dot_git = base_path.join(".git");
825    if dot_git.join("HEAD").is_file() {
826        return Repository::open(&dot_git)
827            .map_err(|e| format!("open repo {}: {e}", dot_git.display()));
828    }
829
830    // Multi-repo root mode: extract and strictly validate target repo under `base_path`.
831    let arg = extract_ssh_exec_path_arg(exec_cmd)?;
832    if arg.is_empty() || arg.contains("..") || arg.contains('\\') || arg.contains('\0') {
833        return Err(format!("invalid multi-repo ssh path: {arg}"));
834    }
835    let rel = arg.trim_start_matches('/').trim_end_matches('/');
836    if rel.is_empty() || rel.contains("//") {
837        return Err(format!("invalid multi-repo ssh path: {arg}"));
838    }
839    let mut seg_count = 0usize;
840    for comp in Path::new(rel).components() {
841        match comp {
842            Component::Normal(os) => {
843                let Some(seg) = os.to_str() else {
844                    return Err(format!("invalid multi-repo ssh path: {arg}"));
845                };
846                if seg.is_empty()
847                    || seg.starts_with('.')
848                    || seg.contains("..")
849                    || seg.contains('\\')
850                    || seg.contains('\0')
851                {
852                    return Err(format!("invalid multi-repo ssh path: {arg}"));
853                }
854                seg_count += 1;
855            }
856            _ => return Err(format!("invalid multi-repo ssh path: {arg}")),
857        }
858    }
859    if seg_count == 0 {
860        return Err(format!("invalid multi-repo ssh path: {arg}"));
861    }
862    let clean = rel.trim_end_matches(".git");
863    if clean.is_empty() || clean.ends_with('/') {
864        return Err(format!("invalid multi-repo ssh path: {arg}"));
865    }
866    if Path::new(clean)
867        .file_name()
868        .and_then(|n| n.to_str())
869        .is_none_or(|n| n.is_empty() || n.starts_with('.'))
870    {
871        return Err(format!("invalid multi-repo ssh path: {arg}"));
872    }
873
874    let canon_base = std::fs::canonicalize(base_path)
875        .map_err(|e| format!("open repo root {}: {e}", base_path.display()))?;
876    let candidates = [
877        base_path.join(format!("{clean}.git")),
878        base_path.join(clean),
879        base_path.join(clean).join(".git"),
880    ];
881    for candidate in candidates {
882        if !candidate.join("HEAD").is_file() {
883            continue;
884        }
885        let canon_cand = std::fs::canonicalize(&candidate)
886            .map_err(|e| format!("open repo {}: {e}", candidate.display()))?;
887        if !canon_cand.starts_with(&canon_base) || canon_cand == canon_base {
888            return Err(format!("invalid multi-repo ssh path (escapes root): {arg}"));
889        }
890        return Repository::open(&canon_cand)
891            .map_err(|e| format!("open repo {}: {e}", canon_cand.display()));
892    }
893    Err(format!(
894        "open repo {}: not found under {}",
895        arg,
896        base_path.display()
897    ))
898}
899
900/// Dispatch session `exec` into existing pack stdio paths (Partial; not Claimed SSH channel e2e).
901fn dispatch_git_exec_to_pack(repo_path: &Path, exec_cmd: &str) -> Result<String, String> {
902    let Some(svc) = parse_git_exec_service(exec_cmd) else {
903        return Err(format!("exec not git-upload-pack|receive-pack: {exec_cmd}"));
904    };
905    let mut repo = open_ssh_repo(repo_path, exec_cmd)?;
906    // Empty duplex: proves dispatch wiring into pack entrypoints; real SSH channel IO Partial.
907    let mut buf = Cursor::new(Vec::<u8>::new());
908    match svc {
909        "git-upload-pack" => match upload_pack_stream(&repo, &mut buf) {
910            Ok(()) => Ok(
911                "channel_exec=git-upload-pack dispatched upload_pack_stream ok \
912                 (Partial empty-peer; Claimed SSH channel e2e Missing)"
913                    .to_string(),
914            ),
915            Err(e) => Ok(format!(
916                "channel_exec=git-upload-pack dispatch reached upload_pack_stream err={e} \
917                 (Partial; empty peer expected; not Claimed)"
918            )),
919        },
920        "git-receive-pack" => {
921            let store = ForgeStore::load_shared(repo.common_dir());
922            if store.corrupt {
923                return Err("forge store is corrupted (fail-closed)".into());
924            }
925            if store.archived {
926                return Err("repository is archived (read-only)".into());
927            }
928            match receive_pack_stream_as(&mut repo, &mut buf, &Pusher::ssh()) {
929                Ok(()) => Ok(
930                    "channel_exec=git-receive-pack dispatched receive_pack_stream ok \
931                     (Partial empty-peer; Claimed SSH channel e2e Missing)"
932                        .to_string(),
933                ),
934                Err(e) => Ok(format!(
935                    "channel_exec=git-receive-pack dispatch reached receive_pack_stream err={e} \
936                     (Partial; empty peer expected; not Claimed)"
937                )),
938            }
939        }
940        _ => Err(format!("unknown service {svc}")),
941    }
942}
943
944fn channel_git_hookup_scaffold(repo_path: &Path) -> String {
945    let st = path_status(repo_path);
946    let up = dispatch_git_exec_to_pack(repo_path, "git-upload-pack '.'");
947    let rp = dispatch_git_exec_to_pack(repo_path, "git-receive-pack '.'");
948    format!(
949        "channel_session=partial_dispatch; repo_path={} ({st}); upload={:?}; receive={:?}; \
950         design ≠ Claimed SSH git subsystem e2e",
951        repo_path.display(),
952        up,
953        rp
954    )
955}
956
957/// Encode the X25519 output string as the positive SSH `mpint K`.
958///
959/// RFC 8731 §3.1 deliberately reinterprets the returned octets directly as
960/// an unsigned fixed-length integer in network byte order; it does not first
961/// reverse X25519's little-endian field-element representation.
962fn x25519_shared_as_mpint(shared_wire: &[u8; 32]) -> Vec<u8> {
963    let magnitude = shared_wire.to_vec();
964    let first_nonzero = magnitude
965        .iter()
966        .position(|b| *b != 0)
967        .unwrap_or(magnitude.len());
968    let mut value = magnitude[first_nonzero..].to_vec();
969    if value.first().is_some_and(|b| b & 0x80 != 0) {
970        value.insert(0, 0);
971    }
972    ssh_string(&value)
973}
974
975/// RFC 4253 §7.2 KDF. `encoded_k` includes the SSH mpint length prefix.
976fn ssh_kdf_bytes(encoded_k: &[u8], exchange_hash: &[u8], letter: u8, n: usize) -> Vec<u8> {
977    let mut out = Vec::with_capacity(n);
978    while out.len() < n {
979        let mut h = Sha256::new();
980        h.update(encoded_k);
981        h.update(exchange_hash);
982        if out.is_empty() {
983            h.update([letter]);
984            h.update(exchange_hash); // session_id is H for the first key exchange.
985        } else {
986            h.update(&out);
987        }
988        out.extend_from_slice(&h.finalize());
989    }
990    out.truncate(n);
991    out
992}
993
994fn openssh_chacha(
995    encoded_k: &[u8],
996    exchange_hash: &[u8],
997    client_to_server: bool,
998    sequence: u32,
999) -> Result<OpenSshChaCha, String> {
1000    let letter = if client_to_server { b'C' } else { b'D' };
1001    let key = ssh_kdf_bytes(encoded_k, exchange_hash, letter, 64);
1002    OpenSshChaCha::new(&key, sequence)
1003}
1004
1005fn encrypted_transport_selfcheck(encoded_k: &[u8], exchange_hash: &[u8]) -> String {
1006    let mut c2s = match openssh_chacha(encoded_k, exchange_hash, true, 0) {
1007        Ok(c) => c,
1008        Err(e) => return format!("encrypted_transport=selfcheck_fail ({e})"),
1009    };
1010    let sample = b"arks-ssh-partial-post-newkeys";
1011    match c2s.seal_packet(sample).and_then(|packet| {
1012        let mut peer = openssh_chacha(encoded_k, exchange_hash, true, 0)?;
1013        let encrypted_length = packet[..4].try_into().map_err(|_| "length")?;
1014        // The selfcheck knows the deterministic packet body length.
1015        let body_len = packet.len() - 4 - 16;
1016        let body = packet[4..4 + body_len].to_vec();
1017        let tag = packet[4 + body_len..].try_into().map_err(|_| "tag")?;
1018        peer.open_packet(encrypted_length, body, tag, 65_536)
1019    }) {
1020        Ok(pt) if pt == sample => "encrypted_transport=OpenSSH-ChaCha packet selfcheck=ok \
1021             (live stock-client receipt still required for Claimed)"
1022            .into(),
1023        Ok(_) => "encrypted_transport=selfcheck_mismatch".into(),
1024        Err(e) => format!("encrypted_transport=selfcheck_fail ({e})"),
1025    }
1026}
1027
1028fn write_encrypted_packet(
1029    stream: &mut TcpStream,
1030    cipher: &mut OpenSshChaCha,
1031    payload: &[u8],
1032) -> Result<(), String> {
1033    cipher.write_packet(stream, payload)
1034}
1035
1036fn read_encrypted_packet(
1037    stream: &mut TcpStream,
1038    cipher: &mut OpenSshChaCha,
1039    max: usize,
1040) -> Result<Vec<u8>, String> {
1041    cipher.read_packet(stream, max)
1042}
1043
1044/// After NEWKEYS: AEAD + USERAUTH loop + session channel → pack duplex.
1045fn continue_after_newkeys(
1046    stream: &mut TcpStream,
1047    encoded_k: &[u8],
1048    exchange_hash: &[u8],
1049    initial_sequence: u32,
1050    authorized_keys: &Path,
1051    repo_path: &Path,
1052    host: Option<&HostEd25519>,
1053) -> (SshStage, String) {
1054    let mut notes = vec![encrypted_transport_selfcheck(encoded_k, exchange_hash)];
1055    let mut c2s = match openssh_chacha(encoded_k, exchange_hash, true, initial_sequence) {
1056        Ok(c) => c,
1057        Err(e) => return (SshStage::EncryptedTransport, format!("c2s key error: {e}")),
1058    };
1059    let mut s2c = match openssh_chacha(encoded_k, exchange_hash, false, initial_sequence) {
1060        Ok(c) => c,
1061        Err(e) => return (SshStage::EncryptedTransport, format!("s2c key error: {e}")),
1062    };
1063
1064    // Stock OpenSSH: SERVICE_REQUEST ssh-userauth → SERVICE_ACCEPT, then one or
1065    // more USERAUTH_REQUEST (none → publickey query → signed publickey).
1066    let _ = stream.set_nodelay(true);
1067    // Pack negotiation + tiny clone can exceed the accept-time 2s probe budget.
1068    let _ = stream.set_read_timeout(Some(Duration::from_secs(30)));
1069    let _ = stream.set_write_timeout(Some(Duration::from_secs(30)));
1070    let mut next = read_encrypted_packet(stream, &mut c2s, 65_536);
1071    if let Ok(payload) = &next
1072        && payload.first() == Some(&5)
1073    {
1074        let mut off = 1usize;
1075        if let Some(service) = read_ssh_bytes(payload, &mut off) {
1076            let mut accept = vec![6]; // SSH_MSG_SERVICE_ACCEPT
1077            accept.extend(ssh_string(&service));
1078            match write_encrypted_packet(stream, &mut s2c, &accept) {
1079                Ok(()) => notes.push(format!(
1080                    "wire_SERVICE_ACCEPT={} (OpenSSH ChaCha decrypt+encrypt ok)",
1081                    String::from_utf8_lossy(&service)
1082                )),
1083                Err(e) => notes.push(format!("wire_SERVICE_ACCEPT=write_err ({e})")),
1084            }
1085            next = read_encrypted_packet(stream, &mut c2s, 65_536);
1086        }
1087    }
1088
1089    let mut authed_identity: Option<SshAuthIdentity> = None;
1090    for round in 0..8 {
1091        let payload = match next {
1092            Ok(p) => p,
1093            Err(e) => {
1094                notes.push(format!("wire_auth=timeout_or_err round={round} ({e})"));
1095                break;
1096            }
1097        };
1098        if payload.first() != Some(&50) {
1099            notes.push(format!(
1100                "wire_post_newkeys_msg={} (expected USERAUTH=50)",
1101                payload.first().copied().unwrap_or(0)
1102            ));
1103            break;
1104        }
1105        notes.push(format!("wire_USERAUTH_REQUEST=seen round={round}"));
1106        let (identity, auth_note) = handle_userauth_request_partial(
1107            &payload,
1108            exchange_hash,
1109            authorized_keys,
1110            host,
1111            stream,
1112            &mut s2c,
1113        );
1114        notes.push(auth_note);
1115        if let Some(id) = identity {
1116            authed_identity = Some(id);
1117            break;
1118        }
1119        next = read_encrypted_packet(stream, &mut c2s, 65_536);
1120    }
1121
1122    let Some(auth_id) = authed_identity else {
1123        notes.push(publickey_verify_scaffold(authorized_keys, host));
1124        notes.push(channel_git_hookup_scaffold(repo_path));
1125        return (SshStage::AuthPublickey, notes.join("; "));
1126    };
1127
1128    match run_session_channel_pack(stream, &mut c2s, &mut s2c, repo_path, &auth_id, &mut notes) {
1129        Ok(()) => (SshStage::ChannelSession, notes.join("; ")),
1130        Err(e) => {
1131            notes.push(e);
1132            notes.push(channel_git_hookup_scaffold(repo_path));
1133            (SshStage::ChannelSession, notes.join("; "))
1134        }
1135    }
1136}
1137
1138/// SSH session channel + `exec` → live `upload_pack_stream` / `receive_pack_stream`.
1139fn run_session_channel_pack(
1140    stream: &mut TcpStream,
1141    c2s: &mut OpenSshChaCha,
1142    s2c: &mut OpenSshChaCha,
1143    repo_path: &Path,
1144    auth_id: &SshAuthIdentity,
1145    notes: &mut Vec<String>,
1146) -> Result<(), String> {
1147    let mut peer_chan: Option<u32> = None;
1148    let mut peer_initial_window: u32 = 0;
1149    let mut peer_max_packet: u32 = SSH_LOCAL_MAX_PACKET;
1150    let our_chan: u32 = 0;
1151    let mut exec_cmd: Option<String> = None;
1152
1153    for _ in 0..32 {
1154        let msg = read_encrypted_packet(stream, c2s, 65_536)
1155            .map_err(|e| format!("wire_channel=timeout_or_err ({e})"))?;
1156        match msg.first().copied() {
1157            Some(90) => {
1158                // SSH_MSG_CHANNEL_OPEN
1159                let mut off = 1usize;
1160                let chan_type = read_ssh_bytes(&msg, &mut off).unwrap_or_default();
1161                let sender = read_u32(&msg, &mut off).unwrap_or(0);
1162                peer_initial_window = read_u32(&msg, &mut off).unwrap_or(0);
1163                peer_max_packet = read_u32(&msg, &mut off)
1164                    .unwrap_or(SSH_LOCAL_MAX_PACKET)
1165                    .max(1024);
1166                notes.push(format!(
1167                    "wire_CHANNEL_OPEN={} sender={sender} peer_window={peer_initial_window}",
1168                    String::from_utf8_lossy(&chan_type)
1169                ));
1170                if chan_type.as_slice() != b"session" {
1171                    let mut fail = vec![92]; // CHANNEL_OPEN_FAILURE
1172                    fail.extend_from_slice(&sender.to_be_bytes());
1173                    fail.extend_from_slice(&2u32.to_be_bytes()); // SSH_OPEN_ADMINISTRATIVELY_PROHIBITED
1174                    fail.extend(ssh_string(b"only session"));
1175                    fail.extend(ssh_string(b""));
1176                    let _ = write_encrypted_packet(stream, s2c, &fail);
1177                    return Err("channel_open=non_session".into());
1178                }
1179                peer_chan = Some(sender);
1180                let mut conf = vec![91]; // CHANNEL_OPEN_CONFIRMATION
1181                conf.extend_from_slice(&sender.to_be_bytes());
1182                conf.extend_from_slice(&our_chan.to_be_bytes());
1183                conf.extend_from_slice(&SSH_LOCAL_INITIAL_WINDOW.to_be_bytes());
1184                conf.extend_from_slice(&SSH_LOCAL_MAX_PACKET.to_be_bytes());
1185                write_encrypted_packet(stream, s2c, &conf)
1186                    .map_err(|e| format!("channel_open_confirm=write_err ({e})"))?;
1187            }
1188            Some(93) => {
1189                // RFC 4254 SSH_MSG_CHANNEL_WINDOW_ADJUST received prior to exec.
1190                let mut off = 1usize;
1191                let _recip = read_u32(&msg, &mut off).unwrap_or(0);
1192                let bytes_to_add = read_u32(&msg, &mut off).unwrap_or(0);
1193                peer_initial_window = peer_initial_window.saturating_add(bytes_to_add);
1194            }
1195            Some(98) => {
1196                // CHANNEL_REQUEST
1197                let mut off = 1usize;
1198                let recip = read_u32(&msg, &mut off).unwrap_or(0);
1199                let req = read_ssh_bytes(&msg, &mut off).unwrap_or_default();
1200                let want_reply = msg.get(off).copied().unwrap_or(0) != 0;
1201                if off < msg.len() {
1202                    off += 1;
1203                }
1204                if recip != our_chan {
1205                    notes.push(format!("wire_CHANNEL_REQUEST=wrong_recip={recip}"));
1206                }
1207                if req.as_slice() == b"exec" {
1208                    let cmd = read_ssh_bytes(&msg, &mut off).unwrap_or_default();
1209                    let cmd_s = String::from_utf8_lossy(&cmd).into_owned();
1210                    notes.push(format!("wire_CHANNEL_REQUEST_exec={cmd_s}"));
1211                    if want_reply {
1212                        let mut ok = vec![99]; // CHANNEL_SUCCESS
1213                        ok.extend_from_slice(&peer_chan.unwrap_or(0).to_be_bytes());
1214                        write_encrypted_packet(stream, s2c, &ok)
1215                            .map_err(|e| format!("channel_success=write_err ({e})"))?;
1216                    }
1217                    exec_cmd = Some(cmd_s);
1218                    break;
1219                }
1220                if req.as_slice() == b"subsystem" {
1221                    // git uses exec, not subsystem; refuse cleanly.
1222                    notes.push("wire_CHANNEL_REQUEST_subsystem=refused".into());
1223                    if want_reply {
1224                        let mut fail = vec![100];
1225                        fail.extend_from_slice(&peer_chan.unwrap_or(0).to_be_bytes());
1226                        let _ = write_encrypted_packet(stream, s2c, &fail);
1227                    }
1228                    continue;
1229                }
1230                // OpenSSH git often sends `env` (e.g. GIT_PROTOCOL) before exec.
1231                // Reply SUCCESS so the client continues; we do not apply env vars.
1232                notes.push(format!(
1233                    "wire_CHANNEL_REQUEST_ack={}",
1234                    String::from_utf8_lossy(&req)
1235                ));
1236                if want_reply {
1237                    let mut ok = vec![99]; // CHANNEL_SUCCESS
1238                    ok.extend_from_slice(&peer_chan.unwrap_or(0).to_be_bytes());
1239                    let _ = write_encrypted_packet(stream, s2c, &ok);
1240                }
1241            }
1242            Some(96) | Some(97) => {
1243                notes.push(format!(
1244                    "wire_channel_early_eof_or_close={}",
1245                    msg.first().copied().unwrap_or(0)
1246                ));
1247                break;
1248            }
1249            Some(2) | Some(4) => {
1250                // ignore / debug
1251            }
1252            other => {
1253                notes.push(format!("wire_channel_msg={}", other.unwrap_or(0)));
1254            }
1255        }
1256    }
1257
1258    let Some(peer) = peer_chan else {
1259        return Err("channel_open=missing".into());
1260    };
1261    let Some(cmd) = exec_cmd else {
1262        return Err("channel_exec=missing".into());
1263    };
1264
1265    let exit_code: u32 = if parse_git_exec_service(&cmd).is_some() {
1266        let mut pipe = SshChannelPipe {
1267            stream,
1268            c2s,
1269            s2c,
1270            peer_channel: peer,
1271            max_data: peer_max_packet.min(16_384) as usize,
1272            local_window_remaining: SSH_LOCAL_INITIAL_WINDOW,
1273            local_window_consumed: 0,
1274            peer_window_remaining: peer_initial_window,
1275            inbox: VecDeque::new(),
1276            eof: false,
1277            closed: false,
1278        };
1279        match dispatch_git_exec_live(repo_path, &cmd, auth_id, &mut pipe) {
1280            Ok(pack_note) => {
1281                notes.push(pack_note);
1282                0
1283            }
1284            Err(e) => {
1285                notes.push(e);
1286                1
1287            }
1288        }
1289    } else if cmd.trim() == "true" || cmd.trim().is_empty() {
1290        // B1 OpenSSH probe uses `ssh … true`; succeed with empty body.
1291        notes.push("channel_exec=true_ok".into());
1292        0
1293    } else {
1294        notes.push(format!("channel_exec=unsupported ({cmd})"));
1295        127
1296    };
1297
1298    // Stock OpenSSH/git require exit-status before EOF/CLOSE or the client
1299    // treats the remote command as failed (clone_rc=128) even after a good pack.
1300    send_channel_exit_status(stream, s2c, peer, exit_code)?;
1301    let mut eof_pkt = vec![96]; // CHANNEL_EOF
1302    eof_pkt.extend_from_slice(&peer.to_be_bytes());
1303    write_encrypted_packet(stream, s2c, &eof_pkt)
1304        .map_err(|e| format!("channel_eof=write_err ({e})"))?;
1305    let mut close_pkt = vec![97]; // CHANNEL_CLOSE
1306    close_pkt.extend_from_slice(&peer.to_be_bytes());
1307    write_encrypted_packet(stream, s2c, &close_pkt)
1308        .map_err(|e| format!("channel_close=write_err ({e})"))?;
1309    // Ensure CHANNEL_DATA / exit-status reached the peer before TCP teardown.
1310    let _ = stream.flush();
1311    // Drain a short window for the client's CHANNEL_CLOSE so git does not
1312    // report "Connection closed by remote host" after a successful pack.
1313    let _ = stream.set_read_timeout(Some(Duration::from_millis(500)));
1314    for _ in 0..8 {
1315        match read_encrypted_packet(stream, c2s, 65_536) {
1316            Ok(msg) if msg.first() == Some(&97) || msg.first() == Some(&96) => break,
1317            Ok(_) => continue,
1318            Err(_) => break,
1319        }
1320    }
1321    if exit_code == 0 {
1322        Ok(())
1323    } else {
1324        Err(format!("channel_exec=exit_status={exit_code}"))
1325    }
1326}
1327
1328fn send_channel_exit_status(
1329    stream: &mut TcpStream,
1330    s2c: &mut OpenSshChaCha,
1331    peer_channel: u32,
1332    code: u32,
1333) -> Result<(), String> {
1334    let mut pkt = vec![98]; // SSH_MSG_CHANNEL_REQUEST
1335    pkt.extend_from_slice(&peer_channel.to_be_bytes());
1336    pkt.extend(ssh_string(b"exit-status"));
1337    pkt.push(0); // want_reply = false
1338    pkt.extend_from_slice(&code.to_be_bytes());
1339    write_encrypted_packet(stream, s2c, &pkt).map_err(|e| format!("exit_status=write_err ({e})"))
1340}
1341
1342fn send_channel_window_adjust(
1343    stream: &mut TcpStream,
1344    s2c: &mut OpenSshChaCha,
1345    peer_channel: u32,
1346    bytes_to_add: u32,
1347) -> Result<(), String> {
1348    let mut pkt = Vec::with_capacity(9);
1349    pkt.push(93); // SSH_MSG_CHANNEL_WINDOW_ADJUST (RFC 4254 §5.2)
1350    pkt.extend_from_slice(&peer_channel.to_be_bytes());
1351    pkt.extend_from_slice(&bytes_to_add.to_be_bytes());
1352    write_encrypted_packet(stream, s2c, &pkt).map_err(|e| format!("window_adjust=write_err ({e})"))
1353}
1354
1355/// Duplex adapter: SSH CHANNEL_DATA ↔ Read+Write for pack sessions, enforcing
1356/// bidirectional RFC 4254 `SSH_MSG_CHANNEL_WINDOW_ADJUST` flow control (`NET-02`).
1357struct SshChannelPipe<'a> {
1358    stream: &'a mut TcpStream,
1359    c2s: &'a mut OpenSshChaCha,
1360    s2c: &'a mut OpenSshChaCha,
1361    peer_channel: u32,
1362    max_data: usize,
1363    local_window_remaining: u32,
1364    local_window_consumed: u32,
1365    peer_window_remaining: u32,
1366    inbox: VecDeque<u8>,
1367    eof: bool,
1368    closed: bool,
1369}
1370
1371impl SshChannelPipe<'_> {
1372    fn consume_local_window(&mut self, bytes: usize) -> std::io::Result<()> {
1373        let delta = u32::try_from(bytes).unwrap_or(u32::MAX);
1374        self.local_window_remaining = self.local_window_remaining.saturating_sub(delta);
1375        self.local_window_consumed = self.local_window_consumed.saturating_add(delta);
1376        if self.local_window_consumed >= SSH_LOCAL_WINDOW_REFILL_THRESHOLD
1377            || (self.local_window_remaining < SSH_LOCAL_WINDOW_REFILL_THRESHOLD
1378                && self.local_window_consumed > 0)
1379        {
1380            let add = self.local_window_consumed;
1381            send_channel_window_adjust(self.stream, self.s2c, self.peer_channel, add)
1382                .map_err(std::io::Error::other)?;
1383            self.local_window_remaining = self.local_window_remaining.saturating_add(add);
1384            self.local_window_consumed = 0;
1385        }
1386        Ok(())
1387    }
1388
1389    /// Read and dispatch one incoming encrypted SSH packet, updating inbox,
1390    /// local/peer flow-control windows, and EOF/CLOSE flags.
1391    fn pump_one_packet(&mut self) -> std::io::Result<()> {
1392        let msg =
1393            read_encrypted_packet(self.stream, self.c2s, 65_536).map_err(std::io::Error::other)?;
1394        match msg.first().copied() {
1395            Some(94) => {
1396                // SSH_MSG_CHANNEL_DATA
1397                let mut off = 1usize;
1398                let _recip = read_u32(&msg, &mut off).unwrap_or(0);
1399                if let Some(data) = read_ssh_bytes(&msg, &mut off) {
1400                    let n = data.len();
1401                    self.inbox.extend(data);
1402                    self.consume_local_window(n)?;
1403                }
1404            }
1405            Some(95) => {
1406                // SSH_MSG_CHANNEL_EXTENDED_DATA also consumes local window per RFC 4254 §5.2.
1407                let mut off = 1usize;
1408                let _recip = read_u32(&msg, &mut off).unwrap_or(0);
1409                let _data_type = read_u32(&msg, &mut off).unwrap_or(0);
1410                if let Some(data) = read_ssh_bytes(&msg, &mut off) {
1411                    self.consume_local_window(data.len())?;
1412                }
1413            }
1414            Some(93) => {
1415                // SSH_MSG_CHANNEL_WINDOW_ADJUST from peer increases our send budget.
1416                let mut off = 1usize;
1417                let _recip = read_u32(&msg, &mut off).unwrap_or(0);
1418                let bytes_to_add = read_u32(&msg, &mut off).unwrap_or(0);
1419                self.peer_window_remaining =
1420                    self.peer_window_remaining.saturating_add(bytes_to_add);
1421            }
1422            Some(96) => {
1423                // SSH_MSG_CHANNEL_EOF closes peer->server data; peer may still send WINDOW_ADJUST.
1424                self.eof = true;
1425            }
1426            Some(97) => {
1427                // SSH_MSG_CHANNEL_CLOSE terminates both directions.
1428                self.eof = true;
1429                self.closed = true;
1430            }
1431            Some(98) => {
1432                // Unexpected late request — fail if want_reply.
1433                let mut off = 1usize;
1434                let _ = read_u32(&msg, &mut off);
1435                let _ = read_ssh_bytes(&msg, &mut off);
1436                let want_reply = msg.get(off).copied().unwrap_or(0) != 0;
1437                if want_reply {
1438                    let mut fail = vec![100];
1439                    fail.extend_from_slice(&self.peer_channel.to_be_bytes());
1440                    let _ = write_encrypted_packet(self.stream, self.s2c, &fail);
1441                }
1442            }
1443            Some(2) | Some(4) => {}
1444            _ => {}
1445        }
1446        Ok(())
1447    }
1448
1449    /// Best-effort stderr diagnostic over `SSH_MSG_CHANNEL_EXTENDED_DATA` (stderr=1).
1450    fn send_stderr_notice(&mut self, msg: &str) {
1451        if msg.is_empty() || self.closed {
1452            return;
1453        }
1454        let data = msg.as_bytes();
1455        let allowed = usize::try_from(self.peer_window_remaining).unwrap_or(usize::MAX);
1456        let chunk = data.len().min(self.max_data.max(1)).min(allowed);
1457        if chunk == 0 {
1458            return;
1459        }
1460        let mut pkt = vec![95]; // SSH_MSG_CHANNEL_EXTENDED_DATA
1461        pkt.extend_from_slice(&self.peer_channel.to_be_bytes());
1462        pkt.extend_from_slice(&1u32.to_be_bytes()); // SSH_EXTENDED_DATA_STDERR
1463        pkt.extend(ssh_string(&data[..chunk]));
1464        if write_encrypted_packet(self.stream, self.s2c, &pkt).is_ok() {
1465            self.peer_window_remaining = self
1466                .peer_window_remaining
1467                .saturating_sub(u32::try_from(chunk).unwrap_or(u32::MAX));
1468        }
1469    }
1470}
1471
1472impl Read for SshChannelPipe<'_> {
1473    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
1474        while self.inbox.is_empty() && !self.eof {
1475            self.pump_one_packet()?;
1476        }
1477        if self.inbox.is_empty() {
1478            return Ok(0);
1479        }
1480        self.inbox.read(buf)
1481    }
1482}
1483
1484impl Write for SshChannelPipe<'_> {
1485    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
1486        if buf.is_empty() {
1487            return Ok(0);
1488        }
1489        while self.peer_window_remaining == 0 {
1490            if self.closed {
1491                return Err(std::io::Error::new(
1492                    std::io::ErrorKind::BrokenPipe,
1493                    "SSH peer closed channel with zero send window",
1494                ));
1495            }
1496            self.pump_one_packet()?;
1497        }
1498        let allowed = usize::try_from(self.peer_window_remaining).unwrap_or(usize::MAX);
1499        let chunk = buf.len().min(self.max_data.max(1)).min(allowed);
1500        let mut pkt = vec![94]; // CHANNEL_DATA
1501        pkt.extend_from_slice(&self.peer_channel.to_be_bytes());
1502        pkt.extend(ssh_string(&buf[..chunk]));
1503        write_encrypted_packet(self.stream, self.s2c, &pkt).map_err(std::io::Error::other)?;
1504        self.peer_window_remaining = self
1505            .peer_window_remaining
1506            .saturating_sub(u32::try_from(chunk).unwrap_or(u32::MAX));
1507        Ok(chunk)
1508    }
1509
1510    fn flush(&mut self) -> std::io::Result<()> {
1511        self.stream.flush()
1512    }
1513}
1514
1515fn dispatch_git_exec_live(
1516    repo_path: &Path,
1517    exec_cmd: &str,
1518    auth_id: &SshAuthIdentity,
1519    pipe: &mut SshChannelPipe<'_>,
1520) -> Result<String, String> {
1521    let Some(svc) = parse_git_exec_service(exec_cmd) else {
1522        return Err(format!("exec not git-upload-pack|receive-pack: {exec_cmd}"));
1523    };
1524    let mut repo = open_ssh_repo(repo_path, exec_cmd)?;
1525    let is_single_repo =
1526        repo_path.join("HEAD").is_file() || repo_path.join(".git").join("HEAD").is_file();
1527    if !is_single_repo
1528        && repo.common_dir() != repo_path
1529        && repo_path.join(".arks-global-auth").exists()
1530    {
1531        let global_store = ForgeStore::load_shared(&repo_path.join(".arks-global-auth"));
1532        if global_store.corrupt {
1533            let reason = "global forge store is corrupted (fail-closed)".to_string();
1534            pipe.send_stderr_notice(&format!("remote: {reason}\n"));
1535            return Err(reason);
1536        }
1537        crate::web_ui::sync_global_auth_into_repo(repo_path, repo.common_dir());
1538    }
1539    let store = ForgeStore::load_shared(repo.common_dir());
1540    let effective_user = resolve_ssh_identity(&store, auth_id);
1541    match svc {
1542        "git-upload-pack" => {
1543            if let Err(reason) = check_ssh_repo_rbac(&store, effective_user.as_deref(), false) {
1544                pipe.send_stderr_notice(&format!("remote: {reason}\n"));
1545                return Err(reason);
1546            }
1547            match upload_pack_stream(&repo, pipe) {
1548                Ok(()) => Ok(
1549                    "channel_exec=git-upload-pack live upload_pack_stream ok (OpenSSH channel)"
1550                        .into(),
1551                ),
1552                Err(e) => Err(format!("channel_exec=git-upload-pack live err={e}")),
1553            }
1554        }
1555        "git-receive-pack" => {
1556            if let Err(reason) = check_ssh_repo_rbac(&store, effective_user.as_deref(), true) {
1557                pipe.send_stderr_notice(&format!("remote: {reason}\n"));
1558                return Err(reason);
1559            }
1560            let pusher = match effective_user {
1561                Some(ref user) => Pusher::ssh_user(user.as_str()),
1562                None => Pusher::ssh(),
1563            };
1564            match receive_pack_stream_as(&mut repo, pipe, &pusher) {
1565                Ok(()) => Ok(
1566                    "channel_exec=git-receive-pack live receive_pack_stream ok (OpenSSH channel)"
1567                        .into(),
1568                ),
1569                Err(e) => Err(format!("channel_exec=git-receive-pack live err={e}")),
1570            }
1571        }
1572        _ => Err(format!("unknown service {svc}")),
1573    }
1574}
1575
1576/// Handle one USERAUTH_REQUEST. Returns `(authenticated_identity, notes)`.
1577fn handle_userauth_request_partial(
1578    payload: &[u8],
1579    session_id: &[u8],
1580    authorized_keys: &Path,
1581    host: Option<&HostEd25519>,
1582    stream: &mut TcpStream,
1583    s2c: &mut OpenSshChaCha,
1584) -> (Option<SshAuthIdentity>, String) {
1585    // SSH_MSG_USERAUTH_REQUEST: 50 || string user || string service || string method || …
1586    let mut off = 1usize;
1587    let user = read_ssh_bytes(payload, &mut off).unwrap_or_default();
1588    let service = read_ssh_bytes(payload, &mut off).unwrap_or_default();
1589    let method = read_ssh_bytes(payload, &mut off).unwrap_or_default();
1590    let request_user = String::from_utf8_lossy(&user).trim().to_string();
1591    let mut notes = format!(
1592        "auth_user={} service={} method={}",
1593        request_user,
1594        String::from_utf8_lossy(&service),
1595        String::from_utf8_lossy(&method)
1596    );
1597    if method.as_slice() != b"publickey" {
1598        notes.push_str("; auth=refuse_non_publickey Partial");
1599        let mut failure = vec![51]; // SSH_MSG_USERAUTH_FAILURE
1600        failure.extend(ssh_name_list(&["publickey"]));
1601        failure.push(0); // partial success = false
1602        let _ = write_encrypted_packet(stream, s2c, &failure);
1603        return (None, notes);
1604    }
1605    if off >= payload.len() {
1606        notes.push_str("; auth=publickey_short");
1607        let mut failure = vec![51];
1608        failure.extend(ssh_name_list(&["publickey"]));
1609        failure.push(0);
1610        let _ = write_encrypted_packet(stream, s2c, &failure);
1611        return (None, notes);
1612    }
1613    let has_sig = payload[off] != 0;
1614    off += 1;
1615    let alg = read_ssh_bytes(payload, &mut off).unwrap_or_default();
1616    let pubkey = read_ssh_bytes(payload, &mut off).unwrap_or_default();
1617    notes.push_str(&format!(
1618        "; alg={} has_sig={has_sig}",
1619        String::from_utf8_lossy(&alg)
1620    ));
1621    if !has_sig {
1622        let keys = load_authorized_ed25519_keys(authorized_keys);
1623        let ok = keys
1624            .iter()
1625            .any(|entry| entry.blob.as_slice() == pubkey.as_slice());
1626        notes.push_str(&format!("; auth_pubkey_query_authorized={ok}"));
1627        if ok {
1628            let mut pk_ok = vec![60]; // SSH_MSG_USERAUTH_PK_OK
1629            pk_ok.extend(ssh_string(&alg));
1630            pk_ok.extend(ssh_string(&pubkey));
1631            let _ = write_encrypted_packet(stream, s2c, &pk_ok);
1632        } else {
1633            let mut failure = vec![51];
1634            failure.extend(ssh_name_list(&["publickey"]));
1635            failure.push(0);
1636            let _ = write_encrypted_packet(stream, s2c, &failure);
1637        }
1638        return (None, notes);
1639    }
1640    let signed_request_end = off;
1641    let sig = read_ssh_bytes(payload, &mut off).unwrap_or_default();
1642    let mut challenge = ssh_string(session_id);
1643    challenge.extend_from_slice(&payload[..signed_request_end]);
1644    match verify_publickey_against_authorized(authorized_keys, &pubkey, &challenge, &sig) {
1645        Ok(key_comment_user) => {
1646            notes.push_str("; auth_publickey_verify=ok against authorized_keys");
1647            let _ = write_encrypted_packet(stream, s2c, &[52]); // USERAUTH_SUCCESS
1648            let id = SshAuthIdentity {
1649                request_user,
1650                key_comment_user,
1651                public_blob: pubkey,
1652            };
1653            (Some(id), notes)
1654        }
1655        Err(e) => {
1656            // Offline scaffold note only — must not invent wire auth success.
1657            if let Some(h) = host {
1658                let ch = Sha256::digest(b"arks-ssh-partial-wire-auth-fallback");
1659                let sig_blob = sign_ssh_ed25519(h, &ch);
1660                match verify_publickey_against_authorized(
1661                    authorized_keys,
1662                    &h.public_blob,
1663                    &ch,
1664                    &sig_blob,
1665                ) {
1666                    Ok(_) => notes.push_str(
1667                        "; auth_publickey_verify=wire_sig_fail but authorized_keys path ok offline Partial",
1668                    ),
1669                    Err(_) => notes.push_str(&format!("; auth_publickey_verify=fail ({e})")),
1670                }
1671            } else {
1672                notes.push_str(&format!("; auth_publickey_verify=fail ({e})"));
1673            }
1674            let mut failure = vec![51];
1675            failure.extend(ssh_name_list(&["publickey"]));
1676            failure.push(0);
1677            let _ = write_encrypted_packet(stream, s2c, &failure);
1678            (None, notes)
1679        }
1680    }
1681}
1682
1683/// Attempt peer ECDH + optional host-key sign + NEWKEYS (Partial).
1684#[allow(clippy::too_many_arguments)]
1685fn try_peer_ecdh_and_sign(
1686    stream: &mut TcpStream,
1687    peer_kex: &[String],
1688    host: Option<&HostEd25519>,
1689    our_id: &str,
1690    peer_id: &str,
1691    our_kexinit: &[u8],
1692    peer_kexinit: &[u8],
1693    authorized_keys: &Path,
1694    repo_path: &Path,
1695) -> (SshStage, String) {
1696    let want = peer_kex
1697        .iter()
1698        .any(|n| n == "curve25519-sha256" || n == "curve25519-sha256@libssh.org");
1699    if !want {
1700        return (
1701            SshStage::AlgoSelect,
1702            "ecdh_peer=skipped (no common curve25519-sha256)".into(),
1703        );
1704    }
1705    let payload = match read_ssh_packet(stream, 4096) {
1706        Ok(p) => p,
1707        Err(e)
1708            if e.kind() == std::io::ErrorKind::WouldBlock
1709                || e.kind() == std::io::ErrorKind::TimedOut =>
1710        {
1711            return (SshStage::Ecdh, "ecdh_peer=timeout (no ECDH_INIT)".into());
1712        }
1713        Err(e) => return (SshStage::Ecdh, format!("ecdh_peer=err ({e})")),
1714    };
1715    if payload.is_empty() || payload[0] != 30 {
1716        let mt = payload.first().copied().unwrap_or(0);
1717        return (SshStage::Ecdh, format!("ecdh_peer=unexpected_msg={mt}"));
1718    }
1719    if payload.len() < 5 {
1720        return (SshStage::Ecdh, "ecdh_peer=init_short".into());
1721    }
1722    let qlen = u32::from_be_bytes(payload[1..5].try_into().unwrap_or([0; 4])) as usize;
1723    if qlen != 32 || payload.len() < 5 + qlen {
1724        return (SshStage::Ecdh, format!("ecdh_peer=bad_q_c_len ({qlen})"));
1725    }
1726    let mut q_c = [0u8; 32];
1727    q_c.copy_from_slice(&payload[5..5 + 32]);
1728    let peer_pk = PublicKey::from(q_c);
1729    let secret = StaticSecret::random();
1730    let q_s = PublicKey::from(&secret);
1731    let shared = secret.diffie_hellman(&peer_pk);
1732    if shared.as_bytes().iter().all(|byte| *byte == 0) {
1733        return (
1734            SshStage::Ecdh,
1735            "ecdh_peer=all_zero_shared_secret (RFC 8731 reject)".into(),
1736        );
1737    }
1738    let mut h = Sha256::new();
1739    h.update(b"arks-ssh-partial-peer-ecdh");
1740    h.update(shared.as_bytes());
1741    h.update(q_s.as_bytes());
1742    let digest = h.finalize();
1743    let mut notes = vec![format!(
1744        "ecdh_peer=shared_ok q_s_ready=1 shared_sha256={:02x}{:02x}…",
1745        digest[0], digest[1]
1746    )];
1747
1748    let Some(host) = host else {
1749        notes.push(
1750            "stop=host_key_sign Missing (no loadable ed25519 host key; KEX_ECDH_REPLY withheld)"
1751                .into(),
1752        );
1753        return (SshStage::HostKeySign, notes.join("; "));
1754    };
1755
1756    // RFC 8731 exchange hash:
1757    // string V_C || string V_S || string I_C || string I_S ||
1758    // string K_S || string Q_C || string Q_S || mpint K.
1759    let encoded_k = x25519_shared_as_mpint(shared.as_bytes());
1760    let mut exchange = Vec::new();
1761    exchange.extend(ssh_string(
1762        peer_id.trim_end_matches(['\r', '\n']).as_bytes(),
1763    ));
1764    exchange.extend(ssh_string(our_id.trim_end_matches(['\r', '\n']).as_bytes()));
1765    exchange.extend(ssh_string(peer_kexinit));
1766    exchange.extend(ssh_string(our_kexinit));
1767    exchange.extend(ssh_string(&host.public_blob));
1768    exchange.extend(ssh_string(&q_c));
1769    exchange.extend(ssh_string(q_s.as_bytes()));
1770    exchange.extend_from_slice(&encoded_k);
1771    let exchange_hash = Sha256::digest(&exchange);
1772    let signature = sign_ssh_ed25519(host, &exchange_hash);
1773
1774    let mut reply = Vec::new();
1775    reply.push(31); // SSH_MSG_KEX_ECDH_REPLY
1776    reply.extend(ssh_string(&host.public_blob));
1777    reply.extend(ssh_string(q_s.as_bytes()));
1778    reply.extend(ssh_string(&signature));
1779    if let Err(e) = write_ssh_packet(stream, &reply) {
1780        notes.push(format!("host_key_sign=reply_write_err ({e})"));
1781        return (SshStage::HostKeySign, notes.join("; "));
1782    }
1783    notes.push("host_key_sign=ed25519_KEX_ECDH_REPLY_sent (Partial; not Claimed handshake)".into());
1784
1785    // SSH_MSG_NEWKEYS (cleartext), then switch to OpenSSH ChaCha packets.
1786    if let Err(e) = write_ssh_packet(stream, &[21]) {
1787        notes.push(format!("newkeys=write_err ({e})"));
1788        return (SshStage::NewKeys, notes.join("; "));
1789    }
1790    notes.push("newkeys=sent".into());
1791    match read_ssh_packet(stream, 256) {
1792        Ok(p) if p.first() == Some(&21) => notes.push("newkeys=peer_ok".into()),
1793        Ok(p) => notes.push(format!(
1794            "newkeys=peer_msg={}",
1795            p.first().copied().unwrap_or(0)
1796        )),
1797        Err(e)
1798            if e.kind() == std::io::ErrorKind::WouldBlock
1799                || e.kind() == std::io::ErrorKind::TimedOut =>
1800        {
1801            notes.push("newkeys=peer_timeout".into());
1802        }
1803        Err(e) => notes.push(format!("newkeys=peer_err ({e})")),
1804    }
1805
1806    let strict_kex = peer_kex
1807        .iter()
1808        .any(|name| name == "kex-strict-c-v00@openssh.com");
1809    let initial_sequence = if strict_kex { 0 } else { 3 };
1810    notes.push(format!(
1811        "strict_kex={strict_kex} encrypted_initial_sequence={initial_sequence}"
1812    ));
1813    let (stage, post) = continue_after_newkeys(
1814        stream,
1815        &encoded_k,
1816        &exchange_hash,
1817        initial_sequence,
1818        authorized_keys,
1819        repo_path,
1820        Some(host),
1821    );
1822    notes.push(post);
1823    (stage, notes.join("; "))
1824}
1825
1826struct PeerKexInit {
1827    kex: Vec<String>,
1828    hostkey: Vec<String>,
1829    enc_c2s: Vec<String>,
1830    enc_s2c: Vec<String>,
1831    mac_c2s: Vec<String>,
1832    mac_s2c: Vec<String>,
1833}
1834
1835fn parse_peer_kexinit(payload: &[u8]) -> Option<PeerKexInit> {
1836    if payload.first().copied()? != 20 {
1837        return None;
1838    }
1839    let mut off = 1 + 16; // type + cookie
1840    let kex = read_ssh_name_list(payload, &mut off)?;
1841    let hostkey = read_ssh_name_list(payload, &mut off)?;
1842    let enc_c2s = read_ssh_name_list(payload, &mut off)?;
1843    let enc_s2c = read_ssh_name_list(payload, &mut off)?;
1844    let mac_c2s = read_ssh_name_list(payload, &mut off)?;
1845    let mac_s2c = read_ssh_name_list(payload, &mut off)?;
1846    let _compression_c2s = read_ssh_name_list(payload, &mut off)?;
1847    let _compression_s2c = read_ssh_name_list(payload, &mut off)?;
1848    let _languages_c2s = read_ssh_name_list(payload, &mut off)?;
1849    let _languages_s2c = read_ssh_name_list(payload, &mut off)?;
1850    if off + 5 > payload.len() {
1851        return None;
1852    }
1853    Some(PeerKexInit {
1854        kex,
1855        hostkey,
1856        enc_c2s,
1857        enc_s2c,
1858        mac_c2s,
1859        mac_s2c,
1860    })
1861}
1862
1863fn run_kex_stages(
1864    stream: &mut TcpStream,
1865    host: Option<&HostEd25519>,
1866    our_id: &str,
1867    peer_id: &str,
1868    authorized_keys: &Path,
1869    repo_path: &Path,
1870) -> (SshStage, String) {
1871    let mut notes = Vec::new();
1872    let advertise = host.is_some();
1873    let our_kexinit = build_kexinit_payload(advertise);
1874
1875    if let Err(e) = write_ssh_packet(stream, &our_kexinit) {
1876        return (SshStage::KexInit, format!("kexinit=write_err ({e})"));
1877    }
1878    let peer_payload = match read_ssh_packet(stream, 16_384) {
1879        Ok(p) => p,
1880        Err(e)
1881            if e.kind() == std::io::ErrorKind::WouldBlock
1882                || e.kind() == std::io::ErrorKind::TimedOut =>
1883        {
1884            notes.push("kexinit=sent peer=(timeout)".into());
1885            match curve25519_ecdh_selfcheck() {
1886                Ok(s) => notes.push(s),
1887                Err(e) => notes.push(format!("ecdh_selfcheck=fail ({e})")),
1888            }
1889            notes.push("stop=host_key_sign Missing (no peer KEXINIT)".into());
1890            return (SshStage::HostKeySign, notes.join("; "));
1891        }
1892        Err(e) => {
1893            return (SshStage::KexInit, format!("kexinit=sent peer_err ({e})"));
1894        }
1895    };
1896    notes.push(format!(
1897        "kexinit=sent advertise_ed25519={advertise} peer_payload_len={}",
1898        peer_payload.len()
1899    ));
1900
1901    let peer = match parse_peer_kexinit(&peer_payload) {
1902        Some(v) => v,
1903        None => {
1904            notes.push("algo_select=peer_kexinit_parse_fail".into());
1905            match curve25519_ecdh_selfcheck() {
1906                Ok(s) => notes.push(s),
1907                Err(e) => notes.push(format!("ecdh_selfcheck=fail ({e})")),
1908            }
1909            notes.push("stop=host_key_sign Missing".into());
1910            return (SshStage::HostKeySign, notes.join("; "));
1911        }
1912    };
1913    let kex_ok = peer
1914        .kex
1915        .iter()
1916        .any(|n| n == "curve25519-sha256" || n == "curve25519-sha256@libssh.org");
1917    let hostkey_ok = if advertise {
1918        peer.hostkey.iter().any(|n| n == "ssh-ed25519")
1919    } else {
1920        peer.hostkey
1921            .iter()
1922            .any(|n| n == "arks-partial-missing-hostkey-sign")
1923    };
1924    let cipher_ok = peer
1925        .enc_c2s
1926        .iter()
1927        .any(|n| n == "chacha20-poly1305@openssh.com")
1928        && peer
1929            .enc_s2c
1930            .iter()
1931            .any(|n| n == "chacha20-poly1305@openssh.com");
1932    let mac_ok = peer.mac_c2s.iter().any(|n| n == "hmac-sha2-256")
1933        && peer.mac_s2c.iter().any(|n| n == "hmac-sha2-256");
1934    notes.push(format!(
1935        "algo_select=kex_curve25519={kex_ok} hostkey_common={hostkey_ok} \
1936         openssh_chacha={cipher_ok} mac_name_common={mac_ok} peer_kex_n={} peer_hostkey_n={}",
1937        peer.kex.len(),
1938        peer.hostkey.len()
1939    ));
1940    if !kex_ok || !cipher_ok || !mac_ok {
1941        notes.push("stop=algo_select (no complete supported algorithm set)".into());
1942        return (SshStage::AlgoSelect, notes.join("; "));
1943    }
1944    if advertise && !hostkey_ok {
1945        notes.push(
1946            "note: peer did not offer ssh-ed25519 — still attempt ECDH; sign may be unused".into(),
1947        );
1948    }
1949
1950    match curve25519_ecdh_selfcheck() {
1951        Ok(s) => notes.push(s),
1952        Err(e) => {
1953            notes.push(format!("ecdh_selfcheck=fail ({e})"));
1954            return (SshStage::Ecdh, notes.join("; "));
1955        }
1956    }
1957
1958    let (stage, ecdh_notes) = try_peer_ecdh_and_sign(
1959        stream,
1960        &peer.kex,
1961        host,
1962        our_id,
1963        peer_id,
1964        &our_kexinit,
1965        &peer_payload,
1966        authorized_keys,
1967        repo_path,
1968    );
1969    notes.push(ecdh_notes);
1970
1971    // If ECDH stopped before NEWKEYS, still record offline auth + pack dispatch Partial.
1972    if !matches!(
1973        stage,
1974        SshStage::EncryptedTransport | SshStage::AuthPublickey | SshStage::ChannelSession
1975    ) {
1976        notes.push(publickey_verify_scaffold(authorized_keys, host));
1977        notes.push(channel_git_hookup_scaffold(repo_path));
1978    }
1979    notes.push(format!("reached_stage={}", stage.as_str()));
1980    (stage, notes.join("; "))
1981}
1982
1983/// Run an in-process SSH listener (durable accept per SoT §17(c)).
1984///
1985/// Advances structured KEX / sign / NEWKEYS / auth / channel stages per
1986/// connection. Stays up until `stop` is set. Bind failure fail-closed.
1987///
1988/// Callers MUST NOT silent-degrade to HTTP-only when SSH was left enabled.
1989pub fn serve_ssh_listener(opts: ServeSshOptions, stop: Arc<AtomicBool>) -> Result<(), ServerError> {
1990    let listener = TcpListener::bind(opts.listen)?;
1991    listener.set_nonblocking(true)?;
1992    serve_ssh_on_listener(listener, opts, stop)
1993}
1994
1995fn serve_ssh_on_listener(
1996    mut listener: TcpListener,
1997    opts: ServeSshOptions,
1998    stop: Arc<AtomicBool>,
1999) -> Result<(), ServerError> {
2000    let host_st = path_status(&opts.host_key);
2001    let auth_st = path_status(&opts.authorized_keys);
2002    let host_fmt = probe_host_key_format(&opts.host_key);
2003    let auth_probe = probe_authorized_keys(&opts.authorized_keys);
2004    let repo_st = if opts.path.exists() {
2005        "present"
2006    } else {
2007        "missing"
2008    };
2009    let host_key = match load_host_ed25519(&opts.host_key) {
2010        Ok(h) => Some(h),
2011        Err(e) => {
2012            // Keep going — Partial without sign when key missing/unloadable.
2013            let _ = e;
2014            None
2015        }
2016    };
2017    let host_load = if host_key.is_some() {
2018        "ed25519_unencrypted_ok"
2019    } else {
2020        "unloadable_or_absent"
2021    };
2022
2023    let mut current = listener.local_addr().unwrap_or(opts.listen);
2024    let our_id = "SSH-2.0-arks";
2025    eprintln!(
2026        "arks serve SSH durable listen on {current}; \
2027         host_key={hk} ({host_st}; format={host_fmt}; load={host_load}); \
2028         authorized_keys={ak} ({auth_st}; {auth_probe}); path={path} ({repo_st})",
2029        hk = opts.host_key.display(),
2030        ak = opts.authorized_keys.display(),
2031        path = opts.path.display(),
2032    );
2033
2034    let host_key = Arc::new(host_key);
2035    let auth_keys = opts.authorized_keys.clone();
2036    let repo_path = opts.path.clone();
2037    let host_load = Arc::new(host_load.to_string());
2038    let session_counter = Arc::new(std::sync::atomic::AtomicU64::new(0));
2039    // Bounded dual-bind drain (mirror HTTP B7 Claimed; research:root/20261111090827).
2040    let mut draining: Vec<(TcpListener, SocketAddr, Instant)> = Vec::new();
2041    while !stop.load(Ordering::SeqCst) {
2042        if let Some(slot) = &opts.rebind_desired {
2043            if let Ok(mut g) = slot.lock() {
2044                if let Some(new_addr) = g.take() {
2045                    if new_addr != current {
2046                        match TcpListener::bind(new_addr) {
2047                            Ok(l) => {
2048                                if let Err(e) = l.set_nonblocking(true) {
2049                                    eprintln!(
2050                                        "arks serve SSH: live rebind bind ok but \
2051                                         nonblocking fail ({e}); keeping {current}"
2052                                    );
2053                                    *g = Some(new_addr);
2054                                } else {
2055                                    eprintln!(
2056                                        "arks serve SSH: live rebind dual-bind {current} → {new_addr}; \
2057                                         prior listener draining for 5s"
2058                                    );
2059                                    let old = std::mem::replace(&mut listener, l);
2060                                    draining.push((
2061                                        old,
2062                                        current,
2063                                        Instant::now() + Duration::from_secs(5),
2064                                    ));
2065                                    current = new_addr;
2066                                }
2067                            }
2068                            Err(e) => {
2069                                eprintln!(
2070                                    "arks serve SSH: live rebind fail {current} → \
2071                                     {new_addr} ({e}); keeping prior listen"
2072                                );
2073                            }
2074                        }
2075                    }
2076                }
2077            }
2078        }
2079        draining.retain(|(_, old_addr, deadline)| {
2080            if Instant::now() < *deadline {
2081                true
2082            } else {
2083                eprintln!("arks serve SSH: rebind drain complete; closing {old_addr}");
2084                false
2085            }
2086        });
2087
2088        let spawn_session = |stream: TcpStream, peer: SocketAddr| {
2089            let n = session_counter.fetch_add(1, Ordering::SeqCst) + 1;
2090            let host_key = Arc::clone(&host_key);
2091            let auth_keys = auth_keys.clone();
2092            let repo_path = repo_path.clone();
2093            let host_load = Arc::clone(&host_load);
2094            let our_id = our_id.to_string();
2095            thread::spawn(move || {
2096                handle_ssh_session(
2097                    stream,
2098                    peer,
2099                    n,
2100                    &our_id,
2101                    host_key.as_ref().as_ref(),
2102                    &auth_keys,
2103                    &repo_path,
2104                    host_load.as_str(),
2105                );
2106            });
2107        };
2108
2109        match listener.accept() {
2110            Ok((stream, peer)) => spawn_session(stream, peer),
2111            Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
2112                thread::sleep(Duration::from_millis(20));
2113            }
2114            Err(e) => {
2115                return Err(ServerError::Msg(format!(
2116                    "arks serve SSH durable accept err on {current}: {e}"
2117                )));
2118            }
2119        }
2120        for (old_listener, _, _) in &draining {
2121            match old_listener.accept() {
2122                Ok((stream, peer)) => spawn_session(stream, peer),
2123                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {}
2124                Err(e) => eprintln!("arks serve SSH: draining listener accept error: {e}"),
2125            }
2126        }
2127    }
2128
2129    eprintln!(
2130        "arks serve SSH durable listen stopped on {current} \
2131         (sessions={}; ops SSHD + upload-pack/receive-pack still valid)",
2132        session_counter.load(Ordering::SeqCst)
2133    );
2134    Ok(())
2135}
2136
2137#[allow(clippy::too_many_arguments)]
2138fn handle_ssh_session(
2139    mut stream: TcpStream,
2140    peer: SocketAddr,
2141    sessions: u64,
2142    our_id: &str,
2143    host_key: Option<&HostEd25519>,
2144    authorized_keys: &Path,
2145    path: &Path,
2146    host_load: &str,
2147) {
2148    let _ = stream.set_nonblocking(false);
2149    let _ = stream.set_nodelay(true);
2150    // Longer read window so held peers can overlap a dual-bind drain (IW-B7-SSH).
2151    let _ = stream.set_read_timeout(Some(Duration::from_secs(8)));
2152    let _ = stream.set_write_timeout(Some(Duration::from_secs(8)));
2153    let ours = format!("{our_id}\r\n");
2154    let _ = stream.write_all(ours.as_bytes());
2155    let _ = stream.flush();
2156    let peer_id = read_ssh_identification(&mut stream)
2157        .unwrap_or_default()
2158        .chars()
2159        .take(255)
2160        .collect::<String>();
2161    let id_part = if peer_id.is_empty() {
2162        format!("id_exchange=no_peer_id peer={peer} peer_id=(empty/timeout)")
2163    } else {
2164        format!("id_exchange=ok peer={peer} peer_id={peer_id}")
2165    };
2166    let (stage, kex_part) = if peer_id.is_empty() {
2167        match curve25519_ecdh_selfcheck() {
2168            Ok(s) => {
2169                let auth = publickey_verify_scaffold(authorized_keys, host_key);
2170                let chan = channel_git_hookup_scaffold(path);
2171                (
2172                    SshStage::HostKeySign,
2173                    format!(
2174                        "kex=skipped_no_peer_id; {s}; host_load={host_load}; {auth}; {chan}; \
2175                         stop=host_key_sign/wire Missing without peer"
2176                    ),
2177                )
2178            }
2179            Err(e) => (
2180                SshStage::Ecdh,
2181                format!("kex=skipped_no_peer_id; ecdh_selfcheck=fail ({e})"),
2182            ),
2183        }
2184    } else {
2185        run_kex_stages(
2186            &mut stream,
2187            host_key,
2188            our_id,
2189            &peer_id,
2190            authorized_keys,
2191            path,
2192        )
2193    };
2194    // Flush then half-close write so in-flight CHANNEL_DATA is not RST'd.
2195    let _ = stream.flush();
2196    let _ = stream.shutdown(Shutdown::Write);
2197    eprintln!(
2198        "arks serve SSH session#{sessions} reached_stage={} \
2199         ({id_part}; {kex_part})",
2200        stage.as_str()
2201    );
2202}
2203
2204type LoopbackSsh = (
2205    SocketAddr,
2206    Arc<AtomicBool>,
2207    thread::JoinHandle<Result<(), ServerError>>,
2208);
2209
2210/// Spawn durable SSH listener on a background thread (cohost with HTTP/forge).
2211///
2212/// Binds the socket synchronously before spawning so bind failures surface
2213/// immediately and the kernel listen queue is ready before returning.
2214pub fn spawn_ssh_listener(
2215    opts: ServeSshOptions,
2216) -> Result<(Arc<AtomicBool>, ListenerThread), ServerError> {
2217    let listener = TcpListener::bind(opts.listen)?;
2218    listener.set_nonblocking(true)?;
2219    let stop = Arc::new(AtomicBool::new(false));
2220    let stop2 = stop.clone();
2221    let handle = thread::spawn(move || serve_ssh_on_listener(listener, opts, stop2));
2222    Ok((stop, handle))
2223}
2224
2225/// Ephemeral loopback SSH listener for `arks serve ssh-smoke --git-pack` and tests.
2226///
2227/// Keeps the bound `TcpListener` alive and passes it directly into the serving
2228/// thread (no port-drop TOCTOU window or blind sleep).
2229pub fn spawn_loopback_ssh(opts: ServeSshOptions) -> Result<LoopbackSsh, ServerError> {
2230    let listener = TcpListener::bind("127.0.0.1:0")?;
2231    let addr = listener.local_addr()?;
2232    listener.set_nonblocking(true)?;
2233    let mut opts = opts;
2234    opts.listen = addr;
2235    let stop = Arc::new(AtomicBool::new(false));
2236    let stop2 = stop.clone();
2237    let handle = thread::spawn(move || serve_ssh_on_listener(listener, opts, stop2));
2238    Ok((addr, stop, handle))
2239}
2240
2241#[cfg(test)]
2242mod tests {
2243    use super::*;
2244    use ed25519_dalek::SigningKey;
2245
2246    #[test]
2247    fn parse_git_exec_services() {
2248        assert_eq!(
2249            parse_git_exec_service("git-upload-pack '/tmp/r.git'"),
2250            Some("git-upload-pack")
2251        );
2252        assert_eq!(
2253            parse_git_exec_service("git-receive-pack '/tmp/r.git'"),
2254            Some("git-receive-pack")
2255        );
2256        assert_eq!(parse_git_exec_service("bash"), None);
2257    }
2258
2259    #[test]
2260    fn chacha_aead_roundtrip_partial() {
2261        let shared = x25519_shared_as_mpint(&[7u8; 32]);
2262        let h = Sha256::digest(b"exchange-hash-partial");
2263        let note = encrypted_transport_selfcheck(&shared, &h);
2264        assert!(note.contains("selfcheck=ok"), "{note}");
2265    }
2266
2267    #[test]
2268    fn rfc8731_shared_secret_mpint_encoding() {
2269        let mut high_bit = [0u8; 32];
2270        high_bit[0] = 0x80;
2271        let encoded = x25519_shared_as_mpint(&high_bit);
2272        assert_eq!(&encoded[..4], &33u32.to_be_bytes());
2273        assert_eq!(encoded[4], 0);
2274        assert_eq!(encoded[5], 0x80);
2275
2276        let mut leading_zero = [0u8; 32];
2277        leading_zero[1] = 1;
2278        let encoded = x25519_shared_as_mpint(&leading_zero);
2279        assert_eq!(&encoded[..4], &31u32.to_be_bytes());
2280        assert_eq!(encoded[4], 1);
2281    }
2282
2283    #[test]
2284    fn authorized_keys_verify_partial() {
2285        let dir = tempfile::tempdir().unwrap();
2286        let seed = [9u8; 32];
2287        let signing = SigningKey::from_bytes(&seed);
2288        let vk = signing.verifying_key();
2289        let blob = build_ssh_ed25519_public_blob(vk.as_bytes());
2290        let b64 = base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &blob);
2291        let ak = dir.path().join("authorized_keys");
2292        std::fs::write(&ak, format!("ssh-ed25519 {b64} test@arks\n")).unwrap();
2293        let challenge = b"challenge-partial";
2294        let sig = signing.sign(challenge);
2295        let mut sig_blob = Vec::new();
2296        sig_blob.extend(ssh_string(b"ssh-ed25519"));
2297        sig_blob.extend(ssh_string(&sig.to_bytes()));
2298        verify_publickey_against_authorized(&ak, &blob, challenge, &sig_blob).unwrap();
2299    }
2300
2301    #[test]
2302    fn ssh_receive_pack_rejects_archived_repo() {
2303        let dir = tempfile::tempdir().unwrap();
2304        let repo_path = dir.path().join("arch.git");
2305        std::fs::create_dir_all(repo_path.join("objects")).unwrap();
2306        std::fs::create_dir_all(repo_path.join("refs").join("heads")).unwrap();
2307        std::fs::write(repo_path.join("HEAD"), "ref: refs/heads/main\n").unwrap();
2308        std::fs::write(
2309            repo_path.join("config"),
2310            "[core]\n\trepositoryformatversion = 0\n\tbare = true\n",
2311        )
2312        .unwrap();
2313        let mut store = crate::web_ui::store::ForgeStore::load(&repo_path);
2314        store.archived = true;
2315        store.save(&repo_path).unwrap();
2316        let err = dispatch_git_exec_to_pack(&repo_path, "git-receive-pack '.'").unwrap_err();
2317        assert!(
2318            err.contains("archived"),
2319            "SSH receive-pack must reject archived repo: {err}"
2320        );
2321    }
2322
2323    #[test]
2324    fn ssh_identity_resolution_and_rbac_with_pusher_ssh_user() {
2325        let dir = tempfile::tempdir().unwrap();
2326        let alice_sk = SigningKey::from_bytes(&[1u8; 32]);
2327        let bob_sk = SigningKey::from_bytes(&[2u8; 32]);
2328        let carol_sk = SigningKey::from_bytes(&[3u8; 32]);
2329
2330        let alice_blob = build_ssh_ed25519_public_blob(alice_sk.verifying_key().as_bytes());
2331        let bob_blob = build_ssh_ed25519_public_blob(bob_sk.verifying_key().as_bytes());
2332        let carol_blob = build_ssh_ed25519_public_blob(carol_sk.verifying_key().as_bytes());
2333
2334        let alice_b64 =
2335            base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &alice_blob);
2336        let bob_b64 = base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &bob_blob);
2337        let carol_b64 =
2338            base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &carol_blob);
2339
2340        let ak = dir.path().join("authorized_keys");
2341        std::fs::write(
2342            &ak,
2343            format!(
2344                "# alice (laptop)\nssh-ed25519 {alice_b64} alice@example.invalid\n\
2345                 # bob (reader-key)\nssh-ed25519 {bob_b64} bob@example.invalid\n\
2346                 # carol (collab-key)\nssh-ed25519 {carol_b64} carol@example.invalid\n"
2347            ),
2348        )
2349        .unwrap();
2350
2351        let challenge = b"ssh-userauth-challenge";
2352        let alice_sig = sign_ssh_ed25519(
2353            &HostEd25519 {
2354                signing: alice_sk,
2355                public_blob: alice_blob.clone(),
2356            },
2357            challenge,
2358        );
2359        let comment_user =
2360            verify_publickey_against_authorized(&ak, &alice_blob, challenge, &alice_sig).unwrap();
2361        assert_eq!(comment_user.as_deref(), Some("alice"));
2362
2363        let mut store = ForgeStore {
2364            visibility: "private".into(),
2365            ..Default::default()
2366        };
2367        store.users.push(crate::web_ui::store::UserAccount {
2368            username: "alice".into(),
2369            password_hash: "x".into(),
2370            role: "admin".into(),
2371            ssh_keys: vec![crate::web_ui::store::SshKeyRecord {
2372                title: "laptop".into(),
2373                public_key: format!("ssh-ed25519 {alice_b64} alice@example.invalid"),
2374                added_at: 1,
2375            }],
2376            created_at: 1,
2377            totp_secret_b32: None,
2378            recovery_codes: Vec::new(),
2379        });
2380        store.users.push(crate::web_ui::store::UserAccount {
2381            username: "bob".into(),
2382            password_hash: "x".into(),
2383            role: "reader".into(),
2384            ssh_keys: vec![crate::web_ui::store::SshKeyRecord {
2385                title: "reader-key".into(),
2386                public_key: format!("ssh-ed25519 {bob_b64} bob@example.invalid"),
2387                added_at: 1,
2388            }],
2389            created_at: 1,
2390            totp_secret_b32: None,
2391            recovery_codes: Vec::new(),
2392        });
2393        store.users.push(crate::web_ui::store::UserAccount {
2394            username: "carol".into(),
2395            password_hash: "x".into(),
2396            role: "reader".into(),
2397            ssh_keys: vec![crate::web_ui::store::SshKeyRecord {
2398                title: "collab-key".into(),
2399                public_key: format!("ssh-ed25519 {carol_b64} carol@example.invalid"),
2400                added_at: 1,
2401            }],
2402            created_at: 1,
2403            totp_secret_b32: None,
2404            recovery_codes: Vec::new(),
2405        });
2406        store.collaborators.push("carol".into());
2407
2408        // Connecting as `git@host` with alice's key resolves to `alice` and binds Pusher::ssh_user.
2409        let alice_id = SshAuthIdentity {
2410            request_user: "git".into(),
2411            key_comment_user: Some("alice".into()),
2412            public_blob: alice_blob,
2413        };
2414        let resolved_alice = resolve_ssh_identity(&store, &alice_id);
2415        assert_eq!(resolved_alice.as_deref(), Some("alice"));
2416        let pusher = Pusher::ssh_user(resolved_alice.as_deref().unwrap());
2417        assert_eq!(pusher.transport, "ssh");
2418        assert_eq!(pusher.verified_user.as_deref(), Some("alice"));
2419        assert!(check_ssh_repo_rbac(&store, resolved_alice.as_deref(), false).is_ok());
2420        assert!(check_ssh_repo_rbac(&store, resolved_alice.as_deref(), true).is_ok());
2421
2422        // Spoofing `alice@host` with bob's key MUST resolve to `bob` (never `alice`) and fail RBAC.
2423        let spoof_id = SshAuthIdentity {
2424            request_user: "alice".into(),
2425            key_comment_user: Some("bob".into()),
2426            public_blob: bob_blob,
2427        };
2428        let resolved_bob = resolve_ssh_identity(&store, &spoof_id);
2429        assert_eq!(resolved_bob.as_deref(), Some("bob"));
2430        assert!(check_ssh_repo_rbac(&store, resolved_bob.as_deref(), false).is_err());
2431        assert!(check_ssh_repo_rbac(&store, resolved_bob.as_deref(), true).is_err());
2432
2433        // Explicit `"reader"` collaborator (`carol`) passes private read (`upload-pack`)
2434        // but is denied push (`receive-pack`) to match HTTP parity.
2435        let carol_id = SshAuthIdentity {
2436            request_user: "git".into(),
2437            key_comment_user: Some("carol".into()),
2438            public_blob: carol_blob,
2439        };
2440        let resolved_carol = resolve_ssh_identity(&store, &carol_id);
2441        assert_eq!(resolved_carol.as_deref(), Some("carol"));
2442        assert!(check_ssh_repo_rbac(&store, resolved_carol.as_deref(), false).is_ok());
2443        assert!(check_ssh_repo_rbac(&store, resolved_carol.as_deref(), true).is_err());
2444    }
2445
2446    #[test]
2447    fn ssh_channel_pipe_bidirectional_window_adjust_over_2mib() {
2448        let key_c2s = [0x11u8; 64];
2449        let key_s2c = [0x22u8; 64];
2450        let payload_len = (2 * 1024 * 1024) + (512 * 1024); // 2.5 MiB (> 2 MiB window)
2451
2452        // Part 1: >2 MiB peer -> server transfer (push) must trigger WINDOW_ADJUST back to peer.
2453        {
2454            let listener = TcpListener::bind("127.0.0.1:0").unwrap();
2455            let addr = listener.local_addr().unwrap();
2456            let expected: Vec<u8> = (0..payload_len).map(|i| (i % 251) as u8).collect();
2457            let client_data = expected.clone();
2458
2459            let client = thread::spawn(move || -> u64 {
2460                let mut sock = TcpStream::connect(addr).unwrap();
2461                sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
2462                sock.set_write_timeout(Some(Duration::from_secs(5)))
2463                    .unwrap();
2464                let mut c2s = OpenSshChaCha::new(&key_c2s, 0).unwrap();
2465                let mut s2c = OpenSshChaCha::new(&key_s2c, 0).unwrap();
2466                let mut remote_window: u32 = SSH_LOCAL_INITIAL_WINDOW;
2467                let mut total_adjust_received: u64 = 0;
2468
2469                for chunk in client_data.chunks(16_384) {
2470                    while (remote_window as usize) < chunk.len() {
2471                        let msg = read_encrypted_packet(&mut sock, &mut s2c, 65_536).unwrap();
2472                        assert_eq!(msg.first().copied(), Some(93), "expected WINDOW_ADJUST");
2473                        let mut off = 1usize;
2474                        let _chan = read_u32(&msg, &mut off).unwrap();
2475                        let add = read_u32(&msg, &mut off).unwrap();
2476                        remote_window = remote_window.saturating_add(add);
2477                        total_adjust_received += u64::from(add);
2478                    }
2479                    let mut pkt = vec![94]; // CHANNEL_DATA
2480                    pkt.extend_from_slice(&0u32.to_be_bytes());
2481                    pkt.extend(ssh_string(chunk));
2482                    write_encrypted_packet(&mut sock, &mut c2s, &pkt).unwrap();
2483                    remote_window -= chunk.len() as u32;
2484                }
2485                let mut eof = vec![96];
2486                eof.extend_from_slice(&0u32.to_be_bytes());
2487                write_encrypted_packet(&mut sock, &mut c2s, &eof).unwrap();
2488                let _ = sock.shutdown(std::net::Shutdown::Write);
2489                while let Ok(msg) = read_encrypted_packet(&mut sock, &mut s2c, 65_536) {
2490                    if msg.first().copied() == Some(93) {
2491                        let mut off = 1usize;
2492                        let _chan = read_u32(&msg, &mut off).unwrap();
2493                        let add = read_u32(&msg, &mut off).unwrap();
2494                        total_adjust_received += u64::from(add);
2495                    }
2496                }
2497                total_adjust_received
2498            });
2499
2500            let (mut srv_sock, _) = listener.accept().unwrap();
2501            srv_sock
2502                .set_read_timeout(Some(Duration::from_secs(5)))
2503                .unwrap();
2504            srv_sock
2505                .set_write_timeout(Some(Duration::from_secs(5)))
2506                .unwrap();
2507            let mut c2s = OpenSshChaCha::new(&key_c2s, 0).unwrap();
2508            let mut s2c = OpenSshChaCha::new(&key_s2c, 0).unwrap();
2509            let mut pipe = SshChannelPipe {
2510                stream: &mut srv_sock,
2511                c2s: &mut c2s,
2512                s2c: &mut s2c,
2513                peer_channel: 7,
2514                max_data: 16_384,
2515                local_window_remaining: SSH_LOCAL_INITIAL_WINDOW,
2516                local_window_consumed: 0,
2517                peer_window_remaining: 65_536,
2518                inbox: VecDeque::new(),
2519                eof: false,
2520                closed: false,
2521            };
2522            let mut received = Vec::with_capacity(payload_len);
2523            pipe.read_to_end(&mut received).unwrap();
2524            assert_eq!(received.len(), expected.len());
2525            assert_eq!(received, expected);
2526            let total_adjust = client.join().unwrap();
2527            assert!(
2528                total_adjust >= 512 * 1024,
2529                "server must send WINDOW_ADJUST during >2 MiB push (got {total_adjust})"
2530            );
2531        }
2532
2533        // Part 2: >2 MiB server -> peer transfer (clone/fetch) with small 128 KiB peer initial
2534        // window must wait for peer WINDOW_ADJUST and preserve interleaved CHANNEL_DATA in inbox.
2535        {
2536            let listener = TcpListener::bind("127.0.0.1:0").unwrap();
2537            let addr = listener.local_addr().unwrap();
2538            let expected: Vec<u8> = (0..payload_len).map(|i| ((i * 7) % 251) as u8).collect();
2539            let initial_peer_window: u32 = 128 * 1024;
2540
2541            let client = thread::spawn(move || -> Vec<u8> {
2542                let mut sock = TcpStream::connect(addr).unwrap();
2543                sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
2544                sock.set_write_timeout(Some(Duration::from_secs(5)))
2545                    .unwrap();
2546                let mut c2s = OpenSshChaCha::new(&key_c2s, 0).unwrap();
2547                let mut s2c = OpenSshChaCha::new(&key_s2c, 0).unwrap();
2548                let mut got = Vec::with_capacity(payload_len);
2549                let mut remaining_window: u32 = initial_peer_window;
2550                let mut sent_interleaved_data = false;
2551
2552                while got.len() < payload_len {
2553                    let msg = read_encrypted_packet(&mut sock, &mut s2c, 65_536).unwrap();
2554                    assert_eq!(msg.first().copied(), Some(94), "expected CHANNEL_DATA");
2555                    let mut off = 1usize;
2556                    let _chan = read_u32(&msg, &mut off).unwrap();
2557                    let data = read_ssh_bytes(&msg, &mut off).unwrap();
2558                    assert!(
2559                        (data.len() as u32) <= remaining_window,
2560                        "server violated peer RFC 4254 window: sent {} with {} remaining",
2561                        data.len(),
2562                        remaining_window
2563                    );
2564                    remaining_window -= data.len() as u32;
2565                    got.extend_from_slice(&data);
2566
2567                    if remaining_window == 0 && got.len() < payload_len {
2568                        if !sent_interleaved_data {
2569                            let mut inter = vec![94]; // interleaved CHANNEL_DATA while server blocks
2570                            inter.extend_from_slice(&0u32.to_be_bytes());
2571                            inter.extend(ssh_string(b"interleaved-ping"));
2572                            write_encrypted_packet(&mut sock, &mut c2s, &inter).unwrap();
2573                            sent_interleaved_data = true;
2574                        }
2575                        let refill: u32 = 256 * 1024;
2576                        let mut adj = vec![93]; // WINDOW_ADJUST
2577                        adj.extend_from_slice(&0u32.to_be_bytes());
2578                        adj.extend_from_slice(&refill.to_be_bytes());
2579                        write_encrypted_packet(&mut sock, &mut c2s, &adj).unwrap();
2580                        remaining_window += refill;
2581                    }
2582                }
2583                got
2584            });
2585
2586            let (mut srv_sock, _) = listener.accept().unwrap();
2587            srv_sock
2588                .set_read_timeout(Some(Duration::from_secs(5)))
2589                .unwrap();
2590            srv_sock
2591                .set_write_timeout(Some(Duration::from_secs(5)))
2592                .unwrap();
2593            let mut c2s = OpenSshChaCha::new(&key_c2s, 0).unwrap();
2594            let mut s2c = OpenSshChaCha::new(&key_s2c, 0).unwrap();
2595            let mut pipe = SshChannelPipe {
2596                stream: &mut srv_sock,
2597                c2s: &mut c2s,
2598                s2c: &mut s2c,
2599                peer_channel: 7,
2600                max_data: 16_384,
2601                local_window_remaining: SSH_LOCAL_INITIAL_WINDOW,
2602                local_window_consumed: 0,
2603                peer_window_remaining: initial_peer_window,
2604                inbox: VecDeque::new(),
2605                eof: false,
2606                closed: false,
2607            };
2608            pipe.write_all(&expected).unwrap();
2609            pipe.flush().unwrap();
2610
2611            let mut buffered = [0u8; 32];
2612            let n = pipe.read(&mut buffered).unwrap();
2613            assert_eq!(&buffered[..n], b"interleaved-ping");
2614
2615            let client_got = client.join().unwrap();
2616            assert_eq!(client_got.len(), expected.len());
2617            assert_eq!(client_got, expected);
2618        }
2619    }
2620
2621    #[test]
2622    fn open_ssh_repo_multi_repo_hardening() {
2623        let dir = tempfile::tempdir().unwrap();
2624        let root = dir.path().join("repos");
2625        let outside = dir.path().join("secret.git");
2626        std::fs::create_dir_all(&root).unwrap();
2627
2628        for repo_dir in [
2629            root.join("alpha.git"),
2630            root.join("beta"),
2631            root.join("gamma").join(".git"),
2632            outside.clone(),
2633        ] {
2634            std::fs::create_dir_all(repo_dir.join("objects")).unwrap();
2635            std::fs::create_dir_all(repo_dir.join("refs/heads")).unwrap();
2636            std::fs::write(repo_dir.join("HEAD"), "ref: refs/heads/main\n").unwrap();
2637        }
2638
2639        assert!(open_ssh_repo(&root, "git-upload-pack '/alpha.git'").is_ok());
2640        assert!(open_ssh_repo(&root, "git-upload-pack '/alpha'").is_ok());
2641        assert!(open_ssh_repo(&root, "git-upload-pack '/beta'").is_ok());
2642        assert!(open_ssh_repo(&root, "git-upload-pack '/gamma'").is_ok());
2643
2644        for bad in [
2645            "git-upload-pack '/../secret.git'",
2646            "git-upload-pack '/alpha/../../secret.git'",
2647            "git-upload-pack '/alpha\0.git'",
2648            "git-upload-pack '/.arks-global-auth'",
2649            "git-upload-pack '/.git'",
2650            "git-upload-pack '/..\\secret.git'",
2651            "git-upload-pack '.'",
2652        ] {
2653            assert!(
2654                open_ssh_repo(&root, bad).is_err(),
2655                "must reject traversal/invalid ssh path: {bad}"
2656            );
2657        }
2658
2659        #[cfg(unix)]
2660        {
2661            let link = root.join("escape.git");
2662            std::os::unix::fs::symlink(&outside, &link).unwrap();
2663            assert!(
2664                open_ssh_repo(&root, "git-upload-pack '/escape.git'").is_err(),
2665                "must reject symlink escaping multi-repo root"
2666            );
2667        }
2668    }
2669
2670    #[test]
2671    fn ssh_rbac_corrupt_store_fails_closed() {
2672        let corrupt_store = ForgeStore {
2673            corrupt: true,
2674            ..Default::default()
2675        };
2676        let auth = SshAuthIdentity {
2677            request_user: "alice".into(),
2678            key_comment_user: Some("alice".into()),
2679            public_blob: Vec::new(),
2680        };
2681        assert_eq!(resolve_ssh_identity(&corrupt_store, &auth), None);
2682        let read_err = check_ssh_repo_rbac(&corrupt_store, Some("alice"), false).unwrap_err();
2683        assert!(read_err.contains("corrupted"), "{read_err}");
2684        let write_err = check_ssh_repo_rbac(&corrupt_store, Some("alice"), true).unwrap_err();
2685        assert!(write_err.contains("corrupted"), "{write_err}");
2686    }
2687
2688    #[test]
2689    fn ssh_identity_rejects_keyless_admin_request_user_spoofing() {
2690        let attacker_sk = SigningKey::from_bytes(&[42u8; 32]);
2691        let attacker_blob = build_ssh_ed25519_public_blob(attacker_sk.verifying_key().as_bytes());
2692
2693        let mut store = ForgeStore {
2694            visibility: "private".into(),
2695            ..Default::default()
2696        };
2697        // Keyless admin account (`ssh_keys` is empty).
2698        store.users.push(crate::web_ui::store::UserAccount {
2699            username: "admin".into(),
2700            password_hash: "x".into(),
2701            role: "admin".into(),
2702            ssh_keys: Vec::new(),
2703            created_at: 1,
2704            totp_secret_b32: None,
2705            recovery_codes: Vec::new(),
2706        });
2707
2708        // Unannotated key claiming `request_user: "admin"` MUST NOT bind to keyless admin.
2709        let spoof = SshAuthIdentity {
2710            request_user: "admin".into(),
2711            key_comment_user: None,
2712            public_blob: attacker_blob.clone(),
2713        };
2714        assert_eq!(resolve_ssh_identity(&store, &spoof), None);
2715        assert!(check_ssh_repo_rbac(&store, None, false).is_err());
2716        assert!(check_ssh_repo_rbac(&store, None, true).is_err());
2717
2718        // Explicit `# admin (ops)` annotation in `authorized_keys` remains trusted.
2719        let annotated = SshAuthIdentity {
2720            request_user: "git".into(),
2721            key_comment_user: Some("admin".into()),
2722            public_blob: attacker_blob,
2723        };
2724        assert_eq!(
2725            resolve_ssh_identity(&store, &annotated).as_deref(),
2726            Some("admin")
2727        );
2728        assert!(check_ssh_repo_rbac(&store, Some("admin"), true).is_ok());
2729    }
2730
2731    #[test]
2732    fn ssh_reader_collaborator_upload_allowed_receive_denied_and_multi_repo_global_auth_syncs() {
2733        let mut store = ForgeStore {
2734            visibility: "private".into(),
2735            ..Default::default()
2736        };
2737        store.users.push(crate::web_ui::store::UserAccount {
2738            username: "reader_collab".into(),
2739            password_hash: "x".into(),
2740            role: "reader".into(),
2741            ssh_keys: Vec::new(),
2742            created_at: 1,
2743            totp_secret_b32: None,
2744            recovery_codes: Vec::new(),
2745        });
2746        store.users.push(crate::web_ui::store::UserAccount {
2747            username: "maint1".into(),
2748            password_hash: "x".into(),
2749            role: "maintainer".into(),
2750            ssh_keys: Vec::new(),
2751            created_at: 1,
2752            totp_secret_b32: None,
2753            recovery_codes: Vec::new(),
2754        });
2755        store.collaborators.push("reader_collab".into());
2756
2757        // Reader collaborator can upload-pack (read) but is denied receive-pack (push).
2758        assert!(check_ssh_repo_rbac(&store, Some("reader_collab"), false).is_ok());
2759        let err = check_ssh_repo_rbac(&store, Some("reader_collab"), true).unwrap_err();
2760        assert!(err.contains("cannot push"), "{err}");
2761
2762        // Maintainer passes both upload-pack and receive-pack.
2763        assert!(check_ssh_repo_rbac(&store, Some("maint1"), false).is_ok());
2764        assert!(check_ssh_repo_rbac(&store, Some("maint1"), true).is_ok());
2765
2766        // Multi-repo root global auth sync populates child repo ForgeStore before RBAC.
2767        let dir = tempfile::tempdir().unwrap();
2768        let root = dir.path().join("multi");
2769        let child = root.join("demo.git");
2770        let global = root.join(".arks-global-auth");
2771        std::fs::create_dir_all(child.join("objects")).unwrap();
2772        std::fs::create_dir_all(child.join("refs/heads")).unwrap();
2773        std::fs::write(child.join("HEAD"), "ref: refs/heads/main\n").unwrap();
2774        std::fs::create_dir_all(&global).unwrap();
2775
2776        let admin_sk = SigningKey::from_bytes(&[77u8; 32]);
2777        let admin_blob = build_ssh_ed25519_public_blob(admin_sk.verifying_key().as_bytes());
2778        let admin_b64 =
2779            base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &admin_blob);
2780        let mut gstore = ForgeStore::load(&global);
2781        gstore.users.push(crate::web_ui::store::UserAccount {
2782            username: "global_admin".into(),
2783            password_hash: "x".into(),
2784            role: "admin".into(),
2785            ssh_keys: vec![crate::web_ui::store::SshKeyRecord {
2786                title: "deploy".into(),
2787                public_key: format!("ssh-ed25519 {admin_b64} global-admin@example.invalid"),
2788                added_at: 1,
2789            }],
2790            created_at: 1,
2791            totp_secret_b32: None,
2792            recovery_codes: Vec::new(),
2793        });
2794        gstore.save(&global).unwrap();
2795
2796        let repo = open_ssh_repo(&root, "git-receive-pack '/demo.git'").unwrap();
2797        assert_ne!(repo.common_dir(), root.as_path());
2798        crate::web_ui::sync_global_auth_into_repo(&root, repo.common_dir());
2799        let synced = ForgeStore::load_shared(repo.common_dir());
2800        let id = SshAuthIdentity {
2801            request_user: "git".into(),
2802            key_comment_user: None,
2803            public_blob: admin_blob,
2804        };
2805        let resolved = resolve_ssh_identity(&synced, &id);
2806        assert_eq!(resolved.as_deref(), Some("global_admin"));
2807        assert!(check_ssh_repo_rbac(&synced, resolved.as_deref(), true).is_ok());
2808    }
2809
2810    #[test]
2811    fn parse_openssh_ed25519_bin_rejects_truncated_inputs_without_panic() {
2812        assert!(parse_openssh_ed25519_bin(b"").is_err());
2813        assert!(parse_openssh_ed25519_bin(b"openssh-key-v1\0").is_err());
2814
2815        let mut short_nkeys = b"openssh-key-v1\0".to_vec();
2816        short_nkeys.extend(ssh_string(b"none"));
2817        short_nkeys.extend(ssh_string(b"none"));
2818        short_nkeys.extend(ssh_string(b""));
2819        short_nkeys.extend_from_slice(&[0u8, 1u8]);
2820        assert!(parse_openssh_ed25519_bin(&short_nkeys).is_err());
2821
2822        let mut short_priv = b"openssh-key-v1\0".to_vec();
2823        short_priv.extend(ssh_string(b"none"));
2824        short_priv.extend(ssh_string(b"none"));
2825        short_priv.extend(ssh_string(b""));
2826        short_priv.extend_from_slice(&1u32.to_be_bytes());
2827        short_priv.extend(ssh_string(b"pub"));
2828        short_priv.extend(ssh_string(b"abc"));
2829        assert!(parse_openssh_ed25519_bin(&short_priv).is_err());
2830
2831        let mut off = 2usize;
2832        assert!(read_u32(&[1, 2, 3], &mut off).is_err());
2833        let mut max_off = usize::MAX;
2834        assert!(read_u32(&[1, 2, 3, 4], &mut max_off).is_err());
2835    }
2836}