gitway-lib 0.3.1

Core SSH transport library for Git hosting services (GitHub, GitLab, Codeberg, and self-hosted).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
// SPDX-License-Identifier: GPL-3.0-or-later
// Rust guideline compliant 2026-03-30
// Updated 2026-04-12: added verified_fingerprint tracking for SFRS JSON output
//! SSH session management (FR-1 through FR-5, FR-9 through FR-17).
//!
//! [`GitwaySession`] wraps a russh [`client::Handle`] and exposes the
//! operations Gitway needs: connect, authenticate, exec, and close.
//!
//! Host-key verification is performed inside [`GitwayHandler::check_server_key`]
//! using the fingerprints collected by [`crate::hostkey`].

use std::borrow::Cow;
use std::fmt;
use std::sync::{Arc, Mutex};
use std::time::Duration;

use russh::client;
use russh::keys::{HashAlg, PrivateKeyWithHashAlg};
use russh::{Disconnect, Preferred, cipher, kex};

use crate::config::GitwayConfig;
use crate::error::{GitwayError, GitwayErrorKind};
use crate::hostkey;
use crate::relay;

// ── Handler ───────────────────────────────────────────────────────────────────

/// russh client event handler.
///
/// Validates the server host key (FR-6, FR-7, FR-8) and captures any
/// authentication banner the server sends before confirming the session.
struct GitwayHandler {
    /// Expected SHA-256 fingerprints for the target host.
    fingerprints: Vec<String>,
    /// When `true`, host-key verification is skipped (FR-8).
    skip_check: bool,
    /// Buffer for the last authentication banner received from the server.
    ///
    /// GitHub sends "Hi <user>! You've successfully authenticated…" here.
    auth_banner: Arc<Mutex<Option<String>>>,
    /// The SHA-256 fingerprint of the server key that passed verification.
    ///
    /// Set during `check_server_key`; exposed via
    /// [`GitwaySession::verified_fingerprint`] for structured JSON output.
    verified_fingerprint: Arc<Mutex<Option<String>>>,
}

impl fmt::Debug for GitwayHandler {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("GitwayHandler")
            .field("fingerprints", &self.fingerprints)
            .field("skip_check", &self.skip_check)
            .field("auth_banner", &self.auth_banner)
            .field("verified_fingerprint", &self.verified_fingerprint)
            .finish()
    }
}

impl client::Handler for GitwayHandler {
    type Error = GitwayError;

    async fn check_server_key(
        &mut self,
        server_public_key: &russh::keys::ssh_key::PublicKey,
    ) -> Result<bool, Self::Error> {
        if self.skip_check {
            log::warn!("host-key verification skipped (--insecure-skip-host-check)");
            return Ok(true);
        }

        let fp = server_public_key
            .fingerprint(HashAlg::Sha256)
            .to_string();

        log::debug!("session: checking server host key {fp}");

        if self.fingerprints.iter().any(|f| f == &fp) {
            log::debug!("session: host key verified: {fp}");
            if let Ok(mut guard) = self.verified_fingerprint.lock() {
                *guard = Some(fp);
            }
            Ok(true)
        } else {
            Err(GitwayError::host_key_mismatch(fp))
        }
    }

    async fn auth_banner(
        &mut self,
        banner: &str,
        _session: &mut client::Session,
    ) -> Result<(), Self::Error> {
        let trimmed = banner.trim().to_owned();
        log::info!("server banner: {banner}");
        if let Ok(mut guard) = self.auth_banner.lock() {
            *guard = Some(trimmed);
        }
        Ok(())
    }
}

// ── Session ───────────────────────────────────────────────────────────────────

/// An active SSH session connected to a GitHub (or GHE) host.
///
/// # Typical Usage
///
/// ```no_run
/// use gitway_lib::{GitwayConfig, GitwaySession};
///
/// # async fn doc() -> Result<(), gitway_lib::GitwayError> {
/// let config = GitwayConfig::github();
/// let mut session = GitwaySession::connect(&config).await?;
/// // authenticate, exec, close…
/// # Ok(())
/// # }
/// ```
pub struct GitwaySession {
    handle: client::Handle<GitwayHandler>,
    /// Authentication banner received from the server, if any.
    auth_banner: Arc<Mutex<Option<String>>>,
    /// SHA-256 fingerprint of the server key that passed verification, if any.
    verified_fingerprint: Arc<Mutex<Option<String>>>,
}

