doppel 0.0.1

Intercept secrets in byte payloads, replace them with structurally-equivalent fakes, and transparently restore originals in streaming responses.
Documentation
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
//! Built-in structural patterns and per-call constructor functions.
//!
//! Each `pub fn` in this module returns a [`Pattern`] with an ephemeral salt.
//! For persistent cross-restart fake stability, use [`crate::SecretsFile::to_patterns`].

use crate::secrets::RegisteredPat;
use crate::segment::{BuiltinSegment, CharsetName, MatchCapture, Segment};
use aho_corasick::AhoCorasick;
use std::sync::{Arc, LazyLock};

/// Structural definition of a structural built-in secret class.
#[derive(Clone)]
pub struct StructuralDef {
    /// Stable string identifier for this class, used as the key in patterns files.
    pub(crate) identifier: String,
    /// Ordered sequence of structural segments for this secret class.
    /// See SPEC.md §Structural Patterns.
    pub(crate) segments: Arc<[Segment]>,
    /// Derivation salt for fake generation. Zero in static template definitions;
    /// set to a real (random or loaded) value when constructing a Pattern.
    pub(crate) salt: [u8; 32],
}

impl StructuralDef {
    /// Walk `payload[pos..]` against the segment list. Returns `Some(MatchCapture)`
    /// on a complete match, `None` otherwise.
    ///
    /// Variable segments try lengths from max down to min (longest-first, INV-18).
    /// When a Variable segment is followed by a Literal, the Literal boundary is
    /// located within the valid Variable range — handling embedded markers like
    /// `T3BlbkFJ` that are themselves valid Variable-charset bytes.
    pub(crate) fn try_match(&self, payload: &[u8], pos: usize) -> Option<MatchCapture> {
        let mut variable_lengths = Vec::new();
        let end = match_segments(payload, pos, &self.segments, &mut variable_lengths)?;
        Some(MatchCapture {
            end,
            variable_lengths,
        })
    }
}

/// Recursive segment-list matcher. Returns the exclusive end position on success.
/// Appends one entry to `var_lens` for each Variable segment that matches.
/// On failure, any entries appended in the failing sub-tree are removed by the caller.
fn match_segments(
    payload: &[u8],
    cur: usize,
    segs: &[Segment],
    var_lens: &mut Vec<usize>,
) -> Option<usize> {
    if segs.is_empty() {
        return Some(cur);
    }
    match &segs[0] {
        Segment::Literal(bytes) => {
            let end = cur + bytes.len();
            if payload.get(cur..end)? == bytes.as_slice() {
                match_segments(payload, end, &segs[1..], var_lens)
            } else {
                None
            }
        }
        Segment::Variable { charset, min, max } => {
            let cs = charset.resolve();
            // Try lengths from max down to min (longest-first, INV-18).
            for var_len in (*min..=*max).rev() {
                let end = cur + var_len;
                if end > payload.len() {
                    continue;
                }
                if payload[cur..end].iter().all(|&b| cs.contains(b)) {
                    let saved = var_lens.len();
                    var_lens.push(var_len);
                    if let Some(result) = match_segments(payload, end, &segs[1..], var_lens) {
                        return Some(result);
                    }
                    var_lens.truncate(saved);
                }
            }
            None
        }
    }
}

// Note on sk-proj- vs sk-: at a "sk-proj-..." position, OPENAI_PROJECT_DEF produces a longer
// match because it finds T3BlbkFJ at the correct offset; OPENAI_CLASSIC_DEF fails because
// 'proj-' contains '-' which is not alphanumeric. The swap engine picks the longest match (INV-18).

