#[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::BTreeMap;
fn object(v: &J) -> Result<&[(String, J)], String> {
if let J::Obj(o) = v {
Ok(o)
} else {
Err("composition requires objects".into())
}
}
fn field<'a>(o: &'a [(String, J)], k: &str) -> Option<&'a J> {
o.iter().find(|(n, _)| n == k).map(|(_, v)| v)
}
fn needed<'a>(o: &'a [(String, J)], k: &str) -> Result<&'a J, String> {
field(o, k).ok_or_else(|| format!("composition missing {k}"))
}
fn only(o: &[(String, J)], keys: &[&str]) -> Result<(), String> {
if o.iter().any(|(k, _)| !keys.contains(&k.as_str())) {
Err("unknown composition field".into())
} else {
Ok(())
}
}
fn string(v: &J) -> Result<&str, String> {
if let J::Str(s) = v {
Ok(s)
} else {
Err("composition name must be a string".into())
}
}
fn serialize(v: &J) -> String {
let mut out = String::new();
receipt::ser(v, &mut out);
out
}
fn failure(reason: &str) -> String {
kernel::error_json(reason)
}
fn rename(v: &J, names: &BTreeMap<String, String>) -> Result<J, String> {
match v {
J::Obj(o) => {
let mut result = Vec::new();
for (k, v) in o {
if k == "fact" {
let old = string(v)?;
let new = names.get(old).ok_or("composition unknown fact reference")?;
result.push((k.clone(), J::Str(new.clone())))
} else {
result.push((k.clone(), rename(v, names)?))
}
}
Ok(J::Obj(result))
}
J::Arr(a) => Ok(J::Arr(
a.iter()
.map(|v| rename(v, names))
.collect::<Result<_, _>>()?,
)),
other => Ok(other.clone()),
}
}
fn compile(raw: &[u8]) -> Result<String, String> {
let value = json::parse(raw)?;
let top = object(&value)?;
only(top, &["id", "revision", "checks", "scope"])?;
let id = needed(top, "id")?.clone();
let revision = needed(top, "revision")?.clone();
let current = field(top, "scope").cloned().unwrap_or(J::Obj(vec![]));
let J::Arr(children) = needed(top, "checks")? else {
return Err("checks must be an array".into());
};
if children.is_empty() || children.len() > 16 {
return Err("composition requires 1 to 16 checks".into());
}
let mut inputs = Vec::new();
let mut facts = Vec::new();
let mut conditions = Vec::new();
let mut required = Vec::new();
let mut claims = Vec::new();
let mut scope: BTreeMap<String, J> = BTreeMap::new();
for (i, child) in children.iter().enumerate() {
let child_fields = object(child)?;
only(child_fields, &["check", "facts", "conditions"])?;
let (validated, bad) = kernel::evaluate(Mode::Validate, serialize(child).as_bytes());
if bad {
return Err(format!("child {i} invalid: {validated}"));
}
let def = object(needed(child_fields, "check")?)?;
let mut names = BTreeMap::new();
for (j, (old, ty)) in object(needed(def, "inputs")?)?.iter().enumerate() {
let new = format!("c{i}.f{j}");
names.insert(old.clone(), new.clone());
inputs.push((new, ty.clone()));
}
if let Some(raw_facts) = field(child_fields, "facts") {
for (old, v) in object(raw_facts)? {
facts.push((
names.get(old).ok_or("unknown child fact")?.clone(),
v.clone(),
));
}
}
let mut condition_names = BTreeMap::new();
if let Some(J::Arr(list)) = field(def, "required_conditions") {
for (j, name) in list.iter().enumerate() {
let new = format!("c{i}.r{j}");
condition_names.insert(string(name)?.to_owned(), new.clone());
required.push(J::Str(new));
}
}
if let Some(raw_conditions) = field(child_fields, "conditions") {
for (old, v) in object(raw_conditions)? {
conditions.push((
condition_names
.get(old)
.ok_or("unknown child condition")?
.clone(),
v.clone(),
));
}
}
if let Some(raw_scope) = field(def, "scope") {
for (key, v) in object(raw_scope)? {
if let Some(previous) = scope.get(key) {
if previous != v {
return Err(format!("conflicting child scope: {key}"));
}
} else {
scope.insert(key.clone(), v.clone());
}
}
}
claims.push(rename(needed(def, "claim")?, &names)?);
}
let definition = J::Obj(vec![
("schema".into(), J::Str("instinct.check/v1".into())),
("id".into(), id),
("revision".into(), revision),
("inputs".into(), J::Obj(inputs)),
("required_conditions".into(), J::Arr(required)),
("scope".into(), J::Obj(scope.into_iter().collect())),
(
"claim".into(),
J::Obj(vec![
("op".into(), J::Str("all".into())),
("args".into(), J::Arr(claims)),
]),
),
]);
let compiled = J::Obj(vec![
("check".into(), definition),
("facts".into(), J::Obj(facts)),
("conditions".into(), J::Obj(conditions)),
("scope".into(), current),
]);
let out = serialize(&compiled);
let (validated, bad) = kernel::evaluate(Mode::Validate, out.as_bytes());
if bad {
return Err(format!("aggregate invalid: {validated}"));
}
if out.len() > kernel::MAX_OUTPUT_BYTES {
return Err("composition output exceeds 64 KiB".into());
}
Ok(out)
}
pub fn compose(raw: &[u8]) -> (String, bool) {
match compile(raw) {
Ok(out) => (out, false),
Err(e) => (failure(&e), true),
}
}