gapfuzz 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.
- gapfuzz/__init__.py +39 -0
- gapfuzz/__main__.py +3 -0
- gapfuzz/adapters/__init__.py +1 -0
- gapfuzz/adapters/fake.py +60 -0
- gapfuzz/adapters/hf_classifier.py +143 -0
- gapfuzz/adapters/prompt_guard2.py +70 -0
- gapfuzz/attribution.py +111 -0
- gapfuzz/base.py +32 -0
- gapfuzz/cli.py +1162 -0
- gapfuzz/corpus.py +68 -0
- gapfuzz/decision.py +73 -0
- gapfuzz/evasion.py +339 -0
- gapfuzz/mapping.py +116 -0
- gapfuzz/mutators.py +276 -0
- gapfuzz/oracle.py +36 -0
- gapfuzz/payloads.py +132 -0
- gapfuzz/registry.py +121 -0
- gapfuzz/stats.py +59 -0
- gapfuzz/tokenize.py +37 -0
- gapfuzz/transfer.py +321 -0
- gapfuzz-0.1.0.dist-info/METADATA +406 -0
- gapfuzz-0.1.0.dist-info/RECORD +26 -0
- gapfuzz-0.1.0.dist-info/WHEEL +5 -0
- gapfuzz-0.1.0.dist-info/entry_points.txt +2 -0
- gapfuzz-0.1.0.dist-info/licenses/LICENSE +202 -0
- gapfuzz-0.1.0.dist-info/top_level.txt +1 -0
gapfuzz/corpus.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""Load corpus splits as blind-spot map seeds.
|
|
2
|
+
|
|
3
|
+
Which split you seed with decides what the map means, and the two malicious splits mean
|
|
4
|
+
opposite things:
|
|
5
|
+
|
|
6
|
+
- `malicious_tp.jsonl` - attacks the guardrail **caught**. These are Stage 4/5 input: there is
|
|
7
|
+
a verdict to overturn, so driving one below the threshold is a real bypass.
|
|
8
|
+
- `malicious_fn.jsonl` - attacks it **missed**. These are already below the threshold, so the
|
|
9
|
+
fuzzer has nothing to evade and reports them as `seed_flagged=False`. They are worth studying
|
|
10
|
+
with Stage 2 attribution (what does the detector fail to look at?), not with Stage 4.
|
|
11
|
+
|
|
12
|
+
`load_seeds` therefore rejects unflagged rows by default rather than letting them quietly
|
|
13
|
+
dilute a map.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import json
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import Callable, List, Optional
|
|
21
|
+
|
|
22
|
+
from .mapping import Seed
|
|
23
|
+
from .oracle import ValidityOracle
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _default_family(row: dict) -> str:
|
|
27
|
+
"""Group by the dataset's own split field.
|
|
28
|
+
|
|
29
|
+
Not an attack taxonomy: `xTRam1/safe-guard-prompt-injection` ships no family labels, and
|
|
30
|
+
inventing one here would put a made-up dimension on the headline chart. Pass `family_fn`
|
|
31
|
+
once you have real labels.
|
|
32
|
+
"""
|
|
33
|
+
return str(row.get("source_split", "corpus"))
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def load_seeds(
|
|
37
|
+
path: str | Path,
|
|
38
|
+
*,
|
|
39
|
+
oracle: Optional[ValidityOracle] = None,
|
|
40
|
+
family_fn: Callable[[dict], str] = _default_family,
|
|
41
|
+
limit: Optional[int] = None,
|
|
42
|
+
require_flagged: bool = True,
|
|
43
|
+
) -> List[Seed]:
|
|
44
|
+
"""Read a corpus JSONL into `Seed` tuples for `BlindSpotMapper.map`.
|
|
45
|
+
|
|
46
|
+
`oracle` is attached to every seed; None leaves each one on the mapper's default.
|
|
47
|
+
`require_flagged` raises on a row the guardrail did not flag, which is what catches the
|
|
48
|
+
mistake of pointing this at the false-negative split.
|
|
49
|
+
"""
|
|
50
|
+
path = Path(path)
|
|
51
|
+
seeds: List[Seed] = []
|
|
52
|
+
with path.open() as f:
|
|
53
|
+
for lineno, line in enumerate(f, 1):
|
|
54
|
+
line = line.strip()
|
|
55
|
+
if not line:
|
|
56
|
+
continue
|
|
57
|
+
row = json.loads(line)
|
|
58
|
+
if require_flagged and not row.get("flagged", False):
|
|
59
|
+
raise ValueError(
|
|
60
|
+
f"{path.name}:{lineno} was not flagged by the guardrail "
|
|
61
|
+
f"(outcome={row.get('outcome')!r}, score={row.get('score')!r}). "
|
|
62
|
+
"Evasion needs a verdict to overturn, so seed the true-positive split; "
|
|
63
|
+
"pass require_flagged=False only if you know why you want this."
|
|
64
|
+
)
|
|
65
|
+
seeds.append((family_fn(row), row["text"], oracle))
|
|
66
|
+
if limit is not None and len(seeds) >= limit:
|
|
67
|
+
break
|
|
68
|
+
return seeds
|
gapfuzz/decision.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""The Decision object returned by every guardrail's decide()."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from enum import Enum
|
|
7
|
+
from typing import Any, Dict, List, Optional
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Label(str, Enum):
|
|
11
|
+
"""Normalized guardrail verdict.
|
|
12
|
+
|
|
13
|
+
Guardrails vary in their native label vocabulary (SAFE/INJECTION,
|
|
14
|
+
LABEL_0/LABEL_1, benign/jailbreak, ...). Adapters normalize to these so
|
|
15
|
+
downstream attribution/evasion code can be model-agnostic.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
BENIGN = "benign"
|
|
19
|
+
MALICIOUS = "malicious"
|
|
20
|
+
INJECTION = "injection"
|
|
21
|
+
|
|
22
|
+
def is_positive(self) -> bool:
|
|
23
|
+
"""True if this label represents a flagged (unsafe) prompt."""
|
|
24
|
+
return self in (Label.MALICIOUS, Label.INJECTION)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class Decision:
|
|
29
|
+
"""Uniform output of a guardrail.
|
|
30
|
+
|
|
31
|
+
Attributes
|
|
32
|
+
----------
|
|
33
|
+
label:
|
|
34
|
+
Normalized verdict (see :class:`Label`).
|
|
35
|
+
score:
|
|
36
|
+
Continuous confidence in [0, 1] that the prompt is *unsafe*
|
|
37
|
+
(i.e. probability mass on the positive/flagged class). This is the
|
|
38
|
+
number evasion generation will try to drive down.
|
|
39
|
+
logits:
|
|
40
|
+
Raw model logits, one per class, as plain floats. Carried so callers can
|
|
41
|
+
see the pre-softmax margin without a second forward pass, which stays
|
|
42
|
+
readable after softmax has saturated to 1.0. (Gradient attribution does
|
|
43
|
+
not read this; it backprops from the model's own logit tensor.)
|
|
44
|
+
prompt:
|
|
45
|
+
The exact input string that produced this decision.
|
|
46
|
+
guardrail:
|
|
47
|
+
Name of the guardrail that produced the decision.
|
|
48
|
+
raw_label:
|
|
49
|
+
The guardrail's native label string, before normalization.
|
|
50
|
+
probs:
|
|
51
|
+
Full softmax distribution over classes (parallel to `logits`).
|
|
52
|
+
extra:
|
|
53
|
+
Adapter-specific metadata (model id, id2label map, tokenization info).
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
label: Label
|
|
57
|
+
score: float
|
|
58
|
+
logits: List[float]
|
|
59
|
+
prompt: str
|
|
60
|
+
guardrail: str
|
|
61
|
+
raw_label: Optional[str] = None
|
|
62
|
+
probs: Optional[List[float]] = None
|
|
63
|
+
extra: Dict[str, Any] = field(default_factory=dict)
|
|
64
|
+
|
|
65
|
+
@property
|
|
66
|
+
def flagged(self) -> bool:
|
|
67
|
+
return self.label.is_positive()
|
|
68
|
+
|
|
69
|
+
def __repr__(self) -> str: # concise, evidence-friendly
|
|
70
|
+
return (
|
|
71
|
+
f"Decision(guardrail={self.guardrail!r}, label={self.label.value!r}, "
|
|
72
|
+
f"score={self.score:.4f}, logits={[round(x, 3) for x in self.logits]})"
|
|
73
|
+
)
|
gapfuzz/evasion.py
ADDED
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
"""Stage 4: the evasion fuzzer.
|
|
2
|
+
|
|
3
|
+
Attribution-guided beam search: starting from a flagged attack, repeatedly perturb the spans the
|
|
4
|
+
detector leans on (from `attribute`) using the mutation operators, keep only candidates the
|
|
5
|
+
validity oracle still accepts as real attacks, score them, and keep descending the detector's
|
|
6
|
+
unsafe-score surface. Stop when a *valid* candidate falls below the decision threshold (evasion
|
|
7
|
+
found) or the step/patience budget runs out.
|
|
8
|
+
|
|
9
|
+
This is the "pick the lock instead of trying random keys" loop: the detector's own saliency says
|
|
10
|
+
where to push, and the oracle guarantees the result still works.
|
|
11
|
+
|
|
12
|
+
Two things the caller must get right, because the search cannot check them itself:
|
|
13
|
+
|
|
14
|
+
- **Seed a flagged attack.** Driving a score below the threshold is only meaningful if it started
|
|
15
|
+
above it. A seed the guardrail already passes is not an evasion, it is a false negative the
|
|
16
|
+
detector already had, so `run()` reports it as `seed_flagged=False` instead of claiming a win.
|
|
17
|
+
Corpus false-negative splits are the wrong input here; seed the true positives.
|
|
18
|
+
- **Supply an oracle.** `oracle` is required and has no default, because the obvious default
|
|
19
|
+
(accept everything) silently turns every result into an unvalidated claim. Pass `always_valid`
|
|
20
|
+
explicitly if that is genuinely right for your domain.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import random
|
|
26
|
+
from dataclasses import dataclass, field
|
|
27
|
+
from typing import Callable, Dict, List, Optional, Tuple
|
|
28
|
+
|
|
29
|
+
from .attribution import attribute
|
|
30
|
+
from .base import Guardrail
|
|
31
|
+
from .decision import Decision
|
|
32
|
+
from .tokenize import tokenize
|
|
33
|
+
from .mutators import Mutator, default_mutators
|
|
34
|
+
from .oracle import ValidityOracle
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
_SPAN_STRATEGIES = {"attribution", "random", "anti-attribution", "mutability"}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class _BudgetExceeded(Exception):
|
|
41
|
+
"""Raised inside the search when the guardrail query budget is spent."""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class _CountingGuardrail(Guardrail):
|
|
45
|
+
"""Counts every guardrail query and enforces a hard ceiling.
|
|
46
|
+
|
|
47
|
+
Attribution's cost is invisible otherwise: occlusion issues one scored variant per token
|
|
48
|
+
before a single mutation is tried, while random span selection issues none. Counting at the
|
|
49
|
+
`decide` boundary is the only place that captures both.
|
|
50
|
+
|
|
51
|
+
The ceiling is enforced per call rather than per step. An earlier version checked only at
|
|
52
|
+
step boundaries, which let a single occlusion pass overshoot a 200-query budget to 900 --
|
|
53
|
+
and the overshoot favoured the guided strategy, which is exactly the comparison the budget
|
|
54
|
+
exists to keep fair. A batch that would exceed the ceiling is truncated; if nothing remains,
|
|
55
|
+
the search is unwound and reports the best candidate found so far.
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
def __init__(self, inner: Guardrail, limit: Optional[int] = None):
|
|
59
|
+
self.inner = inner
|
|
60
|
+
self.name = getattr(inner, "name", "counted")
|
|
61
|
+
self.limit = limit
|
|
62
|
+
self.calls = 0
|
|
63
|
+
|
|
64
|
+
@property
|
|
65
|
+
def remaining(self) -> Optional[int]:
|
|
66
|
+
return None if self.limit is None else max(0, self.limit - self.calls)
|
|
67
|
+
|
|
68
|
+
@property
|
|
69
|
+
def exhausted(self) -> bool:
|
|
70
|
+
return self.limit is not None and self.calls >= self.limit
|
|
71
|
+
|
|
72
|
+
def __getattr__(self, item: str):
|
|
73
|
+
"""Forward anything else to the wrapped guardrail.
|
|
74
|
+
|
|
75
|
+
Gradient attribution reaches past `decide` for `.model`, `.tokenizer`,
|
|
76
|
+
`positive_index` and `max_length`. Without this the proxy hides them and
|
|
77
|
+
attribution_method="gradient" dies with an AttributeError the moment a budget is
|
|
78
|
+
installed.
|
|
79
|
+
"""
|
|
80
|
+
if item == "inner": # not yet assigned; do not recurse
|
|
81
|
+
raise AttributeError(item)
|
|
82
|
+
return getattr(self.inner, item)
|
|
83
|
+
|
|
84
|
+
def decide(self, prompt: str) -> Decision:
|
|
85
|
+
if self.exhausted:
|
|
86
|
+
raise _BudgetExceeded
|
|
87
|
+
self.calls += 1
|
|
88
|
+
return self.inner.decide(prompt)
|
|
89
|
+
|
|
90
|
+
def decide_batch(self, prompts):
|
|
91
|
+
if self.exhausted:
|
|
92
|
+
raise _BudgetExceeded
|
|
93
|
+
if self.limit is not None and len(prompts) > self.remaining:
|
|
94
|
+
prompts = prompts[: self.remaining]
|
|
95
|
+
self.calls += len(prompts)
|
|
96
|
+
return self.inner.decide_batch(prompts)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
@dataclass
|
|
100
|
+
class EvasionResult:
|
|
101
|
+
found: bool
|
|
102
|
+
original_prompt: str
|
|
103
|
+
original_score: float
|
|
104
|
+
evasive_prompt: str
|
|
105
|
+
final_score: float
|
|
106
|
+
threshold: float
|
|
107
|
+
steps: int
|
|
108
|
+
operators: List[str] = field(default_factory=list) # mutators applied to reach the evasion
|
|
109
|
+
trajectory: List[float] = field(default_factory=list) # best score after each step
|
|
110
|
+
reason: str = ""
|
|
111
|
+
seed_flagged: bool = True # False => guardrail never flagged the seed; not an evasion
|
|
112
|
+
oracle_calls: int = 0 # the expensive budget: a real oracle hits a live target
|
|
113
|
+
candidates_scored: int = 0
|
|
114
|
+
decide_calls: int = 0 # every guardrail query, attribution included
|
|
115
|
+
|
|
116
|
+
@property
|
|
117
|
+
def score_drop(self) -> float:
|
|
118
|
+
return self.original_score - self.final_score
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
class EvasionFuzzer:
|
|
122
|
+
def __init__(self, guardrail: Guardrail, *, oracle: ValidityOracle,
|
|
123
|
+
threshold: float = 0.5,
|
|
124
|
+
mutators: Optional[List[Mutator]] = None,
|
|
125
|
+
attribution_method: str = "occlusion",
|
|
126
|
+
top_spans: int = 3, beam: int = 4, max_steps: int = 25, patience: int = 4,
|
|
127
|
+
max_len: int = 4000,
|
|
128
|
+
well_formed: Optional[Callable[[str], bool]] = None,
|
|
129
|
+
max_oracle_calls: Optional[int] = None,
|
|
130
|
+
span_strategy: str = "attribution",
|
|
131
|
+
max_decide_calls: Optional[int] = None,
|
|
132
|
+
seed: int = 0):
|
|
133
|
+
self.g = guardrail
|
|
134
|
+
self.threshold = threshold
|
|
135
|
+
self.mutators = mutators if mutators is not None else default_mutators()
|
|
136
|
+
self.oracle = oracle
|
|
137
|
+
self.method = attribution_method
|
|
138
|
+
self.top_spans = top_spans
|
|
139
|
+
self.beam = beam
|
|
140
|
+
self.max_steps = max_steps
|
|
141
|
+
self.patience = patience
|
|
142
|
+
self.max_len = max_len
|
|
143
|
+
self.well_formed = well_formed
|
|
144
|
+
self.max_oracle_calls = max_oracle_calls
|
|
145
|
+
if span_strategy not in _SPAN_STRATEGIES:
|
|
146
|
+
raise ValueError(f"span_strategy must be one of {sorted(_SPAN_STRATEGIES)}, "
|
|
147
|
+
f"got {span_strategy!r}")
|
|
148
|
+
self.span_strategy = span_strategy
|
|
149
|
+
self.max_decide_calls = max_decide_calls
|
|
150
|
+
self.rng = random.Random(seed)
|
|
151
|
+
|
|
152
|
+
def _select_spans(self, text: str) -> List[Tuple[int, int]]:
|
|
153
|
+
"""Which spans to mutate. The project's central claim lives here.
|
|
154
|
+
|
|
155
|
+
`attribution` asks the guardrail which spans carry its verdict, which costs one
|
|
156
|
+
scored variant per token under occlusion. `random` picks spans blindly and costs
|
|
157
|
+
nothing, so at a matched query budget it buys strictly more mutation attempts -- it is
|
|
158
|
+
the baseline the guided strategy has to beat to justify its own price.
|
|
159
|
+
`anti-attribution` targets the *least* salient spans: if it performs like
|
|
160
|
+
`attribution`, the saliency signal is not doing the work.
|
|
161
|
+
|
|
162
|
+
`mutability` weights salience by how many candidates the operator pack can actually
|
|
163
|
+
produce for that span. Plain `attribution` optimises influence alone, and across four
|
|
164
|
+
benchmark runs it never beat random selection on success rate even though
|
|
165
|
+
`anti-attribution` was reliably worse -- the pattern you get when the ranking carries
|
|
166
|
+
signal but the search is maximising the wrong quantity. A synonym swap needs a word the
|
|
167
|
+
thesaurus knows; percent-encoding needs a character that encodes. The most influential
|
|
168
|
+
span is often one the operators cannot touch, and that step then yields nothing. Counting
|
|
169
|
+
candidates costs no guardrail queries, so this arm is free under a matched budget.
|
|
170
|
+
"""
|
|
171
|
+
if self.span_strategy == "random":
|
|
172
|
+
spans = [s for s in tokenize(text) if not s.is_space]
|
|
173
|
+
if not spans:
|
|
174
|
+
return [(0, len(text))]
|
|
175
|
+
k = min(self.top_spans, len(spans))
|
|
176
|
+
return [(s.start, s.end) for s in self.rng.sample(spans, k)]
|
|
177
|
+
|
|
178
|
+
ranked = attribute(text, self.g, method=self.method).ranked()
|
|
179
|
+
|
|
180
|
+
if self.span_strategy == "mutability":
|
|
181
|
+
scored = []
|
|
182
|
+
for t in ranked:
|
|
183
|
+
sp = (t.span.start, t.span.end)
|
|
184
|
+
n = sum(len(m.mutate(text, sp)) for m in self.mutators)
|
|
185
|
+
if n:
|
|
186
|
+
scored.append((t.salience * n, sp))
|
|
187
|
+
scored.sort(key=lambda x: -x[0])
|
|
188
|
+
if scored:
|
|
189
|
+
return [sp for _, sp in scored[: self.top_spans]]
|
|
190
|
+
return [(0, len(text))]
|
|
191
|
+
|
|
192
|
+
if self.span_strategy == "anti-attribution":
|
|
193
|
+
ranked = list(reversed(ranked))
|
|
194
|
+
return [(t.span.start, t.span.end) for t in ranked[: self.top_spans]] or \
|
|
195
|
+
[(0, len(text))]
|
|
196
|
+
|
|
197
|
+
def _expand(self, member: str, seen: set) -> List[Tuple[str, str]]:
|
|
198
|
+
"""Candidates from one beam member, as (candidate, operator) pairs.
|
|
199
|
+
|
|
200
|
+
Filters in increasing order of cost: emptiness and length, then dedup, then the
|
|
201
|
+
well-formedness check. Ill-formed candidates are still marked seen -- a mutation that
|
|
202
|
+
does not parse will not start parsing later, so there is no point regenerating it.
|
|
203
|
+
"""
|
|
204
|
+
spans = self._select_spans(member)
|
|
205
|
+
out: List[Tuple[str, str]] = []
|
|
206
|
+
for m in self.mutators:
|
|
207
|
+
for sp in spans:
|
|
208
|
+
for cand in m.mutate(member, sp):
|
|
209
|
+
if not cand or len(cand) > self.max_len or cand in seen:
|
|
210
|
+
continue
|
|
211
|
+
seen.add(cand)
|
|
212
|
+
if self.well_formed is not None and not self.well_formed(cand):
|
|
213
|
+
continue
|
|
214
|
+
out.append((cand, m.name))
|
|
215
|
+
return out
|
|
216
|
+
|
|
217
|
+
def run(self, attack: str) -> EvasionResult:
|
|
218
|
+
# Swap in a counting proxy for the duration of the run. Budgets are enforced at step
|
|
219
|
+
# boundaries rather than mid-batch, so a run may overshoot by at most one pool; the
|
|
220
|
+
# result reports calls actually spent, which is what a comparison should use.
|
|
221
|
+
real_guardrail = self.g
|
|
222
|
+
counter = _CountingGuardrail(real_guardrail, self.max_decide_calls)
|
|
223
|
+
self.g = counter
|
|
224
|
+
try:
|
|
225
|
+
return self._run(attack)
|
|
226
|
+
finally:
|
|
227
|
+
self.g = real_guardrail
|
|
228
|
+
|
|
229
|
+
def _run(self, attack: str) -> EvasionResult:
|
|
230
|
+
counter = self.g
|
|
231
|
+
try:
|
|
232
|
+
base_score = self.g.decide(attack).score
|
|
233
|
+
except _BudgetExceeded:
|
|
234
|
+
raise ValueError("max_decide_calls is too small to score the seed at all")
|
|
235
|
+
if base_score < self.threshold:
|
|
236
|
+
return EvasionResult(False, attack, base_score, attack, base_score, self.threshold,
|
|
237
|
+
0, [], [base_score], seed_flagged=False,
|
|
238
|
+
decide_calls=counter.calls,
|
|
239
|
+
reason="seed was not flagged at this threshold, nothing to evade")
|
|
240
|
+
|
|
241
|
+
best_text, best_score = attack, base_score
|
|
242
|
+
prov: Dict[str, List[str]] = {attack: []} # text -> operators applied so far
|
|
243
|
+
beam: List[str] = [attack]
|
|
244
|
+
seen = {attack}
|
|
245
|
+
trajectory: List[float] = []
|
|
246
|
+
oracle_calls = 0
|
|
247
|
+
scored_count = 0
|
|
248
|
+
stale = 0
|
|
249
|
+
budget_spent = False
|
|
250
|
+
|
|
251
|
+
def result(found: bool, steps: int, reason: str) -> EvasionResult:
|
|
252
|
+
return EvasionResult(found, attack, base_score, best_text, best_score,
|
|
253
|
+
self.threshold, steps, prov.get(best_text, []), trajectory,
|
|
254
|
+
reason=reason, oracle_calls=oracle_calls,
|
|
255
|
+
candidates_scored=scored_count,
|
|
256
|
+
decide_calls=counter.calls)
|
|
257
|
+
|
|
258
|
+
for step in range(1, self.max_steps + 1):
|
|
259
|
+
pool: List[str] = []
|
|
260
|
+
pool_prov: Dict[str, List[str]] = {}
|
|
261
|
+
try:
|
|
262
|
+
for member in beam:
|
|
263
|
+
for cand, op in self._expand(member, seen):
|
|
264
|
+
pool.append(cand)
|
|
265
|
+
pool_prov[cand] = prov[member] + [op]
|
|
266
|
+
except _BudgetExceeded:
|
|
267
|
+
return result(False, step - 1, "guardrail query budget exhausted")
|
|
268
|
+
|
|
269
|
+
if not pool:
|
|
270
|
+
trajectory.append(best_score)
|
|
271
|
+
stale += 1
|
|
272
|
+
if stale >= self.patience:
|
|
273
|
+
break
|
|
274
|
+
continue
|
|
275
|
+
|
|
276
|
+
# Score the whole pool in one batched call, then validate lazily from the best
|
|
277
|
+
# end. Walking the score-sorted list until `beam` candidates pass the oracle
|
|
278
|
+
# yields exactly the `beam` lowest-scoring valid candidates -- the same set the
|
|
279
|
+
# naive order produces -- while calling the oracle a fraction as often. That
|
|
280
|
+
# matters because a real oracle fires a payload at a live target.
|
|
281
|
+
try:
|
|
282
|
+
decisions = self.g.decide_batch(pool)
|
|
283
|
+
except _BudgetExceeded:
|
|
284
|
+
return result(False, step - 1, "guardrail query budget exhausted")
|
|
285
|
+
# a truncated batch returns fewer decisions than candidates; zip to the shorter
|
|
286
|
+
pool = pool[: len(decisions)]
|
|
287
|
+
scored_count += len(pool)
|
|
288
|
+
ranked = sorted(zip((d.score for d in decisions), pool), key=lambda x: x[0])
|
|
289
|
+
|
|
290
|
+
valid: List[Tuple[float, str]] = []
|
|
291
|
+
crossed = False
|
|
292
|
+
for score, cand in ranked:
|
|
293
|
+
if self.max_oracle_calls is not None and oracle_calls >= self.max_oracle_calls:
|
|
294
|
+
budget_spent = True
|
|
295
|
+
break
|
|
296
|
+
oracle_calls += 1
|
|
297
|
+
if not self.oracle(cand):
|
|
298
|
+
continue
|
|
299
|
+
valid.append((score, cand))
|
|
300
|
+
# Once a valid candidate is under the threshold the run is over, so there is
|
|
301
|
+
# no reason to spend more oracle calls filling the beam.
|
|
302
|
+
if score < self.threshold:
|
|
303
|
+
crossed = True
|
|
304
|
+
break
|
|
305
|
+
if len(valid) >= self.beam:
|
|
306
|
+
break
|
|
307
|
+
|
|
308
|
+
if not valid:
|
|
309
|
+
trajectory.append(best_score)
|
|
310
|
+
if budget_spent:
|
|
311
|
+
return result(False, step, "oracle call budget exhausted")
|
|
312
|
+
stale += 1
|
|
313
|
+
if stale >= self.patience:
|
|
314
|
+
break
|
|
315
|
+
continue
|
|
316
|
+
|
|
317
|
+
step_best_score, step_best_text = valid[0]
|
|
318
|
+
if step_best_score < best_score:
|
|
319
|
+
best_score, best_text = step_best_score, step_best_text
|
|
320
|
+
prov[best_text] = pool_prov[best_text]
|
|
321
|
+
stale = 0
|
|
322
|
+
else:
|
|
323
|
+
stale += 1
|
|
324
|
+
for _, c in valid:
|
|
325
|
+
prov.setdefault(c, pool_prov[c])
|
|
326
|
+
beam = [c for _, c in valid]
|
|
327
|
+
trajectory.append(best_score)
|
|
328
|
+
|
|
329
|
+
if crossed or best_score < self.threshold:
|
|
330
|
+
return result(True, step, "evaded below threshold")
|
|
331
|
+
if counter.exhausted:
|
|
332
|
+
return result(False, step, "guardrail query budget exhausted")
|
|
333
|
+
if budget_spent:
|
|
334
|
+
return result(False, step, "oracle call budget exhausted")
|
|
335
|
+
if stale >= self.patience:
|
|
336
|
+
break
|
|
337
|
+
|
|
338
|
+
return result(False, len(trajectory),
|
|
339
|
+
"budget/patience exhausted without crossing threshold")
|
gapfuzz/mapping.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"""Stage 5: blind-spot mapping.
|
|
2
|
+
|
|
3
|
+
Running the fuzzer on one attack tells you whether *that* attack can evade. Running it across a
|
|
4
|
+
corpus and aggregating tells you *where the detector is systematically weak*: which attack
|
|
5
|
+
families fall over, and which mutation operators do the work. That aggregate map is the actual
|
|
6
|
+
deliverable: it points at what to fix (a family to retrain on, an operator the model is blind to),
|
|
7
|
+
not just a single bypass.
|
|
8
|
+
|
|
9
|
+
Seed this with attacks the guardrail **flags** (the true-positive split). A seed it already lets
|
|
10
|
+
through has nothing to evade, so it is counted under `skipped_unflagged` and kept out of the
|
|
11
|
+
evasion rate rather than scoring as a free win.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from collections import Counter
|
|
17
|
+
from dataclasses import dataclass, field
|
|
18
|
+
from typing import Callable, Dict, List, Optional, Tuple
|
|
19
|
+
|
|
20
|
+
from .base import Guardrail
|
|
21
|
+
from .evasion import EvasionFuzzer, EvasionResult
|
|
22
|
+
from .oracle import ValidityOracle
|
|
23
|
+
|
|
24
|
+
# a seed is (family, attack_text, oracle-for-this-attack-or-None-for-default)
|
|
25
|
+
Seed = Tuple[str, str, Optional[ValidityOracle]]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass
|
|
29
|
+
class BlindSpotReport:
|
|
30
|
+
threshold: float
|
|
31
|
+
results: List[EvasionResult]
|
|
32
|
+
families: List[str]
|
|
33
|
+
evaded: int
|
|
34
|
+
total: int # seeds the guardrail actually flagged (the denominator)
|
|
35
|
+
per_family: Dict[str, Dict[str, float]] = field(default_factory=dict)
|
|
36
|
+
operator_wins: Dict[str, int] = field(default_factory=dict)
|
|
37
|
+
skipped_unflagged: int = 0 # seeds the guardrail never flagged, excluded from the rate
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
def evasion_rate(self) -> float:
|
|
41
|
+
return self.evaded / self.total if self.total else 0.0
|
|
42
|
+
|
|
43
|
+
def summary(self) -> str:
|
|
44
|
+
lines = [f"blind-spot map @ threshold {self.threshold:.4f}",
|
|
45
|
+
f" overall evasion rate: {self.evaded}/{self.total} = {self.evasion_rate:.2f}"]
|
|
46
|
+
if self.skipped_unflagged:
|
|
47
|
+
lines.append(f" skipped {self.skipped_unflagged} seed(s) the guardrail never "
|
|
48
|
+
f"flagged (already false negatives, not evasions)")
|
|
49
|
+
lines.append(" by family (evaded / total, mean score drop):")
|
|
50
|
+
for fam, st in sorted(self.per_family.items()):
|
|
51
|
+
lines.append(f" {fam:10} {int(st['evaded'])}/{int(st['total'])} "
|
|
52
|
+
f"Δscore~{st['mean_drop']:.3f}")
|
|
53
|
+
if self.operator_wins:
|
|
54
|
+
top = ", ".join(f"{k}:{v}" for k, v in
|
|
55
|
+
sorted(self.operator_wins.items(), key=lambda kv: -kv[1]))
|
|
56
|
+
lines.append(f" operators that produced evasions: {top}")
|
|
57
|
+
return "\n".join(lines)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class BlindSpotMapper:
|
|
61
|
+
def __init__(self, guardrail: Guardrail, *, oracle: ValidityOracle,
|
|
62
|
+
threshold: float = 0.5, **fuzzer_kwargs):
|
|
63
|
+
self.g = guardrail
|
|
64
|
+
self.oracle = oracle # per-seed oracles override this; see `Seed`
|
|
65
|
+
self.threshold = threshold
|
|
66
|
+
self.fuzzer_kwargs = fuzzer_kwargs
|
|
67
|
+
|
|
68
|
+
def map(self, seeds: List[Seed],
|
|
69
|
+
on_result: Optional[Callable[[Seed, EvasionResult], None]] = None,
|
|
70
|
+
done: Optional[Dict[str, EvasionResult]] = None) -> BlindSpotReport:
|
|
71
|
+
"""Run every seed and aggregate. `on_result` fires after each one, `done` supplies
|
|
72
|
+
results already computed.
|
|
73
|
+
|
|
74
|
+
Together they make a long run survivable. A corpus map is hours of generation under a
|
|
75
|
+
real oracle, and a map that only writes its report at the end loses all of it to a
|
|
76
|
+
timeout -- which is exactly what happened to the first operator ablation, 48 minutes for
|
|
77
|
+
nothing. The caller owns the checkpoint file; this only needs to emit as it goes and to
|
|
78
|
+
accept what was already finished.
|
|
79
|
+
"""
|
|
80
|
+
results: List[EvasionResult] = []
|
|
81
|
+
fam_stat: Dict[str, Dict[str, float]] = {}
|
|
82
|
+
op_wins: Counter = Counter()
|
|
83
|
+
families: List[str] = []
|
|
84
|
+
skipped = 0
|
|
85
|
+
|
|
86
|
+
for family, attack, oracle in seeds:
|
|
87
|
+
if family not in families:
|
|
88
|
+
families.append(family)
|
|
89
|
+
if done is not None and attack in done:
|
|
90
|
+
res = done[attack]
|
|
91
|
+
else:
|
|
92
|
+
fuzzer = EvasionFuzzer(self.g, threshold=self.threshold,
|
|
93
|
+
oracle=oracle or self.oracle, **self.fuzzer_kwargs)
|
|
94
|
+
res = fuzzer.run(attack)
|
|
95
|
+
if on_result is not None:
|
|
96
|
+
on_result((family, attack, oracle), res)
|
|
97
|
+
results.append(res)
|
|
98
|
+
if not res.seed_flagged:
|
|
99
|
+
skipped += 1
|
|
100
|
+
continue
|
|
101
|
+
|
|
102
|
+
st = fam_stat.setdefault(family, {"evaded": 0.0, "total": 0.0, "drop_sum": 0.0})
|
|
103
|
+
st["total"] += 1
|
|
104
|
+
st["drop_sum"] += res.score_drop
|
|
105
|
+
if res.found:
|
|
106
|
+
st["evaded"] += 1
|
|
107
|
+
for op in dict.fromkeys(res.operators): # unique operators on the winning path
|
|
108
|
+
op_wins[op] += 1
|
|
109
|
+
|
|
110
|
+
for st in fam_stat.values():
|
|
111
|
+
st["mean_drop"] = st["drop_sum"] / st["total"] if st["total"] else 0.0
|
|
112
|
+
|
|
113
|
+
evaded = sum(1 for r in results if r.found)
|
|
114
|
+
return BlindSpotReport(threshold=self.threshold, results=results, families=families,
|
|
115
|
+
evaded=evaded, total=len(results) - skipped, per_family=fam_stat,
|
|
116
|
+
operator_wins=dict(op_wins), skipped_unflagged=skipped)
|