shep-daemon 0.18.2

The supervision engine behind shep: process spawning, restart policy, the log plane, watch and cron restarts, and the RPC server
Documentation
//! Tests for writing a batch of environment variables.
//!
//! A batch is all or nothing under one lock: a collision without force writes
//! nothing at all. A dry run has to refuse exactly what the real send would
//! refuse, or it is not telling the truth.

use super::*;

/// A started `web` and a registered dog, for the batch tests below. Two
/// scripts because the dog is a spawn of its own.
async fn env_batch_harness() -> Harness {
    let h = harness(vec![ProcScript::never_exits(); 2]);
    start_app(&h, AppConfig::minimal("web", "./srv")).await;
    h.ctx
        .supervisor
        .start_dog(dog_app("bark"), DogSource::BuiltIn { grants: None })
        .await
        .unwrap();
    h
}

/// The override store as a cold boot would find it: no file, and no record
/// for `name` inside one. A refusal that wrote leaves either.
fn assert_store_untouched(h: &Harness, name: &str) {
    assert!(
        !h.ctx.paths.overrides.exists(),
        "{name}: the refusal created the store file"
    );
    assert!(
        shep_core::overrides::get(&h.ctx.paths.overrides, name)
            .unwrap()
            .is_none(),
        "{name}: the refusal still wrote a record"
    );
}

/// The stored env of `name`, or a panic naming what was there instead.
fn stored_env(h: &Harness, name: &str) -> serde_json::Map<String, serde_json::Value> {
    let record = shep_core::overrides::get(&h.ctx.paths.overrides, name)
        .unwrap()
        .expect("an override record");
    record.fields["env"]
        .as_object()
        .expect("a flat env object")
        .clone()
}

#[tokio::test(start_paused = true)]
async fn a_batch_writes_every_key_under_one_lock() {
    let h = env_batch_harness().await;
    let batch = h
        .ctx
        .supervisor
        .set_sheep_env_batch(
            "web",
            BTreeMap::from([
                ("A".to_string(), "1".to_string()),
                ("B".to_string(), "2".to_string()),
            ]),
            false,
            false,
        )
        .await
        .unwrap()
        .expect("web exists");
    assert_eq!(batch.set, ["A", "B"]);
    assert!(batch.collisions.is_empty());
    let env = stored_env(&h, "web");
    assert_eq!(env["A"], "1");
    assert_eq!(env["B"], "2");
}

#[tokio::test(start_paused = true)]
async fn an_identical_value_is_unchanged_rather_than_a_collision() {
    let h = env_batch_harness().await;
    let entries = BTreeMap::from([("A".to_string(), "1".to_string())]);
    h.ctx
        .supervisor
        .set_sheep_env_batch("web", entries.clone(), false, false)
        .await
        .unwrap();
    let batch = h
        .ctx
        .supervisor
        .set_sheep_env_batch("web", entries, false, false)
        .await
        .unwrap()
        .expect("web exists");
    assert!(batch.set.is_empty());
    assert_eq!(batch.unchanged, ["A"]);
    assert!(batch.collisions.is_empty());
}

#[tokio::test(start_paused = true)]
async fn a_collision_without_force_writes_nothing_at_all() {
    let h = env_batch_harness().await;
    h.ctx
        .supervisor
        .set_sheep_env_batch(
            "web",
            BTreeMap::from([("A".to_string(), "1".to_string())]),
            false,
            false,
        )
        .await
        .unwrap();
    let batch = h
        .ctx
        .supervisor
        .set_sheep_env_batch(
            "web",
            BTreeMap::from([
                ("A".to_string(), "2".to_string()),
                ("B".to_string(), "9".to_string()),
            ]),
            false,
            false,
        )
        .await
        .unwrap()
        .expect("web exists");
    assert_eq!(batch.collisions, ["A"]);
    assert!(batch.set.is_empty());
    assert!(batch.app.is_none());
    let env = stored_env(&h, "web");
    assert_eq!(env["A"], "1", "the colliding key kept its value");
    assert!(
        !env.contains_key("B"),
        "the clean key was not written either"
    );
}

#[tokio::test(start_paused = true)]
async fn force_overwrites_and_reports_the_collision_in_both_lists() {
    let h = env_batch_harness().await;
    h.ctx
        .supervisor
        .set_sheep_env_batch(
            "web",
            BTreeMap::from([("A".to_string(), "1".to_string())]),
            false,
            false,
        )
        .await
        .unwrap();
    let batch = h
        .ctx
        .supervisor
        .set_sheep_env_batch(
            "web",
            BTreeMap::from([("A".to_string(), "2".to_string())]),
            true,
            false,
        )
        .await
        .unwrap()
        .expect("web exists");
    assert_eq!(batch.set, ["A"]);
    assert_eq!(batch.collisions, ["A"]);
    assert_eq!(stored_env(&h, "web")["A"], "2");
}

#[tokio::test(start_paused = true)]
async fn a_dry_run_answers_and_writes_nothing() {
    let h = env_batch_harness().await;
    let batch = h
        .ctx
        .supervisor
        .set_sheep_env_batch(
            "web",
            BTreeMap::from([("A".to_string(), "1".to_string())]),
            false,
            true,
        )
        .await
        .unwrap()
        .expect("web exists");
    assert_eq!(batch.set, ["A"]);
    assert!(batch.app.is_none());
    assert!(
        shep_core::overrides::get(&h.ctx.paths.overrides, "web")
            .unwrap()
            .is_none(),
        "a dry run left a store behind"
    );
}

