redloop 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- redloop/__init__.py +5 -0
- redloop/__main__.py +3 -0
- redloop/cli.py +431 -0
- redloop/config.py +130 -0
- redloop/converters.py +273 -0
- redloop/crosswalk.py +63 -0
- redloop/data/aixwalk/README.md +8 -0
- redloop/data/aixwalk/crosswalk.json +452 -0
- redloop/data/aixwalk/frameworks/iso-42001-annex-a.json +45 -0
- redloop/data/aixwalk/frameworks/mitre-atlas.json +949 -0
- redloop/data/aixwalk/frameworks/nist-ai-rmf-1.0.json +369 -0
- redloop/data/aixwalk/frameworks/owasp-agentic-2026.json +49 -0
- redloop/data/aixwalk/frameworks/owasp-llm-2025.json +49 -0
- redloop/data/maturity-model.json +425 -0
- redloop/data/templates/assessment.toml +41 -0
- redloop/data/templates/redloop.toml +41 -0
- redloop/data/templates/risk-acceptances.toml +11 -0
- redloop/data/templates/threatmodel.toml +136 -0
- redloop/detectors.py +138 -0
- redloop/evidence.py +140 -0
- redloop/governance.py +106 -0
- redloop/maturity.py +340 -0
- redloop/probes/__init__.py +48 -0
- redloop/probes/base.py +194 -0
- redloop/probes/catalog.py +383 -0
- redloop/py.typed +0 -0
- redloop/report/__init__.py +22 -0
- redloop/report/jsonout.py +13 -0
- redloop/report/md.py +98 -0
- redloop/report/sarif.py +103 -0
- redloop/report/text.py +90 -0
- redloop/results.py +253 -0
- redloop/runner.py +99 -0
- redloop/sandbox.py +207 -0
- redloop/targets/__init__.py +59 -0
- redloop/targets/base.py +109 -0
- redloop/targets/http.py +132 -0
- redloop/targets/mock.py +254 -0
- redloop/targets/openai.py +145 -0
- redloop/targets/transport.py +125 -0
- redloop/threats.py +485 -0
- redloop/util.py +135 -0
- redloop-0.1.0.dist-info/METADATA +278 -0
- redloop-0.1.0.dist-info/RECORD +48 -0
- redloop-0.1.0.dist-info/WHEEL +4 -0
- redloop-0.1.0.dist-info/entry_points.txt +2 -0
- redloop-0.1.0.dist-info/licenses/LICENSE +202 -0
- redloop-0.1.0.dist-info/licenses/NOTICE +16 -0
redloop/report/text.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Console report."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import TYPE_CHECKING
|
|
6
|
+
|
|
7
|
+
if TYPE_CHECKING: # pragma: no cover
|
|
8
|
+
from ..results import RunResult
|
|
9
|
+
|
|
10
|
+
_COLORS = {
|
|
11
|
+
"critical": "\033[1;31m",
|
|
12
|
+
"high": "\033[31m",
|
|
13
|
+
"medium": "\033[33m",
|
|
14
|
+
"low": "\033[36m",
|
|
15
|
+
"info": "\033[37m",
|
|
16
|
+
"ok": "\033[32m",
|
|
17
|
+
"dim": "\033[2m",
|
|
18
|
+
"bold": "\033[1m",
|
|
19
|
+
"reset": "\033[0m",
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _target_label(target: dict) -> str:
|
|
24
|
+
kind = target.get("type", "?")
|
|
25
|
+
if kind == "mock":
|
|
26
|
+
return f"mock (preset: {target.get('preset')})"
|
|
27
|
+
if kind == "openai":
|
|
28
|
+
return f"openai-compatible {target.get('base_url')} model={target.get('model')}"
|
|
29
|
+
if kind == "http":
|
|
30
|
+
return f"http {target.get('url')}"
|
|
31
|
+
return kind
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def render_text(run: RunResult, color: bool = False) -> str:
|
|
35
|
+
def c(name: str, text: str) -> str:
|
|
36
|
+
return f"{_COLORS[name]}{text}{_COLORS['reset']}" if color else text
|
|
37
|
+
|
|
38
|
+
from .. import __version__
|
|
39
|
+
|
|
40
|
+
m = run.metrics
|
|
41
|
+
lines = [
|
|
42
|
+
c("bold", f"redloop {__version__}") + f" target: {_target_label(run.target)}",
|
|
43
|
+
f"run {run.run_id} probes: {m['probes_total']} attempts: {m['attempts']} "
|
|
44
|
+
f"duration: {run.duration_s:.2f}s",
|
|
45
|
+
"",
|
|
46
|
+
]
|
|
47
|
+
accepted = {f.probe_id: f for f in run.findings}
|
|
48
|
+
for r in run.probe_results:
|
|
49
|
+
p = r.probe
|
|
50
|
+
if r.status == "bypassed":
|
|
51
|
+
f = accepted.get(p.id)
|
|
52
|
+
sev = f.severity if f else p.severity
|
|
53
|
+
how = "baseline"
|
|
54
|
+
if r.first_success and r.first_success.round > 0:
|
|
55
|
+
chain = "+".join(r.first_success.converters)
|
|
56
|
+
how = f"after mutation: {chain}" if chain != "paraphrase" else "paraphrase inconsistency"
|
|
57
|
+
tag = c(sev, f"BYPASSED {sev:<8}")
|
|
58
|
+
suffix = ""
|
|
59
|
+
if f and f.accepted:
|
|
60
|
+
suffix = c("dim", " [risk accepted]")
|
|
61
|
+
elif f and f.acceptance_status == "expired":
|
|
62
|
+
suffix = c("high", " [acceptance expired]")
|
|
63
|
+
lines.append(f" {tag} {p.id:<11} {p.title} ({how}){suffix}")
|
|
64
|
+
elif r.status == "defended":
|
|
65
|
+
lines.append(f" {c('ok', 'defended')} {'':<8} {p.id:<11} {p.title} ({len(r.attempts)} attempts)")
|
|
66
|
+
else:
|
|
67
|
+
lines.append(f" {c('dim', f'{r.status:<9}')} {'':<8} {p.id:<11} {p.title} ({r.reason})")
|
|
68
|
+
lines.append("")
|
|
69
|
+
lines.append(
|
|
70
|
+
f"Attack success rate: {m['asr']:.0%} ({m['probes_bypassed']}/{m['probes_executed']} probes)"
|
|
71
|
+
f" - {m['bypassed_after_mutation']} bypassed only after mutation"
|
|
72
|
+
)
|
|
73
|
+
adv = ", ".join(
|
|
74
|
+
f"{k} {v['bypassed']}/{v['executed']}" for k, v in m["by_adversarial_category"].items()
|
|
75
|
+
)
|
|
76
|
+
if adv:
|
|
77
|
+
lines.append(f"By adversarial category: {adv}")
|
|
78
|
+
if "coverage" in m:
|
|
79
|
+
cov = m["coverage"]
|
|
80
|
+
lines.append(
|
|
81
|
+
f"Threat coverage: {cov['covered']}/{cov['testable']} testable threats exercised "
|
|
82
|
+
f"({cov['manual']} manual)"
|
|
83
|
+
)
|
|
84
|
+
for note in run.notes:
|
|
85
|
+
lines.append(c("high", f"note: {note}"))
|
|
86
|
+
if run.gate.passed:
|
|
87
|
+
lines.append(c("ok", f"Gate: PASSED (fail-on {run.gate.fail_on})"))
|
|
88
|
+
else:
|
|
89
|
+
lines.append(c("critical", "Gate: FAILED - " + "; ".join(run.gate.reasons)))
|
|
90
|
+
return "\n".join(lines) + "\n"
|
redloop/results.py
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
"""Findings, metrics and the CI gate."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from . import crosswalk
|
|
10
|
+
from .probes import SEVERITIES, ProbeResult, severity_rank
|
|
11
|
+
from .threats import Threat
|
|
12
|
+
from .util import excerpt
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass
|
|
16
|
+
class Finding:
|
|
17
|
+
fingerprint: str
|
|
18
|
+
probe_id: str
|
|
19
|
+
title: str
|
|
20
|
+
severity: str
|
|
21
|
+
aix: list[str]
|
|
22
|
+
adversarial_category: str
|
|
23
|
+
round: int
|
|
24
|
+
converters: list[str]
|
|
25
|
+
case: str
|
|
26
|
+
evidence: str
|
|
27
|
+
prompt_excerpt: str
|
|
28
|
+
response_excerpt: str
|
|
29
|
+
remediation: str
|
|
30
|
+
threat_ids: list[str] = field(default_factory=list)
|
|
31
|
+
accepted: bool = False
|
|
32
|
+
acceptance_status: str | None = None # active | expired
|
|
33
|
+
acceptance: dict[str, Any] | None = None
|
|
34
|
+
|
|
35
|
+
@property
|
|
36
|
+
def mappings(self) -> dict[str, list[str]]:
|
|
37
|
+
return crosswalk.mappings_for(self.aix)
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
def after_mutation(self) -> bool:
|
|
41
|
+
return self.round > 0 and self.converters != ["paraphrase"]
|
|
42
|
+
|
|
43
|
+
def to_dict(self) -> dict[str, Any]:
|
|
44
|
+
return {
|
|
45
|
+
"fingerprint": self.fingerprint,
|
|
46
|
+
"probe": self.probe_id,
|
|
47
|
+
"title": self.title,
|
|
48
|
+
"severity": self.severity,
|
|
49
|
+
"aix": self.aix,
|
|
50
|
+
"adversarial_category": self.adversarial_category,
|
|
51
|
+
"round": self.round,
|
|
52
|
+
"converters": self.converters,
|
|
53
|
+
"after_mutation": self.after_mutation,
|
|
54
|
+
"case": self.case,
|
|
55
|
+
"evidence": self.evidence,
|
|
56
|
+
"prompt_excerpt": self.prompt_excerpt,
|
|
57
|
+
"response_excerpt": self.response_excerpt,
|
|
58
|
+
"remediation": self.remediation,
|
|
59
|
+
"threats": self.threat_ids,
|
|
60
|
+
"accepted": self.accepted,
|
|
61
|
+
"acceptance_status": self.acceptance_status,
|
|
62
|
+
"acceptance": self.acceptance,
|
|
63
|
+
"mappings": self.mappings,
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def target_key(descriptor: dict[str, Any]) -> str:
|
|
68
|
+
kind = descriptor.get("type", "?")
|
|
69
|
+
detail = descriptor.get("preset") or descriptor.get("model") or ""
|
|
70
|
+
where = descriptor.get("base_url") or descriptor.get("url") or ""
|
|
71
|
+
return f"{kind}|{where}|{detail}"
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def fingerprint(probe_id: str, descriptor: dict[str, Any]) -> str:
|
|
75
|
+
return hashlib.sha256(f"{probe_id}|{target_key(descriptor)}".encode()).hexdigest()[:16]
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def make_findings(
|
|
79
|
+
results: list[ProbeResult], descriptor: dict[str, Any], threats: list[Threat] | None = None
|
|
80
|
+
) -> list[Finding]:
|
|
81
|
+
threats = threats or []
|
|
82
|
+
findings = []
|
|
83
|
+
for r in results:
|
|
84
|
+
if not r.bypassed or r.first_success is None:
|
|
85
|
+
continue
|
|
86
|
+
att = r.first_success
|
|
87
|
+
linked = [t for t in threats if r.probe.id in t.probes]
|
|
88
|
+
severity = r.probe.severity
|
|
89
|
+
for t in linked: # business context can raise, never lower, severity
|
|
90
|
+
if severity_rank(t.severity) > severity_rank(severity):
|
|
91
|
+
severity = t.severity
|
|
92
|
+
prompt = att.exchange.user_text() or "\n".join(att.exchange.documents)
|
|
93
|
+
resp_text = att.response.text if att.response else ""
|
|
94
|
+
if att.response and att.response.tool_calls and not resp_text:
|
|
95
|
+
resp_text = "; ".join(f"{c.name}({c.arguments})" for c in att.response.tool_calls)
|
|
96
|
+
findings.append(
|
|
97
|
+
Finding(
|
|
98
|
+
fingerprint=fingerprint(r.probe.id, descriptor),
|
|
99
|
+
probe_id=r.probe.id,
|
|
100
|
+
title=r.probe.title,
|
|
101
|
+
severity=severity,
|
|
102
|
+
aix=list(r.probe.aix),
|
|
103
|
+
adversarial_category=r.probe.adversarial_category,
|
|
104
|
+
round=att.round,
|
|
105
|
+
converters=list(att.converters),
|
|
106
|
+
case=att.case,
|
|
107
|
+
evidence=att.evidence,
|
|
108
|
+
prompt_excerpt=excerpt(prompt),
|
|
109
|
+
response_excerpt=excerpt(resp_text),
|
|
110
|
+
remediation=r.probe.remediation,
|
|
111
|
+
threat_ids=[t.id for t in linked],
|
|
112
|
+
)
|
|
113
|
+
)
|
|
114
|
+
order = {s: i for i, s in enumerate(reversed(SEVERITIES))}
|
|
115
|
+
findings.sort(key=lambda f: (order[f.severity], f.probe_id))
|
|
116
|
+
return findings
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _rate(bypassed: int, executed: int) -> float:
|
|
120
|
+
return round(bypassed / executed, 4) if executed else 0.0
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def compute_metrics(
|
|
124
|
+
results: list[ProbeResult], findings: list[Finding], threats: list[Threat] | None = None
|
|
125
|
+
) -> dict[str, Any]:
|
|
126
|
+
executed = [r for r in results if r.executed]
|
|
127
|
+
bypassed = [r for r in executed if r.bypassed]
|
|
128
|
+
accepted_ids = {f.probe_id for f in findings if f.accepted}
|
|
129
|
+
by_aix: dict[str, dict[str, Any]] = {}
|
|
130
|
+
by_adv: dict[str, dict[str, Any]] = {}
|
|
131
|
+
for r in executed:
|
|
132
|
+
for aix in r.probe.aix:
|
|
133
|
+
row = by_aix.setdefault(aix, {"name": crosswalk.category_name(aix), "executed": 0, "bypassed": 0})
|
|
134
|
+
row["executed"] += 1
|
|
135
|
+
row["bypassed"] += int(r.bypassed)
|
|
136
|
+
row = by_adv.setdefault(r.probe.adversarial_category, {"executed": 0, "bypassed": 0})
|
|
137
|
+
row["executed"] += 1
|
|
138
|
+
row["bypassed"] += int(r.bypassed)
|
|
139
|
+
for table in (by_aix, by_adv):
|
|
140
|
+
for row in table.values():
|
|
141
|
+
row["asr"] = _rate(row["bypassed"], row["executed"])
|
|
142
|
+
metrics: dict[str, Any] = {
|
|
143
|
+
"probes_total": len(results),
|
|
144
|
+
"probes_executed": len(executed),
|
|
145
|
+
"probes_skipped": sum(1 for r in results if r.status == "skipped"),
|
|
146
|
+
"probes_errored": sum(1 for r in results if r.status == "error"),
|
|
147
|
+
"probes_bypassed": len(bypassed),
|
|
148
|
+
"bypassed_after_mutation": sum(1 for r in bypassed if r.bypassed_after_mutation),
|
|
149
|
+
"defended": len(executed) - len(bypassed),
|
|
150
|
+
"attempts": sum(len(r.attempts) for r in results),
|
|
151
|
+
"asr": _rate(len(bypassed), len(executed)),
|
|
152
|
+
"gate_asr": _rate(len([r for r in bypassed if r.probe.id not in accepted_ids]), len(executed)),
|
|
153
|
+
"by_aix": dict(sorted(by_aix.items())),
|
|
154
|
+
"by_adversarial_category": dict(sorted(by_adv.items())),
|
|
155
|
+
}
|
|
156
|
+
if threats is not None:
|
|
157
|
+
ran = {r.probe.id for r in executed}
|
|
158
|
+
testable = [t for t in threats if t.testable]
|
|
159
|
+
covered = [t for t in testable if set(t.probes) & ran]
|
|
160
|
+
metrics["coverage"] = {
|
|
161
|
+
"threats": len(threats),
|
|
162
|
+
"testable": len(testable),
|
|
163
|
+
"covered": len(covered),
|
|
164
|
+
"manual": len(threats) - len(testable),
|
|
165
|
+
"ratio": _rate(len(covered), len(testable)),
|
|
166
|
+
"uncovered": [t.id for t in testable if t not in covered],
|
|
167
|
+
}
|
|
168
|
+
return metrics
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
@dataclass
|
|
172
|
+
class Gate:
|
|
173
|
+
fail_on: str
|
|
174
|
+
max_asr: float | None
|
|
175
|
+
passed: bool
|
|
176
|
+
reasons: list[str]
|
|
177
|
+
|
|
178
|
+
def to_dict(self) -> dict[str, Any]:
|
|
179
|
+
return {"fail_on": self.fail_on, "max_asr": self.max_asr, "passed": self.passed, "reasons": self.reasons}
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def evaluate_gate(
|
|
183
|
+
findings: list[Finding], metrics: dict[str, Any], fail_on: str, max_asr: float | None
|
|
184
|
+
) -> Gate:
|
|
185
|
+
reasons = []
|
|
186
|
+
blocking = [
|
|
187
|
+
f for f in findings if not f.accepted and severity_rank(f.severity) >= severity_rank(fail_on)
|
|
188
|
+
]
|
|
189
|
+
if blocking:
|
|
190
|
+
reasons.append(f"{len(blocking)} unaccepted finding(s) at or above {fail_on}")
|
|
191
|
+
if max_asr is not None and metrics["gate_asr"] > max_asr:
|
|
192
|
+
reasons.append(f"attack success rate {metrics['gate_asr']:.0%} exceeds max_asr {max_asr:.0%}")
|
|
193
|
+
if metrics["probes_executed"] == 0:
|
|
194
|
+
reasons.append("no probes were executed")
|
|
195
|
+
return Gate(fail_on, max_asr, not reasons, reasons)
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
@dataclass
|
|
199
|
+
class RunResult:
|
|
200
|
+
run_id: str
|
|
201
|
+
started: str
|
|
202
|
+
finished: str
|
|
203
|
+
duration_s: float
|
|
204
|
+
target: dict[str, Any]
|
|
205
|
+
probe_results: list[ProbeResult]
|
|
206
|
+
findings: list[Finding]
|
|
207
|
+
metrics: dict[str, Any]
|
|
208
|
+
gate: Gate
|
|
209
|
+
threats: list[Threat] | None = None
|
|
210
|
+
notes: list[str] = field(default_factory=list)
|
|
211
|
+
config_path: str | None = None
|
|
212
|
+
config_sha256: str | None = None
|
|
213
|
+
threat_model_path: str | None = None
|
|
214
|
+
seed: str = ""
|
|
215
|
+
|
|
216
|
+
def to_dict(self, include_attempts: bool = False) -> dict[str, Any]:
|
|
217
|
+
from . import __version__
|
|
218
|
+
|
|
219
|
+
probes = []
|
|
220
|
+
for r in self.probe_results:
|
|
221
|
+
row: dict[str, Any] = {
|
|
222
|
+
"id": r.probe.id,
|
|
223
|
+
"title": r.probe.title,
|
|
224
|
+
"status": r.status,
|
|
225
|
+
"aix": list(r.probe.aix),
|
|
226
|
+
"adversarial_category": r.probe.adversarial_category,
|
|
227
|
+
"severity": r.probe.severity,
|
|
228
|
+
"attempts": len(r.attempts),
|
|
229
|
+
"reason": r.reason,
|
|
230
|
+
"bypassed_after_mutation": r.bypassed_after_mutation,
|
|
231
|
+
}
|
|
232
|
+
if include_attempts:
|
|
233
|
+
row["attempt_log"] = [a.to_record() for a in r.attempts]
|
|
234
|
+
probes.append(row)
|
|
235
|
+
out: dict[str, Any] = {
|
|
236
|
+
"schema": "redloop.run/v1",
|
|
237
|
+
"redloop_version": __version__,
|
|
238
|
+
"run_id": self.run_id,
|
|
239
|
+
"started": self.started,
|
|
240
|
+
"finished": self.finished,
|
|
241
|
+
"duration_s": self.duration_s,
|
|
242
|
+
"target": self.target,
|
|
243
|
+
"config": {"path": self.config_path, "sha256": self.config_sha256},
|
|
244
|
+
"threat_model": self.threat_model_path,
|
|
245
|
+
"gate": self.gate.to_dict(),
|
|
246
|
+
"metrics": self.metrics,
|
|
247
|
+
"findings": [f.to_dict() for f in self.findings],
|
|
248
|
+
"probes": probes,
|
|
249
|
+
"notes": self.notes,
|
|
250
|
+
}
|
|
251
|
+
if self.threats is not None:
|
|
252
|
+
out["threats"] = [t.to_dict() for t in self.threats]
|
|
253
|
+
return out
|
redloop/runner.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""Execution engine: runs probes against a target with adaptive mutation and builds results."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import datetime as _dt
|
|
6
|
+
import hashlib
|
|
7
|
+
import secrets
|
|
8
|
+
import time
|
|
9
|
+
from collections.abc import Callable
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
|
|
12
|
+
from .config import Policy
|
|
13
|
+
from .converters import Scheduler, all_chains
|
|
14
|
+
from .governance import Acceptance, apply_acceptances
|
|
15
|
+
from .probes import Probe, ProbeContext, ProbeResult
|
|
16
|
+
from .results import RunResult, compute_metrics, evaluate_gate, make_findings
|
|
17
|
+
from .targets.base import Target
|
|
18
|
+
from .threats import Threat
|
|
19
|
+
from .util import iso, utcnow
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def canary_for(seed: str, probe_id: str) -> str:
|
|
23
|
+
digest = hashlib.sha256(f"{seed}:{probe_id}".encode()).hexdigest()
|
|
24
|
+
return "RL-" + digest[:6].upper()
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class Runner:
|
|
29
|
+
"""Holds per-run state (seed, scheduler) so probes can run one by one, e.g. in sandboxes."""
|
|
30
|
+
|
|
31
|
+
rounds: int = 10
|
|
32
|
+
max_depth: int = 2
|
|
33
|
+
seed: str = field(default_factory=lambda: secrets.token_hex(4))
|
|
34
|
+
policy: Policy = field(default_factory=Policy)
|
|
35
|
+
progress: Callable[[ProbeResult], None] | None = None
|
|
36
|
+
|
|
37
|
+
def __post_init__(self) -> None:
|
|
38
|
+
self.scheduler = Scheduler(all_chains(self.max_depth))
|
|
39
|
+
self.results: list[ProbeResult] = []
|
|
40
|
+
self.started = utcnow()
|
|
41
|
+
self._t0 = time.perf_counter()
|
|
42
|
+
|
|
43
|
+
def context(self, probe: Probe, target: Target) -> ProbeContext:
|
|
44
|
+
return ProbeContext(
|
|
45
|
+
canary=canary_for(self.seed, probe.id),
|
|
46
|
+
base_system=target.default_system_prompt,
|
|
47
|
+
must_refuse=list(self.policy.must_refuse),
|
|
48
|
+
must_answer=list(self.policy.must_answer),
|
|
49
|
+
allowed_domains=list(self.policy.allowed_domains),
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
def run_probe(self, target: Target, probe: Probe) -> ProbeResult:
|
|
53
|
+
result = probe.run(target, self.context(probe, target), self.scheduler, self.rounds)
|
|
54
|
+
self.results.append(result)
|
|
55
|
+
if self.progress:
|
|
56
|
+
self.progress(result)
|
|
57
|
+
return result
|
|
58
|
+
|
|
59
|
+
def run(self, target: Target, probes: list[Probe]) -> list[ProbeResult]:
|
|
60
|
+
for probe in probes:
|
|
61
|
+
self.run_probe(target, probe)
|
|
62
|
+
return self.results
|
|
63
|
+
|
|
64
|
+
def finish(
|
|
65
|
+
self,
|
|
66
|
+
descriptor: dict,
|
|
67
|
+
*,
|
|
68
|
+
threats: list[Threat] | None = None,
|
|
69
|
+
acceptances: list[Acceptance] | None = None,
|
|
70
|
+
fail_on: str = "high",
|
|
71
|
+
max_asr: float | None = None,
|
|
72
|
+
today: _dt.date | None = None,
|
|
73
|
+
config_path: str | None = None,
|
|
74
|
+
config_sha256: str | None = None,
|
|
75
|
+
threat_model_path: str | None = None,
|
|
76
|
+
) -> RunResult:
|
|
77
|
+
findings = make_findings(self.results, descriptor, threats)
|
|
78
|
+
notes = apply_acceptances(findings, acceptances or [], today)
|
|
79
|
+
metrics = compute_metrics(self.results, findings, threats)
|
|
80
|
+
gate = evaluate_gate(findings, metrics, fail_on, max_asr)
|
|
81
|
+
finished = utcnow()
|
|
82
|
+
run_id = secrets.token_hex(4)
|
|
83
|
+
return RunResult(
|
|
84
|
+
run_id=run_id,
|
|
85
|
+
started=iso(self.started),
|
|
86
|
+
finished=iso(finished),
|
|
87
|
+
duration_s=round(time.perf_counter() - self._t0, 3),
|
|
88
|
+
target=descriptor,
|
|
89
|
+
probe_results=list(self.results),
|
|
90
|
+
findings=findings,
|
|
91
|
+
metrics=metrics,
|
|
92
|
+
gate=gate,
|
|
93
|
+
threats=threats,
|
|
94
|
+
notes=notes,
|
|
95
|
+
config_path=config_path,
|
|
96
|
+
config_sha256=config_sha256,
|
|
97
|
+
threat_model_path=threat_model_path,
|
|
98
|
+
seed=self.seed,
|
|
99
|
+
)
|
redloop/sandbox.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
"""Ephemeral container sandbox for production-safe testing.
|
|
2
|
+
|
|
3
|
+
Each run (or each probe) gets a fresh container started from an image of the system
|
|
4
|
+
under test. The suite runs against the container's mapped port, container logs are
|
|
5
|
+
captured into the evidence bundle for forensic review, and the container is always
|
|
6
|
+
removed afterwards, so no test can leave persistent state behind.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import subprocess
|
|
12
|
+
import time
|
|
13
|
+
import urllib.error
|
|
14
|
+
import urllib.request
|
|
15
|
+
from collections.abc import Callable
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
from typing import Any
|
|
18
|
+
from urllib.parse import urlsplit, urlunsplit
|
|
19
|
+
|
|
20
|
+
from .util import ConfigError
|
|
21
|
+
|
|
22
|
+
Runner = Callable[..., subprocess.CompletedProcess]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass
|
|
26
|
+
class SandboxConfig:
|
|
27
|
+
image: str
|
|
28
|
+
container_port: int
|
|
29
|
+
env: dict[str, str] = field(default_factory=dict)
|
|
30
|
+
ready_path: str = "/"
|
|
31
|
+
ready_timeout_s: float = 60.0
|
|
32
|
+
isolation: str = "per-run"
|
|
33
|
+
extra_args: list[str] = field(default_factory=list)
|
|
34
|
+
command: list[str] = field(default_factory=list)
|
|
35
|
+
docker: str = "docker"
|
|
36
|
+
|
|
37
|
+
@classmethod
|
|
38
|
+
def from_dict(cls, raw: dict[str, Any]) -> SandboxConfig:
|
|
39
|
+
if not raw.get("image") or not raw.get("container_port"):
|
|
40
|
+
raise ConfigError("[sandbox] requires image and container_port")
|
|
41
|
+
isolation = str(raw.get("isolation", "per-run"))
|
|
42
|
+
if isolation not in ("per-run", "per-probe"):
|
|
43
|
+
raise ConfigError("[sandbox] isolation must be per-run or per-probe")
|
|
44
|
+
extra = raw.get("extra_args", [])
|
|
45
|
+
if not isinstance(extra, list) or not all(isinstance(a, str) for a in extra):
|
|
46
|
+
raise ConfigError("[sandbox] extra_args must be a list of strings")
|
|
47
|
+
command = raw.get("command", [])
|
|
48
|
+
if not isinstance(command, list) or not all(isinstance(a, str) for a in command):
|
|
49
|
+
raise ConfigError("[sandbox] command must be a list of strings")
|
|
50
|
+
return cls(
|
|
51
|
+
image=str(raw["image"]),
|
|
52
|
+
container_port=int(raw["container_port"]),
|
|
53
|
+
env={str(k): str(v) for k, v in raw.get("env", {}).items()},
|
|
54
|
+
ready_path="/" + str(raw.get("ready_path", "/")).lstrip("/"),
|
|
55
|
+
ready_timeout_s=float(raw.get("ready_timeout_s", 60)),
|
|
56
|
+
isolation=isolation,
|
|
57
|
+
extra_args=list(extra),
|
|
58
|
+
command=list(command),
|
|
59
|
+
docker=str(raw.get("docker", "docker")),
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class SandboxError(Exception):
|
|
64
|
+
pass
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class Sandbox:
|
|
68
|
+
"""One container lifecycle: start -> wait ready -> (tests) -> logs -> remove."""
|
|
69
|
+
|
|
70
|
+
def __init__(
|
|
71
|
+
self,
|
|
72
|
+
cfg: SandboxConfig,
|
|
73
|
+
run: Runner = subprocess.run,
|
|
74
|
+
urlopen: Callable[..., Any] = urllib.request.urlopen,
|
|
75
|
+
sleep: Callable[[float], None] = time.sleep,
|
|
76
|
+
clock: Callable[[], float] = time.monotonic,
|
|
77
|
+
) -> None:
|
|
78
|
+
self.cfg = cfg
|
|
79
|
+
self._run = run
|
|
80
|
+
self._urlopen = urlopen
|
|
81
|
+
self._sleep = sleep
|
|
82
|
+
self._clock = clock
|
|
83
|
+
self.container_id: str | None = None
|
|
84
|
+
self.host_port: int | None = None
|
|
85
|
+
|
|
86
|
+
def _docker(self, *args: str) -> str:
|
|
87
|
+
proc = self._run(
|
|
88
|
+
[self.cfg.docker, *args], capture_output=True, text=True, check=False, timeout=120
|
|
89
|
+
)
|
|
90
|
+
if proc.returncode != 0:
|
|
91
|
+
raise SandboxError(f"docker {args[0]} failed: {(proc.stderr or '').strip()}")
|
|
92
|
+
return (proc.stdout or "").strip()
|
|
93
|
+
|
|
94
|
+
def start(self) -> str:
|
|
95
|
+
cmd = ["run", "-d", "--rm", "-p", f"127.0.0.1::{self.cfg.container_port}"]
|
|
96
|
+
for key, val in sorted(self.cfg.env.items()):
|
|
97
|
+
cmd += ["-e", f"{key}={val}"]
|
|
98
|
+
cmd += [*self.cfg.extra_args, self.cfg.image, *self.cfg.command]
|
|
99
|
+
self.container_id = self._docker(*cmd).splitlines()[-1]
|
|
100
|
+
mapping = self._docker("port", self.container_id, f"{self.cfg.container_port}/tcp")
|
|
101
|
+
first = mapping.splitlines()[0]
|
|
102
|
+
try:
|
|
103
|
+
self.host_port = int(first.rsplit(":", 1)[1])
|
|
104
|
+
except (IndexError, ValueError) as exc:
|
|
105
|
+
raise SandboxError(f"cannot parse docker port output {first!r}") from exc
|
|
106
|
+
self._wait_ready()
|
|
107
|
+
return self.base_url
|
|
108
|
+
|
|
109
|
+
@property
|
|
110
|
+
def base_url(self) -> str:
|
|
111
|
+
if self.host_port is None:
|
|
112
|
+
raise SandboxError("sandbox not started")
|
|
113
|
+
return f"http://127.0.0.1:{self.host_port}"
|
|
114
|
+
|
|
115
|
+
def _wait_ready(self) -> None:
|
|
116
|
+
deadline = self._clock() + self.cfg.ready_timeout_s
|
|
117
|
+
url = self.base_url + self.cfg.ready_path
|
|
118
|
+
last = ""
|
|
119
|
+
while self._clock() < deadline:
|
|
120
|
+
try:
|
|
121
|
+
with self._urlopen(url, timeout=5) as resp:
|
|
122
|
+
if 200 <= getattr(resp, "status", 200) < 400:
|
|
123
|
+
return
|
|
124
|
+
except (urllib.error.URLError, OSError, ValueError) as exc:
|
|
125
|
+
last = str(exc)
|
|
126
|
+
self._sleep(0.5)
|
|
127
|
+
raise SandboxError(f"container not ready at {url} within {self.cfg.ready_timeout_s}s {last}")
|
|
128
|
+
|
|
129
|
+
def logs(self) -> str:
|
|
130
|
+
if not self.container_id:
|
|
131
|
+
return ""
|
|
132
|
+
try:
|
|
133
|
+
return self._docker("logs", self.container_id)
|
|
134
|
+
except SandboxError as exc:
|
|
135
|
+
return f"(could not read logs: {exc})"
|
|
136
|
+
|
|
137
|
+
def remove(self) -> None:
|
|
138
|
+
if self.container_id:
|
|
139
|
+
try:
|
|
140
|
+
self._docker("rm", "-f", self.container_id)
|
|
141
|
+
except SandboxError:
|
|
142
|
+
pass
|
|
143
|
+
|
|
144
|
+
def __enter__(self) -> Sandbox:
|
|
145
|
+
try:
|
|
146
|
+
self.start()
|
|
147
|
+
except Exception:
|
|
148
|
+
self.remove()
|
|
149
|
+
raise
|
|
150
|
+
return self
|
|
151
|
+
|
|
152
|
+
def __exit__(self, *exc: object) -> None:
|
|
153
|
+
self.remove()
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def rewrite_target(target_cfg: dict[str, Any], base_url: str) -> dict[str, Any]:
|
|
157
|
+
"""Point an http/openai target at the sandbox, keeping the configured path."""
|
|
158
|
+
kind = target_cfg.get("type")
|
|
159
|
+
key = {"http": "url", "openai": "base_url"}.get(str(kind))
|
|
160
|
+
if key is None or key not in target_cfg:
|
|
161
|
+
raise ConfigError("sandbox needs an http target (url) or openai target (base_url)")
|
|
162
|
+
original = urlsplit(str(target_cfg[key]))
|
|
163
|
+
sandbox = urlsplit(base_url)
|
|
164
|
+
updated = dict(target_cfg)
|
|
165
|
+
updated[key] = urlunsplit((sandbox.scheme, sandbox.netloc, original.path, original.query, ""))
|
|
166
|
+
return updated
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def run_in_sandbox(
|
|
170
|
+
sandbox_cfg: SandboxConfig,
|
|
171
|
+
target_cfg: dict[str, Any],
|
|
172
|
+
runner: Any,
|
|
173
|
+
probes: list[Any],
|
|
174
|
+
*,
|
|
175
|
+
target_factory: Callable[[dict[str, Any]], Any] | None = None,
|
|
176
|
+
sandbox_factory: Callable[[SandboxConfig], Sandbox] = Sandbox,
|
|
177
|
+
) -> tuple[dict[str, Any], dict[str, bytes]]:
|
|
178
|
+
"""Run probes inside fresh containers. Returns (target descriptor, log files)."""
|
|
179
|
+
if target_factory is None:
|
|
180
|
+
from .targets import make_target
|
|
181
|
+
|
|
182
|
+
target_factory = make_target
|
|
183
|
+
descriptor = dict(target_factory(target_cfg).describe())
|
|
184
|
+
logs: dict[str, bytes] = {}
|
|
185
|
+
containers = 0
|
|
186
|
+
|
|
187
|
+
def one(batch: list[Any], label: str) -> None:
|
|
188
|
+
nonlocal containers
|
|
189
|
+
sandbox = sandbox_factory(sandbox_cfg)
|
|
190
|
+
with sandbox:
|
|
191
|
+
containers += 1
|
|
192
|
+
target = target_factory(rewrite_target(target_cfg, sandbox.base_url))
|
|
193
|
+
for probe in batch:
|
|
194
|
+
runner.run_probe(target, probe)
|
|
195
|
+
logs[f"sandbox-{label}.log"] = sandbox.logs().encode("utf-8")
|
|
196
|
+
|
|
197
|
+
if sandbox_cfg.isolation == "per-probe":
|
|
198
|
+
for probe in probes:
|
|
199
|
+
one([probe], probe.id)
|
|
200
|
+
else:
|
|
201
|
+
one(list(probes), "run")
|
|
202
|
+
descriptor["sandbox"] = {
|
|
203
|
+
"image": sandbox_cfg.image,
|
|
204
|
+
"isolation": sandbox_cfg.isolation,
|
|
205
|
+
"containers": containers,
|
|
206
|
+
}
|
|
207
|
+
return descriptor, logs
|