adotenv-lint 0.3.2

Opt-in lint rules, schema checks and verified fixes for adotenv documents.
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
848
849
850
851
852
//! Opt-in schema and `.env.example` presence-and-shape policies.
//!
//! A [`Schema`] declares which keys a `.env` document should contain, whether
//! undeclared keys or empty values are allowed, and what literal shape each
//! key's value must match. Shape checks run strictly on decoded literal values
//! (`Entry::value`), never by expanding variable references or reading the
//! process environment, and emitted [`Finding`]s never contain document values.
//!
//! ```
//! use adotenv_lint::{lint_with_schema, KeySchema, LintOptions, Rule, Schema, ValueShape};
//!
//! let example = adotenv::parse_strict("HOST=localhost\nPORT=8080\n").unwrap();
//! let schema = Schema::from_example(&example)
//!     .with_allow_unknown(false)
//!     .with_key("PORT", KeySchema::new().with_shape(ValueShape::Port));
//!
//! let doc = adotenv::parse_strict("HOST=localhost\nPORT=not-a-port\nEXTRA=1\n").unwrap();
//! let findings = lint_with_schema(&doc, LintOptions::default(), &schema);
//! assert_eq!(findings.len(), 2);
//! assert_eq!(findings[0].rule(), Rule::InvalidValue);
//! assert_eq!(findings[1].rule(), Rule::UnknownKey);
//! ```

use std::collections::BTreeMap;

use adotenv::{AssignmentState, Document, Duplicates, Entry};

use crate::{Finding, LintOptions, Rule};

/// Expected literal value shape for one key in a [`Schema`].
///
/// Checks operate on decoded literal values (`Entry::value`), never by
/// expanding `$VAR` references or inspecting the process environment.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub enum ValueShape {
    /// Any literal value is accepted.
    #[default]
    Any,
    /// Exactly `"true"` or `"false"`, matching `adotenv`'s Serde `bool` rule.
    Bool,
    /// Signed 64-bit base-10 integer accepted by `i64::from_str`.
    Integer,
    /// Unsigned 64-bit base-10 integer of ASCII digits (no leading `+`).
    UnsignedInteger,
    /// TCP/UDP port number in `1..=65535` (ASCII digits, no leading `+`).
    Port,
    /// Finite base-10 floating-point number accepted by `f64::from_str`.
    Float,
    /// URL with an RFC 3986 scheme, `://`, non-empty host, optional `u16` port,
    /// and no ASCII whitespace or control characters.
    Url,
    /// Exact membership in an explicit list of allowed values.
    OneOf(Vec<String>),
}

impl ValueShape {
    /// Returns `true` when `value` satisfies this shape.
    #[must_use]
    pub fn matches(&self, value: &str) -> bool {
        match self {
            Self::Any => true,
            Self::Bool => matches!(value, "true" | "false"),
            Self::Integer => value.parse::<i64>().is_ok(),
            Self::UnsignedInteger => !value.starts_with('+') && value.parse::<u64>().is_ok(),
            Self::Port => {
                !value.starts_with('+') && value.parse::<u16>().is_ok_and(|port| port > 0)
            }
            Self::Float => value.parse::<f64>().is_ok_and(f64::is_finite),
            Self::Url => is_valid_url(value),
            Self::OneOf(allowed) => allowed.iter().any(|candidate| candidate == value),
        }
    }

    pub(crate) fn mismatch_message(&self) -> &'static str {
        match self {
            Self::Any => "value does not match the configured shape",
            Self::Bool => "value is not a valid boolean (expected true or false)",
            Self::Integer => "value is not a valid integer",
            Self::UnsignedInteger => "value is not a valid unsigned integer",
            Self::Port => "value is not a valid port (1-65535)",
            Self::Float => "value is not a valid finite number",
            Self::Url => "value is not a valid URL",
            Self::OneOf(_) => "value is not in the allowed set",
        }
    }
}

