summaryrefslogtreecommitdiffstats
path: root/tests/tofu.rs
blob: a26995f20701d036ed32c5af778e3a4d3af1aaa2 (plain) (blame)
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
//! TOFU trust tests.

use std::path::PathBuf;
use std::process::Command;

use zagan_bet::client::database as client_database;
use zagan_bet::tofu::{decide, spki_fingerprint, TrustDecision};

/// Generate a self-signed certificate under target/ and return its DER bytes.
fn make_cert(tag: &str) -> Vec<u8> {
    let dir = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("tofu-certs");
    std::fs::create_dir_all(&dir).unwrap();
    let key = dir.join(format!("{tag}.key"));
    let pem = dir.join(format!("{tag}.pem"));
    if !pem.exists() {
        let status = Command::new("openssl")
            .args([
                "req",
                "-x509",
                "-newkey",
                "rsa:2048",
                "-keyout",
                key.to_str().unwrap(),
                "-out",
                pem.to_str().unwrap(),
                "-days",
                "365",
                "-nodes",
                "-subj",
                "/CN=zagan-test",
            ])
            .status()
            .expect("openssl must be available for tests");
        assert!(status.success(), "openssl failed");
    }
    // Convert PEM to DER.
    let status = Command::new("openssl")
        .args([
            "x509",
            "-in",
            pem.to_str().unwrap(),
            "-outform",
            "DER",
            "-out",
            dir.join(format!("{tag}.der")).to_str().unwrap(),
        ])
        .status()
        .unwrap();
    assert!(status.success());
    std::fs::read(dir.join(format!("{tag}.der"))).unwrap()
}

/// Independent expected value computed with openssl, not with our code:
/// SHA-256 over the SPKI DER of the certificate.
fn openssl_spki_sha256(pem_path: &str) -> String {
    let out = Command::new("sh")
        .arg("-c")
        .arg(format!(
            "openssl x509 -in {pem} -pubkey -noout | \
             openssl pkey -pubin -outform DER | sha256sum",
            pem = pem_path
        ))
        .output()
        .unwrap();
    assert!(out.status.success());
    let s = String::from_utf8(out.stdout).unwrap();
    s.split_whitespace().next().unwrap().to_string()
}

#[test]
fn fingerprint_is_sha256_of_spki() {
    let der = make_cert("primary");
    let dir = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("tofu-certs");
    let expected = openssl_spki_sha256(dir.join("primary.pem").to_str().unwrap());

    let fp = spki_fingerprint(&der).expect("must parse the test certificate");
    assert_eq!(
        fp, expected,
        "fingerprint must equal openssl's SPKI SHA-256"
    );
}

#[test]
fn fingerprint_rejects_garbage() {
    assert!(spki_fingerprint(b"not a certificate").is_err());
}

#[test]
fn first_contact_trusts_and_records() {
    let observed = "ab12cd34";
    assert_eq!(decide(None, observed), TrustDecision::TrustNew);
}

#[test]
fn matching_key_is_trusted() {
    assert_eq!(decide(Some("ab12cd34"), "ab12cd34"), TrustDecision::Trusted);
}

#[test]
fn changed_key_is_mismatch_with_details() {
    let d = decide(Some("ab12cd34"), "ef56ab78");
    match d {
        TrustDecision::Mismatch { expected, actual } => {
            assert_eq!(expected, "ab12cd34");
            assert_eq!(actual, "ef56ab78");
        }
        other => panic!("expected Mismatch, got {:?}", other),
    }
}

/// Fingerprint persistence roundtrip in the client database.
#[test]
fn fingerprint_roundtrip_in_client_db() {
    let db_path = PathBuf::from(env!("CARGO_TARGET_TMPDIR"))
        .join("tofu-roundtrip.db")
        .to_string_lossy()
        .into_owned();
    let _ = std::fs::remove_file(&db_path);
    let conn = rusqlite::Connection::open(&db_path).unwrap();
    client_database::init_db(&conn);

    // Host starts unknown.
    assert_eq!(client_database::get_fingerprint(&conn, "host1"), None);

    // Save, read back.
    client_database::save_fingerprint(&conn, "host1", "deadbeef").unwrap();
    assert_eq!(
        client_database::get_fingerprint(&conn, "host1"),
        Some("deadbeef".to_string())
    );

    // Forget clears it.
    client_database::forget_host(&conn, "host1").unwrap();
    assert_eq!(client_database::get_fingerprint(&conn, "host1"), None);
}

#[test]
fn a_changed_key_error_names_both_fingerprints() {
    let error = zagan_bet::client::transport::TransportError::KeyChanged {
        expected: "aaaa".to_string(),
        observed: "bbbb".to_string(),
    };
    let text = error.to_string();

    assert!(text.contains("HOST KEY CHANGED"), "{text}");
    assert!(text.contains("aaaa"), "{text}");
    assert!(text.contains("bbbb"), "{text}");
}