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
// SPDX-License-Identifier: GPL-3.0-or-later
// Rust guideline compliant 2026-03-30
//! SSH host-key fingerprint pinning for well-known Git hosting services (FR-6, FR-7).
//!
//! Gitway embeds the published SHA-256 fingerprints for GitHub, GitLab, and
//! Codeberg.  On every connection the server's presented key is hashed and the
//! resulting fingerprint is compared against the embedded list for that host.
//! Any mismatch aborts the connection immediately.
//!
//! # Custom / self-hosted instances
//!
//! Fingerprints for any host not listed below can be added via a
//! `known_hosts`-style file at `~/.config/gitway/known_hosts` (FR-7).
//! Each non-comment line must follow the format:
//!
//! ```text
//! hostname SHA256:<base64-encoded-fingerprint>
//! ```
//!
//! # Fingerprint sources
//!
//! - GitHub:   <https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/githubs-ssh-key-fingerprints>
//! - GitLab:   <https://docs.gitlab.com/ee/user/gitlab_com/index.html#ssh-host-keys-fingerprints>
//! - Codeberg: <https://docs.codeberg.org/security/ssh-fingerprint/>
//!
//! Last verified: 2026-04-11

use std::path::Path;

use crate::cert_authority::{parse_known_hosts, CertAuthority, KnownHostsFile, RevokedEntry};
use crate::error::AnvilError;
use crate::ssh_config::lexer::wildcard_match;

// ── Well-known host constants ─────────────────────────────────────────────────

/// Primary GitHub SSH host (FR-1).
pub const DEFAULT_GITHUB_HOST: &str = "github.com";

/// Fallback GitHub SSH host when port 22 is unavailable (FR-1).
///
/// GitHub routes SSH traffic through HTTPS port 443 on this hostname.
pub const GITHUB_FALLBACK_HOST: &str = "ssh.github.com";

/// Primary GitLab SSH host.
pub const DEFAULT_GITLAB_HOST: &str = "gitlab.com";

/// Fallback GitLab SSH host when port 22 is unavailable.
///
/// GitLab routes SSH traffic through HTTPS port 443 on this hostname.
pub const GITLAB_FALLBACK_HOST: &str = "altssh.gitlab.com";

/// Primary Codeberg SSH host.
pub const DEFAULT_CODEBERG_HOST: &str = "codeberg.org";

/// Default SSH port used by all providers.
///
/// Changing to a value below 1024 requires elevated privileges on most
/// POSIX systems; only override this when using a self-hosted instance
/// with a non-standard port.
pub const DEFAULT_PORT: u16 = 22;

/// HTTPS-port fallback for providers that support it (GitHub, GitLab).
pub const FALLBACK_PORT: u16 = 443;

// ── Legacy alias kept for backward compatibility ──────────────────────────────

/// Alias for [`GITHUB_FALLBACK_HOST`]; retained so existing callers that
/// reference the old name continue to compile.
#[deprecated(since = "0.2.0", note = "use GITHUB_FALLBACK_HOST instead")]
pub const FALLBACK_HOST: &str = GITHUB_FALLBACK_HOST;

// ── Embedded fingerprints ─────────────────────────────────────────────────────

/// GitHub's published SSH host-key fingerprints (SHA-256, FR-6).
///
/// Contains one entry per key type in `SHA256:<base64>` format:
/// - Ed25519  (index 0)
/// - ECDSA    (index 1)
/// - RSA      (index 2)
///
/// **If GitHub rotates its keys, update this constant and cut a patch release.**
pub const GITHUB_FINGERPRINTS: &[&str] = &[
    "SHA256:+DiY3wvvV6TuJJhbpZisF/zLDA0zPMSvHdkr4UvCOqU", // Ed25519
    "SHA256:p2QAMXNIC1TJYWeIOttrVc98/R1BUFWu3/LiyKgUfQM", // ECDSA-SHA2-nistp256
    "SHA256:uNiVztksCsDhcc0u9e8BujQXVUpKZIDTMczCvj3tD2s", // RSA
];