/// Manual Debug impl because `client::Handle<H>` does not implement `Debug`.
impl fmt::Debug for GitwaySession {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("GitwaySession").finish_non_exhaustive()
    }
}

impl GitwaySession {
    // ── Construction ─────────────────────────────────────────────────────────

    /// Establishes a TCP connection to the host in `config` and completes the
    /// SSH handshake (including host-key verification).
    ///
    /// Does **not** authenticate; call [`authenticate`](Self::authenticate) or
    /// [`authenticate_best`](Self::authenticate_best) after this.
    ///
    /// # Errors
    ///
    /// Returns an error on network failure or if the server's host key does not
    /// match any pinned fingerprint.
    pub async fn connect(config: &GitwayConfig) -> Result<Self, GitwayError> {
        let russh_cfg = Arc::new(build_russh_config(config.inactivity_timeout));
        let fingerprints =
            hostkey::fingerprints_for_host(&config.host, &config.custom_known_hosts)?;
        let auth_banner = Arc::new(Mutex::new(None));
        let verified_fingerprint = Arc::new(Mutex::new(None));

        let handler = GitwayHandler {
            fingerprints,
            skip_check: config.skip_host_check,
            auth_banner: Arc::clone(&auth_banner),
            verified_fingerprint: Arc::clone(&verified_fingerprint),
        };

        log::debug!("session: connecting to {}:{}", config.host, config.port);

        let handle = client::connect(
            russh_cfg,
            (config.host.as_str(), config.port),
            handler,
        )
        .await?;

        log::debug!("session: SSH handshake complete with {}", config.host);

        Ok(Self { handle, auth_banner, verified_fingerprint })
    }

    // ── Authentication ────────────────────────────────────────────────────────

    /// Authenticates with an explicit key.
    ///
    /// Use [`authenticate_best`] to let the library discover the key
    /// automatically.
    ///
    /// # Errors
    ///
    /// Returns an error on SSH protocol failures.  Returns
    /// [`GitwayError::is_authentication_failed`] when the server accepts the
    /// exchange but rejects the key.
    pub async fn authenticate(
        &mut self,
        username: &str,
        key: PrivateKeyWithHashAlg,
    ) -> Result<(), GitwayError> {
        log::debug!("session: authenticating as {username}");

        let result = self.handle.authenticate_publickey(username, key).await?;

        if result.success() {
            log::debug!("session: authentication succeeded for {username}");
            Ok(())
        } else {
            Err(GitwayError::authentication_failed())
        }
    }

    /// Authenticates with a private key and an accompanying OpenSSH certificate
    /// (FR-12).
    ///
    /// The certificate is presented to the server in place of the raw public
    /// key.  This is typically used with organisation-issued certificates that
    /// grant access without requiring the public key to be listed in
    /// `authorized_keys`.
    ///
    /// # Errors
    ///
    /// Returns an error on SSH protocol failures or if the server rejects the
    /// certificate.
    pub async fn authenticate_with_cert(
        &mut self,
        username: &str,
        key: russh::keys::PrivateKey,
        cert: russh::keys::Certificate,
    ) -> Result<(), GitwayError> {
        log::debug!("session: authenticating as {username} with OpenSSH certificate");

        let result = self
            .handle
            .authenticate_openssh_cert(username, Arc::new(key), cert)
            .await?;

        if result.success() {
            log::debug!("session: certificate authentication succeeded for {username}");
            Ok(())
        } else {
            Err(GitwayError::authentication_failed())
        }
    }