const ANTHROPIC_SEGS: [BuiltinSegment; 3] = [
    BuiltinSegment::Literal(b"sk-ant-api03-"),
    BuiltinSegment::Variable {
        charset: CharsetName::UrlSafeBase64,
        min: 93,
        max: 93,
    },
    BuiltinSegment::Literal(b"AA"),
];
static ANTHROPIC_DEF: LazyLock<StructuralDef> = LazyLock::new(|| StructuralDef {
    identifier: "anthropic".into(),
    // sk-ant-api03-<93 url_safe_base64>AA = 108 chars total
    // Source: gitleaks `sk-ant-api03-[a-zA-Z0-9_\-]{93}AA`
    segments: ANTHROPIC_SEGS
        .iter()
        .map(Segment::from)
        .collect::<Vec<_>>()
        .into(),
    salt: [0u8; 32],
});

const OPENAI_CLASSIC_SEGS: [BuiltinSegment; 2] = [
    BuiltinSegment::Literal(b"sk-"),
    BuiltinSegment::Variable {
        charset: CharsetName::Alphanumeric,
        min: 48,
        max: 48,
    },
];
static OPENAI_CLASSIC_DEF: LazyLock<StructuralDef> = LazyLock::new(|| StructuralDef {
    identifier: "openai_classic".into(),
    // sk-<48 alphanumeric> = 51 chars total
    segments: OPENAI_CLASSIC_SEGS
        .iter()
        .map(Segment::from)
        .collect::<Vec<_>>()
        .into(),
    salt: [0u8; 32],
});

const OPENAI_PROJECT_SEGS: [BuiltinSegment; 4] = [
    BuiltinSegment::Literal(b"sk-proj-"),
    BuiltinSegment::Variable {
        charset: CharsetName::UrlSafeBase64,
        min: 58,
        max: 74,
    },
    BuiltinSegment::Literal(b"T3BlbkFJ"),
    BuiltinSegment::Variable {
        charset: CharsetName::UrlSafeBase64,
        min: 58,
        max: 74,
    },
];
static OPENAI_PROJECT_DEF: LazyLock<StructuralDef> = LazyLock::new(|| StructuralDef {
    identifier: "openai_project".into(),
    // sk-proj-<58|74 url_safe_b64>T3BlbkFJ<58|74 url_safe_b64> = 132 or 164 chars total.
    // The pre-Aug-2024 56-char format (sk-proj-<48 url_safe_b64>, no T3BlbkFJ) is intentionally
    // not detected: those keys are ~2 years old and structurally indistinguishable from noise
    // without the embedded marker. Best-effort coverage per SPEC.md §Known Limitations.
    // Source: gitleaks openai-api-key rule + OpenAI community reports.
    segments: OPENAI_PROJECT_SEGS
        .iter()
        .map(Segment::from)
        .collect::<Vec<_>>()
        .into(),
    salt: [0u8; 32],
});

const AWS_AKIA_SEGS: [BuiltinSegment; 2] = [
    BuiltinSegment::Literal(b"AKIA"),
    BuiltinSegment::Variable {
        charset: CharsetName::UppercaseAlphanumeric,
        min: 16,
        max: 16,
    },
];
static AWS_AKIA_DEF: LazyLock<StructuralDef> = LazyLock::new(|| StructuralDef {
    identifier: "aws_akia".into(),
    // AKIA<16 uppercase_alphanumeric> = 20 chars total
    segments: AWS_AKIA_SEGS
        .iter()
        .map(Segment::from)
        .collect::<Vec<_>>()
        .into(),
    salt: [0u8; 32],
});

const AWS_ASIA_SEGS: [BuiltinSegment; 2] = [
    BuiltinSegment::Literal(b"ASIA"),
    BuiltinSegment::Variable {
        charset: CharsetName::UppercaseAlphanumeric,
        min: 16,
        max: 16,
    },
];
static AWS_ASIA_DEF: LazyLock<StructuralDef> = LazyLock::new(|| StructuralDef {
    identifier: "aws_asia".into(),
    // ASIA<16 uppercase_alphanumeric> = 20 chars total
    segments: AWS_ASIA_SEGS
        .iter()
        .map(Segment::from)
        .collect::<Vec<_>>()
        .into(),
    salt: [0u8; 32],
});

