Datasets:
Download source/tests/test_security3.py from dnakhla/terminal-desk: direct link, hf CLI and curl.
- Browser
- Download file 5.27 kB
-
https://huggingface.co/datasets/dnakhla/terminal-desk/resolve/main/source/tests/test_security3.py
- Command line
-
hf download hf://datasets/dnakhla/terminal-desk/source/tests/test_security3.py
-
curl -L -o test_security3.py https://huggingface.co/datasets/dnakhla/terminal-desk/resolve/main/source/tests/test_security3.py
5.27 kB
| """Cybersecurity v3 families: for every task id and three seeds the render and the oracle script score 1; | |
| no file, an empty file and a one-value-perturbed file score 0; and each level's caveat changes the answer | |
| (an oracle that ignores it scores 0).""" | |
| import json | |
| import pytest | |
| from test_episodes import _evaluate, _write_oracle # noqa: F401 (sets TERMINAL_DESK_ROOTS first) | |
| from terminal_desk.core.grading import render_artifact | |
| from terminal_desk.families import FAMILIES | |
| from terminal_desk.models import Tbench2Action | |
| from terminal_desk.oracles import oracle_source, run_oracle | |
| from terminal_desk.server.environment import TerminalDeskEnvironment | |
| FAMS = ("sec3_auth_triage", "sec3_fw_verdicts", "sec3_exfil_flows") | |
| TASKS = [f"{f}-L{lv}" for f in FAMS for lv in (1, 2, 3)] | |
| SEEDS = (1, 2, 3) | |
| def _reset(task_id: str, seed: int) -> TerminalDeskEnvironment: | |
| env = TerminalDeskEnvironment(allow_seed=True) | |
| env.reset(task_id=task_id, seed=seed) | |
| return env | |
| def _write(env, content: str): | |
| path = env._ep["built"].artifact.path | |
| obs = env.step(Tbench2Action(action_type="write_file", file_path=path, content=content)) | |
| assert obs.success, obs.error | |
| def _perturb(family: str, content: str) -> str: | |
| """Change exactly one value of a correct answer.""" | |
| if family == "sec3_auth_triage": | |
| lines = content.splitlines() | |
| lines[-1] = "192.0.2.77" # one blocked address swapped for an innocent one | |
| return "\n".join(lines) + "\n" | |
| if family == "sec3_fw_verdicts": | |
| lines = content.splitlines() | |
| cid, verdict, rule = lines[1].split(",") | |
| lines[1] = f"{cid},{'deny' if verdict == 'allow' else 'allow'},{rule}" | |
| return "\n".join(lines) + "\n" | |
| ids = json.loads(content) | |
| return json.dumps(ids[1:]) + "\n" # one alert missed | |
| def test_families_are_registered_as_v3(): | |
| for fid in FAMS: | |
| assert FAMILIES[fid].v3 and FAMILIES[fid].domain == "cybersecurity" and FAMILIES[fid].levels == (1, 2, 3) | |
| def test_render_and_oracle_script_score_one(task_id, seed): | |
| env = _reset(task_id, seed) | |
| built = env._ep["built"] | |
| assert built.root == "/root" and 600 <= len(built.instruction) <= 1000 | |
| assert f"/root/{built.artifact.path}" in built.instruction | |
| _write_oracle(env) | |
| obs = _evaluate(env) | |
| assert obs.reward == 1.0, obs.output | |
| env.reset(task_id=task_id, seed=seed) | |
| out, obs = run_oracle(env, oracle_source(task_id.rpartition("-L")[0])) | |
| assert obs.reward == 1.0, (out, obs.output) | |
| def test_missing_empty_and_perturbed_files_score_zero(task_id, seed): | |
| family = task_id.rpartition("-L")[0] | |
| env = _reset(task_id, seed) | |
| assert _evaluate(env).reward == 0.0 | |
| env.reset(task_id=task_id, seed=seed) | |
| _write(env, "") | |
| assert _evaluate(env).reward == 0.0 | |
| env.reset(task_id=task_id, seed=seed) | |
| content = render_artifact(env._ep["built"].artifact) | |
| wrong = _perturb(family, content) | |
| assert wrong != content | |
| _write(env, wrong) | |
| obs = _evaluate(env) | |
| assert obs.reward == 0.0 and "FAILED" in obs.output | |
| # Each mutation removes one rule or caveat from the oracle; the generator guarantees it changes the answer. | |
| MUTATIONS = [ | |
| ("sec3_auth_triage-L1", "ts[i + K - 1] - ts[i] <= WINDOW", "True"), # total count, no window | |
| ("sec3_auth_triage-L2", 'allow = [ipaddress.ip_network(n) for n in re.findall(r"\\d+\\.\\d+\\.\\d+\\.\\d+/\\d+", notes)]', | |
| "allow = []"), # audit scanner network ignored | |
| ("sec3_auth_triage-L2", 'hit = re.match(r"Failed password for .* from (\\S+)$", msg)', | |
| 'hit = re.match(r"(?:Failed password for|Invalid user) .* from (\\S+)$", msg)'), # notices counted | |
| ("sec3_auth_triage-L3", 'for name in ("auth.log.1", "auth.log"):', 'for name in ("auth.log",):'), # rotated file | |
| ("sec3_auth_triage-L3", "fails[rep.group(2)] += [t] * int(rep.group(1))", "pass"), # repeated lines dropped | |
| ("sec3_fw_verdicts-L1", "ports.update(range(int(lo), int(hi or lo) + 1))", "ports.update(range(int(lo), int(hi or lo)))"), | |
| ("sec3_fw_verdicts-L2", "rules.sort(key=lambda r: r[0])", "pass"), # file order instead of rule_no | |
| ("sec3_fw_verdicts-L3", 'if r.get("enabled", "yes") != "yes":', "if False:"), # disabled rules loaded | |
| ("sec3_exfil_flows-L1", 'float(r["mb_out"]) > policy["threshold_mb"]', 'float(r["mb_out"]) >= policy["threshold_mb"]'), | |
| ("sec3_exfil_flows-L1", "not start <= minute < end", "not start <= minute <= end"), # closing time inclusive | |
| ("sec3_exfil_flows-L2", "and not any(dst in n for n in internal)", ""), # internal traffic alerts | |
| ("sec3_exfil_flows-L3", 'policy.get("office_utc_offset_hours", 0) * 60', "0"), # UTC taken as local | |
| ] | |
| def test_oracle_without_a_caveat_scores_zero(task_id, old, new): | |
| source = oracle_source(task_id.rpartition("-L")[0]) | |
| assert old in source | |
| broken = source.replace(old, new) | |
| for seed in SEEDS: | |
| env = _reset(task_id, seed) | |
| out, obs = run_oracle(env, broken) | |
| assert "@@oracle-exit=0" in out, out | |
| assert obs.reward == 0.0, (seed, out) | |