/// GitLab.com's published SSH host-key fingerprints (SHA-256).
///
/// Contains one entry per key type in `SHA256:<base64>` format:
/// - Ed25519  (index 0)
/// - ECDSA    (index 1)
/// - RSA      (index 2)
///
/// **If GitLab rotates its keys, update this constant and cut a patch release.**
pub const GITLAB_FINGERPRINTS: &[&str] = &[
    "SHA256:eUXGGm1YGsMAS7vkcx6JOJdOGHPem5gQp4taiCfCLB8", // Ed25519
    "SHA256:HbW3g8zUjNSksFbqTiUWPWg2Bq1x8xdGUrliXFzSnUw", // ECDSA-SHA2-nistp256
    "SHA256:ROQFvPThGrW4RuWLoL9tq9I9zJ42fK4XywyRtbOz/EQ", // RSA
];

/// Codeberg.org's published SSH host-key fingerprints (SHA-256).
///
/// Contains one entry per key type in `SHA256:<base64>` format:
/// - Ed25519  (index 0)
/// - ECDSA    (index 1)
/// - RSA      (index 2)
///
/// **If Codeberg rotates its keys, update this constant and cut a patch release.**
pub const CODEBERG_FINGERPRINTS: &[&str] = &[
    "SHA256:mIlxA9k46MmM6qdJOdMnAQpzGxF4WIVVL+fj+wZbw0g", // Ed25519
    "SHA256:T9FYDEHELhVkulEKKwge5aVhVTbqCW0MIRwAfpARs/E", // ECDSA-SHA2-nistp256
    "SHA256:6QQmYi4ppFS4/+zSZ5S4IU+4sa6rwvQ4PbhCtPEBekQ", // RSA
];

// ── Known-hosts parser for custom / GHE support ───────────────────────────────

/// Parses a known-hosts file and returns all fingerprints for `hostname`.
///
/// Lines starting with `#` and blank lines are ignored. Each valid line has
/// the form `hostname SHA256:<fp>`.
///
/// # Errors
///
/// Returns an error if the file cannot be read.
fn fingerprints_from_known_hosts(path: &Path, hostname: &str) -> Result<Vec<String>, AnvilError> {
    let content = std::fs::read_to_string(path)?;
    let mut fps = Vec::new();

    for line in content.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let mut parts = line.splitn(2, ' ');
        let Some(host_part) = parts.next() else {
            continue;
        };
        let Some(fp_part) = parts.next() else {
            continue;
        };
        if host_part == hostname {
            fps.push(fp_part.trim().to_owned());
        }
    }

    Ok(fps)
}

/// Returns the default known-hosts path: `~/.config/gitway/known_hosts`.
fn default_known_hosts_path() -> Option<std::path::PathBuf> {
    dirs::config_dir().map(|d| d.join("gitway").join("known_hosts"))
}

// ── Public verifier ───────────────────────────────────────────────────────────

/// Collects all expected fingerprints for `host`.
///
/// For well-known hosts (GitHub, GitLab, Codeberg and their fallback
/// hostnames) the embedded fingerprint set is returned.  For any other host
/// the custom known-hosts file is consulted; if it provides entries those are
/// used, otherwise the connection is refused with an actionable error.
///
/// # Errors
///
/// Returns an error if `custom_path` is specified but cannot be read, or if
/// no fingerprints can be found for the given host.
pub fn fingerprints_for_host(
    host: &str,
    custom_path: &Option<std::path::PathBuf>,
) -> Result<Vec<String>, AnvilError> {
    // Start with the embedded set for the well-known hosted services.
    let mut fps: Vec<String> = match host {
        "github.com" | "ssh.github.com" => {
            GITHUB_FINGERPRINTS.iter().map(|&s| s.to_owned()).collect()
        }
        "gitlab.com" | "altssh.gitlab.com" => {
            GITLAB_FINGERPRINTS.iter().map(|&s| s.to_owned()).collect()
        }
        "codeberg.org" => CODEBERG_FINGERPRINTS
            .iter()
            .map(|&s| s.to_owned())
            .collect(),
        _ => Vec::new(),
    };

    // Consult the known-hosts file (user-supplied path or the default location)
    // to allow custom / self-hosted instances and to let users extend or
    // override the embedded sets.
    let known_hosts_path = custom_path.clone().or_else(default_known_hosts_path);

    if let Some(ref path) = known_hosts_path {
        if path.exists() {
            let extras = fingerprints_from_known_hosts(path, host)?;
            fps.extend(extras);
        }
    }

    // No fingerprints at all → refuse the connection with a clear message.
    if fps.is_empty() {
        return Err(
            AnvilError::invalid_config(format!("no fingerprints known for host '{host}'"))
                .with_hint(format!(
                    "Gitway refuses to connect to hosts whose SSH fingerprint it can't \
             verify (no trust-on-first-use). Either you typed the hostname \
             wrong, or this is a self-hosted server and you need to pin its \
             fingerprint: fetch it from the provider's docs (GitHub, GitLab, \
             Codeberg publish them) and append one line to \
             ~/.config/gitway/known_hosts:\n\
             \n\
                 {host} SHA256:<base64-fingerprint>\n\
             \n\
             As a last resort, re-run with --insecure-skip-host-check (not \
             recommended — this disables MITM protection)."
                )),
        );
    }

    Ok(fps)
}