const GITHUB_CLASSIC_SEGS: [BuiltinSegment; 2] = [
    BuiltinSegment::Literal(b"ghp_"),
    BuiltinSegment::Variable {
        charset: CharsetName::Alphanumeric,
        min: 36,
        max: 36,
    },
];
static GITHUB_CLASSIC_DEF: LazyLock<StructuralDef> = LazyLock::new(|| StructuralDef {
    identifier: "github_classic".into(),
    // ghp_<36 alphanumeric> = 40 chars total
    segments: GITHUB_CLASSIC_SEGS
        .iter()
        .map(Segment::from)
        .collect::<Vec<_>>()
        .into(),
    salt: [0u8; 32],
});

const GITHUB_FG_SEGS: [BuiltinSegment; 4] = [
    BuiltinSegment::Literal(b"github_pat_"),
    BuiltinSegment::Variable {
        charset: CharsetName::Alphanumeric,
        min: 22,
        max: 22,
    },
    BuiltinSegment::Literal(b"_"),
    BuiltinSegment::Variable {
        charset: CharsetName::Alphanumeric,
        min: 59,
        max: 59,
    },
];
static GITHUB_FG_DEF: LazyLock<StructuralDef> = LazyLock::new(|| StructuralDef {
    identifier: "github_fine_grained".into(),
    // github_pat_<22 alnum>_<59 alnum> = 93 chars total
    // Source: gitleaks `github_pat_\w{82}` (82 = 22 + 1 separator + 59)
    segments: GITHUB_FG_SEGS
        .iter()
        .map(Segment::from)
        .collect::<Vec<_>>()
        .into(),
    salt: [0u8; 32],
});

const GCP_SEGS: [BuiltinSegment; 2] = [
    BuiltinSegment::Literal(b"AIza"),
    BuiltinSegment::Variable {
        charset: CharsetName::UrlSafeBase64,
        min: 35,
        max: 35,
    },
];
static GCP_DEF: LazyLock<StructuralDef> = LazyLock::new(|| StructuralDef {
    identifier: "gcp".into(),
    // AIza<35 url_safe_base64> = 39 chars total
    segments: GCP_SEGS
        .iter()
        .map(Segment::from)
        .collect::<Vec<_>>()
        .into(),
    salt: [0u8; 32],
});

const OPENROUTER_SEGS: [BuiltinSegment; 2] = [
    BuiltinSegment::Literal(b"sk-or-v1-"),
    BuiltinSegment::Variable {
        charset: CharsetName::HexLower,
        min: 64,
        max: 64,
    },
];
static OPENROUTER_DEF: LazyLock<StructuralDef> = LazyLock::new(|| StructuralDef {
    identifier: "openrouter".into(),
    // sk-or-v1-<64 hex_lower> = 73 chars total
    // Source: xchecker-dev `sk-or-v1-[0-9a-fA-F]{64}`
    segments: OPENROUTER_SEGS
        .iter()
        .map(Segment::from)
        .collect::<Vec<_>>()
        .into(),
    salt: [0u8; 32],
});

const OPENAI_SVCACCT_SEGS: [BuiltinSegment; 4] = [
    BuiltinSegment::Literal(b"sk-svcacct-"),
    BuiltinSegment::Variable {
        charset: CharsetName::UrlSafeBase64,
        min: 58,
        max: 74,
    },
    BuiltinSegment::Literal(b"T3BlbkFJ"),
    BuiltinSegment::Variable {
        charset: CharsetName::UrlSafeBase64,
        min: 58,
        max: 74,
    },
];
static OPENAI_SVCACCT_DEF: LazyLock<StructuralDef> = LazyLock::new(|| StructuralDef {
    identifier: "openai_svcacct".into(),
    // sk-svcacct-<58|74>T3BlbkFJ<58|74> = 135 or 167 chars total
    // Source: gitleaks `sk-(?:proj|svcacct|admin)-...T3BlbkFJ...`
    segments: OPENAI_SVCACCT_SEGS
        .iter()
        .map(Segment::from)
        .collect::<Vec<_>>()
        .into(),
    salt: [0u8; 32],
});

