attackstr 0.2.3

Grammar-based security payload generation - TOML-driven, composable, encoding-aware
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
#![warn(clippy::pedantic)]
#![cfg_attr(
    not(test),
    deny(
        clippy::unwrap_used,
        clippy::expect_used,
        clippy::todo,
        clippy::unimplemented,
        clippy::panic
    )
)]
#![allow(clippy::module_name_repetitions)]
//! # attackstr
//!
//! Grammar-based security payload generation for the Santh ecosystem.
//!
//! Every security tool needs attack payloads  -  `SQLi`, XSS, command injection,
//! SSTI, SSRF, XXE, and more. This crate provides a single, configurable
//! engine that all Santh tools share. Upgrade payloads once, every tool
//! benefits.
//!
//! # Architecture
//!
//! Payloads are defined in TOML grammar files. Each grammar specifies:
//!
//! - **Contexts**: injection points (string break, numeric, attribute, etc.)
//! - **Techniques**: attack patterns with template variables
//! - **Variables**: substitution values (tautologies, commands, etc.)
//! - **Encodings**: transforms applied to final payloads (URL, hex, unicode, etc.)
//!
//! The engine computes the Cartesian product:
//! `contexts × techniques × variable_combos × encodings`
//!
//! # Usage
//!
//! ```rust
//! use attackstr::{PayloadDb, PayloadConfig};
//!
//! let mut db = PayloadDb::with_config(PayloadConfig::default());
//! db.load_toml(r#"
//! [grammar]
//! name = "example"
//! sink_category = "sql-injection"
//!
//! [[techniques]]
//! name = "basic"
//! template = "' OR 1=1 --"
//! "#).unwrap();
//!
//! // Get payloads for a category
//! let sqli = db.payloads("sql-injection");
//! for payload in sqli {
//!     println!("{}", payload.text);
//! }
//!
//! // Get payloads with marker injection for taint tracking
//! let marked = db.payloads_with_marker("xss", "SLN_MARKER_42");
//! ```
//!
//! # Custom Encodings
//!
//! Register custom encoding transforms:
//!
//! ```rust
//! use attackstr::PayloadDb;
//!
//! let mut db = PayloadDb::new();
//! db.register_encoding("rot13", |s| {
//!     s.chars().map(|c| match c {
//!         'a'..='m' | 'A'..='M' => (c as u8 + 13) as char,
//!         'n'..='z' | 'N'..='Z' => (c as u8 - 13) as char,
//!         _ => c,
//!     }).collect()
//! });
//! ```

#![forbid(unsafe_code)]
#![warn(missing_docs)]

/// TOML-configurable settings.
pub mod config;
mod encoding;
pub mod grammar;
mod loader;
mod mutate;
#[cfg(feature = "exploits")]
pub mod ports;
/// Grammar validation.
pub mod validate;

pub use config::{parse_marker_position, PayloadConfigFile};
pub use encoding::{apply_encoding, BuiltinEncoding, CustomEncoder, Encoder, EncodingError};
pub use grammar::{
    depluralize, expand, expand_template, Context, Encoding, Grammar, GrammarMeta, Technique,
    TemplateExpansionError, Variable,
};
pub use loader::PayloadDb;
pub use mutate::{
    mutate_all, mutate_case, mutate_encoding_mix, mutate_html, mutate_null_bytes,
    mutate_sql_comments, mutate_unicode, mutate_whitespace,
};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::hash::{Hash, Hasher};
pub use validate::{validate, GrammarIssue, IssueLevel};

/// A trait for sources that can provide payloads.
///
/// This trait abstracts over different payload storage and generation
/// strategies, allowing users to swap implementations.
///
/// # Thread Safety
/// This trait does not require `Send` or `Sync`. Thread-safety depends on the
/// concrete implementing type.
///
/// # Example
///
/// ```rust
/// use attackstr::{PayloadSource, PayloadDb};
///
/// fn count_payloads(source: &mut dyn PayloadSource) -> usize {
///     source.payload_count()
/// }
/// ```
pub trait PayloadSource {
    /// Get all payloads for a given category.
    ///
    /// The returned slice is cached on subsequent calls for the same category.
    fn payloads(&mut self, category: &str) -> &[Payload];

    /// Get all available category names.
    fn categories(&self) -> Vec<&str>;