/// Policy for one key declared in a [`Schema`].
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct KeySchema {
    /// Whether the key must be declared in the document.
    pub required: bool,
    /// Per-key override for empty values (`KEY=` or `KEY=""`).
    ///
    /// When `None`, keys with [`ValueShape::Any`] inherit
    /// [`Schema::allow_empty`], while keys with a stricter [`ValueShape`]
    /// disallow empty values unless explicitly set to `Some(true)`.
    pub allow_empty: Option<bool>,
    /// Whether a bare declaration without `=` (such as `KEY`) is accepted.
    pub allow_bare: bool,
    /// Expected shape for non-empty literal values.
    pub shape: ValueShape,
}

impl Default for KeySchema {
    fn default() -> Self {
        Self::new()
    }
}

impl KeySchema {
    /// Creates a required key policy that inherits empty-value defaults and
    /// rejects bare declarations without `=`.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            required: true,
            allow_empty: None,
            allow_bare: false,
            shape: ValueShape::Any,
        }
    }

    /// Creates an optional key policy (`required = false`).
    #[must_use]
    pub const fn optional() -> Self {
        Self {
            required: false,
            allow_empty: None,
            allow_bare: false,
            shape: ValueShape::Any,
        }
    }

    /// Sets whether this key must be present in the document.
    #[must_use]
    pub const fn with_required(mut self, required: bool) -> Self {
        self.required = required;
        self
    }

    /// Explicitly allows or disallows empty values (`KEY=` or `KEY=""`) for
    /// this key, overriding [`Schema::allow_empty`] and typed-shape defaults.
    #[must_use]
    pub const fn with_allow_empty(mut self, allow_empty: bool) -> Self {
        self.allow_empty = Some(allow_empty);
        self
    }

    /// Sets whether a bare declaration without `=` is accepted for this key.
    #[must_use]
    pub const fn with_allow_bare(mut self, allow_bare: bool) -> Self {
        self.allow_bare = allow_bare;
        self
    }

    /// Sets the expected [`ValueShape`] for non-empty values of this key.
    #[must_use]
    pub fn with_shape(mut self, shape: ValueShape) -> Self {
        self.shape = shape;
        self
    }

    pub(crate) fn effective_allow_empty(&self, schema_default: bool) -> bool {
        match self.allow_empty {
            Some(explicit) => explicit,
            None => match &self.shape {
                ValueShape::Any => schema_default,
                ValueShape::OneOf(allowed) => allowed.iter().any(String::is_empty),
                _ => false,
            },
        }
    }
}

/// Presence and value-shape policy for a `.env` document.
///
/// Build a schema directly with [`Schema::new`] and [`Schema::with_key`], or
/// derive one from a parsed `.env.example` document with
/// [`Schema::from_example`].
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Schema {
    /// Per-key policies indexed by literal key name.
    pub keys: BTreeMap<String, KeySchema>,
    /// Whether declarations whose keys are absent from [`keys`](Self::keys)
    /// are permitted. Defaults to `true`.
    pub allow_unknown: bool,
    /// Default policy for empty values (`KEY=` or `KEY=""`) on keys with
    /// [`ValueShape::Any`] and on allowed unknown keys. Defaults to `true`.
    pub allow_empty: bool,
}

impl Default for Schema {
    fn default() -> Self {
        Self::new()
    }
}

impl Schema {
    /// Creates an empty, permissive schema (`allow_unknown = true`,
    /// `allow_empty = true`).
    #[must_use]
    pub fn new() -> Self {
        Self {
            keys: BTreeMap::new(),
            allow_unknown: true,
            allow_empty: true,
        }
    }