const GOOGLE_OAUTH_SEGS: [BuiltinSegment; 2] = [
    BuiltinSegment::Literal(b"GOCSPX-"),
    BuiltinSegment::Variable {
        charset: CharsetName::UrlSafeBase64,
        min: 28,
        max: 28,
    },
];
static GOOGLE_OAUTH_SECRET_DEF: LazyLock<StructuralDef> = LazyLock::new(|| StructuralDef {
    identifier: "google_oauth_secret".into(),
    // GOCSPX-<28 url_safe_base64> = 35 chars total
    // Source: secretgate docs "GOCSPX- + 28 chars"
    segments: GOOGLE_OAUTH_SEGS
        .iter()
        .map(Segment::from)
        .collect::<Vec<_>>()
        .into(),
    salt: [0u8; 32],
});

const SLACK_BOT_SEGS: [BuiltinSegment; 6] = [
    BuiltinSegment::Literal(b"xoxb-"),
    BuiltinSegment::Variable {
        charset: CharsetName::Digits,
        min: 10,
        max: 13,
    },
    BuiltinSegment::Literal(b"-"),
    BuiltinSegment::Variable {
        charset: CharsetName::Digits,
        min: 10,
        max: 13,
    },
    BuiltinSegment::Literal(b"-"),
    BuiltinSegment::Variable {
        charset: CharsetName::Alphanumeric,
        min: 24,
        max: 24,
    },
];
static SLACK_BOT_DEF: LazyLock<StructuralDef> = LazyLock::new(|| StructuralDef {
    identifier: "slack_bot".into(),
    // xoxb-<10-13 digits>-<10-13 digits>-<24 alnum> = 51-57 chars total
    // Source: gitleaks `xoxb-[0-9]{10,13}-[0-9]{10,13}[a-zA-Z0-9-]*`
    segments: SLACK_BOT_SEGS
        .iter()
        .map(Segment::from)
        .collect::<Vec<_>>()
        .into(),
    salt: [0u8; 32],
});

const ANTHROPIC_ADMIN01_SEGS: [BuiltinSegment; 3] = [
    BuiltinSegment::Literal(b"sk-ant-admin01-"),
    BuiltinSegment::Variable {
        charset: CharsetName::UrlSafeBase64,
        min: 93,
        max: 93,
    },
    BuiltinSegment::Literal(b"AA"),
];
static ANTHROPIC_ADMIN01_DEF: LazyLock<StructuralDef> = LazyLock::new(|| StructuralDef {
    identifier: "anthropic_admin01".into(),
    // sk-ant-admin01-<93 url_safe_base64>AA = 110 chars total
    // Source: gitleaks `sk-ant-admin01-[a-zA-Z0-9_\-]{93}AA`
    segments: ANTHROPIC_ADMIN01_SEGS
        .iter()
        .map(Segment::from)
        .collect::<Vec<_>>()
        .into(),
    salt: [0u8; 32],
});

const ANTHROPIC_ADMIN03_SEGS: [BuiltinSegment; 3] = [
    BuiltinSegment::Literal(b"sk-ant-admin03-"),
    BuiltinSegment::Variable {
        charset: CharsetName::UrlSafeBase64,
        min: 93,
        max: 93,
    },
    BuiltinSegment::Literal(b"AA"),
];
static ANTHROPIC_ADMIN03_DEF: LazyLock<StructuralDef> = LazyLock::new(|| StructuralDef {
    identifier: "anthropic_admin03".into(),
    // sk-ant-admin03-<93 url_safe_base64>AA = 110 chars total
    // Source: Anthropic Terraform provider docs
    segments: ANTHROPIC_ADMIN03_SEGS
        .iter()
        .map(Segment::from)
        .collect::<Vec<_>>()
        .into(),
    salt: [0u8; 32],
});