    /// Get the total number of payloads across all categories.
    fn payload_count(&self) -> usize;
}

/// A static payload source that holds payloads directly in memory.
///
/// This is useful for users who generate payloads externally and want
/// to use them with the attackstr ecosystem.
///
/// # Thread Safety
/// `StaticPayloads` is `Send` and `Sync`.
///
/// # Example
///
/// ```rust
/// use attackstr::{StaticPayloads, Payload, PayloadSource};
///
/// let payloads = vec![
///     Payload {
///         text: "test".into(),
///         category: "custom".into(),
///         technique: "manual".into(),
///         context: "default".into(),
///         encoding: "raw".into(),
///         cwe: None,
///         severity: None,
///         confidence: 1.0,
///         expected_pattern: None,
///         target_media_type: None,
///     },
/// ];
///
/// let mut source = StaticPayloads::new(payloads);
/// assert_eq!(source.payloads("custom").len(), 1);
/// ```
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct StaticPayloads {
    payloads: Vec<Payload>,
    #[serde(skip)]
    category_ranges: BTreeMap<String, std::ops::Range<usize>>,
}

impl StaticPayloads {
    /// Create a new `StaticPayloads` from a vector of payloads.
    ///
    /// Example:
    /// ```rust
    /// use attackstr::{Payload, StaticPayloads};
    ///
    /// let payloads = vec![Payload {
    ///     text: "alert(1)".into(),
    ///     category: "xss".into(),
    ///     technique: "basic".into(),
    ///     context: "default".into(),
    ///     encoding: "raw".into(),
    ///     cwe: None,
    ///     severity: None,
    ///     confidence: 1.0,
    ///     expected_pattern: None,
    ///     target_media_type: None,
    /// }];
    ///
    /// let source = StaticPayloads::new(payloads);
    /// assert_eq!(source.all_payloads().len(), 1);
    /// ```
    pub fn new(mut payloads: Vec<Payload>) -> Self {
        sort_payloads_by_category(&mut payloads);
        Self {
            category_ranges: build_category_ranges(&payloads),
            payloads,
        }
    }

    /// Add a single payload to this source.
    ///
    /// Example:
    /// ```rust
    /// use attackstr::{Payload, StaticPayloads};
    ///
    /// let mut source = StaticPayloads::default();
    /// source.add(Payload {
    ///     text: "test".into(),
    ///     category: "custom".into(),
    ///     technique: "manual".into(),
    ///     context: "default".into(),
    ///     encoding: "raw".into(),
    ///     cwe: None,
    ///     severity: None,
    ///     confidence: 1.0,
    ///     expected_pattern: None,
    ///     target_media_type: None,
    /// });
    /// assert_eq!(source.all_payloads().len(), 1);
    /// ```
    pub fn add(&mut self, payload: Payload) {
        self.payloads.push(payload);
        sort_payloads_by_category(&mut self.payloads);
        self.category_ranges = build_category_ranges(&self.payloads);
    }

    /// Get all payloads regardless of category.
    ///
    /// Example:
    /// ```rust
    /// use attackstr::StaticPayloads;
    ///
    /// let source = StaticPayloads::default();
    /// assert!(source.all_payloads().is_empty());
    /// ```
    pub fn all_payloads(&self) -> &[Payload] {
        &self.payloads
    }

    /// Iterate over all payloads in this source.
    ///
    /// Example:
    /// ```rust
    /// use attackstr::StaticPayloads;
    ///
    /// let source = StaticPayloads::default();
    /// assert_eq!(source.iter().count(), 0);
    /// ```
    pub fn iter(&self) -> impl Iterator<Item = &Payload> {
        self.payloads.iter()
    }

    /// Iterate over payloads for a single category.
    ///
    /// Example:
    /// ```rust
    /// use attackstr::{Payload, StaticPayloads};
    ///
    /// let source = StaticPayloads::new(vec![Payload {
    ///     text: "alert(1)".into(),
    ///     category: "xss".into(),
    ///     technique: "basic".into(),
    ///     context: "default".into(),
    ///     encoding: "raw".into(),
    ///     cwe: None,
    ///     severity: None,
    ///     confidence: 1.0,
    ///     expected_pattern: None,
    ///     target_media_type: None,
    /// }]);
    /// assert_eq!(source.iter_category("xss").count(), 1);
    /// ```
    pub fn iter_category<'a>(
        &'a self,
        category: &'a str,
    ) -> impl Iterator<Item = &'a Payload> + 'a {
        self.payloads
            .iter()
            .filter(move |payload| payload.category == category)
    }
}