    /// Discovers the best available key and authenticates using it.
    ///
    /// Priority order (FR-9):
    /// 1. Explicit `--identity` path from config.
    /// 2. Default `.ssh` paths (`id_ed25519` → `id_ecdsa` → `id_rsa`).
    /// 3. SSH agent via `$SSH_AUTH_SOCK` (Unix only).
    ///
    /// If a certificate path is configured in `config.cert_file`, certificate
    /// authentication (FR-12) is used instead of raw public-key authentication
    /// for file-based keys.
    ///
    /// When the chosen key requires a passphrase this method returns an error
    /// whose [`is_key_encrypted`](GitwayError::is_key_encrypted) predicate is
    /// `true`; the caller (CLI layer) should then prompt and call
    /// [`authenticate_with_passphrase`](Self::authenticate_with_passphrase).
    ///
    /// # Errors
    ///
    /// Returns [`GitwayError::is_no_key_found`] when no key is available via
    /// any discovery method.
    pub async fn authenticate_best(&mut self, config: &GitwayConfig) -> Result<(), GitwayError> {
        use crate::auth::{IdentityResolution, find_identity, wrap_key};

        let resolution = find_identity(config)?;

        match resolution {
            IdentityResolution::Found { key, .. } => {
                return self.auth_key_or_cert(config, key).await;
            }
            IdentityResolution::Encrypted { path } => {
                log::debug!(
                    "session: key at {} is passphrase-protected; trying SSH agent first",
                    path.display()
                );
                // Try the agent before asking for a passphrase.  The key may
                // already be loaded via `ssh-add`, and a passphrase prompt is
                // impossible when gitway is spawned by Git without a terminal.
                #[cfg(unix)]
                {
                    use crate::auth::connect_agent;
                    if let Some(conn) = connect_agent().await? {
                        match self.authenticate_with_agent(&config.username, conn).await {
                            Ok(()) => return Ok(()),
                            Err(e) if e.is_authentication_failed() => {
                                log::debug!(
                                    "session: agent could not authenticate; \
                                     will request passphrase for {}",
                                    path.display()
                                );
                            }
                            Err(e) => return Err(e),
                        }
                    }
                }
                return Err(GitwayError::new(GitwayErrorKind::Keys(
                    russh::keys::Error::KeyIsEncrypted,
                )));
            }
            IdentityResolution::NotFound => {
                // Fall through to agent (below).
            }
        }

        // Priority 3: SSH agent — reached only when no file-based key exists (FR-9).
        #[cfg(unix)]
        {
            use crate::auth::connect_agent;
            if let Some(conn) = connect_agent().await? {
                return self.authenticate_with_agent(&config.username, conn).await;
            }
        }

        // For RSA keys, ask the server which hash algorithm it prefers (FR-11).
        // This branch is only reached when we must still try a key via wrap_key
        // after exhausting the above — currently unused, but kept for clarity.
        let _ = wrap_key; // suppress unused-import warning on non-Unix builds
        Err(GitwayError::no_key_found())
    }

    /// Loads an encrypted key with `passphrase` and authenticates.
    ///
    /// Call this after [`authenticate_best`] returns an encrypted-key error
    /// and the CLI has collected the passphrase from the terminal.
    ///
    /// If `config.cert_file` is set, certificate authentication is used
    /// (FR-12).
    ///
    /// # Errors
    ///
    /// Returns an error if the passphrase is wrong or authentication fails.
    pub async fn authenticate_with_passphrase(
        &mut self,
        config: &GitwayConfig,
        path: &std::path::Path,
        passphrase: &str,
    ) -> Result<(), GitwayError> {
        use crate::auth::load_encrypted_key;

        let key = load_encrypted_key(path, passphrase)?;
        self.auth_key_or_cert(config, key).await
    }

