summaryrefslogtreecommitdiff
path: root/rust-bindings/tests/sign/mod.rs
blob: aa2a59a0aaa5b886bff2284ef56b4d47b4ea4015 (plain)
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
use std::process::Command;

use ostree::prelude::SignExt;
use ostree::prelude::*;
use ostree::Sign;
use ostree::{gio, glib};

#[test]
fn sign_api_should_work() {
    let dummy_sign = ostree::Sign::by_name("dummy").unwrap();
    assert_eq!(dummy_sign.name().unwrap(), "dummy");

    let result = ostree::prelude::SignExt::data(
        &dummy_sign,
        &glib::Bytes::from_static(b"1234"),
        gio::Cancellable::NONE,
    );
    assert!(result.is_err());

    let result = dummy_sign.data_verify(&glib::Bytes::from_static(b"1234"), &"1234".to_variant());
    assert!(result.is_err());

    let result = ostree::Sign::by_name("NOPE");
    assert!(result.is_err());
}

fn inner_sign_ed25519<T: SignExt>(signer: T) {
    assert_eq!(signer.name().unwrap(), "ed25519");

    let td = tempfile::tempdir().unwrap();
    let path = td.path();

    // Horrible bits to reuse libtest shell script code to generate keys
    let pwd = std::env::current_dir().unwrap();
    let cmd = format!(
        r#". {:?}/tests/libtest.sh
gen_ed25519_keys
echo $ED25519PUBLIC > ed25519.public
echo $ED25519SEED > ed25519.seed
echo $ED25519SECRET > ed25519.secret
"#,
        pwd
    );
    let s = Command::new("bash")
        .env("G_TEST_SRCDIR", pwd)
        .current_dir(path)
        .args(["-euo", "pipefail"])
        .args(["-c", cmd.as_str()])
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .unwrap();
    assert!(s.success());

    let seckey = std::fs::read_to_string(path.join("ed25519.secret")).unwrap();
    let seckey = seckey.to_variant();
    signer.set_sk(&seckey).unwrap();
    let pubkey = std::fs::read_to_string(path.join("ed25519.public")).unwrap();
    let pubkey = pubkey.to_variant();
    signer.add_pk(&pubkey).unwrap();

    let payload = &glib::Bytes::from_static(b"1234");

    let signature = signer.data(payload, gio::Cancellable::NONE).unwrap();
    let signatures = [&*signature].to_variant();

    let msg = signer.data_verify(payload, &signatures).unwrap().unwrap();
    assert!(msg.starts_with("ed25519: Signature verified successfully"));

    assert!(signer
        .data_verify(&glib::Bytes::from_static(b""), &signatures)
        .is_err());

    let badsigs = [b"".as_slice()].to_variant();

    let e = signer.data_verify(payload, &badsigs).err().unwrap();
    assert!(e
        .to_string()
        .contains("Invalid signature length of 0 bytes"))
}

#[test]
fn sign_ed25519() {
    if let Some(signer) = Sign::by_name("ed25519").ok() {
        inner_sign_ed25519(signer)
    }
}