justrunme's picture
Redesign demo: scenario gallery, run-all, tamper check
46cddde verified
Raw History Blame Contribute Delete
12.8 kB
"""Browser-side helpers around the bundled ASC v0.2.1 library."""
from __future__ import annotations
import json
import os
from typing import Any
import yaml
from asc.digest import compute_capability_digest
from asc.envelope import build_envelope, policy_sha256_bytes, verify_envelope
from asc.evaluator import evaluate
from asc.models import EvaluationResult, Verdict
from asc.policy import PolicyError, parse_policy
from asc.trace import TraceError, parse_trace
ASC_PIN_COMMIT = "768853bde5a56fcc6c9b486f52848761db1b0ef1"
ASC_PIN_VERSION = "0.2.1"
os.environ["ASC_COMMIT_SHA"] = ASC_PIN_COMMIT
CUSTOM_ID = "custom"
DEFAULT_PRESET = "path_traversal_relative"
SCENARIOS: dict[str, dict[str, Any]] = {}
DEFAULT_POLICY_YAML = ""
DEMO_CATALOG_DIGEST = ""
def _pretty_json(value: Any) -> str:
return json.dumps(value, indent=2, ensure_ascii=False) + "\n"
def _block_result(reason: str, scenario_id: str) -> EvaluationResult:
return EvaluationResult(verdict=Verdict.BLOCK, reason=reason, scenario_id=scenario_id)
def _format_decision(result: EvaluationResult, envelope: dict[str, Any]) -> str:
acs = envelope.get("acs_disposition", "")
lines = [
f"Verdict: {result.verdict.value}",
f"ACS disposition: {acs}" if acs else "ACS disposition: (not set)",
f"Reason: {result.reason}",
]
if result.blocked_call_id:
lines.append(f"Blocked call: {result.blocked_call_id}")
if result.details:
lines.append(f"Details: {json.dumps(result.details, ensure_ascii=False, sort_keys=True)}")
lines.append(f"Scenario: {result.scenario_id}")
return "\n".join(lines)
def _trace_editor_value(scenario: dict[str, Any]) -> str:
trace_obj = dict(scenario["trace"])
parsed = parse_trace(scenario["trace"])
if parsed.tool_catalog is not None:
observed = compute_capability_digest(parsed.tool_catalog)
if observed == DEMO_CATALOG_DIGEST:
trace_obj.pop("tool_catalog", None)
return _pretty_json(trace_obj)
def _preset_label(scenario: dict[str, Any]) -> str:
title = scenario.get("title") or scenario["scenario_id"]
return f"[{scenario['expected']}] {title} — {scenario['scenario_id']}"
def _scenario_tag(scenario: dict[str, Any]) -> str:
"""Short label taken from the official owasp_risk field, nothing invented."""
risk = (scenario.get("owasp_risk") or "").strip()
if not risk or risk.lower().startswith("n/a"):
return "Benign control"
if " / " in risk:
return risk.split(" / ", 1)[1]
return risk
def _calls_view(trace_text: str, blocked_call_id: str | None = None) -> list[dict[str, Any]]:
try:
trace = parse_trace(json.loads(trace_text))
except Exception:
return []
calls: list[dict[str, Any]] = []
for call in trace.calls:
calls.append(
{
"call_id": call.call_id,
"tool": call.tool,
"approved": call.approved,
"args": call.args,
"blocked": bool(blocked_call_id) and call.call_id == blocked_call_id,
}
)
return calls
def _preset_record(scenario_id: str, scenario: dict[str, Any]) -> dict[str, Any]:
expected = scenario["expected"]
return {
"id": scenario_id,
"label": _preset_label(scenario),
"title": scenario.get("title") or scenario_id,
"description": (scenario.get("description") or "").strip(),
"expected": expected,
"severity": scenario.get("severity") or "",
"owasp_risk": scenario.get("owasp_risk") or "",
"tag": _scenario_tag(scenario),
"group": "benign" if expected == "ALLOW" else "attack",
}
def init(policy_yaml: str, scenarios_json: str) -> str:
"""Load the shipped policy and corpus. Called once after the library is imported."""
global SCENARIOS, DEFAULT_POLICY_YAML, DEMO_CATALOG_DIGEST
DEFAULT_POLICY_YAML = policy_yaml
SCENARIOS = json.loads(scenarios_json)
policy = parse_policy(yaml.safe_load(DEFAULT_POLICY_YAML))
DEMO_CATALOG_DIGEST = policy.capability_digest
presets = [_preset_record(sid, sc) for sid, sc in SCENARIOS.items()]
attack_count = sum(1 for p in presets if p["group"] == "attack")
benign_count = sum(1 for p in presets if p["group"] == "benign")
tags = sorted({p["tag"] for p in presets if p["tag"] != "Benign control"})
return json.dumps(
{
"version": ASC_PIN_VERSION,
"commit": ASC_PIN_COMMIT,
"scenario_count": len(SCENARIOS),
"attack_count": attack_count,
"benign_count": benign_count,
"default_preset": DEFAULT_PRESET,
"tags": tags,
"presets": presets,
}
)
def load_preset(scenario_id: str) -> str:
if scenario_id == CUSTOM_ID or scenario_id not in SCENARIOS:
example = {
"agent_id": "demo-agent",
"trace_id": "custom-1",
"calls": [
{
"call_id": "c1",
"tool": "filesystem.read",
"args": {"path": "/workspace/README.md"},
}
],
}
trace = _pretty_json(example)
note = (
"Custom trace. Paste a corpus-style trace object "
"(agent_id, trace_id, calls, optional tool_catalog). "
"If tool_catalog is omitted, the evaluator uses the policy catalog. "
"Unknown tools, digest mismatch, and invalid JSON fail closed to BLOCK."
)
return json.dumps(
{
"id": CUSTOM_ID,
"trace": trace,
"policy": DEFAULT_POLICY_YAML,
"note": note,
"title": "Custom trace",
"description": "",
"expected": "",
"tag": "",
"group": "custom",
"calls": _calls_view(trace),
}
)
scenario = SCENARIOS[scenario_id]
record = _preset_record(scenario_id, scenario)
note_parts = [
f"{record['title']}.",
record["description"],
f"Corpus expected verdict: {record['expected']}.",
]
if record["owasp_risk"]:
note_parts.append(f"OWASP risk tag: {record['owasp_risk']}.")
trace = _trace_editor_value(scenario)
record.update(
{
"trace": trace,
"policy": DEFAULT_POLICY_YAML,
"note": " ".join(part for part in note_parts if part),
"calls": _calls_view(trace),
}
)
return json.dumps(record)
def recompute_digest(policy_yaml: str) -> str:
try:
raw = yaml.safe_load(policy_yaml)
if not isinstance(raw, dict):
return json.dumps({"policy": policy_yaml, "message": "Policy must be a YAML mapping."})
policy = parse_policy(raw)
except Exception as exc:
return json.dumps({"policy": policy_yaml, "message": f"Could not recompute digest: {exc}"})
digest = compute_capability_digest(policy.capabilities)
raw["capability_digest"] = digest
updated = yaml.safe_dump(raw, sort_keys=False, allow_unicode=True)
return json.dumps(
{
"policy": updated,
"message": f"Set capability_digest to {digest} from the policy catalog.",
}
)
def _evaluate(scenario_id: str, trace_text: str, policy_yaml: str) -> dict[str, Any]:
policy = None
trace = None
result: EvaluationResult | None = None
try:
raw_policy = yaml.safe_load(policy_yaml)
if not isinstance(raw_policy, dict):
raise PolicyError("policy must be a YAML mapping")
policy = parse_policy(raw_policy)
except Exception as exc:
result = _block_result(f"invalid or missing policy: {exc}", scenario_id)
if result is None:
try:
raw_trace = json.loads(trace_text)
trace = parse_trace(raw_trace)
except (json.JSONDecodeError, TraceError, Exception) as exc:
result = _block_result(f"invalid or malformed trace: {exc}", scenario_id)
if result is None:
assert policy is not None and trace is not None
result = evaluate(policy, trace, scenario_id=scenario_id)
policy_bytes = policy_yaml.encode("utf-8")
envelope = build_envelope(
result=result,
policy=policy,
policy_path=None,
trace=trace,
commit_sha=ASC_PIN_COMMIT,
policy_version=policy.version if policy is not None else "unknown",
policy_digest=policy_sha256_bytes(policy_bytes) if policy_yaml.strip() else None,
)
try:
verify_envelope(envelope, expected_policy_sha256=envelope["policy_sha256"])
integrity = "passed"
integrity_text = "Evidence envelope integrity check: passed"
except Exception as exc:
integrity = "failed"
integrity_text = f"Evidence envelope integrity check: failed ({exc})"
decision = _format_decision(result, envelope) + "\n" + integrity_text
expected = ""
if scenario_id in SCENARIOS:
expected = SCENARIOS[scenario_id]["expected"]
return {
"verdict": result.verdict.value,
"reason": result.reason,
"acs_disposition": envelope.get("acs_disposition"),
"blocked_call_id": result.blocked_call_id,
"details": result.details,
"scenario_id": result.scenario_id,
"expected": expected,
"integrity": integrity,
"decision": decision,
"envelope": envelope,
"envelope_text": _pretty_json(envelope),
"calls": _calls_view(trace_text, result.blocked_call_id),
}
def evaluate_trace(scenario_id: str, trace_text: str, policy_yaml: str) -> str:
sid = scenario_id if scenario_id and scenario_id != CUSTOM_ID else CUSTOM_ID
if sid not in SCENARIOS and sid != CUSTOM_ID:
sid = CUSTOM_ID
return json.dumps(_evaluate(sid, trace_text, policy_yaml))
def evaluate_scenario(scenario_id: str) -> str:
"""Evaluate a corpus preset the same way the UI does (compact catalog when it matches)."""
loaded = json.loads(load_preset(scenario_id))
return evaluate_trace(scenario_id, loaded["trace"], loaded["policy"])
def run_corpus() -> str:
"""Evaluate every official scenario against the shipped demo policy."""
failures: list[dict[str, Any]] = []
results: list[dict[str, Any]] = []
for scenario_id, scenario in SCENARIOS.items():
loaded = json.loads(load_preset(scenario_id))
out = _evaluate(scenario_id, loaded["trace"], loaded["policy"])
expected = scenario["expected"]
actual = out["verdict"]
row = {
"id": scenario_id,
"expected": expected,
"actual": actual,
"match": actual == expected,
"reason": out["reason"],
"integrity": out["integrity"],
}
results.append(row)
if not row["match"] or out["integrity"] != "passed":
failures.append(row)
return json.dumps(
{
"total": len(SCENARIOS),
"passed": len(SCENARIOS) - len(failures),
"failed": len(failures),
"failures": failures,
"results": results,
}
)
def tamper_and_verify(envelope_json: str, field: str = "reason") -> str:
"""Mutate one envelope field and run the library verifier without recomputing the digest."""
try:
envelope = json.loads(envelope_json)
if not isinstance(envelope, dict):
raise ValueError("envelope must be a JSON object")
except Exception as exc:
return json.dumps(
{
"detected": False,
"error": f"invalid envelope JSON: {exc}",
"field": field,
}
)
original = envelope.get(field)
if field == "reason":
envelope["reason"] = f"{original} [tampered]"
elif field == "verdict":
envelope["verdict"] = "ALLOW" if original != "ALLOW" else "BLOCK"
else:
envelope[field] = f"{original} [tampered]"
tampered = envelope.get(field)
try:
verify_envelope(envelope)
return json.dumps(
{
"detected": False,
"error": None,
"field": field,
"original": original,
"tampered": tampered,
"envelope_text": _pretty_json(envelope),
}
)
except Exception as exc:
return json.dumps(
{
"detected": True,
"error": str(exc),
"field": field,
"original": original,
"tampered": tampered,
"envelope_text": _pretty_json(envelope),
}
)