impl std::fmt::Display for StaticPayloads {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "StaticPayloads(count={})", self.payloads.len())
    }
}

impl From<Vec<Payload>> for StaticPayloads {
    fn from(payloads: Vec<Payload>) -> Self {
        Self::new(payloads)
    }
}

impl PayloadSource for StaticPayloads {
    fn payloads(&mut self, category: &str) -> &[Payload] {
        if self.category_ranges.is_empty() && !self.payloads.is_empty() {
            self.category_ranges = build_category_ranges(&self.payloads);
        }
        self.category_ranges
            .get(category)
            .map_or(&[], |range| &self.payloads[range.clone()])
    }

    fn categories(&self) -> Vec<&str> {
        use std::collections::HashSet;
        let mut seen = HashSet::new();
        self.payloads
            .iter()
            .filter_map(|p| {
                if seen.insert(p.category.clone()) {
                    Some(p.category.as_str())
                } else {
                    None
                }
            })
            .collect()
    }

    fn payload_count(&self) -> usize {
        self.payloads.len()
    }
}

fn build_category_ranges(payloads: &[Payload]) -> BTreeMap<String, std::ops::Range<usize>> {
    let mut ranges = BTreeMap::new();
    let mut start = 0;
    while start < payloads.len() {
        let category = payloads[start].category.clone();
        let mut end = start + 1;
        while end < payloads.len() && payloads[end].category == category {
            end += 1;
        }
        ranges.insert(category, start..end);
        start = end;
    }
    ranges
}

/// Configuration for payload generation behavior.
///
/// # Thread Safety
/// `PayloadConfig` is `Send` and `Sync`.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct PayloadConfig {
    /// Maximum payloads per category before truncation (0 = unlimited).
    pub max_per_category: usize,
    /// Whether to deduplicate identical payloads within a category.
    pub deduplicate: bool,
    /// Default marker prefix for taint tracking (e.g. "SLN").
    pub marker_prefix: String,
    /// Categories to exclude from generation (e.g. for compliance).
    pub exclude_categories: Vec<String>,
    /// Categories to include exclusively (empty = all).
    pub include_categories: Vec<String>,
    /// Restrict loaded grammars to one or more runtimes (empty = all).
    pub target_runtime: Option<Vec<String>>,
    /// Where to place the taint marker in generated marker payloads.
    pub marker_position: MarkerPosition,
    /// Maximum length of a single payload in bytes (0 = unlimited).
    pub max_payload_length: usize,
}

impl PayloadConfig {
    /// Create a builder for [`PayloadConfig`].
    ///
    /// Example:
    /// ```rust
    /// use attackstr::PayloadConfig;
    ///
    /// let config = PayloadConfig::builder().marker_prefix("TRACE").build();
    /// assert_eq!(config.marker_prefix, "TRACE");
    /// ```
    pub fn builder() -> PayloadConfigBuilder {
        PayloadConfigBuilder::default()
    }

    /// Load a [`PayloadConfig`] from a TOML file.
    ///
    /// Example:
    /// ```rust
    /// use attackstr::PayloadConfig;
    ///
    /// let dir = tempfile::tempdir().unwrap();
    /// let path = dir.path().join("payloads.toml");
    /// std::fs::write(&path, "marker_prefix = \"TRACE\"\n").unwrap();
    ///
    /// let config = PayloadConfig::load(&path).unwrap();
    /// assert_eq!(config.marker_prefix, "TRACE");
    /// ```
    ///
    /// # Errors
    /// Returns a [`PayloadError`] if reading or parsing the file fails.
    pub fn load<P: AsRef<std::path::Path>>(path: P) -> Result<Self, PayloadError> {
        PayloadConfigFile::load(path)?.into_config()
    }