    /// Derives a schema from a parsed `.env.example` document.
    ///
    /// Every unique non-empty key declared in `example` (including bare keys in
    /// dialects with `BareKeys::Ignore` and non-lookup keys such as Node
    /// `__proto__`) becomes a required key with [`ValueShape::Any`]. Keys whose
    /// effective declaration is bare allow bare declarations
    /// (`allow_bare = true`), so `example` always validates cleanly against its
    /// own derived schema across every dialect.
    #[must_use]
    pub fn from_example(example: &Document<'_>) -> Self {
        let winners = effective_entries(example);
        let mut keys = BTreeMap::new();
        for (key, winner) in winners {
            keys.insert(
                key.to_owned(),
                KeySchema::new().with_allow_bare(winner.state() == AssignmentState::Bare),
            );
        }
        Self {
            keys,
            allow_unknown: true,
            allow_empty: true,
        }
    }

    /// Inserts or replaces the policy for `key`.
    #[must_use]
    pub fn with_key(mut self, key: impl Into<String>, policy: KeySchema) -> Self {
        self.keys.insert(key.into(), policy);
        self
    }

    /// Sets whether keys not declared in [`keys`](Self::keys) are allowed.
    #[must_use]
    pub const fn with_allow_unknown(mut self, allow_unknown: bool) -> Self {
        self.allow_unknown = allow_unknown;
        self
    }

    /// Sets the default policy for empty values on untyped and allowed unknown
    /// keys.
    #[must_use]
    pub const fn with_allow_empty(mut self, allow_empty: bool) -> Self {
        self.allow_empty = allow_empty;
        self
    }
}

fn effective_entries<'doc>(document: &'doc Document<'doc>) -> BTreeMap<&'doc str, Entry<'doc>> {
    let lookup = document.lookup_index();
    let first_wins = document.dialect().duplicates == Duplicates::First;
    let mut winners: BTreeMap<&'doc str, Entry<'doc>> = BTreeMap::new();
    for entry in document.entries() {
        let key = entry.key();
        if key.is_empty() {
            continue;
        }
        if let Some(lookup_winner) = lookup.get_entry(key) {
            winners.entry(key).or_insert(lookup_winner);
        } else if first_wins {
            winners.entry(key).or_insert(entry);
        } else {
            winners.insert(key, entry);
        }
    }
    winners
}

pub(crate) fn schema_findings(
    document: &Document<'_>,
    options: LintOptions,
    schema: &Schema,
    findings: &mut Vec<Finding>,
) {
    let winners = effective_entries(document);
    declared_schema_findings(document, &winners, options, schema, findings);
    undeclared_schema_findings(document, &winners, options, schema, findings);
}

fn declared_schema_findings(
    document: &Document<'_>,
    winners: &BTreeMap<&str, Entry<'_>>,
    options: LintOptions,
    schema: &Schema,
    findings: &mut Vec<Finding>,
) {
    let doc_start = document.bom_span().map_or(0, |span| span.end);

    for (key, spec) in &schema.keys {
        let winner = if key.is_empty() {
            document.get_entry(key)
        } else {
            winners.get(key.as_str()).copied()
        };
        let Some(entry) = winner else {
            if spec.required && options.missing_keys {
                findings.push(Finding::new(
                    Rule::MissingKey,
                    "required key is missing",
                    options.severity_for_rule(Rule::MissingKey),
                    doc_start..doc_start,
                    1,
                    Some(key),
                    None,
                ));
            }
            continue;
        };

        if entry.state() == AssignmentState::Bare {
            if !spec.allow_bare && options.empty_values {
                findings.push(Finding::new(
                    Rule::EmptyValue,
                    "bare key has no value",
                    options.severity_for_rule(Rule::EmptyValue),
                    entry.key_span(),
                    entry.line(),
                    Some(entry.key()),
                    None,
                ));
            }
            continue;
        }

        let Some(value) = entry.value() else {
            continue;
        };
        if value.is_empty() {
            if !spec.effective_allow_empty(schema.allow_empty) && options.empty_values {
                findings.push(Finding::new(
                    Rule::EmptyValue,
                    "key has an empty value",
                    options.severity_for_rule(Rule::EmptyValue),
                    entry.value_span().unwrap_or_else(|| entry.key_span()),
                    entry.line(),
                    Some(entry.key()),
                    None,
                ));
            }
            continue;
        }

        if options.invalid_values && !spec.shape.matches(value) {
            findings.push(Finding::new(
                Rule::InvalidValue,
                spec.shape.mismatch_message(),
                options.severity_for_rule(Rule::InvalidValue),
                entry.value_span().unwrap_or_else(|| entry.key_span()),
                entry.line(),
                Some(entry.key()),
                None,
            ));
        }
    }
}