/// A preview that does not match the outcome is worse than no preview:
/// `normalize` is this door's only validation, so a dry run that skipped
/// it would report `SHEP_NAME` as `set` and then fail on the real send,
/// after the caller had acted on the preview.
#[tokio::test(start_paused = true)]
async fn a_dry_run_refuses_what_the_real_send_would_refuse() {
    let h = env_batch_harness().await;
    let err = h
        .ctx
        .supervisor
        .set_sheep_env_batch(
            "web",
            BTreeMap::from([("SHEP_NAME".to_string(), "nope".to_string())]),
            false,
            true,
        )
        .await
        .unwrap_err();
    assert!(matches!(err, SupervisorError::InvalidEnv(_)), "{err:?}");
    assert!(
        shep_core::overrides::get(&h.ctx.paths.overrides, "web")
            .unwrap()
            .is_none(),
        "a refused dry run left a store behind"
    );
}

/// A refused batch changes nothing, so validating the merged config is
/// moot and the collision report is the whole answer.
#[tokio::test(start_paused = true)]
async fn a_refused_collision_reports_rather_than_validating() {
    let h = env_batch_harness().await;
    h.ctx
        .supervisor
        .set_sheep_env_batch(
            "web",
            BTreeMap::from([("A".to_string(), "1".to_string())]),
            false,
            false,
        )
        .await
        .unwrap();
    let batch = h
        .ctx
        .supervisor
        .set_sheep_env_batch(
            "web",
            BTreeMap::from([
                ("A".to_string(), "2".to_string()),
                ("SHEP_NAME".to_string(), "nope".to_string()),
            ]),
            false,
            false,
        )
        .await
        .unwrap()
        .expect("web exists");
    assert_eq!(batch.collisions, ["A"]);
    assert!(batch.set.is_empty());
    assert!(batch.app.is_none());
}

/// The contract says `app` is `Some` only when something was written.
/// A batch every key of which is already held writes nothing, so
/// `rpc/dispatch.rs` must not record a no-op and rewrite the muster roll for it.
#[tokio::test(start_paused = true)]
async fn a_batch_that_changes_nothing_parks_nothing() {
    let h = env_batch_harness().await;
    let entries = BTreeMap::from([("A".to_string(), "1".to_string())]);
    h.ctx
        .supervisor
        .set_sheep_env_batch("web", entries.clone(), false, false)
        .await
        .unwrap();
    let batch = h
        .ctx
        .supervisor
        .set_sheep_env_batch("web", entries, false, false)
        .await
        .unwrap()
        .expect("web exists");
    assert!(batch.set.is_empty());
    assert_eq!(batch.unchanged, ["A"]);
    assert!(batch.app.is_none(), "nothing was written to record");
}

#[tokio::test(start_paused = true)]
async fn a_batch_refuses_a_dog_and_an_unknown_name() {
    let h = env_batch_harness().await;
    let entries = BTreeMap::from([("A".to_string(), "1".to_string())]);
    assert!(
        h.ctx
            .supervisor
            .set_sheep_env_batch("absent", entries.clone(), false, false)
            .await
            .unwrap()
            .is_none()
    );
    let err = h
        .ctx
        .supervisor
        .set_sheep_env_batch("bark", entries, false, false)
        .await
        .unwrap_err();
    assert!(matches!(err, SupervisorError::IsADog(_)));
}

/// The dog refusal is a security boundary, and four pane doors reach it: a
/// read of a dog's whole config, one env key, a batch, and a bare field.
/// Each is asserted against the store as well as the code, since a refusal
/// that still wrote is the same hole with a better error.
///
/// The batch door's refusal is already pinned by
/// [`a_batch_refuses_a_dog_and_an_unknown_name`] above; what this adds for
/// it is the store half, and for the other three the whole refusal.
#[tokio::test(start_paused = true)]
async fn every_pane_door_refuses_a_dog_and_leaves_the_store_untouched() {
    let h = env_batch_harness().await;

    let err = h.ctx.supervisor.sheep_config("bark").await.unwrap_err();
    assert!(matches!(err, SupervisorError::IsADog(_)), "{err:?}");
    assert_store_untouched(&h, "bark");

    let err = h
        .ctx
        .supervisor
        .set_sheep_env(
            "bark",
            "PATH",
            Some(EnvValue::from("/tmp/evil".to_string())),
        )
        .await
        .unwrap_err();
    assert!(matches!(err, SupervisorError::IsADog(_)), "{err:?}");
    assert_store_untouched(&h, "bark");

    let err = h
        .ctx
        .supervisor
        .set_sheep_env_batch(
            "bark",
            BTreeMap::from([("PATH".to_string(), "/tmp/evil".to_string())]),
            false,
            false,
        )
        .await
        .unwrap_err();
    assert!(matches!(err, SupervisorError::IsADog(_)), "{err:?}");
    assert_store_untouched(&h, "bark");

    let err = h
        .ctx
        .supervisor
        .set_sheep_field("bark", "script", serde_json::json!("/tmp/evil"))
        .await
        .unwrap_err();
    assert!(matches!(err, SupervisorError::IsADog(_)), "{err:?}");
    assert_store_untouched(&h, "bark");
}