// ── M14: combined trust view (FR-60, FR-64) ──────────────────────────────────

/// Combined view of every `known_hosts` entry that bears on the
/// connection target.
///
/// Returned by [`host_key_trust`].  A connection target's effective
/// trust is the union of:
///
/// - `fingerprints` — direct SHA-256 pins (embedded + custom-file).
///   Identical to what [`fingerprints_for_host`] returns.
/// - `cert_authorities` — `@cert-authority` entries whose host pattern
///   matches the target.  Live cert verification (FR-61, FR-62, FR-63)
///   is deferred until russh exposes the server's certificate; the
///   field is populated today so `gitway config show --json` and
///   audit tooling can surface CA identities.
/// - `revoked` — `@revoked` entries whose host pattern matches.
///   Enforced first in
///   [`crate::session::AnvilSession::connect`]'s host-key check: any
///   presented key whose fingerprint hits one of these is rejected
///   regardless of `StrictHostKeyChecking` policy.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct HostKeyTrust {
    pub fingerprints: Vec<String>,
    pub cert_authorities: Vec<CertAuthority>,
    pub revoked: Vec<RevokedEntry>,
}

/// Returns the [`HostKeyTrust`] for `host`, combining the embedded
/// fingerprint set, any direct pins / `@cert-authority` / `@revoked`
/// lines from the user-supplied or default `known_hosts` file, and
/// pattern-matching for the cert-authority + revoked classes.
///
/// Unlike [`fingerprints_for_host`], an empty trust set is **not** an
/// error — the caller decides whether the absence is fatal (the
/// `StrictHostKeyChecking::AcceptNew` path tolerates an empty set; the
/// `Yes` path does not).
///
/// # Errors
/// [`AnvilError::invalid_config`] when the known-hosts file exists but
/// fails to parse (a malformed `@cert-authority` line, for instance).
/// File-not-found is silently treated as no entries.
pub fn host_key_trust(
    host: &str,
    custom_path: &Option<std::path::PathBuf>,
) -> Result<HostKeyTrust, AnvilError> {
    let mut trust = HostKeyTrust {
        fingerprints: embedded_fingerprints(host),
        cert_authorities: Vec::new(),
        revoked: Vec::new(),
    };

    let known_hosts_path = custom_path.clone().or_else(default_known_hosts_path);
    let Some(path) = known_hosts_path else {
        return Ok(trust);
    };
    if !path.exists() {
        return Ok(trust);
    }

    let content = std::fs::read_to_string(&path).map_err(|e| {
        AnvilError::invalid_config(format!(
            "could not read known_hosts {}: {e}",
            path.display(),
        ))
    })?;
    let parsed: KnownHostsFile = parse_known_hosts(&content)?;

    for direct in parsed.direct {
        if wildcard_match(&direct.host_pattern, host) {
            trust.fingerprints.push(direct.fingerprint);
        }
    }
    for ca in parsed.cert_authorities {
        if wildcard_match(&ca.host_pattern, host) {
            trust.cert_authorities.push(ca);
        }
    }
    for rev in parsed.revoked {
        if wildcard_match(&rev.host_pattern, host) {
            trust.revoked.push(rev);
        }
    }

    Ok(trust)
}

