anvil-ssh 0.5.0

Pure-Rust SSH stack for Git tooling: transport, keys, signing, agent. Foundation library extracted from Steelbore/Gitway.
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
// SPDX-License-Identifier: GPL-3.0-or-later
// Rust guideline compliant 2026-03-30
//! Configuration builder for an [`AnvilSession`](crate::AnvilSession).
//!
//! # 0.3.0 API break
//!
//! Two fields changed shape in 0.3.0 to align with `ssh_config(5)`:
//!
//! - `identity_file: Option<PathBuf>` -> `identity_files: Vec<PathBuf>`.
//!   OpenSSH allows multiple `IdentityFile` directives; the resolver and
//!   the auth path now honour the full list in order.  Reads of the old
//!   single-path getter still work via the `#[deprecated]` shim.
//! - `skip_host_check: bool` -> `strict_host_key_checking:
//!   StrictHostKeyChecking`.  The new enum encodes `Yes` / `No` /
//!   `AcceptNew`, matching `ssh_config(5)`.  The old boolean getter and
//!   builder method continue to work via deprecation shims.
//!
//! # Examples
//!
//! ```rust
//! use anvil_ssh::AnvilConfig;
//! use std::time::Duration;
//!
//! // Connect to GitHub (default):
//! let config = AnvilConfig::github();
//!
//! // Connect to GitLab:
//! let config = AnvilConfig::gitlab();
//!
//! // Connect to Codeberg:
//! let config = AnvilConfig::codeberg();
//!
//! // Connect to any host with a custom port:
//! let config = AnvilConfig::builder("git.example.com")
//!     .port(22)
//!     .username("git")
//!     .inactivity_timeout(Duration::from_secs(60))
//!     .build();
//! ```

use std::path::{Path, PathBuf};
use std::time::Duration;

use crate::hostkey::{
    DEFAULT_CODEBERG_HOST, DEFAULT_GITHUB_HOST, DEFAULT_GITLAB_HOST, DEFAULT_PORT, FALLBACK_PORT,
    GITHUB_FALLBACK_HOST, GITLAB_FALLBACK_HOST,
};
use crate::ssh_config::{ResolvedSshConfig, StrictHostKeyChecking};

// ── Public config type ────────────────────────────────────────────────────────

/// Immutable configuration for an [`AnvilSession`](crate::AnvilSession).
///
/// Construct via [`AnvilConfig::builder`], or use one of the convenience
/// constructors ([`github`](Self::github), [`gitlab`](Self::gitlab),
/// [`codeberg`](Self::codeberg)) for the most common targets.
#[derive(Debug, Clone)]
pub struct AnvilConfig {
    /// Primary SSH host (e.g. `github.com`, `gitlab.com`, `codeberg.org`).
    pub host: String,
    /// Primary SSH port (default: 22).
    pub port: u16,
    /// Remote username (always `git` for hosted services; FR-13).
    pub username: String,
    /// Ordered list of identity-file paths.  Tried in source order during
    /// authentication; an empty list falls through to the default search
    /// path (`~/.ssh/id_ed25519`, `id_ecdsa`, `id_rsa`).  Populated by
    /// `IdentityFile` directives from `ssh_config`, by the
    /// [`AnvilConfigBuilder::add_identity_file`] /
    /// [`AnvilConfigBuilder::identity_files`] builder methods, and (for
    /// 0.2.x compatibility) by the deprecated
    /// [`AnvilConfigBuilder::identity_file`] method.
    pub identity_files: Vec<PathBuf>,
    /// OpenSSH certificate path supplied via `--cert` (FR-12).
    pub cert_file: Option<PathBuf>,
    /// Host-key verification policy.  Defaults to
    /// [`StrictHostKeyChecking::Yes`].
    pub strict_host_key_checking: StrictHostKeyChecking,
    /// Inactivity timeout for the SSH session (FR-5).
    ///
    /// GitHub's idle threshold is around 60 s; this is the configured
    /// client-side inactivity timeout, not a per-packet deadline.
    pub inactivity_timeout: Duration,
    /// Path to a `known_hosts`-style file for custom or self-hosted instances
    /// (FR-7).  Format: one `hostname SHA256:<fp>` entry per line.
    pub custom_known_hosts: Option<PathBuf>,
    /// Enable verbose debug logging when `true`.
    pub verbose: bool,
    /// Optional fallback host when port 22 is unavailable (FR-1).
    ///
    /// GitHub: `ssh.github.com:443`. GitLab: `altssh.gitlab.com:443`.
    /// Codeberg has no published port-443 fallback.
    pub fallback: Option<(String, u16)>,
}

