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.
Files changed (48) hide show
  1. redloop/__init__.py +5 -0
  2. redloop/__main__.py +3 -0
  3. redloop/cli.py +431 -0
  4. redloop/config.py +130 -0
  5. redloop/converters.py +273 -0
  6. redloop/crosswalk.py +63 -0
  7. redloop/data/aixwalk/README.md +8 -0
  8. redloop/data/aixwalk/crosswalk.json +452 -0
  9. redloop/data/aixwalk/frameworks/iso-42001-annex-a.json +45 -0
  10. redloop/data/aixwalk/frameworks/mitre-atlas.json +949 -0
  11. redloop/data/aixwalk/frameworks/nist-ai-rmf-1.0.json +369 -0
  12. redloop/data/aixwalk/frameworks/owasp-agentic-2026.json +49 -0
  13. redloop/data/aixwalk/frameworks/owasp-llm-2025.json +49 -0
  14. redloop/data/maturity-model.json +425 -0
  15. redloop/data/templates/assessment.toml +41 -0
  16. redloop/data/templates/redloop.toml +41 -0
  17. redloop/data/templates/risk-acceptances.toml +11 -0
  18. redloop/data/templates/threatmodel.toml +136 -0
  19. redloop/detectors.py +138 -0
  20. redloop/evidence.py +140 -0
  21. redloop/governance.py +106 -0
  22. redloop/maturity.py +340 -0
  23. redloop/probes/__init__.py +48 -0
  24. redloop/probes/base.py +194 -0
  25. redloop/probes/catalog.py +383 -0
  26. redloop/py.typed +0 -0
  27. redloop/report/__init__.py +22 -0
  28. redloop/report/jsonout.py +13 -0
  29. redloop/report/md.py +98 -0
  30. redloop/report/sarif.py +103 -0
  31. redloop/report/text.py +90 -0
  32. redloop/results.py +253 -0
  33. redloop/runner.py +99 -0
  34. redloop/sandbox.py +207 -0
  35. redloop/targets/__init__.py +59 -0
  36. redloop/targets/base.py +109 -0
  37. redloop/targets/http.py +132 -0
  38. redloop/targets/mock.py +254 -0
  39. redloop/targets/openai.py +145 -0
  40. redloop/targets/transport.py +125 -0
  41. redloop/threats.py +485 -0
  42. redloop/util.py +135 -0
  43. redloop-0.1.0.dist-info/METADATA +278 -0
  44. redloop-0.1.0.dist-info/RECORD +48 -0
  45. redloop-0.1.0.dist-info/WHEEL +4 -0
  46. redloop-0.1.0.dist-info/entry_points.txt +2 -0
  47. redloop-0.1.0.dist-info/licenses/LICENSE +202 -0
  48. redloop-0.1.0.dist-info/licenses/NOTICE +16 -0