    /// Parse a [`PayloadConfig`] directly from TOML text.
    ///
    /// Example:
    /// ```rust
    /// use attackstr::{MarkerPosition, PayloadConfig};
    ///
    /// let config = PayloadConfig::from_toml("marker_position = \"suffix\"", "<inline>").unwrap();
    /// assert_eq!(config.marker_position, MarkerPosition::Suffix);
    /// ```
    ///
    /// # Errors
    /// Returns a [`PayloadError`] if parsing the TOML fails.
    pub fn from_toml(toml_str: &str, source: impl Into<String>) -> Result<Self, PayloadError> {
        PayloadConfigFile::from_toml(toml_str, source.into())?.into_config()
    }
}

impl std::fmt::Display for PayloadConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "PayloadConfig(max_per_category={}, deduplicate={}, marker_position={})",
            self.max_per_category, self.deduplicate, self.marker_position
        )
    }
}

impl Default for PayloadConfig {
    fn default() -> Self {
        Self {
            max_per_category: 0,
            deduplicate: true,
            marker_prefix: "SLN".into(),
            exclude_categories: Vec::new(),
            include_categories: Vec::new(),
            target_runtime: None,
            marker_position: MarkerPosition::Prefix,
            max_payload_length: 100_000,
        }
    }
}

/// Placement strategy for marker-injected payloads.
///
/// # Thread Safety
/// `MarkerPosition` is `Send` and `Sync`.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[non_exhaustive]
pub enum MarkerPosition {
    /// Prepend the marker to the payload text.
    Prefix,
    /// Append the marker to the payload text.
    Suffix,
    /// Wrap the marker in braces and prepend it inline.
    Inline,
    /// Replace `{MARKER}` placeholders in the payload text.
    Replace(String),
}

impl std::fmt::Display for MarkerPosition {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Prefix => f.write_str("prefix"),
            Self::Suffix => f.write_str("suffix"),
            Self::Inline => f.write_str("inline"),
            Self::Replace(value) => write!(f, "replace:{value}"),
        }
    }
}

/// Builder for [`PayloadConfig`].
///
/// # Thread Safety
/// `PayloadConfigBuilder` is `Send` and `Sync`.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
pub struct PayloadConfigBuilder {
    config: PayloadConfig,
}

impl std::fmt::Display for PayloadConfigBuilder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "PayloadConfigBuilder({})", self.config)
    }
}

impl PayloadConfigBuilder {
    /// Set the maximum payload count per category.
    pub fn max_per_category(mut self, max_per_category: usize) -> Self {
        self.config.max_per_category = max_per_category;
        self
    }

    /// Set whether identical payloads should be deduplicated.
    pub fn deduplicate(mut self, deduplicate: bool) -> Self {
        self.config.deduplicate = deduplicate;
        self
    }

    /// Set the marker prefix.
    pub fn marker_prefix(mut self, marker_prefix: impl Into<String>) -> Self {
        self.config.marker_prefix = marker_prefix.into();
        self
    }

    /// Set the categories to exclude.
    pub fn exclude_categories(mut self, exclude_categories: Vec<String>) -> Self {
        self.config.exclude_categories = exclude_categories;
        self
    }

    /// Set the categories to include.
    pub fn include_categories(mut self, include_categories: Vec<String>) -> Self {
        self.config.include_categories = include_categories;
        self
    }

    /// Set the allowed target runtimes.
    pub fn target_runtime(mut self, target_runtime: Option<Vec<String>>) -> Self {
        self.config.target_runtime = target_runtime;
        self
    }

    /// Set the marker placement strategy.
    pub fn marker_position(mut self, marker_position: MarkerPosition) -> Self {
        self.config.marker_position = marker_position;
        self
    }

    /// Set the maximum length of a single payload in bytes.
    pub fn max_payload_length(mut self, max_payload_length: usize) -> Self {
        self.config.max_payload_length = max_payload_length;
        self
    }

    /// Build the final [`PayloadConfig`].
    ///
    /// Example:
    /// ```rust
    /// use attackstr::PayloadConfig;
    ///
    /// let config = PayloadConfig::builder().max_per_category(10).build();
    /// assert_eq!(config.max_per_category, 10);
    /// ```
    pub fn build(self) -> PayloadConfig {
        self.config
    }
}

fn sort_payloads_by_category(payloads: &mut [Payload]) {
    payloads.sort_by(|left, right| {
        left.category
            .cmp(&right.category)
            .then_with(|| left.technique.cmp(&right.technique))
            .then_with(|| left.context.cmp(&right.context))
            .then_with(|| left.encoding.cmp(&right.encoding))
            .then_with(|| left.text.cmp(&right.text))
    });
}

