// generated by hxc 1.0.0-acgt-compiler from tests/check_contract.hlx -- do not edit by hand
#[cfg(windows)]
#[allow(dead_code)]
const SYS_CURL: &str = "C:\\Windows\\System32\\curl.exe";
#[cfg(not(windows))]
#[allow(dead_code)]
const SYS_CURL: &str = "curl";
#[allow(dead_code)]
fn _helix_allowed(var: &str, what: &str) -> bool {
let ok = std::env::var(var).map(|v| v == "1").unwrap_or(false);
if !ok {
eprintln!("helix: BLOCKED {} -- permission denied (set {}=1 to allow; `hxc run` allows by default, a `hxc build`/`export-rust` binary does not)", what, var);
}
ok
}
#[cfg(windows)]
#[allow(dead_code)]
fn _nw_exec(mut c: std::process::Command) -> std::process::Command {
if !_helix_allowed("HELIX_ALLOW_RUN", "process execution") {
std::process::exit(13);
}
use std::os::windows::process::CommandExt;
c.creation_flags(0x08000000);
c
}
#[cfg(not(windows))]
#[allow(dead_code)]
fn _nw_exec(c: std::process::Command) -> std::process::Command {
if !_helix_allowed("HELIX_ALLOW_RUN", "process execution") {
std::process::exit(13);
}
c
}
#[cfg(windows)]
#[allow(dead_code)]
fn _nw_net(mut c: std::process::Command) -> std::process::Command {
if !_helix_allowed("HELIX_ALLOW_NET", "network access") {
std::process::exit(13);
}
use std::os::windows::process::CommandExt;
c.creation_flags(0x08000000);
c
}
#[cfg(not(windows))]
#[allow(dead_code)]
fn _nw_net(c: std::process::Command) -> std::process::Command {
if !_helix_allowed("HELIX_ALLOW_NET", "network access") {
std::process::exit(13);
}
c
}
// hlx:3
// Independent acceptance tests for `instinct check`, written from docs/checks.md only.
// hlx:4
// Every case runs the real binary in a fresh HOME / XDG / store environment, and every command is wrapped by a
// hlx:5
// before/after snapshot of that whole environment (and the working directory): nothing may be created or changed.
// hlx:6
use std::io::Write;
// hlx:7
use std::path::{Path, PathBuf};
// hlx:8
use std::process::{Command, Stdio};
// hlx:9
use std::sync::atomic::{AtomicUsize, Ordering};
// hlx:10
use std::time::Duration;
// hlx:11
fn bin() -> &'static str {
// hlx:12
env!("CARGO_BIN_EXE_instinct")
// hlx:13
}
// hlx:14
// ---------------------------------------------------------------- minimal JSON reader for the outputs
// hlx:15
#[derive(Debug, Clone, PartialEq)]
// hlx:16
enum J {
// hlx:17
Null,
// hlx:18
Bool(bool),
// hlx:19
Num(String),
// hlx:20
Str(String),
// hlx:21
Arr(Vec<J>),
// hlx:22
Obj(Vec<(String, J)>),
// hlx:23
}
// hlx:24
impl J {
// hlx:25
fn get(&self, k: &str) -> Option<&J> {
// hlx:26
match self {
// hlx:27
J::Obj(v) => v.iter().find(|(a, _)| a == k).map(|(_, b)| b),
// hlx:28
_ => None,
// hlx:29
}
// hlx:30
}
// hlx:31
fn as_str(&self) -> Option<&str> {
// hlx:32
match self {
// hlx:33
J::Str(s) => Some(s),
// hlx:34
_ => None,
// hlx:35
}
// hlx:36
}
// hlx:37
}
// hlx:38
struct P<'a> {
// hlx:39
b: &'a [u8],
// hlx:40
i: usize,
// hlx:41
}
// hlx:42
impl<'a> P<'a> {
// hlx:43
fn ws(&mut self) {
// hlx:44
while self.i < self.b.len() && matches!(self.b[self.i], b' ' | b'\n' | b'\t' | b'\r') {
// hlx:45
self.i += 1;
// hlx:46
}
// hlx:47
}
// hlx:48
fn lit(&mut self, w: &str, v: J) -> Result<J, String> {
// hlx:49
if self.b[self.i..].starts_with(w.as_bytes()) {
// hlx:50
self.i += w.len();
// hlx:51
Ok(v)
// hlx:52
} else {
// hlx:53
Err(format!("bad literal at {}", self.i))
// hlx:54
}
// hlx:55
}
// hlx:56
fn hex4(&mut self) -> Result<u32, String> {
// hlx:57
let h = self.b.get(self.i..self.i + 4).ok_or("short \\u")?;
// hlx:58
let h = std::str::from_utf8(h).map_err(|e| e.to_string())?;
// hlx:59
self.i += 4;
// hlx:60
u32::from_str_radix(h, 16).map_err(|e| e.to_string())
// hlx:61
}
// hlx:62
fn string(&mut self) -> Result<String, String> {
// hlx:63
if self.b.get(self.i) != Some(&b'"') {
// hlx:64
return Err(format!("expected string at {}", self.i));
// hlx:65
}
// hlx:66
self.i += 1;
// hlx:67
let mut out: Vec<u8> = Vec::new();
// hlx:68
loop {
// hlx:69
let c = *self.b.get(self.i).ok_or("unterminated string")?;
// hlx:70
self.i += 1;
// hlx:71
match c {
// hlx:72
b'"' => return String::from_utf8(out).map_err(|e| e.to_string()),
// hlx:73
b'\\' => {
// hlx:74
let e = *self.b.get(self.i).ok_or("bad escape")?;
// hlx:75
self.i += 1;
// hlx:76
let ch = match e {
// hlx:77
b'"' => '"',
// hlx:78
b'\\' => '\\',
// hlx:79
b'/' => '/',
// hlx:80
b'b' => '\u{8}',
// hlx:81
b'f' => '\u{c}',
// hlx:82
b'n' => '\n',
// hlx:83
b'r' => '\r',
// hlx:84
b't' => '\t',
// hlx:85
b'u' => {
// hlx:86
let hi = self.hex4()?;
// hlx:87
if (0xD800..0xDC00).contains(&hi) {
// hlx:88
if self.b.get(self.i) != Some(&b'\\')
|| self.b.get(self.i + 1) != Some(&b'u')
{
// hlx:89
return Err("lone surrogate".into());
// hlx:90
}
// hlx:91
self.i += 2;
// hlx:92
let lo = self.hex4()?;
// hlx:93
char::from_u32(
0x10000 + ((hi - 0xD800) << 10) + (lo.wrapping_sub(0xDC00)),
)
// hlx:94
.ok_or("bad pair")?
// hlx:95
} else {
// hlx:96
char::from_u32(hi).ok_or("lone surrogate")?
// hlx:97
}
// hlx:98
}
// hlx:99
_ => return Err("bad escape".into()),
// hlx:100
};
// hlx:101
let mut buf = [0u8; 4];
// hlx:102
out.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes());
// hlx:103
}
// hlx:104
_ => out.push(c),
// hlx:105
}
// hlx:106
}
// hlx:107
}
// hlx:108
fn val(&mut self) -> Result<J, String> {
// hlx:109
self.ws();
// hlx:110
match self.b.get(self.i).copied() {
// hlx:111
None => Err("eof".into()),
// hlx:112
Some(b'{') => {
// hlx:113
self.i += 1;
// hlx:114
let mut v = Vec::new();
// hlx:115
self.ws();
// hlx:116
if self.b.get(self.i) == Some(&b'}') {
// hlx:117
self.i += 1;
// hlx:118
return Ok(J::Obj(v));
// hlx:119
}
// hlx:120
loop {
// hlx:121
self.ws();
// hlx:122
let k = self.string()?;
// hlx:123
self.ws();
// hlx:124
if self.b.get(self.i) != Some(&b':') {
// hlx:125
return Err("expected colon".into());
// hlx:126
}
// hlx:127
self.i += 1;
// hlx:128
let x = self.val()?;
// hlx:129
v.push((k, x));
// hlx:130
self.ws();
// hlx:131
match self.b.get(self.i) {
// hlx:132
Some(b',') => self.i += 1,
// hlx:133
Some(b'}') => {
// hlx:134
self.i += 1;
// hlx:135
return Ok(J::Obj(v));
// hlx:136
}
// hlx:137
_ => return Err("bad object".into()),
// hlx:138
}
// hlx:139
}
// hlx:140
}
// hlx:141
Some(b'[') => {
// hlx:142
self.i += 1;
// hlx:143
let mut v = Vec::new();
// hlx:144
self.ws();
// hlx:145
if self.b.get(self.i) == Some(&b']') {
// hlx:146
self.i += 1;
// hlx:147
return Ok(J::Arr(v));
// hlx:148
}
// hlx:149
loop {
// hlx:150
v.push(self.val()?);
// hlx:151
self.ws();
// hlx:152
match self.b.get(self.i) {
// hlx:153
Some(b',') => self.i += 1,
// hlx:154
Some(b']') => {
// hlx:155
self.i += 1;
// hlx:156
return Ok(J::Arr(v));
// hlx:157
}
// hlx:158
_ => return Err("bad array".into()),
// hlx:159
}
// hlx:160
}
// hlx:161
}
// hlx:162
Some(b'"') => Ok(J::Str(self.string()?)),
// hlx:163
Some(b't') => self.lit("true", J::Bool(true)),
// hlx:164
Some(b'f') => self.lit("false", J::Bool(false)),
// hlx:165
Some(b'n') => self.lit("null", J::Null),
// hlx:166
Some(_) => {
// hlx:167
let st = self.i;
// hlx:168
while self.i < self.b.len()
&& matches!(
self.b[self.i],
b'-' | b'+' | b'.' | b'e' | b'E' | b'0'..=b'9'
)
{
// hlx:169
self.i += 1;
// hlx:170
}
// hlx:171
if st == self.i {
// hlx:172
return Err(format!("unexpected byte at {st}"));
// hlx:173
}
// hlx:174
Ok(J::Num(
String::from_utf8_lossy(&self.b[st..self.i]).into_owned(),
))
// hlx:175
} // hlx:176
}
// hlx:177
}
// hlx:178
}
// hlx:179
fn parse_json(s: &str) -> Result<J, String> {
// hlx:180
let mut p = P {
b: s.as_bytes(),
i: 0,
};
// hlx:181
let v = p.val()?;
// hlx:182
p.ws();
// hlx:183
if p.i != p.b.len() {
// hlx:184
return Err("trailing data".into());
// hlx:185
}
// hlx:186
Ok(v)
// hlx:187
}
// hlx:188
fn to_s(j: &J) -> String {
// hlx:189
match j {
// hlx:190
J::Null => "null".into(),
// hlx:191
J::Bool(b) => b.to_string(),
// hlx:192
J::Num(n) => n.clone(),
// hlx:193
J::Str(s) => format!("{s:?}"),
// hlx:194
J::Arr(v) => format!("[{}]", v.iter().map(to_s).collect::<Vec<_>>().join(",")),
// hlx:195
J::Obj(v) => format!(
"{{{}}}",
v.iter()
.map(|(k, x)| format!("{k:?}:{}", to_s(x)))
.collect::<Vec<_>>()
.join(",")
),
// hlx:196
}
// hlx:197
}
// hlx:198
// ---------------------------------------------------------------- isolated environment and process runner
// hlx:199
struct Out {
// hlx:200
code: Option<i32>,
// hlx:201
out: Vec<u8>,
// hlx:202
err: Vec<u8>,
// hlx:203
}
// hlx:204
impl Out {
// hlx:205
fn text(&self) -> String {
// hlx:206
String::from_utf8_lossy(&self.out).into_owned()
// hlx:207
}
// hlx:208
}
// hlx:209
fn fnv(b: &[u8]) -> u64 {
// hlx:210
let mut h = 0xcbf29ce484222325u64;
// hlx:211
for x in b {
// hlx:212
h ^= *x as u64;
// hlx:213
h = h.wrapping_mul(0x100000001b3);
// hlx:214
}
// hlx:215
h
// hlx:216
}
// hlx:217
fn walk(base: &Path, dir: &Path, acc: &mut Vec<String>) {
// hlx:218
let mut ents: Vec<_> = match std::fs::read_dir(dir) {
// hlx:219
Ok(r) => r.filter_map(|e| e.ok()).collect(),
// hlx:220
Err(_) => return,
// hlx:221
};
// hlx:222
ents.sort_by_key(|e| e.file_name());
// hlx:223
for e in ents {
// hlx:224
let p = e.path();
// hlx:225
let rel = p.strip_prefix(base).unwrap().display().to_string();
// hlx:226
let md = match std::fs::symlink_metadata(&p) {
// hlx:227
Ok(m) => m,
// hlx:228
Err(_) => continue,
// hlx:229
};
// hlx:230
if md.is_dir() {
// hlx:231
acc.push(format!("d {rel}"));
// hlx:232
walk(base, &p, acc);
// hlx:233
} else {
// hlx:234
let b = std::fs::read(&p).unwrap_or_default();
// hlx:235
acc.push(format!("f {rel} {} {:x}", b.len(), fnv(&b)));
// hlx:236
}
// hlx:237
}
// hlx:238
}
// hlx:239
struct Env {
// hlx:240
root: PathBuf,
// hlx:241
}
// hlx:242
impl Env {
// hlx:243
fn new(name: &str) -> Env {
// hlx:244
static N: AtomicUsize = AtomicUsize::new(0);
// hlx:245
let root = std::env::temp_dir().join(format!(
// hlx:246
"instinct-check-contract-{}-{}-{name}",
// hlx:247
std::process::id(),
// hlx:248
N.fetch_add(1, Ordering::Relaxed) // hlx:249
));
// hlx:250
let _ = std::fs::remove_dir_all(&root);
// hlx:251
for d in [
"home", "data", "local", "cfg", "state", "cache", "cwd", "in",
] {
// hlx:252
std::fs::create_dir_all(root.join(d)).unwrap();
// hlx:253
}
// hlx:254
Env { root }
// hlx:255
}
// hlx:256
fn bank(&self) -> PathBuf {
// hlx:257
let base = if cfg!(windows) { "local" } else { "data" };
// hlx:258
self.root.join(base).join("instinct").join("bank.hxdb")
// hlx:259
}
// hlx:260
fn put(&self, name: &str, bytes: &[u8]) -> PathBuf {
// hlx:261
let p = self.root.join("in").join(name);
// hlx:262
std::fs::write(&p, bytes).unwrap();
// hlx:263
p
// hlx:264
}
// hlx:265
fn snapshot(&self) -> Vec<String> {
// hlx:266
let mut acc = Vec::new();
// hlx:267
walk(&self.root, &self.root, &mut acc);
// hlx:268
acc
// hlx:269
}
// hlx:270
fn exec_env(&self, args: &[&str], stdin: &[u8], envs: &[(&str, &str)]) -> Out {
// hlx:271
let before = self.snapshot();
// hlx:272
let mut c = Command::new(bin());
// hlx:273
c.args(args)
// hlx:274
.current_dir(self.root.join("cwd"))
// hlx:275
.env("HOME", self.root.join("home"))
// hlx:276
.env("XDG_DATA_HOME", self.root.join("data"))
// hlx:277
.env("XDG_CONFIG_HOME", self.root.join("cfg"))
// hlx:278
.env("XDG_STATE_HOME", self.root.join("state"))
// hlx:279
.env("XDG_CACHE_HOME", self.root.join("cache"))
// hlx:280
.env("LOCALAPPDATA", self.root.join("local"))
// hlx:281
.env("APPDATA", self.root.join("local"));
// hlx:282
for (k, _) in std::env::vars() {
// hlx:283
if k.starts_with("INSTINCT_") {
// hlx:284
c.env_remove(k);
// hlx:285
}
// hlx:286
}
// hlx:287
for (k, v) in envs {
// hlx:288
c.env(k, v);
// hlx:289
}
// hlx:290
c.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
// hlx:291
let mut child = c.spawn().unwrap();
// hlx:292
let mut si = child.stdin.take().unwrap();
// hlx:293
let data = stdin.to_vec();
// hlx:294
let w = std::thread::spawn(move || {
// hlx:295
let _ = si.write_all(&data);
// hlx:296
});
// hlx:297
let (tx, rx) = std::sync::mpsc::channel();
// hlx:298
std::thread::spawn(move || {
// hlx:299
let _ = tx.send(child.wait_with_output());
// hlx:300
});
// hlx:301
let o = rx
.recv_timeout(Duration::from_secs(180))
.expect("instinct check hung")
.unwrap();
// hlx:302
let _ = w.join();
// hlx:303
let after = self.snapshot();
// hlx:304
assert_eq!(before, after, "command changed the filesystem: {args:?}");
// hlx:305
if std::env::var_os("CHECK_CONTRACT_COUNT").is_some() {
// hlx:306
eprintln!("check_contract_exec");
// hlx:307
}
// hlx:308
Out {
code: o.status.code(),
out: o.stdout,
err: o.stderr,
}
// hlx:309
}
// hlx:310
fn exec(&self, args: &[&str], stdin: &[u8]) -> Out {
// hlx:311
self.exec_env(args, stdin, &[])
// hlx:312
}
// hlx:313
fn run(&self, sub: &str, doc: &str) -> Out {
// hlx:314
self.exec(&["check", sub, "--input", "-"], doc.as_bytes())
// hlx:315
}
// hlx:316
fn run_bytes(&self, sub: &str, doc: &[u8]) -> Out {
// hlx:317
self.exec(&["check", sub, "--input", "-"], doc)
// hlx:318
}
// hlx:319
}
// hlx:320
impl Drop for Env {
// hlx:321
fn drop(&mut self) {
// hlx:322
let _ = std::fs::remove_dir_all(&self.root);
// hlx:323
}
// hlx:324
}
// hlx:325
// ---------------------------------------------------------------- output assertions
// hlx:326
fn trunc(s: &str) -> String {
// hlx:327
s.chars().take(400).collect()
// hlx:328
}
// hlx:329
fn obj(o: &Out) -> J {
// hlx:330
let t = o.text();
// hlx:331
let j = parse_json(t.trim())
.unwrap_or_else(|e| panic!("stdout is not one JSON value ({e}): {}", trunc(&t)));
// hlx:332
assert!(
matches!(j, J::Obj(_)),
"stdout must be one JSON object: {}",
trunc(&t)
);
// hlx:333
j
// hlx:334
}
// hlx:335
fn sf<'a>(j: &'a J, k: &str) -> &'a str {
// hlx:336
j.get(k)
.and_then(J::as_str)
.unwrap_or_else(|| panic!("missing string field {k} in {}", trunc(&to_s(j))))
// hlx:337
}
// hlx:338
fn names(j: &J) -> Vec<String> {
// hlx:339
match j {
// hlx:340
J::Arr(v) => v
.iter()
.map(|x| x.as_str().expect("array of strings").to_string())
.collect(),
// hlx:341
other => panic!("expected an array, got {}", to_s(other)),
// hlx:342
}
// hlx:343
}
// hlx:344
fn pairs(j: &J) -> Vec<(String, String)> {
// hlx:345
match j {
// hlx:346
J::Obj(v) => {
// hlx:347
let mut r: Vec<(String, String)> =
// hlx:348
v.iter().map(|(k, x)| (k.clone(), x.as_str().expect("string scope value").to_string())).collect();
// hlx:349
r.sort();
// hlx:350
r
// hlx:351
}
// hlx:352
other => panic!("expected an object, got {}", to_s(other)),
// hlx:353
}
// hlx:354
}
// hlx:355
fn result(o: &Out) -> J {
// hlx:356
assert_eq!(o.code, Some(0), "expected exit 0: {}", trunc(&o.text()));
// hlx:357
let j = obj(o);
// hlx:358
assert_eq!(
sf(&j, "schema"),
"instinct.check-result/v1",
"{}",
trunc(&o.text())
);
// hlx:359
assert!(
["pass", "fail", "abstain"].contains(&sf(&j, "verdict")),
"{}",
trunc(&o.text())
);
// hlx:360
assert_eq!(sf(&j, "authorization"), "not_evaluated");
// hlx:361
assert_eq!(sf(&j, "evidence_origin"), "caller_reported");
// hlx:362
assert!(!sf(&j, "reason").is_empty());
// hlx:363
assert!(!sf(&j, "check_id").is_empty());
// hlx:364
match j.get("revision") {
// hlx:365
Some(J::Num(n)) => assert!(n.parse::<u32>().is_ok(), "revision must be an integer: {n}"),
// hlx:366
other => panic!("revision must be a number: {other:?}"),
// hlx:367
}
// hlx:368
match j.get("steps") {
// hlx:369
Some(J::Num(n)) => assert!(
n.parse::<u64>().is_ok(),
"steps must be a non-negative integer: {n}"
),
// hlx:370
other => panic!("steps must be a number: {other:?}"),
// hlx:371
}
// hlx:372
match j.get("witness") {
// hlx:373
Some(J::Null) | Some(J::Str(_)) => {}
// hlx:374
other => panic!("witness must be string or null: {other:?}"),
// hlx:375
}
// hlx:376
let m = names(j.get("missing").expect("missing field"));
// hlx:377
let mut sorted = m.clone();
// hlx:378
sorted.sort();
// hlx:379
sorted.dedup();
// hlx:380
assert_eq!(m, sorted, "missing must be sorted and unique");
// hlx:381
assert!(
matches!(j.get("scope"), Some(J::Obj(_))),
"scope must be an object"
);
// hlx:382
let verdict = sf(&j, "verdict");
// hlx:383
if verdict == "pass" || verdict == "abstain" {
// hlx:384
assert_eq!(
j.get("witness"),
Some(&J::Null),
"only a failed check has a witness: {}",
trunc(&o.text())
);
// hlx:385
}
// hlx:386
j
// hlx:387
}
// hlx:388
fn verdict(o: &Out) -> String {
// hlx:389
sf(&result(o), "verdict").to_string()
// hlx:390
}
// hlx:391
fn err(o: &Out, ctx: &str) {
// hlx:392
assert_eq!(
o.code,
Some(2),
"{ctx}: expected exit 2, stdout={}",
trunc(&o.text())
);
// hlx:393
let j = obj(o);
// hlx:394
assert_eq!(
sf(&j, "schema"),
"instinct.check-error/v1",
"{ctx}: {}",
trunc(&o.text())
);
// hlx:395
assert_eq!(sf(&j, "verdict"), "error", "{ctx}");
// hlx:396
assert!(!sf(&j, "reason").is_empty(), "{ctx}");
// hlx:397
assert_eq!(sf(&j, "authorization"), "not_evaluated", "{ctx}");
// hlx:398
assert!(
o.out.len() <= 65_537,
"{ctx}: error output must be bounded, got {} bytes",
o.out.len()
);
// hlx:399
}
// hlx:400
// run validate, run and explain: every one must reject the document
// hlx:401
fn all_err(env: &Env, raw: &[u8], ctx: &str) {
// hlx:402
for sub in ["validate", "run", "explain"] {
// hlx:403
err(&env.run_bytes(sub, raw), &format!("{sub} {ctx}"));
// hlx:404
}
// hlx:405
}
// hlx:406
fn all_err_s(env: &Env, raw: &str, ctx: &str) {
// hlx:407
all_err(env, raw.as_bytes(), &format!("{ctx}: {}", trunc(raw)));
// hlx:408
}
// hlx:409
fn valid(env: &Env, raw: &str, ctx: &str) {
// hlx:410
let o = env.run("validate", raw);
// hlx:411
assert_eq!(o.code, Some(0), "{ctx}: {}", trunc(&o.text()));
// hlx:412
let j = obj(&o);
// hlx:413
assert_eq!(sf(&j, "schema"), "instinct.check-validation/v1", "{ctx}");
// hlx:414
assert_eq!(j.get("valid"), Some(&J::Bool(true)), "{ctx}");
// hlx:415
assert_eq!(sf(&j, "authorization"), "not_evaluated");
// hlx:416
}
// hlx:417
// ---------------------------------------------------------------- document builders
// hlx:418
#[derive(Clone)]
// hlx:419
struct D {
// hlx:420
schema: String,
// hlx:421
id: String,
// hlx:422
rev: String,
// hlx:423
inputs: String,
// hlx:424
claim: String,
// hlx:425
req: Option<String>,
// hlx:426
dscope: Option<String>,
// hlx:427
facts: Option<String>,
// hlx:428
conds: Option<String>,
// hlx:429
scope: Option<String>,
// hlx:430
}
// hlx:431
fn d(inputs: &str, claim: &str) -> D {
// hlx:432
D {
// hlx:433
schema: "\"instinct.check/v1\"".into(),
// hlx:434
id: "\"t1\"".into(),
// hlx:435
rev: "1".into(),
// hlx:436
inputs: inputs.into(),
// hlx:437
claim: claim.into(),
// hlx:438
req: None,
// hlx:439
dscope: None,
// hlx:440
facts: None,
// hlx:441
conds: None,
// hlx:442
scope: None,
// hlx:443
}
// hlx:444
}
// hlx:445
impl D {
// hlx:446
fn facts(mut self, s: &str) -> D {
// hlx:447
self.facts = Some(s.into());
// hlx:448
self
// hlx:449
}
// hlx:450
fn conds(mut self, s: &str) -> D {
// hlx:451
self.conds = Some(s.into());
// hlx:452
self
// hlx:453
}
// hlx:454
fn scope(mut self, s: &str) -> D {
// hlx:455
self.scope = Some(s.into());
// hlx:456
self
// hlx:457
}
// hlx:458
fn dscope(mut self, s: &str) -> D {
// hlx:459
self.dscope = Some(s.into());
// hlx:460
self
// hlx:461
}
// hlx:462
fn req(mut self, s: &str) -> D {
// hlx:463
self.req = Some(s.into());
// hlx:464
self
// hlx:465
}
// hlx:466
fn id(mut self, s: &str) -> D {
// hlx:467
self.id = s.into();
// hlx:468
self
// hlx:469
}
// hlx:470
fn rev(mut self, s: &str) -> D {
// hlx:471
self.rev = s.into();
// hlx:472
self
// hlx:473
}
// hlx:474
fn schema(mut self, s: &str) -> D {
// hlx:475
self.schema = s.into();
// hlx:476
self
// hlx:477
}
// hlx:478
fn json(&self) -> String {
// hlx:479
let mut c = format!(
// hlx:480
"{{\"schema\":{},\"id\":{},\"revision\":{},\"inputs\":{},\"claim\":{}",
// hlx:481
self.schema,
self.id,
self.rev,
self.inputs,
self.claim // hlx:482
);
// hlx:483
if let Some(r) = &self.req {
// hlx:484
c.push_str(&format!(",\"required_conditions\":{r}"));
// hlx:485
}
// hlx:486
if let Some(s) = &self.dscope {
// hlx:487
c.push_str(&format!(",\"scope\":{s}"));
// hlx:488
}
// hlx:489
c.push('}');
// hlx:490
let mut t = format!("{{\"check\":{c}");
// hlx:491
if let Some(f) = &self.facts {
// hlx:492
t.push_str(&format!(",\"facts\":{f}"));
// hlx:493
}
// hlx:494
if let Some(f) = &self.conds {
// hlx:495
t.push_str(&format!(",\"conditions\":{f}"));
// hlx:496
}
// hlx:497
if let Some(f) = &self.scope {
// hlx:498
t.push_str(&format!(",\"scope\":{f}"));
// hlx:499
}
// hlx:500
t.push('}');
// hlx:501
t
// hlx:502
}
// hlx:503
}
// hlx:504
fn fact(n: &str) -> String {
// hlx:505
format!("{{\"fact\":\"{n}\"}}")
// hlx:506
}
// hlx:507
fn op2(op: &str, l: &str, r: &str) -> String {
// hlx:508
format!(
"{{\"op\":\"{op}\",\"left\":{},\"right\":{}}}",
fact(l),
fact(r)
)
// hlx:509
}
// hlx:510
fn all_of(a: &[String]) -> String {
// hlx:511
format!("{{\"op\":\"all\",\"args\":[{}]}}", a.join(","))
// hlx:512
}
// hlx:513
fn any_of(a: &[String]) -> String {
// hlx:514
format!("{{\"op\":\"any\",\"args\":[{}]}}", a.join(","))
// hlx:515
}
// hlx:516
fn not_of(a: &str) -> String {
// hlx:517
format!("{{\"op\":\"not\",\"arg\":{a}}}")
// hlx:518
}
// hlx:519
// the example from the contract, on one line
// hlx:520
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\"}}";
// hlx:521
const SET_IN: &str = "{\"actual\":\"set<string>\",\"allowed\":\"set<string>\"}";
// hlx:522
fn mutate(from: &str, to: &str) -> String {
// hlx:523
assert_eq!(
BASE.matches(from).count(),
1,
"mutation anchor must be unique: {from}"
);
// hlx:524
BASE.replacen(from, to, 1)
// hlx:525
}
// hlx:526
fn set_doc(op: &str, l: &str, r: &str) -> String {
// hlx:527
d(SET_IN, &op2(op, "actual", "allowed"))
.facts(&format!("{{\"actual\":{l},\"allowed\":{r}}}"))
.json()
// hlx:528
}
// hlx:529
fn js(items: &[&str]) -> String {
// hlx:530
format!(
"[{}]",
items
.iter()
.map(|s| format!("\"{s}\""))
.collect::<Vec<_>>()
.join(",")
)
// hlx:531
}
// hlx:532
fn many(n: usize, prefix: &str) -> String {
// hlx:533
format!(
"[{}]",
(0..n)
.map(|i| format!("\"{prefix}{i:05}\""))
.collect::<Vec<_>>()
.join(",")
)
// hlx:534
}
// hlx:535
// ---------------------------------------------------------------- wire and result basics
// hlx:536
#[test]
// hlx:537
fn contract_example_fails_with_the_first_unexpected_member() {
// hlx:538
let env = Env::new("example");
// hlx:539
let o = env.run("run", BASE);
// hlx:540
let j = result(&o);
// hlx:541
assert!(
o.text().trim_start().starts_with('{'),
"no logging before the JSON result"
);
// hlx:542
assert_eq!(sf(&j, "verdict"), "fail");
// hlx:543
assert_eq!(sf(&j, "check_id"), "artifact-membership");
// hlx:544
assert_eq!(j.get("revision"), Some(&J::Num("1".into())));
// hlx:545
assert_eq!(j.get("witness"), Some(&J::Str("scratch.env".into())));
// hlx:546
assert_eq!(names(j.get("missing").unwrap()), Vec::<String>::new());
// hlx:547
assert_eq!(
pairs(j.get("scope").unwrap()),
vec![("project".to_string(), "release-lab".to_string())]
);
// hlx:548
}
// hlx:549
#[test]
// hlx:550
fn contract_example_with_a_complete_allow_list_passes_without_a_witness() {
// hlx:551
let env = Env::new("example-pass");
// hlx:552
let doc = mutate(
"\"allowed\":[\"release.bin\"]",
"\"allowed\":[\"scratch.env\",\"release.bin\"]",
);
// hlx:553
let j = result(&env.run("run", &doc));
// hlx:554
assert_eq!(sf(&j, "verdict"), "pass");
// hlx:555
assert_eq!(j.get("witness"), Some(&J::Null));
// hlx:556
assert_eq!(names(j.get("missing").unwrap()), Vec::<String>::new());
// hlx:557
}
// hlx:558
#[test]
// hlx:559
fn validate_checks_the_definition_and_never_claims_a_predicate_pass() {
// hlx:560
let env = Env::new("validate");
// hlx:561
let o = env.run("validate", BASE);
// hlx:562
assert_eq!(o.code, Some(0));
// hlx:563
let j = obj(&o);
// hlx:564
assert_eq!(sf(&j, "schema"), "instinct.check-validation/v1");
// hlx:565
assert_eq!(sf(&j, "check_id"), "artifact-membership");
// hlx:566
assert_eq!(j.get("revision"), Some(&J::Num("1".into())));
// hlx:567
assert_eq!(j.get("valid"), Some(&J::Bool(true)));
// hlx:568
assert_eq!(sf(&j, "authorization"), "not_evaluated");
// hlx:569
assert!(
j.get("verdict").is_none(),
"validation is not a verdict: {}",
o.text()
);
// hlx:570
assert!(j.get("witness").is_none());
// hlx:571
assert!(
!o.text().contains("\"pass\""),
"validation must not read as a PASS"
);
// hlx:572
// The predicate fails on these facts, yet the definition and the supplied evidence are valid.
// hlx:573
// Missing facts, missing conditions and a missing scope are not validation errors either.
// hlx:574
let bare = d(SET_IN, &op2("subset", "actual", "allowed"))
.req("[\"c1\"]")
.dscope("{\"project\":\"p\"}");
// hlx:575
for doc in [
// hlx:576
bare.clone().json(),
// hlx:577
bare.clone().facts("{}").conds("{}").scope("{}").json(),
// hlx:578
bare.clone().facts("{\"actual\":[\"x\"]}").json(),
// hlx:579
bare.clone()
.facts("{\"actual\":[\"x\"],\"allowed\":[]}")
.conds("{\"c1\":false}")
.scope("{\"project\":\"other\"}")
.json(),
// hlx:580
] {
// hlx:581
valid(&env, &doc, &doc);
// hlx:582
}
// hlx:583
}
// hlx:584
#[test]
// hlx:585
fn explain_repeats_the_result_and_adds_declared_types_conditions_and_scope() {
// hlx:586
let env = Env::new("explain");
// hlx:587
let run = result(&env.run("run", BASE));
// hlx:588
let o = env.run("explain", BASE);
// hlx:589
let ex = result(&o);
// hlx:590
for k in [
"check_id", "revision", "verdict", "reason", "witness", "missing", "scope", "steps",
] {
// hlx:591
assert_eq!(run.get(k), ex.get(k), "explain must carry the same {k}");
// hlx:592
}
// hlx:593
let e = ex
.get("explanation")
.unwrap_or_else(|| panic!("explain needs an explanation: {}", trunc(&o.text())));
// hlx:594
assert_ne!(e, &J::Null);
// hlx:595
let t = to_s(e);
// hlx:596
for needle in [
"set<string>",
"actual",
"allowed",
"complete-inventory",
"explicit-policy",
"release-lab",
"subset",
] {
// hlx:597
assert!(
t.contains(needle),
"explanation should mention {needle}: {t}"
);
// hlx:598
}
// hlx:599
assert!(
!t.contains("release.bin"),
"explanation must not echo fact values: {t}"
);
// hlx:600
assert!(run.get("explanation").is_none(), "run has no explanation");
// hlx:601
}
// hlx:602
#[test]
// hlx:603
fn explain_and_run_do_not_expose_unrelated_fact_values() {
// hlx:604
let env = Env::new("expose");
// hlx:605
let inputs = "{\"actual\":\"set<string>\",\"allowed\":\"set<string>\",\"note\":\"string\",\"other\":\"set<string>\"}";
// hlx:606
let doc = d(inputs, &op2("subset", "actual", "allowed"))
// hlx:607
.facts("{\"actual\":[\"a\"],\"allowed\":[\"a\",\"SECRET_MEMBER_77\"],\"note\":\"SECRET_NOTE_88\",\"other\":[\"SECRET_OTHER_99\"]}")
// hlx:608
.json();
// hlx:609
for sub in ["run", "explain"] {
// hlx:610
let o = env.run(sub, &doc);
// hlx:611
let t = o.text();
// hlx:612
assert_eq!(verdict(&o), "pass");
// hlx:613
for s in ["SECRET_MEMBER_77", "SECRET_NOTE_88", "SECRET_OTHER_99"] {
// hlx:614
assert!(!t.contains(s), "{sub} leaked {s}: {t}");
// hlx:615
}
// hlx:616
}
// hlx:617
let failing = d(inputs, &op2("subset", "actual", "allowed"))
// hlx:618
.facts("{\"actual\":[\"zz\"],\"allowed\":[],\"note\":\"SECRET_NOTE_88\",\"other\":[\"SECRET_OTHER_99\"]}")
// hlx:619
.json();
// hlx:620
for sub in ["run", "explain"] {
// hlx:621
let t = env.run(sub, &failing).text();
// hlx:622
assert!(
!t.contains("SECRET_NOTE_88") && !t.contains("SECRET_OTHER_99"),
"{sub} leaked: {t}"
);
// hlx:623
}
// hlx:624
}
// hlx:625
#[test]
// hlx:626
fn omitted_facts_conditions_and_scope_default_to_empty_and_missing_evidence_abstains() {
// hlx:627
let env = Env::new("defaults");
// hlx:628
let doc = d(SET_IN, &op2("subset", "actual", "allowed")).json();
// hlx:629
let j = result(&env.run("run", &doc));
// hlx:630
assert_eq!(sf(&j, "verdict"), "abstain");
// hlx:631
assert_eq!(names(j.get("missing").unwrap()), vec!["actual", "allowed"]);
// hlx:632
assert_eq!(pairs(j.get("scope").unwrap()), vec![]);
// hlx:633
for explicit in ["{}"] {
// hlx:634
let same = d(SET_IN, &op2("subset", "actual", "allowed"))
.facts(explicit)
.conds(explicit)
.scope(explicit)
.json();
// hlx:635
let k = result(&env.run("run", &same));
// hlx:636
assert_eq!(k.get("verdict"), j.get("verdict"));
// hlx:637
assert_eq!(k.get("missing"), j.get("missing"));
// hlx:638
}
// hlx:639
}
// hlx:640
#[test]
// hlx:641
fn results_are_deterministic_across_runs_and_machines() {
// hlx:642
let a = Env::new("det-a");
// hlx:643
let b = Env::new("det-b");
// hlx:644
for doc in [
BASE.to_string(),
set_doc("disjoint", "[\"b\",\"a\"]", "[\"a\",\"b\"]"),
] {
// hlx:645
for sub in ["run", "validate", "explain"] {
// hlx:646
let x = a.run(sub, &doc);
// hlx:647
assert_eq!(x.out, a.run(sub, &doc).out);
// hlx:648
assert_eq!(x.out, b.run(sub, &doc).out);
// hlx:649
}
// hlx:650
}
// hlx:651
}
// hlx:652
#[test]
// hlx:653
fn file_and_stdin_input_are_identical_for_results_and_errors() {
// hlx:654
let env = Env::new("parity");
// hlx:655
let docs = [
// hlx:656
BASE.to_string(),
// hlx:657
mutate("\"revision\":1", "\"revision\":2"),
// hlx:658
mutate(
"\"complete-inventory\":true",
"\"complete-inventory\":false",
),
// hlx:659
"{\"check\":".to_string(),
// hlx:660
mutate("\"op\":\"subset\"", "\"op\":\"nope\""),
// hlx:661
String::new(),
// hlx:662
];
// hlx:663
for (i, doc) in docs.iter().enumerate() {
// hlx:664
let path = env.put(&format!("doc{i}.json"), doc.as_bytes());
// hlx:665
let p = path.to_str().unwrap();
// hlx:666
for sub in ["run", "validate", "explain"] {
// hlx:667
let f = env.exec(&["check", sub, "--input", p], b"");
// hlx:668
let s = env.run(sub, doc);
// hlx:669
assert_eq!(f.code, s.code, "{sub} doc{i}");
// hlx:670
assert_eq!(f.out, s.out, "{sub} doc{i}");
// hlx:671
// the document is read from the file; stdin is ignored when a file is named
// hlx:672
let both = env.exec(&["check", sub, "--input", p], BASE.as_bytes());
// hlx:673
assert_eq!(f.out, both.out, "{sub} doc{i}: named file wins over stdin");
// hlx:674
}
// hlx:675
}
// hlx:676
}
// hlx:677
#[test]
// hlx:678
fn input_io_errors_use_the_error_shape() {
// hlx:679
let env = Env::new("io");
// hlx:680
let missing = env.root.join("in").join("nope.json");
// hlx:681
err(
&env.exec(&["check", "run", "--input", missing.to_str().unwrap()], b""),
"missing file",
);
// hlx:682
err(
&env.exec(
&[
"check",
"validate",
"--input",
env.root.join("in").to_str().unwrap(),
],
b"",
),
"directory",
);
// hlx:683
err(
&env.exec(&["check", "explain", "--input", ""], b""),
"empty path",
);
// hlx:684
err(
&env.exec(&["check", "run", "--input", "-"], b""),
"empty stdin",
);
// hlx:685
}
// hlx:686
// ---------------------------------------------------------------- top-level keys and definition keys
// hlx:687
#[test]
// hlx:688
fn top_level_shape_is_strict() {
// hlx:689
let env = Env::new("top");
// hlx:690
let check = "{\"schema\":\"instinct.check/v1\",\"id\":\"t1\",\"revision\":1,\"inputs\":{\"a\":\"bool\"},\"claim\":{\"op\":\"eq\",\"left\":{\"fact\":\"a\"},\"right\":{\"fact\":\"a\"}}}";
// hlx:691
let bad = [
// hlx:692
"{}".to_string(),
// hlx:693
"[]".to_string(),
// hlx:694
"null".to_string(),
// hlx:695
"\"check\"".to_string(),
// hlx:696
"7".to_string(),
// hlx:697
"true".to_string(),
// hlx:698
format!("{{\"facts\":{{}},\"check\":null}}"),
// hlx:699
format!("{{\"check\":[]}}"),
// hlx:700
format!("{{\"check\":{check},\"extra\":{{}}}}"),
// hlx:701
format!("{{\"check\":{check},\"Facts\":{{}}}}"),
// hlx:702
format!("{{\"check\":{check},\"facts\":null}}"),
// hlx:703
format!("{{\"check\":{check},\"conditions\":null}}"),
// hlx:704
format!("{{\"check\":{check},\"scope\":null}}"),
// hlx:705
format!("{{\"check\":{check},\"facts\":[]}}"),
// hlx:706
format!("{{\"check\":{check},\"conditions\":[]}}"),
// hlx:707
format!("{{\"check\":{check},\"scope\":[]}}"),
// hlx:708
format!("{{\"facts\":{{}},\"conditions\":{{}},\"scope\":{{}}}}"),
// hlx:709
];
// hlx:710
for doc in &bad {
// hlx:711
all_err_s(&env, doc, "top level");
// hlx:712
}
// hlx:713
valid(&env, &format!("{{\"check\":{check}}}"), "check alone");
// hlx:714
valid(
&env,
&format!("{{\"scope\":{{}},\"conditions\":{{}},\"facts\":{{}},\"check\":{check}}}"),
"order is free",
);
// hlx:715
}
// hlx:716
#[test]
// hlx:717
fn definition_requires_its_five_keys_and_rejects_unknown_ones() {
// hlx:718
let env = Env::new("defkeys");
// hlx:719
let parts = [
// hlx:720
("schema", "\"instinct.check/v1\""),
// hlx:721
("id", "\"t1\""),
// hlx:722
("revision", "1"),
// hlx:723
("inputs", "{\"a\":\"bool\"}"),
// hlx:724
(
"claim",
"{\"op\":\"eq\",\"left\":{\"fact\":\"a\"},\"right\":{\"fact\":\"a\"}}",
),
// hlx:725
];
// hlx:726
let build = |skip: Option<&str>, extra: &str| {
// hlx:727
let body: Vec<String> =
// hlx:728
parts.iter().filter(|(k, _)| Some(*k) != skip).map(|(k, v)| format!("\"{k}\":{v}")).collect();
// hlx:729
format!("{{\"check\":{{{}{extra}}}}}", body.join(","))
// hlx:730
};
// hlx:731
valid(&env, &build(None, ""), "complete");
// hlx:732
valid(
&env,
&build(None, ",\"required_conditions\":[],\"scope\":{}"),
"optional keys",
);
// hlx:733
for (k, _) in parts {
// hlx:734
all_err_s(&env, &build(Some(k), ""), &format!("missing {k}"));
// hlx:735
}
// hlx:736
for extra in [
// hlx:737
",\"extra\":1",
// hlx:738
",\"description\":\"x\"",
// hlx:739
",\"Scope\":{}",
// hlx:740
",\"required_conditions\":null",
// hlx:741
",\"required_conditions\":\"c\"",
// hlx:742
",\"required_conditions\":{}",
// hlx:743
",\"required_conditions\":[1]",
// hlx:744
",\"required_conditions\":[null]",
// hlx:745
",\"required_conditions\":[[\"c\"]]",
// hlx:746
",\"scope\":null",
// hlx:747
",\"scope\":[]",
// hlx:748
",\"inputs\":{}",
// hlx:749
] {
// hlx:750
all_err_s(&env, &build(None, extra), extra);
// hlx:751
}
// hlx:752
}
// hlx:753
#[test]
// hlx:754
fn schema_string_must_match_exactly() {
// hlx:755
let env = Env::new("schema");
// hlx:756
let base = d("{\"a\":\"bool\"}", &op2("eq", "a", "a"));
// hlx:757
valid(&env, &base.clone().json(), "v1");
// hlx:758
for s in [
// hlx:759
"\"instinct.check/v2\"",
// hlx:760
"\"instinct.check/v0\"",
// hlx:761
"\"instinct.check/V1\"",
// hlx:762
"\"Instinct.check/v1\"",
// hlx:763
"\"instinct.check/v1 \"",
// hlx:764
"\"instinct.check\"",
// hlx:765
"\"instinct.check-result/v1\"",
// hlx:766
"\"\"",
// hlx:767
"1",
// hlx:768
"null",
// hlx:769
"true",
// hlx:770
"[\"instinct.check/v1\"]",
// hlx:771
] {
// hlx:772
all_err_s(&env, &base.clone().schema(s).json(), s);
// hlx:773
}
// hlx:774
}
// hlx:775
#[test]
// hlx:776
fn ids_are_one_to_128_ascii_characters_starting_with_a_letter() {
// hlx:777
let env = Env::new("ids");
// hlx:778
let base = d("{\"a\":\"bool\"}", &op2("eq", "a", "a")).facts("{\"a\":true}");
// hlx:779
let long_ok = format!("a{}", "b".repeat(127));
// hlx:780
let ok = [
"a",
"Z",
"a1",
"A_b-c.d",
"x.y.z",
"a-",
"a.",
"a_",
"ab0",
&long_ok,
"artifact-membership",
];
// hlx:781
for id in ok {
// hlx:782
let j = result(&env.run("run", &base.clone().id(&format!("\"{id}\"")).json()));
// hlx:783
assert_eq!(sf(&j, "check_id"), id);
// hlx:784
assert_eq!(sf(&j, "verdict"), "pass");
// hlx:785
}
// hlx:786
let too_long = format!("a{}", "b".repeat(128));
// hlx:787
let bad = [
// hlx:788
"".to_string(),
// hlx:789
"1a".to_string(),
// hlx:790
"0".to_string(),
// hlx:791
"_a".to_string(),
// hlx:792
"-a".to_string(),
// hlx:793
".a".to_string(),
// hlx:794
"a b".to_string(),
// hlx:795
"a/b".to_string(),
// hlx:796
"a:b".to_string(),
// hlx:797
"a\\u00e9".to_string(),
// hlx:798
"\\u00e9a".to_string(),
// hlx:799
"a\\u0000".to_string(),
// hlx:800
"a\\n".to_string(),
// hlx:801
"a b".replace(' ', "\\t"),
// hlx:802
"a*".to_string(),
// hlx:803
"a@b".to_string(),
// hlx:804
"a\\u0430".to_string(),
// hlx:805
too_long,
// hlx:806
];
// hlx:807
for id in &bad {
// hlx:808
all_err_s(
&env,
&base.clone().id(&format!("\"{id}\"")).json(),
&format!("id {id:?}"),
);
// hlx:809
}
// hlx:810
for raw in ["null", "1", "true", "[]", "{}", "[\"a\"]"] {
// hlx:811
all_err_s(&env, &base.clone().id(raw).json(), raw);
// hlx:812
}
// hlx:813
}
// hlx:814
#[test]
// hlx:815
fn revision_is_an_exact_integer_literal_between_1_and_2147483647() {
// hlx:816
let env = Env::new("rev");
// hlx:817
let base = d("{\"a\":\"bool\"}", &op2("eq", "a", "a")).facts("{\"a\":true}");
// hlx:818
for r in ["1", "2", "10", "255", "65536", "2147483646", "2147483647"] {
// hlx:819
let j = result(&env.run("run", &base.clone().rev(r).json()));
// hlx:820
assert_eq!(j.get("revision"), Some(&J::Num(r.into())), "revision {r}");
// hlx:821
}
// hlx:822
for r in [
// hlx:823
"0",
"-1",
"2147483648",
"2147483649",
"4294967296",
"99999999999999999999",
"01",
"001",
"1.0",
"1.",
".5",
"1.5",
"1e0",
// hlx:824
"1E0",
"1e+0",
"1e1",
"10e-1",
"0.1e1",
"+1",
"-0",
"-",
"--1",
"0x1",
"1_0",
"Infinity",
"NaN",
"null",
"true",
"false",
// hlx:825
"\"1\"",
"[1]",
"{}",
"1 2",
"1.0000000000000001",
// hlx:826
] {
// hlx:827
all_err_s(&env, &base.clone().rev(r).json(), &format!("revision {r}"));
// hlx:828
}
// hlx:829
}
// hlx:830
// ---------------------------------------------------------------- types
// hlx:831
#[test]
// hlx:832
fn input_type_names_are_exactly_the_five_supported_ones() {
// hlx:833
let env = Env::new("typenames");
// hlx:834
for t in ["string", "bool", "int", "rational", "set<string>"] {
// hlx:835
let doc = d(&format!("{{\"a\":\"{t}\"}}"), &op2("eq", "a", "a")).json();
// hlx:836
valid(&env, &doc, t);
// hlx:837
}
// hlx:838
for t in [
// hlx:839
"float",
"number",
"integer",
"i64",
"u32",
"str",
"boolean",
"set<int>",
"set<bool>",
"set",
"set<>",
"set<string",
// hlx:840
"Set<string>",
"set< string >",
"set<String>",
"SET<STRING>",
"String",
"Bool",
"INT",
"list<string>",
"array<string>",
// hlx:841
"map<string,string>",
"set<set<string>>",
"graph",
"node",
"edge",
"set<node>",
"",
" string",
"string ",
"null",
"any",
// hlx:842
"string|int",
"string?",
"option<string>",
// hlx:843
] {
// hlx:844
let doc = d(&format!("{{\"a\":\"{t}\"}}"), &op2("eq", "a", "a")).json();
// hlx:845
all_err_s(&env, &doc, &format!("type {t:?}"));
// hlx:846
}
// hlx:847
for raw in [
"null",
"1",
"true",
"[]",
"[\"string\"]",
"{\"type\":\"string\"}",
"{}",
] {
// hlx:848
all_err_s(
&env,
&d(&format!("{{\"a\":{raw}}}"), &op2("eq", "a", "a")).json(),
raw,
);
// hlx:849
}
// hlx:850
for raw in ["[]", "null", "\"a\"", "1"] {
// hlx:851
all_err_s(&env, &d(raw, &op2("eq", "a", "a")).json(), raw);
// hlx:852
}
// hlx:853
// names differing only by case are different facts
// hlx:854
let two = d("{\"A\":\"string\",\"a\":\"string\"}", &op2("eq", "A", "a"))
.facts("{\"A\":\"x\",\"a\":\"x\"}")
.json();
// hlx:855
assert_eq!(verdict(&env.run("run", &two)), "pass");
// hlx:856
}
// hlx:857
#[test]
// hlx:858
fn supplied_facts_must_be_declared_and_correctly_typed() {
// hlx:859
let env = Env::new("facttypes");
// hlx:860
let ins = "{\"s\":\"string\",\"b\":\"bool\",\"n\":\"int\",\"x\":\"set<string>\"}";
// hlx:861
let claim = all_of(&[
op2("eq", "s", "s"),
op2("eq", "b", "b"),
op2("eq", "n", "n"),
op2("eq", "x", "x"),
]);
// hlx:862
let mk = |facts: &str| d(ins, &claim).facts(facts).json();
// hlx:863
let good = "{\"s\":\"v\",\"b\":true,\"n\":\"7\",\"x\":[\"p\",\"q\"]}";
// hlx:864
assert_eq!(verdict(&env.run("run", &mk(good))), "pass");
// hlx:865
valid(&env, &mk(good), "good");
// hlx:866
valid(
&env,
&mk("{\"s\":\"\",\"b\":false,\"n\":\"0\",\"x\":[]}"),
"empty values",
);
// hlx:867
valid(&env, &mk("{}"), "no facts");
// hlx:868
valid(&env, &mk("{\"x\":[\"p\"]}"), "some facts");
// hlx:869
for f in [
// hlx:870
"{\"s\":1}",
// hlx:871
"{\"s\":true}",
// hlx:872
"{\"s\":null}",
// hlx:873
"{\"s\":[\"a\"]}",
// hlx:874
"{\"s\":{}}",
// hlx:875
"{\"b\":\"true\"}",
// hlx:876
"{\"b\":1}",
// hlx:877
"{\"b\":0}",
// hlx:878
"{\"b\":null}",
// hlx:879
"{\"b\":\"false\"}",
// hlx:880
"{\"n\":7}",
// hlx:881
"{\"n\":0}",
// hlx:882
"{\"n\":7.0}",
// hlx:883
"{\"n\":true}",
// hlx:884
"{\"n\":null}",
// hlx:885
"{\"n\":[\"7\"]}",
// hlx:886
"{\"x\":\"p\"}",
// hlx:887
"{\"x\":null}",
// hlx:888
"{\"x\":{}}",
// hlx:889
"{\"x\":[1]}",
// hlx:890
"{\"x\":[null]}",
// hlx:891
"{\"x\":[true]}",
// hlx:892
"{\"x\":[[\"p\"]]}",
// hlx:893
"{\"x\":[{}]}",
// hlx:894
"{\"x\":[\"p\",\"p\"]}",
// hlx:895
"{\"x\":[\"p\",\"q\",\"p\"]}",
// hlx:896
"{\"unknown\":\"v\"}",
// hlx:897
"{\"S\":\"v\"}",
// hlx:898
"{\"s\":\"v\",\"zzz\":true}",
// hlx:899
"[]",
// hlx:900
"null",
// hlx:901
"\"s\"",
// hlx:902
"7",
// hlx:903
] {
// hlx:904
all_err_s(&env, &mk(f), f);
// hlx:905
}
// hlx:906
}
// hlx:907
#[test]
// hlx:908
fn supplied_facts_are_type_checked_even_when_short_circuit_would_skip_them() {
// hlx:909
let env = Env::new("shortcircuit-types");
// hlx:910
let ins = "{\"one\":\"bool\",\"zero\":\"bool\",\"s\":\"string\"}";
// hlx:911
let any_t = any_of(&[op2("eq", "one", "one"), op2("eq", "s", "s")]);
// hlx:912
let all_f = all_of(&[op2("eq", "one", "zero"), op2("eq", "s", "s")]);
// hlx:913
for claim in [any_t, all_f] {
// hlx:914
let ok = d(ins, &claim)
.facts("{\"one\":true,\"zero\":false,\"s\":\"x\"}")
.json();
// hlx:915
assert_ne!(verdict(&env.run("run", &ok)), "abstain");
// hlx:916
let bad = d(ins, &claim)
.facts("{\"one\":true,\"zero\":false,\"s\":5}")
.json();
// hlx:917
all_err_s(&env, &bad, "unread wrong-typed fact");
// hlx:918
let undeclared = d(ins, &claim)
.facts("{\"one\":true,\"zero\":false,\"s\":\"x\",\"ghost\":true}")
.json();
// hlx:919
all_err_s(&env, &undeclared, "unread undeclared fact");
// hlx:920
}
// hlx:921
}
// hlx:922
#[test]
// hlx:923
fn int_facts_are_canonical_decimal_strings_within_i128() {
// hlx:924
let env = Env::new("ints");
// hlx:925
let mk = |v: &str| {
d("{\"n\":\"int\"}", &op2("eq", "n", "n"))
.facts(&format!("{{\"n\":\"{v}\"}}"))
.json()
};
// hlx:926
for v in [
// hlx:927
"0",
// hlx:928
"1",
// hlx:929
"-1",
// hlx:930
"9",
// hlx:931
"10",
// hlx:932
"-10",
// hlx:933
"123",
// hlx:934
"9007199254740992",
// hlx:935
"9007199254740993",
// hlx:936
"-9007199254740993",
// hlx:937
"9223372036854775807",
// hlx:938
"9223372036854775808",
// hlx:939
"-9223372036854775808",
// hlx:940
"-9223372036854775809",
// hlx:941
"18446744073709551615",
// hlx:942
"18446744073709551616",
// hlx:943
"170141183460469231731687303715884105727",
// hlx:944
"-170141183460469231731687303715884105728",
// hlx:945
] {
// hlx:946
assert_eq!(verdict(&env.run("run", &mk(v))), "pass", "{v}");
// hlx:947
valid(&env, &mk(v), v);
// hlx:948
}
// hlx:949
for v in [
// hlx:950
"+1",
// hlx:951
"+0",
// hlx:952
"1e3",
// hlx:953
"1E3",
// hlx:954
"1.0",
// hlx:955
"1.",
// hlx:956
".5",
// hlx:957
"01",
// hlx:958
"00",
// hlx:959
"-0",
// hlx:960
"-00",
// hlx:961
"-01",
// hlx:962
"",
// hlx:963
" ",
// hlx:964
"- 1",
// hlx:965
" 1",
// hlx:966
"1 ",
// hlx:967
"1\\n",
// hlx:968
"\\t1",
// hlx:969
"0x10",
// hlx:970
"0b1",
// hlx:971
"1_000",
// hlx:972
"1,000",
// hlx:973
"-",
// hlx:974
"--1",
// hlx:975
"+-1",
// hlx:976
"abc",
// hlx:977
"NaN",
// hlx:978
"Infinity",
// hlx:979
"null",
// hlx:980
"true",
// hlx:981
"170141183460469231731687303715884105728",
// hlx:982
"-170141183460469231731687303715884105729",
// hlx:983
"340282366920938463463374607431768211455",
// hlx:984
"99999999999999999999999999999999999999999999",
// hlx:985
"-99999999999999999999999999999999999999999999",
// hlx:986
"\\uff11\\uff12",
// hlx:987
"\\u0661",
// hlx:988
"\\u0663\\u0664",
// hlx:989
"1\\u0000",
// hlx:990
"\\u2212",
// hlx:991
"1\\u00a0",
// hlx:992
] {
// hlx:993
all_err_s(&env, &mk(v), &format!("int {v:?}"));
// hlx:994
}
// hlx:995
}
// hlx:996
#[test]
// hlx:997
fn int_comparisons_are_exact_beyond_f64_and_numeric_not_lexical() {
// hlx:998
let env = Env::new("intcmp");
// hlx:999
let max = "170141183460469231731687303715884105727";
// hlx:1000
let min = "-170141183460469231731687303715884105728";
// hlx:1001
// (a, b, lt, lte, eq)
// hlx:1002
let rows: Vec<(&str, &str, &str, &str, &str)> = vec![
// hlx:1003
(
"9007199254740992",
"9007199254740993",
"pass",
"pass",
"fail",
),
// hlx:1004
(
"9007199254740993",
"9007199254740992",
"fail",
"fail",
"fail",
),
// hlx:1005
(
"9007199254740993",
"9007199254740993",
"fail",
"pass",
"pass",
),
// hlx:1006
(
"9007199254740993",
"9007199254740995",
"pass",
"pass",
"fail",
),
// hlx:1007
(
"-9007199254740993",
"-9007199254740992",
"pass",
"pass",
"fail",
),
// hlx:1008
(
"-9007199254740992",
"-9007199254740993",
"fail",
"fail",
"fail",
),
// hlx:1009
("-1", "0", "pass", "pass", "fail"),
// hlx:1010
("0", "-1", "fail", "fail", "fail"),
// hlx:1011
("-10", "-9", "pass", "pass", "fail"),
// hlx:1012
("-9", "-10", "fail", "fail", "fail"),
// hlx:1013
("9", "10", "pass", "pass", "fail"),
// hlx:1014
("10", "9", "fail", "fail", "fail"),
// hlx:1015
("2", "10", "pass", "pass", "fail"),
// hlx:1016
("0", "0", "fail", "pass", "pass"),
// hlx:1017
("-5", "-5", "fail", "pass", "pass"),
// hlx:1018
(
"9223372036854775807",
"9223372036854775808",
"pass",
"pass",
"fail",
),
// hlx:1019
(
"-9223372036854775809",
"-9223372036854775808",
"pass",
"pass",
"fail",
),
// hlx:1020
(
"18446744073709551615",
"18446744073709551616",
"pass",
"pass",
"fail",
),
// hlx:1021
(
"18446744073709551616",
"18446744073709551615",
"fail",
"fail",
"fail",
),
// hlx:1022
(min, max, "pass", "pass", "fail"),
// hlx:1023
(max, min, "fail", "fail", "fail"),
// hlx:1024
(max, max, "fail", "pass", "pass"),
// hlx:1025
(min, min, "fail", "pass", "pass"),
// hlx:1026
(
"170141183460469231731687303715884105726",
max,
"pass",
"pass",
"fail",
),
// hlx:1027
(
max,
"170141183460469231731687303715884105726",
"fail",
"fail",
"fail",
),
// hlx:1028
(
min,
"-170141183460469231731687303715884105727",
"pass",
"pass",
"fail",
),
// hlx:1029
(
"-170141183460469231731687303715884105727",
min,
"fail",
"fail",
"fail",
),
// hlx:1030
(max, "0", "fail", "fail", "fail"),
// hlx:1031
(min, "0", "pass", "pass", "fail"),
// hlx:1032
];
// hlx:1033
for (a, b, lt, lte, eq) in rows {
// hlx:1034
let facts = format!("{{\"a\":\"{a}\",\"b\":\"{b}\"}}");
// hlx:1035
for (op, want) in [("lt", lt), ("lte", lte), ("eq", eq)] {
// hlx:1036
let doc = d("{\"a\":\"int\",\"b\":\"int\"}", &op2(op, "a", "b"))
.facts(&facts)
.json();
// hlx:1037
let j = result(&env.run("run", &doc));
// hlx:1038
assert_eq!(sf(&j, "verdict"), want, "{op}({a}, {b})");
// hlx:1039
}
// hlx:1040
}
// hlx:1041
}
// hlx:1042
#[test]
// hlx:1043
fn operand_types_must_match_the_operator_even_with_no_facts_supplied() {
// hlx:1044
let env = Env::new("opptypes");
// hlx:1045
let ins = "{\"s\":\"string\",\"t\":\"string\",\"b\":\"bool\",\"c\":\"bool\",\"n\":\"int\",\"m\":\"int\",\"x\":\"set<string>\",\"y\":\"set<string>\"}";
// hlx:1046
let good = [
// hlx:1047
("eq", "s", "t"),
// hlx:1048
("eq", "b", "c"),
// hlx:1049
("eq", "n", "m"),
// hlx:1050
("eq", "x", "y"),
// hlx:1051
("subset", "x", "y"),
// hlx:1052
("disjoint", "x", "y"),
// hlx:1053
("contains", "x", "s"),
// hlx:1054
("lt", "n", "m"),
// hlx:1055
("lte", "n", "m"),
// hlx:1056
];
// hlx:1057
for (op, l, r) in good {
// hlx:1058
valid(
&env,
&d(ins, &op2(op, l, r)).json(),
&format!("{op} {l} {r}"),
);
// hlx:1059
}
// hlx:1060
let bad = [
// hlx:1061
("eq", "s", "n"),
// hlx:1062
("eq", "s", "b"),
// hlx:1063
("eq", "s", "x"),
// hlx:1064
("eq", "n", "b"),
// hlx:1065
("eq", "n", "x"),
// hlx:1066
("eq", "b", "x"),
// hlx:1067
("lt", "s", "t"),
// hlx:1068
("lt", "b", "c"),
// hlx:1069
("lt", "x", "y"),
// hlx:1070
("lt", "n", "s"),
// hlx:1071
("lt", "s", "n"),
// hlx:1072
("lte", "s", "t"),
// hlx:1073
("lte", "b", "c"),
// hlx:1074
("lte", "x", "y"),
// hlx:1075
("lte", "n", "x"),
// hlx:1076
("subset", "s", "t"),
// hlx:1077
("subset", "x", "s"),
// hlx:1078
("subset", "s", "y"),
// hlx:1079
("subset", "n", "m"),
// hlx:1080
("subset", "b", "c"),
// hlx:1081
("disjoint", "x", "s"),
// hlx:1082
("disjoint", "s", "y"),
// hlx:1083
("disjoint", "n", "m"),
// hlx:1084
("contains", "s", "t"),
// hlx:1085
("contains", "s", "x"),
// hlx:1086
("contains", "x", "y"),
// hlx:1087
("contains", "x", "n"),
// hlx:1088
("contains", "x", "b"),
// hlx:1089
("contains", "n", "s"),
// hlx:1090
];
// hlx:1091
for (op, l, r) in bad {
// hlx:1092
all_err_s(
&env,
&d(ins, &op2(op, l, r)).json(),
&format!("{op}({l}, {r})"),
);
// hlx:1093
}
// hlx:1094
}
// hlx:1095
// ---------------------------------------------------------------- set semantics, Unicode, witnesses
// hlx:1096
#[test]
// hlx:1097
fn subset_and_disjoint_ignore_order_and_name_a_deterministic_witness() {
// hlx:1098
let env = Env::new("sets");
// hlx:1099
// (op, left, right, verdict, witness)
// hlx:1100
let rows: Vec<(&str, &str, &str, &str, Option<&str>)> = vec![
// hlx:1101
("subset", "[]", "[]", "pass", None),
// hlx:1102
("subset", "[]", "[\"x\"]", "pass", None),
// hlx:1103
("subset", "[\"x\"]", "[]", "fail", Some("x")),
// hlx:1104
(
"subset",
"[\"a\",\"b\"]",
"[\"b\",\"a\",\"c\"]",
"pass",
None,
),
// hlx:1105
("subset", "[\"b\",\"a\"]", "[\"a\",\"b\"]", "pass", None),
// hlx:1106
(
"subset",
"[\"z\",\"b\",\"m\"]",
"[\"m\"]",
"fail",
Some("b"),
),
// hlx:1107
(
"subset",
"[\"m\",\"b\",\"z\"]",
"[\"m\"]",
"fail",
Some("b"),
),
// hlx:1108
(
"subset",
"[\"b\",\"m\",\"z\"]",
"[\"m\"]",
"fail",
Some("b"),
),
// hlx:1109
("subset", "[\"a\",\"B\"]", "[]", "fail", Some("B")),
// hlx:1110
("subset", "[\"a\",\"A\"]", "[\"a\"]", "fail", Some("A")),
// hlx:1111
("subset", "[\"ab\",\"a\"]", "[]", "fail", Some("a")),
// hlx:1112
("subset", "[\"\"]", "[\"\"]", "pass", None),
// hlx:1113
("subset", "[\"\",\"a\"]", "[\"a\"]", "fail", Some("")),
// hlx:1114
("subset", "[\"A\"]", "[\"a\"]", "fail", Some("A")),
// hlx:1115
("subset", "[\"a \"]", "[\"a\"]", "fail", Some("a ")),
// hlx:1116
("subset", "[\"a\\nb\"]", "[]", "fail", Some("a\nb")),
// hlx:1117
("subset", "[\"q\\\"r\\\\s\"]", "[]", "fail", Some("q\"r\\s")),
// hlx:1118
("subset", "[\"a\\u0000b\"]", "[\"a\\u0000b\"]", "pass", None),
// hlx:1119
("disjoint", "[]", "[]", "pass", None),
// hlx:1120
("disjoint", "[]", "[\"a\"]", "pass", None),
// hlx:1121
("disjoint", "[\"a\"]", "[]", "pass", None),
// hlx:1122
("disjoint", "[\"a\"]", "[\"b\"]", "pass", None),
// hlx:1123
("disjoint", "[\"a\",\"b\"]", "[\"c\",\"d\"]", "pass", None),
// hlx:1124
("disjoint", "[\"a\"]", "[\"A\"]", "pass", None),
// hlx:1125
(
"disjoint",
"[\"a\",\"b\"]",
"[\"b\",\"c\"]",
"fail",
Some("b"),
),
// hlx:1126
(
"disjoint",
"[\"m\",\"b\"]",
"[\"b\",\"m\"]",
"fail",
Some("b"),
),
// hlx:1127
(
"disjoint",
"[\"b\",\"m\"]",
"[\"m\",\"b\"]",
"fail",
Some("b"),
),
// hlx:1128
(
"disjoint",
"[\"z\",\"m\",\"b\"]",
"[\"q\",\"m\",\"b\",\"z\"]",
"fail",
Some("b"),
),
// hlx:1129
];
// hlx:1130
for (op, l, r, v, w) in rows {
// hlx:1131
let j = result(&env.run("run", &set_doc(op, l, r)));
// hlx:1132
assert_eq!(sf(&j, "verdict"), v, "{op} {l} {r}");
// hlx:1133
match w {
// hlx:1134
Some(w) => assert_eq!(j.get("witness"), Some(&J::Str(w.into())), "{op} {l} {r}"),
// hlx:1135
None => assert_eq!(j.get("witness"), Some(&J::Null), "{op} {l} {r}"),
// hlx:1136
}
// hlx:1137
}
// hlx:1138
}
// hlx:1139
#[test]
// hlx:1140
fn witness_does_not_depend_on_input_order() {
// hlx:1141
let env = Env::new("perm");
// hlx:1142
let orders = [
// hlx:1143
["a", "b", "c", "d"],
// hlx:1144
["d", "c", "b", "a"],
// hlx:1145
["b", "d", "a", "c"],
// hlx:1146
["c", "a", "d", "b"],
// hlx:1147
];
// hlx:1148
let mut seen = Vec::new();
// hlx:1149
for l in orders {
// hlx:1150
for r in orders {
// hlx:1151
let ls = js(&l);
// hlx:1152
let rs = js(&r[..2]);
// hlx:1153
let sub = result(&env.run("run", &set_doc("subset", &ls, &rs)));
// hlx:1154
let dis = result(&env.run("run", &set_doc("disjoint", &ls, &rs)));
// hlx:1155
seen.push((
sub.get("verdict").cloned(),
sub.get("witness").cloned(),
dis.get("verdict").cloned(),
dis.get("witness").cloned(),
));
// hlx:1156
}
// hlx:1157
}
// hlx:1158
// the right-hand set is {a,b} or {d,c} etc. depending on order, so group by the actual right set
// hlx:1159
for l in orders {
// hlx:1160
let mut by_set: Vec<(Vec<String>, J, J)> = Vec::new();
// hlx:1161
for r in orders {
// hlx:1162
let mut key: Vec<String> = r[..2].iter().map(|s| s.to_string()).collect();
// hlx:1163
key.sort();
// hlx:1164
let o = result(&env.run("run", &set_doc("subset", &js(&l), &js(&r[..2]))));
// hlx:1165
let w = o.get("witness").cloned().unwrap();
// hlx:1166
let v = o.get("verdict").cloned().unwrap();
// hlx:1167
if let Some(prev) = by_set.iter().find(|(k, _, _)| *k == key) {
// hlx:1168
assert_eq!(
(prev.1.clone(), prev.2.clone()),
(v, w),
"order changed the outcome for {l:?} vs {r:?}"
);
// hlx:1169
} else {
// hlx:1170
by_set.push((key, v, w));
// hlx:1171
}
// hlx:1172
}
// hlx:1173
}
// hlx:1174
assert!(!seen.is_empty());
// hlx:1175
}
// hlx:1176
#[test]
// hlx:1177
fn contains_is_exact_membership_without_case_folding_or_normalization() {
// hlx:1178
let env = Env::new("contains");
// hlx:1179
let ins = "{\"x\":\"set<string>\",\"s\":\"string\"}";
// hlx:1180
let rows: Vec<(&str, &str, &str)> = vec![
// hlx:1181
("[\"a\",\"b\"]", "b", "pass"),
// hlx:1182
("[\"a\",\"b\"]", "c", "fail"),
// hlx:1183
("[\"a\",\"b\"]", "B", "fail"),
// hlx:1184
("[\"a\",\"b\"]", "ab", "fail"),
// hlx:1185
("[\"a\",\"b\"]", "", "fail"),
// hlx:1186
("[\"a\",\"\"]", "", "pass"),
// hlx:1187
("[]", "a", "fail"),
// hlx:1188
("[\"\\u00e9\"]", "\\u00e9", "pass"),
// hlx:1189
("[\"\\u00e9\"]", "e\\u0301", "fail"),
// hlx:1190
("[\"e\\u0301\"]", "\\u00e9", "fail"),
// hlx:1191
("[\"e\\u0301\"]", "e\\u0301", "pass"),
// hlx:1192
("[\"\\u00df\"]", "SS", "fail"),
// hlx:1193
("[\"\\u00df\"]", "ss", "fail"),
// hlx:1194
("[\"\\u0130\"]", "i", "fail"),
// hlx:1195
("[\"K\"]", "\\u212a", "fail"),
// hlx:1196
("[\"\\ud83d\\ude00\"]", "\\ud83d\\ude00", "pass"),
// hlx:1197
("[\"a\\u200bb\"]", "ab", "fail"),
// hlx:1198
("[\"a\\u0000b\"]", "a\\u0000b", "pass"),
// hlx:1199
("[\"a\\u0000b\"]", "a", "fail"),
// hlx:1200
("[\"Stra\\u00dfe\"]", "STRASSE", "fail"),
// hlx:1201
("[\"\\u0391\"]", "\\u0041", "fail"),
// hlx:1202
];
// hlx:1203
for (x, s, want) in rows {
// hlx:1204
let doc = d(ins, &op2("contains", "x", "s"))
.facts(&format!("{{\"x\":{x},\"s\":\"{s}\"}}"))
.json();
// hlx:1205
assert_eq!(verdict(&env.run("run", &doc)), want, "contains {x} {s}");
// hlx:1206
}
// hlx:1207
// raw UTF-8 and the escaped spelling are the same scalar sequence
// hlx:1208
let raw = d(ins, &op2("contains", "x", "s"))
.facts("{\"x\":[\"\\ud83d\\ude00\",\"\\u00e9\"],\"s\":\"\u{1F600}\"}")
.json();
// hlx:1209
assert_eq!(verdict(&env.run("run", &raw)), "pass");
// hlx:1210
let raw = d(ins, &op2("contains", "x", "s"))
.facts("{\"x\":[\"\u{1F600}\",\"\u{e9}\"],\"s\":\"\\u00e9\"}")
.json();
// hlx:1211
assert_eq!(verdict(&env.run("run", &raw)), "pass");
// hlx:1212
}
// hlx:1213
#[test]
// hlx:1214
fn unicode_members_are_compared_as_exact_scalar_sequences_and_witnessed_verbatim() {
// hlx:1215
let env = Env::new("unicode");
// hlx:1216
let j = result(&env.run("run", &set_doc("subset", "[\"e\\u0301\"]", "[\"\\u00e9\"]")));
// hlx:1217
assert_eq!(sf(&j, "verdict"), "fail");
// hlx:1218
assert_eq!(j.get("witness"), Some(&J::Str("e\u{301}".into())));
// hlx:1219
let j = result(&env.run(
"run",
&set_doc(
"subset",
"[\"\u{e9}\",\"\\ud83d\\ude00\"]",
"[\"\\u00e9\",\"\u{1F600}\"]",
),
));
// hlx:1220
assert_eq!(sf(&j, "verdict"), "pass");
// hlx:1221
let j = result(&env.run(
"run",
&set_doc("disjoint", "[\"\u{e9}\"]", "[\"e\\u0301\"]"),
));
// hlx:1222
assert_eq!(sf(&j, "verdict"), "pass");
// hlx:1223
let j = result(&env.run("run", &set_doc("subset", "[\"\\u0434\\u0430\"]", "[]")));
// hlx:1224
assert_eq!(j.get("witness"), Some(&J::Str("\u{434}\u{430}".into())));
// hlx:1225
let j = result(&env.run("run", &set_doc("subset", "[\"\u{1F600}\"]", "[]")));
// hlx:1226
assert_eq!(j.get("witness"), Some(&J::Str("\u{1F600}".into())));
// hlx:1227
// code point order decides "first lexicographic"
// hlx:1228
let j = result(&env.run(
"run",
&set_doc("subset", "[\"\u{e9}\",\"z\",\"\u{1F600}\"]", "[]"),
));
// hlx:1229
assert_eq!(j.get("witness"), Some(&J::Str("z".into())));
// hlx:1230
// strings compare exactly in eq
// hlx:1231
let eq = |a: &str, b: &str| {
// hlx:1232
let doc = d("{\"a\":\"string\",\"b\":\"string\"}", &op2("eq", "a", "b"))
.facts(&format!("{{\"a\":\"{a}\",\"b\":\"{b}\"}}"))
.json();
// hlx:1233
verdict(&env.run("run", &doc))
// hlx:1234
};
// hlx:1235
assert_eq!(eq("\\u00e9", "\u{e9}"), "pass");
// hlx:1236
assert_eq!(eq("\\u00e9", "e\\u0301"), "fail");
// hlx:1237
assert_eq!(eq("a", "A"), "fail");
// hlx:1238
assert_eq!(eq("", ""), "pass");
// hlx:1239
assert_eq!(eq("a", "a "), "fail");
// hlx:1240
assert_eq!(eq("\\ud83d\\ude00", "\u{1F600}"), "pass");
// hlx:1241
assert_eq!(eq("\\/", "/"), "pass");
// hlx:1242
}
// hlx:1243
#[test]
// hlx:1244
fn duplicate_set_members_are_rejected_including_escaped_spellings() {
// hlx:1245
let env = Env::new("setdups");
// hlx:1246
for l in [
// hlx:1247
"[\"a\",\"a\"]",
// hlx:1248
"[\"a\",\"b\",\"a\"]",
// hlx:1249
"[\"\",\"\"]",
// hlx:1250
"[\"\\u0061\",\"a\"]",
// hlx:1251
"[\"a\",\"\\u0061\"]",
// hlx:1252
"[\"\\u00e9\",\"\u{e9}\"]",
// hlx:1253
"[\"\\u00E9\",\"\\u00e9\"]",
// hlx:1254
"[\"\\ud83d\\ude00\",\"\u{1F600}\"]",
// hlx:1255
"[\"a\\/b\",\"a/b\"]",
// hlx:1256
"[\"a\\nb\",\"a\\u000ab\"]",
// hlx:1257
] {
// hlx:1258
all_err_s(&env, &set_doc("subset", l, "[]"), l);
// hlx:1259
all_err_s(&env, &set_doc("subset", "[]", l), l);
// hlx:1260
}
// hlx:1261
for l in [
// hlx:1262
"[\"a\",\"A\"]",
// hlx:1263
"[\"a\",\"a \"]",
// hlx:1264
"[\"\\u00e9\",\"e\\u0301\"]",
// hlx:1265
"[\"\",\"a\"]",
// hlx:1266
"[\"a\\u0000\",\"a\"]",
// hlx:1267
] {
// hlx:1268
valid(&env, &set_doc("subset", l, "[]"), l);
// hlx:1269
}
// hlx:1270
}
// hlx:1271
#[test]
// hlx:1272
fn strings_must_be_unicode_scalar_sequences() {
// hlx:1273
let env = Env::new("surrogates");
// hlx:1274
for l in [
// hlx:1275
"[\"\\ud800\"]",
// hlx:1276
"[\"\\udc00\"]",
// hlx:1277
"[\"\\udfff\"]",
// hlx:1278
"[\"a\\ud800\"]",
// hlx:1279
"[\"\\ud800a\"]",
// hlx:1280
"[\"\\ud83d\\ud83d\"]",
// hlx:1281
"[\"\\ude00\\ud83d\"]",
// hlx:1282
"[\"\\ud83d\\u0061\"]",
// hlx:1283
] {
// hlx:1284
all_err_s(&env, &set_doc("subset", l, "[]"), l);
// hlx:1285
let doc = d("{\"s\":\"string\"}", &op2("eq", "s", "s"))
.facts(&format!("{{\"s\":{}}}", &l[1..l.len() - 1]))
.json();
// hlx:1286
all_err_s(&env, &doc, l);
// hlx:1287
}
// hlx:1288
}
// hlx:1289
#[test]
// hlx:1290
fn eq_compares_each_supported_type_and_sets_without_order() {
// hlx:1291
let env = Env::new("eq");
// hlx:1292
let ins = "{\"x\":\"set<string>\",\"y\":\"set<string>\"}";
// hlx:1293
let cases = [
// hlx:1294
("[\"a\",\"b\"]", "[\"b\",\"a\"]", "pass"),
// hlx:1295
("[]", "[]", "pass"),
// hlx:1296
("[\"a\"]", "[\"a\",\"b\"]", "fail"),
// hlx:1297
("[\"a\",\"b\"]", "[\"a\"]", "fail"),
// hlx:1298
("[\"a\"]", "[\"A\"]", "fail"),
// hlx:1299
("[\"a\",\"b\",\"c\"]", "[\"c\",\"a\",\"b\"]", "pass"),
// hlx:1300
("[]", "[\"a\"]", "fail"),
// hlx:1301
];
// hlx:1302
for (x, y, want) in cases {
// hlx:1303
let doc = d(ins, &op2("eq", "x", "y"))
.facts(&format!("{{\"x\":{x},\"y\":{y}}}"))
.json();
// hlx:1304
assert_eq!(verdict(&env.run("run", &doc)), want, "{x} == {y}");
// hlx:1305
}
// hlx:1306
for (a, b, want) in [
("true", "true", "pass"),
("false", "false", "pass"),
("true", "false", "fail"),
("false", "true", "fail"),
] {
// hlx:1307
let doc = d("{\"a\":\"bool\",\"b\":\"bool\"}", &op2("eq", "a", "b"))
.facts(&format!("{{\"a\":{a},\"b\":{b}}}"))
.json();
// hlx:1308
assert_eq!(verdict(&env.run("run", &doc)), want, "{a} == {b}");
// hlx:1309
}
// hlx:1310
}
// hlx:1311
// ---------------------------------------------------------------- missing evidence and three-valued logic
// hlx:1312
#[test]
// hlx:1313
fn missing_facts_abstain_and_are_listed_sorted_and_unique() {
// hlx:1314
let env = Env::new("missing");
// hlx:1315
let ins = "{\"z\":\"bool\",\"m\":\"bool\",\"a\":\"bool\"}";
// hlx:1316
let claim = all_of(&[
op2("eq", "z", "a"),
op2("eq", "m", "a"),
op2("eq", "z", "m"),
]);
// hlx:1317
let j = result(&env.run("run", &d(ins, &claim).json()));
// hlx:1318
assert_eq!(sf(&j, "verdict"), "abstain");
// hlx:1319
assert_eq!(names(j.get("missing").unwrap()), vec!["a", "m", "z"]);
// hlx:1320
// supplying one removes it from the list; the rest stay missing
// hlx:1321
let j = result(&env.run("run", &d(ins, &claim).facts("{\"m\":true}").json()));
// hlx:1322
assert_eq!(sf(&j, "verdict"), "abstain");
// hlx:1323
let miss = names(j.get("missing").unwrap());
// hlx:1324
assert!(
!miss.contains(&"m".to_string())
&& miss.contains(&"a".to_string())
&& miss.contains(&"z".to_string()),
"{miss:?}"
);
// hlx:1325
// all supplied: nothing missing
// hlx:1326
let j = result(
&env.run(
"run",
&d(ins, &claim)
.facts("{\"z\":true,\"m\":true,\"a\":true}")
.json(),
),
);
// hlx:1327
assert_eq!(sf(&j, "verdict"), "pass");
// hlx:1328
assert_eq!(names(j.get("missing").unwrap()), Vec::<String>::new());
// hlx:1329
// each operator abstains when one operand is missing
// hlx:1330
for (op, ins, facts) in [
// hlx:1331
("subset", SET_IN, "{\"actual\":[\"a\"]}"),
// hlx:1332
("subset", SET_IN, "{\"allowed\":[\"a\"]}"),
// hlx:1333
("disjoint", SET_IN, "{\"actual\":[\"a\"]}"),
// hlx:1334
(
"eq",
"{\"actual\":\"string\",\"allowed\":\"string\"}",
"{\"actual\":\"a\"}",
),
// hlx:1335
(
"lt",
"{\"actual\":\"int\",\"allowed\":\"int\"}",
"{\"allowed\":\"3\"}",
),
// hlx:1336
("lte", "{\"actual\":\"int\",\"allowed\":\"int\"}", "{}"),
// hlx:1337
] {
// hlx:1338
let j = result(&env.run(
"run",
&d(ins, &op2(op, "actual", "allowed")).facts(facts).json(),
));
// hlx:1339
assert_eq!(sf(&j, "verdict"), "abstain", "{op} {facts}");
// hlx:1340
assert_eq!(j.get("witness"), Some(&J::Null));
// hlx:1341
assert!(!names(j.get("missing").unwrap()).is_empty());
// hlx:1342
}
// hlx:1343
let doc = d(
"{\"x\":\"set<string>\",\"s\":\"string\"}",
&op2("contains", "x", "s"),
)
.facts("{\"x\":[\"a\"]}")
.json();
// hlx:1344
assert_eq!(verdict(&env.run("run", &doc)), "abstain");
// hlx:1345
}
// hlx:1346
#[test]
// hlx:1347
fn three_valued_all_any_not_follow_the_documented_tables() {
// hlx:1348
let env = Env::new("truth");
// hlx:1349
let ins = "{\"one\":\"bool\",\"zero\":\"bool\",\"gone\":\"bool\"}";
// hlx:1350
let facts = "{\"one\":true,\"zero\":false}";
// hlx:1351
fn build(s: &[u8], i: &mut usize) -> (String, char) {
// hlx:1352
let c = s[*i];
// hlx:1353
*i += 1;
// hlx:1354
match c {
// hlx:1355
b'T' => (op2("eq", "one", "one"), 'T'),
// hlx:1356
b'F' => (op2("eq", "one", "zero"), 'F'),
// hlx:1357
b'U' => (op2("eq", "one", "gone"), 'U'),
// hlx:1358
b'!' => {
// hlx:1359
let (e, v) = build(s, i);
// hlx:1360
(
not_of(&e),
match v {
'T' => 'F',
'F' => 'T',
_ => 'U',
},
)
// hlx:1361
}
// hlx:1362
b'A' | b'O' => {
// hlx:1363
assert_eq!(s[*i], b'(');
// hlx:1364
*i += 1;
// hlx:1365
let (mut es, mut vs) = (Vec::new(), Vec::new());
// hlx:1366
while s[*i] != b')' {
// hlx:1367
let (e, v) = build(s, i);
// hlx:1368
es.push(e);
// hlx:1369
vs.push(v);
// hlx:1370
}
// hlx:1371
*i += 1;
// hlx:1372
if c == b'A' {
// hlx:1373
let v = if vs.contains(&'F') {
'F'
} else if vs.contains(&'U') {
'U'
} else {
'T'
};
// hlx:1374
(all_of(&es), v)
// hlx:1375
} else {
// hlx:1376
let v = if vs.contains(&'T') {
'T'
} else if vs.contains(&'U') {
'U'
} else {
'F'
};
// hlx:1377
(any_of(&es), v)
// hlx:1378
}
// hlx:1379
}
// hlx:1380
other => panic!("bad dsl {}", other as char),
// hlx:1381
}
// hlx:1382
}
// hlx:1383
let check = |expr: &str| {
// hlx:1384
let mut i = 0;
// hlx:1385
let (claim, v) = build(expr.as_bytes(), &mut i);
// hlx:1386
assert_eq!(i, expr.len());
// hlx:1387
let want = match v {
'T' => "pass",
'F' => "fail",
_ => "abstain",
};
// hlx:1388
let j = result(&env.run("run", &d(ins, &claim).facts(facts).json()));
// hlx:1389
assert_eq!(sf(&j, "verdict"), want, "{expr}");
// hlx:1390
if want == "abstain" {
// hlx:1391
assert!(
names(j.get("missing").unwrap()).contains(&"gone".to_string()),
"{expr}"
);
// hlx:1392
}
// hlx:1393
};
// hlx:1394
let mut level1: Vec<String> = Vec::new();
// hlx:1395
for l in ["T", "F", "U"] {
// hlx:1396
level1.push(l.to_string());
// hlx:1397
level1.push(format!("!{l}"));
// hlx:1398
}
// hlx:1399
for op in ["A", "O"] {
// hlx:1400
for n in 1..=3usize {
// hlx:1401
let mut combos: Vec<String> = vec![String::new()];
// hlx:1402
for _ in 0..n {
// hlx:1403
combos = combos
.iter()
.flat_map(|c| ["T", "F", "U"].map(|l| format!("{c}{l}")))
.collect();
// hlx:1404
}
// hlx:1405
for c in combos {
// hlx:1406
level1.push(format!("{op}({c})"));
// hlx:1407
level1.push(format!("!{op}({c})"));
// hlx:1408
}
// hlx:1409
}
// hlx:1410
}
// hlx:1411
for e in &level1 {
// hlx:1412
check(e);
// hlx:1413
}
// hlx:1414
let sample = [
"T", "F", "U", "!U", "!A(TU)", "O(FU)", "A(UF)", "!O(FF)", "A(TTT)", "O(UU)",
];
// hlx:1415
for a in sample {
// hlx:1416
for b in sample {
// hlx:1417
check(&format!("A({a}{b})"));
// hlx:1418
check(&format!("O({a}{b})"));
// hlx:1419
check(&format!("!A({a}{b})"));
// hlx:1420
check(&format!("!O({b}{a})"));
// hlx:1421
}
// hlx:1422
}
// hlx:1423
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))",
] {
// hlx:1424
check(e);
// hlx:1425
}
// hlx:1426
}
// hlx:1427
#[test]
// hlx:1428
fn a_false_operand_decides_all_and_a_true_operand_decides_any_regardless_of_unknown_siblings() {
// hlx:1429
let env = Env::new("decide");
// hlx:1430
let ins = "{\"one\":\"bool\",\"zero\":\"bool\",\"gone\":\"bool\"}";
// hlx:1431
let u = op2("eq", "one", "gone");
// hlx:1432
let t = op2("eq", "one", "one");
// hlx:1433
let f = op2("eq", "one", "zero");
// hlx:1434
let facts = "{\"one\":true,\"zero\":false}";
// hlx:1435
let run = |claim: String| verdict(&env.run("run", &d(ins, &claim).facts(facts).json()));
// hlx:1436
assert_eq!(run(all_of(&[u.clone(), f.clone()])), "fail");
// hlx:1437
assert_eq!(run(all_of(&[f.clone(), u.clone()])), "fail");
// hlx:1438
assert_eq!(run(any_of(&[u.clone(), t.clone()])), "pass");
// hlx:1439
assert_eq!(run(any_of(&[t.clone(), u.clone()])), "pass");
// hlx:1440
assert_eq!(run(all_of(&[t.clone(), u.clone()])), "abstain");
// hlx:1441
assert_eq!(run(any_of(&[f.clone(), u.clone()])), "abstain");
// hlx:1442
assert_eq!(run(not_of(&u)), "abstain");
// hlx:1443
let j = result(&env.run(
"run",
&d(ins, &all_of(&[u.clone(), f.clone()])).facts(facts).json(),
));
// hlx:1444
assert_eq!(j.get("verdict"), Some(&J::Str("fail".into())));
// hlx:1445
}
// hlx:1446
#[test]
// hlx:1447
fn a_missing_required_condition_or_scope_mismatch_abstains_whatever_the_claim_says() {
// hlx:1448
let env = Env::new("gates");
// hlx:1449
let ins = "{\"one\":\"bool\",\"zero\":\"bool\"}";
// hlx:1450
let t = op2("eq", "one", "one");
// hlx:1451
let f = op2("eq", "one", "zero");
// hlx:1452
let facts = "{\"one\":true,\"zero\":false}";
// hlx:1453
for (claim, open_verdict) in [(&t, "pass"), (&f, "fail")] {
// hlx:1454
let base = d(ins, claim)
.facts(facts)
.req("[\"c1\",\"c2\"]")
.dscope("{\"project\":\"p\",\"persona\":\"q\"}");
// hlx:1455
let open = base
.clone()
.conds("{\"c1\":true,\"c2\":true}")
.scope("{\"project\":\"p\",\"persona\":\"q\"}");
// hlx:1456
assert_eq!(verdict(&env.run("run", &open.json())), open_verdict);
// hlx:1457
let gated = [
// hlx:1458
(
"no conditions",
base.clone().scope("{\"project\":\"p\",\"persona\":\"q\"}"),
),
// hlx:1459
("one missing", open.clone().conds("{\"c1\":true}")),
// hlx:1460
("other missing", open.clone().conds("{\"c2\":true}")),
// hlx:1461
(
"one false",
open.clone().conds("{\"c1\":false,\"c2\":true}"),
),
// hlx:1462
(
"other false",
open.clone().conds("{\"c1\":true,\"c2\":false}"),
),
// hlx:1463
(
"both false",
open.clone().conds("{\"c1\":false,\"c2\":false}"),
),
// hlx:1464
("no scope", open.clone().scope("{}")),
// hlx:1465
(
"scope omitted",
base.clone().conds("{\"c1\":true,\"c2\":true}"),
),
// hlx:1466
(
"wrong project",
open.clone().scope("{\"project\":\"x\",\"persona\":\"q\"}"),
),
// hlx:1467
(
"wrong persona",
open.clone().scope("{\"project\":\"p\",\"persona\":\"x\"}"),
),
// hlx:1468
("one dimension", open.clone().scope("{\"project\":\"p\"}")),
// hlx:1469
];
// hlx:1470
for (name, doc) in gated {
// hlx:1471
for sub in ["run", "explain"] {
// hlx:1472
let j = result(&env.run(sub, &doc.json()));
// hlx:1473
assert_eq!(sf(&j, "verdict"), "abstain", "{sub} {name} claim={claim}");
// hlx:1474
assert_eq!(j.get("witness"), Some(&J::Null), "{name}");
// hlx:1475
}
// hlx:1476
}
// hlx:1477
}
// hlx:1478
}
// hlx:1479
#[test]
// hlx:1480
fn missing_required_conditions_are_named_in_missing() {
// hlx:1481
let env = Env::new("condmissing");
// hlx:1482
let doc = d("{\"one\":\"bool\"}", &op2("eq", "one", "one"))
.facts("{\"one\":true}")
.req("[\"zeta\",\"alpha\"]");
// hlx:1483
let j = result(&env.run("run", &doc.clone().json()));
// hlx:1484
assert_eq!(sf(&j, "verdict"), "abstain");
// hlx:1485
assert_eq!(names(j.get("missing").unwrap()), vec!["alpha", "zeta"]);
// hlx:1486
let j = result(&env.run("run", &doc.clone().conds("{\"zeta\":true}").json()));
// hlx:1487
assert_eq!(sf(&j, "verdict"), "abstain");
// hlx:1488
assert_eq!(names(j.get("missing").unwrap()), vec!["alpha"]);
// hlx:1489
let j = result(&env.run(
"run",
&doc.clone().conds("{\"zeta\":true,\"alpha\":true}").json(),
));
// hlx:1490
assert_eq!(sf(&j, "verdict"), "pass");
// hlx:1491
assert_eq!(names(j.get("missing").unwrap()), Vec::<String>::new());
// hlx:1492
}
// hlx:1493
#[test]
// hlx:1494
fn conditions_are_declared_booleans_only() {
// hlx:1495
let env = Env::new("conditions");
// hlx:1496
let base = d("{\"a\":\"bool\"}", &op2("eq", "a", "a"))
.facts("{\"a\":true}")
.req("[\"c1\",\"c2\"]");
// hlx:1497
valid(&env, &base.clone().conds("{}").json(), "empty");
// hlx:1498
valid(&env, &base.clone().conds("{\"c1\":true}").json(), "partial");
// hlx:1499
valid(
&env,
&base.clone().conds("{\"c1\":false,\"c2\":true}").json(),
"false is fine",
);
// hlx:1500
for c in [
// hlx:1501
"{\"c3\":true}",
// hlx:1502
"{\"c1\":true,\"c3\":true}",
// hlx:1503
"{\"C1\":true}",
// hlx:1504
"{\"c1\":\"true\"}",
// hlx:1505
"{\"c1\":1}",
// hlx:1506
"{\"c1\":0}",
// hlx:1507
"{\"c1\":null}",
// hlx:1508
"{\"c1\":[true]}",
// hlx:1509
"{\"c1\":{}}",
// hlx:1510
"[\"c1\"]",
// hlx:1511
"null",
// hlx:1512
"true",
// hlx:1513
] {
// hlx:1514
all_err_s(&env, &base.clone().conds(c).json(), c);
// hlx:1515
}
// hlx:1516
// conditions are rejected when the definition requires none
// hlx:1517
let none = d("{\"a\":\"bool\"}", &op2("eq", "a", "a")).facts("{\"a\":true}");
// hlx:1518
all_err_s(
&env,
&none.clone().conds("{\"c1\":true}").json(),
"undeclared condition",
);
// hlx:1519
valid(&env, &none.clone().conds("{}").json(), "no conditions");
// hlx:1520
let empty_req = none.clone().req("[]");
// hlx:1521
valid(
&env,
&empty_req.clone().conds("{}").json(),
"empty required list",
);
// hlx:1522
all_err_s(
&env,
&empty_req.conds("{\"c1\":false}").json(),
"condition not in empty list",
);
// hlx:1523
}
// hlx:1524
// ---------------------------------------------------------------- scope
// hlx:1525
#[test]
// hlx:1526
fn scope_objects_accept_only_the_five_dimensions_with_nonempty_strings() {
// hlx:1527
let env = Env::new("scopeshape");
// hlx:1528
let base = d("{\"a\":\"bool\"}", &op2("eq", "a", "a")).facts("{\"a\":true}");
// hlx:1529
let good = [
// hlx:1530
"{}",
// hlx:1531
"{\"project\":\"p\"}",
// hlx:1532
"{\"persona\":\"p\"}",
// hlx:1533
"{\"harness\":\"h\"}",
// hlx:1534
"{\"version\":\"1.2.3\"}",
// hlx:1535
"{\"machine\":\"m\"}",
// hlx:1536
"{\"project\":\"p\",\"persona\":\"q\",\"harness\":\"h\",\"version\":\"v\",\"machine\":\"m\"}",
// hlx:1537
"{\"project\":\" \"}",
// hlx:1538
"{\"project\":\"a*b\"}",
// hlx:1539
"{\"project\":\"**\"}",
// hlx:1540
"{\"project\":\"p*\"}",
// hlx:1541
"{\"project\":\"\\u00e9\"}",
// hlx:1542
"{\"project\":\"\\ud83d\\ude00\"}",
// hlx:1543
"{\"project\":\"a b\"}",
// hlx:1544
];
// hlx:1545
for s in good {
// hlx:1546
valid(&env, &base.clone().dscope(s).json(), s);
// hlx:1547
valid(&env, &base.clone().scope(s).json(), s);
// hlx:1548
valid(&env, &base.clone().dscope(s).scope(s).json(), s);
// hlx:1549
}
// hlx:1550
let bad = [
// hlx:1551
"{\"project\":\"\"}",
// hlx:1552
"{\"project\":null}",
// hlx:1553
"{\"project\":1}",
// hlx:1554
"{\"project\":true}",
// hlx:1555
"{\"project\":[\"p\"]}",
// hlx:1556
"{\"project\":{}}",
// hlx:1557
"{\"project\":\"*\"}",
// hlx:1558
"{\"env\":\"x\"}",
// hlx:1559
"{\"cwd\":\"/tmp\"}",
// hlx:1560
"{\"user\":\"x\"}",
// hlx:1561
"{\"Project\":\"p\"}",
// hlx:1562
"{\"PROJECT\":\"p\"}",
// hlx:1563
"{\"project \":\"p\"}",
// hlx:1564
"{\"project\":\"p\",\"extra\":\"x\"}",
// hlx:1565
"{\"*\":\"x\"}",
// hlx:1566
"{\"project\":\"p\",\"persona\":\"\"}",
// hlx:1567
"[]",
// hlx:1568
"[\"project\"]",
// hlx:1569
"\"project\"",
// hlx:1570
"1",
// hlx:1571
"true",
// hlx:1572
];
// hlx:1573
for s in bad {
// hlx:1574
all_err_s(
&env,
&base.clone().dscope(s).json(),
&format!("definition scope {s}"),
);
// hlx:1575
all_err_s(
&env,
&base.clone().scope(s).json(),
&format!("request scope {s}"),
);
// hlx:1576
}
// hlx:1577
// a bad request scope is an error even when the definition scope is different
// hlx:1578
all_err_s(
&env,
&base
.clone()
.dscope("{\"project\":\"p\"}")
.scope("{\"env\":\"x\"}")
.json(),
"bad request scope",
);
// hlx:1579
all_err_s(
&env,
&base
.clone()
.dscope("{\"env\":\"x\"}")
.scope("{\"project\":\"p\"}")
.json(),
"bad definition scope",
);
// hlx:1580
}
// hlx:1581
#[test]
// hlx:1582
fn scope_matching_is_exact_per_required_dimension() {
// hlx:1583
let env = Env::new("scopematch");
// hlx:1584
let ins = "{\"one\":\"bool\",\"zero\":\"bool\"}";
// hlx:1585
let facts = "{\"one\":true,\"zero\":false}";
// hlx:1586
// the claim fails when evaluated, so "fail" proves the scope matched and "abstain" proves it did not
// hlx:1587
let claim = op2("eq", "one", "zero");
// hlx:1588
let rows: Vec<(Option<&str>, Option<&str>, &str)> = vec![
// hlx:1589
(Some("{\"project\":\"p\"}"), Some("{\"project\":\"p\"}"), "fail"),
// hlx:1590
(Some("{\"project\":\"p\"}"), Some("{\"project\":\"q\"}"), "abstain"),
// hlx:1591
(Some("{\"project\":\"p\"}"), Some("{\"project\":\"P\"}"), "abstain"),
// hlx:1592
(Some("{\"project\":\"p\"}"), Some("{\"project\":\"p \"}"), "abstain"),
// hlx:1593
(Some("{\"project\":\"p\"}"), Some("{\"project\":\" p\"}"), "abstain"),
// hlx:1594
(Some("{\"project\":\"p\"}"), Some("{\"project\":\"pp\"}"), "abstain"),
// hlx:1595
(Some("{\"project\":\"pp\"}"), Some("{\"project\":\"p\"}"), "abstain"),
// hlx:1596
(Some("{\"project\":\"p\"}"), None, "abstain"),
// hlx:1597
(Some("{\"project\":\"p\"}"), Some("{}"), "abstain"),
// hlx:1598
(Some("{\"project\":\"p\"}"), Some("{\"persona\":\"p\"}"), "abstain"),
// hlx:1599
(Some("{\"project\":\"p\"}"), Some("{\"project\":\"p\",\"persona\":\"x\"}"), "fail"),
// hlx:1600
(Some("{}"), Some("{\"project\":\"p\"}"), "fail"),
// hlx:1601
(Some("{}"), Some("{}"), "fail"),
// hlx:1602
(Some("{}"), None, "fail"),
// hlx:1603
(None, Some("{\"project\":\"p\"}"), "fail"),
// hlx:1604
(None, None, "fail"),
// hlx:1605
(Some("{\"project\":\"p\",\"persona\":\"a\"}"), Some("{\"project\":\"p\"}"), "abstain"),
// hlx:1606
(Some("{\"project\":\"p\",\"persona\":\"a\"}"), Some("{\"persona\":\"a\"}"), "abstain"),
// hlx:1607
(Some("{\"project\":\"p\",\"persona\":\"a\"}"), Some("{\"project\":\"p\",\"persona\":\"b\"}"), "abstain"),
// hlx:1608
(Some("{\"project\":\"p\",\"persona\":\"a\"}"), Some("{\"project\":\"q\",\"persona\":\"a\"}"), "abstain"),
// hlx:1609
(Some("{\"project\":\"p\",\"persona\":\"a\"}"), Some("{\"persona\":\"a\",\"project\":\"p\"}"), "fail"),
// hlx:1610
(Some("{\"project\":\"p\",\"persona\":\"a\"}"), Some("{\"project\":\"p\",\"persona\":\"a\",\"machine\":\"m\"}"), "fail"),
// hlx:1611
(Some("{\"harness\":\"h\"}"), Some("{\"harness\":\"h\"}"), "fail"),
// hlx:1612
(Some("{\"harness\":\"h\"}"), Some("{\"harness\":\"H\"}"), "abstain"),
// hlx:1613
(Some("{\"version\":\"1.0\"}"), Some("{\"version\":\"1.0\"}"), "fail"),
// hlx:1614
(Some("{\"version\":\"1.0\"}"), Some("{\"version\":\"1.00\"}"), "abstain"),
// hlx:1615
(Some("{\"version\":\"1.0\"}"), Some("{\"version\":\"1\"}"), "abstain"),
// hlx:1616
(Some("{\"machine\":\"m\"}"), Some("{\"machine\":\"m\"}"), "fail"),
// hlx:1617
(Some("{\"machine\":\"m\"}"), Some("{\"machine\":\"n\"}"), "abstain"),
// hlx:1618
(Some("{\"machine\":\"m\"}"), Some("{\"project\":\"m\"}"), "abstain"),
// hlx:1619
(Some("{\"project\":\"a*b\"}"), Some("{\"project\":\"axxb\"}"), "abstain"),
// hlx:1620
(Some("{\"project\":\"a*b\"}"), Some("{\"project\":\"a*b\"}"), "fail"),
// hlx:1621
(Some("{\"project\":\"pr\\u00f3\"}"), Some("{\"project\":\"pr\\u00f3\"}"), "fail"),
// hlx:1622
(Some("{\"project\":\"pr\\u00f3\"}"), Some("{\"project\":\"pr\u{f3}\"}"), "fail"),
// hlx:1623
(Some("{\"project\":\"pr\\u00f3\"}"), Some("{\"project\":\"pro\\u0301\"}"), "abstain"),
// hlx:1624
(Some("{\"project\":\"pro\\u0301\"}"), Some("{\"project\":\"pr\\u00f3\"}"), "abstain"),
// hlx:1625
(Some("{\"project\":\"p\",\"persona\":\"a\",\"harness\":\"h\",\"version\":\"v\",\"machine\":\"m\"}"),
// hlx:1626
Some("{\"project\":\"p\",\"persona\":\"a\",\"harness\":\"h\",\"version\":\"v\",\"machine\":\"m\"}"), "fail"),
// hlx:1627
(Some("{\"project\":\"p\",\"persona\":\"a\",\"harness\":\"h\",\"version\":\"v\",\"machine\":\"m\"}"),
// hlx:1628
Some("{\"project\":\"p\",\"persona\":\"a\",\"harness\":\"h\",\"version\":\"v\",\"machine\":\"x\"}"), "abstain"),
// hlx:1629
(Some("{\"project\":\"p\",\"persona\":\"a\",\"harness\":\"h\",\"version\":\"v\",\"machine\":\"m\"}"),
// hlx:1630
Some("{\"project\":\"p\",\"persona\":\"a\",\"harness\":\"h\",\"version\":\"v\"}"), "abstain"),
// hlx:1631
];
// hlx:1632
for (def, req, want) in rows {
// hlx:1633
let mut doc = d(ins, &claim).facts(facts);
// hlx:1634
if let Some(s) = def {
// hlx:1635
doc = doc.dscope(s);
// hlx:1636
}
// hlx:1637
if let Some(s) = req {
// hlx:1638
doc = doc.scope(s);
// hlx:1639
}
// hlx:1640
let j = result(&env.run("run", &doc.json()));
// hlx:1641
assert_eq!(
sf(&j, "verdict"),
want,
"definition {def:?} request {req:?}"
);
// hlx:1642
// the result reports the explicit current scope, never an inferred one
// hlx:1643
let want_scope = match req {
// hlx:1644
Some(s) => pairs(&parse_json(s).unwrap()),
// hlx:1645
None => vec![],
// hlx:1646
};
// hlx:1647
assert_eq!(
pairs(j.get("scope").unwrap()),
want_scope,
"definition {def:?} request {req:?}"
);
// hlx:1648
}
// hlx:1649
}
// hlx:1650
// ---------------------------------------------------------------- expression shape errors, even when unreachable
// hlx:1651
#[test]
// hlx:1652
fn malformed_predicates_are_rejected_even_in_unreachable_branches() {
// hlx:1653
let env = Env::new("shape");
// hlx:1654
let ins = "{\"one\":\"bool\",\"zero\":\"bool\",\"a\":\"string\",\"b\":\"string\",\"x\":\"set<string>\",\"n\":\"int\"}";
// hlx:1655
let facts = "{\"one\":true,\"zero\":false}";
// hlx:1656
let fa = fact("a");
// hlx:1657
let fb = fact("b");
// hlx:1658
let t = op2("eq", "one", "one");
// hlx:1659
let f = op2("eq", "one", "zero");
// hlx:1660
let bad: Vec<String> = vec![
// hlx:1661
format!("{{\"op\":\"xor\",\"left\":{fa},\"right\":{fb}}}"),
// hlx:1662
format!("{{\"op\":\"neq\",\"left\":{fa},\"right\":{fb}}}"),
// hlx:1663
format!("{{\"op\":\"gt\",\"left\":{{\"fact\":\"n\"}},\"right\":{{\"fact\":\"n\"}}}}"),
// hlx:1664
format!("{{\"op\":\"Eq\",\"left\":{fa},\"right\":{fb}}}"),
// hlx:1665
format!("{{\"op\":\"EQ\",\"left\":{fa},\"right\":{fb}}}"),
// hlx:1666
format!("{{\"op\":\"ALL\",\"args\":[{t}]}}"),
// hlx:1667
format!("{{\"op\":\"Not\",\"arg\":{t}}}"),
// hlx:1668
format!("{{\"op\":\"\",\"left\":{fa},\"right\":{fb}}}"),
// hlx:1669
format!("{{\"op\":\"eq \",\"left\":{fa},\"right\":{fb}}}"),
// hlx:1670
format!("{{\"op\":\"matches\",\"left\":{fa},\"right\":{fb}}}"),
// hlx:1671
format!("{{\"op\":\"exec\",\"left\":{fa},\"right\":{fb}}}"),
// hlx:1672
format!("{{\"op\":1,\"left\":{fa},\"right\":{fb}}}"),
// hlx:1673
format!("{{\"op\":null,\"left\":{fa},\"right\":{fb}}}"),
// hlx:1674
format!("{{\"op\":[\"eq\"],\"left\":{fa},\"right\":{fb}}}"),
// hlx:1675
format!("{{\"left\":{fa},\"right\":{fb}}}"),
// hlx:1676
format!("{{\"op\":\"eq\",\"left\":{fa},\"right\":{fb},\"extra\":1}}"),
// hlx:1677
format!("{{\"op\":\"eq\",\"left\":{fa},\"right\":{fb},\"args\":[]}}"),
// hlx:1678
format!("{{\"op\":\"eq\",\"left\":{fa},\"right\":{fb},\"arg\":{t}}}"),
// hlx:1679
format!("{{\"op\":\"eq\",\"left\":{fa}}}"),
// hlx:1680
format!("{{\"op\":\"eq\",\"right\":{fb}}}"),
// hlx:1681
format!("{{\"op\":\"eq\"}}"),
// hlx:1682
format!("{{\"op\":\"eq\",\"left\":{fa},\"right\":null}}"),
// hlx:1683
format!("{{\"op\":\"eq\",\"left\":{{\"fact\":\"nope\"}},\"right\":{fb}}}"),
// hlx:1684
format!("{{\"op\":\"eq\",\"left\":{fa},\"right\":{{\"fact\":\"nope\"}}}}"),
// hlx:1685
format!("{{\"op\":\"eq\",\"left\":{{\"fact\":\"A\"}},\"right\":{fb}}}"),
// hlx:1686
format!("{{\"op\":\"eq\",\"left\":{{\"fact\":\"\"}},\"right\":{fb}}}"),
// hlx:1687
format!("{{\"op\":\"eq\",\"left\":{{\"value\":\"lit\"}},\"right\":{fb}}}"),
// hlx:1688
format!("{{\"op\":\"eq\",\"left\":{{\"literal\":\"lit\"}},\"right\":{fb}}}"),
// hlx:1689
format!("{{\"op\":\"eq\",\"left\":{{\"const\":\"lit\"}},\"right\":{fb}}}"),
// hlx:1690
format!("{{\"op\":\"eq\",\"left\":\"lit\",\"right\":{fb}}}"),
// hlx:1691
format!("{{\"op\":\"eq\",\"left\":\"a\",\"right\":\"b\"}}"),
// hlx:1692
format!("{{\"op\":\"eq\",\"left\":1,\"right\":{fb}}}"),
// hlx:1693
format!("{{\"op\":\"eq\",\"left\":true,\"right\":{fb}}}"),
// hlx:1694
format!("{{\"op\":\"eq\",\"left\":[\"a\"],\"right\":{fb}}}"),
// hlx:1695
format!("{{\"op\":\"eq\",\"left\":{{}},\"right\":{fb}}}"),
// hlx:1696
format!("{{\"op\":\"eq\",\"left\":{{\"fact\":1}},\"right\":{fb}}}"),
// hlx:1697
format!("{{\"op\":\"eq\",\"left\":{{\"fact\":null}},\"right\":{fb}}}"),
// hlx:1698
format!("{{\"op\":\"eq\",\"left\":{{\"fact\":[\"a\"]}},\"right\":{fb}}}"),
// hlx:1699
format!("{{\"op\":\"eq\",\"left\":{{\"fact\":\"a\",\"extra\":1}},\"right\":{fb}}}"),
// hlx:1700
format!("{{\"op\":\"eq\",\"left\":{{\"fact\":\"a\",\"fact\":\"b\"}},\"right\":{fb}}}"),
// hlx:1701
format!("{{\"op\":\"eq\",\"left\":{{\"Fact\":\"a\"}},\"right\":{fb}}}"),
// hlx:1702
format!("{{\"op\":\"eq\",\"left\":{t},\"right\":{f}}}"),
// hlx:1703
format!("{{\"op\":\"eq\",\"left\":{fa},\"right\":{{\"fact\":\"one\"}}}}"),
// hlx:1704
format!("{{\"op\":\"lt\",\"left\":{fa},\"right\":{fb}}}"),
// hlx:1705
format!("{{\"op\":\"subset\",\"left\":{fa},\"right\":{fb}}}"),
// hlx:1706
format!("{{\"op\":\"contains\",\"left\":{fa},\"right\":{fb}}}"),
// hlx:1707
format!("{{\"op\":\"contains\",\"left\":{{\"fact\":\"x\"}},\"right\":{{\"fact\":\"x\"}}}}"),
// hlx:1708
format!("{{\"op\":\"disjoint\",\"left\":{{\"fact\":\"x\"}},\"right\":{fb}}}"),
// hlx:1709
"{\"op\":\"all\",\"args\":[]}".to_string(),
// hlx:1710
"{\"op\":\"any\",\"args\":[]}".to_string(),
// hlx:1711
"{\"op\":\"all\"}".to_string(),
// hlx:1712
"{\"op\":\"any\"}".to_string(),
// hlx:1713
"{\"op\":\"all\",\"args\":null}".to_string(),
// hlx:1714
"{\"op\":\"all\",\"args\":\"x\"}".to_string(),
// hlx:1715
format!("{{\"op\":\"all\",\"args\":{t}}}"),
// hlx:1716
"{\"op\":\"any\",\"args\":[1]}".to_string(),
// hlx:1717
"{\"op\":\"any\",\"args\":[null]}".to_string(),
// hlx:1718
"{\"op\":\"any\",\"args\":[\"eq\"]}".to_string(),
// hlx:1719
"{\"op\":\"any\",\"args\":[[]]}".to_string(),
// hlx:1720
format!("{{\"op\":\"all\",\"arg\":{t}}}"),
// hlx:1721
format!("{{\"op\":\"all\",\"args\":[{t}],\"arg\":{t}}}"),
// hlx:1722
format!("{{\"op\":\"any\",\"args\":[{t}],\"extra\":true}}"),
// hlx:1723
format!("{{\"op\":\"all\",\"args\":[{t}],\"left\":{fa}}}"),
// hlx:1724
format!("{{\"op\":\"all\",\"args\":[{t},{{\"op\":\"eq\"}}]}}"),
// hlx:1725
"{\"op\":\"not\"}".to_string(),
// hlx:1726
"{\"op\":\"not\",\"arg\":null}".to_string(),
// hlx:1727
"{\"op\":\"not\",\"arg\":1}".to_string(),
// hlx:1728
"{\"op\":\"not\",\"arg\":\"x\"}".to_string(),
// hlx:1729
"{\"op\":\"not\",\"arg\":{}}".to_string(),
// hlx:1730
format!("{{\"op\":\"not\",\"arg\":[{t}]}}"),
// hlx:1731
format!("{{\"op\":\"not\",\"args\":[{t}]}}"),
// hlx:1732
format!("{{\"op\":\"not\",\"arg\":{t},\"args\":[{t}]}}"),
// hlx:1733
format!("{{\"op\":\"not\",\"arg\":{t},\"extra\":1}}"),
// hlx:1734
format!("{{\"op\":\"not\",\"arg\":{t},\"arg\":{f}}}"),
// hlx:1735
format!("{{\"op\":\"not\",\"left\":{t}}}"),
// hlx:1736
format!("{{\"op\":\"all\",\"args\":[{t}],\"args\":[{f}]}}"),
// hlx:1737
"{}".to_string(),
// hlx:1738
"[]".to_string(),
// hlx:1739
"null".to_string(),
// hlx:1740
"\"eq\"".to_string(),
// hlx:1741
"1".to_string(),
// hlx:1742
"true".to_string(),
// hlx:1743
"{\"fact\":\"one\"}".to_string(),
// hlx:1744
format!("[{t}]"),
// hlx:1745
];
// hlx:1746
for b in &bad {
// hlx:1747
let direct = d(ins, b).facts(facts).json();
// hlx:1748
all_err_s(&env, &direct, &format!("direct {b}"));
// hlx:1749
// behind a short circuit that would never read it
// hlx:1750
for (wrapped, what) in [
// hlx:1751
(any_of(&[t.clone(), b.clone()]), "any[T,bad]"),
// hlx:1752
(all_of(&[f.clone(), b.clone()]), "all[F,bad]"),
// hlx:1753
(not_of(b), "not[bad]"),
// hlx:1754
(
any_of(&[t.clone(), all_of(&[f.clone(), b.clone()])]),
"any[T,all[F,bad]]",
),
// hlx:1755
] {
// hlx:1756
let doc = d(ins, &wrapped).facts(facts).json();
// hlx:1757
all_err_s(&env, &doc, &format!("{what} {b}"));
// hlx:1758
}
// hlx:1759
}
// hlx:1760
// the good forms of the same shapes still work
// hlx:1761
for claim in [
any_of(&[t.clone(), f.clone()]),
all_of(&[t.clone()]),
not_of(&f),
] {
// hlx:1762
assert_eq!(
verdict(&env.run("run", &d(ins, &claim).facts(facts).json())),
"pass"
);
// hlx:1763
}
// hlx:1764
// a bad reference or type in a branch the evaluator would skip is still an error
// hlx:1765
for claim in [
// hlx:1766
any_of(&[t.clone(), op2("eq", "a", "one")]),
// hlx:1767
any_of(&[t.clone(), op2("lt", "a", "b")]),
// hlx:1768
any_of(&[t.clone(), op2("eq", "ghost", "a")]),
// hlx:1769
all_of(&[f.clone(), op2("subset", "a", "b")]),
// hlx:1770
all_of(&[f.clone(), op2("contains", "x", "x")]),
// hlx:1771
] {
// hlx:1772
all_err_s(&env, &d(ins, &claim).facts(facts).json(), &claim);
// hlx:1773
}
// hlx:1774
}
// hlx:1775
// ---------------------------------------------------------------- wire format
// hlx:1776
#[test]
// hlx:1777
fn invalid_json_is_a_structured_error() {
// hlx:1778
let env = Env::new("badjson");
// hlx:1779
let inner = &BASE[1..BASE.len() - 1];
// hlx:1780
let mut docs: Vec<String> = vec![
// hlx:1781
"".into(),
// hlx:1782
" ".into(),
// hlx:1783
"\n".into(),
// hlx:1784
"{".into(),
// hlx:1785
"}".into(),
// hlx:1786
"{{}}".into(),
// hlx:1787
"{\"check\"".into(),
// hlx:1788
"{\"check\":".into(),
// hlx:1789
"{\"check\":}".into(),
// hlx:1790
"{\"check\":{}".into(),
// hlx:1791
"{\"check\" {}}".into(),
// hlx:1792
"{check:{}}".into(),
// hlx:1793
"{'check':{}}".into(),
// hlx:1794
"{\"check\":{},}".into(),
// hlx:1795
"{,\"check\":{}}".into(),
// hlx:1796
"{\"check\":{}} x".into(),
// hlx:1797
"{\"check\":{}}{}".into(),
// hlx:1798
"x".into(),
// hlx:1799
"nul".into(),
// hlx:1800
"tru".into(),
// hlx:1801
"NaN".into(),
// hlx:1802
"undefined".into(),
// hlx:1803
"{\"check\":NaN}".into(),
// hlx:1804
"{\"check\":Infinity}".into(),
// hlx:1805
"{\"check\":undefined}".into(),
// hlx:1806
"{\"check\":[1,]}".into(),
// hlx:1807
"{\"check\":[,1]}".into(),
// hlx:1808
"{\"check\":[1 2]}".into(),
// hlx:1809
"{\"check\":\"abc}".into(),
// hlx:1810
"{\"check\":\"a\\qb\"}".into(),
// hlx:1811
"{\"check\":\"a\\u12\"}".into(),
// hlx:1812
"{\"check\":\"a\\u12G4\"}".into(),
// hlx:1813
"{\"check\":\"a\\x41\"}".into(),
// hlx:1814
"{\"check\":\"a\\'b\"}".into(),
// hlx:1815
"{\"check\":\"a\\".into(),
// hlx:1816
format!("{BASE} x"),
// hlx:1817
format!("{BASE}{BASE}"),
// hlx:1818
format!("{BASE},"),
// hlx:1819
format!("{BASE}}}"),
// hlx:1820
format!("{BASE}\n{BASE}"),
// hlx:1821
format!("{BASE} // comment"),
// hlx:1822
format!("/* c */ {BASE}"),
// hlx:1823
format!("# c\n{BASE}"),
// hlx:1824
format!("[{BASE}]"),
// hlx:1825
BASE[..BASE.len() - 1].to_string(),
// hlx:1826
BASE[..BASE.len() / 2].to_string(),
// hlx:1827
BASE.replacen(":", " ", 1),
// hlx:1828
BASE.replacen("{\"schema\"", "{schema", 1),
// hlx:1829
BASE.replacen("\"id\":", "\"id\"=", 1),
// hlx:1830
BASE.replacen(
"\"id\":\"artifact-membership\"",
"\"id\":\"artifact-membership\",",
1,
),
// hlx:1831
BASE.replacen("\"revision\":1,", "\"revision\":1,,", 1),
// hlx:1832
BASE.replacen(
"\"project\":\"release-lab\"",
"\"project\":'release-lab'",
1,
),
// hlx:1833
BASE.replacen("true", "True", 1),
// hlx:1834
BASE.replacen("true", "tru", 1),
// hlx:1835
BASE.replacen("true", "TRUE", 1),
// hlx:1836
format!("{{{inner},}}"),
// hlx:1837
format!("{{\"a\":1 {inner}}}"),
// hlx:1838
];
// hlx:1839
docs.push(format!("\u{feff}{BASE}"));
// hlx:1840
docs.push(format!("\u{0}{BASE}"));
// hlx:1841
docs.push(format!("{BASE}\u{0}"));
// hlx:1842
docs.push(format!("\u{c}{BASE}"));
// hlx:1843
docs.push(format!("{BASE}\u{b}"));
// hlx:1844
for doc in docs {
// hlx:1845
all_err_s(&env, &doc, "invalid json");
// hlx:1846
}
// hlx:1847
// surrounding JSON whitespace is fine
// hlx:1848
valid(&env, &format!(" \n\t\r{BASE}\r\n\t "), "whitespace");
// hlx:1849
valid(
&env,
&BASE.replace(",", ",\n ").replace(":", " : "),
"pretty printed",
);
// hlx:1850
}
// hlx:1851
#[test]
// hlx:1852
fn raw_control_characters_and_bad_utf8_are_rejected_but_escapes_are_fine() {
// hlx:1853
let env = Env::new("ctrl");
// hlx:1854
for c in [
"\n", "\t", "\r", "\u{1}", "\u{8}", "\u{b}", "\u{c}", "\u{1f}", "\u{0}",
] {
// hlx:1855
all_err_s(
&env,
&BASE.replacen("release.bin", &format!("rel{c}ease"), 1),
&format!("control {c:?} in a value"),
);
// hlx:1856
all_err_s(
&env,
&BASE.replacen("\"actual\":[", &format!("\"ac{c}tual\":["), 1),
&format!("control {c:?} in a key"),
);
// hlx:1857
all_err_s(
&env,
&BASE.replacen("artifact-membership", &format!("{c}"), 1),
&format!("control {c:?} as id"),
);
// hlx:1858
}
// hlx:1859
for esc in [
"\\n", "\\t", "\\r", "\\b", "\\f", "\\u0001", "\\u001f", "\\u0000", "\\\"", "\\\\", "\\/",
] {
// hlx:1860
valid(
&env,
&set_doc("subset", &format!("[\"a{esc}b\"]"), "[]"),
esc,
);
// hlx:1861
}
// hlx:1862
// 0x7f and non-ASCII are not control characters of the JSON grammar
// hlx:1863
valid(&env, &set_doc("subset", "[\"a\u{7f}b\"]", "[]"), "DEL");
// hlx:1864
valid(
&env,
&set_doc("subset", "[\"\u{85}\u{2028}\u{2029}\"]", "[]"),
"unicode separators",
);
// hlx:1865
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\":\"";
// hlx:1866
let suffix = b"\"}}";
// hlx:1867
let mk = |mid: &[u8]| {
// hlx:1868
let mut v = prefix.to_vec();
// hlx:1869
v.extend_from_slice(mid);
// hlx:1870
v.extend_from_slice(suffix);
// hlx:1871
v
// hlx:1872
};
// hlx:1873
assert_eq!(
verdict(&env.run_bytes("run", &mk("caf\u{e9} \u{1F600}".as_bytes()))),
"pass"
);
// hlx:1874
for (name, mid) in [
// hlx:1875
("0xff", vec![0xffu8]),
// hlx:1876
("0xfe", vec![0xfe]),
// hlx:1877
("lone continuation", vec![0x80]),
// hlx:1878
("truncated 2-byte", vec![b'a', 0xc3]),
// hlx:1879
("overlong slash", vec![0xc0, 0xaf]),
// hlx:1880
("overlong nul", vec![0xc0, 0x80]),
// hlx:1881
("truncated 3-byte", vec![0xe2, 0x82]),
// hlx:1882
("encoded surrogate", vec![0xed, 0xa0, 0x80]),
// hlx:1883
("encoded low surrogate", vec![0xed, 0xbf, 0xbf]),
// hlx:1884
("above U+10FFFF", vec![0xf4, 0x90, 0x80, 0x80]),
// hlx:1885
("5-byte form", vec![0xf8, 0x88, 0x80, 0x80, 0x80]),
// hlx:1886
("truncated 4-byte", vec![0xf0, 0x9f, 0x98]),
// hlx:1887
] {
// hlx:1888
all_err(&env, &mk(&mid), name);
// hlx:1889
}
// hlx:1890
// invalid UTF-8 outside strings too
// hlx:1891
let mut bad = BASE.as_bytes().to_vec();
// hlx:1892
bad.push(0xff);
// hlx:1893
all_err(&env, &bad, "trailing 0xff");
// hlx:1894
}
// hlx:1895
#[test]
// hlx:1896
fn duplicate_keys_are_rejected_everywhere_including_escaped_spellings() {
// hlx:1897
let env = Env::new("dupkeys");
// hlx:1898
// (anchor that occurs exactly once in BASE, replacement that adds a duplicate)
// hlx:1899
let rows: Vec<(&str, &str)> = vec![
// hlx:1900
("\"id\":\"artifact-membership\"", "\"id\":\"artifact-membership\",\"id\":\"artifact-membership\""),
// hlx:1901
("\"id\":\"artifact-membership\"", "\"id\":\"artifact-membership\",\"id\":\"other\""),
// hlx:1902
("\"id\":\"artifact-membership\"", "\"id\":\"artifact-membership\",\"\\u0069d\":\"artifact-membership\""),
// hlx:1903
("\"id\":\"artifact-membership\"", "\"id\":\"artifact-membership\",\"i\\u0064\":\"x\""),
// hlx:1904
("\"id\":\"artifact-membership\"", "\"id\":\"artifact-membership\",\"\\u0049d\":\"x\",\"i\\u0064\":\"y\""),
// hlx:1905
("\"revision\":1", "\"revision\":1,\"revision\":1"),
// hlx:1906
("\"revision\":1", "\"revision\":1,\"\\u0072evision\":1"),
// hlx:1907
("\"schema\":\"instinct.check/v1\"", "\"schema\":\"instinct.check/v1\",\"sch\\u0065ma\":\"instinct.check/v1\""),
// hlx:1908
("\"inputs\":{", "\"inputs\":{\"actual\":\"set<string>\","),
// hlx:1909
("\"inputs\":{", "\"inputs\":{\"a\\u0063tual\":\"set<string>\","),
// hlx:1910
("\"inputs\":{\"actual\":\"set<string>\"", "\"inputs\":{\"actual\":\"set<string>\",\"\\u0061ctual\":\"string\""),
// hlx:1911
("\"inputs\":{\"actual\":\"set<string>\"", "\"inputs\":{\"actual\":\"set<string>\",\"a\\u0063\\u0074ual\":\"set<string>\""),
// hlx:1912
("\"allowed\":\"set<string>\"}", "\"allowed\":\"set<string>\",\"allowed\":\"set<string>\"}"),
// hlx:1913
("\"claim\":{\"op\":\"subset\"", "\"claim\":{\"op\":\"subset\",\"op\":\"subset\""),
// hlx:1914
("\"claim\":{\"op\":\"subset\"", "\"claim\":{\"op\":\"subset\",\"o\\u0070\":\"subset\""),
// hlx:1915
("\"claim\":{\"op\":\"subset\"", "\"claim\":{\"op\":\"subset\",\"\\u006fp\":\"disjoint\""),
// hlx:1916
("\"left\":{\"fact\":\"actual\"}", "\"left\":{\"fact\":\"actual\",\"fact\":\"actual\"}"),
// hlx:1917
("\"left\":{\"fact\":\"actual\"}", "\"left\":{\"fact\":\"actual\",\"f\\u0061ct\":\"actual\"}"),
// hlx:1918
("\"left\":{\"fact\":\"actual\"}", "\"left\":{\"fact\":\"actual\"},\"left\":{\"fact\":\"actual\"}"),
// hlx:1919
("\"left\":{\"fact\":\"actual\"}", "\"left\":{\"fact\":\"actual\"},\"l\\u0065ft\":{\"fact\":\"actual\"}"),
// hlx:1920
("\"right\":{\"fact\":\"allowed\"}", "\"right\":{\"fact\":\"allowed\"},\"right\":{\"fact\":\"allowed\"}"),
// hlx:1921
("\"right\":{\"fact\":\"allowed\"}", "\"right\":{\"fact\":\"allowed\"},\"r\\u0069ght\":{\"fact\":\"allowed\"}"),
// hlx:1922
("\"required_conditions\":[", "\"required_conditions\":[\"complete-inventory\"],\"required_conditions\":["),
// hlx:1923
("\"required_conditions\":[", "\"required_conditions\":[\"complete-inventory\"],\"required_cond\\u0069tions\":["),
// hlx:1924
("\"scope\":{\"project\":\"release-lab\"}},\"facts\"", "\"scope\":{\"project\":\"release-lab\"},\"scope\":{\"project\":\"release-lab\"}},\"facts\""),
// hlx:1925
("\"scope\":{\"project\":\"release-lab\"}},\"facts\"", "\"scope\":{\"project\":\"release-lab\",\"project\":\"release-lab\"}},\"facts\""),
// hlx:1926
("\"scope\":{\"project\":\"release-lab\"}},\"facts\"", "\"scope\":{\"project\":\"release-lab\",\"\\u0070roject\":\"other\"}},\"facts\""),
// hlx:1927
("\"scope\":{\"project\":\"release-lab\"}},\"facts\"", "\"scope\":{\"project\":\"release-lab\"},\"sc\\u006fpe\":{}},\"facts\""),
// hlx:1928
("\"facts\":{", "\"facts\":{\"actual\":[],"),
// hlx:1929
("\"facts\":{", "\"facts\":{\"actual\":[\"release.bin\",\"scratch.env\"],\"\\u0061ctual\":[],"),
// hlx:1930
("\"facts\":{\"actual\":[\"release.bin\",\"scratch.env\"]", "\"facts\":{\"actual\":[\"release.bin\",\"scratch.env\"],\"actual\":[\"release.bin\",\"scratch.env\"]"),
// hlx:1931
("\"allowed\":[\"release.bin\"]}", "\"allowed\":[\"release.bin\"],\"allowed\":[\"release.bin\"]}"),
// hlx:1932
("\"allowed\":[\"release.bin\"]}", "\"allowed\":[\"release.bin\"],\"a\\u006cl\\u006fwed\":[]}"),
// hlx:1933
("\"allowed\":[\"release.bin\"]}", "\"allowed\":[\"release.bin\"],\"\\u0041llowed\":[],\"allowed\":[]}"),
// hlx:1934
("\"allowed\":[\"release.bin\"]},\"conditions\"", "\"allowed\":[\"release.bin\"]},\"facts\":{},\"conditions\""),
// hlx:1935
("\"allowed\":[\"release.bin\"]},\"conditions\"", "\"allowed\":[\"release.bin\"]},\"f\\u0061cts\":{},\"conditions\""),
// hlx:1936
("\"allowed\":[\"release.bin\"]},\"conditions\"", "\"allowed\":[\"release.bin\"]},\"\\u0066acts\":{\"actual\":[],\"allowed\":[]},\"conditions\""),
// hlx:1937
("\"conditions\":{", "\"conditions\":{\"complete-inventory\":true,"),
// hlx:1938
("\"conditions\":{", "\"conditions\":{\"complete\\u002dinventory\":true,"),
// hlx:1939
("\"conditions\":{", "\"conditions\":{\"complete\\u002Dinventory\":false,"),
// hlx:1940
("\"explicit-policy\":true}", "\"explicit-policy\":true,\"explicit-policy\":true}"),
// hlx:1941
("\"explicit-policy\":true},\"scope\":{\"project\":\"release-lab\"}}", "\"explicit-policy\":true},\"conditions\":{},\"scope\":{\"project\":\"release-lab\"}}"),
// hlx:1942
("\"explicit-policy\":true},\"scope\":{\"project\":\"release-lab\"}}", "\"explicit-policy\":true},\"cond\\u0069tions\":{},\"scope\":{\"project\":\"release-lab\"}}"),
// hlx:1943
("\"explicit-policy\":true},\"scope\":{\"project\":\"release-lab\"}}", "\"explicit-policy\":true},\"scope\":{\"project\":\"release-lab\"},\"scope\":{\"project\":\"release-lab\"}}"),
// hlx:1944
("\"explicit-policy\":true},\"scope\":{\"project\":\"release-lab\"}}", "\"explicit-policy\":true},\"scope\":{\"project\":\"release-lab\",\"project\":\"release-lab\"}}"),
// hlx:1945
("\"explicit-policy\":true},\"scope\":{\"project\":\"release-lab\"}}", "\"explicit-policy\":true},\"scope\":{\"project\":\"release-lab\"},\"\\u0073cope\":{}}"),
// hlx:1946
("\"explicit-policy\":true},\"scope\":{\"project\":\"release-lab\"}}", "\"explicit-policy\":true},\"scope\":{\"pro\\u006aect\":\"x\",\"project\":\"release-lab\"}}"),
// hlx:1947
("{\"check\":{", "{\"check\":{},\"check\":{"),
// hlx:1948
("{\"check\":{", "{\"ch\\u0065ck\":{},\"check\":{"),
// hlx:1949
("{\"check\":{", "{\"\\u0063heck\":{\"x\":1},\"check\":{"),
// hlx:1950
("{\"check\":{", "{\"che\\u0063k\":{\"schema\":\"instinct.check/v1\"},\"check\":{"),
// hlx:1951
];
// hlx:1952
for (anchor, repl) in rows {
// hlx:1953
let doc = mutate(anchor, repl);
// hlx:1954
all_err_s(&env, &doc, "duplicate key");
// hlx:1955
}
// hlx:1956
// every spelling of a duplicated top-level key, same value or not
// hlx:1957
for (k, v) in [("facts", "{}"), ("conditions", "{}"), ("scope", "{}")] {
// hlx:1958
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]),
] {
// hlx:1959
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}}}");
// hlx:1960
all_err_s(&env, &doc, &format!("top-level {k} as {esc}"));
// hlx:1961
}
// hlx:1962
}
// hlx:1963
// Unicode: the escaped and literal spellings of one key collide, in any object
// hlx:1964
for (a, b) in [
// hlx:1965
("\\u00e9", "\u{e9}"),
// hlx:1966
("\\u00E9", "\\u00e9"),
// hlx:1967
("\\ud83d\\ude00", "\u{1F600}"),
// hlx:1968
("\\ud83d\\ude00", "\\uD83D\\uDE00"),
// hlx:1969
("a\\/b", "a/b"),
// hlx:1970
("\\u0041", "A"),
// hlx:1971
("\\u00e9\\u0301", "\u{e9}\\u0301"),
// hlx:1972
("\\u0000", "\\u0000"),
// hlx:1973
] {
// hlx:1974
let doc = d(
&format!("{{\"{a}\":\"string\",\"{b}\":\"string\"}}"),
&op2("eq", "x", "x"),
)
.json();
// hlx:1975
all_err_s(&env, &doc, &format!("inputs {a} / {b}"));
// hlx:1976
let doc = d("{\"s\":\"string\"}", &op2("eq", "s", "s"))
.facts(&format!("{{\"s\":\"v\",\"{a}\":\"v\",\"{b}\":\"v\"}}"))
.json();
// hlx:1977
all_err_s(&env, &doc, &format!("facts {a} / {b}"));
// hlx:1978
let doc = d("{\"s\":\"string\"}", &op2("eq", "s", "s"))
.dscope(&format!("{{\"{a}\":\"v\",\"{b}\":\"v\"}}"))
.json();
// hlx:1979
all_err_s(&env, &doc, &format!("scope {a} / {b}"));
// hlx:1980
}
// hlx:1981
// keys that differ only by case or by an extra character are different keys
// hlx:1982
let two = d(
"{\"e\":\"string\",\"E\":\"string\",\"ee\":\"string\",\"e\\u0045\":\"string\"}",
&op2("eq", "e", "E"),
)
// hlx:1983
.facts("{\"e\":\"3\",\"E\":\"3\",\"ee\":\"1\"}")
// hlx:1984
.json();
// hlx:1985
assert_eq!(verdict(&env.run("run", &two)), "pass");
// hlx:1986
}
// hlx:1987
#[test]
// hlx:1988
fn malformed_numbers_anywhere_are_errors() {
// hlx:1989
let env = Env::new("numbers");
// hlx:1990
for n in [
// hlx:1991
"01",
"00",
"-01",
"1.",
".5",
"-.5",
"1.e3",
"1e",
"1e+",
"1e-",
"+1",
"-",
"--1",
"0x1",
"1_0",
"1,0",
"Infinity",
"-Infinity",
"NaN",
// hlx:1992
"1.0.0",
"1e1e1",
"٣",
"1 1",
"0123",
"1E",
"- 1",
"1d",
"0b1",
"0o7",
"1f",
"1L",
"0.0.0",
"1e0.5",
// hlx:1993
] {
// hlx:1994
for place in [
// hlx:1995
BASE.replacen("\"revision\":1", &format!("\"revision\":{n}"), 1),
// hlx:1996
d("{\"a\":\"bool\"}", &op2("eq", "a", "a"))
.facts(&format!("{{\"a\":{n}}}"))
.json(),
// hlx:1997
d("{\"a\":\"bool\"}", &op2("eq", "a", "a"))
.facts(&format!("{{\"a\":true,\"zz\":[{n}]}}"))
.json(),
// hlx:1998
format!("{{\"check\":{{}},\"x\":{n}}}"),
// hlx:1999
d("{\"a\":\"bool\"}", &op2("eq", "a", "a")).json().replacen(
"\"check\":{",
&format!("\"x\":{n},\"check\":{{"),
1,
),
// hlx:2000
] {
// hlx:2001
all_err_s(&env, &place, &format!("number {n}"));
// hlx:2002
}
// hlx:2003
}
// hlx:2004
for n in [
"1e999999",
"1e-999999",
"123456789012345678901234567890e5",
"-1e400",
"1E+400",
"9".repeat(5000).as_str(),
] {
// hlx:2005
all_err_s(
&env,
&BASE.replacen("\"revision\":1", &format!("\"revision\":{n}"), 1),
n,
);
// hlx:2006
}
// hlx:2007
}
// hlx:2008
#[test]
// hlx:2009
fn json_nesting_beyond_64_is_an_error_and_deep_input_does_not_crash() {
// hlx:2010
let env = Env::new("nesting");
// hlx:2011
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\":";
// hlx:2012
for n in [65usize, 70, 100, 1000, 100_000, 500_000] {
// hlx:2013
for (open, close) in [("[", "]"), ("{\"k\":", "}")] {
// hlx:2014
let doc = format!("{head}{}true{}}}}}", open.repeat(n), close.repeat(n));
// hlx:2015
if doc.len() > 1_048_576 {
// hlx:2016
continue;
// hlx:2017
}
// hlx:2018
for sub in ["run", "validate"] {
// hlx:2019
let o = env.run(sub, &doc);
// hlx:2020
assert!(
o.code.is_some(),
"deep input killed the process by signal (nesting {n} {open}): stderr={}",
trunc(&String::from_utf8_lossy(&o.err))
);
// hlx:2021
err(&o, &format!("{sub} nesting {n} {open}"));
// hlx:2022
}
// hlx:2023
}
// hlx:2024
}
// hlx:2025
// nesting inside the claim is bounded the same way (and the claim depth limit)
// hlx:2026
let mut claim = op2("eq", "a", "a");
// hlx:2027
for _ in 0..70 {
// hlx:2028
claim = not_of(&claim);
// hlx:2029
}
// hlx:2030
all_err_s(
&env,
&d("{\"a\":\"bool\"}", &claim).facts("{\"a\":true}").json(),
"70 nested not",
);
// hlx:2031
// nesting inside inputs
// hlx:2032
let nested = format!("{}{}", "[".repeat(80), "]".repeat(80));
// hlx:2033
all_err_s(
&env,
&d(&format!("{{\"a\":{nested}}}"), &op2("eq", "a", "a")).json(),
"deep inputs",
);
// hlx:2034
}
// hlx:2035
#[test]
// hlx:2036
fn input_is_limited_to_one_mebibyte_from_stdin_and_from_files() {
// hlx:2037
let env = Env::new("size");
// hlx:2038
let limit = 1_048_576usize;
// hlx:2039
let mut exact = BASE.as_bytes().to_vec();
// hlx:2040
exact.resize(limit, b' ');
// hlx:2041
assert_eq!(exact.len(), limit);
// hlx:2042
let mut over = exact.clone();
// hlx:2043
over.push(b' ');
// hlx:2044
let mut way_over = BASE.as_bytes().to_vec();
// hlx:2045
way_over.resize(3 * limit, b' ');
// hlx:2046
let ex_path = env.put("exact.json", &exact);
// hlx:2047
let over_path = env.put("over.json", &over);
// hlx:2048
let way_path = env.put("way.json", &way_over);
// hlx:2049
for sub in ["validate", "run", "explain"] {
// hlx:2050
let o = env.run_bytes(sub, &exact);
// hlx:2051
assert_eq!(o.code, Some(0), "{sub} exactly 1 MiB: {}", trunc(&o.text()));
// hlx:2052
let f = env.exec(&["check", sub, "--input", ex_path.to_str().unwrap()], b"");
// hlx:2053
assert_eq!(f.out, o.out, "{sub} file == stdin at the limit");
// hlx:2054
err(
&env.run_bytes(sub, &over),
&format!("{sub} stdin 1 MiB + 1"),
);
// hlx:2055
err(
&env.exec(&["check", sub, "--input", over_path.to_str().unwrap()], b""),
&format!("{sub} file 1 MiB + 1"),
);
// hlx:2056
err(
&env.run_bytes(sub, &way_over),
&format!("{sub} stdin 3 MiB"),
);
// hlx:2057
err(
&env.exec(&["check", sub, "--input", way_path.to_str().unwrap()], b""),
&format!("{sub} file 3 MiB"),
);
// hlx:2058
}
// hlx:2059
// oversized garbage is an error, not a hang or crash
// hlx:2060
let junk = vec![b'x'; 8 * limit];
// hlx:2061
err(&env.run_bytes("run", &junk), "8 MiB of junk");
// hlx:2062
// an over-limit document whose first MiB is valid is still an error
// hlx:2063
let mut tail = BASE.as_bytes().to_vec();
// hlx:2064
tail.resize(limit, b' ');
// hlx:2065
tail.extend_from_slice(b"{}");
// hlx:2066
err(
&env.run_bytes("run", &tail),
"valid prefix, junk after the limit",
);
// hlx:2067
}
// hlx:2068
// ---------------------------------------------------------------- structural, fuel and output limits
// hlx:2069
#[test]
// hlx:2070
fn claim_depth_and_node_limits_are_enforced_before_evaluation() {
// hlx:2071
let env = Env::new("claimlimits");
// hlx:2072
let ins = "{\"a\":\"bool\"}";
// hlx:2073
let leaf = op2("eq", "a", "a");
// hlx:2074
// within limits
// hlx:2075
for k in [0usize, 1, 10, 20, 30] {
// hlx:2076
let mut claim = leaf.clone();
// hlx:2077
for _ in 0..k {
// hlx:2078
claim = not_of(&claim);
// hlx:2079
}
// hlx:2080
let want = if k % 2 == 0 { "pass" } else { "fail" };
// hlx:2081
assert_eq!(
verdict(&env.run("run", &d(ins, &claim).facts("{\"a\":true}").json())),
want,
"not^{k}"
);
// hlx:2082
}
// hlx:2083
let mut nest = leaf.clone();
// hlx:2084
for _ in 0..20 {
// hlx:2085
nest = all_of(&[nest]);
// hlx:2086
}
// hlx:2087
assert_eq!(
verdict(&env.run("run", &d(ins, &nest).facts("{\"a\":true}").json())),
"pass"
);
// hlx:2088
// too deep
// hlx:2089
for k in [40usize, 50, 60] {
// hlx:2090
let mut claim = leaf.clone();
// hlx:2091
for _ in 0..k {
// hlx:2092
claim = not_of(&claim);
// hlx:2093
}
// hlx:2094
all_err_s(
&env,
&d(ins, &claim).facts("{\"a\":true}").json(),
&format!("not^{k}"),
);
// hlx:2095
let mut claim = leaf.clone();
// hlx:2096
for _ in 0..k {
// hlx:2097
claim = any_of(&[claim]);
// hlx:2098
}
// hlx:2099
all_err_s(
&env,
&d(ins, &claim).facts("{\"a\":true}").json(),
&format!("any^{k}"),
);
// hlx:2100
}
// hlx:2101
// many nodes, shallow
// hlx:2102
let leaves = |n: usize| (0..n).map(|_| leaf.clone()).collect::<Vec<_>>();
// hlx:2103
assert_eq!(
verdict(&env.run(
"run",
&d(ins, &all_of(&leaves(1000))).facts("{\"a\":true}").json()
)),
"pass"
);
// hlx:2104
assert_eq!(
verdict(&env.run(
"run",
&d(ins, &any_of(&leaves(1000))).facts("{\"a\":true}").json()
)),
"pass"
);
// hlx:2105
for n in [4200usize, 5000, 9000] {
// hlx:2106
all_err_s(
&env,
&d(ins, &all_of(&leaves(n))).facts("{\"a\":true}").json(),
&format!("all of {n} leaves"),
);
// hlx:2107
all_err_s(
&env,
&d(ins, &any_of(&leaves(n))).facts("{\"a\":true}").json(),
&format!("any of {n} leaves"),
);
// hlx:2108
}
// hlx:2109
let groups: Vec<String> = (0..100).map(|_| all_of(&leaves(50))).collect();
// hlx:2110
all_err_s(
&env,
&d(ins, &all_of(&groups)).facts("{\"a\":true}").json(),
"100 groups of 50",
);
// hlx:2111
}
// hlx:2112
#[test]
// hlx:2113
fn oversized_fact_sets_are_bounded_not_passed() {
// hlx:2114
let env = Env::new("factlimits");
// hlx:2115
// within the limit
// hlx:2116
let big = many(4000, "m");
// hlx:2117
assert_eq!(
verdict(&env.run("run", &set_doc("subset", &big, &big))),
"pass"
);
// hlx:2118
valid(&env, &set_doc("subset", &big, &big), "4000 members");
// hlx:2119
// beyond 10000 members in aggregate: bounded outcome, never a pass or a crash
// hlx:2120
for (l, r) in [
(many(10_500, "m"), "[]".to_string()),
(many(6000, "l"), many(6000, "r")),
(many(20_000, "m"), many(20_000, "m")),
] {
// hlx:2121
let doc = set_doc("subset", &l, &r);
// hlx:2122
for sub in ["run", "validate", "explain"] {
// hlx:2123
let o = env.run_bytes(sub, doc.as_bytes());
// hlx:2124
match o.code {
// hlx:2125
Some(2) => err(&o, &format!("{sub} oversized facts")),
// hlx:2126
Some(0) => {
// hlx:2127
let j = obj(&o);
// hlx:2128
if sub == "validate" {
// hlx:2129
panic!(
"validation accepted facts over the aggregate limit: {}",
trunc(&o.text())
);
// hlx:2130
}
// hlx:2131
assert_eq!(
sf(&j, "verdict"),
"abstain",
"{sub} oversized facts must abstain, got {}",
trunc(&o.text())
);
// hlx:2132
assert!(o.out.len() <= 65_537);
// hlx:2133
}
// hlx:2134
other => panic!("{sub} oversized facts: unexpected exit {other:?}"),
// hlx:2135
}
// hlx:2136
}
// hlx:2137
}
// hlx:2138
// beyond 10000 entries: many declared scalar facts
// hlx:2139
let n = 10_600;
// hlx:2140
let inputs = format!(
"{{{}}}",
(0..n)
.map(|i| format!("\"f{i}\":\"bool\""))
.collect::<Vec<_>>()
.join(",")
);
// hlx:2141
let facts = format!(
"{{{}}}",
(0..n)
.map(|i| format!("\"f{i}\":true"))
.collect::<Vec<_>>()
.join(",")
);
// hlx:2142
let doc = d(&inputs, &op2("eq", "f0", "f1")).facts(&facts).json();
// hlx:2143
for sub in ["run", "explain"] {
// hlx:2144
let o = env.run(sub, &doc);
// hlx:2145
match o.code {
// hlx:2146
Some(2) => err(&o, "entries over limit"),
// hlx:2147
Some(0) => assert_eq!(
sf(&obj(&o), "verdict"),
"abstain",
"entries over limit must not pass"
),
// hlx:2148
other => panic!("unexpected exit {other:?}"),
// hlx:2149
}
// hlx:2150
}
// hlx:2151
}
// hlx:2152
#[test]
// hlx:2153
fn fuel_exhaustion_abstains_and_never_reports_partial_evaluation_as_pass() {
// hlx:2154
let env = Env::new("fuel");
// hlx:2155
let n = 4900;
// hlx:2156
let left = many(n, "m");
// hlx:2157
let mut rev: Vec<String> = (0..n).map(|i| format!("\"m{i:05}\"")).collect();
// hlx:2158
rev.reverse();
// hlx:2159
let right = format!("[{}]", rev.join(","));
// hlx:2160
let sub = op2("subset", "actual", "allowed");
// hlx:2161
let facts = format!("{{\"actual\":{left},\"allowed\":{right}}}");
// hlx:2162
// a single pass over this input is cheap and true
// hlx:2163
assert_eq!(
verdict(&env.run("run", &d(SET_IN, &sub).facts(&facts).json())),
"pass"
);
// hlx:2164
// thirty full scans cost at least 30 * 4900 charged operations: over the 100000 budget
// hlx:2165
let heavy = all_of(&(0..30).map(|_| sub.clone()).collect::<Vec<_>>());
// hlx:2166
for s in ["run", "explain"] {
// hlx:2167
let o = env.run(s, &d(SET_IN, &heavy).facts(&facts).json());
// hlx:2168
let j = result(&o);
// hlx:2169
assert_eq!(
sf(&j, "verdict"),
"abstain",
"{s}: fuel exhaustion must abstain: {}",
trunc(&o.text())
);
// hlx:2170
assert_eq!(j.get("witness"), Some(&J::Null));
// hlx:2171
assert!(o.out.len() <= 65_537);
// hlx:2172
}
// hlx:2173
// negation, nesting and any must not turn the exhausted evaluation into a pass or a fail
// hlx:2174
for claim in [
not_of(&heavy),
all_of(&[heavy.clone()]),
not_of(¬_of(&heavy)),
all_of(&[heavy.clone(), heavy.clone()]),
] {
// hlx:2175
let v = verdict(&env.run("run", &d(SET_IN, &claim).facts(&facts).json()));
// hlx:2176
assert_eq!(v, "abstain", "exhaustion under a wrapper");
// hlx:2177
}
// hlx:2178
// validation never spends the fuel
// hlx:2179
valid(
&env,
&d(SET_IN, &heavy).facts(&facts).json(),
"heavy claim validates",
);
// hlx:2180
// a definition that cannot be evaluated cheaply still reports where it was declared
// hlx:2181
let j = result(
&env.run(
"run",
&d(SET_IN, &heavy)
.id("\"burner\"")
.rev("7")
.facts(&facts)
.json(),
),
);
// hlx:2182
assert_eq!(sf(&j, "check_id"), "burner");
// hlx:2183
assert_eq!(j.get("revision"), Some(&J::Num("7".into())));
// hlx:2184
}
// hlx:2185
#[test]
// hlx:2186
fn witnesses_and_errors_are_bounded_to_64_kib() {
// hlx:2187
let env = Env::new("bounded");
// hlx:2188
// a witness that cannot fit in 64 KiB is a bounded explicit error, never a truncated or substituted witness
// hlx:2189
for n in [100_000usize, 300_000] {
// hlx:2190
let huge = "x".repeat(n);
// hlx:2191
for sub in ["run", "explain"] {
// hlx:2192
for doc in [
// hlx:2193
set_doc("subset", &format!("[\"{huge}\"]"), "[]"),
// hlx:2194
set_doc(
"disjoint",
&format!("[\"{huge}\"]"),
&format!("[\"{huge}\"]"),
),
// hlx:2195
] {
// hlx:2196
err(&env.run(sub, &doc), &format!("{sub} {n}-byte witness"));
// hlx:2197
}
// hlx:2198
}
// hlx:2199
}
// hlx:2200
let wide = "\u{1F600}".repeat(60_000);
// hlx:2201
err(
&env.run("run", &set_doc("subset", &format!("[\"{wide}\"]"), "[]")),
"240000-byte multibyte witness",
);
// hlx:2202
// an error never echoes the request
// hlx:2203
let long_key = "k".repeat(300_000);
// hlx:2204
let docs = [
// hlx:2205
BASE.replacen("\"facts\":{", &format!("\"facts\":{{\"{long_key}\":1,"), 1),
// hlx:2206
BASE.replacen(
"\"id\":\"artifact-membership\"",
&format!("\"id\":\"{long_key}\""),
1,
),
// hlx:2207
BASE.replacen("\"op\":\"subset\"", &format!("\"op\":\"{long_key}\""), 1),
// hlx:2208
BASE.replacen(
"\"actual\":\"set<string>\"",
&format!("\"actual\":\"{long_key}\""),
1,
),
// hlx:2209
BASE.replacen(
"\"project\":\"release-lab\"}},",
&format!("\"{long_key}\":\"x\"}},"),
1,
),
// hlx:2210
format!("{{\"{long_key}\":1}}"),
// hlx:2211
BASE.replacen(
"\"complete-inventory\":true",
&format!("\"{long_key}\":true"),
1,
),
// hlx:2212
set_doc("subset", &format!("[\"{long_key}\",\"{long_key}\"]"), "[]"),
// hlx:2213
set_doc("subset", &format!("[1,\"{long_key}\"]"), "[]"),
// hlx:2214
];
// hlx:2215
for doc in &docs {
// hlx:2216
for sub in ["run", "validate", "explain"] {
// hlx:2217
let o = env.run(sub, doc);
// hlx:2218
err(&o, &format!("{sub} long-key error"));
// hlx:2219
assert!(
!o.text().contains(&"k".repeat(1000)),
"{sub}: the error repeated the request"
);
// hlx:2220
}
// hlx:2221
}
// hlx:2222
}
// hlx:2223
// ---------------------------------------------------------------- CLI
// hlx:2224
#[test]
// hlx:2225
fn cli_argument_mistakes_are_errors_and_have_no_side_effects() {
// hlx:2226
let env = Env::new("cliargs");
// hlx:2227
let f = env.put("good.json", BASE.as_bytes());
// hlx:2228
let f = f.to_str().unwrap();
// hlx:2229
let rows: Vec<Vec<&str>> = vec![
// hlx:2230
vec!["check", "frob"],
// hlx:2231
vec!["check", "RUN", "--input", f],
// hlx:2232
vec!["check", "Run", "--input", f],
// hlx:2233
vec!["check", "", "--input", f],
// hlx:2234
vec!["check", "--input", f],
// hlx:2235
vec!["check", "-"],
// hlx:2236
vec!["check", f],
// hlx:2237
vec!["check", "run"],
// hlx:2238
vec!["check", "validate"],
// hlx:2239
vec!["check", "explain"],
// hlx:2240
vec!["check", "run", "--input"],
// hlx:2241
vec!["check", "validate", "--input"],
// hlx:2242
vec!["check", "explain", "--input"],
// hlx:2243
vec!["check", "run", "--input", f, "--input", f],
// hlx:2244
vec!["check", "validate", "--input", f, "--input", f],
// hlx:2245
vec!["check", "explain", "--input", f, "--input", f],
// hlx:2246
vec!["check", "run", "--input", "-", "--input", "-"],
// hlx:2247
vec!["check", "run", "--input", f, "--input", "-"],
// hlx:2248
vec!["check", "run", "--input", "-", "--input", f],
// hlx:2249
vec!["check", "run", "--input", f, "extra"],
// hlx:2250
vec!["check", "run", "extra", "--input", f],
// hlx:2251
vec!["check", "run", f],
// hlx:2252
vec!["check", "run", "-"],
// hlx:2253
vec!["check", "validate", "--input", f, "run"],
// hlx:2254
vec!["check", "run", "run", "--input", f],
// hlx:2255
vec!["check", "run", "--input", f, "--input"],
// hlx:2256
vec!["check", "run", "--bogus"],
// hlx:2257
vec!["check", "run", "--bogus", "--input", f],
// hlx:2258
vec!["check", "run", "--input", f, "--bogus"],
// hlx:2259
vec!["check", "run", "--input", f, "--bogus=1"],
// hlx:2260
vec!["check", "run", "-i", f],
// hlx:2261
vec!["check", "run", "-input", f],
// hlx:2262
vec!["check", "run", "--Input", f],
// hlx:2263
vec!["check", "run", "--INPUT", f],
// hlx:2264
vec!["check", "run", "--inputs", f],
// hlx:2265
vec!["check", "run", "--in", f],
// hlx:2266
vec!["check", "run", "--file", f],
// hlx:2267
vec!["check", "run", "--json", "--input", f],
// hlx:2268
vec!["check", "run", "--input", f, "--json"],
// hlx:2269
vec!["check", "run", "--verbose", "--input", f],
// hlx:2270
vec!["check", "run", "--store", f, "--input", f],
// hlx:2271
vec!["check", "validate", "--bogus"],
// hlx:2272
vec!["check", "explain", "--bogus"],
// hlx:2273
vec!["check", "explain", "--input", f, "-x"],
// hlx:2274
vec!["check", "run", "--"],
// hlx:2275
vec!["check", "run", "--", "--input", f],
// hlx:2276
vec!["check", "run", "--input", "--input", f],
// hlx:2277
vec!["check", "run", "--input", f, "--help", "--help"],
// hlx:2278
];
// hlx:2279
for row in &rows {
// hlx:2280
let o = env.exec(row, BASE.as_bytes());
// hlx:2281
if row == &vec!["check", "-"] || row == &vec!["check", f] {
// hlx:2282
assert_ne!(o.code, Some(0), "{row:?}");
// hlx:2283
continue;
// hlx:2284
}
// hlx:2285
err(&o, &format!("{row:?}"));
// hlx:2286
}
// hlx:2287
// a bare `check` is not a success either
// hlx:2288
let o = env.exec(&["check"], BASE.as_bytes());
// hlx:2289
assert_ne!(o.code, Some(0), "bare `check`");
// hlx:2290
assert!(!o.text().contains("\"pass\""));
// hlx:2291
}
// hlx:2292
#[test]
// hlx:2293
fn help_is_explicit_and_side_effect_free() {
// hlx:2294
let env = Env::new("help");
// hlx:2295
let f = env.put("good.json", BASE.as_bytes());
// hlx:2296
let f = f.to_str().unwrap();
// hlx:2297
for args in [
// hlx:2298
vec!["check", "--help"],
// hlx:2299
vec!["check", "-h"],
// hlx:2300
] {
// hlx:2301
let o = env.exec(&args, b"");
// hlx:2302
if args.contains(&"-h") {
// hlx:2303
// -h is not promised by the contract; it must at least not run a check
// hlx:2304
assert!(!o.text().contains("\"verdict\":\"pass\""), "{args:?}");
// hlx:2305
continue;
// hlx:2306
}
// hlx:2307
assert_eq!(
o.code,
Some(0),
"{args:?}: {}",
trunc(&String::from_utf8_lossy(&o.err))
);
// hlx:2308
let all = format!("{}{}", o.text(), String::from_utf8_lossy(&o.err));
// hlx:2309
assert!(
all.contains("--input"),
"{args:?}: help must describe --input: {}",
trunc(&all)
);
// hlx:2310
assert!(
!o.text().contains("check-error") && !o.text().contains("check-result"),
"{args:?}"
);
// hlx:2311
assert!(!all.trim().is_empty());
// hlx:2312
}
// hlx:2313
// `--help` is explicit: it does not read stdin or the named file
// hlx:2314
let o = env.exec(&["check", "--help"], BASE.as_bytes());
// hlx:2315
assert_eq!(o.code, Some(0));
// hlx:2316
assert!(!o.text().contains("artifact-membership"));
// hlx:2317
let o = env.exec(&["check", "--help", "--input", f], b"");
// hlx:2318
assert!(
!o.text().contains("check-result"),
"help must not run the check"
);
// hlx:2319
}
// hlx:2320
// docs/checks.md says "`--help` is explicit" without saying whether it is per subcommand; a subcommand
// hlx:2321
// asked for help should explain itself, not fail as a bad argument.
// hlx:2322
#[test]
// hlx:2323
fn subcommand_help_is_explicit_and_side_effect_free() {
// hlx:2324
let env = Env::new("subhelp");
// hlx:2325
for sub in ["run", "validate", "explain"] {
// hlx:2326
let o = env.exec(&["check", sub, "--help"], BASE.as_bytes());
// hlx:2327
assert_eq!(o.code, Some(0), "check {sub} --help: {}", trunc(&o.text()));
// hlx:2328
let all = format!("{}{}", o.text(), String::from_utf8_lossy(&o.err));
// hlx:2329
assert!(
all.contains("--input"),
"check {sub} --help must describe --input: {}",
trunc(&all)
);
// hlx:2330
assert!(!o.text().contains("check-error") && !o.text().contains("check-result"));
// hlx:2331
}
// hlx:2332
}
// hlx:2333
#[test]
// hlx:2334
fn a_successful_check_writes_one_json_object_and_nothing_before_it() {
// hlx:2335
let env = Env::new("stdout");
// hlx:2336
for sub in ["run", "validate", "explain"] {
// hlx:2337
for doc in [BASE.to_string(), mutate("\"revision\":1", "\"revision\":0")] {
// hlx:2338
let o = env.run(sub, &doc);
// hlx:2339
let t = o.text();
// hlx:2340
assert!(
t.starts_with('{'),
"{sub}: stdout must begin with the JSON object: {}",
trunc(&t)
);
// hlx:2341
assert!(
parse_json(t.trim()).is_ok(),
"{sub}: stdout is exactly one JSON value: {}",
trunc(&t)
);
// hlx:2342
assert!(!t.trim().contains("\n\n\n"), "{sub}");
// hlx:2343
}
// hlx:2344
}
// hlx:2345
}
// hlx:2346
// ---------------------------------------------------------------- no bank, no environment, no side effects
// hlx:2347
#[test]
// hlx:2348
fn no_bank_is_opened_or_created_and_a_corrupt_bank_is_untouched() {
// hlx:2349
let env = Env::new("nobank");
// hlx:2350
assert!(!env.bank().exists());
// hlx:2351
for sub in ["run", "validate", "explain"] {
// hlx:2352
let o = env.run(sub, BASE);
// hlx:2353
assert_eq!(o.code, Some(0), "{sub}");
// hlx:2354
}
// hlx:2355
assert!(!env.bank().exists(), "check must not create a bank");
// hlx:2356
assert!(
!env.bank().parent().unwrap().exists(),
"check must not create the bank folder"
);
// hlx:2357
// the exec wrapper compares the whole tree, so anything new anywhere would already have failed above
// hlx:2358
std::fs::create_dir_all(env.bank().parent().unwrap()).unwrap();
// hlx:2359
std::fs::write(env.bank(), b"\xff\xfenot a bank at all\n{{{").unwrap();
// hlx:2360
let a = env.run("run", BASE);
// hlx:2361
let b = env.run("validate", BASE);
// hlx:2362
assert_eq!(a.code, Some(0));
// hlx:2363
assert_eq!(b.code, Some(0));
// hlx:2364
assert_eq!(
std::fs::read(env.bank()).unwrap(),
b"\xff\xfenot a bank at all\n{{{"
);
// hlx:2365
// a store override that points nowhere usable changes nothing
// hlx:2366
let missing = env.root.join("elsewhere").join("deep").join("bank.hxdb");
// hlx:2367
let blocked = env.put("blocker", b"i am a file");
// hlx:2368
let blocked_store = blocked.join("bank.hxdb");
// hlx:2369
let clean = env.run("run", BASE).out;
// hlx:2370
for store in [
missing.to_str().unwrap(),
blocked_store.to_str().unwrap(),
"",
"/nonexistent-root-dir/bank.hxdb",
] {
// hlx:2371
for sub in ["run", "validate", "explain"] {
// hlx:2372
let o = env.exec_env(
&["check", sub, "--input", "-"],
BASE.as_bytes(),
&[("INSTINCT_STORE", store)],
);
// hlx:2373
assert_eq!(
o.code,
Some(0),
"{sub} with store {store:?}: {}",
trunc(&o.text())
);
// hlx:2374
if sub == "run" {
// hlx:2375
assert_eq!(o.out, clean, "store {store:?}");
// hlx:2376
}
// hlx:2377
}
// hlx:2378
}
// hlx:2379
assert!(!missing.exists() && !missing.parent().unwrap().exists());
// hlx:2380
// even failures leave the machine alone
// hlx:2381
err(&env.run("run", "{"), "bad json");
// hlx:2382
assert!(!missing.exists());
// hlx:2383
}
// hlx:2384
#[test]
// hlx:2385
fn the_environment_never_supplies_scope_or_changes_results() {
// hlx:2386
let env = Env::new("envscope");
// hlx:2387
let envs = [
// hlx:2388
("INSTINCT_PROJECT", "release-lab"),
// hlx:2389
("INSTINCT_PERSONA", "p"),
// hlx:2390
("INSTINCT_HARNESS", "h"),
// hlx:2391
("INSTINCT_HARNESS_VERSION", "1"),
// hlx:2392
("INSTINCT_MACHINE", "m"),
// hlx:2393
("INSTINCT_SESSION", "s"),
// hlx:2394
("INSTINCT_EXPLORE", "1"),
// hlx:2395
("INSTINCT_METER", "1"),
// hlx:2396
("CLAUDE_PROJECT_DIR", "release-lab"),
// hlx:2397
("PROJECT", "release-lab"),
// hlx:2398
("HOSTNAME", "m"),
// hlx:2399
];
// hlx:2400
let ins = "{\"one\":\"bool\",\"zero\":\"bool\"}";
// hlx:2401
let doc = d(ins, &op2("eq", "one", "zero"))
.facts("{\"one\":true,\"zero\":false}")
.dscope("{\"project\":\"release-lab\",\"machine\":\"m\",\"persona\":\"p\"}")
.json();
// hlx:2402
for sub in ["run", "explain"] {
// hlx:2403
let plain = env.run(sub, &doc);
// hlx:2404
let with = env.exec_env(&["check", sub, "--input", "-"], doc.as_bytes(), &envs);
// hlx:2405
let j = result(&with);
// hlx:2406
assert_eq!(
sf(&j, "verdict"),
"abstain",
"{sub}: the environment must not satisfy a required scope"
);
// hlx:2407
assert_eq!(pairs(j.get("scope").unwrap()), vec![]);
// hlx:2408
assert_eq!(plain.out, with.out, "{sub}: environment changed the output");
// hlx:2409
}
// hlx:2410
// the working directory name is not a scope either
// hlx:2411
let sub_cwd = env.root.join("cwd");
// hlx:2412
assert!(sub_cwd.exists());
// hlx:2413
let j = result(&env.run("run", &doc));
// hlx:2414
assert_eq!(sf(&j, "verdict"), "abstain");
// hlx:2415
// the opposite direction: the explicit request scope is what counts, whatever the environment says
// hlx:2416
let doc = d(ins, &op2("eq", "one", "zero"))
.facts("{\"one\":true,\"zero\":false}")
.dscope("{\"project\":\"release-lab\"}")
.scope("{\"project\":\"release-lab\"}")
.json();
// hlx:2417
let o = env.exec_env(
&["check", "run", "--input", "-"],
doc.as_bytes(),
&[("INSTINCT_PROJECT", "something-else")],
);
// hlx:2418
assert_eq!(verdict(&o), "fail");
// hlx:2419
}
// hlx:2420
#[test]
// hlx:2421
fn nothing_in_the_input_is_executed_read_or_followed() {
// hlx:2422
let env = Env::new("inert");
// hlx:2423
let marker = env.root.join("home").join("pwned");
// hlx:2424
let marker_s = marker.to_str().unwrap().to_string();
// hlx:2425
let hostile = [
// hlx:2426
format!("$(touch {marker_s})"),
// hlx:2427
format!("`touch {marker_s}`"),
// hlx:2428
format!("; touch {marker_s}"),
// hlx:2429
"../../../../etc/passwd".to_string(),
// hlx:2430
"/etc/shadow".to_string(),
// hlx:2431
"file:///etc/passwd".to_string(),
// hlx:2432
"http://127.0.0.1:1/x".to_string(),
// hlx:2433
"-rf /".to_string(),
// hlx:2434
"%n%n%n%s%s".to_string(),
// hlx:2435
"{{7*7}}".to_string(),
// hlx:2436
];
// hlx:2437
for h in hostile {
// hlx:2438
let esc = h.replace('\\', "\\\\").replace('"', "\\\"");
// hlx:2439
let ins = "{\"p\":\"string\",\"q\":\"string\",\"x\":\"set<string>\"}";
// hlx:2440
let claim = all_of(&[op2("eq", "p", "q"), op2("contains", "x", "p")]);
// hlx:2441
let doc = d(ins, &claim)
// hlx:2442
.facts(&format!(
"{{\"p\":\"{esc}\",\"q\":\"{esc}\",\"x\":[\"{esc}\"]}}"
))
// hlx:2443
.dscope(&format!("{{\"project\":\"{esc}\"}}"))
// hlx:2444
.scope(&format!("{{\"project\":\"{esc}\"}}"))
// hlx:2445
.json();
// hlx:2446
for sub in ["run", "validate", "explain"] {
// hlx:2447
let o = env.run(sub, &doc);
// hlx:2448
assert_eq!(o.code, Some(0), "{sub} {h}");
// hlx:2449
}
// hlx:2450
assert_eq!(verdict(&env.run("run", &doc)), "pass", "{h}");
// hlx:2451
assert!(!marker.exists(), "input text was executed: {h}");
// hlx:2452
}
// hlx:2453
// host paths in facts are plain strings, not access grants and not read
// hlx:2454
let doc = d("{\"p\":\"string\"}", &op2("eq", "p", "p"))
.facts("{\"p\":\"/etc/passwd\"}")
.json();
// hlx:2455
assert_eq!(verdict(&env.run("run", &doc)), "pass");
// hlx:2456
}
// hlx:2457
#[test]
// hlx:2458
fn authorization_is_never_evaluated_and_evidence_is_always_caller_reported() {
// hlx:2459
let env = Env::new("authz");
// hlx:2460
let cases = [
// hlx:2461
BASE.to_string(),
// hlx:2462
mutate(
"\"complete-inventory\":true",
"\"complete-inventory\":false",
),
// hlx:2463
mutate(
"\"allowed\":[\"release.bin\"]",
"\"allowed\":[\"scratch.env\",\"release.bin\"]",
),
// hlx:2464
d(SET_IN, &op2("subset", "actual", "allowed")).json(),
// hlx:2465
];
// hlx:2466
for doc in cases {
// hlx:2467
for sub in ["run", "explain"] {
// hlx:2468
let o = env.run(sub, &doc);
// hlx:2469
let j = result(&o);
// hlx:2470
assert_eq!(sf(&j, "authorization"), "not_evaluated");
// hlx:2471
assert_eq!(sf(&j, "evidence_origin"), "caller_reported");
// hlx:2472
}
// hlx:2473
let o = env.run("validate", &doc);
// hlx:2474
assert_eq!(sf(&obj(&o), "authorization"), "not_evaluated");
// hlx:2475
}
// hlx:2476
// a condition that says true is still only a caller report
// hlx:2477
let j = result(&env.run("run", BASE));
// hlx:2478
assert_eq!(sf(&j, "evidence_origin"), "caller_reported");
// hlx:2479
for bad in [
// hlx:2480
mutate("\"id\":\"artifact-membership\"", "\"id\":\"0bad\""),
// hlx:2481
"{".to_string(),
// hlx:2482
mutate("\"op\":\"subset\"", "\"op\":\"zzz\""),
// hlx:2483
] {
// hlx:2484
let o = env.run("run", &bad);
// hlx:2485
err(&o, "error shape");
// hlx:2486
assert_eq!(sf(&obj(&o), "authorization"), "not_evaluated");
// hlx:2487
}
// hlx:2488
}
// hlx:2489
// docs/checks.md bounds witness/explanation output at 64 KiB and calls the result scope "explicit current scope".
// hlx:2490
// Ordinary scope values (up to 20,000 characters) must be echoed exactly. Past the output bound, a bounded structured
// hlx:2491
// error is acceptable (docs clarification); a success must echo the scope exactly and the JSON text must stay within
// hlx:2492
// 65536 bytes (stdout within 65537 with the CLI newline). Silent truncation or an empty scope is never acceptable.
// hlx:2493
#[test]
// hlx:2494
fn a_huge_request_scope_value_is_rejected_or_echoed_exactly_never_truncated_or_unbounded() {
// hlx:2495
let env = Env::new("hugescope");
// hlx:2496
let ins = "{\"a\":\"bool\"}";
// hlx:2497
let mk = |n: usize| {
// hlx:2498
let v = "p".repeat(n);
// hlx:2499
(
d(ins, &op2("eq", "a", "a"))
.facts("{\"a\":true}")
.scope(&format!("{{\"project\":\"{v}\"}}"))
.json(),
v,
)
// hlx:2500
};
// hlx:2501
// ordinary sizes: success with an exact echo is required, not an arbitrary rejection
// hlx:2502
for n in [1usize, 1_000, 20_000, 60_000] {
// hlx:2503
let (doc, v) = mk(n);
// hlx:2504
for sub in ["run", "explain"] {
// hlx:2505
let o = env.run(sub, &doc);
// hlx:2506
let j = result(&o);
// hlx:2507
assert_eq!(sf(&j, "verdict"), "pass", "{sub} scope {n}");
// hlx:2508
assert_eq!(
pairs(j.get("scope").unwrap()),
vec![("project".to_string(), v.clone())],
"{sub}: scope {n} must echo exactly"
);
// hlx:2509
assert!(
o.text().trim_end().len() <= 65_536 && o.out.len() <= 65_537,
"{sub}: scope {n} produced {} bytes",
o.out.len()
);
// hlx:2510
}
// hlx:2511
valid(&env, &doc, &format!("validate scope {n}"));
// hlx:2512
}
// hlx:2513
// around the 64 KiB boundary and far beyond it: error, or an exact in-bound echo
// hlx:2514
for n in [
64_000usize,
65_000,
65_300,
65_500,
65_536,
65_537,
66_000,
70_000,
90_000,
300_000,
] {
// hlx:2515
let (doc, v) = mk(n);
// hlx:2516
for sub in ["run", "explain", "validate"] {
// hlx:2517
let o = env.run(sub, &doc);
// hlx:2518
match o.code {
// hlx:2519
Some(2) => err(&o, &format!("{sub} scope {n}")),
// hlx:2520
Some(0) => {
// hlx:2521
assert!(
o.text().trim_end().len() <= 65_536 && o.out.len() <= 65_537,
"{sub}: {n}-char scope produced {} bytes",
o.out.len()
);
// hlx:2522
if sub != "validate" {
// hlx:2523
let j = result(&o);
// hlx:2524
assert_eq!(
pairs(j.get("scope").unwrap()),
vec![("project".to_string(), v.clone())],
"{sub}: scope {n} must not be truncated"
);
// hlx:2525
}
// hlx:2526
}
// hlx:2527
other => panic!("{sub}: unexpected exit {other:?}"),
// hlx:2528
}
// hlx:2529
}
// hlx:2530
}
// hlx:2531
// a definition-side huge scope value is bounded the same way
// hlx:2532
for n in [20_000usize, 90_000] {
// hlx:2533
let v = "q".repeat(n);
// hlx:2534
let doc = d(ins, &op2("eq", "a", "a"))
.facts("{\"a\":true}")
.dscope(&format!("{{\"project\":\"{v}\"}}"))
.scope(&format!("{{\"project\":\"{v}\"}}"))
.json();
// hlx:2535
for sub in ["run", "explain"] {
// hlx:2536
let o = env.run(sub, &doc);
// hlx:2537
match o.code {
// hlx:2538
Some(2) => err(&o, &format!("{sub} definition scope {n}")),
// hlx:2539
Some(0) => assert!(
o.text().trim_end().len() <= 65_536 && o.out.len() <= 65_537,
"{sub}: definition scope {n} produced {} bytes",
o.out.len()
),
// hlx:2540
other => panic!("{sub}: unexpected exit {other:?}"),
// hlx:2541
}
// hlx:2542
}
// hlx:2543
}
// hlx:2544
}
// hlx:2545
fn pattern(n: usize) -> String {
// hlx:2546
// non-uniform, so truncation, padding or substitution is detectable
// hlx:2547
let mut s: String = (0..n)
.map(|i| (b'a' + (i * 7 % 26) as u8) as char)
.collect();
// hlx:2548
if n > 0 {
// hlx:2549
s.replace_range(n - 1..n, "Z");
// hlx:2550
}
// hlx:2551
s
// hlx:2552
}
// hlx:2553
#[test]
// hlx:2554
fn witnesses_that_fit_64_kib_are_echoed_exactly() {
// hlx:2555
let env = Env::new("witness-exact");
// hlx:2556
for n in [
1usize, 100, 1_000, 4_096, 4_110, 4_111, 5_000, 8_192, 20_000, 60_000,
] {
// hlx:2557
let m = pattern(n);
// hlx:2558
for sub in ["run", "explain"] {
// hlx:2559
let o = env.run(sub, &set_doc("subset", &format!("[\"{m}\"]"), "[]"));
// hlx:2560
let j = result(&o);
// hlx:2561
assert_eq!(sf(&j, "verdict"), "fail", "{sub} {n}");
// hlx:2562
assert_eq!(
j.get("witness"),
Some(&J::Str(m.clone())),
"{sub}: {n}-char witness must be exact"
);
// hlx:2563
let o = env.run(
sub,
&set_doc(
"disjoint",
&format!("[\"{m}\",\"zz\"]"),
&format!("[\"{m}\"]"),
),
);
// hlx:2564
let j = result(&o);
// hlx:2565
assert_eq!(sf(&j, "verdict"), "fail", "{sub} {n}");
// hlx:2566
assert_eq!(
j.get("witness"),
Some(&J::Str(m.clone())),
"{sub}: {n}-char disjoint witness must be exact"
);
// hlx:2567
assert!(o.text().trim_end().len() <= 65_536 && o.out.len() <= 65_537);
// hlx:2568
}
// hlx:2569
}
// hlx:2570
// multi-byte scalars and escapes, long
// hlx:2571
for (raw, json) in [
// hlx:2572
(
"\u{e9}".repeat(20_000) + "Z",
format!("{}Z", "\\u00e9".repeat(20_000)),
),
// hlx:2573
(
"\u{1F600}".repeat(10_000) + "Z",
format!("{}Z", "\\ud83d\\ude00".repeat(10_000)),
),
// hlx:2574
(
"a\"b\\c\nd\u{1}".repeat(3_000),
"a\\\"b\\\\c\\nd\\u0001".repeat(3_000),
),
// hlx:2575
(
"\u{e9}\u{301}\u{4e2d}".repeat(5_000),
"\\u00e9\\u0301\\u4e2d".repeat(5_000),
),
// hlx:2576
] {
// hlx:2577
let j = result(&env.run("run", &set_doc("subset", &format!("[\"{json}\"]"), "[]")));
// hlx:2578
assert_eq!(
j.get("witness"),
Some(&J::Str(raw)),
"long escaped/multibyte witness"
);
// hlx:2579
}
// hlx:2580
// the lexicographically first of several long unexpected members is the one named, whole
// hlx:2581
let (a, b) = (pattern(5_000), format!("{}!", pattern(5_000)));
// hlx:2582
let j = result(&env.run(
"run",
&set_doc("subset", &format!("[\"{b}\",\"{a}\"]"), "[]"),
));
// hlx:2583
assert_eq!(j.get("witness"), Some(&J::Str(a.min(b))));
// hlx:2584
// around the 64 KiB boundary: an exact in-bound witness or a bounded error, never a different witness
// hlx:2585
for n in [
64_000usize,
64_500,
65_000,
65_200,
65_400,
65_536,
65_537,
66_000,
] {
// hlx:2586
let m = pattern(n);
// hlx:2587
for sub in ["run", "explain"] {
// hlx:2588
let o = env.run(sub, &set_doc("subset", &format!("[\"{m}\"]"), "[]"));
// hlx:2589
match o.code {
// hlx:2590
Some(2) => err(&o, &format!("{sub} {n}-char witness")),
// hlx:2591
Some(0) => {
// hlx:2592
let j = result(&o);
// hlx:2593
assert_eq!(
j.get("witness"),
Some(&J::Str(m.clone())),
"{sub}: {n}-char witness must be exact or an error"
);
// hlx:2594
assert!(
o.text().trim_end().len() <= 65_536 && o.out.len() <= 65_537,
"{sub} {n}: {} bytes",
o.out.len()
);
// hlx:2595
}
// hlx:2596
other => panic!("unexpected exit {other:?}"),
// hlx:2597
}
// hlx:2598
}
// hlx:2599
}
// hlx:2600
}