    /// Tries each identity held in `conn` until one succeeds or all are
    /// exhausted.
    ///
    /// On Unix this is called automatically by [`authenticate_best`] when no
    /// file-based key is found.  For plain public-key identities the signing
    /// challenge is forwarded to the agent; for certificate identities the
    /// full certificate is presented alongside the agent-signed challenge.
    ///
    /// # Errors
    ///
    /// Returns [`GitwayError::is_authentication_failed`] if all identities are
    /// rejected, or [`GitwayError::is_no_key_found`] if the agent was empty.
    #[cfg(unix)]
    pub async fn authenticate_with_agent(
        &mut self,
        username: &str,
        mut conn: crate::auth::AgentConnection,
    ) -> Result<(), GitwayError> {
        use russh::keys::agent::AgentIdentity;

        for identity in conn.identities.clone() {
            let result = match &identity {
                AgentIdentity::PublicKey { key, .. } => {
                    let hash_alg = if key.algorithm().is_rsa() {
                        self.handle
                            .best_supported_rsa_hash()
                            .await?
                            .flatten()
                            // Fall back to SHA-256 when the server offers no guidance (FR-11).
                            .or(Some(HashAlg::Sha256))
                    } else {
                        None
                    };
                    self.handle
                        .authenticate_publickey_with(
                            username,
                            key.clone(),
                            hash_alg,
                            &mut conn.client,
                        )
                        .await
                        .map_err(GitwayError::from)
                }
                AgentIdentity::Certificate { certificate, .. } => {
                    self.handle
                        .authenticate_certificate_with(
                            username,
                            certificate.clone(),
                            None,
                            &mut conn.client,
                        )
                        .await
                        .map_err(GitwayError::from)
                }
            };

            match result? {
                r if r.success() => {
                    log::debug!("session: agent authentication succeeded");
                    return Ok(());
                }
                _ => {
                    log::debug!("session: agent identity rejected; trying next");
                }
            }
        }

        Err(GitwayError::no_key_found())
    }

    // ── Exec / relay ──────────────────────────────────────────────────────────

    /// Opens a session channel, executes `command`, and relays stdio
    /// bidirectionally until the remote process exits.
    ///
    /// Returns the remote exit code (FR-16).  Exit-via-signal returns
    /// `128 + signal_number` (FR-17).
    ///
    /// # Errors
    ///
    /// Returns an error on channel open failure or SSH protocol errors.
    pub async fn exec(&mut self, command: &str) -> Result<u32, GitwayError> {
        log::debug!("session: opening exec channel for '{command}'");

        let channel = self.handle.channel_open_session().await?;
        channel.exec(true, command).await?;

        let exit_code = relay::relay_channel(channel).await?;

        log::debug!("session: command '{command}' exited with code {exit_code}");

        Ok(exit_code)
    }

    // ── Lifecycle ─────────────────────────────────────────────────────────────

    /// Sends a graceful `SSH_MSG_DISCONNECT` and closes the connection.
    ///
    /// # Errors
    ///
    /// Returns an error if the disconnect message cannot be sent.
    pub async fn close(self) -> Result<(), GitwayError> {
        self.handle
            .disconnect(Disconnect::ByApplication, "", "English")
            .await?;
        Ok(())
    }

    // ── Accessors ─────────────────────────────────────────────────────────────

    /// Returns the authentication banner last received from the server (if any).
    ///
    /// For GitHub.com this contains the "Hi <user>!" welcome message.
    ///
    /// # Panics
    ///
    /// Panics if the internal mutex is poisoned, which can only occur if another
    /// thread panicked while holding the lock — a programming error.
    #[must_use]
    pub fn auth_banner(&self) -> Option<String> {
        self.auth_banner
            .lock()
            .expect("auth_banner lock is not poisoned")
            .clone()
    }

    /// Returns the SHA-256 fingerprint of the server key that was verified.
    ///
    /// Available after a successful [`connect`](Self::connect).  Returns `None`
    /// when host-key verification was skipped (`--insecure-skip-host-check`).
    ///
    /// # Panics
    ///
    /// Panics if the internal mutex is poisoned — a programming error.
    #[must_use]
    pub fn verified_fingerprint(&self) -> Option<String> {
        self.verified_fingerprint
            .lock()
            .expect("verified_fingerprint lock is not poisoned")
            .clone()
    }

    // ── Internal helpers ──────────────────────────────────────────────────────