impl AnvilConfig {
    /// Begin building a config targeting `host`.
    ///
    /// All optional fields default to sensible values. No fallback host is
    /// set by default; use the provider-specific convenience constructors
    /// ([`github`](Self::github), [`gitlab`](Self::gitlab)) if you want the
    /// port-443 fallback pre-configured.
    pub fn builder(host: impl Into<String>) -> AnvilConfigBuilder {
        AnvilConfigBuilder::new(host.into())
    }

    /// Convenience constructor for the default GitHub target (`github.com:22`).
    ///
    /// Includes the `ssh.github.com:443` fallback pre-configured.
    #[must_use]
    pub fn github() -> Self {
        Self::builder(DEFAULT_GITHUB_HOST)
            .fallback(Some((GITHUB_FALLBACK_HOST.to_owned(), FALLBACK_PORT)))
            .build()
    }

    /// Convenience constructor for the default GitLab target (`gitlab.com:22`).
    ///
    /// Includes the `altssh.gitlab.com:443` fallback pre-configured.
    #[must_use]
    pub fn gitlab() -> Self {
        Self::builder(DEFAULT_GITLAB_HOST)
            .fallback(Some((GITLAB_FALLBACK_HOST.to_owned(), FALLBACK_PORT)))
            .build()
    }

    /// Convenience constructor for Codeberg (`codeberg.org:22`).
    ///
    /// Codeberg has no published port-443 SSH fallback; no fallback is set.
    #[must_use]
    pub fn codeberg() -> Self {
        Self::builder(DEFAULT_CODEBERG_HOST).build()
    }

    /// First identity-file path, or `None` if [`Self::identity_files`] is
    /// empty.  Provided as a 0.2.x compatibility shim — new code should
    /// read [`Self::identity_files`] directly.
    #[deprecated(since = "0.3.0", note = "read `identity_files` directly")]
    #[must_use]
    pub fn identity_file(&self) -> Option<&Path> {
        self.identity_files.first().map(PathBuf::as_path)
    }

    /// `true` when [`Self::strict_host_key_checking`] is
    /// [`StrictHostKeyChecking::No`].  Provided as a 0.2.x compatibility
    /// shim — new code should read [`Self::strict_host_key_checking`]
    /// directly.
    #[deprecated(since = "0.3.0", note = "read `strict_host_key_checking` directly")]
    #[must_use]
    pub fn skip_host_check(&self) -> bool {
        matches!(self.strict_host_key_checking, StrictHostKeyChecking::No)
    }
}

// ── Builder ───────────────────────────────────────────────────────────────────

/// Builder for [`AnvilConfig`].
///
/// Obtained via [`AnvilConfig::builder`].
#[derive(Debug)]
#[must_use]
pub struct AnvilConfigBuilder {
    host: String,
    port: u16,
    username: String,
    identity_files: Vec<PathBuf>,
    cert_file: Option<PathBuf>,
    strict_host_key_checking: StrictHostKeyChecking,
    inactivity_timeout: Duration,
    custom_known_hosts: Option<PathBuf>,
    verbose: bool,
    fallback: Option<(String, u16)>,
}

impl AnvilConfigBuilder {
    fn new(host: String) -> Self {
        Self {
            host,
            port: DEFAULT_PORT,
            username: "git".to_owned(),
            identity_files: Vec::new(),
            cert_file: None,
            strict_host_key_checking: StrictHostKeyChecking::Yes,
            // 60 seconds — large enough to survive slow host responses.
            // Changing this below ~10 s risks spurious timeouts on congested
            // links.
            inactivity_timeout: Duration::from_secs(60),
            custom_known_hosts: None,
            verbose: false,
            // No fallback by default; provider-specific convenience
            // constructors set this when a known fallback exists.
            fallback: None,
        }
    }

    /// Override the target SSH port (default: 22, FR-1).
    pub fn port(mut self, port: u16) -> Self {
        self.port = port;
        self
    }