const LINEAR_SEGS: [BuiltinSegment; 2] = [
    BuiltinSegment::Literal(b"lin_api_"),
    BuiltinSegment::Variable {
        charset: CharsetName::Alphanumeric,
        min: 40,
        max: 40,
    },
];
static LINEAR_DEF: LazyLock<StructuralDef> = LazyLock::new(|| StructuralDef {
    identifier: "linear".into(),
    // lin_api_<40 alphanumeric> = 48 chars total
    // Source: gitleaks `lin_api_(?i)[a-z0-9]{40}`
    segments: LINEAR_SEGS
        .iter()
        .map(Segment::from)
        .collect::<Vec<_>>()
        .into(),
    salt: [0u8; 32],
});

static ALL_STRUCTURAL_DEFS: LazyLock<Vec<&'static StructuralDef>> = LazyLock::new(|| {
    vec![
        &*ANTHROPIC_DEF,
        &*ANTHROPIC_ADMIN01_DEF,
        &*ANTHROPIC_ADMIN03_DEF,
        &*OPENAI_CLASSIC_DEF,
        &*OPENAI_PROJECT_DEF,
        &*OPENAI_SVCACCT_DEF,
        &*AWS_AKIA_DEF,
        &*AWS_ASIA_DEF,
        &*GITHUB_CLASSIC_DEF,
        &*GITHUB_FG_DEF,
        &*GCP_DEF,
        &*OPENROUTER_DEF,
        &*GOOGLE_OAUTH_SECRET_DEF,
        &*SLACK_BOT_DEF,
        &*LINEAR_DEF,
    ]
});

/// Returns references to all 15 built-in structural pattern definitions.
/// Used by patterns file loading to iterate and inject salts.
pub(crate) fn all_defs() -> &'static [&'static StructuralDef] {
    &ALL_STRUCTURAL_DEFS
}

static STRUCTURAL_PREFIXES: &[&[u8]] = &[
    b"sk-ant-api03-",
    b"sk-ant-admin01-",
    b"sk-ant-admin03-",
    b"sk-proj-",
    b"sk-svcacct-",
    b"sk-or-v1-",
    b"sk-",
    b"AKIA",
    b"ASIA",
    b"ghp_",
    b"github_pat_",
    b"AIza",
    b"GOCSPX-",
    b"xoxb-",
    b"lin_api_",
];

pub(crate) static TIER1_PREFIX_FILTER: LazyLock<AhoCorasick> = LazyLock::new(|| {
    AhoCorasick::new(STRUCTURAL_PREFIXES).expect("failed to build structural prefix AC")
});

/// Returns the pre-built Aho-Corasick automaton for structural-pattern literal prefix detection.
pub(crate) fn prefix_filter() -> &'static AhoCorasick {
    &TIER1_PREFIX_FILTER
}

/// A detection descriptor for [`crate::swap`].
///
/// Obtain via [`crate::patterns`] functions or [`crate::register`]/[`crate::register_with_options`].
/// Pass to [`crate::swap`] — do not match on variants in stable code; the variant
/// set may change in future versions.
#[derive(Clone)]
#[non_exhaustive]
pub enum Pattern {
    /// Structural pattern: matched by walking payload bytes against a segment list.
    Structural(StructuralDef),
    /// Registered pattern: matched by start/end fragment + HMAC verification.
    Registered(Arc<RegisteredPat>),
}

impl Pattern {
    pub(crate) fn is_registered(&self) -> bool {
        matches!(self, Pattern::Registered(_))
    }
}

use rand::RngCore;
use rand::rngs::OsRng;

fn random_salt() -> [u8; 32] {
    let mut salt = [0u8; 32];
    OsRng.fill_bytes(&mut salt);
    salt
}

/// Returns an Anthropic key pattern with an ephemeral salt.
///
/// Fakes are stable for the lifetime of the returned `Pattern` value but differ
/// across calls and process restarts. For cross-restart stability, use
/// `SecretsFile::to_patterns()`.
pub fn anthropic() -> Pattern {
    Pattern::Structural(StructuralDef {
        salt: random_salt(),
        ..ANTHROPIC_DEF.clone()
    })
}