redloop/threats.py ADDED
@@ -0,0 +1,485 @@
1
+ """Threat-model-as-code: components and flows -> threat register -> test plan.
2
+
3
+ Component types follow the infrastructure layers of a production AI system (ingestion,
4
+ processing, model, validation, observability, serving) plus agent orchestration. Rules
5
+ produce threats per component; a graph traversal finds multi-vector chains where
6
+ untrusted input can reach a tool with side effects through an agent.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass, field
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from . import crosswalk
16
+ from .probes import get_probe
17
+ from .targets.base import Capabilities
18
+ from .util import ConfigError, load_structured
19
+
20
+ COMPONENT_TYPES = (
21
+ "data_source", "data_pipeline", "feature_store", "training", "fine_tuning", "model_registry",
22
+ "model", "inference_api", "prompt_surface", "rag_store", "agent", "tool", "memory",
23
+ "third_party_model", "guardrail", "monitoring",
24
+ )
25
+ TOOL_CAPABILITIES = ("read", "write", "send", "delete", "execute", "network")
26
+ EXPOSURES = ("internet", "internal")
27
+ CLASSIFICATIONS = ("public", "internal", "confidential", "restricted")
28
+ LAYER_OF = {
29
+ "data_source": "ingestion", "data_pipeline": "ingestion", "feature_store": "processing",
30
+ "training": "processing", "fine_tuning": "processing", "model_registry": "model",
31
+ "model": "model", "third_party_model": "model", "guardrail": "validation",
32
+ "monitoring": "observability", "inference_api": "serving", "prompt_surface": "serving",
33
+ "rag_store": "ingestion", "memory": "orchestration", "agent": "orchestration",
34
+ "tool": "orchestration",
35
+ }
36
+ _CLASS_IMPACT = {"public": 1, "internal": 1, "confidential": 2, "restricted": 3}
37
+ _REASONERS = {"model", "agent", "third_party_model", "inference_api"}
38
+ _CONTENT_STORES = {"rag_store", "data_source", "memory"}
39
+ _EXFIL = {"send", "network"}
40
+ _DESTRUCTIVE = {"delete", "write"}
41
+ _SIDE_EFFECTS = _EXFIL | _DESTRUCTIVE | {"execute"}
42
+
43
+
44
+ @dataclass
45
+ class Component:
46
+ id: str
47
+ type: str
48
+ name: str
49
+ exposure: str = "internal"
50
+ untrusted_input: bool = False
51
+ data_classification: str = "internal"
52
+ capabilities: list[str] = field(default_factory=list)
53
+ source: str = "internal"
54
+ model_kind: str = "llm"
55
+
56
+ @property
57
+ def layer(self) -> str:
58
+ return LAYER_OF[self.type]
59
+
60
+
61
+ @dataclass
62
+ class ThreatModel:
63
+ name: str
64
+ description: str
65
+ components: dict[str, Component]
66
+ flows: list[tuple[str, str]]
67
+ path: Path | None = None
68
+
69
+ def successors(self, cid: str) -> list[str]:
70
+ return [b for a, b in self.flows if a == cid]
71
+
72
+ def predecessors(self, cid: str) -> list[str]:
73
+ return [a for a, b in self.flows if b == cid]
74
+
75
+ def reachable(self, cid: str) -> set[str]:
76
+ seen: set[str] = set()
77
+ stack = [cid]
78
+ while stack:
79
+ cur = stack.pop()
80
+ for nxt in self.successors(cur):
81
+ if nxt not in seen:
82
+ seen.add(nxt)
83
+ stack.append(nxt)
84
+ return seen
85
+
86
+ def of_type(self, *types: str) -> list[Component]:
87
+ return [c for c in self.components.values() if c.type in types]
88
+
89
+
90
+ @dataclass
91
+ class Threat:
92
+ id: str
93
+ title: str
94
+ aix: list[str]
95
+ adversarial_category: str | None
96
+ components: list[str]
97
+ likelihood: int
98
+ impact: int
99
+ probes: list[str]
100
+ controls: list[str]
101
+ rationale: str
102
+ path: list[str] | None = None
103
+
104
+ @property
105
+ def severity(self) -> str:
106
+ return score_to_severity(self.likelihood * self.impact)
107
+
108
+ @property
109
+ def testable(self) -> bool:
110
+ return bool(self.probes)
111
+
112
+ @property
113
+ def mappings(self) -> dict[str, list[str]]:
114
+ return crosswalk.mappings_for(self.aix)
115
+
116
+ @property
117
+ def lifecycle(self) -> list[str]:
118
+ return list(crosswalk.category(self.aix[0])["lifecycle"])
119
+
120
+ def to_dict(self) -> dict[str, Any]:
121
+ primary = crosswalk.category(self.aix[0])
122
+ return {
123
+ "id": self.id,
124
+ "title": self.title,
125
+ "aix": self.aix,
126
+ "adversarial_category": self.adversarial_category,
127
+ "lifecycle": self.lifecycle,
128
+ "persistence": primary.get("persistence"),
129
+ "detection_difficulty": primary.get("detection_difficulty"),
130
+ "components": self.components,
131
+ "path": self.path,
132
+ "likelihood": self.likelihood,
133
+ "impact": self.impact,
134
+ "severity": self.severity,
135
+ "probes": self.probes,
136
+ "testing": "automated" if self.testable else "manual",
137
+ "controls": self.controls,
138
+ "rationale": self.rationale,
139
+ "mappings": self.mappings,
140
+ }
141
+
142
+
143
+ def score_to_severity(score: int) -> str:
144
+ if score >= 9:
145
+ return "critical"
146
+ if score >= 6:
147
+ return "high"
148
+ if score >= 3:
149
+ return "medium"
150
+ return "low"
151
+
152
+
153
+ # --- loading --------------------------------------------------------------------------------
154
+
155
+ def load_threat_model(path: str | Path) -> ThreatModel:
156
+ p = Path(path)
157
+ raw = load_structured(p)
158
+ system = raw.get("system", {})
159
+ comps: dict[str, Component] = {}
160
+ for i, item in enumerate(raw.get("component", [])):
161
+ where = f"{p}: component #{i + 1}"
162
+ cid = item.get("id")
163
+ ctype = item.get("type")
164
+ if not cid or not isinstance(cid, str):
165
+ raise ConfigError(f"{where}: missing id")
166
+ if cid in comps:
167
+ raise ConfigError(f"{where}: duplicate id {cid!r}")
168
+ if ctype not in COMPONENT_TYPES:
169
+ raise ConfigError(f"{where}: type must be one of {', '.join(COMPONENT_TYPES)}")
170
+ exposure = item.get("exposure", "internal")
171
+ if exposure not in EXPOSURES:
172
+ raise ConfigError(f"{where}: exposure must be internet or internal")
173
+ cls = item.get("data_classification", "internal")
174
+ if cls not in CLASSIFICATIONS:
175
+ raise ConfigError(f"{where}: data_classification must be one of {', '.join(CLASSIFICATIONS)}")
176
+ caps = item.get("capabilities", [])
177
+ if not isinstance(caps, list) or any(c not in TOOL_CAPABILITIES for c in caps):
178
+ raise ConfigError(f"{where}: capabilities must be a subset of {', '.join(TOOL_CAPABILITIES)}")
179
+ comps[cid] = Component(
180
+ id=cid,
181
+ type=ctype,
182
+ name=str(item.get("name", cid)),
183
+ exposure=exposure,
184
+ untrusted_input=bool(item.get("untrusted_input", False)),
185
+ data_classification=cls,
186
+ capabilities=list(caps),
187
+ source=str(item.get("source", "internal")),
188
+ model_kind=str(item.get("model_kind", "llm")),
189
+ )
190
+ if not comps:
191
+ raise ConfigError(f"{p}: at least one [[component]] is required")
192
+ flows: list[tuple[str, str]] = []
193
+ for i, item in enumerate(raw.get("flow", [])):
194
+ a, b = item.get("from"), item.get("to")
195
+ if a not in comps or b not in comps:
196
+ raise ConfigError(f"{p}: flow #{i + 1} references unknown component ({a!r} -> {b!r})")
197
+ flows.append((a, b))
198
+ return ThreatModel(
199
+ name=str(system.get("name", p.stem)),
200
+ description=str(system.get("description", "")),
201
+ components=comps,
202
+ flows=flows,
203
+ path=p,
204
+ )
205
+
206
+
207
+ # --- analysis -------------------------------------------------------------------------------
208
+
209
+ def _likelihood(tm: ThreatModel, ids: list[str]) -> int:
210
+ comps = [tm.components[i] for i in ids]
211
+ score = 1
212
+ if any(c.exposure == "internet" for c in comps):
213
+ score += 1
214
+ if any(c.untrusted_input for c in comps):
215
+ score += 1
216
+ return min(score, 3)
217
+
218
+
219
+ def _data_impact(tm: ThreatModel, ids: list[str]) -> int:
220
+ return max(_CLASS_IMPACT[tm.components[i].data_classification] for i in ids)
221
+
222
+
223
+ def entry_points(tm: ThreatModel, targets: set[str]) -> list[str]:
224
+ """Internet-exposed or untrusted components from which any of ``targets`` is reachable."""
225
+ out = []
226
+ for c in tm.components.values():
227
+ if (c.exposure == "internet" or c.untrusted_input) and (tm.reachable(c.id) & targets):
228
+ out.append(c.id)
229
+ return out
230
+
231
+
232
+ class _Register:
233
+ def __init__(self, tm: ThreatModel) -> None:
234
+ self.tm = tm
235
+ self.items: dict[str, Threat] = {}
236
+
237
+ def add(
238
+ self, tid: str, title: str, aix: list[str], comps: list[str], probes: list[str],
239
+ controls: list[str], rationale: str, base_impact: int, adversarial: str | None = None,
240
+ path: list[str] | None = None, exposure_ids: list[str] | None = None,
241
+ ) -> None:
242
+ if tid in self.items:
243
+ return
244
+ primary = crosswalk.category(aix[0])
245
+ involved = list(path or comps)
246
+ self.items[tid] = Threat(
247
+ id=tid,
248
+ title=title,
249
+ aix=aix,
250
+ adversarial_category=adversarial or primary.get("adversarial_category"),
251
+ components=comps,
252
+ likelihood=_likelihood(self.tm, involved + list(exposure_ids or [])),
253
+ impact=max(base_impact, _data_impact(self.tm, involved)),
254
+ probes=probes,
255
+ controls=controls,
256
+ rationale=rationale,
257
+ path=path,
258
+ )
259
+
260
+
261
+ def analyze(tm: ThreatModel) -> tuple[list[Threat], list[str]]:
262
+ """Return (threats, observations) for a threat model."""
263
+ reg = _Register(tm)
264
+ comps = tm.components
265
+
266
+ for c in comps.values():
267
+ downstream = tm.reachable(c.id)
268
+ feeds_reasoner = any(comps[d].type in _REASONERS for d in downstream)
269
+
270
+ if c.type == "prompt_surface" or (c.type == "inference_api" and c.exposure == "internet"):
271
+ reg.add(f"T-AIX01-{c.id}", f"Direct prompt injection through {c.name}", ["AIX-01"], [c.id],
272
+ ["RL-PI-001", "RL-PI-002"],
273
+ ["Normalize input and use an injection classifier, not keyword filters",
274
+ "Keep instructions and user data in separate channels"],
275
+ "User-controlled text reaches the model.", 2)
276
+ reg.add(f"T-AIX03-{c.id}", f"Policy guardrail bypass through {c.name}", ["AIX-03"], [c.id],
277
+ ["RL-REF-001", "RL-MET-001"],
278
+ ["Enforce business policy server-side", "Test refusals on paraphrase sets"],
279
+ "Refusal behavior is the only barrier for disallowed requests.", 2)
280
+ reg.add(f"T-AIX04-{c.id}", f"System prompt leakage through {c.name}", ["AIX-04"], [c.id],
281
+ ["RL-SPL-001"],
282
+ ["Keep secrets out of system prompts", "Filter instruction text from output"],
283
+ "Users can ask the model about its own instructions.", 1)
284
+ reg.add(f"T-AIX13-{c.id}", f"Unsafe rendering of model output in {c.name}", ["AIX-13"], [c.id],
285
+ ["RL-OUT-001", "RL-OUT-002"],
286
+ ["Escape/sanitize output before rendering", "Allowlist link and image hosts"],
287
+ "Model output is displayed to users.", 2)
288
+
289
+ if c.type in _CONTENT_STORES and c.untrusted_input and feeds_reasoner:
290
+ reg.add(f"T-AIX02-{c.id}", f"Indirect prompt injection via {c.name}", ["AIX-02"], [c.id],
291
+ ["RL-IPI-001"],
292
+ ["Treat retrieved content as data", "Filter instruction-like content at ingestion"],
293
+ "Untrusted content is placed into the model context.", 2)
294
+ if c.type == "rag_store":
295
+ reg.add(f"T-AIX12-{c.id}", f"Retrieval index poisoning of {c.name}", ["AIX-12"], [c.id],
296
+ ["RL-IPI-001"],
297
+ ["Validate and attribute content before indexing", "Restrict index write access"],
298
+ "Attacker-influenced content can enter the retrieval index.", 2)
299
+ if c.type == "memory":
300
+ reg.add(f"T-AIX18-{c.id}", f"Memory poisoning of {c.name}", ["AIX-18"], [c.id], [],
301
+ ["Scope memory per user and task", "Expire and review persisted memories"],
302
+ "Untrusted content can persist in agent memory.", 2)
303
+
304
+ if (
305
+ c.type in _CONTENT_STORES | {"feature_store"}
306
+ and c.data_classification in ("confidential", "restricted")
307
+ and feeds_reasoner
308
+ ):
309
+ reg.add(f"T-AIX05-{c.id}", f"Disclosure of {c.data_classification} data from {c.name}",
310
+ ["AIX-05"], [c.id], ["RL-SID-001"],
311
+ ["Least-privilege retrieval filtered by the requesting user",
312
+ "Output classification checks"],
313
+ "Sensitive records are available in the model context.", 2,
314
+ exposure_ids=entry_points(tm, {d for d in downstream if comps[d].type in _REASONERS}))
315
+
316
+ if c.type == "agent":
317
+ tools = [comps[t] for t in tm.successors(c.id) if comps[t].type == "tool"]
318
+ caps = {cap for t in tools for cap in t.capabilities}
319
+ if caps & _SIDE_EFFECTS:
320
+ probes = []
321
+ if caps & _DESTRUCTIVE:
322
+ probes.append("RL-AGY-001")
323
+ if caps & _EXFIL:
324
+ probes.append("RL-IPI-002")
325
+ reg.add(f"T-AIX14-{c.id}", f"Excessive agency of {c.name}", ["AIX-14"],
326
+ [c.id] + [t.id for t in tools], probes,
327
+ ["Least-privilege tools", "Human approval for side-effecting actions",
328
+ "Bind tool authorization to the user's request"],
329
+ f"The agent can call tools with {', '.join(sorted(caps & _SIDE_EFFECTS))} capability.", 3,
330
+ exposure_ids=entry_points(tm, {c.id}))
331
+ reg.add(f"T-AIX15-{c.id}", f"Identity and privilege abuse by {c.name}", ["AIX-15"],
332
+ [c.id] + [t.id for t in tools], [],
333
+ ["Per-user, short-lived, scoped credentials for tools", "No shared service accounts"],
334
+ "Agent tools act with credentials; review whose authority they use.", 2,
335
+ exposure_ids=entry_points(tm, {c.id}))
336
+ for other in tm.successors(c.id):
337
+ if comps[other].type == "agent":
338
+ reg.add(f"T-AIX19-{c.id}-{other}", f"Inter-agent message tampering {c.name} -> {comps[other].name}",
339
+ ["AIX-19"], [c.id, other], [],
340
+ ["Authenticate and validate inter-agent messages", "Treat peer output as untrusted"],
341
+ "Agents exchange messages that can carry injected instructions.", 2)
342
+
343
+ if c.type == "tool":
344
+ if "execute" in c.capabilities:
345
+ reg.add(f"T-AIX17-{c.id}", f"Code execution through {c.name}", ["AIX-17"], [c.id], [],
346
+ ["Sandbox execution with no network and no secrets", "Allowlist commands"],
347
+ "A tool executes code or commands produced by the model.", 3)
348
+ if c.source == "external":
349
+ reg.add(f"T-AIX16-{c.id}", f"Poisoned third-party tool {c.name}", ["AIX-16"], [c.id], [],
350
+ ["Pin and review tool definitions", "Monitor tool responses for instructions"],
351
+ "Tool definitions or responses come from a third party.", 2)
352
+
353
+ if c.type in ("training", "fine_tuning", "data_pipeline", "feature_store"):
354
+ upstream = [comps[u] for u in tm.predecessors(c.id)] + [c]
355
+ if any(u.untrusted_input or u.source == "external" for u in upstream):
356
+ reg.add(f"T-AIX08-{c.id}", f"Training-data poisoning in {c.name}", ["AIX-08"],
357
+ [u.id for u in upstream], [],
358
+ ["Data provenance and dataset pinning", "Outlier and influence analysis before training"],
359
+ "Training or fine-tuning consumes data from untrusted or external sources.", 3)
360
+ if c.data_classification in ("confidential", "restricted"):
361
+ for model in [comps[d] for d in tm.successors(c.id) if comps[d].type in ("model", "model_registry")]:
362
+ reg.add(f"T-AIX06-{model.id}", f"Training-data inference against {model.name}", ["AIX-06"],
363
+ [c.id, model.id], [],
364
+ ["Differential privacy or data minimization in training", "Limit output detail and query rates"],
365
+ "The model was trained on sensitive data.", 2)
366
+
367
+ if c.type in ("model", "model_registry", "third_party_model") and c.source == "external":
368
+ if c.type == "third_party_model":
369
+ controls = ["Pin the model version in API calls and monitor for provider-side changes",
370
+ "Review the provider's security and data-handling commitments"]
371
+ else:
372
+ controls = ["Pin model revisions and verify hashes", "Scan repositories with modelbom"]
373
+ reg.add(f"T-AIX10-{c.id}", f"Supply-chain compromise of {c.name}", ["AIX-10"], [c.id], [],
374
+ controls, "The model or registry is obtained from an external source.", 3)
375
+ if c.type != "third_party_model":
376
+ reg.add(f"T-AIX11-{c.id}", f"Unsafe deserialization of {c.name} artifacts", ["AIX-11"], [c.id], [],
377
+ ["Prefer safetensors", "Scan artifacts with modelbom before loading"],
378
+ "Externally sourced model artifacts are loaded.", 3)
379
+ reg.add(f"T-AIX09-{c.id}", f"Backdoored weights in {c.name}", ["AIX-09"], [c.id], [],
380
+ ["Behavioral evaluation on trigger-sensitive test sets", "Use trusted publishers"],
381
+ "Externally trained weights may carry hidden behavior.", 3)
382
+
383
+ if c.type in ("model", "inference_api", "third_party_model") and c.exposure == "internet":
384
+ reg.add(f"T-AIX23-{c.id}", f"Model extraction through {c.name}", ["AIX-23"], [c.id], [],
385
+ ["Per-client rate limits and quotas", "Query pattern monitoring"],
386
+ "The model is reachable from the internet.", 2)
387
+ reg.add(f"T-AIX24-{c.id}", f"Resource exhaustion of {c.name}", ["AIX-24"], [c.id], [],
388
+ ["Rate limits, request size limits and timeouts", "Autoscaling with hard ceilings"],
389
+ "The model is reachable from the internet.", 2)
390
+ if c.model_kind == "classifier":
391
+ reg.add(f"T-AIX07-{c.id}", f"Adversarial evasion of {c.name}", ["AIX-07"], [c.id], [],
392
+ ["Adversarial robustness evaluation", "Input preprocessing and ensembles"],
393
+ "An internet-facing classifier can be probed with crafted inputs.", 2)
394
+
395
+ for n, path in enumerate(_chains(tm), start=1):
396
+ tool = comps[path[-1]]
397
+ aix = ["AIX-20"]
398
+ types = {comps[i].type for i in path}
399
+ if types & {"training", "fine_tuning", "data_pipeline", "feature_store"}:
400
+ aix.append("AIX-08")
401
+ elif types & {"rag_store", "data_source"}:
402
+ aix.append("AIX-02")
403
+ if "prompt_surface" in types:
404
+ aix.append("AIX-01")
405
+ if "memory" in types:
406
+ aix.append("AIX-18")
407
+ aix.append("AIX-14")
408
+ probes = []
409
+ if set(tool.capabilities) & _EXFIL:
410
+ probes.append("RL-IPI-002")
411
+ if set(tool.capabilities) & _DESTRUCTIVE:
412
+ probes.append("RL-AGY-001")
413
+ names = " -> ".join(comps[i].name for i in path)
414
+ reg.add(f"T-CHAIN-{n}", f"Multi-vector chain: {names}", aix, list(path), probes,
415
+ ["Break the chain at two points: untrusted-content handling and tool authorization"],
416
+ "Untrusted input can reach a side-effecting tool through an agent.", 3,
417
+ adversarial="multi_vector", path=list(path))
418
+
419
+ observations = []
420
+ for c in tm.of_type("prompt_surface", "agent"):
421
+ guarded = any(comps[p].type == "guardrail" for p in tm.predecessors(c.id))
422
+ if not guarded:
423
+ observations.append(f"No guardrail component in front of {c.name} ({c.id}).")
424
+ if not tm.of_type("monitoring"):
425
+ observations.append(
426
+ "No monitoring component: model inputs, outputs and tool calls are not observed."
427
+ )
428
+ order = {"critical": 0, "high": 1, "medium": 2, "low": 3}
429
+ threats = sorted(reg.items.values(), key=lambda t: (order[t.severity], t.id))
430
+ return threats, observations
431
+
432
+
433
+ def _chains(tm: ThreatModel, max_len: int = 8) -> list[list[str]]:
434
+ comps = tm.components
435
+ sources = [c.id for c in comps.values() if c.untrusted_input]
436
+ out: list[list[str]] = []
437
+
438
+ def walk(path: list[str]) -> None:
439
+ cur = comps[path[-1]]
440
+ if cur.type == "tool" and set(cur.capabilities) & _SIDE_EFFECTS:
441
+ if any(comps[i].type == "agent" for i in path[:-1]):
442
+ out.append(list(path))
443
+ return
444
+ if len(path) >= max_len:
445
+ return
446
+ for nxt in tm.successors(cur.id):
447
+ if nxt not in path:
448
+ walk([*path, nxt])
449
+
450
+ for src in sources:
451
+ walk([src])
452
+ return out
453
+
454
+
455
+ # --- planning -------------------------------------------------------------------------------
456
+
457
+ @dataclass
458
+ class PlanRow:
459
+ threat: Threat
460
+ runnable: list[str]
461
+ blocked: dict[str, list[str]]
462
+
463
+
464
+ def plan(threats: list[Threat], capabilities: Capabilities | None = None) -> list[PlanRow]:
465
+ caps = capabilities or Capabilities(True, True, True)
466
+ rows = []
467
+ for t in threats:
468
+ runnable, blocked = [], {}
469
+ for pid in t.probes:
470
+ missing = [r for r in get_probe(pid).requires if not caps.has(r)]
471
+ if missing:
472
+ blocked[pid] = missing
473
+ else:
474
+ runnable.append(pid)
475
+ rows.append(PlanRow(t, runnable, blocked))
476
+ return rows
477
+
478
+
479
+ def probes_for(threats: list[Threat]) -> list[str]:
480
+ out: list[str] = []
481
+ for t in threats:
482
+ for pid in t.probes:
483
+ if pid not in out:
484
+ out.append(pid)
485
+ return out
redloop/util.py ADDED
@@ -0,0 +1,135 @@
1
+ """Small shared helpers: structured-file loading, env expansion, hashing, redaction."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import datetime as _dt
6
+ import hashlib
7
+ import json
8
+ import os
9
+ import re
10
+ import tomllib
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+
15
+ class ConfigError(Exception):
16
+ """Raised for invalid configuration; the CLI maps it to exit code 2."""
17
+
18
+
19
+ SENSITIVE_KEY_PATTERN = re.compile(
20
+ r"(authorization|api[-_]?key|token|secret|password|cookie|credential)", re.IGNORECASE
21
+ )
22
+ _ENV_PATTERN = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}")
23
+
24
+
25
+ def load_structured(path: str | Path) -> dict[str, Any]:
26
+ """Load a TOML, JSON or (if PyYAML is installed) YAML document into a dict."""
27
+ p = Path(path)
28
+ if not p.is_file():
29
+ raise ConfigError(f"file not found: {p}")
30
+ suffix = p.suffix.lower()
31
+ try:
32
+ if suffix == ".toml":
33
+ with p.open("rb") as fh:
34
+ data = tomllib.load(fh)
35
+ elif suffix == ".json":
36
+ data = json.loads(p.read_text(encoding="utf-8"))
37
+ elif suffix in (".yaml", ".yml"):
38
+ try:
39
+ import yaml # type: ignore[import-untyped]
40
+ except ImportError as exc: # pragma: no cover - depends on environment
41
+ raise ConfigError(
42
+ f"{p}: YAML needs PyYAML (pip install 'redloop[yaml]'); use TOML or JSON"
43
+ ) from exc
44
+ data = yaml.safe_load(p.read_text(encoding="utf-8")) or {}
45
+ else:
46
+ raise ConfigError(f"{p}: unsupported file type (use .toml, .json or .yaml)")
47
+ except (tomllib.TOMLDecodeError, json.JSONDecodeError) as exc:
48
+ raise ConfigError(f"{p}: {exc}") from exc
49
+ if not isinstance(data, dict):
50
+ raise ConfigError(f"{p}: top level must be a table/object")
51
+ return data
52
+
53
+
54
+ def expand_env(value: str, environ: dict[str, str] | None = None) -> str:
55
+ """Replace ``${VAR}`` with the environment value; missing variables are an error."""
56
+ env = os.environ if environ is None else environ
57
+
58
+ def repl(match: re.Match[str]) -> str:
59
+ name = match.group(1)
60
+ if name not in env:
61
+ raise ConfigError(f"environment variable {name} is not set")
62
+ return env[name]
63
+
64
+ return _ENV_PATTERN.sub(repl, value)
65
+
66
+
67
+ def env_references(value: str) -> list[str]:
68
+ return _ENV_PATTERN.findall(value)
69
+
70
+
71
+ def redact_headers(headers: dict[str, str]) -> dict[str, str]:
72
+ """Return a copy of headers safe to log: sensitive values become ``***``."""
73
+ out = {}
74
+ for key, val in headers.items():
75
+ if SENSITIVE_KEY_PATTERN.search(key) or env_references(str(val)):
76
+ out[key] = "***"
77
+ else:
78
+ out[key] = val
79
+ return out
80
+
81
+
82
+ def redact_text(text: str, secrets: list[str]) -> str:
83
+ for secret in secrets:
84
+ if secret and len(secret) >= 4:
85
+ text = text.replace(secret, "***")
86
+ return text
87
+
88
+
89
+ def sha256_bytes(data: bytes) -> str:
90
+ return hashlib.sha256(data).hexdigest()
91
+
92
+
93
+ def sha256_file(path: str | Path) -> str:
94
+ h = hashlib.sha256()
95
+ with Path(path).open("rb") as fh:
96
+ for chunk in iter(lambda: fh.read(65536), b""):
97
+ h.update(chunk)
98
+ return h.hexdigest()
99
+
100
+
101
+ def utcnow() -> _dt.datetime:
102
+ return _dt.datetime.now(_dt.UTC)
103
+
104
+
105
+ def iso(ts: _dt.datetime) -> str:
106
+ return ts.astimezone(_dt.UTC).isoformat(timespec="seconds").replace("+00:00", "Z")
107
+
108
+
109
+ def parse_iso(value: str) -> _dt.datetime:
110
+ return _dt.datetime.fromisoformat(value.replace("Z", "+00:00"))
111
+
112
+
113
+ def excerpt(text: str, limit: int = 240) -> str:
114
+ flat = " ".join(text.split())
115
+ return flat if len(flat) <= limit else flat[: limit - 1] + "…"
116
+
117
+
118
+ def dig(obj: Any, path: str) -> Any:
119
+ """Follow a dotted path through dicts and lists, e.g. ``choices.0.message.content``."""
120
+ cur = obj
121
+ for part in path.split("."):
122
+ if part == "":
123
+ continue
124
+ if isinstance(cur, list):
125
+ try:
126
+ cur = cur[int(part)]
127
+ except (ValueError, IndexError) as exc:
128
+ raise KeyError(path) from exc
129
+ elif isinstance(cur, dict):
130
+ if part not in cur:
131
+ raise KeyError(path)
132
+ cur = cur[part]
133
+ else:
134
+ raise KeyError(path)
135
+ return cur