    /// Override the remote username (default: `"git"`, FR-13).
    pub fn username(mut self, username: impl Into<String>) -> Self {
        self.username = username.into();
        self
    }

    /// Append `path` to the ordered identity-file list (FR-9).
    ///
    /// Use this to add CLI-supplied keys; ssh_config-supplied keys flow
    /// in through [`Self::apply_ssh_config`].  Both can coexist; auth
    /// tries them in the order they were added.
    pub fn add_identity_file(mut self, path: impl Into<PathBuf>) -> Self {
        self.identity_files.push(path.into());
        self
    }

    /// Replace the entire identity-file list with `paths`.  Existing
    /// entries are discarded.
    pub fn identity_files(mut self, paths: Vec<PathBuf>) -> Self {
        self.identity_files = paths;
        self
    }

    /// Set a single identity-file path, replacing any existing entries.
    ///
    /// 0.2.x compatibility shim.  New code should use
    /// [`Self::add_identity_file`] (additive) or [`Self::identity_files`]
    /// (replace-all) for clarity.
    #[deprecated(
        since = "0.3.0",
        note = "use `add_identity_file` or `identity_files` for the multi-key API"
    )]
    pub fn identity_file(mut self, path: impl Into<PathBuf>) -> Self {
        self.identity_files.clear();
        self.identity_files.push(path.into());
        self
    }

    /// Set an OpenSSH certificate path (FR-12).
    pub fn cert_file(mut self, path: impl Into<PathBuf>) -> Self {
        self.cert_file = Some(path.into());
        self
    }

    /// Set the host-key verification policy (FR-8).
    pub fn strict_host_key_checking(mut self, policy: StrictHostKeyChecking) -> Self {
        self.strict_host_key_checking = policy;
        self
    }

    /// Disable host-key verification.  **Use only for emergencies** (FR-8).
    ///
    /// `true` maps to [`StrictHostKeyChecking::No`]; `false` to
    /// [`StrictHostKeyChecking::Yes`].  Lossless from the 0.2.x boolean
    /// shape (which only encoded those two states).
    #[deprecated(
        since = "0.3.0",
        note = "use `strict_host_key_checking(StrictHostKeyChecking::No)` for clarity"
    )]
    pub fn skip_host_check(mut self, skip: bool) -> Self {
        self.strict_host_key_checking = if skip {
            StrictHostKeyChecking::No
        } else {
            StrictHostKeyChecking::Yes
        };
        self
    }

    /// Override the session inactivity timeout (FR-5).
    pub fn inactivity_timeout(mut self, timeout: Duration) -> Self {
        self.inactivity_timeout = timeout;
        self
    }

    /// Path to a custom `known_hosts`-style file for self-hosted instances
    /// (FR-7).
    pub fn custom_known_hosts(mut self, path: impl Into<PathBuf>) -> Self {
        self.custom_known_hosts = Some(path.into());
        self
    }

    /// Enable verbose debug logging.
    pub fn verbose(mut self, verbose: bool) -> Self {
        self.verbose = verbose;
        self
    }

    /// Override the fallback host/port.  Pass `None` to disable fallback.
    pub fn fallback(mut self, fallback: Option<(String, u16)>) -> Self {
        self.fallback = fallback;
        self
    }

    /// Layer values from a [`ResolvedSshConfig`] into this builder.
    ///
    /// Provides ssh_config-derived defaults that subsequent builder calls
    /// can still override (call this *before* CLI-derived overrides if
    /// you want CLI to win).  The following mappings are applied:
    ///
    /// | `ssh_config` directive | Builder field |
    /// |---|---|
    /// | `HostName` | `host` (overridden) |
    /// | `Port` | `port` (overridden) |
    /// | `User` | `username` (overridden) |
    /// | `IdentityFile` (multi) | `identity_files` (extended) |
    /// | `StrictHostKeyChecking` | `strict_host_key_checking` (overridden) |
    /// | `UserKnownHostsFile` (first) | `custom_known_hosts` (filled if `None`) |
    ///
    /// Algorithm directives (`HostKeyAlgorithms`, `KexAlgorithms`,
    /// `Ciphers`, `MACs`) and `ConnectTimeout` / `ConnectionAttempts` are
    /// not yet plumbed through to the session builder; they are recorded
    /// in [`ResolvedSshConfig`] for `gitway config show` but consumption
    /// is deferred to M17 / M18.
    pub fn apply_ssh_config(mut self, resolved: &ResolvedSshConfig) -> Self {
        if let Some(hostname) = &resolved.hostname {
            self.host.clone_from(hostname);
        }
        if let Some(port) = resolved.port {
            self.port = port;
        }
        if let Some(user) = &resolved.user {
            self.username.clone_from(user);
        }
        self.identity_files
            .extend(resolved.identity_files.iter().cloned());
        if let Some(policy) = resolved.strict_host_key_checking {
            self.strict_host_key_checking = policy;
        }
        if self.custom_known_hosts.is_none() {
            if let Some(p) = resolved.user_known_hosts_files.first() {
                self.custom_known_hosts = Some(p.clone());
            }
        }
        warn_unhonored_directives(resolved);
        self
    }

    // (Unhonored-directives warning helper lives below `impl` block.)

    /// Finalise and return the [`AnvilConfig`].
    #[must_use]
    pub fn build(self) -> AnvilConfig {
        AnvilConfig {
            host: self.host,
            port: self.port,
            username: self.username,
            identity_files: self.identity_files,
            cert_file: self.cert_file,
            strict_host_key_checking: self.strict_host_key_checking,
            inactivity_timeout: self.inactivity_timeout,
            custom_known_hosts: self.custom_known_hosts,
            verbose: self.verbose,
            fallback: self.fallback,
        }
    }
}