fn undeclared_schema_findings(
    document: &Document<'_>,
    winners: &BTreeMap<&str, Entry<'_>>,
    options: LintOptions,
    schema: &Schema,
    findings: &mut Vec<Finding>,
) {
    for entry in document.entries() {
        let key = entry.key();
        if key.is_empty() || schema.keys.contains_key(key) {
            continue;
        }
        if !schema.allow_unknown && options.unknown_keys {
            findings.push(Finding::new(
                Rule::UnknownKey,
                "key is not declared in the schema",
                options.severity_for_rule(Rule::UnknownKey),
                entry.key_span(),
                entry.line(),
                Some(key),
                None,
            ));
            continue;
        }
        if !schema.allow_empty
            && options.empty_values
            && winners
                .get(key)
                .is_some_and(|winner| winner.id() == entry.id())
        {
            if entry.state() == AssignmentState::Bare {
                findings.push(Finding::new(
                    Rule::EmptyValue,
                    "bare key has no value",
                    options.severity_for_rule(Rule::EmptyValue),
                    entry.key_span(),
                    entry.line(),
                    Some(key),
                    None,
                ));
            } else if entry.value() == Some("") {
                findings.push(Finding::new(
                    Rule::EmptyValue,
                    "key has an empty value",
                    options.severity_for_rule(Rule::EmptyValue),
                    entry.value_span().unwrap_or_else(|| entry.key_span()),
                    entry.line(),
                    Some(key),
                    None,
                ));
            }
        }
    }
}

fn is_valid_url(value: &str) -> bool {
    if value.is_empty() || value.bytes().any(|b| b <= 0x20 || b == 0x7f) {
        return false;
    }
    let Some((scheme, rest)) = value.split_once("://") else {
        return false;
    };
    let scheme_bytes = scheme.as_bytes();
    if scheme_bytes.is_empty()
        || !scheme_bytes[0].is_ascii_alphabetic()
        || !scheme_bytes[1..]
            .iter()
            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'-' | b'.'))
    {
        return false;
    }
    let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
    let authority = &rest[..authority_end];
    let hostport = authority
        .rsplit_once('@')
        .map_or(authority, |(_, right)| right);
    if hostport.is_empty() {
        return false;
    }
    if let Some(bracketed) = hostport.strip_prefix('[') {
        let Some((inside, after)) = bracketed.split_once(']') else {
            return false;
        };
        if inside.is_empty() || inside.contains('[') {
            return false;
        }
        if after.is_empty() {
            return true;
        }
        return after.strip_prefix(':').is_some_and(is_valid_url_port);
    }
    if hostport.contains(['[', ']']) {
        return false;
    }
    if let Some((host, port)) = hostport.split_once(':') {
        !host.is_empty() && is_valid_url_port(port)
    } else {
        true
    }
}

