use serde_json::{json, Value};
use stratum_node_core::{
AclMode, ContainerPath, ContainerPathError, JobCeilings, JobLimits, ManifestRule, MilliCpus,
ParsePodPathError, PodMethod, ValidManifest, WorkspaceMode,
};
fn image() -> String {
format!("sha256:{}", "ab".repeat(32))
}
fn base() -> Value {
json!({
"name": "report",
"version": "1.0.0",
"image_id": image(),
"profile": "job",
"containers": [
{"path": "reports-input/", "modes": ["Read"], "operations": ["GET", "HEAD"]},
{"path": "reports/", "modes": ["Read", "Write"], "operations": ["GET", "HEAD", "PUT"]}
],
"workspace": "none",
"max_body_bytes": 65536,
"limits": {"cpus": 1.5, "memory_bytes": 268_435_456, "pids": 64, "tmp_bytes": 16_777_216, "timeout_secs": 300}
})
}
fn refused(manifest: &Value) -> (ManifestRule, String) {
let err = ValidManifest::from_value(manifest, &JobCeilings::DEFAULT)
.expect_err("the manifest must be refused");
(err.rule(), err.field().to_owned())
}
fn with(edit: impl FnOnce(&mut Value)) -> Value {
let mut m = base();
edit(&mut m);
m
}
#[test]
fn e3b_5_the_base_manifest_is_valid_and_keeps_its_limits() {
let valid = ValidManifest::from_value(&base(), &JobCeilings::DEFAULT).expect("valid");
let limits = valid.limits();
assert_eq!(limits.cpus, MilliCpus::new(1500), "cpus as millicpus");
assert_eq!(limits.cpus.cpu_max(), "150000 100000", "cpu.max");
assert_eq!(limits.memory_bytes, 268_435_456, "memory");
assert_eq!(limits.timeout_secs, 300, "timeout");
let m = valid.manifest();
assert_eq!(
m.containers[1].modes,
[AclMode::Read, AclMode::Write],
"modes"
);
assert!(m.containers[1].allows(PodMethod::Put), "PUT allowed");
assert_eq!(m.workspace, WorkspaceMode::None, "workspace");
let again = ValidManifest::parse(valid.to_json().as_bytes(), &JobCeilings::DEFAULT)
.expect("the stored form reads back");
assert_eq!(again, valid, "round trip through the stored form");
}
#[test]
fn e3b_5_omitted_limits_take_the_contract_defaults() {
let m = with(|m| {
m.as_object_mut().expect("object").remove("limits");
});
let valid = ValidManifest::from_value(&m, &JobCeilings::DEFAULT).expect("valid");
assert_eq!(
valid.limits(),
JobLimits::DEFAULT,
"1 CPU, 512 MiB, 128, 64 MiB, 600 s"
);
let partial = with(|m| m["limits"] = json!({"pids": 32}));
let valid = ValidManifest::from_value(&partial, &JobCeilings::DEFAULT).expect("valid");
assert_eq!(valid.limits().pids, 32, "named limit kept");
assert_eq!(
valid.limits().cpus,
JobLimits::DEFAULT.cpus,
"others defaulted"
);
}
#[test]
fn e3b_5_refuses_a_mode_other_than_read_or_write() {
for mode in ["Control", "Append", "read", "Write2"] {
let m = with(|m| m["containers"][1]["modes"] = json!(["Read", mode]));
assert_eq!(
refused(&m),
(ManifestRule::Mode, "containers[1].modes".to_owned()),
"{mode}"
);
}
for modes in [
json!(["Write"]),
json!(["Write", "Read"]),
json!([]),
json!(["Read", "Read"]),
] {
let m = with(|m| m["containers"][0]["modes"] = modes.clone());
assert_eq!(
refused(&m),
(ManifestRule::ModeSet, "containers[0].modes".to_owned()),
"{modes}"
);
}
}
#[test]
fn e3b_5_refuses_paths_that_fail_the_path_rule() {
for path in [
"",
"/reports/",
"reports",
"reports//",
"a//b/",
"./",
"a/../",
"a/./b/",
"a%2Fb/",
"profile/",
"profile/x/",
"R\u{e9}ports/",
"a b/",
"a?b/",
] {
let m = with(|m| m["containers"][0]["path"] = json!(path));
assert_eq!(
refused(&m),
(ManifestRule::Path, "containers[0].path".to_owned()),
"{path:?}"
);
}
for path in [
"profiles/",
"Profile/",
"reports.acl/",
"a/b/c/",
"x~y_z-1.2/",
] {
assert!(ContainerPath::parse(path).is_ok(), "{path} is allowed");
}
}
#[test]
fn e3b_5_path_refusals_name_the_broken_part_of_the_rule() {
let cases = [
("", ContainerPathError::Empty),
("/a/", ContainerPathError::LeadingSlash),
("a%20/", ContainerPathError::Percent),
("a", ContainerPathError::NotAContainer),
(
"a/../",
ContainerPathError::Shape(ParsePodPathError::DotSegment),
),
(
"a//",
ContainerPathError::Shape(ParsePodPathError::EmptySegment),
),
(
"a:b/",
ContainerPathError::Shape(ParsePodPathError::ForbiddenCharacter),
),
("profile/", ContainerPathError::Profile),
];
for (path, expected) in cases {
assert_eq!(ContainerPath::parse(path), Err(expected), "{path:?}");
}
}
#[test]
fn e3b_5_refuses_operations_outside_get_head_put_delete() {
for op in ["POST", "PATCH", "OPTIONS", "get", "CONNECT"] {
let m = with(|m| m["containers"][1]["operations"] = json!(["GET", op]));
assert_eq!(
refused(&m),
(
ManifestRule::Operation,
"containers[1].operations".to_owned()
),
"{op}"
);
}
for ops in [json!([]), json!(["GET", "GET"])] {
let m = with(|m| m["containers"][1]["operations"] = ops.clone());
assert_eq!(refused(&m).0, ManifestRule::OperationSet, "{ops}");
}
}
#[test]
fn e3b_5_refuses_put_or_delete_without_write() {
for op in ["PUT", "DELETE"] {
let m = with(|m| m["containers"][0]["operations"] = json!(["GET", op]));
assert_eq!(
refused(&m),
(
ManifestRule::WriteOperationWithoutWrite,
"containers[0].operations".to_owned()
),
"{op}"
);
}
}
#[test]
fn e3b_5_refuses_two_entries_for_one_path() {
let m = with(|m| m["containers"][1]["path"] = json!("reports-input/"));
assert_eq!(
refused(&m),
(ManifestRule::DuplicatePath, "containers[1].path".to_owned()),
"duplicate"
);
}
#[test]
fn e3b_5_refuses_zero_or_more_than_eight_containers() {
let empty = with(|m| m["containers"] = json!([]));
assert_eq!(refused(&empty).0, ManifestRule::ContainerCount, "zero");
let nine: Vec<Value> = (0..9)
.map(|i| json!({"path": format!("c{i}/"), "modes": ["Read"], "operations": ["GET"]}))
.collect();
let many = with(|m| m["containers"] = Value::Array(nine.clone()));
assert_eq!(refused(&many).0, ManifestRule::ContainerCount, "nine");
let eight = with(|m| m["containers"] = Value::Array(nine[..8].to_vec()));
assert!(
ValidManifest::from_value(&eight, &JobCeilings::DEFAULT).is_ok(),
"eight are allowed"
);
}
#[test]
fn e3b_5_refuses_a_limit_that_is_zero_or_negative() {
for key in ["cpus", "memory_bytes", "pids", "tmp_bytes", "timeout_secs"] {
for bad in [json!(0), json!(-1), json!(-0.5)] {
let m = with(|m| m["limits"][key] = bad.clone());
assert_eq!(
refused(&m),
(ManifestRule::LimitNotPositive, format!("limits.{key}")),
"{key} = {bad}"
);
}
}
let fractional = with(|m| m["limits"]["pids"] = json!(1.5));
assert_eq!(
refused(&fractional).0,
ManifestRule::LimitNotPositive,
"pids 1.5"
);
let fine = with(|m| m["limits"]["cpus"] = json!(0.0005));
assert_eq!(
refused(&fine),
(ManifestRule::LimitNotPositive, "limits.cpus".to_owned()),
"four decimal places"
);
let text = with(|m| m["limits"]["cpus"] = json!("1"));
assert_eq!(refused(&text).0, ManifestRule::WrongType, "cpus as text");
}
#[test]
fn e3b_5_refuses_a_limit_above_the_ceiling() {
let ceilings = JobCeilings::DEFAULT;
let cases = [
("cpus", json!(4.001)),
("memory_bytes", json!(ceilings.memory_bytes + 1)),
("pids", json!(ceilings.pids + 1)),
("tmp_bytes", json!(ceilings.tmp_bytes + 1)),
("timeout_secs", json!(ceilings.timeout_secs + 1)),
];
for (key, value) in cases {
let m = with(|m| {
m["limits"][key] = value.clone();
if key == "tmp_bytes" {
m["limits"]["memory_bytes"] = json!(ceilings.memory_bytes);
}
});
assert_eq!(
refused(&m),
(ManifestRule::LimitAboveCeiling, format!("limits.{key}")),
"{key}"
);
}
let at = with(|m| m["limits"]["cpus"] = json!(4));
assert!(
ValidManifest::from_value(&at, &ceilings).is_ok(),
"at the ceiling is allowed"
);
}
#[test]
fn e3b_5_a_default_above_a_lowered_ceiling_is_refused_at_launch() {
let m = with(|m| {
m.as_object_mut().expect("object").remove("limits");
});
let valid = ValidManifest::from_value(&m, &JobCeilings::DEFAULT).expect("valid");
let lowered = JobCeilings {
timeout_secs: 300,
..JobCeilings::DEFAULT
};
let err = valid
.check_ceilings(&lowered)
.expect_err("600 s default above 300");
assert_eq!(err.rule(), ManifestRule::LimitAboveCeiling, "rule");
assert_eq!(err.field(), "limits.timeout_secs", "field");
}
#[test]
fn e3b_5_refuses_tmp_bytes_at_or_above_memory_bytes() {
for tmp in [268_435_456_u64, 268_435_457] {
let m = with(|m| m["limits"]["tmp_bytes"] = json!(tmp));
assert_eq!(
refused(&m),
(
ManifestRule::TmpNotBelowMemory,
"limits.tmp_bytes".to_owned()
),
"{tmp}"
);
}
}
#[test]
fn e3b_5_refuses_memory_the_engine_cannot_apply_exactly() {
for (memory, tmp) in [
(6_291_455_u64, 1_048_576_u64),
(4_194_304, 1_048_576),
(268_435_457, 1_048_576),
] {
let m = with(|m| {
m["limits"]["memory_bytes"] = json!(memory);
m["limits"]["tmp_bytes"] = json!(tmp);
});
assert_eq!(
refused(&m),
(
ManifestRule::MemoryNotUsable,
"limits.memory_bytes".to_owned()
),
"{memory}"
);
}
let ok = with(|m| {
m["limits"]["memory_bytes"] = json!(6_291_456_u64);
m["limits"]["tmp_bytes"] = json!(1_048_576_u64);
});
assert!(
ValidManifest::from_value(&ok, &JobCeilings::DEFAULT).is_ok(),
"6 MiB is accepted"
);
}
#[test]
fn e3b_5_refuses_a_timeout_below_240_seconds() {
let m = with(|m| m["limits"]["timeout_secs"] = json!(239));
assert_eq!(
refused(&m),
(
ManifestRule::TimeoutTooShort,
"limits.timeout_secs".to_owned()
),
"239"
);
let ok = with(|m| m["limits"]["timeout_secs"] = json!(240));
assert!(
ValidManifest::from_value(&ok, &JobCeilings::DEFAULT).is_ok(),
"240 is allowed"
);
}
#[test]
fn e3b_5_refuses_unknown_members_everywhere() {
let top = with(|m| m["extra"] = json!(1));
assert_eq!(
refused(&top),
(ManifestRule::UnknownMember, "extra".to_owned()),
"top"
);
let entry = with(|m| m["containers"][0]["default"] = json!(true));
assert_eq!(
refused(&entry),
(
ManifestRule::UnknownMember,
"containers[0].default".to_owned()
),
"entry"
);
let limits = with(|m| m["limits"]["storage_bytes"] = json!(1));
assert_eq!(
refused(&limits),
(
ManifestRule::UnknownMember,
"limits.storage_bytes".to_owned()
),
"limits"
);
}
#[test]
fn e3b_5_refuses_shape_errors_with_their_own_rule() {
let missing = with(|m| {
m.as_object_mut().expect("object").remove("max_body_bytes");
});
assert_eq!(
refused(&missing),
(ManifestRule::MissingMember, "max_body_bytes".to_owned()),
"max_body_bytes is required"
);
let zero_body = with(|m| m["max_body_bytes"] = json!(0));
assert_eq!(
refused(&zero_body).0,
ManifestRule::MaxBodyBytes,
"zero body"
);
let profile = with(|m| m["profile"] = json!("service"));
assert_eq!(refused(&profile).0, ManifestRule::Profile, "profile");
let workspace = with(|m| m["workspace"] = json!("rw"));
assert_eq!(refused(&workspace).0, ManifestRule::Workspace, "workspace");
let image = with(|m| m["image_id"] = json!("busybox:latest"));
assert_eq!(refused(&image).0, ManifestRule::ImageId, "image");
let name = with(|m| m["name"] = json!(""));
assert_eq!(refused(&name).0, ManifestRule::Label, "empty name");
let control = with(|m| m["version"] = json!("1\n2"));
assert_eq!(
refused(&control).0,
ManifestRule::Label,
"control in version"
);
let err = ValidManifest::parse(b"[1]", &JobCeilings::DEFAULT).expect_err("not an object");
assert_eq!(err.rule(), ManifestRule::Json, "array");
let err = ValidManifest::parse(b"{", &JobCeilings::DEFAULT).expect_err("not json");
assert_eq!(err.rule(), ManifestRule::Json, "truncated");
}
#[test]
fn e3b_5_a_refusal_never_echoes_a_value() {
let secret_looking = "s3cr3t-value-that-must-not-appear";
let m = with(|m| m["containers"][0]["path"] = json!(secret_looking));
let err = ValidManifest::from_value(&m, &JobCeilings::DEFAULT).expect_err("refused");
assert!(
!err.to_string().contains(secret_looking),
"the message names the member, not its value: {err}"
);
}
#[test]
fn e3b_5_cpus_round_trips_as_a_decimal_without_floating_point_after_parsing() {
for (text, milli) in [
("1", 1000),
("0.5", 500),
("1.25", 1250),
("0.001", 1),
("3.999", 3999),
] {
let cpus: MilliCpus = serde_json::from_str(text).expect("parse");
assert_eq!(cpus.get(), milli, "{text}");
assert_eq!(
serde_json::to_string(&cpus).expect("write"),
text,
"{text} writes back"
);
assert_eq!(cpus.nano_cpus(), u64::from(milli) * 1_000_000, "NanoCpus");
}
}