/// Returns an Anthropic Admin v1 key pattern (`sk-ant-admin01-`) with an ephemeral salt.
///
/// See [`anthropic`] for salt stability semantics.
pub fn anthropic_admin01() -> Pattern {
    Pattern::Structural(StructuralDef {
        salt: random_salt(),
        ..ANTHROPIC_ADMIN01_DEF.clone()
    })
}

/// Returns an Anthropic Admin v3 key pattern (`sk-ant-admin03-`) with an ephemeral salt.
///
/// See [`anthropic`] for salt stability semantics.
pub fn anthropic_admin03() -> Pattern {
    Pattern::Structural(StructuralDef {
        salt: random_salt(),
        ..ANTHROPIC_ADMIN03_DEF.clone()
    })
}

/// Returns an OpenAI classic secret key pattern (`sk-`) with an ephemeral salt.
///
/// See [`anthropic`] for salt stability semantics.
pub fn openai_classic() -> Pattern {
    Pattern::Structural(StructuralDef {
        salt: random_salt(),
        ..OPENAI_CLASSIC_DEF.clone()
    })
}

/// Returns an OpenAI project key pattern (`sk-proj-`) with an ephemeral salt.
///
/// See [`anthropic`] for salt stability semantics.
pub fn openai_project() -> Pattern {
    Pattern::Structural(StructuralDef {
        salt: random_salt(),
        ..OPENAI_PROJECT_DEF.clone()
    })
}

/// Returns an OpenAI service account key pattern (`sk-svcacct-`) with an ephemeral salt.
///
/// See [`anthropic`] for salt stability semantics.
pub fn openai_svcacct() -> Pattern {
    Pattern::Structural(StructuralDef {
        salt: random_salt(),
        ..OPENAI_SVCACCT_DEF.clone()
    })
}

/// Returns an AWS IAM access key ID pattern (`AKIA`) with an ephemeral salt.
///
/// See [`anthropic`] for salt stability semantics.
pub fn aws_akia() -> Pattern {
    Pattern::Structural(StructuralDef {
        salt: random_salt(),
        ..AWS_AKIA_DEF.clone()
    })
}

/// Returns an AWS STS temporary credential pattern (`ASIA`) with an ephemeral salt.
///
/// See [`anthropic`] for salt stability semantics.
pub fn aws_asia() -> Pattern {
    Pattern::Structural(StructuralDef {
        salt: random_salt(),
        ..AWS_ASIA_DEF.clone()
    })
}

/// Returns a GitHub classic personal access token pattern (`ghp_`) with an ephemeral salt.
///
/// See [`anthropic`] for salt stability semantics.
pub fn github_classic() -> Pattern {
    Pattern::Structural(StructuralDef {
        salt: random_salt(),
        ..GITHUB_CLASSIC_DEF.clone()
    })
}

/// Returns a GitHub fine-grained personal access token pattern (`github_pat_`) with an ephemeral salt.
///
/// See [`anthropic`] for salt stability semantics.
pub fn github_fine_grained() -> Pattern {
    Pattern::Structural(StructuralDef {
        salt: random_salt(),
        ..GITHUB_FG_DEF.clone()
    })
}

/// Returns a GCP/Gemini API key pattern (`AIza`) with an ephemeral salt.
///
/// See [`anthropic`] for salt stability semantics.
pub fn gcp() -> Pattern {
    Pattern::Structural(StructuralDef {
        salt: random_salt(),
        ..GCP_DEF.clone()
    })
}

/// Returns an OpenRouter API key pattern (`sk-or-v1-`) with an ephemeral salt.
///
/// See [`anthropic`] for salt stability semantics.
pub fn openrouter() -> Pattern {
    Pattern::Structural(StructuralDef {
        salt: random_salt(),
        ..OPENROUTER_DEF.clone()
    })
}

