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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
//! The `Detector` adapter for a parsed declarative ruleset (issue #495,
//! `decision-define-declarative-detector-ruleset-contract`).
//!
//! [`crate::ruleset::parse_ruleset`] turns caller-supplied bytes into
//! [`RulesetDetectorSpec`]s; this module turns each spec into a
//! [`RulesetDetector`], feeding the unmodified [`super::pattern::scan_prefixed_shapes`]
//! — the same left-to-right, longest-prefix-wins, linear-time engine every
//! built-in prefixed detector already runs through. Nothing here changes
//! `pattern.rs`'s matching logic, alphabets, `RunLength` shape, or boundary
//! check.
//!
//! Two properties this adapter fixes, both already documented as settled on
//! `crate::ruleset`'s module docs and issue #495's "Decisions this issue
//! settles":
//!
//! - **Confidence is always [`Confidence::Medium`]**, regardless of the
//! ruleset's own content. There is no way to lower or raise it — revision
//! 1's grammar has no `confidence` field.
//! - **The `trailing-lower-hex` validator cannot be expressed as a
//! [`PostCheck`]**, because `PostCheck` is a bare function pointer
//! (`fn(&[u8], usize, usize) -> bool`) with no captured environment, and a
//! ruleset's checksum tail length is a per-ruleset, runtime value. This
//! adapter instead applies the check itself, after
//! `scan_prefixed_shapes` returns — still the identical boundary- and
//! run-length-filtered match, just with one extra fixed-shape filter on
//! top, the same position a `PostCheck` would have run it in.
use crate::error::DetectorFailure;
use crate::ruleset::{AlphabetName, RulesetDetectorSpec, RunSpec, ValidatorName};
use crate::types::{ByteRange, Candidate, Confidence, Detector, DetectorContext};
use super::pattern::{
self, Alphabet, PrefixShape, RunLength, is_alnum, is_alnum_dash, is_alnum_dash_dot,
is_base64_body, is_digit, is_lower_hex, is_upper_alnum,
};
use super::prefilter;
/// Maps a ruleset's named alphabet to the matching byte-class predicate —
/// the same seven functions [`super::pattern`] already defines for every
/// built-in shape. A ruleset cannot name an eighth
/// (`crate::ruleset::AlphabetName::from_wire`).
const fn alphabet_fn(name: AlphabetName) -> Alphabet {
match name {
AlphabetName::Alnum => is_alnum,
AlphabetName::AlnumDash => is_alnum_dash,
AlphabetName::AlnumDashDot => is_alnum_dash_dot,
AlphabetName::UpperAlnum => is_upper_alnum,
AlphabetName::Digit => is_digit,
AlphabetName::LowerHex => is_lower_hex,
AlphabetName::Base64Body => is_base64_body,
}
}
/// The declared `run` count, whichever form it took. This is the only
/// length available to the `trailing-lower-hex` validator — revision 1's
/// grammar has no second, caller-supplied checksum-length field
/// (`decision-define-declarative-detector-ruleset-contract`, "Closed
/// validator enum": "`n` comes from the ruleset detector's own run-length
/// field, not a second caller-supplied parameter").
const fn declared_run_count(run: RunSpec) -> usize {
match run {
RunSpec::Exact(count) | RunSpec::AtLeast(count) => count,
}
}
/// `true` when the matched run's final `tail_len` bytes are lowercase hex —
/// generalizing the Cloudflare detector's already-shipped
/// `checksum_tail_is_lower_hex` shape
/// (`crate::detectors::cloudflare`) to a caller-declared tail length. For
/// `run: exact <n>`, `tail_len` equals the whole matched run, so the check
/// covers it entirely; for `run: at-least <n>`, it covers only the final
/// `n` bytes of however much longer the matched run turned out to be, the
/// same "body of unspecified length, fixed-length checksum tail" shape
/// Cloudflare's own detector uses.
fn trailing_lower_hex_ok(bytes: &[u8], start: usize, end: usize, tail_len: usize) -> bool {
let matched_len = end - start;
if tail_len > matched_len {
return false;
}
let tail_start = end - tail_len;
bytes[tail_start..end].iter().copied().all(is_lower_hex)
}
/// A registrable [`Detector`] for one parsed ruleset detector block.
///
/// Wraps the spec's prefix, alphabet, run, and validator into exactly the
/// [`PrefixShape`] grammar the ADR fixes, and always emits
/// [`Confidence::Medium`] at the spec's own claimed
/// [`Specificity`](crate::Specificity) — never [`Specificity::Structural`],
/// [`Specificity::Provider`], or [`Specificity::PrivateKey`], which
/// [`crate::ruleset::parse_ruleset`] already refuses to parse.
pub(crate) struct RulesetDetector {
spec: RulesetDetectorSpec,
}
impl RulesetDetector {
/// Wraps an already-validated spec. Construction cannot fail: every
/// rejection happened during parsing.
#[must_use]
pub(crate) const fn new(spec: RulesetDetectorSpec) -> Self {
Self { spec }
}
}
impl Detector for RulesetDetector {
fn id(&self) -> &str {
self.spec.id()
}
fn detect(
&self,
input: &str,
_context: &DetectorContext,
) -> Result<Vec<Candidate>, DetectorFailure> {
// Every candidate starts with the prefix. Inside a pipeline scan the
// scan copy's shared byte pairs can rule it out without searching
// (issue #1057); debug builds search anyway and check that the scan
// would have found nothing.
if !prefilter::ruleset_literal_may_occur(input, self.spec.prefix().as_bytes()) {
#[cfg(debug_assertions)]
assert!(
self.scan(input).is_empty(),
"the ruleset prefilter ruled out a prefix that occurs in its input"
);
return Ok(Vec::new());
}
Ok(self.scan(input))
}
}
impl RulesetDetector {
/// Every candidate in `input`, found by searching it.
fn scan(&self, input: &str) -> Vec<Candidate> {
let alphabet = alphabet_fn(self.spec.alphabet());
let run = match self.spec.run() {
RunSpec::Exact(count) => RunLength::Exact(count),
RunSpec::AtLeast(count) => RunLength::AtLeast(count),
};
// Revision 1's grammar carries no separate boundary alphabet, so
// the matched alphabet doubles as its own boundary: a candidate is
// rejected when it is a truncated slice of a longer run of the same
// alphabet, the fixed behavior `crate::ruleset`'s module docs
// promise ("Boundary behavior is fixed and not caller-configurable").
let shape = PrefixShape {
prefix: self.spec.prefix(),
run,
alphabet,
signals: &[],
post_check: None,
};
let mut candidates = Vec::with_capacity(1);
for (start, end, _signals) in pattern::scan_prefixed_shapes(input, &[shape], alphabet) {
if self.spec.validator() == ValidatorName::TrailingLowerHex {
let tail_len = declared_run_count(self.spec.run());
if !trailing_lower_hex_ok(input.as_bytes(), start, end, tail_len) {
continue;
}
}
let Some(range) = ByteRange::new(start, end) else {
continue;
};
candidates.push(
Candidate::new(self.spec.id(), Confidence::Medium, range)
.with_specificity(self.spec.specificity()),
);
}
candidates
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ruleset::parse_ruleset;
use crate::types::Specificity;
fn ruleset(body: &str) -> String {
format!("ruleset-revision: 1\n{body}")
}
fn detect_with(ruleset_text: &str, input: &str) -> Vec<Candidate> {
let mut parsed = parse_ruleset(ruleset_text.as_bytes()).unwrap();
let detector = RulesetDetector::new(parsed.detectors.remove(0));
detector
.detect(input, &DetectorContext::new(input.len()))
.unwrap()
}
#[test]
fn id_is_the_declared_detector_id() {
let text = ruleset(
"detector: acme-internal-token\n\
specificity: contextual\n\
prefix: \"ACME_\"\n\
alphabet: alnum-dash\n\
run: at-least 20\n\
validator: none\n",
);
let mut parsed = parse_ruleset(text.as_bytes()).unwrap();
let detector = RulesetDetector::new(parsed.detectors.remove(0));
assert_eq!(detector.id(), "acme-internal-token");
}
#[test]
fn matches_an_exact_run_and_always_claims_medium_confidence() {
let text = ruleset(
"detector: acme-internal-token\n\
specificity: contextual\n\
prefix: \"ACME_\"\n\
alphabet: alnum-dash\n\
run: exact 20\n\
validator: none\n",
);
let value = "a".repeat(20);
let input = format!("ACME_{value}");
let candidates = detect_with(&text, &input);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].type_name(), "acme-internal-token");
assert_eq!(candidates[0].confidence(), Confidence::Medium);
assert_eq!(
candidates[0].effective_specificity(),
Specificity::Contextual
);
assert_eq!(
candidates[0].range(),
ByteRange::new(0, input.len()).unwrap()
);
}
#[test]
fn an_entropy_specificity_claim_round_trips() {
let text = ruleset(
"detector: acme-heuristic-token\n\
specificity: entropy\n\
prefix: \"ACME_\"\n\
alphabet: alnum\n\
run: at-least 10\n\
validator: none\n",
);
let candidates = detect_with(&text, "ACME_abcdefghij");
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].effective_specificity(), Specificity::Entropy);
}
#[test]
fn rejects_a_run_shorter_than_the_declared_minimum() {
let text = ruleset(
"detector: acme-internal-token\n\
specificity: contextual\n\
prefix: \"ACME_\"\n\
alphabet: alnum-dash\n\
run: at-least 20\n\
validator: none\n",
);
assert!(detect_with(&text, "ACME_shorttoken").is_empty());
}
#[test]
fn takes_the_maximal_run_for_at_least() {
let text = ruleset(
"detector: acme-internal-token\n\
specificity: contextual\n\
prefix: \"ACME_\"\n\
alphabet: alnum-dash\n\
run: at-least 10\n\
validator: none\n",
);
let value = "a".repeat(40);
let input = format!("ACME_{value}");
let candidates = detect_with(&text, &input);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].range().len(), input.len());
}
#[test]
fn rejects_a_candidate_truncated_by_the_self_boundary() {
// The matched alphabet is also the boundary: a wider identical-alphabet
// run right after the declared count must reject, not truncate.
let text = ruleset(
"detector: acme-internal-token\n\
specificity: contextual\n\
prefix: \"ACME_\"\n\
alphabet: alnum-dash\n\
run: exact 20\n\
validator: none\n",
);
let input = format!("ACME_{}extra", "a".repeat(20));
assert!(detect_with(&text, &input).is_empty());
}
#[test]
fn rejects_the_prefix_embedded_in_a_wider_identifier() {
let text = ruleset(
"detector: acme-internal-token\n\
specificity: contextual\n\
prefix: \"ACME_\"\n\
alphabet: alnum-dash\n\
run: at-least 20\n\
validator: none\n",
);
let value = "a".repeat(20);
assert_eq!(detect_with(&text, &format!("ACME_{value}")).len(), 1);
assert!(detect_with(&text, &format!("xACME_{value}")).is_empty());
}
#[test]
fn trailing_lower_hex_validator_requires_the_final_declared_count_of_bytes_to_be_hex() {
let text = ruleset(
"detector: acme-checksum-token\n\
specificity: contextual\n\
prefix: \"ACME_\"\n\
alphabet: alnum\n\
run: at-least 8\n\
validator: trailing-lower-hex\n",
);
// A run whose final 8 bytes are lowercase hex passes.
let good = "SYNTHETICdeadbeef";
let input = format!("ACME_{good}");
let candidates = detect_with(&text, &input);
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].range().len(), input.len());
// A run whose final 8 bytes are not all lowercase hex is rejected
// outright — the ruleset grammar has no fallback truncation.
let bad = "SYNTHETICnothexZZ";
assert!(detect_with(&text, &format!("ACME_{bad}")).is_empty());
}
#[test]
fn trailing_lower_hex_validator_on_an_exact_run_requires_the_whole_run_to_be_hex() {
let text = ruleset(
"detector: acme-checksum-token\n\
specificity: contextual\n\
prefix: \"ACME_\"\n\
alphabet: alnum\n\
run: exact 8\n\
validator: trailing-lower-hex\n",
);
assert_eq!(detect_with(&text, "ACME_deadbeef").len(), 1);
assert!(detect_with(&text, "ACME_deadbeeZ").is_empty());
}
#[test]
fn finds_deterministic_findings_across_repeated_calls() {
let text = ruleset(
"detector: acme-internal-token\n\
specificity: contextual\n\
prefix: \"ACME_\"\n\
alphabet: alnum-dash\n\
run: at-least 20\n\
validator: none\n",
);
let input = format!("ACME_{}", "a".repeat(20));
assert_eq!(detect_with(&text, &input), detect_with(&text, &input));
}
#[test]
fn reports_every_occurrence_in_the_input() {
let text = ruleset(
"detector: acme-internal-token\n\
specificity: contextual\n\
prefix: \"ACME_\"\n\
alphabet: alnum-dash\n\
run: at-least 20\n\
validator: none\n",
);
let value = "a".repeat(20);
let input = format!("ACME_{value} ACME_{value}");
assert_eq!(detect_with(&text, &input).len(), 2);
}
}