File size: 12,804 Bytes
c77a5a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46cddde
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c77a5a3
 
 
 
 
 
 
46cddde
 
 
 
c77a5a3
 
 
 
 
46cddde
 
c77a5a3
46cddde
c77a5a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46cddde
c77a5a3
 
 
 
 
 
 
 
 
46cddde
c77a5a3
 
46cddde
 
 
 
 
 
c77a5a3
 
 
 
46cddde
c77a5a3
46cddde
 
 
c77a5a3
46cddde
 
 
 
c77a5a3
46cddde
c77a5a3
 
46cddde
c77a5a3
 
46cddde
c77a5a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46cddde
 
 
c77a5a3
 
 
 
 
 
 
46cddde
c77a5a3
 
 
 
46cddde
c77a5a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46cddde
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
"""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),
            }
        )