#[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
}
use super::json::{self, J};
use std::collections::{BTreeMap, BTreeSet};
pub const MAX_CLAIM_DEPTH: usize = 32;
pub const MAX_CLAIM_NODES: usize = 4096;
pub const MAX_FACT_ENTRIES: usize = 10000;
pub const MAX_STEPS: u64 = 100000;
pub const MAX_OUTPUT_BYTES: usize = 65536;
const MAX_LISTED: usize = 128;
const MAX_CLAIM_TEXT: usize = 16384;
const DIMS: [&str; 5] = ["project", "persona", "harness", "version", "machine"];
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Mode {
Validate,
Run,
Explain,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Ty {
Str,
Bool,
Int,
Set,
}
impl Ty {
fn name(self) -> &'static str {
match self {
Ty::Str => "string",
Ty::Bool => "bool",
Ty::Int => "int",
Ty::Set => "set<string>",
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Cmp {
Subset,
Disjoint,
Contains,
Eq,
Lt,
Lte,
}
impl Cmp {
fn name(self) -> &'static str {
match self {
Cmp::Subset => "subset",
Cmp::Disjoint => "disjoint",
Cmp::Contains => "contains",
Cmp::Eq => "eq",
Cmp::Lt => "lt",
Cmp::Lte => "lte",
}
}
}
#[derive(Debug)]
enum Node {
Cmp(Cmp, String, String),
All(Vec<Node>),
Any(Vec<Node>),
Not(Box<Node>),
}
#[derive(Debug)]
enum Val {
S(String),
B(bool),
I(i128),
Set(Vec<String>),
}
struct Def {
id: String,
revision: u32,
inputs: BTreeMap<String, Ty>,
claim: Node,
conditions: Vec<String>,
scope: Vec<(&'static str, String)>,
}
type R<T> = Result<T, String>;
fn clip(s: &str) -> String {
let mut out = String::new();
for ch in s.chars().take(48) {
if ch.is_control()
|| matches!(ch as u32, 0x00ad | 0x061c | 0x180e | 0x200b..=0x200f | 0x2028..=0x202e | 0x2060..=0x206f | 0xfeff | 0xfff9..=0xfffb | 0x1bca0..=0x1bca3 | 0x1d173..=0x1d17a | 0xe0001 | 0xe0020..=0xe007f)
{
out.push('?');
} else {
out.push(ch);
}
}
if s.chars().count() > 48 {
out.push_str("...");
}
out
}
fn is_ident(s: &str) -> bool {
let b = s.as_bytes();
!b.is_empty()
&& b.len() <= 128
&& b[0].is_ascii_alphabetic()
&& b.iter().all(|c| c.is_ascii_alphanumeric() || matches!(c, b'.' | b'_' | b'-'))
}
fn obj<'a>(j: &'a J, what: &str) -> R<&'a [(String, J)]> {
match j {
J::Obj(o) => Ok(o),
_ => Err(format!("malformed_definition: {what} must be an object")),
}
}
fn field<'a>(o: &'a [(String, J)], k: &str) -> Option<&'a J> {
o.iter().find(|(key, _)| key == k).map(|(_, v)| v)
}
fn only_keys(o: &[(String, J)], allowed: &[&str], what: &str) -> R<()> {
for (k, _) in o {
if !allowed.contains(&k.as_str()) {
return Err(format!(
"unknown_field: {what} has unknown key \"{}\"",
clip(k)
));
}
}
Ok(())
}
fn need<'a>(o: &'a [(String, J)], k: &str, what: &str) -> R<&'a J> {
field(o, k).ok_or_else(|| format!("malformed_definition: {what} requires \"{k}\""))
}
fn text<'a>(j: &'a J, what: &str) -> R<&'a str> {
match j {
J::Str(s) => Ok(s),
_ => Err(format!("malformed_definition: {what} must be a string")),
}
}
fn parse_scope(j: &J, what: &str) -> R<Vec<(&'static str, String)>> {
let o = obj(j, what)?;
only_keys(o, &DIMS, what)?;
let mut out = Vec::new();
for dim in DIMS {
if let Some(v) = field(o, dim) {
let s = text(v, what)?;
if s.is_empty() || s == "*" {
return Err(format!(
"invalid_scope: {what}.{dim} must be a nonempty literal, not \"*\""
));
}
out.push((dim, s.to_string()));
}
}
Ok(out)
}
fn canonical_int(s: &str) -> Option<i128> {
let digits = s.strip_prefix('-').unwrap_or(s);
if digits.is_empty() || !digits.bytes().all(|c| c.is_ascii_digit()) {
return None;
}
if digits.len() > 1 && digits.starts_with('0') {
return None;
}
if s.starts_with('-') && digits == "0" {
return None;
}
s.parse::<i128>().ok()
}
fn parse_ty(s: &str) -> R<Ty> {
match s {
"string" => Ok(Ty::Str),
"bool" => Ok(Ty::Bool),
"int" => Ok(Ty::Int),
"set<string>" => Ok(Ty::Set),
"rational" | "graph" => Err(format!(
"unsupported_feature: type \"{s}\" is not supported in this version"
)),
_ => Err(format!("invalid_type: unknown type \"{}\"", clip(s))),
}
}
fn operand(j: &J, inputs: &BTreeMap<String, Ty>, nodes: &mut usize) -> R<(String, Ty)> {
*nodes += 1;
if *nodes > MAX_CLAIM_NODES {
return Err("limit_exceeded: claim has more than 4096 nodes".to_string());
}
let o = obj(j, "operand")?;
only_keys(o, &["fact"], "operand")?;
let name = text(need(o, "fact", "operand")?, "operand fact")?;
match inputs.get(name) {
Some(t) => Ok((name.to_string(), *t)),
None => Err(format!(
"unknown_reference: fact \"{}\" is not declared in inputs",
clip(name)
)),
}
}
fn compile(j: &J, depth: usize, inputs: &BTreeMap<String, Ty>, nodes: &mut usize) -> R<Node> {
if depth > MAX_CLAIM_DEPTH {
return Err("limit_exceeded: claim is nested deeper than 32".to_string());
}
*nodes += 1;
if *nodes > MAX_CLAIM_NODES {
return Err("limit_exceeded: claim has more than 4096 nodes".to_string());
}
let o = obj(j, "claim expression")?;
let op = text(need(o, "op", "claim expression")?, "op")?;
let cmp = match op {
"subset" => Cmp::Subset,
"disjoint" => Cmp::Disjoint,
"contains" => Cmp::Contains,
"eq" => Cmp::Eq,
"lt" => Cmp::Lt,
"lte" => Cmp::Lte,
"all" | "any" => {
only_keys(o, &["op", "args"], op)?;
let args = match need(o, "args", op)? {
J::Arr(a) if !a.is_empty() => a,
_ => {
return Err(format!(
"malformed_definition: {op} args must be a nonempty array"
))
} };
let mut kids = Vec::new();
for a in args {
kids.push(compile(a, depth + 1, inputs, nodes)?);
}
return Ok(if op == "all" {
Node::All(kids)
} else {
Node::Any(kids)
});
}
"not" => {
only_keys(o, &["op", "arg"], op)?;
return Ok(Node::Not(Box::new(compile(
need(o, "arg", op)?,
depth + 1,
inputs,
nodes,
)?)));
}
_ => return Err(format!("unknown_operator: \"{}\"", clip(op))),
};
only_keys(o, &["op", "left", "right"], op)?;
let (l, lt) = operand(need(o, "left", op)?, inputs, nodes)?;
let (r, rt) = operand(need(o, "right", op)?, inputs, nodes)?;
let ok = match cmp {
Cmp::Subset | Cmp::Disjoint => lt == Ty::Set && rt == Ty::Set,
Cmp::Contains => lt == Ty::Set && rt == Ty::Str,
Cmp::Eq => lt == rt,
Cmp::Lt | Cmp::Lte => lt == Ty::Int && rt == Ty::Int,
};
if !ok {
return Err(format!(
"type_mismatch: {} cannot compare {} with {}",
op,
lt.name(),
rt.name()
));
}
Ok(Node::Cmp(cmp, l, r))
}
fn compile_def(j: &J) -> R<Def> {
let o = obj(j, "check")?;
only_keys(
o,
&[
"schema",
"id",
"revision",
"inputs",
"claim",
"required_conditions",
"scope",
],
"check",
)?;
let schema = text(need(o, "schema", "check")?, "schema")?;
if schema != "instinct.check/v1" {
return Err(format!("unsupported_schema: \"{}\"", clip(schema)));
}
let id = text(need(o, "id", "check")?, "id")?;
if !is_ident(id) {
return Err("malformed_definition: id must be 1-128 ASCII letters, digits or ._- starting with a letter".to_string());
}
let revision = match need(o, "revision", "check")? {
J::Num(n) => match n.parse::<u32>() {
Ok(v)
if (1..=2147483647).contains(&v)
&& n.bytes().all(|c| c.is_ascii_digit())
&& !n.starts_with('0') =>
{
v
}
_ => {
return Err(
"invalid_number: revision must be an integer literal from 1 to 2147483647"
.to_string(),
)
} },
_ => {
return Err(
"invalid_number: revision must be an integer literal, not a string".to_string(),
)
} };
let mut inputs = BTreeMap::new();
for (k, v) in obj(need(o, "inputs", "check")?, "inputs")? {
if !is_ident(k) {
return Err(format!(
"malformed_definition: input name \"{}\" is not a valid name",
clip(k)
));
}
inputs.insert(k.clone(), parse_ty(text(v, "input type")?)?);
}
let mut conditions = Vec::new();
if let Some(rc) = field(o, "required_conditions") {
match rc {
J::Arr(a) => {
for c in a {
let name = text(c, "required condition")?;
if !is_ident(name) {
return Err(format!(
"malformed_definition: condition name \"{}\" is not a valid name",
clip(name)
));
}
if conditions.iter().any(|x: &String| x == name) {
return Err(format!(
"malformed_definition: duplicate required condition \"{}\"",
clip(name)
));
}
conditions.push(name.to_string());
}
}
_ => {
return Err("malformed_definition: required_conditions must be an array".to_string())
} }
}
let scope = match field(o, "scope") {
Some(s) => parse_scope(s, "check scope")?,
None => Vec::new(),
};
let mut nodes = 0usize;
let claim = compile(need(o, "claim", "check")?, 1, &inputs, &mut nodes)?;
Ok(Def {
id: id.to_string(),
revision,
inputs,
claim,
conditions,
scope,
})
}
struct Request {
facts: BTreeMap<String, Val>,
entries: usize,
conditions: BTreeMap<String, bool>,
scope: Vec<(&'static str, String)>,
}
fn read_request(top: &[(String, J)], def: &Def) -> R<Request> {
let mut facts = BTreeMap::new();
let mut entries = 0usize;
if let Some(f) = field(top, "facts") {
for (k, v) in obj(f, "facts")? {
let ty = match def.inputs.get(k) {
Some(t) => *t,
None => {
return Err(format!(
"unknown_fact: \"{}\" is not declared in inputs",
clip(k)
))
} };
entries += 1;
let val = match (ty, v) {
(Ty::Str, J::Str(s)) => Val::S(s.clone()),
(Ty::Bool, J::Bool(b)) => Val::B(*b),
(Ty::Int, J::Str(s)) => match canonical_int(s) {
Some(n) => Val::I(n),
None => {
return Err(format!(
"invalid_number: fact \"{}\" is not a canonical decimal i128 string",
clip(k)
))
} },
(Ty::Set, J::Arr(items)) => {
let mut members = Vec::new();
for it in items {
match it {
J::Str(s) => members.push(s.clone()),
_ => {
return Err(format!(
"type_mismatch: fact \"{}\" must be an array of strings",
clip(k)
))
} }
}
entries += members.len();
members.sort();
if members.windows(2).any(|w| w[0] == w[1]) {
return Err(format!(
"duplicate_member: fact \"{}\" has a duplicate set member",
clip(k)
));
}
Val::Set(members)
}
_ => {
return Err(format!(
"type_mismatch: fact \"{}\" is not of declared type {}",
clip(k),
ty.name()
))
} };
facts.insert(k.clone(), val);
}
}
let mut conditions = BTreeMap::new();
if let Some(c) = field(top, "conditions") {
for (k, v) in obj(c, "conditions")? {
if !def.conditions.iter().any(|x| x == k) {
return Err(format!(
"unknown_condition: \"{}\" is not a required condition",
clip(k)
));
}
match v {
J::Bool(b) => {
conditions.insert(k.clone(), *b);
}
_ => {
return Err(format!(
"type_mismatch: condition \"{}\" must be a boolean",
clip(k)
))
} }
}
}
let scope = match field(top, "scope") {
Some(s) => parse_scope(s, "request scope")?,
None => Vec::new(),
};
Ok(Request {
facts,
entries,
conditions,
scope,
})
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Tri {
T,
F,
U,
}
struct Exhausted;
struct Ev<'a> {
facts: &'a BTreeMap<String, Val>,
steps: u64,
missing: BTreeSet<String>,
}
type Out = Result<(Tri, Option<String>), Exhausted>;
fn tri(b: bool) -> Tri {
if b {
Tri::T
} else {
Tri::F
}
}
impl<'a> Ev<'a> {
fn charge(&mut self, n: u64) -> Result<(), Exhausted> {
self.steps = self.steps.saturating_add(n);
if self.steps > MAX_STEPS {
self.steps = MAX_STEPS;
return Err(Exhausted);
}
Ok(())
}
fn contains(&mut self, set: &[String], x: &str) -> Result<bool, Exhausted> {
let (mut lo, mut hi) = (0usize, set.len());
while lo < hi {
self.charge(1)?;
let mid = lo + (hi - lo) / 2;
match set[mid].as_str().cmp(x) {
std::cmp::Ordering::Equal => return Ok(true),
std::cmp::Ordering::Less => lo = mid + 1,
std::cmp::Ordering::Greater => hi = mid,
}
}
Ok(false)
}
fn eval(&mut self, n: &Node) -> Out {
self.charge(1)?;
match n {
Node::Cmp(c, l, r) => self.cmp(*c, l, r),
Node::Not(inner) => {
let (t, _) = self.eval(inner)?;
Ok((
match t {
Tri::T => Tri::F,
Tri::F => Tri::T,
Tri::U => Tri::U,
},
None,
))
}
Node::All(kids) => {
let mut unknown = false;
for k in kids {
let (t, w) = self.eval(k)?;
match t {
Tri::F => return Ok((Tri::F, w)),
Tri::U => unknown = true,
Tri::T => {} }
}
Ok((if unknown { Tri::U } else { Tri::T }, None))
}
Node::Any(kids) => {
let mut unknown = false;
for k in kids {
let (t, _) = self.eval(k)?;
match t {
Tri::T => return Ok((Tri::T, None)),
Tri::U => unknown = true,
Tri::F => {} }
}
Ok((if unknown { Tri::U } else { Tri::F }, None))
} }
}
fn cmp(&mut self, c: Cmp, l: &str, r: &str) -> Out {
let facts = self.facts;
let (lv, rv) = (facts.get(l), facts.get(r));
if lv.is_none() {
self.missing.insert(l.to_string());
}
if rv.is_none() {
self.missing.insert(r.to_string());
}
let (lv, rv) = match (lv, rv) {
(Some(a), Some(b)) => (a, b),
_ => return Ok((Tri::U, None)),
};
match (c, lv, rv) {
(Cmp::Subset, Val::Set(a), Val::Set(b)) => {
let (mut i, mut j) = (0usize, 0usize);
while i < a.len() {
self.charge(1)?;
if j >= b.len() || a[i] < b[j] {
return Ok((Tri::F, Some(a[i].clone())));
}
if a[i] == b[j] {
i += 1;
}
j += 1;
}
Ok((Tri::T, None))
}
(Cmp::Disjoint, Val::Set(a), Val::Set(b)) => {
let (mut i, mut j) = (0usize, 0usize);
while i < a.len() && j < b.len() {
self.charge(1)?;
match a[i].cmp(&b[j]) {
std::cmp::Ordering::Equal => return Ok((Tri::F, Some(a[i].clone()))),
std::cmp::Ordering::Less => i += 1,
std::cmp::Ordering::Greater => j += 1,
}
}
Ok((Tri::T, None))
}
(Cmp::Contains, Val::Set(a), Val::S(x)) => {
let found = self.contains(a, x)?;
Ok((tri(found), None))
}
(Cmp::Eq, Val::Set(a), Val::Set(b)) => {
self.charge(1)?;
if a.len() != b.len() {
return Ok((Tri::F, None));
}
for k in 0..a.len() {
self.charge(1)?;
if a[k] != b[k] {
return Ok((Tri::F, None));
}
}
Ok((Tri::T, None))
}
(Cmp::Eq, Val::S(a), Val::S(b)) => Ok((tri(a == b), None)),
(Cmp::Eq, Val::B(a), Val::B(b)) => Ok((tri(a == b), None)),
(Cmp::Eq, Val::I(a), Val::I(b)) => Ok((tri(a == b), None)),
(Cmp::Lt, Val::I(a), Val::I(b)) => Ok((tri(a < b), None)),
(Cmp::Lte, Val::I(a), Val::I(b)) => Ok((tri(a <= b), None)),
_ => Ok((Tri::U, None)),
}
}
}
fn render_claim(n: &Node, out: &mut String) {
if out.len() > MAX_CLAIM_TEXT {
return;
}
match n {
Node::Cmp(c, l, r) => out.push_str(&format!("{}({}, {})", c.name(), l, r)),
Node::Not(k) => {
out.push_str("not(");
render_claim(k, out);
out.push(')');
}
Node::All(kids) | Node::Any(kids) => {
out.push_str(if matches!(n, Node::All(_)) {
"all("
} else {
"any("
});
for (i, k) in kids.iter().enumerate() {
if i > 0 {
out.push_str(", ");
}
render_claim(k, out);
}
out.push(')');
} }
}
fn jstr(s: &str) -> String {
let mut o = String::with_capacity(s.len() + 2);
o.push('"');
for ch in s.chars() {
match ch {
'"' => o.push_str("\\\""),
'\\' => o.push_str("\\\\"),
'\n' => o.push_str("\\n"),
'\r' => o.push_str("\\r"),
'\t' => o.push_str("\\t"),
c if (c as u32) < 0x20 => o.push_str(&format!("\\u{:04x}", c as u32)),
c => o.push(c),
}
}
o.push('"');
o
}
fn jlist(items: &[String]) -> String {
let parts: Vec<String> = items.iter().map(|s| jstr(s)).collect();
format!("[{}]", parts.join(","))
}
fn jscope(scope: &[(&'static str, String)]) -> String {
let parts: Vec<String> = scope
.iter()
.map(|(k, v)| format!("{}:{}", jstr(k), jstr(v)))
.collect();
format!("{{{}}}", parts.join(","))
}
pub fn error_json(reason: &str) -> String {
format!("{{\"schema\":\"instinct.check-error/v1\",\"verdict\":\"error\",\"reason\":{},\"authorization\":\"not_evaluated\"}}", jstr(reason))
}
pub fn evaluate(mode: Mode, input: &[u8]) -> (String, bool) {
match evaluate_inner(mode, input) {
Ok(s) => (s, false),
Err(e) => (error_json(&e), true),
}
}
fn evaluate_inner(mode: Mode, input: &[u8]) -> R<String> {
let tree = json::parse(input)?;
let top = match &tree {
J::Obj(o) => o,
_ => return Err("malformed_definition: the request must be a JSON object".to_string()),
};
only_keys(top, &["check", "facts", "conditions", "scope"], "request")?;
let def = compile_def(need(top, "check", "request")?)?;
let req = read_request(top, &def)?;
if mode == Mode::Validate {
if req.entries > MAX_FACT_ENTRIES {
return Err(
"limit_exceeded: facts have more than 10000 entries and set members".to_string(),
);
}
return Ok(format!(
"{{\"schema\":\"instinct.check-validation/v1\",\"check_id\":{},\"revision\":{},\"valid\":true,\"authorization\":\"not_evaluated\"}}",
jstr(&def.id),
def.revision
));
}
let mut missing: BTreeSet<String> = BTreeSet::new();
let mut steps = 0u64;
let mut witness: Option<String> = None;
let (verdict, reason) = 'decide: {
if req.entries > MAX_FACT_ENTRIES {
break 'decide (
"abstain",
"resource_limit: facts exceed 10000 entries".to_string(),
);
}
for (dim, want) in &def.scope {
match req.scope.iter().find(|(d, _)| d == dim) {
None => break 'decide ("abstain", format!("scope_missing: {dim}")),
Some((_, have)) if have != want => {
break 'decide ("abstain", format!("scope_mismatch: {dim}"))
}
Some(_) => {} }
}
for c in &def.conditions {
if req.conditions.get(c) != Some(&true) {
missing.insert(c.clone());
}
}
if !missing.is_empty() {
break 'decide ("abstain", "required_condition_not_met".to_string());
}
let mut ev = Ev {
facts: &req.facts,
steps: 0,
missing: BTreeSet::new(),
};
let res = ev.eval(&def.claim);
steps = ev.steps;
missing.extend(ev.missing);
match res {
Err(Exhausted) => (
"abstain",
"resource_limit: evaluation budget exhausted".to_string(),
),
Ok((Tri::T, _)) => ("pass", "claim_holds".to_string()),
Ok((Tri::F, w)) => {
witness = w;
("fail", "claim_false".to_string())
}
Ok((Tri::U, _)) => ("abstain", "fact_missing".to_string()),
}
};
let missing: Vec<String> = missing.into_iter().collect();
let mut out = format!(
"{{\"schema\":\"instinct.check-result/v1\",\"check_id\":{},\"revision\":{},\"verdict\":\"{}\",\"reason\":{},\"witness\":{},\"missing\":{},\"scope\":{},\"steps\":{}",
jstr(&def.id),
def.revision,
verdict,
jstr(&reason),
match &witness {
Some(w) => jstr(w),
None => "null".to_string(),
},
jlist(&missing),
jscope(&req.scope),
steps
);
if mode == Mode::Explain {
let mut claim = String::new();
render_claim(&def.claim, &mut claim);
let claim_truncated = claim.len() > MAX_CLAIM_TEXT;
if claim_truncated {
let mut end = MAX_CLAIM_TEXT;
while !claim.is_char_boundary(end) {
end -= 1;
}
claim.truncate(end);
claim.push_str("...");
}
let inputs: Vec<String> = def
.inputs
.iter()
.take(MAX_LISTED)
.map(|(k, t)| format!("{}:{}", jstr(k), jstr(t.name())))
.collect();
let conds: Vec<String> = def.conditions.iter().take(MAX_LISTED).cloned().collect();
out.push_str(&format!(
",\"explanation\":{{\"claim\":{},\"claim_truncated\":{},\"inputs\":{{{}}},\"inputs_truncated\":{},\"required_conditions\":{},\"required_conditions_truncated\":{},\"required_scope\":{}}}",
jstr(&claim),
claim_truncated,
inputs.join(","),
def.inputs.len() > MAX_LISTED,
jlist(&conds),
def.conditions.len() > MAX_LISTED,
jscope(&def.scope)
));
}
out.push_str(",\"authorization\":\"not_evaluated\",\"evidence_origin\":\"caller_reported\"}");
if out.len() > MAX_OUTPUT_BYTES {
return Err(
"limit_exceeded: result would exceed 64 KiB (scope, missing or explanation too large)"
.to_string(),
);
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
fn subset_doc(member: &str) -> String {
format!(
"{{\"check\":{{\"schema\":\"instinct.check/v1\",\"id\":\"a\",\"revision\":1,\"inputs\":{{\"x\":\"set<string>\",\"y\":\"set<string>\"}},\"claim\":{{\"op\":\"subset\",\"left\":{{\"fact\":\"x\"}},\"right\":{{\"fact\":\"y\"}}}}}},\"facts\":{{\"x\":[\"{member}\"],\"y\":[]}}}}"
)
}
#[test]
fn diagnostic_clip_removes_display_controls_without_changing_fact_strings() {
assert_eq!(clip("bad\u{202e}name\u{2066}x\u{200d}"), "bad?name?x?");
assert_eq!(clip("café日本語"), "café日本語");
assert!(jstr("\u{202e}fact").contains('\u{202e}'));
}
#[test]
fn explanation_declares_when_display_claim_is_incomplete() {
let leaf =
r#"{"op":"eq","left":{"fact":"long_fact_name"},"right":{"fact":"long_fact_name"}}"#;
let claim = format!(
"{{\"op\":\"all\",\"args\":[{}]}}",
vec![leaf; 1000].join(",")
);
let input = format!("{{\"check\":{{\"schema\":\"instinct.check/v1\",\"id\":\"explain-limit\",\"revision\":1,\"inputs\":{{\"long_fact_name\":\"bool\"}},\"claim\":{claim}}},\"facts\":{{\"long_fact_name\":true}}}}");
let (out, error) = evaluate(Mode::Explain, input.as_bytes());
assert!(!error, "{out}");
assert!(out.contains("\"claim_truncated\":true"), "{out}");
assert!(out.len() <= MAX_OUTPUT_BYTES);
}
#[test]
fn long_witness_is_the_exact_member_when_the_result_fits() {
let member = "z".repeat(5000);
let (out, is_err) = evaluate(Mode::Run, subset_doc(&member).as_bytes());
assert!(!is_err);
assert!(out.contains(&format!("\"witness\":\"{member}\"")));
assert!(!out.contains("truncated"));
}
#[test]
fn a_witness_that_cannot_fit_is_an_error_never_a_fabricated_member() {
let member = "z".repeat(70000);
let (out, is_err) = evaluate(Mode::Run, subset_doc(&member).as_bytes());
assert!(is_err);
assert!(out.contains("limit_exceeded") && out.len() < 300);
}
}