/// A generated payload with metadata about its origin.
///
/// # Thread Safety
/// `Payload` is `Send` and `Sync`.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Payload {
    /// The payload string.
    pub text: String,
    /// Which category this payload targets (e.g. "sql-injection").
    pub category: String,
    /// Which technique generated it (e.g. "union-based").
    pub technique: String,
    /// Which context it was generated in (e.g. "string-break").
    pub context: String,
    /// Which encoding was applied (e.g. "`url_encode`").
    pub encoding: String,
    /// Optional CWE identifier inherited from the grammar.
    pub cwe: Option<String>,
    /// Optional severity hint inherited from the grammar.
    pub severity: Option<String>,
    /// Confidence score for this payload variant.
    pub confidence: f64,
    /// Optional regex pattern expected in the observed response.
    pub expected_pattern: Option<String>,
    /// Target media type for correct downstream escaping.
    #[serde(default)]
    pub target_media_type: Option<String>,
}

impl PartialEq for Payload {
    fn eq(&self, other: &Self) -> bool {
        self.text == other.text
            && self.category == other.category
            && self.technique == other.technique
            && self.context == other.context
            && self.encoding == other.encoding
            && self.cwe == other.cwe
            && self.severity == other.severity
            && self.confidence.to_bits() == other.confidence.to_bits()
            && self.expected_pattern == other.expected_pattern
            && self.target_media_type == other.target_media_type
    }
}

impl Default for Payload {
    fn default() -> Self {
        Self {
            text: String::new(),
            category: String::new(),
            technique: String::new(),
            context: String::new(),
            encoding: "raw".to_string(),
            cwe: None,
            severity: None,
            confidence: 1.0,
            expected_pattern: None,
            target_media_type: None,
        }
    }
}

impl Eq for Payload {}

impl Hash for Payload {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.text.hash(state);
        self.category.hash(state);
        self.technique.hash(state);
        self.context.hash(state);
        self.encoding.hash(state);
        self.cwe.hash(state);
        self.severity.hash(state);
        self.confidence.to_bits().hash(state);
        self.expected_pattern.hash(state);
        self.target_media_type.hash(state);
    }
}

impl std::fmt::Display for Payload {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}:{}:{}:{}",
            self.category, self.technique, self.context, self.text
        )
    }
}

/// Errors from payload operations.
///
/// # Thread Safety
/// `PayloadError` is `Send` and `Sync`.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum PayloadError {
    /// Failed to read a file.
    #[error("{0}. Fix: verify the file or directory exists and that the current process has permission to read it.")]
    Io(#[from] std::io::Error),
    /// Failed to parse TOML configuration.
    #[error("{message}", message = Self::config_parse_message(file, source))]
    ConfigParse {
        /// Which config file failed.
        file: String,
        /// The parse error.
        source: Box<toml::de::Error>,
    },
    /// Failed to parse TOML grammar.
    #[error("{message}", message = Self::grammar_parse_message(file, source))]
    GrammarParse {
        /// Which file failed.
        file: String,
        /// The parse error.
        source: Box<toml::de::Error>,
    },
    /// Grammar parsed but failed semantic validation.
    #[error("{message}", message = Self::grammar_validation_message(file, issues))]
    GrammarValidation {
        /// Which file failed.
        file: String,
        /// Structured validation issues collected for the grammar.
        issues: Vec<GrammarIssue>,
    },
    /// Failed to expand template placeholders in a grammar.
    #[error("{message}", message = Self::template_expansion_message(file, source))]
    TemplateExpansion {
        /// Which file failed.
        file: String,
        /// The expansion error.
        source: TemplateExpansionError,
    },
    /// Path is not a directory.
    #[error("path '{0}' is not a directory. Fix: pass a directory that contains `.toml` grammar files or update `grammar_dirs` in your config.")]
    NotADirectory(String),
    /// Another directory load is already in progress for this database instance.
    #[error("payload database load is already in progress. Fix: wait for the current `load_dir` call to finish before starting another one on the same `PayloadDb`.")]
    ConcurrentLoad,
    /// Invalid configuration value encountered during conversion.
    #[error("invalid configuration value: {0}. Fix: check your config file against the supported options.")]
    InvalidConfig(String),
}