/// Returns a Google OAuth client secret pattern (`GOCSPX-`) with an ephemeral salt.
///
/// See [`anthropic`] for salt stability semantics.
pub fn google_oauth_secret() -> Pattern {
    Pattern::Structural(StructuralDef {
        salt: random_salt(),
        ..GOOGLE_OAUTH_SECRET_DEF.clone()
    })
}

/// Returns a Slack bot token pattern (`xoxb-`) with an ephemeral salt.
///
/// See [`anthropic`] for salt stability semantics.
pub fn slack_bot() -> Pattern {
    Pattern::Structural(StructuralDef {
        salt: random_salt(),
        ..SLACK_BOT_DEF.clone()
    })
}

/// Returns a Linear API key pattern (`lin_api_`) with an ephemeral salt.
///
/// See [`anthropic`] for salt stability semantics.
pub fn linear() -> Pattern {
    Pattern::Structural(StructuralDef {
        salt: random_salt(),
        ..LINEAR_DEF.clone()
    })
}

/// Returns all built-in structural patterns with ephemeral per-call salts.
///
/// Fakes produced by these patterns are stable within the returned `Vec<Pattern>`
/// instance but differ across calls to `all()` and across process restarts.
/// For persistent cross-restart stability, use `SecretsFile::to_patterns()`.
///
/// Covers: Anthropic API (`sk-ant-api03-`), Anthropic Admin (`sk-ant-admin01-`,
/// `sk-ant-admin03-`), OpenAI classic (`sk-`), OpenAI project (`sk-proj-`),
/// OpenAI service account (`sk-svcacct-`), AWS AKIA/ASIA, GitHub classic/fine-grained,
/// GCP/Gemini (`AIza`), OpenRouter (`sk-or-v1-`), Google OAuth secret (`GOCSPX-`),
/// Slack bot (`xoxb-`), Linear (`lin_api_`).
pub fn all() -> Vec<Pattern> {
    vec![
        anthropic(),
        anthropic_admin01(),
        anthropic_admin03(),
        openai_classic(),
        openai_project(),
        openai_svcacct(),
        aws_akia(),
        aws_asia(),
        github_classic(),
        github_fine_grained(),
        gcp(),
        openrouter(),
        google_oauth_secret(),
        slack_bot(),
        linear(),
    ]
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::segment::Segment;

    #[test]
    fn test_structural_all_classes_present() {
        // INV-22: all built-in classes present in patterns::all()
        let all = all();
        // Verify by probing each pattern's first Literal segment
        let leading_lits: Vec<&[u8]> = all
            .iter()
            .filter_map(|p| match p {
                Pattern::Structural(d) => match d.segments.first()? {
                    Segment::Literal(b) => Some(b.as_slice()),
                    _ => None,
                },
                _ => None,
            })
            .collect();
        for expected in &[
            b"sk-ant-api03-".as_slice(),
            b"sk-ant-admin01-",
            b"sk-ant-admin03-",
            b"sk-",
            b"sk-proj-",
            b"sk-svcacct-",
            b"AKIA",
            b"ASIA",
            b"ghp_",
            b"github_pat_",
            b"AIza",
            b"sk-or-v1-",
            b"GOCSPX-",
            b"xoxb-",
            b"lin_api_",
        ] {
            assert!(
                leading_lits.contains(expected),
                "missing leading literal: {}",
                std::str::from_utf8(expected).unwrap()
            );
        }
    }

    #[test]
    fn test_aws_akia_try_match_returns_capture() {
        let payload = b"access_key: AKIAIOSFODNN7EXAMPLE";
        let akia_pos = payload.windows(4).position(|w| w == b"AKIA").unwrap();
        let cap = AWS_AKIA_DEF.try_match(payload, akia_pos).unwrap();
        assert_eq!(cap.end, akia_pos + 20);
        assert_eq!(cap.variable_lengths, vec![16]);
    }

    #[test]
    fn test_gcp_key_try_match_returns_capture() {
        let payload = b"AIzaSyD-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
        let cap = GCP_DEF.try_match(payload, 0).unwrap();
        assert_eq!(cap.end, 39);
        assert_eq!(cap.variable_lengths, vec![35]);
    }

    #[test]
    fn test_anthropic_suffix_aa_enforced() {
        // AA suffix must appear; pure A payload still works because A+A == "AA"
        let good = b"sk-ant-api03-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
        assert!(ANTHROPIC_DEF.try_match(good, 0).is_some());
        // Payload with wrong suffix (BB) must not match
        let mut bad = good.to_vec();
        let len = bad.len();
        bad[len - 2] = b'B';
        bad[len - 1] = b'B';
        assert!(ANTHROPIC_DEF.try_match(&bad, 0).is_none());
    }

    #[test]
    fn test_openai_project_requires_t3blbkfj() {
        // Must contain T3BlbkFJ at position 8+58 or 8+74
        let good: Vec<u8> = b"sk-proj-"
            .iter()
            .chain(b"B".repeat(58).iter())
            .chain(b"T3BlbkFJ".iter())
            .chain(b"B".repeat(58).iter())
            .copied()
            .collect();
        assert!(OPENAI_PROJECT_DEF.try_match(&good, 0).is_some());

        // Without T3BlbkFJ — should not match
        let bad: Vec<u8> = b"sk-proj-"
            .iter()
            .chain(b"B".repeat(124).iter())
            .copied()
            .collect();
        assert!(OPENAI_PROJECT_DEF.try_match(&bad, 0).is_none());
    }

    #[test]
    fn test_github_fg_requires_underscore_separator() {
        // Must have _ at position 11+22
        let good: Vec<u8> = b"github_pat_"
            .iter()
            .chain(b"A".repeat(22).iter())
            .chain(b"_".iter())
            .chain(b"B".repeat(59).iter())
            .copied()
            .collect();
        assert!(GITHUB_FG_DEF.try_match(&good, 0).is_some());

        // All A's without embedded _ must not match
        let bad: Vec<u8> = b"github_pat_"
            .iter()
            .chain(b"A".repeat(82).iter())
            .copied()
            .collect();
        assert!(GITHUB_FG_DEF.try_match(&bad, 0).is_none());
    }

    #[test]
    fn test_slack_requires_digit_segments() {
        // Valid: digit-digit-alnum
        let good = b"xoxb-1234567890-1234567890-AAAAAAAAAAAAAAAAAAAAAAAA";
        assert!(SLACK_BOT_DEF.try_match(good, 0).is_some());

        // Invalid: letters in digit position
        let bad = b"xoxb-AAAAAAAAAA-AAAAAAAAAA-AAAAAAAAAAAAAAAAAAAAAAAA";
        assert!(SLACK_BOT_DEF.try_match(bad, 0).is_none());
    }

    #[test]
    fn test_prefix_mismatch_returns_none() {
        let payload = b"not-a-key";
        assert!(ANTHROPIC_DEF.try_match(payload, 0).is_none());
    }

    #[test]
    fn test_all_defs_identifiers_unique() {
        let defs = all_defs();
        assert_eq!(defs.len(), 15, "must have 15 built-in structural defs");
        let mut ids: Vec<&str> = defs.iter().map(|d| d.identifier.as_str()).collect();
        ids.sort();
        ids.dedup();
        assert_eq!(ids.len(), 15, "all identifiers must be unique");
    }

    #[test]
    fn test_all_defs_matches_all_patterns() {
        let defs = all_defs();
        let all = all();
        assert_eq!(
            defs.len(),
            all.len(),
            "all_defs and patterns::all must have same count"
        );
        for def in defs {
            assert!(
                all.iter()
                    .any(|p| matches!(p, Pattern::Structural(d) if d.identifier == def.identifier)),
                "all_defs entry {} must appear in patterns::all()",
                def.identifier
            );
        }
    }
}