/// Emits a single `log::warn!` listing any directives in `resolved` that
/// the resolver successfully parsed but Anvil does not yet honor.  Called
/// from [`AnvilConfigBuilder::apply_ssh_config`] so the warning fires
/// when a config is actually being prepared for connection — `gitway
/// config show` and similar inspection callers do not trigger it.
///
/// The split:
/// - `HostKeyAlgorithms`, `KexAlgorithms`, `Ciphers`, `MACs` — parsed
///   into [`ResolvedSshConfig`] for `gitway config show`, but
///   [`crate::session::build_russh_config`] uses hardcoded preferences
///   today.  M17 plumbs the `+`/`-`/`^` modifier semantics through to
///   russh's preference list.
/// - `ConnectTimeout`, `ConnectionAttempts` — parsed but not yet wired
///   into `connect()`.  M18 honors them.
fn warn_unhonored_directives(resolved: &ResolvedSshConfig) {
    let mut m17: Vec<&'static str> = Vec::new();
    if resolved.host_key_algorithms.is_some() {
        m17.push("HostKeyAlgorithms");
    }
    if resolved.kex_algorithms.is_some() {
        m17.push("KexAlgorithms");
    }
    if resolved.ciphers.is_some() {
        m17.push("Ciphers");
    }
    if resolved.macs.is_some() {
        m17.push("MACs");
    }

    let mut m18: Vec<&'static str> = Vec::new();
    if resolved.connect_timeout.is_some() {
        m18.push("ConnectTimeout");
    }
    if resolved.connection_attempts.is_some() {
        m18.push("ConnectionAttempts");
    }

    if !m17.is_empty() {
        log::warn!(
            "ssh_config: directive(s) {} parsed but not yet honored \
             (landing in M17 — Gitway PRD §8); current connections use \
             Anvil's hardcoded algorithm preferences",
            m17.join(", "),
        );
    }
    if !m18.is_empty() {
        log::warn!(
            "ssh_config: directive(s) {} parsed but not yet honored \
             (landing in M18 — Gitway PRD §8)",
            m18.join(", "),
        );
    }
}

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

    #[test]
    fn builder_defaults_yes_strict_host_check() {
        let cfg = AnvilConfig::builder("h").build();
        assert_eq!(cfg.strict_host_key_checking, StrictHostKeyChecking::Yes);
        assert!(cfg.identity_files.is_empty());
    }

    #[test]
    fn add_identity_file_accumulates() {
        let cfg = AnvilConfig::builder("h")
            .add_identity_file(PathBuf::from("/a"))
            .add_identity_file(PathBuf::from("/b"))
            .build();
        assert_eq!(
            cfg.identity_files,
            vec![PathBuf::from("/a"), PathBuf::from("/b")],
        );
    }

    #[test]
    fn identity_files_replaces_list() {
        let cfg = AnvilConfig::builder("h")
            .add_identity_file(PathBuf::from("/old"))
            .identity_files(vec![PathBuf::from("/new1"), PathBuf::from("/new2")])
            .build();
        assert_eq!(
            cfg.identity_files,
            vec![PathBuf::from("/new1"), PathBuf::from("/new2")],
        );
    }

    #[test]
    #[allow(deprecated, reason = "exercising the deprecated shim")]
    fn deprecated_identity_file_shim_clears_then_pushes() {
        let cfg = AnvilConfig::builder("h")
            .add_identity_file(PathBuf::from("/should_be_cleared"))
            .identity_file(PathBuf::from("/single"))
            .build();
        assert_eq!(cfg.identity_files, vec![PathBuf::from("/single")]);
        // The deprecated accessor returns the first identity file.
        assert_eq!(cfg.identity_file(), Some(Path::new("/single")));
    }

    #[test]
    #[allow(deprecated, reason = "exercising the deprecated shim")]
    fn deprecated_skip_host_check_maps_to_enum() {
        let cfg_skip = AnvilConfig::builder("h").skip_host_check(true).build();
        assert_eq!(cfg_skip.strict_host_key_checking, StrictHostKeyChecking::No);
        assert!(cfg_skip.skip_host_check());

        let cfg_check = AnvilConfig::builder("h").skip_host_check(false).build();
        assert_eq!(
            cfg_check.strict_host_key_checking,
            StrictHostKeyChecking::Yes,
        );
        assert!(!cfg_check.skip_host_check());
    }

    #[test]
    fn strict_host_key_checking_accepts_all_three() {
        for policy in [
            StrictHostKeyChecking::Yes,
            StrictHostKeyChecking::No,
            StrictHostKeyChecking::AcceptNew,
        ] {
            let cfg = AnvilConfig::builder("h")
                .strict_host_key_checking(policy)
                .build();
            assert_eq!(cfg.strict_host_key_checking, policy);
        }
    }

    #[test]
    fn apply_ssh_config_layers_resolved_values() {
        let resolved = ResolvedSshConfig {
            hostname: Some("real.example.com".to_owned()),
            user: Some("alice".to_owned()),
            port: Some(2222),
            identity_files: vec![PathBuf::from("/cfg/key")],
            strict_host_key_checking: Some(StrictHostKeyChecking::AcceptNew),
            user_known_hosts_files: vec![PathBuf::from("/cfg/known_hosts")],
            ..ResolvedSshConfig::default()
        };
        let cfg = AnvilConfig::builder("alias")
            .apply_ssh_config(&resolved)
            .build();
        assert_eq!(cfg.host, "real.example.com");
        assert_eq!(cfg.port, 2222);
        assert_eq!(cfg.username, "alice");
        assert_eq!(cfg.identity_files, vec![PathBuf::from("/cfg/key")]);
        assert_eq!(
            cfg.strict_host_key_checking,
            StrictHostKeyChecking::AcceptNew,
        );
        assert_eq!(
            cfg.custom_known_hosts,
            Some(PathBuf::from("/cfg/known_hosts"))
        );
    }

    #[test]
    fn apply_ssh_config_extends_identity_files_does_not_replace() {
        let resolved = ResolvedSshConfig {
            identity_files: vec![PathBuf::from("/cfg/a")],
            ..ResolvedSshConfig::default()
        };
        let cfg = AnvilConfig::builder("h")
            .add_identity_file(PathBuf::from("/cli/first"))
            .apply_ssh_config(&resolved)
            .build();
        // CLI ones come first, ssh_config appends after.
        assert_eq!(
            cfg.identity_files,
            vec![PathBuf::from("/cli/first"), PathBuf::from("/cfg/a")],
        );
    }

    #[test]
    fn apply_ssh_config_does_not_overwrite_explicit_known_hosts() {
        let resolved = ResolvedSshConfig {
            user_known_hosts_files: vec![PathBuf::from("/from/cfg")],
            ..ResolvedSshConfig::default()
        };
        let cfg = AnvilConfig::builder("h")
            .custom_known_hosts(PathBuf::from("/from/cli"))
            .apply_ssh_config(&resolved)
            .build();
        assert_eq!(cfg.custom_known_hosts, Some(PathBuf::from("/from/cli")));
    }
}