airlock / engine.py
justrunme's picture
Add Airlock policy engine demo (v0.1.0)
665bfb9 verified
Raw History Blame Contribute Delete
7.52 kB
"""Browser-side helpers around the bundled Airlock policy engine."""
from __future__ import annotations
import json
from typing import Any
from airlock.policy import PolicyEngine
from airlock.schemas import ActionRequest
SOURCE_COMMIT = "719e13b353bfa21d3d129563226de0ebb17cffb5"
PACKAGE_VERSION = "0.1.0"
DEFAULT_OFFICIAL_ID = "r4adv090"
CUSTOM_ID = "custom"
ENGINE = PolicyEngine()
OFFICIAL: list[dict[str, Any]] = []
INDEPENDENT: list[dict[str, Any]] = []
OFFICIAL_BY_ID: dict[str, dict[str, Any]] = {}
META: dict[str, str] = {}
def _dumps(value: Any) -> str:
return json.dumps(value, ensure_ascii=False)
def _action(lang: str, code: str, case_id: str) -> ActionRequest:
if lang == "tool":
return ActionRequest(id=case_id, task_id="hf-demo", tool=code)
return ActionRequest(
id=case_id,
task_id="hf-demo",
tool="run_code",
lang=lang,
code=code,
)
def _decision_payload(decision, case: dict[str, Any] | None = None) -> dict[str, Any]:
blast = decision.blast_radius
factors = blast.factors
if hasattr(factors, "model_dump"):
factor_data = factors.model_dump()
else:
factor_data = {
"fs_write": getattr(factors, "fs_write", None),
"net": getattr(factors, "net", None),
"procs": getattr(factors, "procs", None),
"duration": getattr(factors, "duration", None),
}
payload: dict[str, Any] = {
"verdict": decision.verdict,
"rules_fired": list(decision.rules_fired),
"reason": decision.reason or "",
"blast_radius": {"score": blast.score, "factors": factor_data},
"policy_sha256": decision.policy_sha256,
"caps": dict(decision.caps or {}),
"source_commit": SOURCE_COMMIT,
"package_version": PACKAGE_VERSION,
}
if case is not None:
payload["case"] = {
"id": case.get("id") or f"ind{case.get('line')}",
"lang": case.get("lang"),
"label": case.get("label") or case.get("kind"),
"source": case.get("source") or "tests/corpus_independent/corpus.jsonl",
"pinned_verdict": case.get("pinned_verdict") or "",
"pinned_rule": case.get("pinned_rule") or "",
"listed_miss": case.get("listed_miss") or "",
"triage": case.get("triage") or "",
}
return payload
def evaluate_request(lang: str, code: str, case_id: str = CUSTOM_ID) -> str:
try:
decision = ENGINE.evaluate(_action(lang, code, case_id))
except Exception as exc: # fail-closed on evaluator errors
return _dumps(
{
"ok": False,
"verdict": "deny",
"rules_fired": [],
"reason": f"Evaluator error (fail-closed): {type(exc).__name__}: {exc}",
"blast_radius": None,
"policy_sha256": ENGINE.policy_hash,
"source_commit": SOURCE_COMMIT,
"package_version": PACKAGE_VERSION,
}
)
payload = _decision_payload(decision, OFFICIAL_BY_ID.get(case_id))
payload["ok"] = True
payload["lang"] = lang
payload["code"] = code
payload["id"] = case_id
return _dumps(payload)
def evaluate_official(case_id: str) -> str:
case = OFFICIAL_BY_ID.get(case_id)
if case is None:
return _dumps({"ok": False, "reason": f"Unknown official case: {case_id}"})
out = json.loads(evaluate_request(case["lang"], case["code"], case["id"]))
return _dumps(out)
def init(corpus_json: str) -> str:
global OFFICIAL, INDEPENDENT, OFFICIAL_BY_ID, META
data = json.loads(corpus_json)
OFFICIAL = list(data["official"])
INDEPENDENT = list(data["independent"])
OFFICIAL_BY_ID = {row["id"]: row for row in OFFICIAL}
META = {
"source_commit": data.get("source_commit", SOURCE_COMMIT),
"policy_sha256_expected": data.get("policy_sha256", ""),
"policy_sha256": ENGINE.policy_hash,
"official_corpus_sha256": data.get("official_corpus_sha256", ""),
"independent_corpus_sha256": data.get("independent_corpus_sha256", ""),
"official_adversarial": sum(1 for r in OFFICIAL if r["label"] == "adversarial"),
"official_benign": sum(1 for r in OFFICIAL if r["label"] == "benign"),
"independent_attack": sum(1 for r in INDEPENDENT if r["kind"] == "attack"),
"independent_benign": sum(1 for r in INDEPENDENT if r["kind"] == "benign"),
"default_id": DEFAULT_OFFICIAL_ID if DEFAULT_OFFICIAL_ID in OFFICIAL_BY_ID else OFFICIAL[0]["id"],
"package_version": PACKAGE_VERSION,
}
official_short = [
{
"id": r["id"],
"lang": r["lang"],
"label": r["label"],
"source": r["source"],
"pinned_verdict": r["pinned_verdict"],
"pinned_rule": r["pinned_rule"],
"preview": r["code"].replace("\n", " ")[:140],
}
for r in OFFICIAL
]
return _dumps({"ok": True, "meta": META, "official": official_short})
def official_code(case_id: str) -> str:
case = OFFICIAL_BY_ID.get(case_id)
if case is None:
return _dumps({"ok": False, "reason": f"Unknown official case: {case_id}"})
return _dumps({"ok": True, "id": case["id"], "lang": case["lang"], "code": case["code"], "label": case["label"]})
def evaluate_official_index(index: int) -> str:
if index < 0 or index >= len(OFFICIAL):
return _dumps({"ok": False, "reason": f"Official index out of range: {index}"})
case = OFFICIAL[index]
decision = ENGINE.evaluate(_action(case["lang"], case["code"], case["id"]))
expected = case["pinned_verdict"]
match = decision.verdict == expected
label = case["label"]
false_allow = label == "adversarial" and decision.verdict == "allow"
false_deny = label == "benign" and decision.verdict != "allow"
return _dumps(
{
"ok": True,
"index": index,
"id": case["id"],
"lang": case["lang"],
"label": label,
"verdict": decision.verdict,
"expected": expected,
"match": match,
"false_allow": false_allow,
"false_deny": false_deny,
"rules_fired": list(decision.rules_fired),
}
)
def evaluate_independent_index(index: int) -> str:
if index < 0 or index >= len(INDEPENDENT):
return _dumps({"ok": False, "reason": f"Independent index out of range: {index}"})
case = INDEPENDENT[index]
decision = ENGINE.evaluate(_action(case["lang"], case["code"], f"ind{case['line']}"))
allowed = decision.verdict == "allow"
kind = case["kind"]
false_allow = kind == "attack" and allowed
false_deny = kind == "benign" and not allowed
miss = false_allow or false_deny
listed = case.get("listed_miss") or ""
expected_listed = ("false_allow" if false_allow else "false_deny") if miss else ""
return _dumps(
{
"ok": True,
"index": index,
"line": case["line"],
"lang": case["lang"],
"kind": kind,
"verdict": decision.verdict,
"false_allow": false_allow,
"false_deny": false_deny,
"miss": miss,
"listed_miss": listed,
"triage": case.get("triage") or "",
"untriaged": miss and listed != expected_listed,
"rules_fired": list(decision.rules_fired),
}
)