/// Returns the embedded SHA-256 fingerprints for the listed
/// well-known hosts.  Internal helper used by both
/// [`fingerprints_for_host`] and [`host_key_trust`].
fn embedded_fingerprints(host: &str) -> Vec<String> {
    match host {
        "github.com" | "ssh.github.com" => {
            GITHUB_FINGERPRINTS.iter().map(|&s| s.to_owned()).collect()
        }
        "gitlab.com" | "altssh.gitlab.com" => {
            GITLAB_FINGERPRINTS.iter().map(|&s| s.to_owned()).collect()
        }
        "codeberg.org" => CODEBERG_FINGERPRINTS
            .iter()
            .map(|&s| s.to_owned())
            .collect(),
        _ => Vec::new(),
    }
}

/// Appends `host SHA256:<fingerprint>` as a new line to the `known_hosts`
/// file at `path`, creating the file (and any missing parent directories)
/// if needed.
///
/// Used by [`crate::ssh_config::StrictHostKeyChecking::AcceptNew`] to
/// record the fingerprint of an otherwise-unknown host on first
/// connection.  This is the minimum write surface — file locking and
/// duplicate-detection are deferred to the post-M12 TOFU UX.
///
/// # Errors
///
/// Returns an error if the parent directory cannot be created, or if
/// the file cannot be opened for append, or if the write fails.
pub(crate) fn append_known_host(
    path: &Path,
    host: &str,
    fingerprint: &str,
) -> Result<(), AnvilError> {
    use std::io::Write;

    if let Some(parent) = path.parent() {
        if !parent.as_os_str().is_empty() {
            std::fs::create_dir_all(parent).map_err(|e| {
                AnvilError::invalid_config(format!(
                    "could not create known_hosts parent {}: {e}",
                    parent.display(),
                ))
            })?;
        }
    }

    let line = format!("{host} {fingerprint}\n");
    let mut file = std::fs::OpenOptions::new()
        .append(true)
        .create(true)
        .open(path)
        .map_err(|e| {
            AnvilError::invalid_config(format!(
                "could not open known_hosts {} for append: {e}",
                path.display(),
            ))
        })?;
    file.write_all(line.as_bytes()).map_err(|e| {
        AnvilError::invalid_config(format!(
            "could not write to known_hosts {}: {e}",
            path.display(),
        ))
    })?;

    Ok(())
}

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

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

    #[test]
    fn github_com_returns_three_fingerprints() {
        let fps = fingerprints_for_host("github.com", &None).unwrap();
        assert_eq!(fps.len(), 3);
    }

    #[test]
    fn ssh_github_com_returns_same_fingerprints() {
        let fps = fingerprints_for_host("ssh.github.com", &None).unwrap();
        assert_eq!(fps.len(), 3);
    }

    #[test]
    fn gitlab_com_returns_three_fingerprints() {
        let fps = fingerprints_for_host("gitlab.com", &None).unwrap();
        assert_eq!(fps.len(), 3);
    }

    #[test]
    fn altssh_gitlab_com_returns_same_fingerprints_as_gitlab() {
        let primary = fingerprints_for_host("gitlab.com", &None).unwrap();
        let fallback = fingerprints_for_host("altssh.gitlab.com", &None).unwrap();
        assert_eq!(primary, fallback);
    }

    #[test]
    fn codeberg_org_returns_three_fingerprints() {
        let fps = fingerprints_for_host("codeberg.org", &None).unwrap();
        assert_eq!(fps.len(), 3);
    }

    #[test]
    fn all_github_fingerprints_start_with_sha256_prefix() {
        for fp in GITHUB_FINGERPRINTS {
            assert!(fp.starts_with("SHA256:"), "malformed fingerprint: {fp}");
        }
    }

    #[test]
    fn all_gitlab_fingerprints_start_with_sha256_prefix() {
        for fp in GITLAB_FINGERPRINTS {
            assert!(fp.starts_with("SHA256:"), "malformed fingerprint: {fp}");
        }
    }

    #[test]
    fn all_codeberg_fingerprints_start_with_sha256_prefix() {
        for fp in CODEBERG_FINGERPRINTS {
            assert!(fp.starts_with("SHA256:"), "malformed fingerprint: {fp}");
        }
    }

    #[test]
    fn unknown_host_without_known_hosts_is_error() {
        let result = fingerprints_for_host("git.example.com", &None);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("git.example.com"));
    }

    // ── M14: host_key_trust ──────────────────────────────────────────────────

    /// Helper: write `content` to a fresh temp file and return its path.
    fn write_known_hosts(content: &str) -> (tempfile::TempDir, std::path::PathBuf) {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("known_hosts");
        std::fs::write(&path, content).expect("write");
        (dir, path)
    }

    #[test]
    fn host_key_trust_embeds_well_known_fingerprints() {
        let trust = host_key_trust("github.com", &None).expect("trust");
        assert_eq!(trust.fingerprints.len(), 3);
        assert!(trust.cert_authorities.is_empty());
        assert!(trust.revoked.is_empty());
    }

    #[test]
    fn host_key_trust_pattern_matches_cert_authority() {
        let (_g, path) = write_known_hosts(
            "@cert-authority *.example.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILM+rvN+ot98qgEN796jTiQfZfG1KaT0PtFDJ/XFSqti ca\n",
        );
        let trust = host_key_trust("foo.example.com", &Some(path)).expect("trust");
        assert_eq!(trust.cert_authorities.len(), 1);
        assert_eq!(trust.cert_authorities[0].host_pattern, "*.example.com");
    }

    #[test]
    fn host_key_trust_pattern_excludes_non_match() {
        let (_g, path) = write_known_hosts(
            "@cert-authority *.example.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILM+rvN+ot98qgEN796jTiQfZfG1KaT0PtFDJ/XFSqti ca\n",
        );
        let trust = host_key_trust("other.org", &Some(path)).expect("trust");
        assert!(trust.cert_authorities.is_empty());
    }

    #[test]
    fn host_key_trust_revoked_pattern_matches() {
        let (_g, path) = write_known_hosts(
            "@revoked *.example.com SHA256:revokedfp\n\
             @revoked unrelated.com SHA256:other\n",
        );
        let trust = host_key_trust("foo.example.com", &Some(path)).expect("trust");
        assert_eq!(trust.revoked.len(), 1);
        assert_eq!(trust.revoked[0].fingerprint, "SHA256:revokedfp");
    }

    #[test]
    fn host_key_trust_combines_direct_and_embedded() {
        let (_g, path) = write_known_hosts("github.com SHA256:extra-pin\n");
        let trust = host_key_trust("github.com", &Some(path)).expect("trust");
        // Three embedded + one extra direct.
        assert_eq!(trust.fingerprints.len(), 4);
        assert!(trust.fingerprints.contains(&"SHA256:extra-pin".to_owned()));
    }

    #[test]
    fn host_key_trust_missing_file_returns_embedded_only() {
        let trust = host_key_trust(
            "github.com",
            &Some(std::path::PathBuf::from("/this/path/does/not/exist")),
        )
        .expect("trust");
        assert_eq!(trust.fingerprints.len(), 3);
        assert!(trust.cert_authorities.is_empty());
        assert!(trust.revoked.is_empty());
    }

    #[test]
    fn host_key_trust_empty_for_unknown_host_no_file() {
        // Unlike `fingerprints_for_host`, `host_key_trust` does NOT
        // error on an empty trust set — that is the caller's policy
        // call.  This is the path the AcceptNew policy relies on.
        let trust = host_key_trust("git.example.com", &None).expect("trust");
        assert!(trust.fingerprints.is_empty());
        assert!(trust.cert_authorities.is_empty());
        assert!(trust.revoked.is_empty());
    }
}