Cotton code
427 lines · 14.9 KB · RustRaw
//! The placement applier's rules, over a temp home.//!//! **Every value here is invented.** A placement test writes a credential to a//! disk, so the credentials in it are strings like `not-a-real-token` and the//! paths are under a `tempfile::tempdir()` that goes away with the test.use std::fs;use std::path::{Path, PathBuf};use super::*;fn placement(path: &str, format: Format, env_name: Option<&str>) -> Placement {    Placement {        id: "placement-1".to_string(),        secret_id: "secret-1".to_string(),        path: path.to_string(),        mode: 0o600,        format,        env_name: env_name.map(str::to_string),        applied_hash: None,    }}fn home() -> (tempfile::TempDir, PathBuf) {    let dir = tempfile::tempdir().expect("a temp home");    let path = dir.path().to_path_buf();    (dir, path)}fn mode_bits(path: &Path) -> u32 {    use std::os::unix::fs::PermissionsExt;    fs::metadata(path).expect("the file").permissions().mode() & 0o777}// ── resolve ────────────────────────────────────────────────────────────────#[test]fn a_path_is_a_tilde_path_under_the_home_and_nothing_else() {    let (_guard, home) = home();    assert_eq!(        resolve("~/.config/forge/token", &home),        Ok(home.join(".config").join("forge").join("token"))    );    assert_eq!(resolve("~/token", &home), Ok(home.join("token")));}/// RULE: A password placed on a machine as a file goes under the home folder and nowhere else; an absolute, relative or climbing path is refused by name.#[test]fn every_shape_that_is_not_a_tilde_path_is_refused_by_name() {    let (_guard, home) = home();    for path in [        "/etc/passwd",        "token",        "./token",        "../token",        "~token",        "~",        "$HOME/token",    ] {        assert_eq!(            resolve(path, &home),            Err(PathRefusal::NotInHome),            "{path} should not be in the home"        );    }}#[test]fn a_dot_dot_segment_is_refused_wherever_it_stands() {    let (_guard, home) = home();    for path in ["~/../escape", "~/a/../../escape", "~/a/b/.."] {        assert_eq!(            resolve(path, &home),            Err(PathRefusal::ClimbsOut),            "{path} climbs out"        );    }}#[test]fn a_path_that_names_no_file_is_refused_rather_than_repaired() {    let (_guard, home) = home();    assert_eq!(resolve("~/", &home), Err(PathRefusal::NoName));    assert_eq!(resolve("~/a//b", &home), Err(PathRefusal::NoName));    assert_eq!(resolve("~/./b", &home), Err(PathRefusal::NoName));    assert_eq!(resolve("~/a/", &home), Err(PathRefusal::NoName));}#[test]fn every_refusal_says_something_a_person_can_act_on() {    for refusal in [        PathRefusal::NotInHome,        PathRefusal::ClimbsOut,        PathRefusal::NoName,    ] {        let sentence = refusal.sentence();        assert!(sentence.len() > 20, "{sentence:?} is not a sentence");        // It is drawn under a field on the secret's page, in the middle of a        // line, so it is a plain lower-case clause and never a shouted one.        assert_eq!(sentence, sentence.to_lowercase(), "{sentence:?} shouts");    }}// ── render ─────────────────────────────────────────────────────────────────#[test]fn a_raw_placement_is_the_value_and_no_trailing_newline() {    let bytes = render(Format::Raw, None, "not-a-real-token", None).expect("raw");    assert_eq!(bytes, b"not-a-real-token".to_vec());    assert!(!bytes.ends_with(b"\n"));}#[test]fn a_raw_placement_ignores_whatever_the_file_held() {    let bytes = render(Format::Raw, None, "second", Some("first")).expect("raw");    assert_eq!(bytes, b"second".to_vec());}#[test]fn an_env_placement_with_no_file_writes_one_line() {    let bytes = render(Format::Env, Some("FORGE_TOKEN"), "not-a-real-token", None).expect("env");    assert_eq!(String::from_utf8(bytes).unwrap(), "FORGE_TOKEN=not-a-real-token\n");}#[test]fn an_env_placement_replaces_its_line_in_place_and_keeps_every_other() {    let existing = "# the forge\nFORGE_TOKEN=old\nOTHER=left-alone\n# trailing note\n";    let bytes = render(Format::Env, Some("FORGE_TOKEN"), "new", Some(existing)).expect("env");    assert_eq!(        String::from_utf8(bytes).unwrap(),        "# the forge\nFORGE_TOKEN=new\nOTHER=left-alone\n# trailing note\n"    );}#[test]fn an_env_placement_appends_when_the_file_names_something_else() {    let bytes = render(Format::Env, Some("B"), "two", Some("A=one\n")).expect("env");    assert_eq!(String::from_utf8(bytes).unwrap(), "A=one\nB=two\n");}#[test]fn an_env_placement_finishes_a_file_that_had_no_trailing_newline() {    let bytes = render(Format::Env, Some("B"), "two", Some("A=one")).expect("env");    assert_eq!(String::from_utf8(bytes).unwrap(), "A=one\nB=two\n");}#[test]fn an_exported_line_names_the_same_variable_and_is_the_one_replaced() {    let bytes = render(Format::Env, Some("A"), "two", Some("export A=one\nB=keep\n")).expect("env");    assert_eq!(String::from_utf8(bytes).unwrap(), "A=two\nB=keep\n");}#[test]fn a_second_line_naming_the_same_variable_is_dropped_rather_than_left_to_win() {    let bytes = render(Format::Env, Some("A"), "new", Some("A=one\nB=keep\nA=two\n")).expect("env");    assert_eq!(String::from_utf8(bytes).unwrap(), "A=new\nB=keep\n");}#[test]fn an_env_placement_with_no_name_is_refused() {    assert_eq!(        render(Format::Env, None, "value", None),        Err(RenderRefusal::NoEnvName)    );}#[test]fn an_env_name_is_a_shell_name_or_it_is_refused() {    for name in ["1TOKEN", "MY TOKEN", "MY-TOKEN", "", "TOKEN=", "TOKÉN"] {        assert_eq!(            render(Format::Env, Some(name), "value", None),            Err(RenderRefusal::BadEnvName),            "{name:?} is not an env name"        );    }    for name in ["A", "_A", "FORGE_TOKEN", "a1_B2"] {        assert!(            render(Format::Env, Some(name), "value", None).is_ok(),            "{name:?} is an env name"        );    }}#[test]fn a_value_with_a_newline_is_refused_rather_than_forging_a_second_assignment() {    assert_eq!(        render(Format::Env, Some("A"), "one\nB=two", None),        Err(RenderRefusal::ValueHasNewline)    );    assert_eq!(        render(Format::Env, Some("A"), "one\r\ntwo", None),        Err(RenderRefusal::ValueHasNewline)    );    // A raw placement may hold anything: it IS the file.    assert!(render(Format::Raw, None, "one\ntwo", None).is_ok());}// ── apply_one ──────────────────────────────────────────────────────────────/// RULE: A Linux headless device resolves the placed code credential below its/// own (possibly fake) home and writes it 0600. The systemd applier must never/// leave a credential in its checkout or readable by another local user.#[test]fn a_linux_credential_placement_lands_under_the_fake_home_at_0600() {    let (_guard, home) = home();    let row = placement("~/.cotton-credentials/cotton/code-credential", Format::Raw, None);    let outcome = apply_one(&row, "not-a-real-token", &home);    let target = home.join(".cotton-credentials/cotton/code-credential");    assert_eq!(        outcome,        Outcome::Applied {            id: "placement-1".to_string(),            hash: sha256_hex(b"not-a-real-token"),        }    );    assert_eq!(fs::read(&target).unwrap(), b"not-a-real-token".to_vec());    assert_eq!(mode_bits(&target), 0o600);    assert_eq!(mode_bits(&home.join(".cotton-credentials")), 0o700);    assert_eq!(mode_bits(&home.join(".cotton-credentials/cotton")), 0o700);}#[test]fn an_existing_folder_keeps_the_mode_it_already_had() {    let (_guard, home) = home();    fs::create_dir(home.join("shared")).unwrap();    let before = mode_bits(&home.join("shared"));    let row = placement("~/shared/token", Format::Raw, None);    assert!(matches!(        apply_one(&row, "value", &home),        Outcome::Applied { .. }    ));    assert_eq!(mode_bits(&home.join("shared")), before);}#[test]fn a_second_pass_over_a_stamped_row_writes_nothing() {    let (_guard, home) = home();    let mut row = placement("~/token", Format::Raw, None);    let first = apply_one(&row, "value", &home);    row.applied_hash = first.hash().map(str::to_string);    assert_eq!(        apply_one(&row, "value", &home),        Outcome::Unchanged {            id: "placement-1".to_string()        }    );}#[test]fn a_file_somebody_deleted_comes_back_even_though_the_row_says_it_was_written() {    let (_guard, home) = home();    let mut row = placement("~/token", Format::Raw, None);    row.applied_hash = Some(sha256_hex(b"value"));    let outcome = apply_one(&row, "value", &home);    assert!(matches!(outcome, Outcome::Applied { .. }));    assert_eq!(fs::read(home.join("token")).unwrap(), b"value".to_vec());}#[test]fn a_changed_value_is_written_over_the_old_one() {    let (_guard, home) = home();    let mut row = placement("~/token", Format::Raw, None);    row.applied_hash = Some(apply_one(&row, "old", &home).hash().unwrap().to_string());    let outcome = apply_one(&row, "new", &home);    assert_eq!(        outcome,        Outcome::Applied {            id: "placement-1".to_string(),            hash: sha256_hex(b"new"),        }    );    assert_eq!(fs::read(home.join("token")).unwrap(), b"new".to_vec());}#[test]fn a_file_whose_mode_somebody_widened_is_written_again_at_the_mode_asked_for() {    use std::os::unix::fs::PermissionsExt;    let (_guard, home) = home();    let mut row = placement("~/token", Format::Raw, None);    row.applied_hash = Some(apply_one(&row, "value", &home).hash().unwrap().to_string());    fs::set_permissions(home.join("token"), fs::Permissions::from_mode(0o644)).unwrap();    assert!(matches!(        apply_one(&row, "value", &home),        Outcome::Applied { .. }    ));    assert_eq!(mode_bits(&home.join("token")), 0o600);}#[test]fn an_env_placement_keeps_the_lines_around_it_on_the_real_disk() {    let (_guard, home) = home();    fs::write(home.join(".env.local"), "COTTON_IMAGE_API_KEY=kept\n").unwrap();    let row = placement("~/.env.local", Format::Env, Some("FORGE_TOKEN"));    assert!(matches!(        apply_one(&row, "not-a-real-token", &home),        Outcome::Applied { .. }    ));    assert_eq!(        fs::read_to_string(home.join(".env.local")).unwrap(),        "COTTON_IMAGE_API_KEY=kept\nFORGE_TOKEN=not-a-real-token\n"    );}#[test]fn a_path_outside_the_home_is_refused_and_writes_nothing() {    let (_guard, home) = home();    let outcome = apply_one(&placement("/etc/cotton-token", Format::Raw, None), "v", &home);    assert_eq!(        outcome,        Outcome::Refused {            id: "placement-1".to_string(),            sentence: PathRefusal::NotInHome.sentence().to_string(),        }    );    assert!(!Path::new("/etc/cotton-token").exists());}#[test]fn a_climbing_path_is_refused_and_nothing_lands_beside_the_home() {    let (guard, home) = home();    let outcome = apply_one(&placement("~/../escaped", Format::Raw, None), "v", &home);    assert!(matches!(outcome, Outcome::Refused { .. }));    assert!(!guard.path().parent().unwrap().join("escaped").exists());}#[test]fn a_refusal_and_a_failure_both_leave_the_row_with_no_hash_to_stamp() {    let (_guard, home) = home();    let refused = apply_one(&placement("/etc/x", Format::Raw, None), "v", &home);    assert_eq!(refused.hash(), None);    assert!(refused.problem().is_some());}#[test]fn a_folder_where_the_file_should_be_is_a_failure_and_not_a_panic() {    let (_guard, home) = home();    fs::create_dir(home.join("token")).unwrap();    let outcome = apply_one(&placement("~/token", Format::Raw, None), "v", &home);    match outcome {        Outcome::Failed { sentence, .. } => {            assert!(sentence.starts_with("this Mac could not"), "{sentence}");            assert!(!sentence.contains('v') || !sentence.contains("value"));        }        other => panic!("a folder in the way should fail, not {other:?}"),    }}#[test]fn no_outcome_ever_carries_the_value() {    let (_guard, home) = home();    let secret = "swordfish-is-not-a-real-password";    for row in [        placement("~/ok", Format::Raw, None),        placement("/etc/no", Format::Raw, None),        placement("~/env", Format::Env, Some("1BAD")),    ] {        let outcome = apply_one(&row, secret, &home);        assert!(            !format!("{outcome:?}").contains(secret),            "{outcome:?} carries the value"        );    }}// ── apply_all ──────────────────────────────────────────────────────────────#[test]fn a_pass_answers_one_outcome_per_row_in_order() {    let (_guard, home) = home();    let rows = vec![        Placement {            id: "a".to_string(),            secret_id: "s1".to_string(),            ..placement("~/one", Format::Raw, None)        },        Placement {            id: "b".to_string(),            secret_id: "s2".to_string(),            ..placement("/etc/two", Format::Raw, None)        },        Placement {            id: "c".to_string(),            secret_id: "missing".to_string(),            ..placement("~/three", Format::Raw, None)        },    ];    let pass = apply_all(&rows, &home, &mut |secret_id| match secret_id {        "s1" => Some("one".to_string()),        "s2" => Some("two".to_string()),        _ => None,    });    assert_eq!(pass.outcomes.len(), 3);    assert_eq!(pass.written(), 1);    assert!(matches!(pass.outcomes[0], Outcome::Applied { .. }));    assert!(matches!(pass.outcomes[1], Outcome::Refused { .. }));    assert!(matches!(pass.outcomes[2], Outcome::Failed { .. }));    assert_eq!(        pass.problems().iter().map(|(id, _)| *id).collect::<Vec<_>>(),        vec!["b", "c"]    );}#[test]fn a_secret_the_vault_could_not_open_is_a_failure_that_names_no_value() {    let (_guard, home) = home();    let rows = vec![placement("~/one", Format::Raw, None)];    let pass = apply_all(&rows, &home, &mut |_| None);    match &pass.outcomes[0] {        Outcome::Failed { sentence, .. } => {            assert_eq!(sentence, "this Mac could not open the value for this placement");        }        other => panic!("expected a failure, got {other:?}"),    }    assert!(!home.join("one").exists());}#[test]fn the_format_spelling_round_trips_and_an_unknown_one_is_not_guessed_at() {    assert_eq!(Format::parse("raw"), Some(Format::Raw));    assert_eq!(Format::parse("env"), Some(Format::Env));    assert_eq!(Format::parse("json"), None);    assert_eq!(Format::parse(""), None);    assert_eq!(Format::Raw.as_str(), "raw");    assert_eq!(Format::Env.as_str(), "env");}