File size: 7,521 Bytes
665bfb9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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),
        }
    )