#[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 super::kernel::{self, Mode};
use std::collections::BTreeSet;
use std::path::{Component, Path, PathBuf};
const OBSERVE_USAGE: &str = "usage: instinct check observe --root /absolute/staging/root --input FILE|-\n\
// hlx:15
Read-only inventory of names and kinds under the granted root, checked against the caller policy\n\
// hlx:16
(schema instinct.artifact-policy/v1). No bank is opened; exit 0 for observed/incomplete, exit 2 for an error result.\n\
// hlx:17
Spec: docs/check-observation-wire.md.";
const POLICY_SCHEMA: &str = "instinct.artifact-policy/v1";
const CEIL_ENTRIES: u64 = 10000;
const CEIL_DEPTH: u64 = 64;
const CEIL_BYTES: u64 = 1 << 20;
const META_ALLOWANCE: u64 = 64;
#[derive(Clone, Copy)]
struct Limits {
entries: u64,
depth: u64,
bytes: u64,
}
struct Policy {
trusted: bool,
allowed: Vec<String>,
required: Vec<String>,
scope: Vec<(String, String)>,
limits: Limits,
}
#[derive(Clone, PartialEq, Eq, Debug)]
struct Meta {
len: u64,
stamp: [i64; 6],
mode: u32,
}
#[derive(Clone, PartialEq, Eq, Debug)]
struct Ent {
path: String,
dir: bool,
meta: Meta,
}
#[derive(PartialEq, Eq, Debug)]
struct Snap {
root_before: Meta,
root_after: Meta,
ents: Vec<Ent>,
}
struct Stop {
reason: String,
witness: Option<String>,
}
fn stop(reason: &str, witness: Option<&str>) -> Stop {
Stop {
reason: reason.to_string(),
witness: witness.map(|w| w.to_string()),
}
}
fn jstr(s: &str) -> String {
let mut o = String::with_capacity(s.len() + 2);
o.push('"');
for c in s.chars() {
match c {
'"' => 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 || c as u32 == 0x7f => {
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: &[(String, String)]) -> String {
let parts: Vec<String> = scope
.iter()
.map(|(k, v)| format!("{}:{}", jstr(k), jstr(v)))
.collect();
format!("{{{}}}", parts.join(","))
}
fn valid_rel(p: &str) -> Result<(), &'static str> {
if p.is_empty() {
return Err("empty path");
}
if p.contains('\0') {
return Err("NUL in path");
}
if p.starts_with('/') {
return Err("absolute path");
}
if p.starts_with("\\\\") {
return Err("UNC path");
}
let b = p.as_bytes();
if b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':' {
return Err("drive path");
}
if p.ends_with('/') {
return Err("trailing slash");
}
for c in p.split('/') {
if c.is_empty() {
return Err("empty component");
}
if c == "." || c == ".." {
return Err("dot component");
}
}
Ok(())
}
fn obj<'a>(v: &'a J, what: &str) -> Result<&'a [(String, J)], String> {
match v {
J::Obj(o) => Ok(o),
_ => Err(format!("malformed_policy: {what} must be an object")),
}
}
fn only_keys(o: &[(String, J)], allowed: &[&str], what: &str) -> Result<(), String> {
for (k, _) in o {
if !allowed.contains(&k.as_str()) {
return Err(format!("malformed_policy: unknown field in {what}"));
}
}
Ok(())
}
fn get<'a>(o: &'a [(String, J)], k: &str) -> Option<&'a J> {
o.iter().find(|(n, _)| n == k).map(|(_, v)| v)
}
fn path_list(v: &J, name: &str) -> Result<Vec<String>, String> {
let items = match v {
J::Arr(a) => a,
_ => {
return Err(format!(
"malformed_policy: {name} must be an array of strings"
))
}
};
if items.len() as u64 > CEIL_ENTRIES {
return Err(format!(
"limit_exceeded: {name} has more than 10000 entries"
));
}
let mut seen: BTreeSet<&str> = BTreeSet::new();
let mut out = Vec::new();
for (i, it) in items.iter().enumerate() {
let s = match it {
J::Str(s) => s,
_ => return Err(format!("malformed_policy: {name}[{i}] must be a string")),
};
if let Err(why) = valid_rel(s) {
return Err(format!("invalid_path: {name}[{i}]: {why}"));
}
if !seen.insert(s.as_str()) {
return Err(format!("malformed_policy: {name}[{i}] is a duplicate"));
}
out.push(s.clone());
}
Ok(out)
}
fn limit(o: &[(String, J)], key: &str, default: u64, ceil: u64) -> Result<u64, String> {
let v = match get(o, key) {
None => return Ok(default),
Some(J::Num(n)) => n,
Some(_) => return Err(format!("invalid_limit: {key} must be an integer")),
};
let canon = !v.is_empty()
&& v.len() <= 10
&& v.bytes().all(|c| c.is_ascii_digit())
&& (v == "0" || !v.starts_with('0'));
if !canon {
return Err(format!(
"invalid_limit: {key} must be a canonical non-negative integer"
));
}
let n: u64 = v
.parse()
.map_err(|_| format!("invalid_limit: {key} is not a number"))?;
if n > ceil {
return Err(format!("invalid_limit: {key} exceeds the ceiling {ceil}"));
}
Ok(n)
}
fn parse_policy(bytes: &[u8]) -> Result<Policy, String> {
let tree = json::parse(bytes)?;
let top = obj(&tree, "the policy")?;
only_keys(
top,
&[
"schema",
"assumptions",
"allowed",
"required",
"scope",
"limits",
],
"policy",
)?;
match get(top, "schema") {
Some(J::Str(s)) if s == POLICY_SCHEMA => {}
_ => return Err(format!("malformed_policy: schema must be {POLICY_SCHEMA}")),
}
let trusted = match get(top, "assumptions") {
None => false,
Some(a) => {
let ao = obj(a, "assumptions")?;
only_keys(ao, &["trusted_quiescent_staging"], "assumptions")?;
match get(ao, "trusted_quiescent_staging") {
None => false,
Some(J::Bool(b)) => *b,
Some(_) => {
return Err(
"malformed_policy: trusted_quiescent_staging must be a boolean".to_string(),
)
}
}
} };
let allowed = match get(top, "allowed") {
Some(v) => path_list(v, "allowed")?,
None => return Err("malformed_policy: allowed is required".to_string()),
};
let required = match get(top, "required") {
Some(v) => path_list(v, "required")?,
None => Vec::new(),
};
let allow_set: BTreeSet<&str> = allowed.iter().map(String::as_str).collect();
if required.iter().any(|r| !allow_set.contains(r.as_str())) {
return Err("contradictory_policy: every required path must also be allowed".to_string());
}
let mut scope: Vec<(String, String)> = Vec::new();
if let Some(s) = get(top, "scope") {
for (k, v) in obj(s, "scope")? {
match v {
J::Str(v) => scope.push((k.clone(), v.clone())),
_ => return Err("malformed_policy: scope values must be strings".to_string()),
}
}
}
let mut limits = Limits {
entries: CEIL_ENTRIES,
depth: CEIL_DEPTH,
bytes: CEIL_BYTES,
};
if let Some(l) = get(top, "limits") {
let lo = obj(l, "limits")?;
only_keys(
lo,
&["max_entries", "max_depth", "max_inventory_bytes"],
"limits",
)?;
limits.entries = limit(lo, "max_entries", CEIL_ENTRIES, CEIL_ENTRIES)?;
limits.depth = limit(lo, "max_depth", CEIL_DEPTH, CEIL_DEPTH)?;
limits.bytes = limit(lo, "max_inventory_bytes", CEIL_BYTES, CEIL_BYTES)?;
}
Ok(Policy {
trusted,
allowed,
required,
scope,
limits,
})
}
fn check_text(id: &str, left: &str, right: &str, facts: &str, conds: bool, scope: &str) -> String {
let conditions = if conds {
"{\"complete-inventory\":true,\"explicit-policy\":true}"
} else {
"{}"
};
format!(
"{{\"check\":{{\"schema\":\"instinct.check/v1\",\"id\":{},\"revision\":1,\"inputs\":{{{}:\"set<string>\",{}:\"set<string>\"}},\"claim\":{{\"op\":\"subset\",\"left\":{{\"fact\":{}}},\"right\":{{\"fact\":{}}}}},\"required_conditions\":[\"complete-inventory\",\"explicit-policy\"],\"scope\":{}}},\"facts\":{},\"conditions\":{},\"scope\":{}}}",
jstr(id),
jstr(left),
jstr(right),
jstr(left),
jstr(right),
scope,
facts,
conditions,
scope
)
}
const ID_ALLOWED: &str = "artifact-actual-subset-allowed";
const ID_REQUIRED: &str = "artifact-required-subset-actual";
fn policy_facts(p: &Policy, which: u8) -> String {
if which == 0 {
format!("{{\"allowed\":{}}}", jlist(&p.allowed))
} else {
format!("{{\"required\":{}}}", jlist(&p.required))
}
}
fn preflight(p: &Policy) -> Result<(), String> {
let scope = jscope(&p.scope);
let a = check_text(
ID_ALLOWED,
"actual",
"allowed",
&policy_facts(p, 0),
false,
&scope,
);
let (out, err) = kernel::evaluate(Mode::Validate, a.as_bytes());
if err {
return Err(out);
}
if !p.required.is_empty() {
let r = check_text(
ID_REQUIRED,
"required",
"actual",
&policy_facts(p, 1),
false,
&scope,
);
let (out, err) = kernel::evaluate(Mode::Validate, r.as_bytes());
if err {
return Err(out);
}
}
Ok(())
}
fn validate_root(root: &str) -> Result<PathBuf, String> {
if root.is_empty() || root.contains('\0') {
return Err("usage: --root must be a nonempty path".to_string());
}
let p = Path::new(root);
if !p.is_absolute() {
return Err("usage: --root must be an absolute path".to_string());
}
let sep = |c: char| c == '/' || (cfg!(windows) && c == '\\');
let filesystem_root = p.parent().is_none()
&& !root.strip_suffix(sep).is_some_and(|prefix| prefix.ends_with(sep));
if root.len() > 1 && root.ends_with(sep) && !filesystem_root {
return Err("usage: --root must not end with a separator".to_string());
}
if root
.split(sep)
.skip(1)
.any(|c| c.is_empty() && root.len() > 1)
&& !cfg!(windows)
{
return Err("usage: --root must not contain empty components".to_string());
}
if root.split(sep).any(|c| c == "." || c == "..") {
return Err("usage: --root must not contain . or .. components".to_string());
}
if p.components()
.any(|c| matches!(c, Component::CurDir | Component::ParentDir))
{
return Err("usage: --root must not contain . or .. components".to_string());
}
Ok(p.to_path_buf())
}
#[cfg(any(target_os = "macos", all(test, unix)))]
fn system_alias_candidate(root: &Path) -> Option<(&'static str, &'static str, PathBuf)> {
for (alias, target) in [
("/var", "/private/var"),
("/tmp", "/private/tmp"),
("/etc", "/private/etc"),
] {
if let Ok(rest) = root.strip_prefix(alias) {
if !rest.as_os_str().is_empty() {
return Some((alias, target, Path::new(target).join(rest)));
}
}
}
None
}
fn platform_root(root: PathBuf) -> Result<PathBuf, String> {
#[cfg(target_os = "macos")]
if let Some((alias, target, resolved)) = system_alias_candidate(&root) {
let meta = std::fs::symlink_metadata(alias)
.map_err(|_| "root_invalid: cannot inspect system ancestor")?;
if meta.file_type().is_symlink() {
let link = std::fs::read_link(alias)
.map_err(|_| "root_invalid: cannot inspect system alias")?;
let actual = if link.is_absolute() {
link
} else {
Path::new("/").join(link)
};
if actual != Path::new(target) {
return Err("root_invalid: unexpected system alias target".into());
}
return Ok(resolved);
}
}
Ok(root)
}
#[cfg(unix)]
fn meta_of(m: &std::fs::Metadata) -> Meta {
use std::os::unix::fs::MetadataExt;
Meta {
len: m.len(),
stamp: [
m.mtime(),
m.mtime_nsec(),
m.ctime(),
m.ctime_nsec(),
m.dev() as i64,
m.ino() as i64,
],
mode: m.mode(),
}
}
#[cfg(not(unix))]
fn meta_of(m: &std::fs::Metadata) -> Meta {
Meta {
len: m.len(),
stamp: [0; 6],
mode: 0,
}
}
fn io_reason(what: &str, e: &std::io::Error) -> String {
format!("{what}: {:?}", e.kind())
}
fn root_meta(root: &Path) -> Result<Meta, Stop> {
let comps: Vec<Component> = root.components().collect();
let mut cur = PathBuf::new();
for (i, c) in comps.iter().enumerate() {
cur.push(c.as_os_str());
if i + 1 == comps.len() || matches!(c, Component::RootDir | Component::Prefix(_)) {
continue;
}
let am = std::fs::symlink_metadata(&cur)
.map_err(|e| stop(&io_reason("root_unreadable", &e), None))?;
if am.file_type().is_symlink() {
return Err(stop("symlink_rejected: root_ancestor", None));
}
}
let m = std::fs::symlink_metadata(root)
.map_err(|e| stop(&io_reason("root_unreadable", &e), None))?;
if m.file_type().is_symlink() {
return Err(stop("symlink_rejected: root", None));
}
if !m.is_dir() {
return Err(stop("root_not_directory", None));
}
Ok(meta_of(&m))
}
fn walk(root: &Path, lim: Limits, seen: &mut usize) -> Result<Snap, Stop> {
let root_before = root_meta(root)?;
let mut ents: Vec<Ent> = Vec::new();
let mut bytes: u64 = 0;
let mut pending: Vec<(String, u64)> = vec![(String::new(), 0)];
while let Some((rel, depth)) = pending.pop() {
let abs = if rel.is_empty() {
root.to_path_buf()
} else {
root.join(&rel)
};
let shown = if rel.is_empty() { "." } else { rel.as_str() };
let rd = std::fs::read_dir(&abs)
.map_err(|e| stop(&io_reason("read_dir_failed", &e), Some(shown)))?;
let mut names: Vec<String> = Vec::new();
for item in rd {
let item = item.map_err(|e| stop(&io_reason("read_dir_failed", &e), Some(shown)))?;
let name = match item.file_name().into_string() {
Ok(n) => n,
Err(_) => return Err(stop("non_utf8_name", Some(shown))),
};
let child = if rel.is_empty() {
name.clone()
} else {
format!("{rel}/{name}")
};
if ents.len() as u64 + names.len() as u64 + 1 > lim.entries {
return Err(stop("budget_exceeded: max_entries", Some(&child)));
}
if depth + 1 > lim.depth {
return Err(stop("budget_exceeded: max_depth", Some(&child)));
}
bytes += child.len() as u64 + META_ALLOWANCE;
if bytes > lim.bytes {
return Err(stop("budget_exceeded: max_inventory_bytes", Some(&child)));
}
names.push(name);
*seen += 1;
}
names.sort();
for name in names {
let child = if rel.is_empty() {
name.clone()
} else {
format!("{rel}/{name}")
};
let m = std::fs::symlink_metadata(abs.join(&name))
.map_err(|e| stop(&io_reason("entry_unreadable", &e), Some(&child)))?;
let ft = m.file_type();
if ft.is_symlink() {
return Err(stop("symlink_rejected", Some(&child)));
}
let dir = ft.is_dir();
if !dir && !ft.is_file() {
return Err(stop("unsupported_entry_kind", Some(&child)));
}
if dir {
pending.push((child.clone(), depth + 1));
}
ents.push(Ent {
path: child,
dir,
meta: meta_of(&m),
});
}
}
ents.sort_by(|a, b| a.path.cmp(&b.path));
let root_after = root_meta(root)?;
Ok(Snap {
root_before,
root_after,
ents,
})
}
fn first_difference(a: &Snap, b: &Snap) -> String {
for (x, y) in a.ents.iter().zip(b.ents.iter()) {
if x != y {
return x.path.clone();
}
}
if a.ents.len() > b.ents.len() {
return a.ents[b.ents.len()].path.clone();
}
if b.ents.len() > a.ents.len() {
return b.ents[a.ents.len()].path.clone();
}
".".to_string()
}
fn limits_json(l: Limits) -> String {
format!(
"{{\"max_entries\":{},\"max_depth\":{},\"max_inventory_bytes\":{},\"metadata_allowance_bytes\":{}}}",
l.entries, l.depth, l.bytes, META_ALLOWANCE
)
}
fn incomplete(p: &Policy, reason: &str, witness: Option<&str>, visited: usize) -> String {
let w = match witness {
Some(w) => format!(",\"witness\":{}", jstr(w)),
None => String::new(),
};
format!(
"{{\"schema\":\"instinct.artifact-observation/v1\",\"adapter\":\"artifact-inventory/v1\",\"validity\":\"incomplete\",\"evidence_origin\":\"adapter_observed\",\"authorization\":\"not_evaluated\",\"reason\":{}{},\"assumptions\":{{\"trusted_quiescent_staging\":{}}},\"scope\":{},\"inventory\":[],\"checks\":[],\"limits\":{},\"visited_entries\":{}}}",
jstr(reason),
w,
p.trusted,
jscope(&p.scope),
limits_json(p.limits),
visited
)
}
fn identity_hash(domain: &str, pieces: &[&[u8]]) -> String {
let mut bytes = Vec::new();
bytes.extend_from_slice(domain.as_bytes());
bytes.push(0);
for piece in pieces {
bytes.extend_from_slice(&(piece.len() as u64).to_le_bytes());
bytes.extend_from_slice(piece);
}
super::digest::hex(&super::digest::sha256(&bytes))
}
fn metadata_bytes(meta: &Meta) -> Vec<u8> {
let mut bytes = Vec::new();
bytes.extend_from_slice(&meta.len.to_le_bytes());
for x in meta.stamp {
bytes.extend_from_slice(&x.to_le_bytes());
}
bytes.extend_from_slice(&meta.mode.to_le_bytes());
bytes
}
fn evidence_identity(root: &Path, p: &Policy, snap: &Snap) -> String {
let root_meta = metadata_bytes(&snap.root_before);
let root_bytes = root.as_os_str().as_encoded_bytes();
let root_hash = identity_hash("instinct.observation-root/v1", &[root_bytes, &root_meta]);
let limits = limits_json(p.limits);
let mut ordered_scope = p.scope.clone();
ordered_scope.sort();
let scope = jscope(&ordered_scope);
let allowed = jlist(&p.allowed);
let required = jlist(&p.required);
let grant_hash = identity_hash(
"instinct.observation-grant/v1",
&[
root_bytes,
limits.as_bytes(),
b"reject-symlinks",
b"trusted-quiescent-staging",
],
);
let policy_hash = identity_hash(
"instinct.observation-policy/v1",
&[
allowed.as_bytes(),
required.as_bytes(),
scope.as_bytes(),
limits.as_bytes(),
],
);
let mut inventory = Vec::new();
for entry in &snap.ents {
inventory.extend_from_slice(&(entry.path.len() as u64).to_le_bytes());
inventory.extend_from_slice(entry.path.as_bytes());
inventory.push(entry.dir as u8);
inventory.extend_from_slice(&metadata_bytes(&entry.meta));
}
let metadata_hash = identity_hash(
"instinct.observation-metadata/v1",
&[&root_meta, &inventory],
);
format!("{{\"schema\":\"instinct.observation-identity/v1\",\"root_sha256\":\"{root_hash}\",\"grant_sha256\":\"{grant_hash}\",\"policy_sha256\":\"{policy_hash}\",\"metadata_sha256\":\"{metadata_hash}\",\"content_hashed\":false,\"authentication\":\"none\"}}")
}
fn observed(root: &Path, p: &Policy, snap: &Snap) -> Result<String, String> {
let actual: Vec<String> = snap.ents.iter().map(|e| e.path.clone()).collect();
let scope = jscope(&p.scope);
let mut checks: Vec<String> = Vec::new();
let a = check_text(
ID_ALLOWED,
"actual",
"allowed",
&format!(
"{{\"actual\":{},\"allowed\":{}}}",
jlist(&actual),
jlist(&p.allowed)
),
true,
&scope,
);
let (out, err) = kernel::evaluate(Mode::Run, a.as_bytes());
if err {
return Err(out);
}
checks.push(format!("{{\"name\":\"actual_subset_allowed\",\"provenance\":{{\"actual\":\"adapter_observed\",\"allowed\":\"caller_policy\"}},\"result\":{out}}}"));
if !p.required.is_empty() {
let r = check_text(
ID_REQUIRED,
"required",
"actual",
&format!(
"{{\"required\":{},\"actual\":{}}}",
jlist(&p.required),
jlist(&actual)
),
true,
&scope,
);
let (out, err) = kernel::evaluate(Mode::Run, r.as_bytes());
if err {
return Err(out);
}
checks.push(format!("{{\"name\":\"required_subset_actual\",\"provenance\":{{\"required\":\"caller_policy\",\"actual\":\"adapter_observed\"}},\"result\":{out}}}"));
}
let inv: Vec<String> = snap
.ents
.iter()
.map(|e| {
format!(
"{{\"path\":{},\"kind\":\"{}\"}}",
jstr(&e.path),
if e.dir { "directory" } else { "file" }
)
})
.collect();
Ok(format!(
"{{\"schema\":\"instinct.artifact-observation/v1\",\"adapter\":\"artifact-inventory/v1\",\"validity\":\"observed_snapshot\",\"evidence_origin\":\"adapter_observed\",\"authorization\":\"not_evaluated\",\"reason\":\"inventory_observed_under_caller_assumption\",\"identity\":{},\"assumptions\":{{\"trusted_quiescent_staging\":true}},\"scope\":{},\"inventory\":[{}],\"checks\":[{}],\"limits\":{},\"visited_entries\":{}}}",
evidence_identity(root, p, snap),
scope,
inv.join(","),
checks.join(","),
limits_json(p.limits),
snap.ents.len()
))
}
fn observe_inner(root: &str, policy: &[u8], between: &mut dyn FnMut()) -> (String, bool) {
let root = match validate_root(root) {
Ok(r) => r,
Err(e) => return (kernel::error_json(&e), true),
};
let p = match parse_policy(policy) {
Ok(p) => p,
Err(e) => return (kernel::error_json(&e), true),
};
if let Err(e) = preflight(&p) {
return (e, true);
}
if !p.trusted {
return (
incomplete(
&p,
"assumption_not_asserted: trusted_quiescent_staging",
None,
0,
),
false,
);
}
if cfg!(not(unix)) {
return (
incomplete(
&p,
"unsupported_platform: inventory observation is implemented for Unix only",
None,
0,
),
false,
);
}
let root = match platform_root(root) {
Ok(root) => root,
Err(e) => return (kernel::error_json(&e), true),
};
let mut seen1 = 0usize;
let first = match walk(&root, p.limits, &mut seen1) {
Ok(s) => s,
Err(s) => {
if s.reason.starts_with("root_unreadable")
|| s.reason == "root_not_directory"
|| s.reason.starts_with("symlink_rejected: root")
{
return (
kernel::error_json(&format!("root_invalid: {}", s.reason)),
true,
);
}
return (
incomplete(&p, &s.reason, s.witness.as_deref(), seen1),
false,
);
} };
between();
let second = match walk(&root, p.limits, &mut 0usize) {
Ok(s) => s,
Err(s) => {
return (
incomplete(
&p,
&format!("changed_during_observation: {}", s.reason),
s.witness.as_deref(),
first.ents.len(),
),
false,
)
}
};
if first != second {
let w = first_difference(&first, &second);
return (
incomplete(
&p,
"changed_during_observation: inventory or metadata differs between passes",
Some(&w),
first.ents.len(),
),
false,
);
}
let out = match observed(&root, &p, &first) {
Ok(o) => o,
Err(e) => return (e, true),
};
(out, false)
}
fn observe_with(root: &str, policy: &[u8], between: &mut dyn FnMut()) -> (String, bool) {
let (out, is_error) = observe_inner(root, policy, between);
if out.len() > kernel::MAX_OUTPUT_BYTES {
return (
kernel::error_json("limit_exceeded: observation result exceeds 65536 bytes"),
true,
);
}
(out, is_error)
}
pub fn observe(root: &str, policy: &[u8]) -> (String, bool) {
observe_with(root, policy, &mut || {})
}
fn usage_error(why: &str) -> i32 {
println!("{}", kernel::error_json(&format!("usage: {why}")));
2
}
pub fn cli(args: &[String]) -> i32 {
if args.len() == 1 && (args[0] == "--help" || args[0] == "-h") {
println!("{OBSERVE_USAGE}");
return 0;
}
let mut root: Option<String> = None;
let mut input: Option<String> = None;
let mut i = 0;
while i < args.len() {
let a = &args[i];
let (slot, name, value) = if a == "--root" || a == "--input" {
i += 1;
match args.get(i) {
Some(v) if v == "-" || !v.starts_with("--") => (
if a == "--root" { &mut root } else { &mut input },
a.as_str(),
v.clone(),
),
_ => return usage_error(&format!("{a} needs a value")),
}
} else if let Some(v) = a.strip_prefix("--root=") {
(&mut root, "--root", v.to_string())
} else if let Some(v) = a.strip_prefix("--input=") {
(&mut input, "--input", v.to_string())
} else if a.starts_with('-') && a != "-" {
return usage_error("unknown option (observe accepts only --root and --input)");
} else {
return usage_error("unexpected positional argument");
};
if slot.is_some() {
return usage_error(&format!("{name} given more than once"));
}
*slot = Some(value);
i += 1;
}
let root = match root {
Some(r) if !r.is_empty() => r,
_ => return usage_error("--root ABSOLUTE_DIR is required"),
};
let input = match input {
Some(p) if !p.is_empty() => p,
_ => return usage_error("--input FILE|- is required"),
};
let bytes = match super::read_input(&input) {
Ok(b) => b,
Err(e) => {
println!("{}", kernel::error_json(&e));
return 2;
} };
let (out, is_error) = observe(&root, &bytes);
println!("{out}");
if is_error {
2
} else {
0
}
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
static N: AtomicUsize = AtomicUsize::new(0);
fn tmp() -> PathBuf {
let d = std::env::temp_dir().join(format!(
"instinct-observe-{}-{}",
std::process::id(),
N.fetch_add(1, Ordering::SeqCst)
));
std::fs::create_dir_all(&d).unwrap();
d
}
fn put(root: &Path, rel: &str) {
let p = root.join(rel);
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(p, b"x").unwrap();
}
fn run(root: &Path, policy: &str) -> (String, bool) {
observe(root.to_str().unwrap(), policy.as_bytes())
}
fn pol(allowed: &str, required: &str, extra: &str) -> String {
format!("{{\"schema\":\"instinct.artifact-policy/v1\",\"assumptions\":{{\"trusted_quiescent_staging\":true}},\"allowed\":{allowed},\"required\":{required}{extra}}}")
}
#[test]
fn fixed_system_alias_mapping_is_component_bounded() {
assert_eq!(
system_alias_candidate(Path::new("/var/folders/x"))
.unwrap()
.2,
PathBuf::from("/private/var/folders/x")
);
assert!(system_alias_candidate(Path::new("/var")).is_none());
assert!(system_alias_candidate(Path::new("/var-other/x")).is_none());
assert!(system_alias_candidate(Path::new("/home/user/link/x")).is_none());
}
#[cfg(target_os = "macos")]
#[test]
fn macos_system_temp_alias_works_but_user_links_do_not() {
let r = tmp();
put(&r, "a");
let canonical = std::fs::canonicalize(&r).unwrap();
let alias = canonical
.to_string_lossy()
.replacen("/private/var/", "/var/", 1)
.replacen("/private/tmp/", "/tmp/", 1);
let (out, error) = observe(&alias, pol("[\"a\"]", "[]", "").as_bytes());
assert!(!error && out.contains("observed_snapshot"), "{out}");
std::os::unix::fs::symlink(&r, r.join("link")).unwrap();
let (out, error) = observe(
r.join("link").to_str().unwrap(),
pol("[\"a\"]", "[]", "").as_bytes(),
);
assert!(error && out.contains("symlink_rejected"), "{out}");
}
#[test]
fn clean_tree_passes_with_names_and_kinds() {
let r = tmp();
put(&r, "docs/README");
put(&r, "release.bin");
put(&r, "my file \u{e9}.txt");
let (o, e) = run(
&r,
&pol(
"[\"docs\",\"docs/README\",\"release.bin\",\"my file \u{e9}.txt\"]",
"[\"release.bin\"]",
"",
),
);
assert!(!e, "{o}");
assert!(o.contains("\"validity\":\"observed_snapshot\""), "{o}");
assert!(
o.contains("{\"path\":\"docs\",\"kind\":\"directory\"}"),
"{o}"
);
assert!(
o.contains("{\"path\":\"my file \u{e9}.txt\",\"kind\":\"file\"}"),
"{o}"
);
assert_eq!(o.matches("\"verdict\":\"pass\"").count(), 2, "{o}");
assert!(o.contains("\"assumptions\":{\"trusted_quiescent_staging\":true}"));
assert!(
!o.contains(r.to_str().unwrap()),
"absolute root must not be echoed"
);
}
#[test]
fn empty_root_is_complete_empty_inventory() {
let r = tmp();
let (o, e) = run(&r, &pol("[]", "[]", ""));
assert!(
!e && o.contains("\"inventory\":[]")
&& o.contains("observed_snapshot")
&& o.contains("\"verdict\":\"pass\""),
"{o}"
);
}
#[test]
fn hidden_extra_file_fails_membership_with_witness() {
let r = tmp();
put(&r, "release.bin");
put(&r, ".env");
let (o, e) = run(&r, &pol("[\"release.bin\"]", "[]", ""));
assert!(
!e && o.contains("\"verdict\":\"fail\"") && o.contains("\"witness\":\".env\""),
"{o}"
);
}
#[test]
fn missing_required_fails_separate_check() {
let r = tmp();
put(&r, "a");
let (o, e) = run(&r, &pol("[\"a\",\"b\"]", "[\"b\"]", ""));
assert!(!e, "{o}");
assert!(
o.contains("\"name\":\"required_subset_actual\"") && o.contains("\"witness\":\"b\""),
"{o}"
);
}
#[test]
fn missing_or_false_assumption_abstains_before_traversal() {
let bad = "/nonexistent-instinct-observe-root";
for p in [
"{\"schema\":\"instinct.artifact-policy/v1\",\"allowed\":[]}",
"{\"schema\":\"instinct.artifact-policy/v1\",\"assumptions\":{\"trusted_quiescent_staging\":false},\"allowed\":[]}",
] {
let (o, e) = observe(bad, p.as_bytes());
assert!(!e && o.contains("\"validity\":\"incomplete\"") && o.contains("assumption_not_asserted"), "{o}");
assert!(o.contains("\"inventory\":[]") && o.contains("\"checks\":[]"), "{o}");
}
}
#[test]
fn policy_errors_are_rejected_before_observation() {
let r = tmp();
let cases = [
pol("[\"../x\"]", "[]", ""),
pol("[\"/abs\"]", "[]", ""),
pol("[\"a//b\"]", "[]", ""),
pol("[\"a/\"]", "[]", ""),
pol("[\"a/./b\"]", "[]", ""),
pol("[\"C:\\\\x\"]", "[]", ""),
pol("[\"\\\\\\\\srv\\\\share\"]", "[]", ""),
pol("[\"a\",\"a\"]", "[]", ""),
pol("[\"a\"]", "[\"b\"]", ""),
pol("[\"a\"]", "[]", ",\"scope\":{\"bogus\":\"x\"}"),
pol("[\"a\"]", "[]", ",\"scope\":{\"project\":\"\"}"),
pol("[\"a\"]", "[]", ",\"limits\":{\"max_entries\":10001}"),
pol("[\"a\"]", "[]", ",\"limits\":{\"max_depth\":1.5}"),
pol("[\"a\"]", "[]", ",\"limits\":{\"max_depth\":-1}"),
pol("[\"a\"]", "[]", ",\"extra\":1"),
"{\"schema\":\"instinct.artifact-policy/v1\",\"allowed\":[],\"allowed\":[]}"
.to_string(),
"{\"schema\":\"wrong\",\"allowed\":[]}".to_string(),
];
for c in cases {
let (o, e) = run(&r, &c);
assert!(
e && o.contains("instinct.check-error/v1"),
"accepted {c}: {o}"
);
}
assert!(
std::fs::read_dir(&r).unwrap().next().is_none(),
"root untouched"
);
}
#[test]
fn relative_or_missing_root_is_an_error() {
let p = pol("[]", "[]", "");
assert!(observe("relative/dir", p.as_bytes()).1);
assert!(observe("/nonexistent-instinct-observe-root", p.as_bytes()).1);
let r = tmp();
put(&r, "f");
assert!(observe(r.join("f").to_str().unwrap(), p.as_bytes()).1);
}
#[cfg(unix)]
#[test]
fn symlink_abstains_without_target_disclosure() {
let r = tmp();
let outside = tmp();
put(&outside, "secret-target-name");
std::os::unix::fs::symlink(&outside, r.join("link")).unwrap();
let (o, e) = run(&r, &pol("[\"link\"]", "[]", ""));
assert!(
!e && o.contains("\"validity\":\"incomplete\"")
&& o.contains("symlink_rejected")
&& o.contains("\"witness\":\"link\""),
"{o}"
);
assert!(
!o.contains("secret-target-name") && !o.contains(outside.to_str().unwrap()),
"{o}"
);
assert!(o.contains("\"inventory\":[]") && o.contains("\"checks\":[]"));
let rl = tmp();
std::os::unix::fs::symlink(&r, rl.join("rootlink")).unwrap();
let (o, e) = run(&rl.join("rootlink"), &pol("[]", "[]", ""));
assert!(e && o.contains("root_invalid"), "{o}");
}
#[cfg(unix)]
#[test]
fn symlinked_root_ancestor_is_rejected_before_enumeration() {
let real = tmp();
put(&real, "stage/release.bin");
let base = tmp();
std::os::unix::fs::symlink(&real, base.join("alias")).unwrap();
let p = pol("[\"release.bin\"]", "[]", "");
let (o, e) = run(&base.join("alias").join("stage"), &p);
assert!(
e && o.contains("root_invalid") && o.contains("root_ancestor"),
"{o}"
);
assert!(
!o.contains("release.bin") && !o.contains(real.to_str().unwrap()),
"{o}"
);
let (o, e) = run(&real.join("stage"), &p);
assert!(!e && o.contains("observed_snapshot"), "{o}");
let np = "{\"schema\":\"instinct.artifact-policy/v1\",\"allowed\":[]}";
let (o, e) = observe(
base.join("alias").join("stage").to_str().unwrap(),
np.as_bytes(),
);
assert!(
!e && o.contains("assumption_not_asserted") && o.contains("\"inventory\":[]"),
"{o}"
);
}
#[test]
fn oversized_result_on_every_path_is_a_bounded_error() {
let big = "p".repeat(90000);
let np = format!("{{\"schema\":\"instinct.artifact-policy/v1\",\"allowed\":[],\"scope\":{{\"project\":\"{big}\"}}}}");
let (o, e) = observe("/nonexistent-instinct-observe-root", np.as_bytes());
assert!(
e && o.len() < 1000 && o.contains("limit_exceeded") && !o.contains("pppp"),
"{}",
o.len()
);
let r = tmp();
let tp = format!("{{\"schema\":\"instinct.artifact-policy/v1\",\"assumptions\":{{\"trusted_quiescent_staging\":true}},\"allowed\":[],\"scope\":{{\"project\":\"{big}\"}}}}");
let (o, e) = run(&r, &tp);
assert!(
e && o.contains("limit_exceeded") && o.len() < 1000,
"{}",
o.len()
);
}
#[cfg(unix)]
#[test]
fn root_spelling_variants_cannot_bypass_the_symlink_rule() {
let real = tmp();
put(&real, "f");
let base = tmp();
std::os::unix::fs::symlink(&real, base.join("rl")).unwrap();
let p = pol("[\"f\"]", "[]", "");
let rl = base.join("rl").to_str().unwrap().to_string();
let rs = real.to_str().unwrap().to_string();
for bad in [
rl.clone(),
format!("{rl}/"),
format!("{rl}//"),
format!("{rl}/."),
format!("{rl}/./"),
format!("{}/./{}", base.to_str().unwrap(), "rl"),
format!("{rs}/"),
format!("{rs}//"),
format!("{rs}/."),
format!("{rs}/../{}", real.file_name().unwrap().to_str().unwrap()),
format!("/./{}", &rs[1..]),
rs.replacen('/', "//", 1),
] {
let (o, e) = observe(&bad, p.as_bytes());
assert!(
e && o.contains("instinct.check-error/v1") && !o.contains("observed_snapshot"),
"accepted {bad}: {o}"
);
}
let (o, e) = observe(&rs, p.as_bytes());
assert!(!e && o.contains("observed_snapshot"), "{o}");
}
#[cfg(unix)]
#[test]
fn non_utf8_name_abstains() {
use std::os::unix::ffi::OsStrExt;
let r = tmp();
if let Err(e) = std::fs::write(r.join(std::ffi::OsStr::from_bytes(b"bad\xff")), b"x") {
if cfg!(target_os = "macos") && e.raw_os_error() == Some(92) {
eprintln!("SKIP non-UTF-8 fixture: this macOS filesystem rejects the name (EILSEQ); observation not exercised");
std::fs::remove_dir(&r).unwrap();
return;
}
panic!("cannot create raw-name fixture: {e}");
}
let (o, e) = run(&r, &pol("[]", "[]", ""));
assert!(
!e && o.contains("non_utf8_name") && o.contains("\"validity\":\"incomplete\""),
"{o}"
);
}
#[cfg(unix)]
#[test]
fn socket_is_unsupported_entry() {
let r = tmp();
let _l = std::os::unix::net::UnixListener::bind(r.join("sock")).unwrap();
let (o, e) = run(&r, &pol("[\"sock\"]", "[]", ""));
assert!(!e && o.contains("unsupported_entry_kind"), "{o}");
}
#[cfg(unix)]
#[test]
fn unreadable_directory_abstains() {
use std::os::unix::fs::PermissionsExt;
let r = tmp();
put(&r, "d/inner");
let d = r.join("d");
std::fs::set_permissions(&d, std::fs::Permissions::from_mode(0o000)).unwrap();
if std::fs::read_dir(&d).is_ok() {
std::fs::set_permissions(&d, std::fs::Permissions::from_mode(0o755)).unwrap();
return; }
let (o, e) = run(&r, &pol("[\"d\",\"d/inner\"]", "[]", ""));
std::fs::set_permissions(&d, std::fs::Permissions::from_mode(0o755)).unwrap();
assert!(
!e && o.contains("read_dir_failed")
&& o.contains("\"validity\":\"incomplete\"")
&& o.contains("\"checks\":[]"),
"{o}"
);
}
#[test]
fn mutation_between_passes_abstains() {
let r = tmp();
put(&r, "a");
let p = pol("[\"a\",\"late\"]", "[]", "");
let rc = r.clone();
let (o, e) = observe_with(r.to_str().unwrap(), p.as_bytes(), &mut || put(&rc, "late"));
assert!(
!e && o.contains("changed_during_observation")
&& o.contains("\"witness\":\"late\"")
&& o.contains("\"inventory\":[]"),
"{o}"
);
let rc = r.clone();
let (o, _) = observe_with(r.to_str().unwrap(), p.as_bytes(), &mut || {
std::fs::write(rc.join("a"), b"longer content").unwrap();
});
assert!(
o.contains("changed_during_observation") && o.contains("\"witness\":\"a\""),
"{o}"
);
}
#[test]
fn budgets_terminate_without_partial_pass() {
let r = tmp();
for n in 0..5 {
put(&r, &format!("f{n}"));
}
let all = "[\"f0\",\"f1\",\"f2\",\"f3\",\"f4\"]";
let (o, e) = run(&r, &pol(all, "[]", ",\"limits\":{\"max_entries\":3}"));
assert!(
!e && o.contains("budget_exceeded: max_entries")
&& !o.contains("\"verdict\"")
&& o.contains("\"inventory\":[]"),
"{o}"
);
let (o, _) = run(
&r,
&pol(all, "[]", ",\"limits\":{\"max_inventory_bytes\":100}"),
);
assert!(o.contains("budget_exceeded: max_inventory_bytes"), "{o}");
let d = tmp();
put(&d, "a/b/c");
let (o, _) = run(
&d,
&pol(
"[\"a\",\"a/b\",\"a/b/c\"]",
"[]",
",\"limits\":{\"max_depth\":2}",
),
);
assert!(
o.contains("budget_exceeded: max_depth") && o.contains("\"witness\":\"a/b/c\""),
"{o}"
);
let (o, _) = run(
&d,
&pol(
"[\"a\",\"a/b\",\"a/b/c\"]",
"[]",
",\"limits\":{\"max_depth\":3}",
),
);
assert!(o.contains("observed_snapshot"), "{o}");
}
#[test]
fn scope_mismatch_is_delegated_to_kernel_abstain() {
let r = tmp();
put(&r, "a");
let (o, e) = run(
&r,
&pol("[\"a\"]", "[]", ",\"scope\":{\"project\":\"release-lab\"}"),
);
assert!(
!e && o.contains("\"scope\":{\"project\":\"release-lab\"}")
&& o.contains("\"verdict\":\"pass\""),
"{o}"
);
}
#[test]
fn cli_arg_errors() {
let s = |v: &[&str]| v.iter().map(|x| x.to_string()).collect::<Vec<_>>();
assert_eq!(cli(&s(&["--help"])), 0);
assert_eq!(cli(&s(&[])), 2);
assert_eq!(cli(&s(&["--root", "/x"])), 2);
assert_eq!(cli(&s(&["--input", "-"])), 2);
assert_eq!(
cli(&s(&["--root", "/x", "--root", "/y", "--input", "-"])),
2
);
assert_eq!(cli(&s(&["--root", "/x", "--input", "-", "extra"])), 2);
assert_eq!(cli(&s(&["--root", "/x", "--input", "-", "--bogus"])), 2);
}
}