fn is_valid_url_port(port: &str) -> bool {
    !port.is_empty() && !port.starts_with('+') && port.parse::<u16>().is_ok()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{lint_with_schema, LintOptions};
    use adotenv::{parse_strict, parse_strict_with, Dialect, Duplicates, Severity};

    #[test]
    fn value_shapes_validate_exact_boundaries() {
        assert!(ValueShape::Any.matches(""));
        assert!(ValueShape::Any.matches("anything"));

        assert!(ValueShape::Bool.matches("true"));
        assert!(ValueShape::Bool.matches("false"));
        assert!(!ValueShape::Bool.matches("True"));
        assert!(!ValueShape::Bool.matches("1"));
        assert!(!ValueShape::Bool.matches(""));

        assert!(ValueShape::Integer.matches("0"));
        assert!(ValueShape::Integer.matches("-42"));
        assert!(ValueShape::Integer.matches("9223372036854775807"));
        assert!(!ValueShape::Integer.matches("9223372036854775808"));
        assert!(!ValueShape::Integer.matches("1.5"));

        assert!(ValueShape::UnsignedInteger.matches("0"));
        assert!(ValueShape::UnsignedInteger.matches("18446744073709551615"));
        assert!(!ValueShape::UnsignedInteger.matches("-1"));
        assert!(!ValueShape::UnsignedInteger.matches("+1"));

        assert!(ValueShape::Port.matches("1"));
        assert!(ValueShape::Port.matches("8080"));
        assert!(ValueShape::Port.matches("65535"));
        assert!(!ValueShape::Port.matches("0"));
        assert!(!ValueShape::Port.matches("+80"));
        assert!(!ValueShape::Port.matches("65536"));
        assert!(!ValueShape::Port.matches("-80"));

        assert!(ValueShape::Float.matches("0"));
        assert!(ValueShape::Float.matches("-3.14"));
        assert!(ValueShape::Float.matches("1e-5"));
        assert!(!ValueShape::Float.matches("NaN"));
        assert!(!ValueShape::Float.matches("inf"));
        assert!(!ValueShape::Float.matches("-infinity"));
        assert!(!ValueShape::Float.matches("abc"));

        assert!(ValueShape::Url.matches("https://example.com"));
        assert!(ValueShape::Url.matches("http+unix://localhost:8080/health?ok=1#top"));
        assert!(ValueShape::Url.matches("postgres://u:p@ss@db.internal:5432/app"));
        assert!(ValueShape::Url.matches("http://[::1]:8080/api"));
        assert!(ValueShape::Url.matches("http://[::1]/api"));
        assert!(ValueShape::Url.matches("custom-1.0://host:0"));
        assert!(!ValueShape::Url.matches(""));
        assert!(!ValueShape::Url.matches("not-a-url"));
        assert!(!ValueShape::Url.matches("://example.com"));
        assert!(!ValueShape::Url.matches("1http://example.com"));
        assert!(!ValueShape::Url.matches("ht_tp://example.com"));
        assert!(!ValueShape::Url.matches("https://"));
        assert!(!ValueShape::Url.matches("https://user@"));
        assert!(!ValueShape::Url.matches("https://example.com:99999"));
        assert!(!ValueShape::Url.matches("https://example.com:+80"));
        assert!(!ValueShape::Url.matches("https://example.com:"));
        assert!(!ValueShape::Url.matches("https://:8080"));
        assert!(!ValueShape::Url.matches("https://example.com/a b"));
        assert!(!ValueShape::Url.matches("https://example.com/\x7f"));
        assert!(!ValueShape::Url.matches("http://[]"));
        assert!(!ValueShape::Url.matches("http://[::1"));
        assert!(!ValueShape::Url.matches("http://[[::1]]"));
        assert!(!ValueShape::Url.matches("http://[::1]extra"));
        assert!(!ValueShape::Url.matches("http://[::1]:99999"));
        assert!(!ValueShape::Url.matches("http://bad[host]"));
        assert!(!ValueShape::Url.matches("http://bad]host"));

        let env_shape = ValueShape::OneOf(vec!["dev".to_owned(), "prod".to_owned()]);
        assert!(env_shape.matches("dev"));
        assert!(env_shape.matches("prod"));
        assert!(!env_shape.matches("staging"));
    }

    #[test]
    fn example_validates_against_itself_including_empty_and_bare_keys() {
        let example = parse_strict("HOST=localhost\nSECRET=\nINHERITED\n").unwrap();
        let schema = Schema::from_example(&example).with_allow_unknown(false);
        let findings = lint_with_schema(
            &example,
            LintOptions::new().with_duplicate_keys(false),
            &schema,
        );
        assert_eq!(findings, Vec::new());
    }

    #[test]
    fn schema_reports_missing_unknown_empty_bare_and_invalid_without_leaking_values() {
        let schema = Schema::new()
            .with_allow_unknown(false)
            .with_allow_empty(false)
            .with_key("HOST", KeySchema::new())
            .with_key("PORT", KeySchema::new().with_shape(ValueShape::Port))
            .with_key("DEBUG", KeySchema::optional().with_shape(ValueShape::Bool))
            .with_key(
                "OPT_EMPTY",
                KeySchema::optional()
                    .with_allow_empty(true)
                    .with_shape(ValueShape::Port),
            )
            .with_key("API_KEY", KeySchema::new())
            .with_key("BARE_OK", KeySchema::new().with_allow_bare(true))
            .with_key("BARE_BAD", KeySchema::new());

        let doc = parse_strict(
            "\u{feff}PORT=super-secret-bad-port\nOPT_EMPTY=\nAPI_KEY=\nBARE_OK\nBARE_BAD\nEXTRA=top-secret-extra\n",
        )
        .unwrap();
        let opts = LintOptions::new()
            .with_duplicate_keys(false)
            .with_severity(Rule::MissingKey, Severity::Error)
            .with_severity(Rule::UnknownKey, Severity::Error)
            .with_severity(Rule::EmptyValue, Severity::Info)
            .with_severity(Rule::InvalidValue, Severity::Error);
        let findings = lint_with_schema(&doc, opts, &schema);

        let summary: Vec<_> = findings
            .iter()
            .map(|f| (f.rule(), f.key(), f.severity(), f.line(), f.span()))
            .collect();
        assert_eq!(
            summary,
            vec![
                (Rule::MissingKey, Some("HOST"), Severity::Error, 1, 3..3),
                (Rule::InvalidValue, Some("PORT"), Severity::Error, 1, 8..29),
                (Rule::EmptyValue, Some("API_KEY"), Severity::Info, 3, 49..49),
                (
                    Rule::EmptyValue,
                    Some("BARE_BAD"),
                    Severity::Info,
                    5,
                    58..66
                ),
                (Rule::UnknownKey, Some("EXTRA"), Severity::Error, 6, 67..72),
            ]
        );
        let debug = format!("{findings:?}");
        assert!(!debug.contains("super-secret-bad-port"), "{debug}");
        assert!(!debug.contains("top-secret-extra"), "{debug}");
    }

    #[test]
    fn schema_respects_dialect_duplicate_winners_and_per_rule_toggles() {
        let schema = Schema::new()
            .with_allow_unknown(false)
            .with_key("PORT", KeySchema::new().with_shape(ValueShape::Port))
            .with_key("REQUIRED", KeySchema::new());

        // Portable: last wins -> PORT=8080 is valid.
        let portable = parse_strict("PORT=bad\nPORT=8080\nREQUIRED=\nEXTRA=1\n").unwrap();
        let findings = lint_with_schema(
            &portable,
            LintOptions::new().with_duplicate_keys(false),
            &schema,
        );
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].rule(), Rule::UnknownKey);

        // First-wins dialect: first declaration wins -> PORT=bad is invalid.
        let first_wins = Dialect::PORTABLE.with_duplicates(Duplicates::First);
        let first_doc = parse_strict_with("PORT=bad\nPORT=8080\nREQUIRED=\n", first_wins).unwrap();
        let first_findings = lint_with_schema(
            &first_doc,
            LintOptions::new().with_duplicate_keys(false),
            &schema,
        );
        assert_eq!(first_findings.len(), 1);
        assert_eq!(first_findings[0].rule(), Rule::InvalidValue);
        assert_eq!(first_findings[0].line(), 1);
        assert_eq!(
            first_findings[0].message(),
            "value is not a valid port (1-65535)"
        );

        // Disabling each rule suppresses only that rule.
        let suppressed = lint_with_schema(
            &portable,
            LintOptions::new()
                .with_duplicate_keys(false)
                .with_unknown_keys(false)
                .with_missing_keys(false)
                .with_empty_values(false)
                .with_invalid_values(false),
            &schema,
        );
        assert_eq!(suppressed, Vec::new());

        // Verify all shape mismatch messages are distinct and non-empty.
        assert_eq!(
            ValueShape::Any.mismatch_message(),
            "value does not match the configured shape"
        );
        assert_eq!(
            ValueShape::Bool.mismatch_message(),
            "value is not a valid boolean (expected true or false)"
        );
        assert_eq!(
            ValueShape::Integer.mismatch_message(),
            "value is not a valid integer"
        );
        assert_eq!(
            ValueShape::UnsignedInteger.mismatch_message(),
            "value is not a valid unsigned integer"
        );
        assert_eq!(
            ValueShape::Float.mismatch_message(),
            "value is not a valid finite number"
        );
        assert_eq!(
            ValueShape::Url.mismatch_message(),
            "value is not a valid URL"
        );
        assert_eq!(
            ValueShape::OneOf(vec!["a".to_owned()]).mismatch_message(),
            "value is not in the allowed set"
        );

        // Verify Default and builder constructors + from_example with duplicate keys.
        assert_eq!(Schema::default(), Schema::new());
        assert_eq!(KeySchema::default(), KeySchema::new());
        assert!(!KeySchema::new().with_required(false).required);
        let dup_example = parse_strict("A\nA=1\n").unwrap();
        let dup_schema = Schema::from_example(&dup_example);
        assert!(!dup_schema.keys["A"].allow_bare);
        let dup_first = parse_strict_with("A\nA=1\n", first_wins).unwrap();
        assert!(Schema::from_example(&dup_first).keys["A"].allow_bare);
    }

    #[test]
    fn allow_empty_false_checks_allowed_unknown_keys_once_on_effective_winner() {
        let schema = Schema::new().with_allow_empty(false);
        let doc = parse_strict("A=\nA=filled\nB=filled\nB=\nC\n").unwrap();
        let findings =
            lint_with_schema(&doc, LintOptions::new().with_duplicate_keys(false), &schema);
        let summary: Vec<_> = findings
            .iter()
            .map(|f| (f.rule(), f.key(), f.line(), f.message()))
            .collect();
        assert_eq!(
            summary,
            vec![
                (Rule::EmptyValue, Some("B"), 4, "key has an empty value"),
                (Rule::EmptyValue, Some("C"), 5, "bare key has no value"),
            ]
        );
    }

    #[test]
    fn typed_shape_rejects_empty_unless_allow_empty_is_explicitly_true() {
        let schema = Schema::new()
            .with_allow_empty(true)
            .with_key("PORT", KeySchema::new().with_shape(ValueShape::Port))
            .with_key(
                "OPT_PORT",
                KeySchema::new()
                    .with_allow_empty(true)
                    .with_shape(ValueShape::Port),
            );
        let doc = parse_strict("PORT=\nOPT_PORT=\n").unwrap();
        let findings =
            lint_with_schema(&doc, LintOptions::new().with_duplicate_keys(false), &schema);
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].rule(), Rule::EmptyValue);
        assert_eq!(findings[0].key(), Some("PORT"));
    }

    #[test]
    fn non_participating_keys_one_of_empty_and_disabled_unknown_key_are_consistent() {
        // Compose bare keys (`BareKeys::Ignore`) and empty keys validate cleanly against self.
        let compose_example =
            parse_strict_with("=ignored\nAWS_PROFILE\nHOST=localhost\n", Dialect::COMPOSE).unwrap();
        let compose_schema = Schema::from_example(&compose_example).with_allow_unknown(false);
        assert!(!compose_schema.keys.contains_key(""));
        assert!(compose_schema.keys["AWS_PROFILE"].allow_bare);
        assert_eq!(
            lint_with_schema(
                &compose_example,
                LintOptions::new().with_duplicate_keys(false),
                &compose_schema,
            ),
            Vec::new()
        );

        // Compose bare key rejected by standalone allow_empty = false.
        let compose_bare = parse_strict_with("AWS_PROFILE\n", Dialect::COMPOSE).unwrap();
        let bare_findings = lint_with_schema(
            &compose_bare,
            LintOptions::new().with_duplicate_keys(false),
            &Schema::new().with_allow_empty(false),
        );
        assert_eq!(bare_findings.len(), 1);
        assert_eq!(bare_findings[0].rule(), Rule::EmptyValue);
        assert_eq!(bare_findings[0].key(), Some("AWS_PROFILE"));

        // Node `__proto__` (non-participating under `node_object_keys`) validates against self.
        let node_example = parse_strict_with("__proto__=1\nA=2\n", Dialect::NODE_DOTENV).unwrap();
        let node_schema = Schema::from_example(&node_example).with_allow_unknown(false);
        assert!(node_schema.keys.contains_key("__proto__"));
        assert_eq!(
            lint_with_schema(
                &node_example,
                LintOptions::new().with_duplicate_keys(false),
                &node_schema,
            ),
            Vec::new()
        );

        // Duplicate non-participating entries (`__proto__`) follow dialect First vs Last rules.
        let proto_port =
            Schema::new().with_key("__proto__", KeySchema::new().with_shape(ValueShape::Port));
        let proto_last =
            parse_strict_with("__proto__=bad\n__proto__=8080\n", Dialect::NODE_DOTENV).unwrap();
        assert_eq!(
            lint_with_schema(
                &proto_last,
                LintOptions::new().with_duplicate_keys(false),
                &proto_port,
            ),
            Vec::new()
        );
        let proto_first = parse_strict_with(
            "__proto__=bad\n__proto__=8080\n",
            Dialect::NODE_DOTENV.with_duplicates(Duplicates::First),
        )
        .unwrap();
        let proto_first_findings = lint_with_schema(
            &proto_first,
            LintOptions::new().with_duplicate_keys(false),
            &proto_port,
        );
        assert_eq!(proto_first_findings.len(), 1);
        assert_eq!(proto_first_findings[0].rule(), Rule::InvalidValue);
        assert_eq!(proto_first_findings[0].line(), 1);

        // OneOf containing "" allows empty unless allow_empty is explicitly false.
        let one_of_schema = Schema::new()
            .with_key(
                "MODE",
                KeySchema::new()
                    .with_shape(ValueShape::OneOf(vec![String::new(), "dev".to_owned()])),
            )
            .with_key(
                "STRICT_MODE",
                KeySchema::new()
                    .with_allow_empty(false)
                    .with_shape(ValueShape::OneOf(vec![String::new(), "dev".to_owned()])),
            );
        let mode_doc = parse_strict("MODE=\nSTRICT_MODE=\n").unwrap();
        let mode_findings = lint_with_schema(
            &mode_doc,
            LintOptions::new().with_duplicate_keys(false),
            &one_of_schema,
        );
        assert_eq!(mode_findings.len(), 1);
        assert_eq!(mode_findings[0].key(), Some("STRICT_MODE"));
        assert_eq!(mode_findings[0].rule(), Rule::EmptyValue);

        // Disabling unknown-key with allow_unknown=false + allow_empty=false still checks EmptyValue.
        let closed_non_empty = Schema::new()
            .with_allow_unknown(false)
            .with_allow_empty(false)
            .with_key("A", KeySchema::new());
        let extra_empty = parse_strict("A=1\nEXTRA=\n").unwrap();
        let findings = lint_with_schema(
            &extra_empty,
            LintOptions::new()
                .with_duplicate_keys(false)
                .with_unknown_keys(false),
            &closed_non_empty,
        );
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].rule(), Rule::EmptyValue);
        assert_eq!(findings[0].key(), Some("EXTRA"));
    }
}