impl Serialize for PayloadError {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        use serde::ser::SerializeMap;

        let mut map = serializer.serialize_map(Some(2))?;
        map.serialize_entry("kind", self.kind())?;
        map.serialize_entry("message", &self.to_string())?;
        map.end()
    }
}

impl<'de> Deserialize<'de> for PayloadError {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct PayloadErrorWire {
            kind: String,
            message: String,
        }

        let wire = PayloadErrorWire::deserialize(deserializer)?;
        Ok(Self::Io(std::io::Error::other(format!(
            "[{}] {}",
            wire.kind, wire.message
        ))))
    }
}

impl PayloadError {
    fn kind(&self) -> &'static str {
        match self {
            Self::Io(_) => "io",
            Self::ConfigParse { .. } => "config_parse",
            Self::GrammarParse { .. } => "grammar_parse",
            Self::GrammarValidation { .. } => "grammar_validation",
            Self::TemplateExpansion { .. } => "template_expansion",
            Self::NotADirectory(_) => "not_a_directory",
            Self::ConcurrentLoad => "concurrent_load",
            Self::InvalidConfig(_) => "invalid_config",
        }
    }

    fn config_parse_message(file: &str, source: &toml::de::Error) -> String {
        format!(
            "config parse error in {file}: {source}. Fix: make the file valid TOML and keep payload settings at the top level, for example `max_per_category = 100` and `grammar_dirs = [\"./grammars\"]`."
        )
    }

    fn grammar_parse_message(file: &str, source: &toml::de::Error) -> String {
        let detail = source.to_string();
        let fix = if detail.contains("missing field `grammar`") {
            "Fix: add a `[grammar]` table with at least `name` and `sink_category`."
        } else if detail.contains("missing field `name`")
            || detail.contains("missing field `sink_category`")
        {
            "Fix: every grammar needs a `[grammar]` section with both `name` and `sink_category` fields."
        } else if detail.contains("missing field `template`") {
            "Fix: every `[[techniques]]` entry needs a `name` and `template`."
        } else {
            "Fix: make the file valid TOML and include a `[grammar]` section plus at least one `[[techniques]]` entry."
        };

        format!("grammar parse error in {file}: {detail}. {fix}")
    }

    fn template_expansion_message(file: &str, source: &TemplateExpansionError) -> String {
        let fix = match source {
            TemplateExpansionError::UnclosedBrace { .. } => {
                "Fix: close every `{placeholder}` with a matching `}` and escape literal braces by leaving them outside placeholder syntax."
            }
            TemplateExpansionError::RecursionLimitExceeded { max_depth } => {
                return format!(
                    "template expansion error in {file}: {source}. Fix: remove circular or self-referential variables so expansion stays below the recursion limit of {max_depth}."
                );
            }
            TemplateExpansionError::PayloadLimitExceeded { limit } => {
                return format!(
                    "template expansion error in {file}: {source}. Fix: reduce Cartesian product size (contexts x techniques x variables) to stay below the {limit} limit."
                );
            }
            TemplateExpansionError::ExpansionLengthExceeded { max_len } => {
                return format!(
                    "template expansion error in {file}: {source}. Fix: remove exponential variable growth so expansion stays below {max_len} bytes."
                );
            }
            TemplateExpansionError::UnknownEncoding { transform } => {
                return format!(
                    "template expansion error in {file}: {source}. Fix: register `{transform}` via `PayloadDb::register_encoding`, or replace the reference with a known built-in (raw, url_encode, html_encode, double_url_encode, hex_encode, unicode_escape, base64)."
                );
            }
        };

        format!("template expansion error in {file}: {source}. {fix}")
    }

    fn grammar_validation_message(file: &str, issues: &[GrammarIssue]) -> String {
        let issue_count = issues.len();
        let summary = issues.first().map_or_else(
            || "unknown validation failure".to_string(),
            |issue| format!("{}: {}", issue.level, issue.message),
        );
        format!(
            "grammar validation error in {file}: {summary}. Fix: resolve the reported validation issue{plural} before loading the grammar.",
            plural = if issue_count == 1 { "" } else { "s" }
        )
    }
}

// The README's Rust examples are collected as doctests, so the quick-start
// can never drift from the API (contract rung: README compiles and runs).
#[doc = include_str!("../README.md")]
mod readme_doctests {}