// generated by hxc 1.0.0-acgt-compiler from tests/check_receipt.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
use std::io::Write;
// hlx:4
use std::path::{Path, PathBuf};
// hlx:5
use std::process::{Command, Stdio};
// hlx:6
use std::sync::atomic::{AtomicUsize, Ordering};
// hlx:7
use std::time::Duration;
// hlx:8
fn bin() -> &'static str {
// hlx:9
env!("CARGO_BIN_EXE_instinct")
// hlx:10
}
// hlx:11
// ---------------------------------------------------------------- minimal JSON reader for the outputs
// hlx:12
#[derive(Debug, Clone, PartialEq)]
// hlx:13
enum J {
// hlx:14
Null,
// hlx:15
Bool(bool),
// hlx:16
Num(String),
// hlx:17
Str(String),
// hlx:18
Arr(Vec<J>),
// hlx:19
Obj(Vec<(String, J)>),
// hlx:20
}
// hlx:21
impl J {
// hlx:22
fn get(&self, k: &str) -> Option<&J> {
// hlx:23
match self {
// hlx:24
J::Obj(v) => v.iter().find(|(a, _)| a == k).map(|(_, b)| b),
// hlx:25
_ => None,
// hlx:26
}
// hlx:27
}
// hlx:28
fn as_str(&self) -> Option<&str> {
// hlx:29
match self {
// hlx:30
J::Str(s) => Some(s),
// hlx:31
_ => None,
// hlx:32
}
// hlx:33
}
// hlx:34
}
// hlx:35
struct P<'a> {
// hlx:36
b: &'a [u8],
// hlx:37
i: usize,
// hlx:38
}
// hlx:39
impl<'a> P<'a> {
// hlx:40
fn ws(&mut self) {
// hlx:41
while self.i < self.b.len() && matches!(self.b[self.i], b' ' | b'\n' | b'\t' | b'\r') {
// hlx:42
self.i += 1;
// hlx:43
}
// hlx:44
}
// hlx:45
fn lit(&mut self, w: &str, v: J) -> Result<J, String> {
// hlx:46
if self.b[self.i..].starts_with(w.as_bytes()) {
// hlx:47
self.i += w.len();
// hlx:48
Ok(v)
// hlx:49
} else {
// hlx:50
Err(format!("bad literal at {}", self.i))
// hlx:51
}
// hlx:52
}
// hlx:53
fn hex4(&mut self) -> Result<u32, String> {
// hlx:54
let h = self.b.get(self.i..self.i + 4).ok_or("short \\u")?;
// hlx:55
let h = std::str::from_utf8(h).map_err(|e| e.to_string())?;
// hlx:56
self.i += 4;
// hlx:57
u32::from_str_radix(h, 16).map_err(|e| e.to_string())
// hlx:58
}
// hlx:59
fn string(&mut self) -> Result<String, String> {
// hlx:60
if self.b.get(self.i) != Some(&b'"') {
// hlx:61
return Err(format!("expected string at {}", self.i));
// hlx:62
}
// hlx:63
self.i += 1;
// hlx:64
let mut out: Vec<u8> = Vec::new();
// hlx:65
loop {
// hlx:66
let c = *self.b.get(self.i).ok_or("unterminated string")?;
// hlx:67
self.i += 1;
// hlx:68
match c {
// hlx:69
b'"' => return String::from_utf8(out).map_err(|e| e.to_string()),
// hlx:70
b'\\' => {
// hlx:71
let e = *self.b.get(self.i).ok_or("bad escape")?;
// hlx:72
self.i += 1;
// hlx:73
let ch = match e {
// hlx:74
b'"' => '"',
// hlx:75
b'\\' => '\\',
// hlx:76
b'/' => '/',
// hlx:77
b'b' => '\u{8}',
// hlx:78
b'f' => '\u{c}',
// hlx:79
b'n' => '\n',
// hlx:80
b'r' => '\r',
// hlx:81
b't' => '\t',
// hlx:82
b'u' => {
// hlx:83
let hi = self.hex4()?;
// hlx:84
if (0xD800..0xDC00).contains(&hi) {
// hlx:85
if self.b.get(self.i) != Some(&b'\\')
|| self.b.get(self.i + 1) != Some(&b'u')
{
// hlx:86
return Err("lone surrogate".into());
// hlx:87
}
// hlx:88
self.i += 2;
// hlx:89
let lo = self.hex4()?;
// hlx:90
char::from_u32(
0x10000 + ((hi - 0xD800) << 10) + (lo.wrapping_sub(0xDC00)),
)
// hlx:91
.ok_or("bad pair")?
// hlx:92
} else {
// hlx:93
char::from_u32(hi).ok_or("lone surrogate")?
// hlx:94
}
// hlx:95
}
// hlx:96
_ => return Err("bad escape".into()),
// hlx:97
};
// hlx:98
let mut buf = [0u8; 4];
// hlx:99
out.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes());
// hlx:100
}
// hlx:101
_ => out.push(c),
// hlx:102
}
// hlx:103
}
// hlx:104
}
// hlx:105
fn val(&mut self) -> Result<J, String> {
// hlx:106
self.ws();
// hlx:107
match self.b.get(self.i).copied() {
// hlx:108
None => Err("eof".into()),
// hlx:109
Some(b'{') => {
// hlx:110
self.i += 1;
// hlx:111
let mut v = Vec::new();
// hlx:112
self.ws();
// hlx:113
if self.b.get(self.i) == Some(&b'}') {
// hlx:114
self.i += 1;
// hlx:115
return Ok(J::Obj(v));
// hlx:116
}
// hlx:117
loop {
// hlx:118
self.ws();
// hlx:119
let k = self.string()?;
// hlx:120
self.ws();
// hlx:121
if self.b.get(self.i) != Some(&b':') {
// hlx:122
return Err("expected colon".into());
// hlx:123
}
// hlx:124
self.i += 1;
// hlx:125
let x = self.val()?;
// hlx:126
v.push((k, x));
// hlx:127
self.ws();
// hlx:128
match self.b.get(self.i) {
// hlx:129
Some(b',') => self.i += 1,
// hlx:130
Some(b'}') => {
// hlx:131
self.i += 1;
// hlx:132
return Ok(J::Obj(v));
// hlx:133
}
// hlx:134
_ => return Err("bad object".into()),
// hlx:135
}
// hlx:136
}
// hlx:137
}
// hlx:138
Some(b'[') => {
// hlx:139
self.i += 1;
// hlx:140
let mut v = Vec::new();
// hlx:141
self.ws();
// hlx:142
if self.b.get(self.i) == Some(&b']') {
// hlx:143
self.i += 1;
// hlx:144
return Ok(J::Arr(v));
// hlx:145
}
// hlx:146
loop {
// hlx:147
v.push(self.val()?);
// hlx:148
self.ws();
// hlx:149
match self.b.get(self.i) {
// hlx:150
Some(b',') => self.i += 1,
// hlx:151
Some(b']') => {
// hlx:152
self.i += 1;
// hlx:153
return Ok(J::Arr(v));
// hlx:154
}
// hlx:155
_ => return Err("bad array".into()),
// hlx:156
}
// hlx:157
}
// hlx:158
}
// hlx:159
Some(b'"') => Ok(J::Str(self.string()?)),
// hlx:160
Some(b't') => self.lit("true", J::Bool(true)),
// hlx:161
Some(b'f') => self.lit("false", J::Bool(false)),
// hlx:162
Some(b'n') => self.lit("null", J::Null),
// hlx:163
Some(_) => {
// hlx:164
let st = self.i;
// hlx:165
while self.i < self.b.len()
&& matches!(
self.b[self.i],
b'-' | b'+' | b'.' | b'e' | b'E' | b'0'..=b'9'
)
{
// hlx:166
self.i += 1;
// hlx:167
}
// hlx:168
if st == self.i {
// hlx:169
return Err(format!("unexpected byte at {st}"));
// hlx:170
}
// hlx:171
Ok(J::Num(
String::from_utf8_lossy(&self.b[st..self.i]).into_owned(),
))
// hlx:172
} // hlx:173
}
// hlx:174
}
// hlx:175
}
// hlx:176
fn parse_json(s: &str) -> Result<J, String> {
// hlx:177
let mut p = P {
b: s.as_bytes(),
i: 0,
};
// hlx:178
let v = p.val()?;
// hlx:179
p.ws();
// hlx:180
if p.i != p.b.len() {
// hlx:181
return Err("trailing data".into());
// hlx:182
}
// hlx:183
Ok(v)
// hlx:184
}
// hlx:185
fn to_s(j: &J) -> String {
// hlx:186
match j {
// hlx:187
J::Null => "null".into(),
// hlx:188
J::Bool(b) => b.to_string(),
// hlx:189
J::Num(n) => n.clone(),
// hlx:190
J::Str(s) => format!("{s:?}"),
// hlx:191
J::Arr(v) => format!("[{}]", v.iter().map(to_s).collect::<Vec<_>>().join(",")),
// hlx:192
J::Obj(v) => format!(
"{{{}}}",
v.iter()
.map(|(k, x)| format!("{k:?}:{}", to_s(x)))
.collect::<Vec<_>>()
.join(",")
),
// hlx:193
}
// hlx:194
}
// hlx:195
// ---------------------------------------------------------------- isolated environment and process runner
// hlx:196
struct Out {
// hlx:197
code: Option<i32>,
// hlx:198
out: Vec<u8>,
// hlx:199
err: Vec<u8>,
// hlx:200
}
// hlx:201
impl Out {
// hlx:202
fn text(&self) -> String {
// hlx:203
String::from_utf8_lossy(&self.out).into_owned()
// hlx:204
}
// hlx:205
}
// hlx:206
fn fnv(b: &[u8]) -> u64 {
// hlx:207
let mut h = 0xcbf29ce484222325u64;
// hlx:208
for x in b {
// hlx:209
h ^= *x as u64;
// hlx:210
h = h.wrapping_mul(0x100000001b3);
// hlx:211
}
// hlx:212
h
// hlx:213
}
// hlx:214
fn walk(base: &Path, dir: &Path, acc: &mut Vec<String>) {
// hlx:215
let mut ents: Vec<_> = match std::fs::read_dir(dir) {
// hlx:216
Ok(r) => r.filter_map(|e| e.ok()).collect(),
// hlx:217
Err(_) => return,
// hlx:218
};
// hlx:219
ents.sort_by_key(|e| e.file_name());
// hlx:220
for e in ents {
// hlx:221
let p = e.path();
// hlx:222
let rel = p.strip_prefix(base).unwrap().display().to_string();
// hlx:223
let md = match std::fs::symlink_metadata(&p) {
// hlx:224
Ok(m) => m,
// hlx:225
Err(_) => continue,
// hlx:226
};
// hlx:227
if md.is_dir() {
// hlx:228
acc.push(format!("d {rel}"));
// hlx:229
walk(base, &p, acc);
// hlx:230
} else {
// hlx:231
let b = std::fs::read(&p).unwrap_or_default();
// hlx:232
acc.push(format!("f {rel} {} {:x}", b.len(), fnv(&b)));
// hlx:233
}
// hlx:234
}
// hlx:235
}
// hlx:236
struct Env {
// hlx:237
root: PathBuf,
// hlx:238
}
// hlx:239
impl Env {
// hlx:240
fn new(name: &str) -> Env {
// hlx:241
static N: AtomicUsize = AtomicUsize::new(0);
// hlx:242
let root = std::env::temp_dir().join(format!(
// hlx:243
"instinct-check-contract-{}-{}-{name}",
// hlx:244
std::process::id(),
// hlx:245
N.fetch_add(1, Ordering::Relaxed) // hlx:246
));
// hlx:247
let _ = std::fs::remove_dir_all(&root);
// hlx:248
for d in [
"home", "data", "local", "cfg", "state", "cache", "cwd", "in",
] {
// hlx:249
std::fs::create_dir_all(root.join(d)).unwrap();
// hlx:250
}
// hlx:251
Env { root }
// hlx:252
}
// hlx:253
fn bank(&self) -> PathBuf {
// hlx:254
let base = if cfg!(windows) { "local" } else { "data" };
// hlx:255
self.root.join(base).join("instinct").join("bank.hxdb")
// hlx:256
}
// hlx:257
fn put(&self, name: &str, bytes: &[u8]) -> PathBuf {
// hlx:258
let p = self.root.join("in").join(name);
// hlx:259
std::fs::write(&p, bytes).unwrap();
// hlx:260
p
// hlx:261
}
// hlx:262
fn snapshot(&self) -> Vec<String> {
// hlx:263
let mut acc = Vec::new();
// hlx:264
walk(&self.root, &self.root, &mut acc);
// hlx:265
acc
// hlx:266
}
// hlx:267
fn exec_env(&self, args: &[&str], stdin: &[u8], envs: &[(&str, &str)]) -> Out {
// hlx:268
let before = self.snapshot();
// hlx:269
let mut c = Command::new(bin());
// hlx:270
c.args(args)
// hlx:271
.current_dir(self.root.join("cwd"))
// hlx:272
.env("HOME", self.root.join("home"))
// hlx:273
.env("XDG_DATA_HOME", self.root.join("data"))
// hlx:274
.env("XDG_CONFIG_HOME", self.root.join("cfg"))
// hlx:275
.env("XDG_STATE_HOME", self.root.join("state"))
// hlx:276
.env("XDG_CACHE_HOME", self.root.join("cache"))
// hlx:277
.env("LOCALAPPDATA", self.root.join("local"))
// hlx:278
.env("APPDATA", self.root.join("local"));
// hlx:279
for (k, _) in std::env::vars() {
// hlx:280
if k.starts_with("INSTINCT_") {
// hlx:281
c.env_remove(k);
// hlx:282
}
// hlx:283
}
// hlx:284
for (k, v) in envs {
// hlx:285
c.env(k, v);
// hlx:286
}
// hlx:287
c.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
// hlx:288
let mut child = c.spawn().unwrap();
// hlx:289
let mut si = child.stdin.take().unwrap();
// hlx:290
let data = stdin.to_vec();
// hlx:291
let w = std::thread::spawn(move || {
// hlx:292
let _ = si.write_all(&data);
// hlx:293
});
// hlx:294
let (tx, rx) = std::sync::mpsc::channel();
// hlx:295
std::thread::spawn(move || {
// hlx:296
let _ = tx.send(child.wait_with_output());
// hlx:297
});
// hlx:298
let o = rx
.recv_timeout(Duration::from_secs(180))
.expect("instinct check hung")
.unwrap();
// hlx:299
let _ = w.join();
// hlx:300
let after = self.snapshot();
// hlx:301
assert_eq!(before, after, "command changed the filesystem: {args:?}");
// hlx:302
if std::env::var_os("CHECK_CONTRACT_COUNT").is_some() {
// hlx:303
eprintln!("check_contract_exec");
// hlx:304
}
// hlx:305
Out {
code: o.status.code(),
out: o.stdout,
err: o.stderr,
}
// hlx:306
}
// hlx:307
fn exec(&self, args: &[&str], stdin: &[u8]) -> Out {
// hlx:308
self.exec_env(args, stdin, &[])
// hlx:309
}
// hlx:310
fn run(&self, sub: &str, doc: &str) -> Out {
// hlx:311
self.exec(&["check", sub, "--input", "-"], doc.as_bytes())
// hlx:312
}
// hlx:313
fn run_bytes(&self, sub: &str, doc: &[u8]) -> Out {
// hlx:314
self.exec(&["check", sub, "--input", "-"], doc)
// hlx:315
}
// hlx:316
}
// hlx:317
impl Drop for Env {
// hlx:318
fn drop(&mut self) {
// hlx:319
let _ = std::fs::remove_dir_all(&self.root);
// hlx:320
}
// hlx:321
}
// hlx:322
// ---------------------------------------------------------------- output assertions
// hlx:323
fn trunc(s: &str) -> String {
// hlx:324
s.chars().take(400).collect()
// hlx:325
}
// hlx:326
fn obj(o: &Out) -> J {
// hlx:327
let t = o.text();
// hlx:328
let j = parse_json(t.trim())
.unwrap_or_else(|e| panic!("stdout is not one JSON value ({e}): {}", trunc(&t)));
// hlx:329
assert!(
matches!(j, J::Obj(_)),
"stdout must be one JSON object: {}",
trunc(&t)
);
// hlx:330
j
// hlx:331
}
// hlx:332
fn sf<'a>(j: &'a J, k: &str) -> &'a str {
// hlx:333
j.get(k)
.and_then(J::as_str)
.unwrap_or_else(|| panic!("missing string field {k} in {}", trunc(&to_s(j))))
// hlx:334
}
// hlx:335
fn names(j: &J) -> Vec<String> {
// hlx:336
match j {
// hlx:337
J::Arr(v) => v
.iter()
.map(|x| x.as_str().expect("array of strings").to_string())
.collect(),
// hlx:338
other => panic!("expected an array, got {}", to_s(other)),
// hlx:339
}
// hlx:340
}
// hlx:341
fn result(o: &Out) -> J {
// hlx:342
assert_eq!(o.code, Some(0), "expected exit 0: {}", trunc(&o.text()));
// hlx:343
let j = obj(o);
// hlx:344
assert_eq!(
sf(&j, "schema"),
"instinct.check-result/v1",
"{}",
trunc(&o.text())
);
// hlx:345
assert!(
["pass", "fail", "abstain"].contains(&sf(&j, "verdict")),
"{}",
trunc(&o.text())
);
// hlx:346
assert_eq!(sf(&j, "authorization"), "not_evaluated");
// hlx:347
assert_eq!(sf(&j, "evidence_origin"), "caller_reported");
// hlx:348
assert!(!sf(&j, "reason").is_empty());
// hlx:349
assert!(!sf(&j, "check_id").is_empty());
// hlx:350
match j.get("revision") {
// hlx:351
Some(J::Num(n)) => assert!(n.parse::<u32>().is_ok(), "revision must be an integer: {n}"),
// hlx:352
other => panic!("revision must be a number: {other:?}"),
// hlx:353
}
// hlx:354
match j.get("steps") {
// hlx:355
Some(J::Num(n)) => assert!(
n.parse::<u64>().is_ok(),
"steps must be a non-negative integer: {n}"
),
// hlx:356
other => panic!("steps must be a number: {other:?}"),
// hlx:357
}
// hlx:358
match j.get("witness") {
// hlx:359
Some(J::Null) | Some(J::Str(_)) => {}
// hlx:360
other => panic!("witness must be string or null: {other:?}"),
// hlx:361
}
// hlx:362
let m = names(j.get("missing").expect("missing field"));
// hlx:363
let mut sorted = m.clone();
// hlx:364
sorted.sort();
// hlx:365
sorted.dedup();
// hlx:366
assert_eq!(m, sorted, "missing must be sorted and unique");
// hlx:367
assert!(
matches!(j.get("scope"), Some(J::Obj(_))),
"scope must be an object"
);
// hlx:368
let verdict = sf(&j, "verdict");
// hlx:369
if verdict == "pass" || verdict == "abstain" {
// hlx:370
assert_eq!(
j.get("witness"),
Some(&J::Null),
"only a failed check has a witness: {}",
trunc(&o.text())
);
// hlx:371
}
// hlx:372
j
// hlx:373
}
// hlx:374
fn err(o: &Out, ctx: &str) {
// hlx:375
assert_eq!(
o.code,
Some(2),
"{ctx}: expected exit 2, stdout={}",
trunc(&o.text())
);
// hlx:376
let j = obj(o);
// hlx:377
assert_eq!(
sf(&j, "schema"),
"instinct.check-error/v1",
"{ctx}: {}",
trunc(&o.text())
);
// hlx:378
assert_eq!(sf(&j, "verdict"), "error", "{ctx}");
// hlx:379
assert!(!sf(&j, "reason").is_empty(), "{ctx}");
// hlx:380
assert_eq!(sf(&j, "authorization"), "not_evaluated", "{ctx}");
// hlx:381
assert!(
o.out.len() <= 65_537,
"{ctx}: error output must be bounded, got {} bytes",
o.out.len()
);
// hlx:382
}
// hlx:383
#[derive(Clone)]
// hlx:384
struct D {
// hlx:385
schema: String,
// hlx:386
id: String,
// hlx:387
rev: String,
// hlx:388
inputs: String,
// hlx:389
claim: String,
// hlx:390
req: Option<String>,
// hlx:391
dscope: Option<String>,
// hlx:392
facts: Option<String>,
// hlx:393
conds: Option<String>,
// hlx:394
scope: Option<String>,
// hlx:395
}
// hlx:396
fn d(inputs: &str, claim: &str) -> D {
// hlx:397
D {
// hlx:398
schema: "\"instinct.check/v1\"".into(),
// hlx:399
id: "\"t1\"".into(),
// hlx:400
rev: "1".into(),
// hlx:401
inputs: inputs.into(),
// hlx:402
claim: claim.into(),
// hlx:403
req: None,
// hlx:404
dscope: None,
// hlx:405
facts: None,
// hlx:406
conds: None,
// hlx:407
scope: None,
// hlx:408
}
// hlx:409
}
// hlx:410
impl D {
// hlx:411
fn facts(mut self, s: &str) -> D {
// hlx:412
self.facts = Some(s.into());
// hlx:413
self
// hlx:414
}
// hlx:415
fn conds(mut self, s: &str) -> D {
// hlx:416
self.conds = Some(s.into());
// hlx:417
self
// hlx:418
}
// hlx:419
fn scope(mut self, s: &str) -> D {
// hlx:420
self.scope = Some(s.into());
// hlx:421
self
// hlx:422
}
// hlx:423
fn dscope(mut self, s: &str) -> D {
// hlx:424
self.dscope = Some(s.into());
// hlx:425
self
// hlx:426
}
// hlx:427
fn req(mut self, s: &str) -> D {
// hlx:428
self.req = Some(s.into());
// hlx:429
self
// hlx:430
}
// hlx:431
fn id(mut self, s: &str) -> D {
// hlx:432
self.id = s.into();
// hlx:433
self
// hlx:434
}
// hlx:435
fn rev(mut self, s: &str) -> D {
// hlx:436
self.rev = s.into();
// hlx:437
self
// hlx:438
}
// hlx:439
fn json(&self) -> String {
// hlx:440
let mut c = format!(
// hlx:441
"{{\"schema\":{},\"id\":{},\"revision\":{},\"inputs\":{},\"claim\":{}",
// hlx:442
self.schema,
self.id,
self.rev,
self.inputs,
self.claim // hlx:443
);
// hlx:444
if let Some(r) = &self.req {
// hlx:445
c.push_str(&format!(",\"required_conditions\":{r}"));
// hlx:446
}
// hlx:447
if let Some(s) = &self.dscope {
// hlx:448
c.push_str(&format!(",\"scope\":{s}"));
// hlx:449
}
// hlx:450
c.push('}');
// hlx:451
let mut t = format!("{{\"check\":{c}");
// hlx:452
if let Some(f) = &self.facts {
// hlx:453
t.push_str(&format!(",\"facts\":{f}"));
// hlx:454
}
// hlx:455
if let Some(f) = &self.conds {
// hlx:456
t.push_str(&format!(",\"conditions\":{f}"));
// hlx:457
}
// hlx:458
if let Some(f) = &self.scope {
// hlx:459
t.push_str(&format!(",\"scope\":{f}"));
// hlx:460
}
// hlx:461
t.push('}');
// hlx:462
t
// hlx:463
}
// hlx:464
}
// hlx:465
fn fact(n: &str) -> String {
// hlx:466
format!("{{\"fact\":\"{n}\"}}")
// hlx:467
}
// hlx:468
fn op2(op: &str, l: &str, r: &str) -> String {
// hlx:469
format!(
"{{\"op\":\"{op}\",\"left\":{},\"right\":{}}}",
fact(l),
fact(r)
)
// hlx:470
}
// hlx:471
fn all_of(a: &[String]) -> String {
// hlx:472
format!("{{\"op\":\"all\",\"args\":[{}]}}", a.join(","))
// hlx:473
}
// hlx:474
fn any_of(a: &[String]) -> String {
// hlx:475
format!("{{\"op\":\"any\",\"args\":[{}]}}", a.join(","))
// hlx:476
}
// hlx:477
fn not_of(a: &str) -> String {
// hlx:478
format!("{{\"op\":\"not\",\"arg\":{a}}}")
// hlx:479
}
// hlx:480
// the example from the contract, on one line
// hlx:481
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:482
const SET_IN: &str = "{\"actual\":\"set<string>\",\"allowed\":\"set<string>\"}";
// hlx:483
fn mutate(from: &str, to: &str) -> String {
// hlx:484
assert_eq!(
BASE.matches(from).count(),
1,
"mutation anchor must be unique: {from}"
);
// hlx:485
BASE.replacen(from, to, 1)
// hlx:486
}
// hlx:487
fn set_doc(op: &str, l: &str, r: &str) -> String {
// hlx:488
d(SET_IN, &op2(op, "actual", "allowed"))
.facts(&format!("{{\"actual\":{l},\"allowed\":{r}}}"))
.json()
// hlx:489
}
// hlx:490
fn many(n: usize, prefix: &str) -> String {
// hlx:491
format!(
"[{}]",
(0..n)
.map(|i| format!("\"{prefix}{i:05}\""))
.collect::<Vec<_>>()
.join(",")
)
// hlx:492
}
// hlx:493
// ================================================================ independent oracle (from docs/check-receipt-wire.md)
// hlx:494
fn sha256(data: &[u8]) -> [u8; 32] {
// hlx:495
const K: [u32; 64] = [
// hlx:496
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4,
0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, // hlx:497
0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, // hlx:498
0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3,
0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, // hlx:499
0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, // hlx:500
0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c,
0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, // hlx:501
0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb,
0xbef9a3f7, 0xc67178f2,
// hlx:502
];
// hlx:503
let mut h: [u32; 8] = [
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab,
0x5be0cd19,
];
// hlx:504
let mut msg = data.to_vec();
// hlx:505
let bits = (data.len() as u64).wrapping_mul(8);
// hlx:506
msg.push(0x80);
// hlx:507
while msg.len() % 64 != 56 {
// hlx:508
msg.push(0);
// hlx:509
}
// hlx:510
msg.extend_from_slice(&bits.to_be_bytes());
// hlx:511
for chunk in msg.chunks(64) {
// hlx:512
let mut w = [0u32; 64];
// hlx:513
for i in 0..16 {
// hlx:514
w[i] = u32::from_be_bytes([
chunk[4 * i],
chunk[4 * i + 1],
chunk[4 * i + 2],
chunk[4 * i + 3],
]);
// hlx:515
}
// hlx:516
for i in 16..64 {
// hlx:517
let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
// hlx:518
let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
// hlx:519
w[i] = w[i - 16]
.wrapping_add(s0)
.wrapping_add(w[i - 7])
.wrapping_add(s1);
// hlx:520
}
// hlx:521
let mut v = h;
// hlx:522
for i in 0..64 {
// hlx:523
let s1 = v[4].rotate_right(6) ^ v[4].rotate_right(11) ^ v[4].rotate_right(25);
// hlx:524
let ch = (v[4] & v[5]) ^ (!v[4] & v[6]);
// hlx:525
let t1 = v[7]
.wrapping_add(s1)
.wrapping_add(ch)
.wrapping_add(K[i])
.wrapping_add(w[i]);
// hlx:526
let s0 = v[0].rotate_right(2) ^ v[0].rotate_right(13) ^ v[0].rotate_right(22);
// hlx:527
let maj = (v[0] & v[1]) ^ (v[0] & v[2]) ^ (v[1] & v[2]);
// hlx:528
let t2 = s0.wrapping_add(maj);
// hlx:529
v[7] = v[6];
// hlx:530
v[6] = v[5];
// hlx:531
v[5] = v[4];
// hlx:532
v[4] = v[3].wrapping_add(t1);
// hlx:533
v[3] = v[2];
// hlx:534
v[2] = v[1];
// hlx:535
v[1] = v[0];
// hlx:536
v[0] = t1.wrapping_add(t2);
// hlx:537
}
// hlx:538
for i in 0..8 {
// hlx:539
h[i] = h[i].wrapping_add(v[i]);
// hlx:540
}
// hlx:541
}
// hlx:542
let mut out = [0u8; 32];
// hlx:543
for i in 0..8 {
// hlx:544
out[4 * i..4 * i + 4].copy_from_slice(&h[i].to_be_bytes());
// hlx:545
}
// hlx:546
out
// hlx:547
}
// hlx:548
fn hex(b: &[u8]) -> String {
// hlx:549
b.iter().map(|x| format!("{x:02x}")).collect()
// hlx:550
}
// hlx:551
fn is_hex64(s: &str) -> bool {
// hlx:552
s.len() == 64 && s.bytes().all(|c| matches!(c, b'0'..=b'9' | b'a'..=b'f'))
// hlx:553
}
// hlx:554
fn put_len(out: &mut Vec<u8>, n: usize) {
// hlx:555
out.extend_from_slice(&(n as u64).to_be_bytes());
// hlx:556
}
// hlx:557
// typed, length-framed binary encoding: Null 0, Bool 1+byte, Number 2+len+literal, String 3+len+bytes,
// hlx:558
// Array 4+count+elements, Object 5+count+(key as String, value) with keys in Unicode scalar order
// hlx:559
fn enc(j: &J, out: &mut Vec<u8>) {
// hlx:560
match j {
// hlx:561
J::Null => out.push(0),
// hlx:562
J::Bool(b) => {
// hlx:563
out.push(1);
// hlx:564
out.push(*b as u8);
// hlx:565
}
// hlx:566
J::Num(n) => {
// hlx:567
out.push(2);
// hlx:568
put_len(out, n.len());
// hlx:569
out.extend_from_slice(n.as_bytes());
// hlx:570
}
// hlx:571
J::Str(s) => {
// hlx:572
out.push(3);
// hlx:573
put_len(out, s.len());
// hlx:574
out.extend_from_slice(s.as_bytes());
// hlx:575
}
// hlx:576
J::Arr(v) => {
// hlx:577
out.push(4);
// hlx:578
put_len(out, v.len());
// hlx:579
for x in v {
// hlx:580
enc(x, out);
// hlx:581
}
// hlx:582
}
// hlx:583
J::Obj(v) => {
// hlx:584
let mut kv = v.clone();
// hlx:585
kv.sort_by(|a, b| a.0.cmp(&b.0));
// hlx:586
out.push(5);
// hlx:587
put_len(out, kv.len());
// hlx:588
for (k, x) in kv {
// hlx:589
enc(&J::Str(k), out);
// hlx:590
enc(&x, out);
// hlx:591
}
// hlx:592
} // hlx:593
}
// hlx:594
}
// hlx:595
fn digest(prefix: &str, j: &J) -> String {
// hlx:596
let mut pre = prefix.as_bytes().to_vec();
// hlx:597
pre.push(0);
// hlx:598
enc(j, &mut pre);
// hlx:599
hex(&sha256(&pre))
// hlx:600
}
// hlx:601
fn strs(j: &J) -> Vec<String> {
// hlx:602
match j {
// hlx:603
J::Arr(v) => v
.iter()
.map(|x| x.as_str().expect("string").to_string())
.collect(),
// hlx:604
other => panic!("{}", to_s(other)),
// hlx:605
}
// hlx:606
}
// hlx:607
// the canonical request: defaults materialized, set facts and required_conditions sorted, everything else as written
// hlx:608
fn canon_request(req: &J) -> J {
// hlx:609
let check = req.get("check").expect("check");
// hlx:610
let types: Vec<(String, String)> = match check.get("inputs") {
// hlx:611
Some(J::Obj(v)) => v
.iter()
.map(|(k, t)| (k.clone(), t.as_str().unwrap().to_string()))
.collect(),
// hlx:612
_ => panic!("inputs"),
// hlx:613
};
// hlx:614
let facts = match req.get("facts") {
// hlx:615
Some(J::Obj(v)) => J::Obj(
// hlx:616
v.iter()
// hlx:617
.map(|(k, x)| {
// hlx:618
let is_set = types.iter().any(|(n, t)| n == k && t == "set<string>");
// hlx:619
if is_set {
// hlx:620
let mut m = strs(x);
// hlx:621
m.sort();
// hlx:622
(k.clone(), J::Arr(m.into_iter().map(J::Str).collect()))
// hlx:623
} else {
// hlx:624
(k.clone(), x.clone())
// hlx:625
}
// hlx:626
})
// hlx:627
.collect(),
// hlx:628
),
// hlx:629
_ => J::Obj(vec![]),
// hlx:630
};
// hlx:631
let obj_or_empty = |k: &str| req.get(k).cloned().unwrap_or(J::Obj(vec![]));
// hlx:632
let mut cv: Vec<(String, J)> = match check {
// hlx:633
J::Obj(v) => v
.iter()
.filter(|(k, _)| k != "required_conditions" && k != "scope")
.cloned()
.collect(),
// hlx:634
_ => panic!("check"),
// hlx:635
};
// hlx:636
let mut rc = check
.get("required_conditions")
.map(strs)
.unwrap_or_default();
// hlx:637
rc.sort();
// hlx:638
cv.push((
"required_conditions".into(),
J::Arr(rc.into_iter().map(J::Str).collect()),
));
// hlx:639
cv.push((
"scope".into(),
check.get("scope").cloned().unwrap_or(J::Obj(vec![])),
));
// hlx:640
J::Obj(vec![
// hlx:641
("check".into(), J::Obj(cv)),
// hlx:642
("facts".into(), facts),
// hlx:643
("conditions".into(), obj_or_empty("conditions")),
// hlx:644
("scope".into(), obj_or_empty("scope")),
// hlx:645
])
// hlx:646
}
// hlx:647
fn oracle_input(req_text: &str) -> String {
// hlx:648
digest(
"instinct.check-input/v1",
&canon_request(&parse_json(req_text).expect("request json")),
)
// hlx:649
}
// hlx:650
// the result core is the kernel `run` result without `steps`
// hlx:651
fn oracle_result(run_out: &J) -> String {
// hlx:652
match run_out {
// hlx:653
J::Obj(v) => digest(
"instinct.check-result-core/v1",
&J::Obj(v.iter().filter(|(k, _)| k != "steps").cloned().collect()),
),
// hlx:654
_ => panic!("result"),
// hlx:655
}
// hlx:656
}
// hlx:657
fn esc_str(s: &str, ascii: bool) -> String {
// hlx:658
let mut o = String::from("\"");
// hlx:659
for c in s.chars() {
// hlx:660
match c {
// hlx:661
'"' => o.push_str("\\\""),
// hlx:662
'\\' => o.push_str("\\\\"),
// hlx:663
'\n' => o.push_str("\\n"),
// hlx:664
c if (c as u32) < 0x20 => o.push_str(&format!("\\u{:04x}", c as u32)),
// hlx:665
c if ascii && (c as u32) > 0x7e => {
// hlx:666
let mut b = [0u16; 2];
// hlx:667
for u in c.encode_utf16(&mut b) {
// hlx:668
o.push_str(&format!("\\u{:04x}", u));
// hlx:669
}
// hlx:670
}
// hlx:671
c => o.push(c),
// hlx:672
}
// hlx:673
}
// hlx:674
o.push('"');
// hlx:675
o
// hlx:676
}
// hlx:677
fn ser(j: &J, ws: bool, ascii: bool) -> String {
// hlx:678
let (sep, colon) = if ws { (",\n ", " : ") } else { (",", ":") };
// hlx:679
match j {
// hlx:680
J::Null => "null".into(),
// hlx:681
J::Bool(b) => b.to_string(),
// hlx:682
J::Num(n) => n.clone(),
// hlx:683
J::Str(s) => esc_str(s, ascii),
// hlx:684
J::Arr(v) => format!(
"[{}]",
v.iter()
.map(|x| ser(x, ws, ascii))
.collect::<Vec<_>>()
.join(sep)
),
// hlx:685
J::Obj(v) => format!(
"{{{}}}",
v.iter()
.map(|(k, x)| format!("{}{colon}{}", esc_str(k, ascii), ser(x, ws, ascii)))
.collect::<Vec<_>>()
.join(sep)
),
// hlx:686
}
// hlx:687
}
// hlx:688
fn reorder<T>(mut v: Vec<T>, mode: usize) -> Vec<T> {
// hlx:689
match mode {
// hlx:690
0 => v.reverse(),
// hlx:691
1 => {
// hlx:692
if !v.is_empty() {
// hlx:693
v.rotate_left(1)
// hlx:694
}
// hlx:695
}
// hlx:696
_ => {
// hlx:697
let n = v.len();
// hlx:698
if n > 2 {
// hlx:699
v.swap(0, n - 1);
// hlx:700
v.swap(1, n / 2);
// hlx:701
}
// hlx:702
} // hlx:703
}
// hlx:704
v
// hlx:705
}
// hlx:706
// reorder every object's keys and every set-like array (but never the ordered `args` of all/any)
// hlx:707
fn permute(j: &J, mode: usize) -> J {
// hlx:708
match j {
// hlx:709
J::Obj(v) => J::Obj(
// hlx:710
reorder(v.clone(), mode)
// hlx:711
.into_iter()
// hlx:712
.map(|(k, x)| {
// hlx:713
let nx = match (&k[..], &x) {
// hlx:714
("args", J::Arr(items)) => {
J::Arr(items.iter().map(|i| permute(i, mode)).collect())
}
// hlx:715
(_, J::Arr(items)) => J::Arr(reorder(items.clone(), mode)),
// hlx:716
_ => permute(&x, mode),
// hlx:717
};
// hlx:718
(k, nx)
// hlx:719
})
// hlx:720
.collect(),
// hlx:721
),
// hlx:722
other => other.clone(),
// hlx:723
}
// hlx:724
}
// hlx:725
// ================================================================ CLI helpers
// hlx:726
const MEANING: &str = "matches_recomputed_supplied_facts_not_world_truth";
// hlx:727
fn keys_of(j: &J) -> Vec<String> {
// hlx:728
match j {
// hlx:729
J::Obj(v) => {
// hlx:730
let mut k: Vec<String> = v.iter().map(|(k, _)| k.clone()).collect();
// hlx:731
k.sort();
// hlx:732
k
// hlx:733
}
// hlx:734
_ => panic!("object"),
// hlx:735
}
// hlx:736
}
// hlx:737
fn rcpt(o: &Out) -> J {
// hlx:738
assert_eq!(o.code, Some(0), "receipt: {}", trunc(&o.text()));
// hlx:739
assert!(o.out.len() <= 65_537, "{} bytes", o.out.len());
// hlx:740
let j = obj(o);
// hlx:741
let mut want = vec![
"authorization",
"check_id",
"evidence_origin",
"input_sha256",
"result_sha256",
"revision",
"schema",
"verdict",
"verifier",
];
// hlx:742
want.sort();
// hlx:743
assert_eq!(
keys_of(&j),
want,
"a receipt has exactly these keys: {}",
trunc(&o.text())
);
// hlx:744
assert_eq!(sf(&j, "schema"), "instinct.check-receipt/v1");
// hlx:745
assert_eq!(sf(&j, "verifier"), "instinct.check-kernel/v1");
// hlx:746
assert_eq!(sf(&j, "authorization"), "not_evaluated");
// hlx:747
assert_eq!(sf(&j, "evidence_origin"), "caller_reported");
// hlx:748
assert!(
is_hex64(sf(&j, "input_sha256")) && is_hex64(sf(&j, "result_sha256")),
"{}",
trunc(&o.text())
);
// hlx:749
assert!(["pass", "fail", "abstain"].contains(&sf(&j, "verdict")));
// hlx:750
assert!(!sf(&j, "check_id").is_empty());
// hlx:751
assert!(matches!(j.get("revision"), Some(J::Num(n)) if n.parse::<u32>().is_ok()));
// hlx:752
let t = o.text();
// hlx:753
for bad in [
"safe_to_release",
"signature",
"authenticated",
"adapter_observed",
"\"witness\"",
"\"scope\"",
"\"facts\"",
] {
// hlx:754
assert!(
!t.contains(bad),
"a receipt must not contain {bad}: {}",
trunc(&t)
);
// hlx:755
}
// hlx:756
j
// hlx:757
}
// hlx:758
fn replay_doc(req: &str, receipt: &str) -> String {
// hlx:759
format!("{{\"request\":{req},\"receipt\":{receipt}}}")
// hlx:760
}
// hlx:761
fn consistent(o: &Out, verdict: &str, input: &str, result: &str) {
// hlx:762
assert_eq!(o.code, Some(0), "replay: {}", trunc(&o.text()));
// hlx:763
assert!(o.out.len() <= 65_537);
// hlx:764
let j = obj(o);
// hlx:765
let mut want = vec![
"authorization",
"evidence_origin",
"input_sha256",
"meaning",
"result_sha256",
"schema",
"status",
"verdict",
];
// hlx:766
want.sort();
// hlx:767
assert_eq!(keys_of(&j), want, "{}", trunc(&o.text()));
// hlx:768
assert_eq!(sf(&j, "schema"), "instinct.check-replay/v1");
// hlx:769
assert_eq!(sf(&j, "status"), "consistent", "{}", trunc(&o.text()));
// hlx:770
assert_eq!(sf(&j, "verdict"), verdict);
// hlx:771
assert_eq!(sf(&j, "input_sha256"), input);
// hlx:772
assert_eq!(sf(&j, "result_sha256"), result);
// hlx:773
assert_eq!(sf(&j, "authorization"), "not_evaluated");
// hlx:774
assert_eq!(sf(&j, "evidence_origin"), "caller_reported");
// hlx:775
assert_eq!(sf(&j, "meaning"), MEANING);
// hlx:776
}
// hlx:777
fn mismatch(o: &Out, forbidden: &[&str], ctx: &str) {
// hlx:778
assert_eq!(o.code, Some(0), "{ctx}: {}", trunc(&o.text()));
// hlx:779
assert!(o.out.len() <= 65_537);
// hlx:780
let j = obj(o);
// hlx:781
assert_eq!(sf(&j, "schema"), "instinct.check-replay/v1", "{ctx}");
// hlx:782
assert_eq!(sf(&j, "status"), "mismatch", "{ctx}: {}", trunc(&o.text()));
// hlx:783
assert_eq!(sf(&j, "verdict"), "abstain", "{ctx}");
// hlx:784
assert_eq!(sf(&j, "reason"), "receipt_mismatch", "{ctx}");
// hlx:785
assert_eq!(sf(&j, "authorization"), "not_evaluated");
// hlx:786
assert_eq!(sf(&j, "evidence_origin"), "caller_reported");
// hlx:787
assert_eq!(sf(&j, "meaning"), MEANING);
// hlx:788
let t = o.text();
// hlx:789
for f in forbidden {
// hlx:790
assert!(
!t.contains(f),
"{ctx}: a mismatch must not echo {f}: {}",
trunc(&t)
);
// hlx:791
}
// hlx:792
}
// hlx:793
struct Made {
// hlx:794
receipt: J,
// hlx:795
input: String,
// hlx:796
result: String,
// hlx:797
verdict: String,
// hlx:798
}
// hlx:799
// receipt for a request, checked against the independent oracle
// hlx:800
fn make(env: &Env, req: &str) -> Made {
// hlx:801
let o = env.run("receipt", req);
// hlx:802
let r = rcpt(&o);
// hlx:803
let run = result(&env.run("run", req));
// hlx:804
let input = oracle_input(req);
// hlx:805
let res = oracle_result(&run);
// hlx:806
assert_eq!(
sf(&r, "input_sha256"),
input,
"input digest must equal the independent oracle for {}",
trunc(req)
);
// hlx:807
assert_eq!(
sf(&r, "result_sha256"),
res,
"result digest must equal the independent oracle for {}",
trunc(req)
);
// hlx:808
assert_eq!(sf(&r, "verdict"), sf(&run, "verdict"));
// hlx:809
assert_eq!(sf(&r, "check_id"), sf(&run, "check_id"));
// hlx:810
assert_eq!(r.get("revision"), run.get("revision"));
// hlx:811
Made {
receipt: r.clone(),
input,
result: res,
verdict: sf(&r, "verdict").to_string(),
}
// hlx:812
}
// hlx:813
// a request exercising every type, nested ordered logic, big sets and several conditions
// hlx:814
fn rich() -> String {
// hlx:815
let ins = "{\"z\":\"string\",\"actual\":\"set<string>\",\"allowed\":\"set<string>\",\"n\":\"int\",\"m\":\"int\",\"b\":\"bool\",\"c\":\"bool\"}";
// hlx:816
let claim = all_of(&[
// hlx:817
op2("subset", "actual", "allowed"),
// hlx:818
op2("contains", "allowed", "z"),
// hlx:819
any_of(&[op2("lt", "n", "m"), op2("eq", "b", "c")]),
// hlx:820
not_of(&op2("disjoint", "actual", "allowed")),
// hlx:821
]);
// hlx:822
d(ins, &claim)
// hlx:823
.id("\"rich-check_1.x\"")
// hlx:824
.rev("7")
// hlx:825
.req("[\"c3\",\"c1\",\"c2\"]")
// hlx:826
.dscope("{\"project\":\"p\",\"persona\":\"q\"}")
// hlx:827
.facts("{\"z\":\"\\u00e9\",\"actual\":[\"d\",\"b\",\"a\",\"\\u00e9\",\"c\"],\"allowed\":[\"e\",\"a\",\"b\",\"d\",\"c\",\"\\u00e9\"],\"n\":\"9007199254740993\",\"m\":\"9007199254740995\",\"b\":true,\"c\":false}")
// hlx:828
.conds("{\"c2\":true,\"c1\":true,\"c3\":true}")
// hlx:829
.scope("{\"project\":\"p\",\"persona\":\"q\",\"machine\":\"m1\"}")
// hlx:830
.json()
// hlx:831
}
// hlx:832
fn corpus() -> Vec<(&'static str, String)> {
// hlx:833
let heavy_sets = {
// hlx:834
let n = 4900;
// hlx:835
let left = many(n, "m");
// hlx:836
let mut rev: Vec<String> = (0..n).map(|i| format!("\"m{i:05}\"")).collect();
// hlx:837
rev.reverse();
// hlx:838
let sub = op2("subset", "actual", "allowed");
// hlx:839
d(
SET_IN,
&all_of(&(0..30).map(|_| sub.clone()).collect::<Vec<_>>()),
)
// hlx:840
.facts(&format!(
"{{\"actual\":{left},\"allowed\":[{}]}}",
rev.join(",")
))
// hlx:841
.json()
// hlx:842
};
// hlx:843
vec![
// hlx:844
("contract example (fail)", BASE.to_string()),
// hlx:845
("pass", mutate("\"allowed\":[\"release.bin\"]", "\"allowed\":[\"scratch.env\",\"release.bin\"]")),
// hlx:846
("abstain: facts omitted", d(SET_IN, &op2("subset", "actual", "allowed")).json()),
// hlx:847
("abstain: one fact missing", d(SET_IN, &op2("subset", "actual", "allowed")).facts("{\"actual\":[\"a\"]}").json()),
// hlx:848
("abstain: condition false", mutate("\"complete-inventory\":true", "\"complete-inventory\":false")),
// hlx:849
("abstain: condition missing", mutate("\"complete-inventory\":true,", "")),
// hlx:850
("abstain: scope mismatch", mutate("\"explicit-policy\":true},\"scope\":{\"project\":\"release-lab\"}}", "\"explicit-policy\":true},\"scope\":{\"project\":\"other\"}}")),
// hlx:851
("abstain: fuel exhaustion", heavy_sets),
// hlx:852
("rich", rich()),
// hlx:853
("ints", d("{\"a\":\"int\",\"b\":\"int\"}", &op2("lt", "a", "b")).facts("{\"a\":\"170141183460469231731687303715884105726\",\"b\":\"170141183460469231731687303715884105727\"}").json()),
// hlx:854
("long exact witness", set_doc("subset", &format!("[\"{}\"]", "w".repeat(5000)), "[]")),
// hlx:855
("unicode set", set_doc("subset", "[\"e\\u0301\",\"\\u00e9\",\"\\ud83d\\ude00\"]", "[\"\\u00e9\"]")),
// hlx:856
("empty sets", set_doc("subset", "[]", "[]")),
// hlx:857
("scope 20k", d("{\"a\":\"bool\"}", &op2("eq", "a", "a")).facts("{\"a\":true}").scope(&format!("{{\"project\":\"{}\"}}", "p".repeat(20_000))).json()),
// hlx:858
]
// hlx:859
}
// hlx:860
// ================================================================ the oracle itself
// hlx:861
#[test]
// hlx:862
fn the_independent_sha256_oracle_matches_the_standard_vectors() {
// hlx:863
assert_eq!(
hex(&sha256(b"")),
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
);
// hlx:864
assert_eq!(
hex(&sha256(b"abc")),
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
);
// hlx:865
assert_eq!(
// hlx:866
hex(&sha256(
b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"
)),
// hlx:867
"248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1" // hlx:868
);
// hlx:869
assert_eq!(
hex(&sha256(&vec![b'a'; 1_000_000])),
"cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0"
);
// hlx:870
// the framing is exactly as documented: tag, big-endian u64 length, bytes
// hlx:871
let mut v = Vec::new();
// hlx:872
enc(&J::Str("ab".into()), &mut v);
// hlx:873
assert_eq!(v, [3, 0, 0, 0, 0, 0, 0, 0, 2, b'a', b'b']);
// hlx:874
let mut v = Vec::new();
// hlx:875
enc(
&J::Obj(vec![
("b".into(), J::Bool(true)),
("a".into(), J::Num("1".into())),
]),
&mut v,
);
// hlx:876
assert_eq!(
v,
[
5, 0, 0, 0, 0, 0, 0, 0, 2, 3, 0, 0, 0, 0, 0, 0, 0, 1, b'a', 2, 0, 0, 0, 0, 0, 0, 0, 1,
b'1', 3, 0, 0, 0, 0, 0, 0, 0, 1, b'b', 1, 1
]
);
// hlx:877
}
// hlx:878
// ================================================================ receipts
// hlx:879
#[test]
// hlx:880
fn a_receipt_has_exactly_the_documented_keys_and_digests_that_match_the_independent_oracle() {
// hlx:881
let env = Env::new("receipt");
// hlx:882
for (name, req) in corpus() {
// hlx:883
let m = make(&env, &req);
// hlx:884
assert!(is_hex64(&m.input) && is_hex64(&m.result), "{name}");
// hlx:885
assert_ne!(m.input, m.result, "{name}");
// hlx:886
}
// hlx:887
let m = make(&env, BASE);
// hlx:888
assert_eq!(sf(&m.receipt, "check_id"), "artifact-membership");
// hlx:889
assert_eq!(m.receipt.get("revision"), Some(&J::Num("1".into())));
// hlx:890
assert_eq!(m.verdict, "fail");
// hlx:891
}
// hlx:892
#[test]
// hlx:893
fn receipts_are_deterministic_and_identical_from_file_stdin_and_other_machines() {
// hlx:894
let a = Env::new("det-a");
// hlx:895
let b = Env::new("det-b");
// hlx:896
for (name, req) in corpus() {
// hlx:897
let x = a.run("receipt", &req);
// hlx:898
assert_eq!(x.out, a.run("receipt", &req).out, "{name}");
// hlx:899
assert_eq!(x.out, b.run("receipt", &req).out, "{name}");
// hlx:900
let f = a.put("req.json", req.as_bytes());
// hlx:901
let y = a.exec(&["check", "receipt", "--input", f.to_str().unwrap()], b"");
// hlx:902
assert_eq!(x.out, y.out, "{name}: file == stdin");
// hlx:903
}
// hlx:904
}
// hlx:905
#[test]
// hlx:906
fn missing_evidence_gives_an_abstain_receipt_never_a_pass() {
// hlx:907
let env = Env::new("abstain");
// hlx:908
for (name, req) in corpus() {
// hlx:909
if !name.starts_with("abstain") {
// hlx:910
continue;
// hlx:911
}
// hlx:912
let m = make(&env, &req);
// hlx:913
assert_eq!(m.verdict, "abstain", "{name}");
// hlx:914
let o = env.run("replay", &replay_doc(&req, &ser(&m.receipt, false, false)));
// hlx:915
consistent(&o, "abstain", &m.input, &m.result);
// hlx:916
}
// hlx:917
}
// hlx:918
#[test]
// hlx:919
fn malformed_requests_and_output_limit_errors_are_structured_errors_not_receipts() {
// hlx:920
let env = Env::new("receipt-errors");
// hlx:921
let huge = "w".repeat(100_000);
// hlx:922
let bad: Vec<String> = vec![
// hlx:923
"".into(),
// hlx:924
"{".into(),
// hlx:925
"[]".into(),
// hlx:926
"{}".into(),
// hlx:927
mutate("\"op\":\"subset\"", "\"op\":\"nope\""),
// hlx:928
mutate("\"revision\":1", "\"revision\":0"),
// hlx:929
mutate("\"revision\":1", "\"revision\":1.0"),
// hlx:930
mutate("\"id\":\"artifact-membership\"", "\"id\":\"0bad\""),
// hlx:931
mutate(
"\"actual\":[\"release.bin\",\"scratch.env\"]",
"\"actual\":[\"a\",\"a\"]",
),
// hlx:932
mutate(
"\"actual\":[\"release.bin\",\"scratch.env\"]",
"\"actual\":\"a\"",
),
// hlx:933
mutate("\"facts\":{", "\"facts\":{\"ghost\":true,"),
// hlx:934
mutate("\"facts\":{", "\"facts\":{\"actual\":[],"),
// hlx:935
mutate(
"\"id\":\"artifact-membership\"",
"\"id\":\"artifact-membership\",\"\\u0069d\":\"x\"",
),
// hlx:936
mutate(
"\"complete-inventory\":true",
"\"complete-inventory\":\"true\"",
),
// hlx:937
mutate(
"\"project\":\"release-lab\"}},\"facts\"",
"\"env\":\"x\"}},\"facts\"",
),
// hlx:938
format!("{BASE} x"),
// hlx:939
set_doc("subset", "[\"\\ud800\"]", "[]"),
// hlx:940
// an output-limit error: the exact witness cannot fit
// hlx:941
set_doc("subset", &format!("[\"{huge}\"]"), "[]"),
// hlx:942
d("{\"a\":\"bool\"}", &op2("eq", "a", "a"))
.facts("{\"a\":true}")
.scope(&format!("{{\"project\":\"{}\"}}", "p".repeat(90_000)))
.json(),
// hlx:943
];
// hlx:944
for doc in &bad {
// hlx:945
let r = env.run("receipt", doc);
// hlx:946
err(&r, &format!("receipt {}", trunc(doc)));
// hlx:947
let run = env.run("run", doc);
// hlx:948
assert_eq!(
run.code,
Some(2),
"the kernel agrees that this request is an error: {}",
trunc(doc)
);
// hlx:949
let o = env.run(
"replay",
&replay_doc(doc, &ser(&make(&env, BASE).receipt, false, false)),
);
// hlx:950
err(&o, &format!("replay {}", trunc(doc)));
// hlx:951
}
// hlx:952
let mut padded = BASE.as_bytes().to_vec();
// hlx:953
padded.resize(1_048_576, b' ');
// hlx:954
assert_eq!(
env.run_bytes("receipt", &padded).code,
Some(0),
"exactly 1 MiB is accepted"
);
// hlx:955
padded.push(b' ');
// hlx:956
err(&env.run_bytes("receipt", &padded), "1 MiB + 1");
// hlx:957
let mut bytes = BASE.as_bytes().to_vec();
// hlx:958
bytes.splice(10..10, [0xffu8]);
// hlx:959
err(&env.run_bytes("receipt", &bytes), "invalid UTF-8");
// hlx:960
}
// hlx:961
// ================================================================ canonical identity
// hlx:962
#[test]
// hlx:963
fn key_order_set_order_whitespace_and_escapes_do_not_change_the_identity() {
// hlx:964
let env = Env::new("equiv");
// hlx:965
for (name, req) in [("contract", BASE.to_string()), ("rich", rich())] {
// hlx:966
let base = make(&env, &req);
// hlx:967
let tree = parse_json(&req).unwrap();
// hlx:968
let mut variants: Vec<(String, String)> = Vec::new();
// hlx:969
for mode in 0..3 {
// hlx:970
for (ws, ascii) in [(false, false), (true, false), (false, true), (true, true)] {
// hlx:971
variants.push((
format!("{name} mode {mode} ws={ws} ascii={ascii}"),
ser(&permute(&tree, mode), ws, ascii),
));
// hlx:972
}
// hlx:973
}
// hlx:974
for (label, v) in variants {
// hlx:975
let m = make(&env, &v);
// hlx:976
assert_eq!(m.input, base.input, "{label}: input identity");
// hlx:977
assert_eq!(
m.result, base.result,
"{label}: result identity (steps are telemetry, not identity)"
);
// hlx:978
assert_eq!(
ser(&m.receipt, false, false),
ser(&base.receipt, false, false),
"{label}"
);
// hlx:979
// a receipt made from the original replays against the permuted request and vice versa
// hlx:980
consistent(
&env.run("replay", &replay_doc(&v, &ser(&base.receipt, false, false))),
&base.verdict,
&base.input,
&base.result,
);
// hlx:981
consistent(
&env.run("replay", &replay_doc(&req, &ser(&m.receipt, true, true))),
&base.verdict,
&base.input,
&base.result,
);
// hlx:982
}
// hlx:983
}
// hlx:984
}
// hlx:985
#[test]
// hlx:986
fn omitted_defaults_equal_their_explicit_empty_forms() {
// hlx:987
let env = Env::new("defaults");
// hlx:988
let ins = "{\"a\":\"bool\",\"x\":\"set<string>\"}";
// hlx:989
let claim = op2("eq", "a", "a");
// hlx:990
let omitted = d(ins, &claim).json();
// hlx:991
let explicit = d(ins, &claim)
.req("[]")
.dscope("{}")
.facts("{}")
.conds("{}")
.scope("{}")
.json();
// hlx:992
let a = make(&env, &omitted);
// hlx:993
let b = make(&env, &explicit);
// hlx:994
assert_eq!((a.input.clone(), a.result.clone()), (b.input, b.result));
// hlx:995
assert_eq!(a.verdict, "abstain");
// hlx:996
// each default individually
// hlx:997
for variant in [
// hlx:998
d(ins, &claim).req("[]").json(),
// hlx:999
d(ins, &claim).dscope("{}").json(),
// hlx:1000
d(ins, &claim).facts("{}").json(),
// hlx:1001
d(ins, &claim).conds("{}").json(),
// hlx:1002
d(ins, &claim).scope("{}").json(),
// hlx:1003
] {
// hlx:1004
let m = make(&env, &variant);
// hlx:1005
assert_eq!(m.input, a.input, "{}", trunc(&variant));
// hlx:1006
}
// hlx:1007
// but an empty set is a supplied fact, not a missing one, and a false condition is not a missing one
// hlx:1008
let supplied = d(ins, &claim).facts("{\"x\":[]}").json();
// hlx:1009
assert_ne!(make(&env, &supplied).input, a.input);
// hlx:1010
let c_missing = d(ins, &claim).req("[\"c\"]").json();
// hlx:1011
let c_false = d(ins, &claim).req("[\"c\"]").conds("{\"c\":false}").json();
// hlx:1012
let c_true = d(ins, &claim).req("[\"c\"]").conds("{\"c\":true}").json();
// hlx:1013
let ids = [
make(&env, &c_missing).input,
make(&env, &c_false).input,
make(&env, &c_true).input,
];
// hlx:1014
assert!(
ids[0] != ids[1] && ids[1] != ids[2] && ids[0] != ids[2],
"missing, false and true conditions are three identities"
);
// hlx:1015
}
// hlx:1016
#[test]
// hlx:1017
fn every_semantic_change_alters_the_input_identity_even_when_the_verdict_stays_the_same() {
// hlx:1018
let env = Env::new("identity");
// hlx:1019
let allowed_a = "\"allowed\":[\"release.bin\"]},\"conditions\"";
// hlx:1020
let actual_a = "\"actual\":[\"release.bin\",\"scratch.env\"]";
// hlx:1021
let cond_a = "\"conditions\":{\"complete-inventory\":true,\"explicit-policy\":true}";
// hlx:1022
let req_a = "\"required_conditions\":[\"complete-inventory\",\"explicit-policy\"]";
// hlx:1023
let claim_a = "\"claim\":{\"op\":\"subset\",\"left\":{\"fact\":\"actual\"},\"right\":{\"fact\":\"allowed\"}}";
// hlx:1024
let scope_def = "\"scope\":{\"project\":\"release-lab\"}},\"facts\"";
// hlx:1025
let scope_req = "\"explicit-policy\":true},\"scope\":{\"project\":\"release-lab\"}}";
// hlx:1026
let variants: Vec<(&str, String)> = vec![
// hlx:1027
("base", BASE.to_string()),
// hlx:1028
("revision 2", mutate("\"revision\":1", "\"revision\":2")),
// hlx:1029
("revision 3", mutate("\"revision\":1", "\"revision\":3")),
// hlx:1030
("check id", mutate("\"id\":\"artifact-membership\"", "\"id\":\"artifact-membership2\"")),
// hlx:1031
("fact value, same verdict and witness", mutate(allowed_a, "\"allowed\":[\"release.bin\",\"zzz\"]},\"conditions\"")),
// hlx:1032
("fact value, other witness", mutate(actual_a, "\"actual\":[\"aaa\",\"release.bin\",\"scratch.env\"]")),
// hlx:1033
("fact missing", mutate(allowed_a, "},\"conditions\"").replace(",},\"conditions\"", "},\"conditions\"")),
// hlx:1034
("fact case", mutate(allowed_a, "\"allowed\":[\"Release.bin\"]},\"conditions\"")),
// hlx:1035
("fact trailing space", mutate(allowed_a, "\"allowed\":[\"release.bin \"]},\"conditions\"")),
// hlx:1036
("fact composed unicode", mutate(allowed_a, "\"allowed\":[\"release.bin\",\"\\u00e9\"]},\"conditions\"")),
// hlx:1037
("fact decomposed unicode", mutate(allowed_a, "\"allowed\":[\"release.bin\",\"e\\u0301\"]},\"conditions\"")),
// hlx:1038
("request scope extra dimension", mutate(scope_req, "\"explicit-policy\":true},\"scope\":{\"project\":\"release-lab\",\"persona\":\"p\"}}")),
// hlx:1039
("request and definition scope extra", mutate(scope_req, "\"explicit-policy\":true},\"scope\":{\"project\":\"release-lab\",\"persona\":\"p\"}}").replace(scope_def, "\"scope\":{\"project\":\"release-lab\",\"persona\":\"p\"}},\"facts\"")),
// hlx:1040
("scope value (both sides)", BASE.replace("release-lab", "release-lab-2")),
// hlx:1041
("scope value case", BASE.replace("release-lab", "Release-Lab")),
// hlx:1042
("condition false", mutate("\"complete-inventory\":true", "\"complete-inventory\":false")),
// hlx:1043
("condition missing", mutate("\"complete-inventory\":true,", "")),
// hlx:1044
("extra required condition", mutate(req_a, "\"required_conditions\":[\"complete-inventory\",\"explicit-policy\",\"third\"]").replace(cond_a, "\"conditions\":{\"complete-inventory\":true,\"explicit-policy\":true,\"third\":true}")),
// hlx:1045
("fewer required conditions", mutate(req_a, "\"required_conditions\":[\"complete-inventory\"]").replace(cond_a, "\"conditions\":{\"complete-inventory\":true}")),
// hlx:1046
("claim operands swapped", mutate(claim_a, "\"claim\":{\"op\":\"subset\",\"left\":{\"fact\":\"allowed\"},\"right\":{\"fact\":\"actual\"}}")),
// hlx:1047
("claim operator", mutate(claim_a, "\"claim\":{\"op\":\"disjoint\",\"left\":{\"fact\":\"actual\"},\"right\":{\"fact\":\"allowed\"}}")),
// hlx:1048
("claim wrapped in not(not())", mutate(claim_a, "\"claim\":{\"op\":\"not\",\"arg\":{\"op\":\"not\",\"arg\":{\"op\":\"subset\",\"left\":{\"fact\":\"actual\"},\"right\":{\"fact\":\"allowed\"}}}}")),
// hlx:1049
];
// hlx:1050
let mut seen: Vec<(String, &str)> = Vec::new();
// hlx:1051
let mut made: Vec<Made> = Vec::new();
// hlx:1052
for (name, req) in &variants {
// hlx:1053
let m = make(&env, req);
// hlx:1054
if let Some((_, other)) = seen.iter().find(|(d, _)| *d == m.input) {
// hlx:1055
panic!("{name} has the same input identity as {other}");
// hlx:1056
}
// hlx:1057
seen.push((m.input.clone(), name));
// hlx:1058
made.push(m);
// hlx:1059
}
// hlx:1060
// a receipt never replays as consistent against any other variant
// hlx:1061
let base = &made[0];
// hlx:1062
for ((name, req), _m) in variants.iter().zip(made.iter()).skip(1) {
// hlx:1063
let o = env.run(
"replay",
&replay_doc(req, &ser(&base.receipt, false, false)),
);
// hlx:1064
mismatch(&o, &[&base.input, &base.result], name);
// hlx:1065
}
// hlx:1066
// the same verdict and witness with different facts: equal result identity, different input identity
// hlx:1067
let same = &made[4];
// hlx:1068
assert_eq!(same.verdict, base.verdict);
// hlx:1069
assert_eq!(
same.result, base.result,
"result identity excludes steps and raw facts"
);
// hlx:1070
assert_ne!(same.input, base.input);
// hlx:1071
// changes that alter the decision alter the result identity
// hlx:1072
for i in [1usize, 2, 3, 5, 6, 11, 14, 15, 16, 19, 20] {
// hlx:1073
assert_ne!(made[i].result, base.result, "{}", variants[i].0);
// hlx:1074
}
// hlx:1075
}
// hlx:1076
#[test]
// hlx:1077
fn ordered_logic_is_part_of_the_identity() {
// hlx:1078
let env = Env::new("ordered");
// hlx:1079
let ins = "{\"one\":\"bool\",\"zero\":\"bool\"}";
// hlx:1080
let t = op2("eq", "one", "one");
// hlx:1081
let f = op2("eq", "one", "zero");
// hlx:1082
let facts = "{\"one\":true,\"zero\":false}";
// hlx:1083
let mk = |claim: String| make(&env, &d(ins, &claim).facts(facts).json());
// hlx:1084
let tf = mk(all_of(&[t.clone(), f.clone()]));
// hlx:1085
let ft = mk(all_of(&[f.clone(), t.clone()]));
// hlx:1086
let tf_any = mk(any_of(&[t.clone(), f.clone()]));
// hlx:1087
let ft_any = mk(any_of(&[f.clone(), t.clone()]));
// hlx:1088
assert_eq!(tf.verdict, ft.verdict, "same verdict");
// hlx:1089
assert_ne!(
tf.input, ft.input,
"all[T,F] and all[F,T] are different definitions"
);
// hlx:1090
assert_ne!(tf_any.input, ft_any.input);
// hlx:1091
assert_ne!(tf.input, tf_any.input);
// hlx:1092
// but permuting keys inside the same ordered logic keeps the identity
// hlx:1093
let doc = d(ins, &all_of(&[t.clone(), f.clone()])).facts(facts).json();
// hlx:1094
let v = ser(&permute(&parse_json(&doc).unwrap(), 0), false, false);
// hlx:1095
assert_eq!(make(&env, &v).input, tf.input);
// hlx:1096
// the order of args survives permutation of everything else
// hlx:1097
let v1 = ser(
&permute(
&parse_json(&d(ins, &all_of(&[f.clone(), t.clone()])).facts(facts).json()).unwrap(),
1,
),
false,
false,
);
// hlx:1098
assert_eq!(make(&env, &v1).input, ft.input);
// hlx:1099
}
// hlx:1100
#[test]
// hlx:1101
fn unicode_values_are_exact_and_no_extra_normalization_happens() {
// hlx:1102
let env = Env::new("unicode-id");
// hlx:1103
let mk = |s: &str| {
make(
&env,
&d("{\"s\":\"string\"}", &op2("eq", "s", "s"))
.facts(&format!("{{\"s\":\"{s}\"}}"))
.json(),
)
.input
};
// hlx:1104
let composed = mk("\\u00e9");
// hlx:1105
assert_eq!(
composed,
mk("\u{e9}"),
"an escape and the raw character are the same scalar"
);
// hlx:1106
assert_ne!(
composed,
mk("e\\u0301"),
"composed and decomposed are different"
);
// hlx:1107
assert_ne!(mk("a"), mk("A"));
// hlx:1108
assert_ne!(mk("a"), mk("a "));
// hlx:1109
assert_ne!(mk("a b"), mk("a b"));
// hlx:1110
assert_ne!(mk("a\\nb"), mk("a b"));
// hlx:1111
assert_ne!(mk("a/b"), mk("a\\\\b"));
// hlx:1112
assert_ne!(mk("a/b"), mk("a//b"));
// hlx:1113
assert_eq!(mk("a\\/b"), mk("a/b"));
// hlx:1114
assert_eq!(mk("\\ud83d\\ude00"), mk("\u{1F600}"));
// hlx:1115
assert_ne!(mk(""), mk(" "));
// hlx:1116
// set members sort in Unicode scalar order whatever their spelling or position
// hlx:1117
let mkset = |items: &str| make(&env, &set_doc("subset", items, "[]")).input;
// hlx:1118
let one = mkset("[\"\\u00e9\",\"z\",\"\\ud83d\\ude00\",\"A\",\"a\"]");
// hlx:1119
assert_eq!(one, mkset("[\"a\",\"A\",\"\u{1F600}\",\"z\",\"\u{e9}\"]"));
// hlx:1120
assert_eq!(
one,
mkset("[\"\\ud83d\\ude00\",\"\\u00e9\",\"a\",\"z\",\"A\"]")
);
// hlx:1121
assert_ne!(one, mkset("[\"\\u00e9\",\"z\",\"\\ud83d\\ude00\",\"A\"]"));
// hlx:1122
// int identities are the exact canonical strings
// hlx:1123
let mki = |a: &str| {
make(
&env,
&d("{\"n\":\"int\"}", &op2("eq", "n", "n"))
.facts(&format!("{{\"n\":\"{a}\"}}"))
.json(),
)
.input
};
// hlx:1124
assert_ne!(mki("9007199254740992"), mki("9007199254740993"));
// hlx:1125
assert_ne!(mki("1"), mki("-1"));
// hlx:1126
assert_ne!(mki("0"), mki("1"));
// hlx:1127
}
// hlx:1128
// ================================================================ replay
// hlx:1129
#[test]
// hlx:1130
fn replay_of_a_matching_receipt_is_consistent_and_says_what_it_does_not_prove() {
// hlx:1131
let env = Env::new("replay-ok");
// hlx:1132
for (name, req) in corpus() {
// hlx:1133
let m = make(&env, &req);
// hlx:1134
let doc = replay_doc(&req, &ser(&m.receipt, false, false));
// hlx:1135
let o = env.run("replay", &doc);
// hlx:1136
consistent(&o, &m.verdict, &m.input, &m.result);
// hlx:1137
let t = o.text();
// hlx:1138
for bad in [
"safe_to_release",
"signature",
"authenticated",
"adapter_observed",
"\"witness\"",
"\"facts\"",
] {
// hlx:1139
assert!(!t.contains(bad), "{name}: {bad}");
// hlx:1140
}
// hlx:1141
// a receipt written by the independent oracle (not by the CLI) is consistent too
// hlx:1142
let forged = format!(
// hlx:1143
"{{\"schema\":\"instinct.check-receipt/v1\",\"verifier\":\"instinct.check-kernel/v1\",\"check_id\":{},\"revision\":{},\"input_sha256\":\"{}\",\"result_sha256\":\"{}\",\"verdict\":\"{}\",\"authorization\":\"not_evaluated\",\"evidence_origin\":\"caller_reported\"}}",
// hlx:1144
esc_str(sf(&m.receipt, "check_id"), false),
// hlx:1145
to_s(m.receipt.get("revision").unwrap()),
// hlx:1146
m.input,
// hlx:1147
m.result,
// hlx:1148
m.verdict
// hlx:1149
);
// hlx:1150
consistent(
&env.run("replay", &replay_doc(&req, &forged)),
&m.verdict,
&m.input,
&m.result,
);
// hlx:1151
// spelling of the envelope and of the receipt does not matter
// hlx:1152
let pretty = format!(
"{{\n \"receipt\" : {},\n \"request\" : {}\n}}",
ser(&m.receipt, true, true),
ser(&parse_json(&req).unwrap(), true, true)
);
// hlx:1153
consistent(&env.run("replay", &pretty), &m.verdict, &m.input, &m.result);
// hlx:1154
let f = env.put("replay.json", doc.as_bytes());
// hlx:1155
let via_file = env.exec(&["check", "replay", "--input", f.to_str().unwrap()], b"");
// hlx:1156
assert_eq!(via_file.out, o.out, "{name}: file == stdin");
// hlx:1157
assert_eq!(env.run("replay", &doc).out, o.out, "{name}: deterministic");
// hlx:1158
}
// hlx:1159
// a receipt for changed facts that was recomputed is legitimately consistent: replay is not authentication
// hlx:1160
let changed = mutate(
"\"allowed\":[\"release.bin\"]",
"\"allowed\":[\"release.bin\",\"scratch.env\"]",
);
// hlx:1161
let m = make(&env, &changed);
// hlx:1162
consistent(
&env.run(
"replay",
&replay_doc(&changed, &ser(&m.receipt, false, false)),
),
"pass",
&m.input,
&m.result,
);
// hlx:1163
}
// hlx:1164
#[test]
// hlx:1165
fn any_one_byte_digest_mutation_forgery_or_changed_request_is_a_mismatch_never_consistent() {
// hlx:1166
let env = Env::new("replay-bad");
// hlx:1167
let m = make(&env, BASE);
// hlx:1168
let r = &m.receipt;
// hlx:1169
let set = |k: &str, v: J| -> String {
// hlx:1170
let mut o = match r {
// hlx:1171
J::Obj(kv) => kv.clone(),
// hlx:1172
_ => unreachable!(),
// hlx:1173
};
// hlx:1174
for e in o.iter_mut() {
// hlx:1175
if e.0 == k {
// hlx:1176
e.1 = v.clone();
// hlx:1177
}
// hlx:1178
}
// hlx:1179
ser(&J::Obj(o), false, false)
// hlx:1180
};
// hlx:1181
let forbid: Vec<&str> = vec![];
// hlx:1182
// flip each hex digit of each digest
// hlx:1183
for k in ["input_sha256", "result_sha256"] {
// hlx:1184
let orig = sf(r, k).to_string();
// hlx:1185
for i in 0..64 {
// hlx:1186
let mut b = orig.clone().into_bytes();
// hlx:1187
b[i] = if b[i] == b'0' { b'1' } else { b'0' };
// hlx:1188
let mutated = String::from_utf8(b).unwrap();
// hlx:1189
let o = env.run(
"replay",
&replay_doc(BASE, &set(k, J::Str(mutated.clone()))),
);
// hlx:1190
mismatch(&o, &[&mutated, &orig], &format!("{k}[{i}]"));
// hlx:1191
}
// hlx:1192
}
// hlx:1193
// forged fields on an otherwise valid receipt
// hlx:1194
let forged: Vec<(&str, String)> = vec![
// hlx:1195
("verdict pass", set("verdict", J::Str("pass".into()))),
// hlx:1196
("verdict abstain", set("verdict", J::Str("abstain".into()))),
// hlx:1197
("check_id", set("check_id", J::Str("other-check".into()))),
// hlx:1198
("revision 2", set("revision", J::Num("2".into()))),
// hlx:1199
(
"revision 2147483647",
set("revision", J::Num("2147483647".into())),
),
// hlx:1200
(
"input digest zeros",
set("input_sha256", J::Str("0".repeat(64))),
),
// hlx:1201
(
"result digest ffs",
set("result_sha256", J::Str("f".repeat(64))),
),
// hlx:1202
("digests swapped", {
// hlx:1203
let mut o = match r {
// hlx:1204
J::Obj(kv) => kv.clone(),
// hlx:1205
_ => unreachable!(),
// hlx:1206
};
// hlx:1207
let (a, b) = (
sf(r, "input_sha256").to_string(),
sf(r, "result_sha256").to_string(),
);
// hlx:1208
for e in o.iter_mut() {
// hlx:1209
if e.0 == "input_sha256" {
// hlx:1210
e.1 = J::Str(b.clone());
// hlx:1211
}
// hlx:1212
if e.0 == "result_sha256" {
// hlx:1213
e.1 = J::Str(a.clone());
// hlx:1214
}
// hlx:1215
}
// hlx:1216
ser(&J::Obj(o), false, false)
// hlx:1217
}),
// hlx:1218
];
// hlx:1219
for (name, rc) in &forged {
// hlx:1220
mismatch(
&env.run("replay", &replay_doc(BASE, rc)),
&["other-check", &m.input, &m.result],
name,
);
// hlx:1221
}
// hlx:1222
// a receipt for one request replayed against another
// hlx:1223
let other = mutate(
"\"allowed\":[\"release.bin\"]",
"\"allowed\":[\"release.bin\",\"zzz\"]",
);
// hlx:1224
mismatch(
&env.run("replay", &replay_doc(&other, &ser(r, false, false))),
&[&m.input, &m.result],
"different facts, same verdict",
);
// hlx:1225
let other_rev = mutate("\"revision\":1", "\"revision\":2");
// hlx:1226
mismatch(
&env.run("replay", &replay_doc(&other_rev, &ser(r, false, false))),
&[&m.input, &m.result],
"different revision",
);
// hlx:1227
// a receipt for a different check whose digests and verdict are right but whose id differs
// hlx:1228
let renamed = mutate("\"id\":\"artifact-membership\"", "\"id\":\"renamed\"");
// hlx:1229
mismatch(
&env.run("replay", &replay_doc(&renamed, &ser(r, false, false))),
&["renamed", &m.input],
"different id",
);
// hlx:1230
let _ = forbid;
// hlx:1231
}
// hlx:1232
#[test]
// hlx:1233
fn malformed_receipts_and_envelopes_are_errors_not_mismatches() {
// hlx:1234
let env = Env::new("replay-malformed");
// hlx:1235
let m = make(&env, BASE);
// hlx:1236
let r = ser(&m.receipt, false, false);
// hlx:1237
let kv = match &m.receipt {
// hlx:1238
J::Obj(kv) => kv.clone(),
// hlx:1239
_ => unreachable!(),
// hlx:1240
};
// hlx:1241
let with = |k: &str, v: Option<J>| -> String {
// hlx:1242
let mut o: Vec<(String, J)> = kv.iter().filter(|(n, _)| n != k).cloned().collect();
// hlx:1243
if let Some(v) = v {
// hlx:1244
o.push((k.to_string(), v));
// hlx:1245
}
// hlx:1246
ser(&J::Obj(o), false, false)
// hlx:1247
};
// hlx:1248
let mut bad: Vec<(String, String)> = Vec::new();
// hlx:1249
for (k, _) in &kv {
// hlx:1250
bad.push((format!("missing {k}"), with(k, None)));
// hlx:1251
bad.push((format!("{k} null"), with(k, Some(J::Null))));
// hlx:1252
bad.push((format!("{k} array"), with(k, Some(J::Arr(vec![])))));
// hlx:1253
bad.push((format!("{k} object"), with(k, Some(J::Obj(vec![])))));
// hlx:1254
bad.push((format!("{k} bool"), with(k, Some(J::Bool(true)))));
// hlx:1255
}
// hlx:1256
for (name, k, v) in [
// hlx:1257
(
"schema v2",
"schema",
J::Str("instinct.check-receipt/v2".into()),
),
// hlx:1258
(
"schema other",
"schema",
J::Str("instinct.check-result/v1".into()),
),
// hlx:1259
("schema empty", "schema", J::Str("".into())),
// hlx:1260
(
"schema case",
"schema",
J::Str("Instinct.check-receipt/v1".into()),
),
// hlx:1261
(
"verifier v2",
"verifier",
J::Str("instinct.check-kernel/v2".into()),
),
// hlx:1262
("verifier other", "verifier", J::Str("someone-else".into())),
// hlx:1263
("verifier empty", "verifier", J::Str("".into())),
// hlx:1264
(
"authorization granted",
"authorization",
J::Str("granted".into()),
),
// hlx:1265
(
"authorization allowed",
"authorization",
J::Str("allowed".into()),
),
// hlx:1266
("authorization empty", "authorization", J::Str("".into())),
// hlx:1267
(
"origin adapter_observed",
"evidence_origin",
J::Str("adapter_observed".into()),
),
// hlx:1268
(
"origin observed",
"evidence_origin",
J::Str("observed".into()),
),
// hlx:1269
(
"origin world",
"evidence_origin",
J::Str("world_verified".into()),
),
// hlx:1270
("verdict error", "verdict", J::Str("error".into())),
// hlx:1271
("verdict PASS", "verdict", J::Str("PASS".into())),
// hlx:1272
("verdict empty", "verdict", J::Str("".into())),
// hlx:1273
("verdict true", "verdict", J::Bool(true)),
// hlx:1274
("id number", "check_id", J::Num("7".into())),
// hlx:1275
("revision string", "revision", J::Str("1".into())),
// hlx:1276
("revision zero", "revision", J::Num("0".into())),
// hlx:1277
("revision negative", "revision", J::Num("-1".into())),
// hlx:1278
("revision too big", "revision", J::Num("2147483648".into())),
// hlx:1279
("revision float", "revision", J::Num("1.0".into())),
// hlx:1280
("revision exponent", "revision", J::Num("1e0".into())),
// hlx:1281
("revision leading zero", "revision", J::Num("01".into())),
// hlx:1282
("input digest short", "input_sha256", J::Str("a".repeat(63))),
// hlx:1283
("input digest long", "input_sha256", J::Str("a".repeat(65))),
// hlx:1284
("input digest empty", "input_sha256", J::Str("".into())),
// hlx:1285
(
"input digest uppercase",
"input_sha256",
J::Str(sf(&m.receipt, "input_sha256").to_uppercase()),
),
// hlx:1286
(
"input digest non-hex",
"input_sha256",
J::Str("g".repeat(64)),
),
// hlx:1287
(
"input digest with prefix",
"input_sha256",
J::Str(format!("sha256:{}", &sf(&m.receipt, "input_sha256")[..57])),
),
// hlx:1288
(
"input digest padded",
"input_sha256",
J::Str(format!(" {}", &sf(&m.receipt, "input_sha256")[..63])),
),
// hlx:1289
(
"result digest short",
"result_sha256",
J::Str("a".repeat(63)),
),
// hlx:1290
(
"result digest uppercase",
"result_sha256",
J::Str(sf(&m.receipt, "result_sha256").to_uppercase()),
),
// hlx:1291
(
"result digest non-hex",
"result_sha256",
J::Str("z".repeat(64)),
),
// hlx:1292
("result digest number", "result_sha256", J::Num("0".into())),
// hlx:1293
] {
// hlx:1294
bad.push((name.to_string(), with(k, Some(v))));
// hlx:1295
}
// hlx:1296
bad.push(("unknown key".into(), r.replacen('{', "{\"extra\":1,", 1)));
// hlx:1297
bad.push((
"signature key".into(),
r.replacen('{', "{\"signature\":\"abc\",", 1),
));
// hlx:1298
bad.push((
"witness key".into(),
r.replacen('{', "{\"witness\":\"x\",", 1),
));
// hlx:1299
bad.push(("scope key".into(), r.replacen('{', "{\"scope\":{},", 1)));
// hlx:1300
bad.push((
"duplicate schema".into(),
r.replacen('{', "{\"schema\":\"instinct.check-receipt/v1\",", 1),
));
// hlx:1301
bad.push((
"duplicate escaped".into(),
r.replacen('{', "{\"sch\\u0065ma\":\"instinct.check-receipt/v1\",", 1),
));
// hlx:1302
bad.push((
"duplicate digest".into(),
r.replacen(
'{',
&format!("{{\"input_sha256\":\"{}\",", sf(&m.receipt, "input_sha256")),
1,
),
));
// hlx:1303
bad.push((
"duplicate escaped id".into(),
r.replacen('{', "{\"check\\u005fid\":\"artifact-membership\",", 1),
));
// hlx:1304
bad.push(("not an object: array".into(), "[]".into()));
// hlx:1305
bad.push(("not an object: string".into(), "\"receipt\"".into()));
// hlx:1306
bad.push(("not an object: null".into(), "null".into()));
// hlx:1307
bad.push(("empty object".into(), "{}".into()));
// hlx:1308
bad.push(("truncated".into(), r[..r.len() - 1].to_string()));
// hlx:1309
bad.push(("trailing garbage".into(), format!("{r} x")));
// hlx:1310
for (name, rc) in &bad {
// hlx:1311
let o = env.run("replay", &replay_doc(BASE, rc));
// hlx:1312
err(&o, name);
// hlx:1313
assert!(
!o.text().contains("\"consistent\"") && !o.text().contains("\"mismatch\""),
"{name}"
);
// hlx:1314
}
// hlx:1315
// envelope shape
// hlx:1316
let envelope_bad: Vec<(&str, String)> = vec![
// hlx:1317
("missing receipt", format!("{{\"request\":{BASE}}}")),
// hlx:1318
("missing request", format!("{{\"receipt\":{r}}}")),
// hlx:1319
(
"extra key",
format!("{{\"request\":{BASE},\"receipt\":{r},\"extra\":1}}"),
),
// hlx:1320
(
"extra key root",
format!("{{\"request\":{BASE},\"receipt\":{r},\"root\":\"/tmp\"}}"),
),
// hlx:1321
(
"duplicate request",
format!("{{\"request\":{BASE},\"request\":{BASE},\"receipt\":{r}}}"),
),
// hlx:1322
(
"duplicate receipt",
format!("{{\"request\":{BASE},\"receipt\":{r},\"receipt\":{r}}}"),
),
// hlx:1323
(
"duplicate escaped",
format!("{{\"request\":{BASE},\"receipt\":{r},\"rec\\u0065ipt\":{r}}}"),
),
// hlx:1324
(
"request null",
format!("{{\"request\":null,\"receipt\":{r}}}"),
),
// hlx:1325
(
"receipt null",
format!("{{\"request\":{BASE},\"receipt\":null}}"),
),
// hlx:1326
(
"request string",
format!("{{\"request\":\"x\",\"receipt\":{r}}}"),
),
// hlx:1327
(
"receipt string",
format!("{{\"request\":{BASE},\"receipt\":\"x\"}}"),
),
// hlx:1328
("array envelope", format!("[{BASE},{r}]")),
// hlx:1329
("bare request", BASE.to_string()),
// hlx:1330
("bare receipt", r.clone()),
// hlx:1331
("empty", String::new()),
// hlx:1332
(
"invalid request inside",
replay_doc(&mutate("\"op\":\"subset\"", "\"op\":\"nope\""), &r),
),
// hlx:1333
(
"duplicate key inside request",
replay_doc(
&mutate(
"\"id\":\"artifact-membership\"",
"\"id\":\"artifact-membership\",\"id\":\"x\"",
),
&r,
),
),
// hlx:1334
];
// hlx:1335
for (name, doc) in &envelope_bad {
// hlx:1336
err(&env.run("replay", doc), name);
// hlx:1337
}
// hlx:1338
// REVISION NOTE (docs/check-receipt-clarifications.md): the replay envelope alone may carry 1 MiB + 4096 bytes.
// hlx:1339
// The original expectation "1 MiB + 1 is an error" applied to the envelope; it now applies at 1 MiB + 4096 + 1.
// hlx:1340
let mut padded = replay_doc(BASE, &r).into_bytes();
// hlx:1341
padded.resize(1_048_576, b' ');
// hlx:1342
consistent(
&env.run_bytes("replay", &padded),
"fail",
&m.input,
&m.result,
);
// hlx:1343
padded.resize(1_048_576 + 4096, b' ');
// hlx:1344
consistent(
&env.run_bytes("replay", &padded),
"fail",
&m.input,
&m.result,
);
// hlx:1345
padded.push(b' ');
// hlx:1346
err(
&env.run_bytes("replay", &padded),
"envelope over 1 MiB + 4096",
);
// hlx:1347
}
// hlx:1348
// ================================================================ privacy, authority and isolation
// hlx:1349
#[test]
// hlx:1350
fn receipts_and_replays_never_echo_facts_witnesses_scope_or_paths() {
// hlx:1351
let env = Env::new("privacy");
// hlx:1352
let s = "SECRET_SENTINEL_731";
// hlx:1353
let ins = "{\"actual\":\"set<string>\",\"allowed\":\"set<string>\",\"note\":\"string\"}";
// hlx:1354
let req = d(ins, &op2("subset", "actual", "allowed"))
// hlx:1355
.id("\"public-check-id\"")
// hlx:1356
.dscope(&format!("{{\"project\":\"{s}-proj\"}}"))
// hlx:1357
.facts(&format!("{{\"actual\":[\"{s}-member\",\"/home/user/{s}/path\"],\"allowed\":[],\"note\":\"{s}-note\"}}"))
// hlx:1358
.scope(&format!("{{\"project\":\"{s}-proj\",\"persona\":\"{s}-persona\"}}"))
// hlx:1359
.json();
// hlx:1360
let m = make(&env, &req);
// hlx:1361
assert_eq!(m.verdict, "fail");
// hlx:1362
let run = env.run("run", &req).text();
// hlx:1363
assert!(
run.contains(s),
"the kernel result itself carries the witness; the receipt must not"
);
// hlx:1364
let rc_text = env.run("receipt", &req).text();
// hlx:1365
assert!(
!rc_text.contains(s) && !rc_text.contains("/home/user"),
"{rc_text}"
);
// hlx:1366
assert!(
rc_text.contains("public-check-id"),
"the public check id is the one allowed identifier"
);
// hlx:1367
let good = replay_doc(&req, &ser(&m.receipt, false, false));
// hlx:1368
assert!(!env.run("replay", &good).text().contains(s));
// hlx:1369
let other = req.replace(&format!("{s}-note"), "changed");
// hlx:1370
let o = env.run(
"replay",
&replay_doc(&other, &ser(&m.receipt, false, false)),
);
// hlx:1371
mismatch(&o, &[s, "/home/user", &m.input, &m.result], "changed note");
// hlx:1372
// errors do not echo the request either
// hlx:1373
let broken = req.replace("\"allowed\":[]", &format!("\"allowed\":\"{s}\""));
// hlx:1374
for sub in ["receipt", "replay"] {
// hlx:1375
let doc = if sub == "receipt" {
broken.clone()
} else {
replay_doc(&broken, &ser(&m.receipt, false, false))
};
// hlx:1376
let o = env.run(sub, &doc);
// hlx:1377
err(&o, sub);
// hlx:1378
assert!(!o.text().contains(s), "{sub}: {}", trunc(&o.text()));
// hlx:1379
}
// hlx:1380
}
// hlx:1381
#[test]
// hlx:1382
fn authority_and_origin_are_fixed_and_the_environment_never_changes_a_receipt() {
// hlx:1383
let env = Env::new("authority");
// hlx:1384
for (name, req) in corpus() {
// hlx:1385
let m = make(&env, &req);
// hlx:1386
assert_eq!(sf(&m.receipt, "authorization"), "not_evaluated", "{name}");
// hlx:1387
assert_eq!(
sf(&m.receipt, "evidence_origin"),
"caller_reported",
"{name}"
);
// hlx:1388
}
// hlx:1389
let doc = d("{\"a\":\"bool\"}", &op2("eq", "a", "a"))
.facts("{\"a\":true}")
.dscope("{\"project\":\"release-lab\"}")
.json();
// hlx:1390
let plain = env.run("receipt", &doc);
// hlx:1391
let envs = [
("INSTINCT_PROJECT", "release-lab"),
("INSTINCT_PERSONA", "p"),
("INSTINCT_HARNESS", "h"),
("INSTINCT_MACHINE", "m"),
("PWD", "/"),
];
// hlx:1392
let with = env.exec_env(&["check", "receipt", "--input", "-"], doc.as_bytes(), &envs);
// hlx:1393
assert_eq!(plain.out, with.out, "no ambient scope");
// hlx:1394
assert_eq!(
sf(&rcpt(&plain), "verdict"),
"abstain",
"the definition requires a project that was not supplied"
);
// hlx:1395
let r = rcpt(&with);
// hlx:1396
assert_eq!(sf(&r, "verdict"), "abstain");
// hlx:1397
// the kernel's own run output still says caller_reported
// hlx:1398
assert_eq!(
sf(&result(&env.run("run", &doc)), "evidence_origin"),
"caller_reported"
);
// hlx:1399
}
// hlx:1400
#[test]
// hlx:1401
fn receipt_and_replay_write_nothing_and_leave_a_bank_alone() {
// hlx:1402
let env = Env::new("nowrites");
// hlx:1403
std::fs::create_dir_all(env.bank().parent().unwrap()).unwrap();
// hlx:1404
std::fs::write(env.bank(), b"\xff\xfenot a bank").unwrap();
// hlx:1405
let m = make(&env, BASE);
// hlx:1406
let r = ser(&m.receipt, false, false);
// hlx:1407
for doc in [BASE.to_string(), "{".to_string()] {
// hlx:1408
let _ = env.run("receipt", &doc);
// hlx:1409
}
// hlx:1410
for doc in [
replay_doc(BASE, &r),
replay_doc(BASE, "{}"),
"{".to_string(),
] {
// hlx:1411
let _ = env.run("replay", &doc);
// hlx:1412
}
// hlx:1413
assert_eq!(std::fs::read(env.bank()).unwrap(), b"\xff\xfenot a bank");
// hlx:1414
// INSTINCT_STORE pointing nowhere does not matter and nothing is created
// hlx:1415
let missing = env.root.join("elsewhere").join("bank.hxdb");
// hlx:1416
let o = env.exec_env(
&["check", "receipt", "--input", "-"],
BASE.as_bytes(),
&[("INSTINCT_STORE", missing.to_str().unwrap())],
);
// hlx:1417
assert_eq!(o.code, Some(0));
// hlx:1418
assert!(!missing.exists() && !missing.parent().unwrap().exists());
// hlx:1419
// the exec wrapper snapshots the whole tree around every call: no temp, sidecar, ledger or journal file appeared
// hlx:1420
}
// hlx:1421
// ================================================================ CLI shape
// hlx:1422
#[test]
// hlx:1423
fn receipt_and_replay_argument_mistakes_are_errors_and_help_is_side_effect_free() {
// hlx:1424
let env = Env::new("cli");
// hlx:1425
let f = env.put("req.json", BASE.as_bytes());
// hlx:1426
let f = f.to_str().unwrap();
// hlx:1427
for sub in ["receipt", "replay"] {
// hlx:1428
let rows: Vec<Vec<&str>> = vec![
// hlx:1429
vec!["check", sub],
// hlx:1430
vec!["check", sub, "--input"],
// hlx:1431
vec!["check", sub, "--input", f, "--input", f],
// hlx:1432
vec!["check", sub, "--input", "-", "--input", f],
// hlx:1433
vec!["check", sub, "--input", f, "extra"],
// hlx:1434
vec!["check", sub, f],
// hlx:1435
vec!["check", sub, "--bogus"],
// hlx:1436
vec!["check", sub, "--input", f, "--bogus"],
// hlx:1437
vec!["check", sub, "--root", f, "--input", f],
// hlx:1438
vec!["check", sub, "--Input", f],
// hlx:1439
vec!["check", sub, "-i", f],
// hlx:1440
vec!["check", sub, "--input", f, "--help"],
// hlx:1441
];
// hlx:1442
for row in rows {
// hlx:1443
let o = env.exec(&row, BASE.as_bytes());
// hlx:1444
err(&o, &format!("{row:?}"));
// hlx:1445
}
// hlx:1446
let o = env.exec(&["check", sub, "--help"], BASE.as_bytes());
// hlx:1447
assert_eq!(o.code, Some(0), "check {sub} --help: {}", trunc(&o.text()));
// hlx:1448
let all = format!("{}{}", o.text(), String::from_utf8_lossy(&o.err));
// hlx:1449
assert!(all.contains("--input"), "{sub}: {}", trunc(&all));
// hlx:1450
assert!(
!o.text().contains("check-receipt")
&& !o.text().contains("check-replay")
&& !o.text().contains("check-error"),
"help is not a result"
);
// hlx:1451
}
// hlx:1452
// the legacy commands keep their behavior
// hlx:1453
assert_eq!(env.run("run", BASE).code, Some(0));
// hlx:1454
assert_eq!(env.run("validate", BASE).code, Some(0));
// hlx:1455
assert_eq!(env.run("explain", BASE).code, Some(0));
// hlx:1456
err(
&env.exec(&["check", "run", "--input", f, "--input", f], b""),
"legacy duplicate",
);
// hlx:1457
}
// hlx:1458
// ================================================================ round-trip boundaries (docs/check-receipt-clarifications.md)
// hlx:1459
fn nested_all(k: usize) -> String {
// hlx:1460
let mut c = op2("eq", "a", "a");
// hlx:1461
for _ in 0..k {
// hlx:1462
c = all_of(&[c]);
// hlx:1463
}
// hlx:1464
d("{\"a\":\"bool\"}", &c).facts("{\"a\":true}").json()
// hlx:1465
}
// hlx:1466
// a compact request of exactly `total` bytes: one big set fact, a short string fact and a cheap claim
// hlx:1467
fn exact_size_request(total: usize) -> String {
// hlx:1468
let n = 9000usize;
// hlx:1469
let ins = "{\"actual\":\"set<string>\",\"z\":\"string\"}";
// hlx:1470
let claim = op2("contains", "actual", "z");
// hlx:1471
let mk = |members: &str| {
format!("{{\"check\":{{\"schema\":\"instinct.check/v1\",\"id\":\"big\",\"revision\":1,\"inputs\":{ins},\"claim\":{claim}}},\"facts\":{{\"actual\":[{members}],\"z\":\"m00001\"}}}}")
};
// hlx:1472
let base = mk("").len();
// hlx:1473
let per = (total - base - (n - 1)) / n - 2;
// hlx:1474
let member = |i: usize, len: usize| format!("\"m{i:05}{}\"", "x".repeat(len - 6));
// hlx:1475
let mut parts: Vec<String> = (0..n).map(|i| member(i, per)).collect();
// hlx:1476
let used = mk(&parts.join(",")).len();
// hlx:1477
let extra = total - used;
// hlx:1478
parts[n - 1] = member(n - 1, per + extra);
// hlx:1479
let doc = mk(&parts.join(","));
// hlx:1480
assert_eq!(doc.len(), total, "fixture builder");
// hlx:1481
doc
// hlx:1482
}
// hlx:1483
#[test]
// hlx:1484
fn a_valid_request_at_the_nesting_limit_round_trips_through_receipt_and_replay() {
// hlx:1485
let env = Env::new("roundtrip-depth");
// hlx:1486
// the request nesting limit is 64: 30 nested `all` is the deepest valid shape (the 29-level control is shallower)
// hlx:1487
for k in [0usize, 1, 10, 28, 29, 30] {
// hlx:1488
let req = nested_all(k);
// hlx:1489
let m = make(&env, &req);
// hlx:1490
assert_eq!(m.verdict, "pass", "k={k}");
// hlx:1491
let o = env.run("replay", &replay_doc(&req, &ser(&m.receipt, false, false)));
// hlx:1492
consistent(&o, "pass", &m.input, &m.result);
// hlx:1493
// spelled with whitespace and escapes too (whitespace does not count toward nesting)
// hlx:1494
let pretty = ser(&parse_json(&req).unwrap(), true, true);
// hlx:1495
consistent(
&env.run("replay", &replay_doc(&pretty, &ser(&m.receipt, true, true))),
"pass",
&m.input,
&m.result,
);
// hlx:1496
}
// hlx:1497
// one level deeper is not a valid request, so there is no receipt and replay cannot succeed either
// hlx:1498
let valid_receipt = ser(&make(&env, &nested_all(30)).receipt, false, false);
// hlx:1499
for k in [31usize, 32, 40] {
// hlx:1500
let req = nested_all(k);
// hlx:1501
err(&env.run("receipt", &req), &format!("receipt k={k}"));
// hlx:1502
err(&env.run("run", &req), &format!("run k={k}"));
// hlx:1503
err(
&env.run("replay", &replay_doc(&req, &valid_receipt)),
&format!("replay k={k}"),
);
// hlx:1504
}
// hlx:1505
// other operators at the same depth
// hlx:1506
let mut c = op2("eq", "a", "a");
// hlx:1507
for i in 0..30 {
// hlx:1508
c = if i % 2 == 0 {
any_of(&[c])
} else {
all_of(&[c])
};
// hlx:1509
}
// hlx:1510
let req = d("{\"a\":\"bool\"}", &c).facts("{\"a\":true}").json();
// hlx:1511
let m = make(&env, &req);
// hlx:1512
consistent(
&env.run("replay", &replay_doc(&req, &ser(&m.receipt, false, false))),
"pass",
&m.input,
&m.result,
);
// hlx:1513
}
// hlx:1514
#[test]
// hlx:1515
fn a_request_of_exactly_one_mebibyte_round_trips_and_one_byte_more_is_still_rejected() {
// hlx:1516
let env = Env::new("roundtrip-size");
// hlx:1517
let limit = 1_048_576usize;
// hlx:1518
let req = exact_size_request(limit);
// hlx:1519
assert_eq!(req.len(), limit);
// hlx:1520
let m = make(&env, &req);
// hlx:1521
let rc = ser(&m.receipt, false, false);
// hlx:1522
let doc = replay_doc(&req, &rc);
// hlx:1523
assert!(
doc.len() > limit && doc.len() <= limit + 4096,
"the envelope overhead is the receipt plus the wrapper: {}",
doc.len() - limit
);
// hlx:1524
let o = env.run("replay", &doc);
// hlx:1525
consistent(&o, &m.verdict, &m.input, &m.result);
// hlx:1526
// the same through files
// hlx:1527
let f = env.put("replay.json", doc.as_bytes());
// hlx:1528
assert_eq!(
env.exec(&["check", "replay", "--input", f.to_str().unwrap()], b"")
.out,
o.out
);
// hlx:1529
let rf = env.put("request.json", req.as_bytes());
// hlx:1530
assert_eq!(
env.exec(&["check", "receipt", "--input", rf.to_str().unwrap()], b"")
.code,
Some(0)
);
// hlx:1531
// inner request beyond 1 MiB errors on receipt and inside the larger envelope
// hlx:1532
let over = exact_size_request(limit + 1);
// hlx:1533
assert_eq!(over.len(), limit + 1);
// hlx:1534
err(&env.run("receipt", &over), "receipt over 1 MiB");
// hlx:1535
err(&env.run("run", &over), "run over 1 MiB");
// hlx:1536
let doc_over = replay_doc(&over, &rc);
// hlx:1537
assert!(
doc_over.len() <= limit + 4096,
"the envelope itself is within its own cap"
);
// hlx:1538
err(
&env.run("replay", &doc_over),
"inner request over 1 MiB inside a legal envelope",
);
// hlx:1539
err(
&env.run("replay", &replay_doc(&exact_size_request(limit + 64), &rc)),
"inner request over 1 MiB by 64 bytes",
);
// hlx:1540
// a legal request plus a legal receipt whose outer whitespace exceeds the envelope cap
// hlx:1541
let mut padded = doc.into_bytes();
// hlx:1542
padded.resize(limit + 4096, b' ');
// hlx:1543
assert_eq!(
env.run_bytes("replay", &padded).code,
Some(0),
"exactly at the envelope cap"
);
// hlx:1544
padded.push(b' ');
// hlx:1545
err(
&env.run_bytes("replay", &padded),
"envelope one byte over its cap",
);
// hlx:1546
}
// hlx:1547
#[test]
// hlx:1548
fn only_replay_gets_the_envelope_allowance_and_other_modes_keep_the_ordinary_cap() {
// hlx:1549
let env = Env::new("cap-scope");
// hlx:1550
let limit = 1_048_576usize;
// hlx:1551
for extra in [1usize, 100, 4096] {
// hlx:1552
let mut padded = BASE.as_bytes().to_vec();
// hlx:1553
padded.resize(limit + extra, b' ');
// hlx:1554
for sub in ["receipt", "run", "validate", "explain"] {
// hlx:1555
err(&env.run_bytes(sub, &padded), &format!("{sub} +{extra}"));
// hlx:1556
}
// hlx:1557
}
// hlx:1558
let mut padded = BASE.as_bytes().to_vec();
// hlx:1559
padded.resize(limit, b' ');
// hlx:1560
for sub in ["receipt", "run", "validate", "explain"] {
// hlx:1561
assert_eq!(
env.run_bytes(sub, &padded).code,
Some(0),
"{sub} at exactly 1 MiB"
);
// hlx:1562
}
// hlx:1563
}
// hlx:1564
#[test]
// hlx:1565
fn envelope_depth_allows_one_extra_level_and_no_more_and_deep_input_is_bounded() {
// hlx:1566
let env = Env::new("env-depth");
// hlx:1567
let m = make(&env, &nested_all(30));
// hlx:1568
let rc = ser(&m.receipt, false, false);
// hlx:1569
// request depth 64 + envelope = 65: accepted (also covered above); the receipt object adds no depth beyond 2
// hlx:1570
consistent(
&env.run("replay", &replay_doc(&nested_all(30), &rc)),
"pass",
&m.input,
&m.result,
);
// hlx:1571
// anything deeper than 65 in total is an error, whatever sits in the deep position, and never a crash
// hlx:1572
let head = format!("{{\"request\":{},\"receipt\":{rc},\"x\":", nested_all(30));
// hlx:1573
for n in [1usize, 2, 64, 65, 66, 1000, 100_000] {
// hlx:1574
for (open, close) in [("[", "]"), ("{\"k\":", "}")] {
// hlx:1575
let doc = format!("{head}{}0{}}}", open.repeat(n), close.repeat(n));
// hlx:1576
if doc.len() > 1_048_576 + 4096 {
// hlx:1577
continue;
// hlx:1578
}
// hlx:1579
let o = env.run("replay", &doc);
// hlx:1580
assert!(
o.code.is_some(),
"a signal killed the process at nesting {n}"
);
// hlx:1581
err(&o, &format!("extra key nested {n}"));
// hlx:1582
}
// hlx:1583
}
// hlx:1584
// a receipt stuffed with arbitrary payload cannot use the allowance: its exact schema is enforced
// hlx:1585
let mut stuffed = rc.clone();
// hlx:1586
stuffed.pop();
// hlx:1587
stuffed.push_str(&format!(",\"pad\":\"{}\"}}", "x".repeat(4000)));
// hlx:1588
err(
&env.run("replay", &replay_doc(&nested_all(30), &stuffed)),
"receipt with a padding field",
);
// hlx:1589
let long_id = "a".repeat(3000);
// hlx:1590
let mut long = m.receipt.clone();
// hlx:1591
if let J::Obj(kv) = &mut long {
// hlx:1592
for e in kv.iter_mut() {
// hlx:1593
if e.0 == "check_id" {
// hlx:1594
e.1 = J::Str(long_id.clone());
// hlx:1595
}
// hlx:1596
}
// hlx:1597
}
// hlx:1598
let o = env.run(
"replay",
&replay_doc(&nested_all(30), &ser(&long, false, false)),
);
// hlx:1599
assert!(
o.code == Some(2) || o.code == Some(0),
"{}",
trunc(&o.text())
);
// hlx:1600
if o.code == Some(0) {
// hlx:1601
mismatch(&o, &[&long_id], "long id");
// hlx:1602
} else {
// hlx:1603
err(&o, "long id");
// hlx:1604
}
// hlx:1605
// 29 levels still replays the ordinary way
// hlx:1606
let m29 = make(&env, &nested_all(29));
// hlx:1607
consistent(
&env.run(
"replay",
&replay_doc(&nested_all(29), &ser(&m29.receipt, false, false)),
),
"pass",
&m29.input,
&m29.result,
);
// hlx:1608
}