    /// Authenticates with `key`, using certificate auth if `config.cert_file`
    /// is set (FR-12), otherwise plain public-key auth (FR-11).
    async fn auth_key_or_cert(
        &mut self,
        config: &GitwayConfig,
        key: russh::keys::PrivateKey,
    ) -> Result<(), GitwayError> {
        use crate::auth::{load_cert, wrap_key};

        if let Some(ref cert_path) = config.cert_file {
            let cert = load_cert(cert_path)?;
            return self
                .authenticate_with_cert(&config.username, key, cert)
                .await;
        }

        // For RSA keys, ask the server which hash algorithm it prefers (FR-11).
        let rsa_hash = if key.algorithm().is_rsa() {
            self.handle
                .best_supported_rsa_hash()
                .await?
                .flatten()
                .or(Some(HashAlg::Sha256))
        } else {
            None
        };

        let wrapped = wrap_key(key, rsa_hash);
        self.authenticate(&config.username, wrapped).await
    }
}

// ── russh config builder ──────────────────────────────────────────────────────

/// Constructs a russh [`client::Config`] with Gitway's preferred algorithms.
///
/// Algorithm preferences (FR-2, FR-3, FR-4):
/// - Key exchange: `curve25519-sha256` (RFC 8731) with
///   `curve25519-sha256@libssh.org` as fallback.
/// - Cipher: `chacha20-poly1305@openssh.com`.
/// - `ext-info-c` advertises server-sig-algs extension support.
fn build_russh_config(inactivity_timeout: Duration) -> client::Config {
    client::Config {
        // 60 s matches GitHub's server-side idle threshold.
        // Lowering below ~10 s risks spurious timeouts on high-latency links.
        inactivity_timeout: Some(inactivity_timeout),
        preferred: Preferred {
            kex: Cow::Owned(vec![
                kex::CURVE25519,              // curve25519-sha256 (RFC 8731)
                kex::CURVE25519_PRE_RFC_8731, // curve25519-sha256@libssh.org
                kex::EXTENSION_SUPPORT_AS_CLIENT, // ext-info-c (FR-4)
            ]),
            cipher: Cow::Owned(vec![
                cipher::CHACHA20_POLY1305, // chacha20-poly1305@openssh.com (FR-3)
            ]),
            ..Default::default()
        },
        ..Default::default()
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    // ── NFR-6: legacy algorithm exclusion ────────────────────────────────────

    /// 3DES-CBC must never appear in the negotiated cipher list (NFR-6).
    ///
    /// Our explicit cipher override contains only chacha20-poly1305, so 3DES
    /// cannot be selected even if the server offers it.
    #[test]
    fn config_cipher_excludes_3des() {
        let config = build_russh_config(Duration::from_secs(60));
        let found = config.preferred.cipher.iter().any(|c| c.as_ref() == "3des-cbc");
        assert!(!found, "3DES-CBC must not appear in the cipher list (NFR-6)");
    }

    /// DSA must never appear in the key-algorithm list (NFR-6).
    ///
    /// russh's `Preferred::DEFAULT` already omits DSA; this test locks that
    /// invariant so a russh upgrade cannot silently re-introduce it.
    #[test]
    fn config_key_algorithms_exclude_dsa() {
        use russh::keys::Algorithm;

        let config = build_russh_config(Duration::from_secs(60));
        assert!(
            !config.preferred.key.contains(&Algorithm::Dsa),
            "DSA must not appear in the key-algorithm list (NFR-6)"
        );
    }

    // ── FR-2 / FR-3 positive assertions ─────────────────────────────────────

    /// curve25519-sha256 must be in the kex list (FR-2).
    #[test]
    fn config_kex_includes_curve25519() {
        let config = build_russh_config(Duration::from_secs(60));
        let found = config.preferred.kex.iter().any(|k| k.as_ref() == "curve25519-sha256");
        assert!(found, "curve25519-sha256 must be in the kex list (FR-2)");
    }

    /// chacha20-poly1305@openssh.com must be in the cipher list (FR-3).
    #[test]
    fn config_cipher_includes_chacha20_poly1305() {
        let config = build_russh_config(Duration::from_secs(60));
        let found = config
            .preferred
            .cipher
            .iter()
            .any(|c| c.as_ref() == "chacha20-poly1305@openssh.com");
        assert!(found, "chacha20-poly1305@openssh.com must be in the cipher list (FR-3)");
    }
}