# Independent acceptance tests for docs/checks.md (instinct check); every line is literal Rust via TAG.
# Source of truth for tests/check_contract.rs: regenerate with hxc export-rust tests/check_contract.hlx
TAG # // Independent acceptance tests for `instinct check`, written from docs/checks.md only.
TAG # // Every case runs the real binary in a fresh HOME / XDG / store environment, and every command is wrapped by a
TAG # // before/after snapshot of that whole environment (and the working directory): nothing may be created or changed.
TAG # use std::io::Write;
TAG # use std::path::{Path, PathBuf};
TAG # use std::process::{Command, Stdio};
TAG # use std::sync::atomic::{AtomicUsize, Ordering};
TAG # use std::time::Duration;
TAG # fn bin() -> &'static str {
TAG # env!("CARGO_BIN_EXE_instinct")
TAG # }
TAG # // ---------------------------------------------------------------- minimal JSON reader for the outputs
TAG # #[derive(Debug, Clone, PartialEq)]
TAG # enum J {
TAG # Null,
TAG # Bool(bool),
TAG # Num(String),
TAG # Str(String),
TAG # Arr(Vec<J>),
TAG # Obj(Vec<(String, J)>),
TAG # }
TAG # impl J {
TAG # fn get(&self, k: &str) -> Option<&J> {
TAG # match self {
TAG # J::Obj(v) => v.iter().find(|(a, _)| a == k).map(|(_, b)| b),
TAG # _ => None,
TAG # }
TAG # }
TAG # fn as_str(&self) -> Option<&str> {
TAG # match self {
TAG # J::Str(s) => Some(s),
TAG # _ => None,
TAG # }
TAG # }
TAG # }
TAG # struct P<'a> {
TAG # b: &'a [u8],
TAG # i: usize,
TAG # }
TAG # impl<'a> P<'a> {
TAG # fn ws(&mut self) {
TAG # while self.i < self.b.len() && matches!(self.b[self.i], b' ' | b'\n' | b'\t' | b'\r') {
TAG # self.i += 1;
TAG # }
TAG # }
TAG # fn lit(&mut self, w: &str, v: J) -> Result<J, String> {
TAG # if self.b[self.i..].starts_with(w.as_bytes()) {
TAG # self.i += w.len();
TAG # Ok(v)
TAG # } else {
TAG # Err(format!("bad literal at {}", self.i))
TAG # }
TAG # }
TAG # fn hex4(&mut self) -> Result<u32, String> {
TAG # let h = self.b.get(self.i..self.i + 4).ok_or("short \\u")?;
TAG # let h = std::str::from_utf8(h).map_err(|e| e.to_string())?;
TAG # self.i += 4;
TAG # u32::from_str_radix(h, 16).map_err(|e| e.to_string())
TAG # }
TAG # fn string(&mut self) -> Result<String, String> {
TAG # if self.b.get(self.i) != Some(&b'"') {
TAG # return Err(format!("expected string at {}", self.i));
TAG # }
TAG # self.i += 1;
TAG # let mut out: Vec<u8> = Vec::new();
TAG # loop {
TAG # let c = *self.b.get(self.i).ok_or("unterminated string")?;
TAG # self.i += 1;
TAG # match c {
TAG # b'"' => return String::from_utf8(out).map_err(|e| e.to_string()),
TAG # b'\\' => {
TAG # let e = *self.b.get(self.i).ok_or("bad escape")?;
TAG # self.i += 1;
TAG # let ch = match e {
TAG # b'"' => '"',
TAG # b'\\' => '\\',
TAG # b'/' => '/',
TAG # b'b' => '\u{8}',
TAG # b'f' => '\u{c}',
TAG # b'n' => '\n',
TAG # b'r' => '\r',
TAG # b't' => '\t',
TAG # b'u' => {
TAG # let hi = self.hex4()?;
TAG # if (0xD800..0xDC00).contains(&hi) {
TAG # if self.b.get(self.i) != Some(&b'\\') || self.b.get(self.i + 1) != Some(&b'u') {
TAG # return Err("lone surrogate".into());
TAG # }
TAG # self.i += 2;
TAG # let lo = self.hex4()?;
TAG # char::from_u32(0x10000 + ((hi - 0xD800) << 10) + (lo.wrapping_sub(0xDC00)))
TAG # .ok_or("bad pair")?
TAG # } else {
TAG # char::from_u32(hi).ok_or("lone surrogate")?
TAG # }
TAG # }
TAG # _ => return Err("bad escape".into()),
TAG # };
TAG # let mut buf = [0u8; 4];
TAG # out.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes());
TAG # }
TAG # _ => out.push(c),
TAG # }
TAG # }
TAG # }
TAG # fn val(&mut self) -> Result<J, String> {
TAG # self.ws();
TAG # match self.b.get(self.i).copied() {
TAG # None => Err("eof".into()),
TAG # Some(b'{') => {
TAG # self.i += 1;
TAG # let mut v = Vec::new();
TAG # self.ws();
TAG # if self.b.get(self.i) == Some(&b'}') {
TAG # self.i += 1;
TAG # return Ok(J::Obj(v));
TAG # }
TAG # loop {
TAG # self.ws();
TAG # let k = self.string()?;
TAG # self.ws();
TAG # if self.b.get(self.i) != Some(&b':') {
TAG # return Err("expected colon".into());
TAG # }
TAG # self.i += 1;
TAG # let x = self.val()?;
TAG # v.push((k, x));
TAG # self.ws();
TAG # match self.b.get(self.i) {
TAG # Some(b',') => self.i += 1,
TAG # Some(b'}') => {
TAG # self.i += 1;
TAG # return Ok(J::Obj(v));
TAG # }
TAG # _ => return Err("bad object".into()),
TAG # }
TAG # }
TAG # }
TAG # Some(b'[') => {
TAG # self.i += 1;
TAG # let mut v = Vec::new();
TAG # self.ws();
TAG # if self.b.get(self.i) == Some(&b']') {
TAG # self.i += 1;
TAG # return Ok(J::Arr(v));
TAG # }
TAG # loop {
TAG # v.push(self.val()?);
TAG # self.ws();
TAG # match self.b.get(self.i) {
TAG # Some(b',') => self.i += 1,
TAG # Some(b']') => {
TAG # self.i += 1;
TAG # return Ok(J::Arr(v));
TAG # }
TAG # _ => return Err("bad array".into()),
TAG # }
TAG # }
TAG # }
TAG # Some(b'"') => Ok(J::Str(self.string()?)),
TAG # Some(b't') => self.lit("true", J::Bool(true)),
TAG # Some(b'f') => self.lit("false", J::Bool(false)),
TAG # Some(b'n') => self.lit("null", J::Null),
TAG # Some(_) => {
TAG # let st = self.i;
TAG # while self.i < self.b.len() && matches!(self.b[self.i], b'-' | b'+' | b'.' | b'e' | b'E' | b'0'..=b'9') {
TAG # self.i += 1;
TAG # }
TAG # if st == self.i {
TAG # return Err(format!("unexpected byte at {st}"));
TAG # }
TAG # Ok(J::Num(String::from_utf8_lossy(&self.b[st..self.i]).into_owned()))
TAG # }
TAG # }
TAG # }
TAG # }
TAG # fn parse_json(s: &str) -> Result<J, String> {
TAG # let mut p = P { b: s.as_bytes(), i: 0 };
TAG # let v = p.val()?;
TAG # p.ws();
TAG # if p.i != p.b.len() {
TAG # return Err("trailing data".into());
TAG # }
TAG # Ok(v)
TAG # }
TAG # fn to_s(j: &J) -> String {
TAG # match j {
TAG # J::Null => "null".into(),
TAG # J::Bool(b) => b.to_string(),
TAG # J::Num(n) => n.clone(),
TAG # J::Str(s) => format!("{s:?}"),
TAG # J::Arr(v) => format!("[{}]", v.iter().map(to_s).collect::<Vec<_>>().join(",")),
TAG # J::Obj(v) => format!("{{{}}}", v.iter().map(|(k, x)| format!("{k:?}:{}", to_s(x))).collect::<Vec<_>>().join(",")),
TAG # }
TAG # }
TAG # // ---------------------------------------------------------------- isolated environment and process runner
TAG # struct Out {
TAG # code: Option<i32>,
TAG # out: Vec<u8>,
TAG # err: Vec<u8>,
TAG # }
TAG # impl Out {
TAG # fn text(&self) -> String {
TAG # String::from_utf8_lossy(&self.out).into_owned()
TAG # }
TAG # }
TAG # fn fnv(b: &[u8]) -> u64 {
TAG # let mut h = 0xcbf29ce484222325u64;
TAG # for x in b {
TAG # h ^= *x as u64;
TAG # h = h.wrapping_mul(0x100000001b3);
TAG # }
TAG # h
TAG # }
TAG # fn walk(base: &Path, dir: &Path, acc: &mut Vec<String>) {
TAG # let mut ents: Vec<_> = match std::fs::read_dir(dir) {
TAG # Ok(r) => r.filter_map(|e| e.ok()).collect(),
TAG # Err(_) => return,
TAG # };
TAG # ents.sort_by_key(|e| e.file_name());
TAG # for e in ents {
TAG # let p = e.path();
TAG # let rel = p.strip_prefix(base).unwrap().display().to_string();
TAG # let md = match std::fs::symlink_metadata(&p) {
TAG # Ok(m) => m,
TAG # Err(_) => continue,
TAG # };
TAG # if md.is_dir() {
TAG # acc.push(format!("d {rel}"));
TAG # walk(base, &p, acc);
TAG # } else {
TAG # let b = std::fs::read(&p).unwrap_or_default();
TAG # acc.push(format!("f {rel} {} {:x}", b.len(), fnv(&b)));
TAG # }
TAG # }
TAG # }
TAG # struct Env {
TAG # root: PathBuf,
TAG # }
TAG # impl Env {
TAG # fn new(name: &str) -> Env {
TAG # static N: AtomicUsize = AtomicUsize::new(0);
TAG # let root = std::env::temp_dir().join(format!(
TAG # "instinct-check-contract-{}-{}-{name}",
TAG # std::process::id(),
TAG # N.fetch_add(1, Ordering::Relaxed)
TAG # ));
TAG # let _ = std::fs::remove_dir_all(&root);
TAG # for d in ["home", "data", "local", "cfg", "state", "cache", "cwd", "in"] {
TAG # std::fs::create_dir_all(root.join(d)).unwrap();
TAG # }
TAG # Env { root }
TAG # }
TAG # fn bank(&self) -> PathBuf {
TAG # let base = if cfg!(windows) { "local" } else { "data" };
TAG # self.root.join(base).join("instinct").join("bank.hxdb")
TAG # }
TAG # fn put(&self, name: &str, bytes: &[u8]) -> PathBuf {
TAG # let p = self.root.join("in").join(name);
TAG # std::fs::write(&p, bytes).unwrap();
TAG # p
TAG # }
TAG # fn snapshot(&self) -> Vec<String> {
TAG # let mut acc = Vec::new();
TAG # walk(&self.root, &self.root, &mut acc);
TAG # acc
TAG # }
TAG # fn exec_env(&self, args: &[&str], stdin: &[u8], envs: &[(&str, &str)]) -> Out {
TAG # let before = self.snapshot();
TAG # let mut c = Command::new(bin());
TAG # c.args(args)
TAG # .current_dir(self.root.join("cwd"))
TAG # .env("HOME", self.root.join("home"))
TAG # .env("XDG_DATA_HOME", self.root.join("data"))
TAG # .env("XDG_CONFIG_HOME", self.root.join("cfg"))
TAG # .env("XDG_STATE_HOME", self.root.join("state"))
TAG # .env("XDG_CACHE_HOME", self.root.join("cache"))
TAG # .env("LOCALAPPDATA", self.root.join("local"))
TAG # .env("APPDATA", self.root.join("local"));
TAG # for (k, _) in std::env::vars() {
TAG # if k.starts_with("INSTINCT_") {
TAG # c.env_remove(k);
TAG # }
TAG # }
TAG # for (k, v) in envs {
TAG # c.env(k, v);
TAG # }
TAG # c.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped());
TAG # let mut child = c.spawn().unwrap();
TAG # let mut si = child.stdin.take().unwrap();
TAG # let data = stdin.to_vec();
TAG # let w = std::thread::spawn(move || {
TAG # let _ = si.write_all(&data);
TAG # });
TAG # let (tx, rx) = std::sync::mpsc::channel();
TAG # std::thread::spawn(move || {
TAG # let _ = tx.send(child.wait_with_output());
TAG # });
TAG # let o = rx.recv_timeout(Duration::from_secs(180)).expect("instinct check hung").unwrap();
TAG # let _ = w.join();
TAG # let after = self.snapshot();
TAG # assert_eq!(before, after, "command changed the filesystem: {args:?}");
TAG # if std::env::var_os("CHECK_CONTRACT_COUNT").is_some() {
TAG # eprintln!("check_contract_exec");
TAG # }
TAG # Out { code: o.status.code(), out: o.stdout, err: o.stderr }
TAG # }
TAG # fn exec(&self, args: &[&str], stdin: &[u8]) -> Out {
TAG # self.exec_env(args, stdin, &[])
TAG # }
TAG # fn run(&self, sub: &str, doc: &str) -> Out {
TAG # self.exec(&["check", sub, "--input", "-"], doc.as_bytes())
TAG # }
TAG # fn run_bytes(&self, sub: &str, doc: &[u8]) -> Out {
TAG # self.exec(&["check", sub, "--input", "-"], doc)
TAG # }
TAG # }
TAG # impl Drop for Env {
TAG # fn drop(&mut self) {
TAG # let _ = std::fs::remove_dir_all(&self.root);
TAG # }
TAG # }
TAG # // ---------------------------------------------------------------- output assertions
TAG # fn trunc(s: &str) -> String {
TAG # s.chars().take(400).collect()
TAG # }
TAG # fn obj(o: &Out) -> J {
TAG # let t = o.text();
TAG # let j = parse_json(t.trim()).unwrap_or_else(|e| panic!("stdout is not one JSON value ({e}): {}", trunc(&t)));
TAG # assert!(matches!(j, J::Obj(_)), "stdout must be one JSON object: {}", trunc(&t));
TAG # j
TAG # }
TAG # fn sf<'a>(j: &'a J, k: &str) -> &'a str {
TAG # j.get(k).and_then(J::as_str).unwrap_or_else(|| panic!("missing string field {k} in {}", trunc(&to_s(j))))
TAG # }
TAG # fn names(j: &J) -> Vec<String> {
TAG # match j {
TAG # J::Arr(v) => v.iter().map(|x| x.as_str().expect("array of strings").to_string()).collect(),
TAG # other => panic!("expected an array, got {}", to_s(other)),
TAG # }
TAG # }
TAG # fn pairs(j: &J) -> Vec<(String, String)> {
TAG # match j {
TAG # J::Obj(v) => {
TAG # let mut r: Vec<(String, String)> =
TAG # v.iter().map(|(k, x)| (k.clone(), x.as_str().expect("string scope value").to_string())).collect();
TAG # r.sort();
TAG # r
TAG # }
TAG # other => panic!("expected an object, got {}", to_s(other)),
TAG # }
TAG # }
TAG # fn result(o: &Out) -> J {
TAG # assert_eq!(o.code, Some(0), "expected exit 0: {}", trunc(&o.text()));
TAG # let j = obj(o);
TAG # assert_eq!(sf(&j, "schema"), "instinct.check-result/v1", "{}", trunc(&o.text()));
TAG # assert!(["pass", "fail", "abstain"].contains(&sf(&j, "verdict")), "{}", trunc(&o.text()));
TAG # assert_eq!(sf(&j, "authorization"), "not_evaluated");
TAG # assert_eq!(sf(&j, "evidence_origin"), "caller_reported");
TAG # assert!(!sf(&j, "reason").is_empty());
TAG # assert!(!sf(&j, "check_id").is_empty());
TAG # match j.get("revision") {
TAG # Some(J::Num(n)) => assert!(n.parse::<u32>().is_ok(), "revision must be an integer: {n}"),
TAG # other => panic!("revision must be a number: {other:?}"),
TAG # }
TAG # match j.get("steps") {
TAG # Some(J::Num(n)) => assert!(n.parse::<u64>().is_ok(), "steps must be a non-negative integer: {n}"),
TAG # other => panic!("steps must be a number: {other:?}"),
TAG # }
TAG # match j.get("witness") {
TAG # Some(J::Null) | Some(J::Str(_)) => {}
TAG # other => panic!("witness must be string or null: {other:?}"),
TAG # }
TAG # let m = names(j.get("missing").expect("missing field"));
TAG # let mut sorted = m.clone();
TAG # sorted.sort();
TAG # sorted.dedup();
TAG # assert_eq!(m, sorted, "missing must be sorted and unique");
TAG # assert!(matches!(j.get("scope"), Some(J::Obj(_))), "scope must be an object");
TAG # let verdict = sf(&j, "verdict");
TAG # if verdict == "pass" || verdict == "abstain" {
TAG # assert_eq!(j.get("witness"), Some(&J::Null), "only a failed check has a witness: {}", trunc(&o.text()));
TAG # }
TAG # j
TAG # }
TAG # fn verdict(o: &Out) -> String {
TAG # sf(&result(o), "verdict").to_string()
TAG # }
TAG # fn err(o: &Out, ctx: &str) {
TAG # assert_eq!(o.code, Some(2), "{ctx}: expected exit 2, stdout={}", trunc(&o.text()));
TAG # let j = obj(o);
TAG # assert_eq!(sf(&j, "schema"), "instinct.check-error/v1", "{ctx}: {}", trunc(&o.text()));
TAG # assert_eq!(sf(&j, "verdict"), "error", "{ctx}");
TAG # assert!(!sf(&j, "reason").is_empty(), "{ctx}");
TAG # assert_eq!(sf(&j, "authorization"), "not_evaluated", "{ctx}");
TAG # assert!(o.out.len() <= 65_537, "{ctx}: error output must be bounded, got {} bytes", o.out.len());
TAG # }
TAG # // run validate, run and explain: every one must reject the document
TAG # fn all_err(env: &Env, raw: &[u8], ctx: &str) {
TAG # for sub in ["validate", "run", "explain"] {
TAG # err(&env.run_bytes(sub, raw), &format!("{sub} {ctx}"));
TAG # }
TAG # }
TAG # fn all_err_s(env: &Env, raw: &str, ctx: &str) {
TAG # all_err(env, raw.as_bytes(), &format!("{ctx}: {}", trunc(raw)));
TAG # }
TAG # fn valid(env: &Env, raw: &str, ctx: &str) {
TAG # let o = env.run("validate", raw);
TAG # assert_eq!(o.code, Some(0), "{ctx}: {}", trunc(&o.text()));
TAG # let j = obj(&o);
TAG # assert_eq!(sf(&j, "schema"), "instinct.check-validation/v1", "{ctx}");
TAG # assert_eq!(j.get("valid"), Some(&J::Bool(true)), "{ctx}");
TAG # assert_eq!(sf(&j, "authorization"), "not_evaluated");
TAG # }
TAG # // ---------------------------------------------------------------- document builders
TAG # #[derive(Clone)]
TAG # struct D {
TAG # schema: String,
TAG # id: String,
TAG # rev: String,
TAG # inputs: String,
TAG # claim: String,
TAG # req: Option<String>,
TAG # dscope: Option<String>,
TAG # facts: Option<String>,
TAG # conds: Option<String>,
TAG # scope: Option<String>,
TAG # }
TAG # fn d(inputs: &str, claim: &str) -> D {
TAG # D {
TAG # schema: "\"instinct.check/v1\"".into(),
TAG # id: "\"t1\"".into(),
TAG # rev: "1".into(),
TAG # inputs: inputs.into(),
TAG # claim: claim.into(),
TAG # req: None,
TAG # dscope: None,
TAG # facts: None,
TAG # conds: None,
TAG # scope: None,
TAG # }
TAG # }
TAG # impl D {
TAG # fn facts(mut self, s: &str) -> D {
TAG # self.facts = Some(s.into());
TAG # self
TAG # }
TAG # fn conds(mut self, s: &str) -> D {
TAG # self.conds = Some(s.into());
TAG # self
TAG # }
TAG # fn scope(mut self, s: &str) -> D {
TAG # self.scope = Some(s.into());
TAG # self
TAG # }
TAG # fn dscope(mut self, s: &str) -> D {
TAG # self.dscope = Some(s.into());
TAG # self
TAG # }
TAG # fn req(mut self, s: &str) -> D {
TAG # self.req = Some(s.into());
TAG # self
TAG # }
TAG # fn id(mut self, s: &str) -> D {
TAG # self.id = s.into();
TAG # self
TAG # }
TAG # fn rev(mut self, s: &str) -> D {
TAG # self.rev = s.into();
TAG # self
TAG # }
TAG # fn schema(mut self, s: &str) -> D {
TAG # self.schema = s.into();
TAG # self
TAG # }
TAG # fn json(&self) -> String {
TAG # let mut c = format!(
TAG # "{{\"schema\":{},\"id\":{},\"revision\":{},\"inputs\":{},\"claim\":{}",
TAG # self.schema, self.id, self.rev, self.inputs, self.claim
TAG # );
TAG # if let Some(r) = &self.req {
TAG # c.push_str(&format!(",\"required_conditions\":{r}"));
TAG # }
TAG # if let Some(s) = &self.dscope {
TAG # c.push_str(&format!(",\"scope\":{s}"));
TAG # }
TAG # c.push('}');
TAG # let mut t = format!("{{\"check\":{c}");
TAG # if let Some(f) = &self.facts {
TAG # t.push_str(&format!(",\"facts\":{f}"));
TAG # }
TAG # if let Some(f) = &self.conds {
TAG # t.push_str(&format!(",\"conditions\":{f}"));
TAG # }
TAG # if let Some(f) = &self.scope {
TAG # t.push_str(&format!(",\"scope\":{f}"));
TAG # }
TAG # t.push('}');
TAG # t
TAG # }
TAG # }
TAG # fn fact(n: &str) -> String {
TAG # format!("{{\"fact\":\"{n}\"}}")
TAG # }
TAG # fn op2(op: &str, l: &str, r: &str) -> String {
TAG # format!("{{\"op\":\"{op}\",\"left\":{},\"right\":{}}}", fact(l), fact(r))
TAG # }
TAG # fn all_of(a: &[String]) -> String {
TAG # format!("{{\"op\":\"all\",\"args\":[{}]}}", a.join(","))
TAG # }
TAG # fn any_of(a: &[String]) -> String {
TAG # format!("{{\"op\":\"any\",\"args\":[{}]}}", a.join(","))
TAG # }
TAG # fn not_of(a: &str) -> String {
TAG # format!("{{\"op\":\"not\",\"arg\":{a}}}")
TAG # }
TAG # // the example from the contract, on one line
TAG # const BASE: &str = "{\"check\":{\"schema\":\"instinct.check/v1\",\"id\":\"artifact-membership\",\"revision\":1,\"inputs\":{\"actual\":\"set<string>\",\"allowed\":\"set<string>\"},\"claim\":{\"op\":\"subset\",\"left\":{\"fact\":\"actual\"},\"right\":{\"fact\":\"allowed\"}},\"required_conditions\":[\"complete-inventory\",\"explicit-policy\"],\"scope\":{\"project\":\"release-lab\"}},\"facts\":{\"actual\":[\"release.bin\",\"scratch.env\"],\"allowed\":[\"release.bin\"]},\"conditions\":{\"complete-inventory\":true,\"explicit-policy\":true},\"scope\":{\"project\":\"release-lab\"}}";
TAG # const SET_IN: &str = "{\"actual\":\"set<string>\",\"allowed\":\"set<string>\"}";
TAG # fn mutate(from: &str, to: &str) -> String {
TAG # assert_eq!(BASE.matches(from).count(), 1, "mutation anchor must be unique: {from}");
TAG # BASE.replacen(from, to, 1)
TAG # }
TAG # fn set_doc(op: &str, l: &str, r: &str) -> String {
TAG # d(SET_IN, &op2(op, "actual", "allowed")).facts(&format!("{{\"actual\":{l},\"allowed\":{r}}}")).json()
TAG # }
TAG # fn js(items: &[&str]) -> String {
TAG # format!("[{}]", items.iter().map(|s| format!("\"{s}\"")).collect::<Vec<_>>().join(","))
TAG # }
TAG # fn many(n: usize, prefix: &str) -> String {
TAG # format!("[{}]", (0..n).map(|i| format!("\"{prefix}{i:05}\"")).collect::<Vec<_>>().join(","))
TAG # }
TAG # // ---------------------------------------------------------------- wire and result basics
TAG # #[test]
TAG # fn contract_example_fails_with_the_first_unexpected_member() {
TAG # let env = Env::new("example");
TAG # let o = env.run("run", BASE);
TAG # let j = result(&o);
TAG # assert!(o.text().trim_start().starts_with('{'), "no logging before the JSON result");
TAG # assert_eq!(sf(&j, "verdict"), "fail");
TAG # assert_eq!(sf(&j, "check_id"), "artifact-membership");
TAG # assert_eq!(j.get("revision"), Some(&J::Num("1".into())));
TAG # assert_eq!(j.get("witness"), Some(&J::Str("scratch.env".into())));
TAG # assert_eq!(names(j.get("missing").unwrap()), Vec::<String>::new());
TAG # assert_eq!(pairs(j.get("scope").unwrap()), vec![("project".to_string(), "release-lab".to_string())]);
TAG # }
TAG # #[test]
TAG # fn contract_example_with_a_complete_allow_list_passes_without_a_witness() {
TAG # let env = Env::new("example-pass");
TAG # let doc = mutate("\"allowed\":[\"release.bin\"]", "\"allowed\":[\"scratch.env\",\"release.bin\"]");
TAG # let j = result(&env.run("run", &doc));
TAG # assert_eq!(sf(&j, "verdict"), "pass");
TAG # assert_eq!(j.get("witness"), Some(&J::Null));
TAG # assert_eq!(names(j.get("missing").unwrap()), Vec::<String>::new());
TAG # }
TAG # #[test]
TAG # fn validate_checks_the_definition_and_never_claims_a_predicate_pass() {
TAG # let env = Env::new("validate");
TAG # let o = env.run("validate", BASE);
TAG # assert_eq!(o.code, Some(0));
TAG # let j = obj(&o);
TAG # assert_eq!(sf(&j, "schema"), "instinct.check-validation/v1");
TAG # assert_eq!(sf(&j, "check_id"), "artifact-membership");
TAG # assert_eq!(j.get("revision"), Some(&J::Num("1".into())));
TAG # assert_eq!(j.get("valid"), Some(&J::Bool(true)));
TAG # assert_eq!(sf(&j, "authorization"), "not_evaluated");
TAG # assert!(j.get("verdict").is_none(), "validation is not a verdict: {}", o.text());
TAG # assert!(j.get("witness").is_none());
TAG # assert!(!o.text().contains("\"pass\""), "validation must not read as a PASS");
TAG # // The predicate fails on these facts, yet the definition and the supplied evidence are valid.
TAG # // Missing facts, missing conditions and a missing scope are not validation errors either.
TAG # let bare = d(SET_IN, &op2("subset", "actual", "allowed")).req("[\"c1\"]").dscope("{\"project\":\"p\"}");
TAG # for doc in [
TAG # bare.clone().json(),
TAG # bare.clone().facts("{}").conds("{}").scope("{}").json(),
TAG # bare.clone().facts("{\"actual\":[\"x\"]}").json(),
TAG # bare.clone().facts("{\"actual\":[\"x\"],\"allowed\":[]}").conds("{\"c1\":false}").scope("{\"project\":\"other\"}").json(),
TAG # ] {
TAG # valid(&env, &doc, &doc);
TAG # }
TAG # }
TAG # #[test]
TAG # fn explain_repeats_the_result_and_adds_declared_types_conditions_and_scope() {
TAG # let env = Env::new("explain");
TAG # let run = result(&env.run("run", BASE));
TAG # let o = env.run("explain", BASE);
TAG # let ex = result(&o);
TAG # for k in ["check_id", "revision", "verdict", "reason", "witness", "missing", "scope", "steps"] {
TAG # assert_eq!(run.get(k), ex.get(k), "explain must carry the same {k}");
TAG # }
TAG # let e = ex.get("explanation").unwrap_or_else(|| panic!("explain needs an explanation: {}", trunc(&o.text())));
TAG # assert_ne!(e, &J::Null);
TAG # let t = to_s(e);
TAG # for needle in ["set<string>", "actual", "allowed", "complete-inventory", "explicit-policy", "release-lab", "subset"] {
TAG # assert!(t.contains(needle), "explanation should mention {needle}: {t}");
TAG # }
TAG # assert!(!t.contains("release.bin"), "explanation must not echo fact values: {t}");
TAG # assert!(run.get("explanation").is_none(), "run has no explanation");
TAG # }
TAG # #[test]
TAG # fn explain_and_run_do_not_expose_unrelated_fact_values() {
TAG # let env = Env::new("expose");
TAG # let inputs = "{\"actual\":\"set<string>\",\"allowed\":\"set<string>\",\"note\":\"string\",\"other\":\"set<string>\"}";
TAG # let doc = d(inputs, &op2("subset", "actual", "allowed"))
TAG # .facts("{\"actual\":[\"a\"],\"allowed\":[\"a\",\"SECRET_MEMBER_77\"],\"note\":\"SECRET_NOTE_88\",\"other\":[\"SECRET_OTHER_99\"]}")
TAG # .json();
TAG # for sub in ["run", "explain"] {
TAG # let o = env.run(sub, &doc);
TAG # let t = o.text();
TAG # assert_eq!(verdict(&o), "pass");
TAG # for s in ["SECRET_MEMBER_77", "SECRET_NOTE_88", "SECRET_OTHER_99"] {
TAG # assert!(!t.contains(s), "{sub} leaked {s}: {t}");
TAG # }
TAG # }
TAG # let failing = d(inputs, &op2("subset", "actual", "allowed"))
TAG # .facts("{\"actual\":[\"zz\"],\"allowed\":[],\"note\":\"SECRET_NOTE_88\",\"other\":[\"SECRET_OTHER_99\"]}")
TAG # .json();
TAG # for sub in ["run", "explain"] {
TAG # let t = env.run(sub, &failing).text();
TAG # assert!(!t.contains("SECRET_NOTE_88") && !t.contains("SECRET_OTHER_99"), "{sub} leaked: {t}");
TAG # }
TAG # }
TAG # #[test]
TAG # fn omitted_facts_conditions_and_scope_default_to_empty_and_missing_evidence_abstains() {
TAG # let env = Env::new("defaults");
TAG # let doc = d(SET_IN, &op2("subset", "actual", "allowed")).json();
TAG # let j = result(&env.run("run", &doc));
TAG # assert_eq!(sf(&j, "verdict"), "abstain");
TAG # assert_eq!(names(j.get("missing").unwrap()), vec!["actual", "allowed"]);
TAG # assert_eq!(pairs(j.get("scope").unwrap()), vec![]);
TAG # for explicit in ["{}"] {
TAG # let same = d(SET_IN, &op2("subset", "actual", "allowed")).facts(explicit).conds(explicit).scope(explicit).json();
TAG # let k = result(&env.run("run", &same));
TAG # assert_eq!(k.get("verdict"), j.get("verdict"));
TAG # assert_eq!(k.get("missing"), j.get("missing"));
TAG # }
TAG # }
TAG # #[test]
TAG # fn results_are_deterministic_across_runs_and_machines() {
TAG # let a = Env::new("det-a");
TAG # let b = Env::new("det-b");
TAG # for doc in [BASE.to_string(), set_doc("disjoint", "[\"b\",\"a\"]", "[\"a\",\"b\"]")] {
TAG # for sub in ["run", "validate", "explain"] {
TAG # let x = a.run(sub, &doc);
TAG # assert_eq!(x.out, a.run(sub, &doc).out);
TAG # assert_eq!(x.out, b.run(sub, &doc).out);
TAG # }
TAG # }
TAG # }
TAG # #[test]
TAG # fn file_and_stdin_input_are_identical_for_results_and_errors() {
TAG # let env = Env::new("parity");
TAG # let docs = [
TAG # BASE.to_string(),
TAG # mutate("\"revision\":1", "\"revision\":2"),
TAG # mutate("\"complete-inventory\":true", "\"complete-inventory\":false"),
TAG # "{\"check\":".to_string(),
TAG # mutate("\"op\":\"subset\"", "\"op\":\"nope\""),
TAG # String::new(),
TAG # ];
TAG # for (i, doc) in docs.iter().enumerate() {
TAG # let path = env.put(&format!("doc{i}.json"), doc.as_bytes());
TAG # let p = path.to_str().unwrap();
TAG # for sub in ["run", "validate", "explain"] {
TAG # let f = env.exec(&["check", sub, "--input", p], b"");
TAG # let s = env.run(sub, doc);
TAG # assert_eq!(f.code, s.code, "{sub} doc{i}");
TAG # assert_eq!(f.out, s.out, "{sub} doc{i}");
TAG # // the document is read from the file; stdin is ignored when a file is named
TAG # let both = env.exec(&["check", sub, "--input", p], BASE.as_bytes());
TAG # assert_eq!(f.out, both.out, "{sub} doc{i}: named file wins over stdin");
TAG # }
TAG # }
TAG # }
TAG # #[test]
TAG # fn input_io_errors_use_the_error_shape() {
TAG # let env = Env::new("io");
TAG # let missing = env.root.join("in").join("nope.json");
TAG # err(&env.exec(&["check", "run", "--input", missing.to_str().unwrap()], b""), "missing file");
TAG # err(&env.exec(&["check", "validate", "--input", env.root.join("in").to_str().unwrap()], b""), "directory");
TAG # err(&env.exec(&["check", "explain", "--input", ""], b""), "empty path");
TAG # err(&env.exec(&["check", "run", "--input", "-"], b""), "empty stdin");
TAG # }
TAG # // ---------------------------------------------------------------- top-level keys and definition keys
TAG # #[test]
TAG # fn top_level_shape_is_strict() {
TAG # let env = Env::new("top");
TAG # let check = "{\"schema\":\"instinct.check/v1\",\"id\":\"t1\",\"revision\":1,\"inputs\":{\"a\":\"bool\"},\"claim\":{\"op\":\"eq\",\"left\":{\"fact\":\"a\"},\"right\":{\"fact\":\"a\"}}}";
TAG # let bad = [
TAG # "{}".to_string(),
TAG # "[]".to_string(),
TAG # "null".to_string(),
TAG # "\"check\"".to_string(),
TAG # "7".to_string(),
TAG # "true".to_string(),
TAG # format!("{{\"facts\":{{}},\"check\":null}}"),
TAG # format!("{{\"check\":[]}}"),
TAG # format!("{{\"check\":{check},\"extra\":{{}}}}"),
TAG # format!("{{\"check\":{check},\"Facts\":{{}}}}"),
TAG # format!("{{\"check\":{check},\"facts\":null}}"),
TAG # format!("{{\"check\":{check},\"conditions\":null}}"),
TAG # format!("{{\"check\":{check},\"scope\":null}}"),
TAG # format!("{{\"check\":{check},\"facts\":[]}}"),
TAG # format!("{{\"check\":{check},\"conditions\":[]}}"),
TAG # format!("{{\"check\":{check},\"scope\":[]}}"),
TAG # format!("{{\"facts\":{{}},\"conditions\":{{}},\"scope\":{{}}}}"),
TAG # ];
TAG # for doc in &bad {
TAG # all_err_s(&env, doc, "top level");
TAG # }
TAG # valid(&env, &format!("{{\"check\":{check}}}"), "check alone");
TAG # valid(&env, &format!("{{\"scope\":{{}},\"conditions\":{{}},\"facts\":{{}},\"check\":{check}}}"), "order is free");
TAG # }
TAG # #[test]
TAG # fn definition_requires_its_five_keys_and_rejects_unknown_ones() {
TAG # let env = Env::new("defkeys");
TAG # let parts = [
TAG # ("schema", "\"instinct.check/v1\""),
TAG # ("id", "\"t1\""),
TAG # ("revision", "1"),
TAG # ("inputs", "{\"a\":\"bool\"}"),
TAG # ("claim", "{\"op\":\"eq\",\"left\":{\"fact\":\"a\"},\"right\":{\"fact\":\"a\"}}"),
TAG # ];
TAG # let build = |skip: Option<&str>, extra: &str| {
TAG # let body: Vec<String> =
TAG # parts.iter().filter(|(k, _)| Some(*k) != skip).map(|(k, v)| format!("\"{k}\":{v}")).collect();
TAG # format!("{{\"check\":{{{}{extra}}}}}", body.join(","))
TAG # };
TAG # valid(&env, &build(None, ""), "complete");
TAG # valid(&env, &build(None, ",\"required_conditions\":[],\"scope\":{}"), "optional keys");
TAG # for (k, _) in parts {
TAG # all_err_s(&env, &build(Some(k), ""), &format!("missing {k}"));
TAG # }
TAG # for extra in [
TAG # ",\"extra\":1",
TAG # ",\"description\":\"x\"",
TAG # ",\"Scope\":{}",
TAG # ",\"required_conditions\":null",
TAG # ",\"required_conditions\":\"c\"",
TAG # ",\"required_conditions\":{}",
TAG # ",\"required_conditions\":[1]",
TAG # ",\"required_conditions\":[null]",
TAG # ",\"required_conditions\":[[\"c\"]]",
TAG # ",\"scope\":null",
TAG # ",\"scope\":[]",
TAG # ",\"inputs\":{}",
TAG # ] {
TAG # all_err_s(&env, &build(None, extra), extra);
TAG # }
TAG # }
TAG # #[test]
TAG # fn schema_string_must_match_exactly() {
TAG # let env = Env::new("schema");
TAG # let base = d("{\"a\":\"bool\"}", &op2("eq", "a", "a"));
TAG # valid(&env, &base.clone().json(), "v1");
TAG # for s in [
TAG # "\"instinct.check/v2\"",
TAG # "\"instinct.check/v0\"",
TAG # "\"instinct.check/V1\"",
TAG # "\"Instinct.check/v1\"",
TAG # "\"instinct.check/v1 \"",
TAG # "\"instinct.check\"",
TAG # "\"instinct.check-result/v1\"",
TAG # "\"\"",
TAG # "1",
TAG # "null",
TAG # "true",
TAG # "[\"instinct.check/v1\"]",
TAG # ] {
TAG # all_err_s(&env, &base.clone().schema(s).json(), s);
TAG # }
TAG # }
TAG # #[test]
TAG # fn ids_are_one_to_128_ascii_characters_starting_with_a_letter() {
TAG # let env = Env::new("ids");
TAG # let base = d("{\"a\":\"bool\"}", &op2("eq", "a", "a")).facts("{\"a\":true}");
TAG # let long_ok = format!("a{}", "b".repeat(127));
TAG # let ok = ["a", "Z", "a1", "A_b-c.d", "x.y.z", "a-", "a.", "a_", "ab0", &long_ok, "artifact-membership"];
TAG # for id in ok {
TAG # let j = result(&env.run("run", &base.clone().id(&format!("\"{id}\"")).json()));
TAG # assert_eq!(sf(&j, "check_id"), id);
TAG # assert_eq!(sf(&j, "verdict"), "pass");
TAG # }
TAG # let too_long = format!("a{}", "b".repeat(128));
TAG # let bad = [
TAG # "".to_string(),
TAG # "1a".to_string(),
TAG # "0".to_string(),
TAG # "_a".to_string(),
TAG # "-a".to_string(),
TAG # ".a".to_string(),
TAG # "a b".to_string(),
TAG # "a/b".to_string(),
TAG # "a:b".to_string(),
TAG # "a\\u00e9".to_string(),
TAG # "\\u00e9a".to_string(),
TAG # "a\\u0000".to_string(),
TAG # "a\\n".to_string(),
TAG # "a b".replace(' ', "\\t"),
TAG # "a*".to_string(),
TAG # "a@b".to_string(),
TAG # "a\\u0430".to_string(),
TAG # too_long,
TAG # ];
TAG # for id in &bad {
TAG # all_err_s(&env, &base.clone().id(&format!("\"{id}\"")).json(), &format!("id {id:?}"));
TAG # }
TAG # for raw in ["null", "1", "true", "[]", "{}", "[\"a\"]"] {
TAG # all_err_s(&env, &base.clone().id(raw).json(), raw);
TAG # }
TAG # }
TAG # #[test]
TAG # fn revision_is_an_exact_integer_literal_between_1_and_2147483647() {
TAG # let env = Env::new("rev");
TAG # let base = d("{\"a\":\"bool\"}", &op2("eq", "a", "a")).facts("{\"a\":true}");
TAG # for r in ["1", "2", "10", "255", "65536", "2147483646", "2147483647"] {
TAG # let j = result(&env.run("run", &base.clone().rev(r).json()));
TAG # assert_eq!(j.get("revision"), Some(&J::Num(r.into())), "revision {r}");
TAG # }
TAG # for r in [
TAG # "0", "-1", "2147483648", "2147483649", "4294967296", "99999999999999999999", "01", "001", "1.0", "1.", ".5", "1.5", "1e0",
TAG # "1E0", "1e+0", "1e1", "10e-1", "0.1e1", "+1", "-0", "-", "--1", "0x1", "1_0", "Infinity", "NaN", "null", "true", "false",
TAG # "\"1\"", "[1]", "{}", "1 2", "1.0000000000000001",
TAG # ] {
TAG # all_err_s(&env, &base.clone().rev(r).json(), &format!("revision {r}"));
TAG # }
TAG # }
TAG # // ---------------------------------------------------------------- types
TAG # #[test]
TAG # fn input_type_names_are_exactly_the_four_supported_ones() {
TAG # let env = Env::new("typenames");
TAG # for t in ["string", "bool", "int", "set<string>"] {
TAG # let doc = d(&format!("{{\"a\":\"{t}\"}}"), &op2("eq", "a", "a")).json();
TAG # valid(&env, &doc, t);
TAG # }
TAG # for t in [
TAG # "float", "rational", "number", "integer", "i64", "u32", "str", "boolean", "set<int>", "set<bool>", "set", "set<>", "set<string",
TAG # "Set<string>", "set< string >", "set<String>", "SET<STRING>", "String", "Bool", "INT", "list<string>", "array<string>",
TAG # "map<string,string>", "set<set<string>>", "graph", "node", "edge", "set<node>", "", " string", "string ", "null", "any",
TAG # "string|int", "string?", "option<string>",
TAG # ] {
TAG # let doc = d(&format!("{{\"a\":\"{t}\"}}"), &op2("eq", "a", "a")).json();
TAG # all_err_s(&env, &doc, &format!("type {t:?}"));
TAG # }
TAG # for raw in ["null", "1", "true", "[]", "[\"string\"]", "{\"type\":\"string\"}", "{}"] {
TAG # all_err_s(&env, &d(&format!("{{\"a\":{raw}}}"), &op2("eq", "a", "a")).json(), raw);
TAG # }
TAG # for raw in ["[]", "null", "\"a\"", "1"] {
TAG # all_err_s(&env, &d(raw, &op2("eq", "a", "a")).json(), raw);
TAG # }
TAG # // names differing only by case are different facts
TAG # let two = d("{\"A\":\"string\",\"a\":\"string\"}", &op2("eq", "A", "a")).facts("{\"A\":\"x\",\"a\":\"x\"}").json();
TAG # assert_eq!(verdict(&env.run("run", &two)), "pass");
TAG # }
TAG # #[test]
TAG # fn supplied_facts_must_be_declared_and_correctly_typed() {
TAG # let env = Env::new("facttypes");
TAG # let ins = "{\"s\":\"string\",\"b\":\"bool\",\"n\":\"int\",\"x\":\"set<string>\"}";
TAG # let claim = all_of(&[op2("eq", "s", "s"), op2("eq", "b", "b"), op2("eq", "n", "n"), op2("eq", "x", "x")]);
TAG # let mk = |facts: &str| d(ins, &claim).facts(facts).json();
TAG # let good = "{\"s\":\"v\",\"b\":true,\"n\":\"7\",\"x\":[\"p\",\"q\"]}";
TAG # assert_eq!(verdict(&env.run("run", &mk(good))), "pass");
TAG # valid(&env, &mk(good), "good");
TAG # valid(&env, &mk("{\"s\":\"\",\"b\":false,\"n\":\"0\",\"x\":[]}"), "empty values");
TAG # valid(&env, &mk("{}"), "no facts");
TAG # valid(&env, &mk("{\"x\":[\"p\"]}"), "some facts");
TAG # for f in [
TAG # "{\"s\":1}",
TAG # "{\"s\":true}",
TAG # "{\"s\":null}",
TAG # "{\"s\":[\"a\"]}",
TAG # "{\"s\":{}}",
TAG # "{\"b\":\"true\"}",
TAG # "{\"b\":1}",
TAG # "{\"b\":0}",
TAG # "{\"b\":null}",
TAG # "{\"b\":\"false\"}",
TAG # "{\"n\":7}",
TAG # "{\"n\":0}",
TAG # "{\"n\":7.0}",
TAG # "{\"n\":true}",
TAG # "{\"n\":null}",
TAG # "{\"n\":[\"7\"]}",
TAG # "{\"x\":\"p\"}",
TAG # "{\"x\":null}",
TAG # "{\"x\":{}}",
TAG # "{\"x\":[1]}",
TAG # "{\"x\":[null]}",
TAG # "{\"x\":[true]}",
TAG # "{\"x\":[[\"p\"]]}",
TAG # "{\"x\":[{}]}",
TAG # "{\"x\":[\"p\",\"p\"]}",
TAG # "{\"x\":[\"p\",\"q\",\"p\"]}",
TAG # "{\"unknown\":\"v\"}",
TAG # "{\"S\":\"v\"}",
TAG # "{\"s\":\"v\",\"zzz\":true}",
TAG # "[]",
TAG # "null",
TAG # "\"s\"",
TAG # "7",
TAG # ] {
TAG # all_err_s(&env, &mk(f), f);
TAG # }
TAG # }
TAG # #[test]
TAG # fn supplied_facts_are_type_checked_even_when_short_circuit_would_skip_them() {
TAG # let env = Env::new("shortcircuit-types");
TAG # let ins = "{\"one\":\"bool\",\"zero\":\"bool\",\"s\":\"string\"}";
TAG # let any_t = any_of(&[op2("eq", "one", "one"), op2("eq", "s", "s")]);
TAG # let all_f = all_of(&[op2("eq", "one", "zero"), op2("eq", "s", "s")]);
TAG # for claim in [any_t, all_f] {
TAG # let ok = d(ins, &claim).facts("{\"one\":true,\"zero\":false,\"s\":\"x\"}").json();
TAG # assert_ne!(verdict(&env.run("run", &ok)), "abstain");
TAG # let bad = d(ins, &claim).facts("{\"one\":true,\"zero\":false,\"s\":5}").json();
TAG # all_err_s(&env, &bad, "unread wrong-typed fact");
TAG # let undeclared = d(ins, &claim).facts("{\"one\":true,\"zero\":false,\"s\":\"x\",\"ghost\":true}").json();
TAG # all_err_s(&env, &undeclared, "unread undeclared fact");
TAG # }
TAG # }
TAG # #[test]
TAG # fn int_facts_are_canonical_decimal_strings_within_i128() {
TAG # let env = Env::new("ints");
TAG # let mk = |v: &str| d("{\"n\":\"int\"}", &op2("eq", "n", "n")).facts(&format!("{{\"n\":\"{v}\"}}")).json();
TAG # for v in [
TAG # "0",
TAG # "1",
TAG # "-1",
TAG # "9",
TAG # "10",
TAG # "-10",
TAG # "123",
TAG # "9007199254740992",
TAG # "9007199254740993",
TAG # "-9007199254740993",
TAG # "9223372036854775807",
TAG # "9223372036854775808",
TAG # "-9223372036854775808",
TAG # "-9223372036854775809",
TAG # "18446744073709551615",
TAG # "18446744073709551616",
TAG # "170141183460469231731687303715884105727",
TAG # "-170141183460469231731687303715884105728",
TAG # ] {
TAG # assert_eq!(verdict(&env.run("run", &mk(v))), "pass", "{v}");
TAG # valid(&env, &mk(v), v);
TAG # }
TAG # for v in [
TAG # "+1",
TAG # "+0",
TAG # "1e3",
TAG # "1E3",
TAG # "1.0",
TAG # "1.",
TAG # ".5",
TAG # "01",
TAG # "00",
TAG # "-0",
TAG # "-00",
TAG # "-01",
TAG # "",
TAG # " ",
TAG # "- 1",
TAG # " 1",
TAG # "1 ",
TAG # "1\\n",
TAG # "\\t1",
TAG # "0x10",
TAG # "0b1",
TAG # "1_000",
TAG # "1,000",
TAG # "-",
TAG # "--1",
TAG # "+-1",
TAG # "abc",
TAG # "NaN",
TAG # "Infinity",
TAG # "null",
TAG # "true",
TAG # "170141183460469231731687303715884105728",
TAG # "-170141183460469231731687303715884105729",
TAG # "340282366920938463463374607431768211455",
TAG # "99999999999999999999999999999999999999999999",
TAG # "-99999999999999999999999999999999999999999999",
TAG # "\\uff11\\uff12",
TAG # "\\u0661",
TAG # "\\u0663\\u0664",
TAG # "1\\u0000",
TAG # "\\u2212" ,
TAG # "1\\u00a0",
TAG # ] {
TAG # all_err_s(&env, &mk(v), &format!("int {v:?}"));
TAG # }
TAG # }
TAG # #[test]
TAG # fn int_comparisons_are_exact_beyond_f64_and_numeric_not_lexical() {
TAG # let env = Env::new("intcmp");
TAG # let max = "170141183460469231731687303715884105727";
TAG # let min = "-170141183460469231731687303715884105728";
TAG # // (a, b, lt, lte, eq)
TAG # let rows: Vec<(&str, &str, &str, &str, &str)> = vec![
TAG # ("9007199254740992", "9007199254740993", "pass", "pass", "fail"),
TAG # ("9007199254740993", "9007199254740992", "fail", "fail", "fail"),
TAG # ("9007199254740993", "9007199254740993", "fail", "pass", "pass"),
TAG # ("9007199254740993", "9007199254740995", "pass", "pass", "fail"),
TAG # ("-9007199254740993", "-9007199254740992", "pass", "pass", "fail"),
TAG # ("-9007199254740992", "-9007199254740993", "fail", "fail", "fail"),
TAG # ("-1", "0", "pass", "pass", "fail"),
TAG # ("0", "-1", "fail", "fail", "fail"),
TAG # ("-10", "-9", "pass", "pass", "fail"),
TAG # ("-9", "-10", "fail", "fail", "fail"),
TAG # ("9", "10", "pass", "pass", "fail"),
TAG # ("10", "9", "fail", "fail", "fail"),
TAG # ("2", "10", "pass", "pass", "fail"),
TAG # ("0", "0", "fail", "pass", "pass"),
TAG # ("-5", "-5", "fail", "pass", "pass"),
TAG # ("9223372036854775807", "9223372036854775808", "pass", "pass", "fail"),
TAG # ("-9223372036854775809", "-9223372036854775808", "pass", "pass", "fail"),
TAG # ("18446744073709551615", "18446744073709551616", "pass", "pass", "fail"),
TAG # ("18446744073709551616", "18446744073709551615", "fail", "fail", "fail"),
TAG # (min, max, "pass", "pass", "fail"),
TAG # (max, min, "fail", "fail", "fail"),
TAG # (max, max, "fail", "pass", "pass"),
TAG # (min, min, "fail", "pass", "pass"),
TAG # ("170141183460469231731687303715884105726", max, "pass", "pass", "fail"),
TAG # (max, "170141183460469231731687303715884105726", "fail", "fail", "fail"),
TAG # (min, "-170141183460469231731687303715884105727", "pass", "pass", "fail"),
TAG # ("-170141183460469231731687303715884105727", min, "fail", "fail", "fail"),
TAG # (max, "0", "fail", "fail", "fail"),
TAG # (min, "0", "pass", "pass", "fail"),
TAG # ];
TAG # for (a, b, lt, lte, eq) in rows {
TAG # let facts = format!("{{\"a\":\"{a}\",\"b\":\"{b}\"}}");
TAG # for (op, want) in [("lt", lt), ("lte", lte), ("eq", eq)] {
TAG # let doc = d("{\"a\":\"int\",\"b\":\"int\"}", &op2(op, "a", "b")).facts(&facts).json();
TAG # let j = result(&env.run("run", &doc));
TAG # assert_eq!(sf(&j, "verdict"), want, "{op}({a}, {b})");
TAG # }
TAG # }
TAG # }
TAG # #[test]
TAG # fn operand_types_must_match_the_operator_even_with_no_facts_supplied() {
TAG # let env = Env::new("opptypes");
TAG # let ins = "{\"s\":\"string\",\"t\":\"string\",\"b\":\"bool\",\"c\":\"bool\",\"n\":\"int\",\"m\":\"int\",\"x\":\"set<string>\",\"y\":\"set<string>\"}";
TAG # let good = [
TAG # ("eq", "s", "t"),
TAG # ("eq", "b", "c"),
TAG # ("eq", "n", "m"),
TAG # ("eq", "x", "y"),
TAG # ("subset", "x", "y"),
TAG # ("disjoint", "x", "y"),
TAG # ("contains", "x", "s"),
TAG # ("lt", "n", "m"),
TAG # ("lte", "n", "m"),
TAG # ];
TAG # for (op, l, r) in good {
TAG # valid(&env, &d(ins, &op2(op, l, r)).json(), &format!("{op} {l} {r}"));
TAG # }
TAG # let bad = [
TAG # ("eq", "s", "n"),
TAG # ("eq", "s", "b"),
TAG # ("eq", "s", "x"),
TAG # ("eq", "n", "b"),
TAG # ("eq", "n", "x"),
TAG # ("eq", "b", "x"),
TAG # ("lt", "s", "t"),
TAG # ("lt", "b", "c"),
TAG # ("lt", "x", "y"),
TAG # ("lt", "n", "s"),
TAG # ("lt", "s", "n"),
TAG # ("lte", "s", "t"),
TAG # ("lte", "b", "c"),
TAG # ("lte", "x", "y"),
TAG # ("lte", "n", "x"),
TAG # ("subset", "s", "t"),
TAG # ("subset", "x", "s"),
TAG # ("subset", "s", "y"),
TAG # ("subset", "n", "m"),
TAG # ("subset", "b", "c"),
TAG # ("disjoint", "x", "s"),
TAG # ("disjoint", "s", "y"),
TAG # ("disjoint", "n", "m"),
TAG # ("contains", "s", "t"),
TAG # ("contains", "s", "x"),
TAG # ("contains", "x", "y"),
TAG # ("contains", "x", "n"),
TAG # ("contains", "x", "b"),
TAG # ("contains", "n", "s"),
TAG # ];
TAG # for (op, l, r) in bad {
TAG # all_err_s(&env, &d(ins, &op2(op, l, r)).json(), &format!("{op}({l}, {r})"));
TAG # }
TAG # }
TAG # // ---------------------------------------------------------------- set semantics, Unicode, witnesses
TAG # #[test]
TAG # fn subset_and_disjoint_ignore_order_and_name_a_deterministic_witness() {
TAG # let env = Env::new("sets");
TAG # // (op, left, right, verdict, witness)
TAG # let rows: Vec<(&str, &str, &str, &str, Option<&str>)> = vec![
TAG # ("subset", "[]", "[]", "pass", None),
TAG # ("subset", "[]", "[\"x\"]", "pass", None),
TAG # ("subset", "[\"x\"]", "[]", "fail", Some("x")),
TAG # ("subset", "[\"a\",\"b\"]", "[\"b\",\"a\",\"c\"]", "pass", None),
TAG # ("subset", "[\"b\",\"a\"]", "[\"a\",\"b\"]", "pass", None),
TAG # ("subset", "[\"z\",\"b\",\"m\"]", "[\"m\"]", "fail", Some("b")),
TAG # ("subset", "[\"m\",\"b\",\"z\"]", "[\"m\"]", "fail", Some("b")),
TAG # ("subset", "[\"b\",\"m\",\"z\"]", "[\"m\"]", "fail", Some("b")),
TAG # ("subset", "[\"a\",\"B\"]", "[]", "fail", Some("B")),
TAG # ("subset", "[\"a\",\"A\"]", "[\"a\"]", "fail", Some("A")),
TAG # ("subset", "[\"ab\",\"a\"]", "[]", "fail", Some("a")),
TAG # ("subset", "[\"\"]", "[\"\"]", "pass", None),
TAG # ("subset", "[\"\",\"a\"]", "[\"a\"]", "fail", Some("")),
TAG # ("subset", "[\"A\"]", "[\"a\"]", "fail", Some("A")),
TAG # ("subset", "[\"a \"]", "[\"a\"]", "fail", Some("a ")),
TAG # ("subset", "[\"a\\nb\"]", "[]", "fail", Some("a\nb")),
TAG # ("subset", "[\"q\\\"r\\\\s\"]", "[]", "fail", Some("q\"r\\s")),
TAG # ("subset", "[\"a\\u0000b\"]", "[\"a\\u0000b\"]", "pass", None),
TAG # ("disjoint", "[]", "[]", "pass", None),
TAG # ("disjoint", "[]", "[\"a\"]", "pass", None),
TAG # ("disjoint", "[\"a\"]", "[]", "pass", None),
TAG # ("disjoint", "[\"a\"]", "[\"b\"]", "pass", None),
TAG # ("disjoint", "[\"a\",\"b\"]", "[\"c\",\"d\"]", "pass", None),
TAG # ("disjoint", "[\"a\"]", "[\"A\"]", "pass", None),
TAG # ("disjoint", "[\"a\",\"b\"]", "[\"b\",\"c\"]", "fail", Some("b")),
TAG # ("disjoint", "[\"m\",\"b\"]", "[\"b\",\"m\"]", "fail", Some("b")),
TAG # ("disjoint", "[\"b\",\"m\"]", "[\"m\",\"b\"]", "fail", Some("b")),
TAG # ("disjoint", "[\"z\",\"m\",\"b\"]", "[\"q\",\"m\",\"b\",\"z\"]", "fail", Some("b")),
TAG # ];
TAG # for (op, l, r, v, w) in rows {
TAG # let j = result(&env.run("run", &set_doc(op, l, r)));
TAG # assert_eq!(sf(&j, "verdict"), v, "{op} {l} {r}");
TAG # match w {
TAG # Some(w) => assert_eq!(j.get("witness"), Some(&J::Str(w.into())), "{op} {l} {r}"),
TAG # None => assert_eq!(j.get("witness"), Some(&J::Null), "{op} {l} {r}"),
TAG # }
TAG # }
TAG # }
TAG # #[test]
TAG # fn witness_does_not_depend_on_input_order() {
TAG # let env = Env::new("perm");
TAG # let orders = [
TAG # ["a", "b", "c", "d"],
TAG # ["d", "c", "b", "a"],
TAG # ["b", "d", "a", "c"],
TAG # ["c", "a", "d", "b"],
TAG # ];
TAG # let mut seen = Vec::new();
TAG # for l in orders {
TAG # for r in orders {
TAG # let ls = js(&l);
TAG # let rs = js(&r[..2]);
TAG # let sub = result(&env.run("run", &set_doc("subset", &ls, &rs)));
TAG # let dis = result(&env.run("run", &set_doc("disjoint", &ls, &rs)));
TAG # seen.push((sub.get("verdict").cloned(), sub.get("witness").cloned(), dis.get("verdict").cloned(), dis.get("witness").cloned()));
TAG # }
TAG # }
TAG # // the right-hand set is {a,b} or {d,c} etc. depending on order, so group by the actual right set
TAG # for l in orders {
TAG # let mut by_set: Vec<(Vec<String>, J, J)> = Vec::new();
TAG # for r in orders {
TAG # let mut key: Vec<String> = r[..2].iter().map(|s| s.to_string()).collect();
TAG # key.sort();
TAG # let o = result(&env.run("run", &set_doc("subset", &js(&l), &js(&r[..2]))));
TAG # let w = o.get("witness").cloned().unwrap();
TAG # let v = o.get("verdict").cloned().unwrap();
TAG # if let Some(prev) = by_set.iter().find(|(k, _, _)| *k == key) {
TAG # assert_eq!((prev.1.clone(), prev.2.clone()), (v, w), "order changed the outcome for {l:?} vs {r:?}");
TAG # } else {
TAG # by_set.push((key, v, w));
TAG # }
TAG # }
TAG # }
TAG # assert!(!seen.is_empty());
TAG # }
TAG # #[test]
TAG # fn contains_is_exact_membership_without_case_folding_or_normalization() {
TAG # let env = Env::new("contains");
TAG # let ins = "{\"x\":\"set<string>\",\"s\":\"string\"}";
TAG # let rows: Vec<(&str, &str, &str)> = vec![
TAG # ("[\"a\",\"b\"]", "b", "pass"),
TAG # ("[\"a\",\"b\"]", "c", "fail"),
TAG # ("[\"a\",\"b\"]", "B", "fail"),
TAG # ("[\"a\",\"b\"]", "ab", "fail"),
TAG # ("[\"a\",\"b\"]", "", "fail"),
TAG # ("[\"a\",\"\"]", "", "pass"),
TAG # ("[]", "a", "fail"),
TAG # ("[\"\\u00e9\"]", "\\u00e9", "pass"),
TAG # ("[\"\\u00e9\"]", "e\\u0301", "fail"),
TAG # ("[\"e\\u0301\"]", "\\u00e9", "fail"),
TAG # ("[\"e\\u0301\"]", "e\\u0301", "pass"),
TAG # ("[\"\\u00df\"]", "SS", "fail"),
TAG # ("[\"\\u00df\"]", "ss", "fail"),
TAG # ("[\"\\u0130\"]", "i", "fail"),
TAG # ("[\"K\"]", "\\u212a", "fail"),
TAG # ("[\"\\ud83d\\ude00\"]", "\\ud83d\\ude00", "pass"),
TAG # ("[\"a\\u200bb\"]", "ab", "fail"),
TAG # ("[\"a\\u0000b\"]", "a\\u0000b", "pass"),
TAG # ("[\"a\\u0000b\"]", "a", "fail"),
TAG # ("[\"Stra\\u00dfe\"]", "STRASSE", "fail"),
TAG # ("[\"\\u0391\"]", "\\u0041", "fail"),
TAG # ];
TAG # for (x, s, want) in rows {
TAG # let doc = d(ins, &op2("contains", "x", "s")).facts(&format!("{{\"x\":{x},\"s\":\"{s}\"}}")).json();
TAG # assert_eq!(verdict(&env.run("run", &doc)), want, "contains {x} {s}");
TAG # }
TAG # // raw UTF-8 and the escaped spelling are the same scalar sequence
TAG # let raw = d(ins, &op2("contains", "x", "s")).facts("{\"x\":[\"\\ud83d\\ude00\",\"\\u00e9\"],\"s\":\"\u{1F600}\"}").json();
TAG # assert_eq!(verdict(&env.run("run", &raw)), "pass");
TAG # let raw = d(ins, &op2("contains", "x", "s")).facts("{\"x\":[\"\u{1F600}\",\"\u{e9}\"],\"s\":\"\\u00e9\"}").json();
TAG # assert_eq!(verdict(&env.run("run", &raw)), "pass");
TAG # }
TAG # #[test]
TAG # fn unicode_members_are_compared_as_exact_scalar_sequences_and_witnessed_verbatim() {
TAG # let env = Env::new("unicode");
TAG # let j = result(&env.run("run", &set_doc("subset", "[\"e\\u0301\"]", "[\"\\u00e9\"]")));
TAG # assert_eq!(sf(&j, "verdict"), "fail");
TAG # assert_eq!(j.get("witness"), Some(&J::Str("e\u{301}".into())));
TAG # let j = result(&env.run("run", &set_doc("subset", "[\"\u{e9}\",\"\\ud83d\\ude00\"]", "[\"\\u00e9\",\"\u{1F600}\"]")));
TAG # assert_eq!(sf(&j, "verdict"), "pass");
TAG # let j = result(&env.run("run", &set_doc("disjoint", "[\"\u{e9}\"]", "[\"e\\u0301\"]")));
TAG # assert_eq!(sf(&j, "verdict"), "pass");
TAG # let j = result(&env.run("run", &set_doc("subset", "[\"\\u0434\\u0430\"]", "[]")));
TAG # assert_eq!(j.get("witness"), Some(&J::Str("\u{434}\u{430}".into())));
TAG # let j = result(&env.run("run", &set_doc("subset", "[\"\u{1F600}\"]", "[]")));
TAG # assert_eq!(j.get("witness"), Some(&J::Str("\u{1F600}".into())));
TAG # // code point order decides "first lexicographic"
TAG # let j = result(&env.run("run", &set_doc("subset", "[\"\u{e9}\",\"z\",\"\u{1F600}\"]", "[]")));
TAG # assert_eq!(j.get("witness"), Some(&J::Str("z".into())));
TAG # // strings compare exactly in eq
TAG # let eq = |a: &str, b: &str| {
TAG # let doc = d("{\"a\":\"string\",\"b\":\"string\"}", &op2("eq", "a", "b")).facts(&format!("{{\"a\":\"{a}\",\"b\":\"{b}\"}}")).json();
TAG # verdict(&env.run("run", &doc))
TAG # };
TAG # assert_eq!(eq("\\u00e9", "\u{e9}"), "pass");
TAG # assert_eq!(eq("\\u00e9", "e\\u0301"), "fail");
TAG # assert_eq!(eq("a", "A"), "fail");
TAG # assert_eq!(eq("", ""), "pass");
TAG # assert_eq!(eq("a", "a "), "fail");
TAG # assert_eq!(eq("\\ud83d\\ude00", "\u{1F600}"), "pass");
TAG # assert_eq!(eq("\\/", "/"), "pass");
TAG # }
TAG # #[test]
TAG # fn duplicate_set_members_are_rejected_including_escaped_spellings() {
TAG # let env = Env::new("setdups");
TAG # for l in [
TAG # "[\"a\",\"a\"]",
TAG # "[\"a\",\"b\",\"a\"]",
TAG # "[\"\",\"\"]",
TAG # "[\"\\u0061\",\"a\"]",
TAG # "[\"a\",\"\\u0061\"]",
TAG # "[\"\\u00e9\",\"\u{e9}\"]",
TAG # "[\"\\u00E9\",\"\\u00e9\"]",
TAG # "[\"\\ud83d\\ude00\",\"\u{1F600}\"]",
TAG # "[\"a\\/b\",\"a/b\"]",
TAG # "[\"a\\nb\",\"a\\u000ab\"]",
TAG # ] {
TAG # all_err_s(&env, &set_doc("subset", l, "[]"), l);
TAG # all_err_s(&env, &set_doc("subset", "[]", l), l);
TAG # }
TAG # for l in [
TAG # "[\"a\",\"A\"]",
TAG # "[\"a\",\"a \"]",
TAG # "[\"\\u00e9\",\"e\\u0301\"]",
TAG # "[\"\",\"a\"]",
TAG # "[\"a\\u0000\",\"a\"]",
TAG # ] {
TAG # valid(&env, &set_doc("subset", l, "[]"), l);
TAG # }
TAG # }
TAG # #[test]
TAG # fn strings_must_be_unicode_scalar_sequences() {
TAG # let env = Env::new("surrogates");
TAG # for l in [
TAG # "[\"\\ud800\"]",
TAG # "[\"\\udc00\"]",
TAG # "[\"\\udfff\"]",
TAG # "[\"a\\ud800\"]",
TAG # "[\"\\ud800a\"]",
TAG # "[\"\\ud83d\\ud83d\"]",
TAG # "[\"\\ude00\\ud83d\"]",
TAG # "[\"\\ud83d\\u0061\"]",
TAG # ] {
TAG # all_err_s(&env, &set_doc("subset", l, "[]"), l);
TAG # let doc = d("{\"s\":\"string\"}", &op2("eq", "s", "s")).facts(&format!("{{\"s\":{}}}", &l[1..l.len() - 1])).json();
TAG # all_err_s(&env, &doc, l);
TAG # }
TAG # }
TAG # #[test]
TAG # fn eq_compares_each_supported_type_and_sets_without_order() {
TAG # let env = Env::new("eq");
TAG # let ins = "{\"x\":\"set<string>\",\"y\":\"set<string>\"}";
TAG # let cases = [
TAG # ("[\"a\",\"b\"]", "[\"b\",\"a\"]", "pass"),
TAG # ("[]", "[]", "pass"),
TAG # ("[\"a\"]", "[\"a\",\"b\"]", "fail"),
TAG # ("[\"a\",\"b\"]", "[\"a\"]", "fail"),
TAG # ("[\"a\"]", "[\"A\"]", "fail"),
TAG # ("[\"a\",\"b\",\"c\"]", "[\"c\",\"a\",\"b\"]", "pass"),
TAG # ("[]", "[\"a\"]", "fail"),
TAG # ];
TAG # for (x, y, want) in cases {
TAG # let doc = d(ins, &op2("eq", "x", "y")).facts(&format!("{{\"x\":{x},\"y\":{y}}}")).json();
TAG # assert_eq!(verdict(&env.run("run", &doc)), want, "{x} == {y}");
TAG # }
TAG # for (a, b, want) in [("true", "true", "pass"), ("false", "false", "pass"), ("true", "false", "fail"), ("false", "true", "fail")] {
TAG # let doc = d("{\"a\":\"bool\",\"b\":\"bool\"}", &op2("eq", "a", "b")).facts(&format!("{{\"a\":{a},\"b\":{b}}}")).json();
TAG # assert_eq!(verdict(&env.run("run", &doc)), want, "{a} == {b}");
TAG # }
TAG # }
TAG # // ---------------------------------------------------------------- missing evidence and three-valued logic
TAG # #[test]
TAG # fn missing_facts_abstain_and_are_listed_sorted_and_unique() {
TAG # let env = Env::new("missing");
TAG # let ins = "{\"z\":\"bool\",\"m\":\"bool\",\"a\":\"bool\"}";
TAG # let claim = all_of(&[op2("eq", "z", "a"), op2("eq", "m", "a"), op2("eq", "z", "m")]);
TAG # let j = result(&env.run("run", &d(ins, &claim).json()));
TAG # assert_eq!(sf(&j, "verdict"), "abstain");
TAG # assert_eq!(names(j.get("missing").unwrap()), vec!["a", "m", "z"]);
TAG # // supplying one removes it from the list; the rest stay missing
TAG # let j = result(&env.run("run", &d(ins, &claim).facts("{\"m\":true}").json()));
TAG # assert_eq!(sf(&j, "verdict"), "abstain");
TAG # let miss = names(j.get("missing").unwrap());
TAG # assert!(!miss.contains(&"m".to_string()) && miss.contains(&"a".to_string()) && miss.contains(&"z".to_string()), "{miss:?}");
TAG # // all supplied: nothing missing
TAG # let j = result(&env.run("run", &d(ins, &claim).facts("{\"z\":true,\"m\":true,\"a\":true}").json()));
TAG # assert_eq!(sf(&j, "verdict"), "pass");
TAG # assert_eq!(names(j.get("missing").unwrap()), Vec::<String>::new());
TAG # // each operator abstains when one operand is missing
TAG # for (op, ins, facts) in [
TAG # ("subset", SET_IN, "{\"actual\":[\"a\"]}"),
TAG # ("subset", SET_IN, "{\"allowed\":[\"a\"]}"),
TAG # ("disjoint", SET_IN, "{\"actual\":[\"a\"]}"),
TAG # ("eq", "{\"actual\":\"string\",\"allowed\":\"string\"}", "{\"actual\":\"a\"}"),
TAG # ("lt", "{\"actual\":\"int\",\"allowed\":\"int\"}", "{\"allowed\":\"3\"}"),
TAG # ("lte", "{\"actual\":\"int\",\"allowed\":\"int\"}", "{}"),
TAG # ] {
TAG # let j = result(&env.run("run", &d(ins, &op2(op, "actual", "allowed")).facts(facts).json()));
TAG # assert_eq!(sf(&j, "verdict"), "abstain", "{op} {facts}");
TAG # assert_eq!(j.get("witness"), Some(&J::Null));
TAG # assert!(!names(j.get("missing").unwrap()).is_empty());
TAG # }
TAG # let doc = d("{\"x\":\"set<string>\",\"s\":\"string\"}", &op2("contains", "x", "s")).facts("{\"x\":[\"a\"]}").json();
TAG # assert_eq!(verdict(&env.run("run", &doc)), "abstain");
TAG # }
TAG # #[test]
TAG # fn three_valued_all_any_not_follow_the_documented_tables() {
TAG # let env = Env::new("truth");
TAG # let ins = "{\"one\":\"bool\",\"zero\":\"bool\",\"gone\":\"bool\"}";
TAG # let facts = "{\"one\":true,\"zero\":false}";
TAG # fn build(s: &[u8], i: &mut usize) -> (String, char) {
TAG # let c = s[*i];
TAG # *i += 1;
TAG # match c {
TAG # b'T' => (op2("eq", "one", "one"), 'T'),
TAG # b'F' => (op2("eq", "one", "zero"), 'F'),
TAG # b'U' => (op2("eq", "one", "gone"), 'U'),
TAG # b'!' => {
TAG # let (e, v) = build(s, i);
TAG # (not_of(&e), match v { 'T' => 'F', 'F' => 'T', _ => 'U' })
TAG # }
TAG # b'A' | b'O' => {
TAG # assert_eq!(s[*i], b'(');
TAG # *i += 1;
TAG # let (mut es, mut vs) = (Vec::new(), Vec::new());
TAG # while s[*i] != b')' {
TAG # let (e, v) = build(s, i);
TAG # es.push(e);
TAG # vs.push(v);
TAG # }
TAG # *i += 1;
TAG # if c == b'A' {
TAG # let v = if vs.contains(&'F') { 'F' } else if vs.contains(&'U') { 'U' } else { 'T' };
TAG # (all_of(&es), v)
TAG # } else {
TAG # let v = if vs.contains(&'T') { 'T' } else if vs.contains(&'U') { 'U' } else { 'F' };
TAG # (any_of(&es), v)
TAG # }
TAG # }
TAG # other => panic!("bad dsl {}", other as char),
TAG # }
TAG # }
TAG # let check = |expr: &str| {
TAG # let mut i = 0;
TAG # let (claim, v) = build(expr.as_bytes(), &mut i);
TAG # assert_eq!(i, expr.len());
TAG # let want = match v { 'T' => "pass", 'F' => "fail", _ => "abstain" };
TAG # let j = result(&env.run("run", &d(ins, &claim).facts(facts).json()));
TAG # assert_eq!(sf(&j, "verdict"), want, "{expr}");
TAG # if want == "abstain" {
TAG # assert!(names(j.get("missing").unwrap()).contains(&"gone".to_string()), "{expr}");
TAG # }
TAG # };
TAG # let mut level1: Vec<String> = Vec::new();
TAG # for l in ["T", "F", "U"] {
TAG # level1.push(l.to_string());
TAG # level1.push(format!("!{l}"));
TAG # }
TAG # for op in ["A", "O"] {
TAG # for n in 1..=3usize {
TAG # let mut combos: Vec<String> = vec![String::new()];
TAG # for _ in 0..n {
TAG # combos = combos.iter().flat_map(|c| ["T", "F", "U"].map(|l| format!("{c}{l}"))).collect();
TAG # }
TAG # for c in combos {
TAG # level1.push(format!("{op}({c})"));
TAG # level1.push(format!("!{op}({c})"));
TAG # }
TAG # }
TAG # }
TAG # for e in &level1 {
TAG # check(e);
TAG # }
TAG # let sample = ["T", "F", "U", "!U", "!A(TU)", "O(FU)", "A(UF)", "!O(FF)", "A(TTT)", "O(UU)"];
TAG # for a in sample {
TAG # for b in sample {
TAG # check(&format!("A({a}{b})"));
TAG # check(&format!("O({a}{b})"));
TAG # check(&format!("!A({a}{b})"));
TAG # check(&format!("!O({b}{a})"));
TAG # }
TAG # }
TAG # for e in ["A(U!TO(UF)A(UT))", "O(A(UT)O(FF)!U)", "!!U", "!!!T", "A(!U!F)", "O(!F!U)", "!O(A(FU)A(TU))"] {
TAG # check(e);
TAG # }
TAG # }
TAG # #[test]
TAG # fn a_false_operand_decides_all_and_a_true_operand_decides_any_regardless_of_unknown_siblings() {
TAG # let env = Env::new("decide");
TAG # let ins = "{\"one\":\"bool\",\"zero\":\"bool\",\"gone\":\"bool\"}";
TAG # let u = op2("eq", "one", "gone");
TAG # let t = op2("eq", "one", "one");
TAG # let f = op2("eq", "one", "zero");
TAG # let facts = "{\"one\":true,\"zero\":false}";
TAG # let run = |claim: String| verdict(&env.run("run", &d(ins, &claim).facts(facts).json()));
TAG # assert_eq!(run(all_of(&[u.clone(), f.clone()])), "fail");
TAG # assert_eq!(run(all_of(&[f.clone(), u.clone()])), "fail");
TAG # assert_eq!(run(any_of(&[u.clone(), t.clone()])), "pass");
TAG # assert_eq!(run(any_of(&[t.clone(), u.clone()])), "pass");
TAG # assert_eq!(run(all_of(&[t.clone(), u.clone()])), "abstain");
TAG # assert_eq!(run(any_of(&[f.clone(), u.clone()])), "abstain");
TAG # assert_eq!(run(not_of(&u)), "abstain");
TAG # let j = result(&env.run("run", &d(ins, &all_of(&[u.clone(), f.clone()])).facts(facts).json()));
TAG # assert_eq!(j.get("verdict"), Some(&J::Str("fail".into())));
TAG # }
TAG # #[test]
TAG # fn a_missing_required_condition_or_scope_mismatch_abstains_whatever_the_claim_says() {
TAG # let env = Env::new("gates");
TAG # let ins = "{\"one\":\"bool\",\"zero\":\"bool\"}";
TAG # let t = op2("eq", "one", "one");
TAG # let f = op2("eq", "one", "zero");
TAG # let facts = "{\"one\":true,\"zero\":false}";
TAG # for (claim, open_verdict) in [(&t, "pass"), (&f, "fail")] {
TAG # let base = d(ins, claim).facts(facts).req("[\"c1\",\"c2\"]").dscope("{\"project\":\"p\",\"persona\":\"q\"}");
TAG # let open = base.clone().conds("{\"c1\":true,\"c2\":true}").scope("{\"project\":\"p\",\"persona\":\"q\"}");
TAG # assert_eq!(verdict(&env.run("run", &open.json())), open_verdict);
TAG # let gated = [
TAG # ("no conditions", base.clone().scope("{\"project\":\"p\",\"persona\":\"q\"}")),
TAG # ("one missing", open.clone().conds("{\"c1\":true}")),
TAG # ("other missing", open.clone().conds("{\"c2\":true}")),
TAG # ("one false", open.clone().conds("{\"c1\":false,\"c2\":true}")),
TAG # ("other false", open.clone().conds("{\"c1\":true,\"c2\":false}")),
TAG # ("both false", open.clone().conds("{\"c1\":false,\"c2\":false}")),
TAG # ("no scope", open.clone().scope("{}")),
TAG # ("scope omitted", base.clone().conds("{\"c1\":true,\"c2\":true}")),
TAG # ("wrong project", open.clone().scope("{\"project\":\"x\",\"persona\":\"q\"}")),
TAG # ("wrong persona", open.clone().scope("{\"project\":\"p\",\"persona\":\"x\"}")),
TAG # ("one dimension", open.clone().scope("{\"project\":\"p\"}")),
TAG # ];
TAG # for (name, doc) in gated {
TAG # for sub in ["run", "explain"] {
TAG # let j = result(&env.run(sub, &doc.json()));
TAG # assert_eq!(sf(&j, "verdict"), "abstain", "{sub} {name} claim={claim}");
TAG # assert_eq!(j.get("witness"), Some(&J::Null), "{name}");
TAG # }
TAG # }
TAG # }
TAG # }
TAG # #[test]
TAG # fn missing_required_conditions_are_named_in_missing() {
TAG # let env = Env::new("condmissing");
TAG # let doc = d("{\"one\":\"bool\"}", &op2("eq", "one", "one")).facts("{\"one\":true}").req("[\"zeta\",\"alpha\"]");
TAG # let j = result(&env.run("run", &doc.clone().json()));
TAG # assert_eq!(sf(&j, "verdict"), "abstain");
TAG # assert_eq!(names(j.get("missing").unwrap()), vec!["alpha", "zeta"]);
TAG # let j = result(&env.run("run", &doc.clone().conds("{\"zeta\":true}").json()));
TAG # assert_eq!(sf(&j, "verdict"), "abstain");
TAG # assert_eq!(names(j.get("missing").unwrap()), vec!["alpha"]);
TAG # let j = result(&env.run("run", &doc.clone().conds("{\"zeta\":true,\"alpha\":true}").json()));
TAG # assert_eq!(sf(&j, "verdict"), "pass");
TAG # assert_eq!(names(j.get("missing").unwrap()), Vec::<String>::new());
TAG # }
TAG # #[test]
TAG # fn conditions_are_declared_booleans_only() {
TAG # let env = Env::new("conditions");
TAG # let base = d("{\"a\":\"bool\"}", &op2("eq", "a", "a")).facts("{\"a\":true}").req("[\"c1\",\"c2\"]");
TAG # valid(&env, &base.clone().conds("{}").json(), "empty");
TAG # valid(&env, &base.clone().conds("{\"c1\":true}").json(), "partial");
TAG # valid(&env, &base.clone().conds("{\"c1\":false,\"c2\":true}").json(), "false is fine");
TAG # for c in [
TAG # "{\"c3\":true}",
TAG # "{\"c1\":true,\"c3\":true}",
TAG # "{\"C1\":true}",
TAG # "{\"c1\":\"true\"}",
TAG # "{\"c1\":1}",
TAG # "{\"c1\":0}",
TAG # "{\"c1\":null}",
TAG # "{\"c1\":[true]}",
TAG # "{\"c1\":{}}",
TAG # "[\"c1\"]",
TAG # "null",
TAG # "true",
TAG # ] {
TAG # all_err_s(&env, &base.clone().conds(c).json(), c);
TAG # }
TAG # // conditions are rejected when the definition requires none
TAG # let none = d("{\"a\":\"bool\"}", &op2("eq", "a", "a")).facts("{\"a\":true}");
TAG # all_err_s(&env, &none.clone().conds("{\"c1\":true}").json(), "undeclared condition");
TAG # valid(&env, &none.clone().conds("{}").json(), "no conditions");
TAG # let empty_req = none.clone().req("[]");
TAG # valid(&env, &empty_req.clone().conds("{}").json(), "empty required list");
TAG # all_err_s(&env, &empty_req.conds("{\"c1\":false}").json(), "condition not in empty list");
TAG # }
TAG # // ---------------------------------------------------------------- scope
TAG # #[test]
TAG # fn scope_objects_accept_only_the_five_dimensions_with_nonempty_strings() {
TAG # let env = Env::new("scopeshape");
TAG # let base = d("{\"a\":\"bool\"}", &op2("eq", "a", "a")).facts("{\"a\":true}");
TAG # let good = [
TAG # "{}",
TAG # "{\"project\":\"p\"}",
TAG # "{\"persona\":\"p\"}",
TAG # "{\"harness\":\"h\"}",
TAG # "{\"version\":\"1.2.3\"}",
TAG # "{\"machine\":\"m\"}",
TAG # "{\"project\":\"p\",\"persona\":\"q\",\"harness\":\"h\",\"version\":\"v\",\"machine\":\"m\"}",
TAG # "{\"project\":\" \"}",
TAG # "{\"project\":\"a*b\"}",
TAG # "{\"project\":\"**\"}",
TAG # "{\"project\":\"p*\"}",
TAG # "{\"project\":\"\\u00e9\"}",
TAG # "{\"project\":\"\\ud83d\\ude00\"}",
TAG # "{\"project\":\"a b\"}",
TAG # ];
TAG # for s in good {
TAG # valid(&env, &base.clone().dscope(s).json(), s);
TAG # valid(&env, &base.clone().scope(s).json(), s);
TAG # valid(&env, &base.clone().dscope(s).scope(s).json(), s);
TAG # }
TAG # let bad = [
TAG # "{\"project\":\"\"}",
TAG # "{\"project\":null}",
TAG # "{\"project\":1}",
TAG # "{\"project\":true}",
TAG # "{\"project\":[\"p\"]}",
TAG # "{\"project\":{}}",
TAG # "{\"project\":\"*\"}",
TAG # "{\"env\":\"x\"}",
TAG # "{\"cwd\":\"/tmp\"}",
TAG # "{\"user\":\"x\"}",
TAG # "{\"Project\":\"p\"}",
TAG # "{\"PROJECT\":\"p\"}",
TAG # "{\"project \":\"p\"}",
TAG # "{\"project\":\"p\",\"extra\":\"x\"}",
TAG # "{\"*\":\"x\"}",
TAG # "{\"project\":\"p\",\"persona\":\"\"}",
TAG # "[]",
TAG # "[\"project\"]",
TAG # "\"project\"",
TAG # "1",
TAG # "true",
TAG # ];
TAG # for s in bad {
TAG # all_err_s(&env, &base.clone().dscope(s).json(), &format!("definition scope {s}"));
TAG # all_err_s(&env, &base.clone().scope(s).json(), &format!("request scope {s}"));
TAG # }
TAG # // a bad request scope is an error even when the definition scope is different
TAG # all_err_s(&env, &base.clone().dscope("{\"project\":\"p\"}").scope("{\"env\":\"x\"}").json(), "bad request scope");
TAG # all_err_s(&env, &base.clone().dscope("{\"env\":\"x\"}").scope("{\"project\":\"p\"}").json(), "bad definition scope");
TAG # }
TAG # #[test]
TAG # fn scope_matching_is_exact_per_required_dimension() {
TAG # let env = Env::new("scopematch");
TAG # let ins = "{\"one\":\"bool\",\"zero\":\"bool\"}";
TAG # let facts = "{\"one\":true,\"zero\":false}";
TAG # // the claim fails when evaluated, so "fail" proves the scope matched and "abstain" proves it did not
TAG # let claim = op2("eq", "one", "zero");
TAG # let rows: Vec<(Option<&str>, Option<&str>, &str)> = vec![
TAG # (Some("{\"project\":\"p\"}"), Some("{\"project\":\"p\"}"), "fail"),
TAG # (Some("{\"project\":\"p\"}"), Some("{\"project\":\"q\"}"), "abstain"),
TAG # (Some("{\"project\":\"p\"}"), Some("{\"project\":\"P\"}"), "abstain"),
TAG # (Some("{\"project\":\"p\"}"), Some("{\"project\":\"p \"}"), "abstain"),
TAG # (Some("{\"project\":\"p\"}"), Some("{\"project\":\" p\"}"), "abstain"),
TAG # (Some("{\"project\":\"p\"}"), Some("{\"project\":\"pp\"}"), "abstain"),
TAG # (Some("{\"project\":\"pp\"}"), Some("{\"project\":\"p\"}"), "abstain"),
TAG # (Some("{\"project\":\"p\"}"), None, "abstain"),
TAG # (Some("{\"project\":\"p\"}"), Some("{}"), "abstain"),
TAG # (Some("{\"project\":\"p\"}"), Some("{\"persona\":\"p\"}"), "abstain"),
TAG # (Some("{\"project\":\"p\"}"), Some("{\"project\":\"p\",\"persona\":\"x\"}"), "fail"),
TAG # (Some("{}"), Some("{\"project\":\"p\"}"), "fail"),
TAG # (Some("{}"), Some("{}"), "fail"),
TAG # (Some("{}"), None, "fail"),
TAG # (None, Some("{\"project\":\"p\"}"), "fail"),
TAG # (None, None, "fail"),
TAG # (Some("{\"project\":\"p\",\"persona\":\"a\"}"), Some("{\"project\":\"p\"}"), "abstain"),
TAG # (Some("{\"project\":\"p\",\"persona\":\"a\"}"), Some("{\"persona\":\"a\"}"), "abstain"),
TAG # (Some("{\"project\":\"p\",\"persona\":\"a\"}"), Some("{\"project\":\"p\",\"persona\":\"b\"}"), "abstain"),
TAG # (Some("{\"project\":\"p\",\"persona\":\"a\"}"), Some("{\"project\":\"q\",\"persona\":\"a\"}"), "abstain"),
TAG # (Some("{\"project\":\"p\",\"persona\":\"a\"}"), Some("{\"persona\":\"a\",\"project\":\"p\"}"), "fail"),
TAG # (Some("{\"project\":\"p\",\"persona\":\"a\"}"), Some("{\"project\":\"p\",\"persona\":\"a\",\"machine\":\"m\"}"), "fail"),
TAG # (Some("{\"harness\":\"h\"}"), Some("{\"harness\":\"h\"}"), "fail"),
TAG # (Some("{\"harness\":\"h\"}"), Some("{\"harness\":\"H\"}"), "abstain"),
TAG # (Some("{\"version\":\"1.0\"}"), Some("{\"version\":\"1.0\"}"), "fail"),
TAG # (Some("{\"version\":\"1.0\"}"), Some("{\"version\":\"1.00\"}"), "abstain"),
TAG # (Some("{\"version\":\"1.0\"}"), Some("{\"version\":\"1\"}"), "abstain"),
TAG # (Some("{\"machine\":\"m\"}"), Some("{\"machine\":\"m\"}"), "fail"),
TAG # (Some("{\"machine\":\"m\"}"), Some("{\"machine\":\"n\"}"), "abstain"),
TAG # (Some("{\"machine\":\"m\"}"), Some("{\"project\":\"m\"}"), "abstain"),
TAG # (Some("{\"project\":\"a*b\"}"), Some("{\"project\":\"axxb\"}"), "abstain"),
TAG # (Some("{\"project\":\"a*b\"}"), Some("{\"project\":\"a*b\"}"), "fail"),
TAG # (Some("{\"project\":\"pr\\u00f3\"}"), Some("{\"project\":\"pr\\u00f3\"}"), "fail"),
TAG # (Some("{\"project\":\"pr\\u00f3\"}"), Some("{\"project\":\"pr\u{f3}\"}"), "fail"),
TAG # (Some("{\"project\":\"pr\\u00f3\"}"), Some("{\"project\":\"pro\\u0301\"}"), "abstain"),
TAG # (Some("{\"project\":\"pro\\u0301\"}"), Some("{\"project\":\"pr\\u00f3\"}"), "abstain"),
TAG # (Some("{\"project\":\"p\",\"persona\":\"a\",\"harness\":\"h\",\"version\":\"v\",\"machine\":\"m\"}"),
TAG # Some("{\"project\":\"p\",\"persona\":\"a\",\"harness\":\"h\",\"version\":\"v\",\"machine\":\"m\"}"), "fail"),
TAG # (Some("{\"project\":\"p\",\"persona\":\"a\",\"harness\":\"h\",\"version\":\"v\",\"machine\":\"m\"}"),
TAG # Some("{\"project\":\"p\",\"persona\":\"a\",\"harness\":\"h\",\"version\":\"v\",\"machine\":\"x\"}"), "abstain"),
TAG # (Some("{\"project\":\"p\",\"persona\":\"a\",\"harness\":\"h\",\"version\":\"v\",\"machine\":\"m\"}"),
TAG # Some("{\"project\":\"p\",\"persona\":\"a\",\"harness\":\"h\",\"version\":\"v\"}"), "abstain"),
TAG # ];
TAG # for (def, req, want) in rows {
TAG # let mut doc = d(ins, &claim).facts(facts);
TAG # if let Some(s) = def {
TAG # doc = doc.dscope(s);
TAG # }
TAG # if let Some(s) = req {
TAG # doc = doc.scope(s);
TAG # }
TAG # let j = result(&env.run("run", &doc.json()));
TAG # assert_eq!(sf(&j, "verdict"), want, "definition {def:?} request {req:?}");
TAG # // the result reports the explicit current scope, never an inferred one
TAG # let want_scope = match req {
TAG # Some(s) => pairs(&parse_json(s).unwrap()),
TAG # None => vec![],
TAG # };
TAG # assert_eq!(pairs(j.get("scope").unwrap()), want_scope, "definition {def:?} request {req:?}");
TAG # }
TAG # }
TAG # // ---------------------------------------------------------------- expression shape errors, even when unreachable
TAG # #[test]
TAG # fn malformed_predicates_are_rejected_even_in_unreachable_branches() {
TAG # let env = Env::new("shape");
TAG # let ins = "{\"one\":\"bool\",\"zero\":\"bool\",\"a\":\"string\",\"b\":\"string\",\"x\":\"set<string>\",\"n\":\"int\"}";
TAG # let facts = "{\"one\":true,\"zero\":false}";
TAG # let fa = fact("a");
TAG # let fb = fact("b");
TAG # let t = op2("eq", "one", "one");
TAG # let f = op2("eq", "one", "zero");
TAG # let bad: Vec<String> = vec![
TAG # format!("{{\"op\":\"xor\",\"left\":{fa},\"right\":{fb}}}"),
TAG # format!("{{\"op\":\"neq\",\"left\":{fa},\"right\":{fb}}}"),
TAG # format!("{{\"op\":\"gt\",\"left\":{{\"fact\":\"n\"}},\"right\":{{\"fact\":\"n\"}}}}"),
TAG # format!("{{\"op\":\"Eq\",\"left\":{fa},\"right\":{fb}}}"),
TAG # format!("{{\"op\":\"EQ\",\"left\":{fa},\"right\":{fb}}}"),
TAG # format!("{{\"op\":\"ALL\",\"args\":[{t}]}}"),
TAG # format!("{{\"op\":\"Not\",\"arg\":{t}}}"),
TAG # format!("{{\"op\":\"\",\"left\":{fa},\"right\":{fb}}}"),
TAG # format!("{{\"op\":\"eq \",\"left\":{fa},\"right\":{fb}}}"),
TAG # format!("{{\"op\":\"matches\",\"left\":{fa},\"right\":{fb}}}"),
TAG # format!("{{\"op\":\"exec\",\"left\":{fa},\"right\":{fb}}}"),
TAG # format!("{{\"op\":1,\"left\":{fa},\"right\":{fb}}}"),
TAG # format!("{{\"op\":null,\"left\":{fa},\"right\":{fb}}}"),
TAG # format!("{{\"op\":[\"eq\"],\"left\":{fa},\"right\":{fb}}}"),
TAG # format!("{{\"left\":{fa},\"right\":{fb}}}"),
TAG # format!("{{\"op\":\"eq\",\"left\":{fa},\"right\":{fb},\"extra\":1}}"),
TAG # format!("{{\"op\":\"eq\",\"left\":{fa},\"right\":{fb},\"args\":[]}}"),
TAG # format!("{{\"op\":\"eq\",\"left\":{fa},\"right\":{fb},\"arg\":{t}}}"),
TAG # format!("{{\"op\":\"eq\",\"left\":{fa}}}"),
TAG # format!("{{\"op\":\"eq\",\"right\":{fb}}}"),
TAG # format!("{{\"op\":\"eq\"}}"),
TAG # format!("{{\"op\":\"eq\",\"left\":{fa},\"right\":null}}"),
TAG # format!("{{\"op\":\"eq\",\"left\":{{\"fact\":\"nope\"}},\"right\":{fb}}}"),
TAG # format!("{{\"op\":\"eq\",\"left\":{fa},\"right\":{{\"fact\":\"nope\"}}}}"),
TAG # format!("{{\"op\":\"eq\",\"left\":{{\"fact\":\"A\"}},\"right\":{fb}}}"),
TAG # format!("{{\"op\":\"eq\",\"left\":{{\"fact\":\"\"}},\"right\":{fb}}}"),
TAG # format!("{{\"op\":\"eq\",\"left\":{{\"value\":\"lit\"}},\"right\":{fb}}}"),
TAG # format!("{{\"op\":\"eq\",\"left\":{{\"literal\":\"lit\"}},\"right\":{fb}}}"),
TAG # format!("{{\"op\":\"eq\",\"left\":{{\"const\":\"lit\"}},\"right\":{fb}}}"),
TAG # format!("{{\"op\":\"eq\",\"left\":\"lit\",\"right\":{fb}}}"),
TAG # format!("{{\"op\":\"eq\",\"left\":\"a\",\"right\":\"b\"}}"),
TAG # format!("{{\"op\":\"eq\",\"left\":1,\"right\":{fb}}}"),
TAG # format!("{{\"op\":\"eq\",\"left\":true,\"right\":{fb}}}"),
TAG # format!("{{\"op\":\"eq\",\"left\":[\"a\"],\"right\":{fb}}}"),
TAG # format!("{{\"op\":\"eq\",\"left\":{{}},\"right\":{fb}}}"),
TAG # format!("{{\"op\":\"eq\",\"left\":{{\"fact\":1}},\"right\":{fb}}}"),
TAG # format!("{{\"op\":\"eq\",\"left\":{{\"fact\":null}},\"right\":{fb}}}"),
TAG # format!("{{\"op\":\"eq\",\"left\":{{\"fact\":[\"a\"]}},\"right\":{fb}}}"),
TAG # format!("{{\"op\":\"eq\",\"left\":{{\"fact\":\"a\",\"extra\":1}},\"right\":{fb}}}"),
TAG # format!("{{\"op\":\"eq\",\"left\":{{\"fact\":\"a\",\"fact\":\"b\"}},\"right\":{fb}}}"),
TAG # format!("{{\"op\":\"eq\",\"left\":{{\"Fact\":\"a\"}},\"right\":{fb}}}"),
TAG # format!("{{\"op\":\"eq\",\"left\":{t},\"right\":{f}}}"),
TAG # format!("{{\"op\":\"eq\",\"left\":{fa},\"right\":{{\"fact\":\"one\"}}}}"),
TAG # format!("{{\"op\":\"lt\",\"left\":{fa},\"right\":{fb}}}"),
TAG # format!("{{\"op\":\"subset\",\"left\":{fa},\"right\":{fb}}}"),
TAG # format!("{{\"op\":\"contains\",\"left\":{fa},\"right\":{fb}}}"),
TAG # format!("{{\"op\":\"contains\",\"left\":{{\"fact\":\"x\"}},\"right\":{{\"fact\":\"x\"}}}}"),
TAG # format!("{{\"op\":\"disjoint\",\"left\":{{\"fact\":\"x\"}},\"right\":{fb}}}"),
TAG # "{\"op\":\"all\",\"args\":[]}".to_string(),
TAG # "{\"op\":\"any\",\"args\":[]}".to_string(),
TAG # "{\"op\":\"all\"}".to_string(),
TAG # "{\"op\":\"any\"}".to_string(),
TAG # "{\"op\":\"all\",\"args\":null}".to_string(),
TAG # "{\"op\":\"all\",\"args\":\"x\"}".to_string(),
TAG # format!("{{\"op\":\"all\",\"args\":{t}}}"),
TAG # "{\"op\":\"any\",\"args\":[1]}".to_string(),
TAG # "{\"op\":\"any\",\"args\":[null]}".to_string(),
TAG # "{\"op\":\"any\",\"args\":[\"eq\"]}".to_string(),
TAG # "{\"op\":\"any\",\"args\":[[]]}".to_string(),
TAG # format!("{{\"op\":\"all\",\"arg\":{t}}}"),
TAG # format!("{{\"op\":\"all\",\"args\":[{t}],\"arg\":{t}}}"),
TAG # format!("{{\"op\":\"any\",\"args\":[{t}],\"extra\":true}}"),
TAG # format!("{{\"op\":\"all\",\"args\":[{t}],\"left\":{fa}}}"),
TAG # format!("{{\"op\":\"all\",\"args\":[{t},{{\"op\":\"eq\"}}]}}"),
TAG # "{\"op\":\"not\"}".to_string(),
TAG # "{\"op\":\"not\",\"arg\":null}".to_string(),
TAG # "{\"op\":\"not\",\"arg\":1}".to_string(),
TAG # "{\"op\":\"not\",\"arg\":\"x\"}".to_string(),
TAG # "{\"op\":\"not\",\"arg\":{}}".to_string(),
TAG # format!("{{\"op\":\"not\",\"arg\":[{t}]}}"),
TAG # format!("{{\"op\":\"not\",\"args\":[{t}]}}"),
TAG # format!("{{\"op\":\"not\",\"arg\":{t},\"args\":[{t}]}}"),
TAG # format!("{{\"op\":\"not\",\"arg\":{t},\"extra\":1}}"),
TAG # format!("{{\"op\":\"not\",\"arg\":{t},\"arg\":{f}}}"),
TAG # format!("{{\"op\":\"not\",\"left\":{t}}}"),
TAG # format!("{{\"op\":\"all\",\"args\":[{t}],\"args\":[{f}]}}"),
TAG # "{}".to_string(),
TAG # "[]".to_string(),
TAG # "null".to_string(),
TAG # "\"eq\"".to_string(),
TAG # "1".to_string(),
TAG # "true".to_string(),
TAG # "{\"fact\":\"one\"}".to_string(),
TAG # format!("[{t}]"),
TAG # ];
TAG # for b in &bad {
TAG # let direct = d(ins, b).facts(facts).json();
TAG # all_err_s(&env, &direct, &format!("direct {b}"));
TAG # // behind a short circuit that would never read it
TAG # for (wrapped, what) in [
TAG # (any_of(&[t.clone(), b.clone()]), "any[T,bad]"),
TAG # (all_of(&[f.clone(), b.clone()]), "all[F,bad]"),
TAG # (not_of(b), "not[bad]"),
TAG # (any_of(&[t.clone(), all_of(&[f.clone(), b.clone()])]), "any[T,all[F,bad]]"),
TAG # ] {
TAG # let doc = d(ins, &wrapped).facts(facts).json();
TAG # all_err_s(&env, &doc, &format!("{what} {b}"));
TAG # }
TAG # }
TAG # // the good forms of the same shapes still work
TAG # for claim in [any_of(&[t.clone(), f.clone()]), all_of(&[t.clone()]), not_of(&f)] {
TAG # assert_eq!(verdict(&env.run("run", &d(ins, &claim).facts(facts).json())), "pass");
TAG # }
TAG # // a bad reference or type in a branch the evaluator would skip is still an error
TAG # for claim in [
TAG # any_of(&[t.clone(), op2("eq", "a", "one")]),
TAG # any_of(&[t.clone(), op2("lt", "a", "b")]),
TAG # any_of(&[t.clone(), op2("eq", "ghost", "a")]),
TAG # all_of(&[f.clone(), op2("subset", "a", "b")]),
TAG # all_of(&[f.clone(), op2("contains", "x", "x")]),
TAG # ] {
TAG # all_err_s(&env, &d(ins, &claim).facts(facts).json(), &claim);
TAG # }
TAG # }
TAG # // ---------------------------------------------------------------- wire format
TAG # #[test]
TAG # fn invalid_json_is_a_structured_error() {
TAG # let env = Env::new("badjson");
TAG # let inner = &BASE[1..BASE.len() - 1];
TAG # let mut docs: Vec<String> = vec![
TAG # "".into(),
TAG # " ".into(),
TAG # "\n".into(),
TAG # "{".into(),
TAG # "}".into(),
TAG # "{{}}".into(),
TAG # "{\"check\"".into(),
TAG # "{\"check\":".into(),
TAG # "{\"check\":}".into(),
TAG # "{\"check\":{}".into(),
TAG # "{\"check\" {}}".into(),
TAG # "{check:{}}".into(),
TAG # "{'check':{}}".into(),
TAG # "{\"check\":{},}".into(),
TAG # "{,\"check\":{}}".into(),
TAG # "{\"check\":{}} x".into(),
TAG # "{\"check\":{}}{}".into(),
TAG # "x".into(),
TAG # "nul".into(),
TAG # "tru".into(),
TAG # "NaN".into(),
TAG # "undefined".into(),
TAG # "{\"check\":NaN}".into(),
TAG # "{\"check\":Infinity}".into(),
TAG # "{\"check\":undefined}".into(),
TAG # "{\"check\":[1,]}".into(),
TAG # "{\"check\":[,1]}".into(),
TAG # "{\"check\":[1 2]}".into(),
TAG # "{\"check\":\"abc}".into(),
TAG # "{\"check\":\"a\\qb\"}".into(),
TAG # "{\"check\":\"a\\u12\"}".into(),
TAG # "{\"check\":\"a\\u12G4\"}".into(),
TAG # "{\"check\":\"a\\x41\"}".into(),
TAG # "{\"check\":\"a\\'b\"}".into(),
TAG # "{\"check\":\"a\\".into(),
TAG # format!("{BASE} x"),
TAG # format!("{BASE}{BASE}"),
TAG # format!("{BASE},"),
TAG # format!("{BASE}}}"),
TAG # format!("{BASE}\n{BASE}"),
TAG # format!("{BASE} // comment"),
TAG # format!("/* c */ {BASE}"),
TAG # format!("# c\n{BASE}"),
TAG # format!("[{BASE}]"),
TAG # BASE[..BASE.len() - 1].to_string(),
TAG # BASE[..BASE.len() / 2].to_string(),
TAG # BASE.replacen(":", " ", 1),
TAG # BASE.replacen("{\"schema\"", "{schema", 1),
TAG # BASE.replacen("\"id\":", "\"id\"=", 1),
TAG # BASE.replacen("\"id\":\"artifact-membership\"", "\"id\":\"artifact-membership\",", 1),
TAG # BASE.replacen("\"revision\":1,", "\"revision\":1,,", 1),
TAG # BASE.replacen("\"project\":\"release-lab\"", "\"project\":'release-lab'", 1),
TAG # BASE.replacen("true", "True", 1),
TAG # BASE.replacen("true", "tru", 1),
TAG # BASE.replacen("true", "TRUE", 1),
TAG # format!("{{{inner},}}"),
TAG # format!("{{\"a\":1 {inner}}}"),
TAG # ];
TAG # docs.push(format!("\u{feff}{BASE}"));
TAG # docs.push(format!("\u{0}{BASE}"));
TAG # docs.push(format!("{BASE}\u{0}"));
TAG # docs.push(format!("\u{c}{BASE}"));
TAG # docs.push(format!("{BASE}\u{b}"));
TAG # for doc in docs {
TAG # all_err_s(&env, &doc, "invalid json");
TAG # }
TAG # // surrounding JSON whitespace is fine
TAG # valid(&env, &format!(" \n\t\r{BASE}\r\n\t "), "whitespace");
TAG # valid(&env, &BASE.replace(",", ",\n ").replace(":", " : "), "pretty printed");
TAG # }
TAG # #[test]
TAG # fn raw_control_characters_and_bad_utf8_are_rejected_but_escapes_are_fine() {
TAG # let env = Env::new("ctrl");
TAG # for c in ["\n", "\t", "\r", "\u{1}", "\u{8}", "\u{b}", "\u{c}", "\u{1f}", "\u{0}"] {
TAG # all_err_s(&env, &BASE.replacen("release.bin", &format!("rel{c}ease"), 1), &format!("control {c:?} in a value"));
TAG # all_err_s(&env, &BASE.replacen("\"actual\":[", &format!("\"ac{c}tual\":["), 1), &format!("control {c:?} in a key"));
TAG # all_err_s(&env, &BASE.replacen("artifact-membership", &format!("{c}"), 1), &format!("control {c:?} as id"));
TAG # }
TAG # for esc in ["\\n", "\\t", "\\r", "\\b", "\\f", "\\u0001", "\\u001f", "\\u0000", "\\\"", "\\\\", "\\/"] {
TAG # valid(&env, &set_doc("subset", &format!("[\"a{esc}b\"]"), "[]"), esc);
TAG # }
TAG # // 0x7f and non-ASCII are not control characters of the JSON grammar
TAG # valid(&env, &set_doc("subset", "[\"a\u{7f}b\"]", "[]"), "DEL");
TAG # valid(&env, &set_doc("subset", "[\"\u{85}\u{2028}\u{2029}\"]", "[]"), "unicode separators");
TAG # let prefix = b"{\"check\":{\"schema\":\"instinct.check/v1\",\"id\":\"t1\",\"revision\":1,\"inputs\":{\"s\":\"string\"},\"claim\":{\"op\":\"eq\",\"left\":{\"fact\":\"s\"},\"right\":{\"fact\":\"s\"}}},\"facts\":{\"s\":\"";
TAG # let suffix = b"\"}}";
TAG # let mk = |mid: &[u8]| {
TAG # let mut v = prefix.to_vec();
TAG # v.extend_from_slice(mid);
TAG # v.extend_from_slice(suffix);
TAG # v
TAG # };
TAG # assert_eq!(verdict(&env.run_bytes("run", &mk("caf\u{e9} \u{1F600}".as_bytes()))), "pass");
TAG # for (name, mid) in [
TAG # ("0xff", vec![0xffu8]),
TAG # ("0xfe", vec![0xfe]),
TAG # ("lone continuation", vec![0x80]),
TAG # ("truncated 2-byte", vec![b'a', 0xc3]),
TAG # ("overlong slash", vec![0xc0, 0xaf]),
TAG # ("overlong nul", vec![0xc0, 0x80]),
TAG # ("truncated 3-byte", vec![0xe2, 0x82]),
TAG # ("encoded surrogate", vec![0xed, 0xa0, 0x80]),
TAG # ("encoded low surrogate", vec![0xed, 0xbf, 0xbf]),
TAG # ("above U+10FFFF", vec![0xf4, 0x90, 0x80, 0x80]),
TAG # ("5-byte form", vec![0xf8, 0x88, 0x80, 0x80, 0x80]),
TAG # ("truncated 4-byte", vec![0xf0, 0x9f, 0x98]),
TAG # ] {
TAG # all_err(&env, &mk(&mid), name);
TAG # }
TAG # // invalid UTF-8 outside strings too
TAG # let mut bad = BASE.as_bytes().to_vec();
TAG # bad.push(0xff);
TAG # all_err(&env, &bad, "trailing 0xff");
TAG # }
TAG # #[test]
TAG # fn duplicate_keys_are_rejected_everywhere_including_escaped_spellings() {
TAG # let env = Env::new("dupkeys");
TAG # // (anchor that occurs exactly once in BASE, replacement that adds a duplicate)
TAG # let rows: Vec<(&str, &str)> = vec![
TAG # ("\"id\":\"artifact-membership\"", "\"id\":\"artifact-membership\",\"id\":\"artifact-membership\""),
TAG # ("\"id\":\"artifact-membership\"", "\"id\":\"artifact-membership\",\"id\":\"other\""),
TAG # ("\"id\":\"artifact-membership\"", "\"id\":\"artifact-membership\",\"\\u0069d\":\"artifact-membership\""),
TAG # ("\"id\":\"artifact-membership\"", "\"id\":\"artifact-membership\",\"i\\u0064\":\"x\""),
TAG # ("\"id\":\"artifact-membership\"", "\"id\":\"artifact-membership\",\"\\u0049d\":\"x\",\"i\\u0064\":\"y\""),
TAG # ("\"revision\":1", "\"revision\":1,\"revision\":1"),
TAG # ("\"revision\":1", "\"revision\":1,\"\\u0072evision\":1"),
TAG # ("\"schema\":\"instinct.check/v1\"", "\"schema\":\"instinct.check/v1\",\"sch\\u0065ma\":\"instinct.check/v1\""),
TAG # ("\"inputs\":{", "\"inputs\":{\"actual\":\"set<string>\","),
TAG # ("\"inputs\":{", "\"inputs\":{\"a\\u0063tual\":\"set<string>\","),
TAG # ("\"inputs\":{\"actual\":\"set<string>\"", "\"inputs\":{\"actual\":\"set<string>\",\"\\u0061ctual\":\"string\""),
TAG # ("\"inputs\":{\"actual\":\"set<string>\"", "\"inputs\":{\"actual\":\"set<string>\",\"a\\u0063\\u0074ual\":\"set<string>\""),
TAG # ("\"allowed\":\"set<string>\"}", "\"allowed\":\"set<string>\",\"allowed\":\"set<string>\"}"),
TAG # ("\"claim\":{\"op\":\"subset\"", "\"claim\":{\"op\":\"subset\",\"op\":\"subset\""),
TAG # ("\"claim\":{\"op\":\"subset\"", "\"claim\":{\"op\":\"subset\",\"o\\u0070\":\"subset\""),
TAG # ("\"claim\":{\"op\":\"subset\"", "\"claim\":{\"op\":\"subset\",\"\\u006fp\":\"disjoint\""),
TAG # ("\"left\":{\"fact\":\"actual\"}", "\"left\":{\"fact\":\"actual\",\"fact\":\"actual\"}"),
TAG # ("\"left\":{\"fact\":\"actual\"}", "\"left\":{\"fact\":\"actual\",\"f\\u0061ct\":\"actual\"}"),
TAG # ("\"left\":{\"fact\":\"actual\"}", "\"left\":{\"fact\":\"actual\"},\"left\":{\"fact\":\"actual\"}"),
TAG # ("\"left\":{\"fact\":\"actual\"}", "\"left\":{\"fact\":\"actual\"},\"l\\u0065ft\":{\"fact\":\"actual\"}"),
TAG # ("\"right\":{\"fact\":\"allowed\"}", "\"right\":{\"fact\":\"allowed\"},\"right\":{\"fact\":\"allowed\"}"),
TAG # ("\"right\":{\"fact\":\"allowed\"}", "\"right\":{\"fact\":\"allowed\"},\"r\\u0069ght\":{\"fact\":\"allowed\"}"),
TAG # ("\"required_conditions\":[", "\"required_conditions\":[\"complete-inventory\"],\"required_conditions\":["),
TAG # ("\"required_conditions\":[", "\"required_conditions\":[\"complete-inventory\"],\"required_cond\\u0069tions\":["),
TAG # ("\"scope\":{\"project\":\"release-lab\"}},\"facts\"", "\"scope\":{\"project\":\"release-lab\"},\"scope\":{\"project\":\"release-lab\"}},\"facts\""),
TAG # ("\"scope\":{\"project\":\"release-lab\"}},\"facts\"", "\"scope\":{\"project\":\"release-lab\",\"project\":\"release-lab\"}},\"facts\""),
TAG # ("\"scope\":{\"project\":\"release-lab\"}},\"facts\"", "\"scope\":{\"project\":\"release-lab\",\"\\u0070roject\":\"other\"}},\"facts\""),
TAG # ("\"scope\":{\"project\":\"release-lab\"}},\"facts\"", "\"scope\":{\"project\":\"release-lab\"},\"sc\\u006fpe\":{}},\"facts\""),
TAG # ("\"facts\":{", "\"facts\":{\"actual\":[],"),
TAG # ("\"facts\":{", "\"facts\":{\"actual\":[\"release.bin\",\"scratch.env\"],\"\\u0061ctual\":[],"),
TAG # ("\"facts\":{\"actual\":[\"release.bin\",\"scratch.env\"]", "\"facts\":{\"actual\":[\"release.bin\",\"scratch.env\"],\"actual\":[\"release.bin\",\"scratch.env\"]"),
TAG # ("\"allowed\":[\"release.bin\"]}", "\"allowed\":[\"release.bin\"],\"allowed\":[\"release.bin\"]}"),
TAG # ("\"allowed\":[\"release.bin\"]}", "\"allowed\":[\"release.bin\"],\"a\\u006cl\\u006fwed\":[]}"),
TAG # ("\"allowed\":[\"release.bin\"]}", "\"allowed\":[\"release.bin\"],\"\\u0041llowed\":[],\"allowed\":[]}"),
TAG # ("\"allowed\":[\"release.bin\"]},\"conditions\"", "\"allowed\":[\"release.bin\"]},\"facts\":{},\"conditions\""),
TAG # ("\"allowed\":[\"release.bin\"]},\"conditions\"", "\"allowed\":[\"release.bin\"]},\"f\\u0061cts\":{},\"conditions\""),
TAG # ("\"allowed\":[\"release.bin\"]},\"conditions\"", "\"allowed\":[\"release.bin\"]},\"\\u0066acts\":{\"actual\":[],\"allowed\":[]},\"conditions\""),
TAG # ("\"conditions\":{", "\"conditions\":{\"complete-inventory\":true,"),
TAG # ("\"conditions\":{", "\"conditions\":{\"complete\\u002dinventory\":true,"),
TAG # ("\"conditions\":{", "\"conditions\":{\"complete\\u002Dinventory\":false,"),
TAG # ("\"explicit-policy\":true}", "\"explicit-policy\":true,\"explicit-policy\":true}"),
TAG # ("\"explicit-policy\":true},\"scope\":{\"project\":\"release-lab\"}}", "\"explicit-policy\":true},\"conditions\":{},\"scope\":{\"project\":\"release-lab\"}}"),
TAG # ("\"explicit-policy\":true},\"scope\":{\"project\":\"release-lab\"}}", "\"explicit-policy\":true},\"cond\\u0069tions\":{},\"scope\":{\"project\":\"release-lab\"}}"),
TAG # ("\"explicit-policy\":true},\"scope\":{\"project\":\"release-lab\"}}", "\"explicit-policy\":true},\"scope\":{\"project\":\"release-lab\"},\"scope\":{\"project\":\"release-lab\"}}"),
TAG # ("\"explicit-policy\":true},\"scope\":{\"project\":\"release-lab\"}}", "\"explicit-policy\":true},\"scope\":{\"project\":\"release-lab\",\"project\":\"release-lab\"}}"),
TAG # ("\"explicit-policy\":true},\"scope\":{\"project\":\"release-lab\"}}", "\"explicit-policy\":true},\"scope\":{\"project\":\"release-lab\"},\"\\u0073cope\":{}}"),
TAG # ("\"explicit-policy\":true},\"scope\":{\"project\":\"release-lab\"}}", "\"explicit-policy\":true},\"scope\":{\"pro\\u006aect\":\"x\",\"project\":\"release-lab\"}}"),
TAG # ("{\"check\":{", "{\"check\":{},\"check\":{"),
TAG # ("{\"check\":{", "{\"ch\\u0065ck\":{},\"check\":{"),
TAG # ("{\"check\":{", "{\"\\u0063heck\":{\"x\":1},\"check\":{"),
TAG # ("{\"check\":{", "{\"che\\u0063k\":{\"schema\":\"instinct.check/v1\"},\"check\":{"),
TAG # ];
TAG # for (anchor, repl) in rows {
TAG # let doc = mutate(anchor, repl);
TAG # all_err_s(&env, &doc, "duplicate key");
TAG # }
TAG # // every spelling of a duplicated top-level key, same value or not
TAG # for (k, v) in [("facts", "{}"), ("conditions", "{}"), ("scope", "{}")] {
TAG # for esc in [k.to_string(), format!("\\u{:04x}{}", k.as_bytes()[0], &k[1..]), format!("{}\\u{:04x}", &k[..k.len() - 1], k.as_bytes()[k.len() - 1])] {
TAG # let doc = format!("{{\"check\":{{\"schema\":\"instinct.check/v1\",\"id\":\"t1\",\"revision\":1,\"inputs\":{{\"a\":\"bool\"}},\"claim\":{{\"op\":\"eq\",\"left\":{{\"fact\":\"a\"}},\"right\":{{\"fact\":\"a\"}}}}}},\"{k}\":{v},\"{esc}\":{v}}}");
TAG # all_err_s(&env, &doc, &format!("top-level {k} as {esc}"));
TAG # }
TAG # }
TAG # // Unicode: the escaped and literal spellings of one key collide, in any object
TAG # for (a, b) in [
TAG # ("\\u00e9", "\u{e9}"),
TAG # ("\\u00E9", "\\u00e9"),
TAG # ("\\ud83d\\ude00", "\u{1F600}"),
TAG # ("\\ud83d\\ude00", "\\uD83D\\uDE00"),
TAG # ("a\\/b", "a/b"),
TAG # ("\\u0041", "A"),
TAG # ("\\u00e9\\u0301", "\u{e9}\\u0301"),
TAG # ("\\u0000", "\\u0000"),
TAG # ] {
TAG # let doc = d(&format!("{{\"{a}\":\"string\",\"{b}\":\"string\"}}"), &op2("eq", "x", "x")).json();
TAG # all_err_s(&env, &doc, &format!("inputs {a} / {b}"));
TAG # let doc = d("{\"s\":\"string\"}", &op2("eq", "s", "s")).facts(&format!("{{\"s\":\"v\",\"{a}\":\"v\",\"{b}\":\"v\"}}")).json();
TAG # all_err_s(&env, &doc, &format!("facts {a} / {b}"));
TAG # let doc = d("{\"s\":\"string\"}", &op2("eq", "s", "s")).dscope(&format!("{{\"{a}\":\"v\",\"{b}\":\"v\"}}")).json();
TAG # all_err_s(&env, &doc, &format!("scope {a} / {b}"));
TAG # }
TAG # // keys that differ only by case or by an extra character are different keys
TAG # let two = d("{\"e\":\"string\",\"E\":\"string\",\"ee\":\"string\",\"e\\u0045\":\"string\"}", &op2("eq", "e", "E"))
TAG # .facts("{\"e\":\"3\",\"E\":\"3\",\"ee\":\"1\"}")
TAG # .json();
TAG # assert_eq!(verdict(&env.run("run", &two)), "pass");
TAG # }
TAG # #[test]
TAG # fn malformed_numbers_anywhere_are_errors() {
TAG # let env = Env::new("numbers");
TAG # for n in [
TAG # "01", "00", "-01", "1.", ".5", "-.5", "1.e3", "1e", "1e+", "1e-", "+1", "-", "--1", "0x1", "1_0", "1,0", "Infinity", "-Infinity", "NaN",
TAG # "1.0.0", "1e1e1", "٣", "1 1", "0123", "1E", "- 1", "1d", "0b1", "0o7", "1f", "1L", "0.0.0", "1e0.5",
TAG # ] {
TAG # for place in [
TAG # BASE.replacen("\"revision\":1", &format!("\"revision\":{n}"), 1),
TAG # d("{\"a\":\"bool\"}", &op2("eq", "a", "a")).facts(&format!("{{\"a\":{n}}}")).json(),
TAG # d("{\"a\":\"bool\"}", &op2("eq", "a", "a")).facts(&format!("{{\"a\":true,\"zz\":[{n}]}}")).json(),
TAG # format!("{{\"check\":{{}},\"x\":{n}}}"),
TAG # d("{\"a\":\"bool\"}", &op2("eq", "a", "a")).json().replacen("\"check\":{", &format!("\"x\":{n},\"check\":{{"), 1),
TAG # ] {
TAG # all_err_s(&env, &place, &format!("number {n}"));
TAG # }
TAG # }
TAG # for n in ["1e999999", "1e-999999", "123456789012345678901234567890e5", "-1e400", "1E+400", "9".repeat(5000).as_str()] {
TAG # all_err_s(&env, &BASE.replacen("\"revision\":1", &format!("\"revision\":{n}"), 1), n);
TAG # }
TAG # }
TAG # #[test]
TAG # fn json_nesting_beyond_64_is_an_error_and_deep_input_does_not_crash() {
TAG # let env = Env::new("nesting");
TAG # let head = "{\"check\":{\"schema\":\"instinct.check/v1\",\"id\":\"t1\",\"revision\":1,\"inputs\":{\"a\":\"bool\"},\"claim\":{\"op\":\"eq\",\"left\":{\"fact\":\"a\"},\"right\":{\"fact\":\"a\"}}},\"facts\":{\"a\":";
TAG # for n in [65usize, 70, 100, 1000, 100_000, 500_000] {
TAG # for (open, close) in [("[", "]"), ("{\"k\":", "}")] {
TAG # let doc = format!("{head}{}true{}}}}}", open.repeat(n), close.repeat(n));
TAG # if doc.len() > 1_048_576 {
TAG # continue;
TAG # }
TAG # for sub in ["run", "validate"] {
TAG # let o = env.run(sub, &doc);
TAG # assert!(o.code.is_some(), "deep input killed the process by signal (nesting {n} {open}): stderr={}", trunc(&String::from_utf8_lossy(&o.err)));
TAG # err(&o, &format!("{sub} nesting {n} {open}"));
TAG # }
TAG # }
TAG # }
TAG # // nesting inside the claim is bounded the same way (and the claim depth limit)
TAG # let mut claim = op2("eq", "a", "a");
TAG # for _ in 0..70 {
TAG # claim = not_of(&claim);
TAG # }
TAG # all_err_s(&env, &d("{\"a\":\"bool\"}", &claim).facts("{\"a\":true}").json(), "70 nested not");
TAG # // nesting inside inputs
TAG # let nested = format!("{}{}", "[".repeat(80), "]".repeat(80));
TAG # all_err_s(&env, &d(&format!("{{\"a\":{nested}}}"), &op2("eq", "a", "a")).json(), "deep inputs");
TAG # }
TAG # #[test]
TAG # fn input_is_limited_to_one_mebibyte_from_stdin_and_from_files() {
TAG # let env = Env::new("size");
TAG # let limit = 1_048_576usize;
TAG # let mut exact = BASE.as_bytes().to_vec();
TAG # exact.resize(limit, b' ');
TAG # assert_eq!(exact.len(), limit);
TAG # let mut over = exact.clone();
TAG # over.push(b' ');
TAG # let mut way_over = BASE.as_bytes().to_vec();
TAG # way_over.resize(3 * limit, b' ');
TAG # let ex_path = env.put("exact.json", &exact);
TAG # let over_path = env.put("over.json", &over);
TAG # let way_path = env.put("way.json", &way_over);
TAG # for sub in ["validate", "run", "explain"] {
TAG # let o = env.run_bytes(sub, &exact);
TAG # assert_eq!(o.code, Some(0), "{sub} exactly 1 MiB: {}", trunc(&o.text()));
TAG # let f = env.exec(&["check", sub, "--input", ex_path.to_str().unwrap()], b"");
TAG # assert_eq!(f.out, o.out, "{sub} file == stdin at the limit");
TAG # err(&env.run_bytes(sub, &over), &format!("{sub} stdin 1 MiB + 1"));
TAG # err(&env.exec(&["check", sub, "--input", over_path.to_str().unwrap()], b""), &format!("{sub} file 1 MiB + 1"));
TAG # err(&env.run_bytes(sub, &way_over), &format!("{sub} stdin 3 MiB"));
TAG # err(&env.exec(&["check", sub, "--input", way_path.to_str().unwrap()], b""), &format!("{sub} file 3 MiB"));
TAG # }
TAG # // oversized garbage is an error, not a hang or crash
TAG # let junk = vec![b'x'; 8 * limit];
TAG # err(&env.run_bytes("run", &junk), "8 MiB of junk");
TAG # // an over-limit document whose first MiB is valid is still an error
TAG # let mut tail = BASE.as_bytes().to_vec();
TAG # tail.resize(limit, b' ');
TAG # tail.extend_from_slice(b"{}");
TAG # err(&env.run_bytes("run", &tail), "valid prefix, junk after the limit");
TAG # }
TAG # // ---------------------------------------------------------------- structural, fuel and output limits
TAG # #[test]
TAG # fn claim_depth_and_node_limits_are_enforced_before_evaluation() {
TAG # let env = Env::new("claimlimits");
TAG # let ins = "{\"a\":\"bool\"}";
TAG # let leaf = op2("eq", "a", "a");
TAG # // within limits
TAG # for k in [0usize, 1, 10, 20, 30] {
TAG # let mut claim = leaf.clone();
TAG # for _ in 0..k {
TAG # claim = not_of(&claim);
TAG # }
TAG # let want = if k % 2 == 0 { "pass" } else { "fail" };
TAG # assert_eq!(verdict(&env.run("run", &d(ins, &claim).facts("{\"a\":true}").json())), want, "not^{k}");
TAG # }
TAG # let mut nest = leaf.clone();
TAG # for _ in 0..20 {
TAG # nest = all_of(&[nest]);
TAG # }
TAG # assert_eq!(verdict(&env.run("run", &d(ins, &nest).facts("{\"a\":true}").json())), "pass");
TAG # // too deep
TAG # for k in [40usize, 50, 60] {
TAG # let mut claim = leaf.clone();
TAG # for _ in 0..k {
TAG # claim = not_of(&claim);
TAG # }
TAG # all_err_s(&env, &d(ins, &claim).facts("{\"a\":true}").json(), &format!("not^{k}"));
TAG # let mut claim = leaf.clone();
TAG # for _ in 0..k {
TAG # claim = any_of(&[claim]);
TAG # }
TAG # all_err_s(&env, &d(ins, &claim).facts("{\"a\":true}").json(), &format!("any^{k}"));
TAG # }
TAG # // many nodes, shallow
TAG # let leaves = |n: usize| (0..n).map(|_| leaf.clone()).collect::<Vec<_>>();
TAG # assert_eq!(verdict(&env.run("run", &d(ins, &all_of(&leaves(1000))).facts("{\"a\":true}").json())), "pass");
TAG # assert_eq!(verdict(&env.run("run", &d(ins, &any_of(&leaves(1000))).facts("{\"a\":true}").json())), "pass");
TAG # for n in [4200usize, 5000, 9000] {
TAG # all_err_s(&env, &d(ins, &all_of(&leaves(n))).facts("{\"a\":true}").json(), &format!("all of {n} leaves"));
TAG # all_err_s(&env, &d(ins, &any_of(&leaves(n))).facts("{\"a\":true}").json(), &format!("any of {n} leaves"));
TAG # }
TAG # let groups: Vec<String> = (0..100).map(|_| all_of(&leaves(50))).collect();
TAG # all_err_s(&env, &d(ins, &all_of(&groups)).facts("{\"a\":true}").json(), "100 groups of 50");
TAG # }
TAG # #[test]
TAG # fn oversized_fact_sets_are_bounded_not_passed() {
TAG # let env = Env::new("factlimits");
TAG # // within the limit
TAG # let big = many(4000, "m");
TAG # assert_eq!(verdict(&env.run("run", &set_doc("subset", &big, &big))), "pass");
TAG # valid(&env, &set_doc("subset", &big, &big), "4000 members");
TAG # // beyond 10000 members in aggregate: bounded outcome, never a pass or a crash
TAG # for (l, r) in [(many(10_500, "m"), "[]".to_string()), (many(6000, "l"), many(6000, "r")), (many(20_000, "m"), many(20_000, "m"))] {
TAG # let doc = set_doc("subset", &l, &r);
TAG # for sub in ["run", "validate", "explain"] {
TAG # let o = env.run_bytes(sub, doc.as_bytes());
TAG # match o.code {
TAG # Some(2) => err(&o, &format!("{sub} oversized facts")),
TAG # Some(0) => {
TAG # let j = obj(&o);
TAG # if sub == "validate" {
TAG # panic!("validation accepted facts over the aggregate limit: {}", trunc(&o.text()));
TAG # }
TAG # assert_eq!(sf(&j, "verdict"), "abstain", "{sub} oversized facts must abstain, got {}", trunc(&o.text()));
TAG # assert!(o.out.len() <= 65_537);
TAG # }
TAG # other => panic!("{sub} oversized facts: unexpected exit {other:?}"),
TAG # }
TAG # }
TAG # }
TAG # // beyond 10000 entries: many declared scalar facts
TAG # let n = 10_600;
TAG # let inputs = format!("{{{}}}", (0..n).map(|i| format!("\"f{i}\":\"bool\"")).collect::<Vec<_>>().join(","));
TAG # let facts = format!("{{{}}}", (0..n).map(|i| format!("\"f{i}\":true")).collect::<Vec<_>>().join(","));
TAG # let doc = d(&inputs, &op2("eq", "f0", "f1")).facts(&facts).json();
TAG # for sub in ["run", "explain"] {
TAG # let o = env.run(sub, &doc);
TAG # match o.code {
TAG # Some(2) => err(&o, "entries over limit"),
TAG # Some(0) => assert_eq!(sf(&obj(&o), "verdict"), "abstain", "entries over limit must not pass"),
TAG # other => panic!("unexpected exit {other:?}"),
TAG # }
TAG # }
TAG # }
TAG # #[test]
TAG # fn fuel_exhaustion_abstains_and_never_reports_partial_evaluation_as_pass() {
TAG # let env = Env::new("fuel");
TAG # let n = 4900;
TAG # let left = many(n, "m");
TAG # let mut rev: Vec<String> = (0..n).map(|i| format!("\"m{i:05}\"")).collect();
TAG # rev.reverse();
TAG # let right = format!("[{}]", rev.join(","));
TAG # let sub = op2("subset", "actual", "allowed");
TAG # let facts = format!("{{\"actual\":{left},\"allowed\":{right}}}");
TAG # // a single pass over this input is cheap and true
TAG # assert_eq!(verdict(&env.run("run", &d(SET_IN, &sub).facts(&facts).json())), "pass");
TAG # // thirty full scans cost at least 30 * 4900 charged operations: over the 100000 budget
TAG # let heavy = all_of(&(0..30).map(|_| sub.clone()).collect::<Vec<_>>());
TAG # for s in ["run", "explain"] {
TAG # let o = env.run(s, &d(SET_IN, &heavy).facts(&facts).json());
TAG # let j = result(&o);
TAG # assert_eq!(sf(&j, "verdict"), "abstain", "{s}: fuel exhaustion must abstain: {}", trunc(&o.text()));
TAG # assert_eq!(j.get("witness"), Some(&J::Null));
TAG # assert!(o.out.len() <= 65_537);
TAG # }
TAG # // negation, nesting and any must not turn the exhausted evaluation into a pass or a fail
TAG # for claim in [not_of(&heavy), all_of(&[heavy.clone()]), not_of(¬_of(&heavy)), all_of(&[heavy.clone(), heavy.clone()])] {
TAG # let v = verdict(&env.run("run", &d(SET_IN, &claim).facts(&facts).json()));
TAG # assert_eq!(v, "abstain", "exhaustion under a wrapper");
TAG # }
TAG # // validation never spends the fuel
TAG # valid(&env, &d(SET_IN, &heavy).facts(&facts).json(), "heavy claim validates");
TAG # // a definition that cannot be evaluated cheaply still reports where it was declared
TAG # let j = result(&env.run("run", &d(SET_IN, &heavy).id("\"burner\"").rev("7").facts(&facts).json()));
TAG # assert_eq!(sf(&j, "check_id"), "burner");
TAG # assert_eq!(j.get("revision"), Some(&J::Num("7".into())));
TAG # }
TAG # #[test]
TAG # fn witnesses_and_errors_are_bounded_to_64_kib() {
TAG # let env = Env::new("bounded");
TAG # // a witness that cannot fit in 64 KiB is a bounded explicit error, never a truncated or substituted witness
TAG # for n in [100_000usize, 300_000] {
TAG # let huge = "x".repeat(n);
TAG # for sub in ["run", "explain"] {
TAG # for doc in [
TAG # set_doc("subset", &format!("[\"{huge}\"]"), "[]"),
TAG # set_doc("disjoint", &format!("[\"{huge}\"]"), &format!("[\"{huge}\"]")),
TAG # ] {
TAG # err(&env.run(sub, &doc), &format!("{sub} {n}-byte witness"));
TAG # }
TAG # }
TAG # }
TAG # let wide = "\u{1F600}".repeat(60_000);
TAG # err(&env.run("run", &set_doc("subset", &format!("[\"{wide}\"]"), "[]")), "240000-byte multibyte witness");
TAG # // an error never echoes the request
TAG # let long_key = "k".repeat(300_000);
TAG # let docs = [
TAG # BASE.replacen("\"facts\":{", &format!("\"facts\":{{\"{long_key}\":1,"), 1),
TAG # BASE.replacen("\"id\":\"artifact-membership\"", &format!("\"id\":\"{long_key}\""), 1),
TAG # BASE.replacen("\"op\":\"subset\"", &format!("\"op\":\"{long_key}\""), 1),
TAG # BASE.replacen("\"actual\":\"set<string>\"", &format!("\"actual\":\"{long_key}\""), 1),
TAG # BASE.replacen("\"project\":\"release-lab\"}},", &format!("\"{long_key}\":\"x\"}},"), 1),
TAG # format!("{{\"{long_key}\":1}}"),
TAG # BASE.replacen("\"complete-inventory\":true", &format!("\"{long_key}\":true"), 1),
TAG # set_doc("subset", &format!("[\"{long_key}\",\"{long_key}\"]"), "[]"),
TAG # set_doc("subset", &format!("[1,\"{long_key}\"]"), "[]"),
TAG # ];
TAG # for doc in &docs {
TAG # for sub in ["run", "validate", "explain"] {
TAG # let o = env.run(sub, doc);
TAG # err(&o, &format!("{sub} long-key error"));
TAG # assert!(!o.text().contains(&"k".repeat(1000)), "{sub}: the error repeated the request");
TAG # }
TAG # }
TAG # }
TAG # // ---------------------------------------------------------------- CLI
TAG # #[test]
TAG # fn cli_argument_mistakes_are_errors_and_have_no_side_effects() {
TAG # let env = Env::new("cliargs");
TAG # let f = env.put("good.json", BASE.as_bytes());
TAG # let f = f.to_str().unwrap();
TAG # let rows: Vec<Vec<&str>> = vec![
TAG # vec!["check", "frob"],
TAG # vec!["check", "RUN", "--input", f],
TAG # vec!["check", "Run", "--input", f],
TAG # vec!["check", "", "--input", f],
TAG # vec!["check", "--input", f],
TAG # vec!["check", "-"],
TAG # vec!["check", f],
TAG # vec!["check", "run"],
TAG # vec!["check", "validate"],
TAG # vec!["check", "explain"],
TAG # vec!["check", "run", "--input"],
TAG # vec!["check", "validate", "--input"],
TAG # vec!["check", "explain", "--input"],
TAG # vec!["check", "run", "--input", f, "--input", f],
TAG # vec!["check", "validate", "--input", f, "--input", f],
TAG # vec!["check", "explain", "--input", f, "--input", f],
TAG # vec!["check", "run", "--input", "-", "--input", "-"],
TAG # vec!["check", "run", "--input", f, "--input", "-"],
TAG # vec!["check", "run", "--input", "-", "--input", f],
TAG # vec!["check", "run", "--input", f, "extra"],
TAG # vec!["check", "run", "extra", "--input", f],
TAG # vec!["check", "run", f],
TAG # vec!["check", "run", "-"],
TAG # vec!["check", "validate", "--input", f, "run"],
TAG # vec!["check", "run", "run", "--input", f],
TAG # vec!["check", "run", "--input", f, "--input"],
TAG # vec!["check", "run", "--bogus"],
TAG # vec!["check", "run", "--bogus", "--input", f],
TAG # vec!["check", "run", "--input", f, "--bogus"],
TAG # vec!["check", "run", "--input", f, "--bogus=1"],
TAG # vec!["check", "run", "-i", f],
TAG # vec!["check", "run", "-input", f],
TAG # vec!["check", "run", "--Input", f],
TAG # vec!["check", "run", "--INPUT", f],
TAG # vec!["check", "run", "--inputs", f],
TAG # vec!["check", "run", "--in", f],
TAG # vec!["check", "run", "--file", f],
TAG # vec!["check", "run", "--json", "--input", f],
TAG # vec!["check", "run", "--input", f, "--json"],
TAG # vec!["check", "run", "--verbose", "--input", f],
TAG # vec!["check", "run", "--store", f, "--input", f],
TAG # vec!["check", "validate", "--bogus"],
TAG # vec!["check", "explain", "--bogus"],
TAG # vec!["check", "explain", "--input", f, "-x"],
TAG # vec!["check", "run", "--"],
TAG # vec!["check", "run", "--", "--input", f],
TAG # vec!["check", "run", "--input", "--input", f],
TAG # vec!["check", "run", "--input", f, "--help", "--help"],
TAG # ];
TAG # for row in &rows {
TAG # let o = env.exec(row, BASE.as_bytes());
TAG # if row == &vec!["check", "-"] || row == &vec!["check", f] {
TAG # assert_ne!(o.code, Some(0), "{row:?}");
TAG # continue;
TAG # }
TAG # err(&o, &format!("{row:?}"));
TAG # }
TAG # // a bare `check` is not a success either
TAG # let o = env.exec(&["check"], BASE.as_bytes());
TAG # assert_ne!(o.code, Some(0), "bare `check`");
TAG # assert!(!o.text().contains("\"pass\""));
TAG # }
TAG # #[test]
TAG # fn help_is_explicit_and_side_effect_free() {
TAG # let env = Env::new("help");
TAG # let f = env.put("good.json", BASE.as_bytes());
TAG # let f = f.to_str().unwrap();
TAG # for args in [
TAG # vec!["check", "--help"],
TAG # vec!["check", "-h"],
TAG # ] {
TAG # let o = env.exec(&args, b"");
TAG # if args.contains(&"-h") {
TAG # // -h is not promised by the contract; it must at least not run a check
TAG # assert!(!o.text().contains("\"verdict\":\"pass\""), "{args:?}");
TAG # continue;
TAG # }
TAG # assert_eq!(o.code, Some(0), "{args:?}: {}", trunc(&String::from_utf8_lossy(&o.err)));
TAG # let all = format!("{}{}", o.text(), String::from_utf8_lossy(&o.err));
TAG # assert!(all.contains("--input"), "{args:?}: help must describe --input: {}", trunc(&all));
TAG # assert!(!o.text().contains("check-error") && !o.text().contains("check-result"), "{args:?}");
TAG # assert!(!all.trim().is_empty());
TAG # }
TAG # // `--help` is explicit: it does not read stdin or the named file
TAG # let o = env.exec(&["check", "--help"], BASE.as_bytes());
TAG # assert_eq!(o.code, Some(0));
TAG # assert!(!o.text().contains("artifact-membership"));
TAG # let o = env.exec(&["check", "--help", "--input", f], b"");
TAG # assert!(!o.text().contains("check-result"), "help must not run the check");
TAG # }
TAG # // docs/checks.md says "`--help` is explicit" without saying whether it is per subcommand; a subcommand
TAG # // asked for help should explain itself, not fail as a bad argument.
TAG # #[test]
TAG # fn subcommand_help_is_explicit_and_side_effect_free() {
TAG # let env = Env::new("subhelp");
TAG # for sub in ["run", "validate", "explain"] {
TAG # let o = env.exec(&["check", sub, "--help"], BASE.as_bytes());
TAG # assert_eq!(o.code, Some(0), "check {sub} --help: {}", trunc(&o.text()));
TAG # let all = format!("{}{}", o.text(), String::from_utf8_lossy(&o.err));
TAG # assert!(all.contains("--input"), "check {sub} --help must describe --input: {}", trunc(&all));
TAG # assert!(!o.text().contains("check-error") && !o.text().contains("check-result"));
TAG # }
TAG # }
TAG # #[test]
TAG # fn a_successful_check_writes_one_json_object_and_nothing_before_it() {
TAG # let env = Env::new("stdout");
TAG # for sub in ["run", "validate", "explain"] {
TAG # for doc in [BASE.to_string(), mutate("\"revision\":1", "\"revision\":0")] {
TAG # let o = env.run(sub, &doc);
TAG # let t = o.text();
TAG # assert!(t.starts_with('{'), "{sub}: stdout must begin with the JSON object: {}", trunc(&t));
TAG # assert!(parse_json(t.trim()).is_ok(), "{sub}: stdout is exactly one JSON value: {}", trunc(&t));
TAG # assert!(!t.trim().contains("\n\n\n"), "{sub}");
TAG # }
TAG # }
TAG # }
TAG # // ---------------------------------------------------------------- no bank, no environment, no side effects
TAG # #[test]
TAG # fn no_bank_is_opened_or_created_and_a_corrupt_bank_is_untouched() {
TAG # let env = Env::new("nobank");
TAG # assert!(!env.bank().exists());
TAG # for sub in ["run", "validate", "explain"] {
TAG # let o = env.run(sub, BASE);
TAG # assert_eq!(o.code, Some(0), "{sub}");
TAG # }
TAG # assert!(!env.bank().exists(), "check must not create a bank");
TAG # assert!(!env.bank().parent().unwrap().exists(), "check must not create the bank folder");
TAG # // the exec wrapper compares the whole tree, so anything new anywhere would already have failed above
TAG # std::fs::create_dir_all(env.bank().parent().unwrap()).unwrap();
TAG # std::fs::write(env.bank(), b"\xff\xfenot a bank at all\n{{{").unwrap();
TAG # let a = env.run("run", BASE);
TAG # let b = env.run("validate", BASE);
TAG # assert_eq!(a.code, Some(0));
TAG # assert_eq!(b.code, Some(0));
TAG # assert_eq!(std::fs::read(env.bank()).unwrap(), b"\xff\xfenot a bank at all\n{{{");
TAG # // a store override that points nowhere usable changes nothing
TAG # let missing = env.root.join("elsewhere").join("deep").join("bank.hxdb");
TAG # let blocked = env.put("blocker", b"i am a file");
TAG # let blocked_store = blocked.join("bank.hxdb");
TAG # let clean = env.run("run", BASE).out;
TAG # for store in [missing.to_str().unwrap(), blocked_store.to_str().unwrap(), "", "/nonexistent-root-dir/bank.hxdb"] {
TAG # for sub in ["run", "validate", "explain"] {
TAG # let o = env.exec_env(&["check", sub, "--input", "-"], BASE.as_bytes(), &[("INSTINCT_STORE", store)]);
TAG # assert_eq!(o.code, Some(0), "{sub} with store {store:?}: {}", trunc(&o.text()));
TAG # if sub == "run" {
TAG # assert_eq!(o.out, clean, "store {store:?}");
TAG # }
TAG # }
TAG # }
TAG # assert!(!missing.exists() && !missing.parent().unwrap().exists());
TAG # // even failures leave the machine alone
TAG # err(&env.run("run", "{"), "bad json");
TAG # assert!(!missing.exists());
TAG # }
TAG # #[test]
TAG # fn the_environment_never_supplies_scope_or_changes_results() {
TAG # let env = Env::new("envscope");
TAG # let envs = [
TAG # ("INSTINCT_PROJECT", "release-lab"),
TAG # ("INSTINCT_PERSONA", "p"),
TAG # ("INSTINCT_HARNESS", "h"),
TAG # ("INSTINCT_HARNESS_VERSION", "1"),
TAG # ("INSTINCT_MACHINE", "m"),
TAG # ("INSTINCT_SESSION", "s"),
TAG # ("INSTINCT_EXPLORE", "1"),
TAG # ("INSTINCT_METER", "1"),
TAG # ("CLAUDE_PROJECT_DIR", "release-lab"),
TAG # ("PROJECT", "release-lab"),
TAG # ("HOSTNAME", "m"),
TAG # ];
TAG # let ins = "{\"one\":\"bool\",\"zero\":\"bool\"}";
TAG # let doc = d(ins, &op2("eq", "one", "zero")).facts("{\"one\":true,\"zero\":false}").dscope("{\"project\":\"release-lab\",\"machine\":\"m\",\"persona\":\"p\"}").json();
TAG # for sub in ["run", "explain"] {
TAG # let plain = env.run(sub, &doc);
TAG # let with = env.exec_env(&["check", sub, "--input", "-"], doc.as_bytes(), &envs);
TAG # let j = result(&with);
TAG # assert_eq!(sf(&j, "verdict"), "abstain", "{sub}: the environment must not satisfy a required scope");
TAG # assert_eq!(pairs(j.get("scope").unwrap()), vec![]);
TAG # assert_eq!(plain.out, with.out, "{sub}: environment changed the output");
TAG # }
TAG # // the working directory name is not a scope either
TAG # let sub_cwd = env.root.join("cwd");
TAG # assert!(sub_cwd.exists());
TAG # let j = result(&env.run("run", &doc));
TAG # assert_eq!(sf(&j, "verdict"), "abstain");
TAG # // the opposite direction: the explicit request scope is what counts, whatever the environment says
TAG # let doc = d(ins, &op2("eq", "one", "zero")).facts("{\"one\":true,\"zero\":false}").dscope("{\"project\":\"release-lab\"}").scope("{\"project\":\"release-lab\"}").json();
TAG # let o = env.exec_env(&["check", "run", "--input", "-"], doc.as_bytes(), &[("INSTINCT_PROJECT", "something-else")]);
TAG # assert_eq!(verdict(&o), "fail");
TAG # }
TAG # #[test]
TAG # fn nothing_in_the_input_is_executed_read_or_followed() {
TAG # let env = Env::new("inert");
TAG # let marker = env.root.join("home").join("pwned");
TAG # let marker_s = marker.to_str().unwrap().to_string();
TAG # let hostile = [
TAG # format!("$(touch {marker_s})"),
TAG # format!("`touch {marker_s}`"),
TAG # format!("; touch {marker_s}"),
TAG # "../../../../etc/passwd".to_string(),
TAG # "/etc/shadow".to_string(),
TAG # "file:///etc/passwd".to_string(),
TAG # "http://127.0.0.1:1/x".to_string(),
TAG # "-rf /".to_string(),
TAG # "%n%n%n%s%s".to_string(),
TAG # "{{7*7}}".to_string(),
TAG # ];
TAG # for h in hostile {
TAG # let esc = h.replace('\\', "\\\\").replace('"', "\\\"");
TAG # let ins = "{\"p\":\"string\",\"q\":\"string\",\"x\":\"set<string>\"}";
TAG # let claim = all_of(&[op2("eq", "p", "q"), op2("contains", "x", "p")]);
TAG # let doc = d(ins, &claim)
TAG # .facts(&format!("{{\"p\":\"{esc}\",\"q\":\"{esc}\",\"x\":[\"{esc}\"]}}"))
TAG # .dscope(&format!("{{\"project\":\"{esc}\"}}"))
TAG # .scope(&format!("{{\"project\":\"{esc}\"}}"))
TAG # .json();
TAG # for sub in ["run", "validate", "explain"] {
TAG # let o = env.run(sub, &doc);
TAG # assert_eq!(o.code, Some(0), "{sub} {h}");
TAG # }
TAG # assert_eq!(verdict(&env.run("run", &doc)), "pass", "{h}");
TAG # assert!(!marker.exists(), "input text was executed: {h}");
TAG # }
TAG # // host paths in facts are plain strings, not access grants and not read
TAG # let doc = d("{\"p\":\"string\"}", &op2("eq", "p", "p")).facts("{\"p\":\"/etc/passwd\"}").json();
TAG # assert_eq!(verdict(&env.run("run", &doc)), "pass");
TAG # }
TAG # #[test]
TAG # fn authorization_is_never_evaluated_and_evidence_is_always_caller_reported() {
TAG # let env = Env::new("authz");
TAG # let cases = [
TAG # BASE.to_string(),
TAG # mutate("\"complete-inventory\":true", "\"complete-inventory\":false"),
TAG # mutate("\"allowed\":[\"release.bin\"]", "\"allowed\":[\"scratch.env\",\"release.bin\"]"),
TAG # d(SET_IN, &op2("subset", "actual", "allowed")).json(),
TAG # ];
TAG # for doc in cases {
TAG # for sub in ["run", "explain"] {
TAG # let o = env.run(sub, &doc);
TAG # let j = result(&o);
TAG # assert_eq!(sf(&j, "authorization"), "not_evaluated");
TAG # assert_eq!(sf(&j, "evidence_origin"), "caller_reported");
TAG # }
TAG # let o = env.run("validate", &doc);
TAG # assert_eq!(sf(&obj(&o), "authorization"), "not_evaluated");
TAG # }
TAG # // a condition that says true is still only a caller report
TAG # let j = result(&env.run("run", BASE));
TAG # assert_eq!(sf(&j, "evidence_origin"), "caller_reported");
TAG # for bad in [
TAG # mutate("\"id\":\"artifact-membership\"", "\"id\":\"0bad\""),
TAG # "{".to_string(),
TAG # mutate("\"op\":\"subset\"", "\"op\":\"zzz\""),
TAG # ] {
TAG # let o = env.run("run", &bad);
TAG # err(&o, "error shape");
TAG # assert_eq!(sf(&obj(&o), "authorization"), "not_evaluated");
TAG # }
TAG # }
TAG # // docs/checks.md bounds witness/explanation output at 64 KiB and calls the result scope "explicit current scope".
TAG # // Ordinary scope values (up to 20,000 characters) must be echoed exactly. Past the output bound, a bounded structured
TAG # // error is acceptable (docs clarification); a success must echo the scope exactly and the JSON text must stay within
TAG # // 65536 bytes (stdout within 65537 with the CLI newline). Silent truncation or an empty scope is never acceptable.
TAG # #[test]
TAG # fn a_huge_request_scope_value_is_rejected_or_echoed_exactly_never_truncated_or_unbounded() {
TAG # let env = Env::new("hugescope");
TAG # let ins = "{\"a\":\"bool\"}";
TAG # let mk = |n: usize| {
TAG # let v = "p".repeat(n);
TAG # (d(ins, &op2("eq", "a", "a")).facts("{\"a\":true}").scope(&format!("{{\"project\":\"{v}\"}}")).json(), v)
TAG # };
TAG # // ordinary sizes: success with an exact echo is required, not an arbitrary rejection
TAG # for n in [1usize, 1_000, 20_000, 60_000] {
TAG # let (doc, v) = mk(n);
TAG # for sub in ["run", "explain"] {
TAG # let o = env.run(sub, &doc);
TAG # let j = result(&o);
TAG # assert_eq!(sf(&j, "verdict"), "pass", "{sub} scope {n}");
TAG # assert_eq!(pairs(j.get("scope").unwrap()), vec![("project".to_string(), v.clone())], "{sub}: scope {n} must echo exactly");
TAG # assert!(o.text().trim_end().len() <= 65_536 && o.out.len() <= 65_537, "{sub}: scope {n} produced {} bytes", o.out.len());
TAG # }
TAG # valid(&env, &doc, &format!("validate scope {n}"));
TAG # }
TAG # // around the 64 KiB boundary and far beyond it: error, or an exact in-bound echo
TAG # for n in [64_000usize, 65_000, 65_300, 65_500, 65_536, 65_537, 66_000, 70_000, 90_000, 300_000] {
TAG # let (doc, v) = mk(n);
TAG # for sub in ["run", "explain", "validate"] {
TAG # let o = env.run(sub, &doc);
TAG # match o.code {
TAG # Some(2) => err(&o, &format!("{sub} scope {n}")),
TAG # Some(0) => {
TAG # assert!(o.text().trim_end().len() <= 65_536 && o.out.len() <= 65_537, "{sub}: {n}-char scope produced {} bytes", o.out.len());
TAG # if sub != "validate" {
TAG # let j = result(&o);
TAG # assert_eq!(pairs(j.get("scope").unwrap()), vec![("project".to_string(), v.clone())], "{sub}: scope {n} must not be truncated");
TAG # }
TAG # }
TAG # other => panic!("{sub}: unexpected exit {other:?}"),
TAG # }
TAG # }
TAG # }
TAG # // a definition-side huge scope value is bounded the same way
TAG # for n in [20_000usize, 90_000] {
TAG # let v = "q".repeat(n);
TAG # let doc = d(ins, &op2("eq", "a", "a")).facts("{\"a\":true}").dscope(&format!("{{\"project\":\"{v}\"}}")).scope(&format!("{{\"project\":\"{v}\"}}")).json();
TAG # for sub in ["run", "explain"] {
TAG # let o = env.run(sub, &doc);
TAG # match o.code {
TAG # Some(2) => err(&o, &format!("{sub} definition scope {n}")),
TAG # Some(0) => assert!(o.text().trim_end().len() <= 65_536 && o.out.len() <= 65_537, "{sub}: definition scope {n} produced {} bytes", o.out.len()),
TAG # other => panic!("{sub}: unexpected exit {other:?}"),
TAG # }
TAG # }
TAG # }
TAG # }
TAG # fn pattern(n: usize) -> String {
TAG # // non-uniform, so truncation, padding or substitution is detectable
TAG # let mut s: String = (0..n).map(|i| (b'a' + (i * 7 % 26) as u8) as char).collect();
TAG # if n > 0 {
TAG # s.replace_range(n - 1..n, "Z");
TAG # }
TAG # s
TAG # }
TAG # #[test]
TAG # fn witnesses_that_fit_64_kib_are_echoed_exactly() {
TAG # let env = Env::new("witness-exact");
TAG # for n in [1usize, 100, 1_000, 4_096, 4_110, 4_111, 5_000, 8_192, 20_000, 60_000] {
TAG # let m = pattern(n);
TAG # for sub in ["run", "explain"] {
TAG # let o = env.run(sub, &set_doc("subset", &format!("[\"{m}\"]"), "[]"));
TAG # let j = result(&o);
TAG # assert_eq!(sf(&j, "verdict"), "fail", "{sub} {n}");
TAG # assert_eq!(j.get("witness"), Some(&J::Str(m.clone())), "{sub}: {n}-char witness must be exact");
TAG # let o = env.run(sub, &set_doc("disjoint", &format!("[\"{m}\",\"zz\"]"), &format!("[\"{m}\"]")));
TAG # let j = result(&o);
TAG # assert_eq!(sf(&j, "verdict"), "fail", "{sub} {n}");
TAG # assert_eq!(j.get("witness"), Some(&J::Str(m.clone())), "{sub}: {n}-char disjoint witness must be exact");
TAG # assert!(o.text().trim_end().len() <= 65_536 && o.out.len() <= 65_537);
TAG # }
TAG # }
TAG # // multi-byte scalars and escapes, long
TAG # for (raw, json) in [
TAG # ("\u{e9}".repeat(20_000) + "Z", format!("{}Z", "\\u00e9".repeat(20_000))),
TAG # ("\u{1F600}".repeat(10_000) + "Z", format!("{}Z", "\\ud83d\\ude00".repeat(10_000))),
TAG # ("a\"b\\c\nd\u{1}".repeat(3_000), "a\\\"b\\\\c\\nd\\u0001".repeat(3_000)),
TAG # ("\u{e9}\u{301}\u{4e2d}".repeat(5_000), "\\u00e9\\u0301\\u4e2d".repeat(5_000)),
TAG # ] {
TAG # let j = result(&env.run("run", &set_doc("subset", &format!("[\"{json}\"]"), "[]")));
TAG # assert_eq!(j.get("witness"), Some(&J::Str(raw)), "long escaped/multibyte witness");
TAG # }
TAG # // the lexicographically first of several long unexpected members is the one named, whole
TAG # let (a, b) = (pattern(5_000), format!("{}!", pattern(5_000)));
TAG # let j = result(&env.run("run", &set_doc("subset", &format!("[\"{b}\",\"{a}\"]"), "[]")));
TAG # assert_eq!(j.get("witness"), Some(&J::Str(a.min(b))));
TAG # // around the 64 KiB boundary: an exact in-bound witness or a bounded error, never a different witness
TAG # for n in [64_000usize, 64_500, 65_000, 65_200, 65_400, 65_536, 65_537, 66_000] {
TAG # let m = pattern(n);
TAG # for sub in ["run", "explain"] {
TAG # let o = env.run(sub, &set_doc("subset", &format!("[\"{m}\"]"), "[]"));
TAG # match o.code {
TAG # Some(2) => err(&o, &format!("{sub} {n}-char witness")),
TAG # Some(0) => {
TAG # let j = result(&o);
TAG # assert_eq!(j.get("witness"), Some(&J::Str(m.clone())), "{sub}: {n}-char witness must be exact or an error");
TAG # assert!(o.text().trim_end().len() <= 65_536 && o.out.len() <= 65_537, "{sub} {n}: {} bytes", o.out.len());
TAG # }
TAG # other => panic!("unexpected exit {other:?}"),
TAG # }
TAG # }
TAG # }
TAG # }