#[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},
kernel::{self, Mode},
receipt,
};
use std::collections::BTreeSet;
fn object(v: &J) -> Result<&[(String, J)], String> {
if let J::Obj(v) = v {
Ok(v)
} else {
Err("snapshot integrity requires objects".into())
}
}
fn field<'a>(o: &'a [(String, J)], key: &str) -> Option<&'a J> {
o.iter().find(|(k, _)| k == key).map(|(_, v)| v)
}
fn only(o: &[(String, J)], keys: &[&str]) -> Result<(), String> {
if o.iter().any(|(k, _)| !keys.contains(&k.as_str())) {
Err("unknown snapshot-integrity field".into())
} else {
Ok(())
}
}
fn text(s: &str) -> J {
J::Str(s.into())
}
fn ser(v: &J) -> String {
let mut out = String::new();
receipt::ser(v, &mut out);
out
}
fn predicate(op: &str, a: &str, b: &str) -> J {
J::Obj(vec![
("op".into(), text(op)),
("left".into(), J::Obj(vec![("fact".into(), text(a))])),
("right".into(), J::Obj(vec![("fact".into(), text(b))])),
])
}
fn keys(v: &J, total: &mut usize) -> Result<(J, bool), String> {
let J::Arr(values) = v else {
return Err("snapshot keys must be arrays".into());
};
*total += values.len();
if *total > 10000 {
return Err("limit_exceeded: snapshot has more than 10000 supplied keys".into());
}
let mut set = BTreeSet::new();
let mut unique = true;
for value in values {
let J::Str(key) = value else {
return Err(
"snapshot keys must be nonempty strings; null and composite keys are unsupported"
.into(),
);
};
if key.is_empty() {
return Err("snapshot keys must be nonempty strings".into());
}
unique &= set.insert(key.clone());
}
Ok((J::Arr(set.into_iter().map(J::Str).collect()), unique))
}
fn run(raw: &[u8]) -> Result<String, String> {
let value = json::parse(raw)?;
let top = object(&value)?;
only(
top,
&["schema", "snapshot", "constraints", "conditions", "scope"],
)?;
if field(top, "schema") != Some(&text("instinct.snapshot-integrity/v1")) {
return Err("unsupported snapshot-integrity schema".into());
}
let empty = J::Obj(vec![]);
let snapshot = object(field(top, "snapshot").unwrap_or(&empty))?;
only(
snapshot,
&["parent_keys", "child_keys", "child_parent_refs"],
)?;
let constraints = object(field(top, "constraints").ok_or("explicit constraints required")?)?;
only(constraints, &["required_parent_keys", "scope"])?;
let mut count = 0;
let mut facts = vec![("truth".into(), J::Bool(true))];
let mut parent_count = None;
let mut child_count = None;
let mut reference_count = None;
if let Some(v) = field(snapshot, "parent_keys") {
let (set, unique) = keys(v, &mut count)?;
if let J::Arr(a) = v {
parent_count = Some(a.len());
}
facts.push(("parents".into(), set));
facts.push(("parent_unique".into(), J::Bool(unique)));
}
if let Some(v) = field(snapshot, "child_keys") {
let (_, unique) = keys(v, &mut count)?;
if let J::Arr(a) = v {
child_count = Some(a.len());
}
facts.push(("child_unique".into(), J::Bool(unique)));
}
if let Some(v) = field(snapshot, "child_parent_refs") {
let (set, _) = keys(v, &mut count)?;
if let J::Arr(a) = v {
reference_count = Some(a.len());
}
facts.push(("references".into(), set));
}
if let (Some(a), Some(b)) = (child_count, reference_count) {
if a != b {
return Err("snapshot child key and reference arrays must have equal lengths".into());
}
}
if let Some(v) = field(constraints, "required_parent_keys") {
let (set, unique) = keys(v, &mut count)?;
if !unique {
return Err("duplicate required parent key in constraints".into());
}
facts.push(("required".into(), set));
}
let inputs = J::Obj(vec![
("truth".into(), text("bool")),
("parent_unique".into(), text("bool")),
("child_unique".into(), text("bool")),
("parents".into(), text("set<string>")),
("references".into(), text("set<string>")),
("required".into(), text("set<string>")),
]);
let checks = vec![
predicate("eq", "parent_unique", "truth"),
predicate("eq", "child_unique", "truth"),
predicate("subset", "references", "parents"),
predicate("subset", "required", "parents"),
];
let definition = J::Obj(vec![
("schema".into(), text("instinct.check/v1")),
("id".into(), text("relational-snapshot-integrity")),
("revision".into(), J::Num("1".into())),
("inputs".into(), inputs),
(
"claim".into(),
J::Obj(vec![
("op".into(), text("all")),
("args".into(), J::Arr(checks)),
]),
),
(
"required_conditions".into(),
J::Arr(vec![
text("complete_snapshot"),
text("explicit_constraints"),
]),
),
(
"scope".into(),
field(constraints, "scope")
.cloned()
.unwrap_or(empty.clone()),
),
]);
let request = J::Obj(vec![
("check".into(), definition),
("facts".into(), J::Obj(facts)),
(
"conditions".into(),
field(top, "conditions").cloned().unwrap_or(empty.clone()),
),
(
"scope".into(),
field(top, "scope").cloned().unwrap_or(empty),
),
]);
let (result, bad) = kernel::evaluate(Mode::Run, ser(&request).as_bytes());
if bad {
return Err("invalid snapshot constraints, conditions or scope".into());
}
let result = json::parse(result.as_bytes())?;
let result = object(&result)?;
let mut out = vec![
(
"schema".into(),
text("instinct.snapshot-integrity-result/v1"),
),
("authorization".into(), text("not_evaluated")),
(
"evidence_origin".into(),
text("caller_reported_snapshot_and_constraints"),
),
("database_opened".into(), J::Bool(false)),
("witness_redacted".into(), J::Bool(true)),
];
for key in ["verdict", "reason", "missing", "steps"] {
out.push((
key.into(),
field(result, key)
.cloned()
.ok_or("kernel result incomplete")?,
));
}
for (key, count) in [("parent_rows", parent_count), ("child_rows", child_count)] {
out.push((
key.into(),
count.map(|n| J::Num(n.to_string())).unwrap_or(J::Null),
));
}
Ok(ser(&J::Obj(out)))
}
pub(super) fn evaluate(raw: &[u8]) -> (String, bool) {
match run(raw) {
Ok(out) => (out, false),
Err(e) => (kernel::error_json(&e), true),
}
}