use std::collections::BTreeMap;
use adotenv::{AssignmentState, Document, Duplicates, Entry};
use crate::{Finding, LintOptions, Rule};
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub enum ValueShape {
#[default]
Any,
Bool,
Integer,
UnsignedInteger,
Port,
Float,
Url,
OneOf(Vec<String>),
}
impl ValueShape {
#[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",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct KeySchema {
pub required: bool,
pub allow_empty: Option<bool>,
pub allow_bare: bool,
pub shape: ValueShape,
}
impl Default for KeySchema {
fn default() -> Self {
Self::new()
}
}
impl KeySchema {
#[must_use]
pub const fn new() -> Self {
Self {
required: true,
allow_empty: None,
allow_bare: false,
shape: ValueShape::Any,
}
}
#[must_use]
pub const fn optional() -> Self {
Self {
required: false,
allow_empty: None,
allow_bare: false,
shape: ValueShape::Any,
}
}
#[must_use]
pub const fn with_required(mut self, required: bool) -> Self {
self.required = required;
self
}
#[must_use]
pub const fn with_allow_empty(mut self, allow_empty: bool) -> Self {
self.allow_empty = Some(allow_empty);
self
}
#[must_use]
pub const fn with_allow_bare(mut self, allow_bare: bool) -> Self {
self.allow_bare = allow_bare;
self
}
#[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,
},
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Schema {
pub keys: BTreeMap<String, KeySchema>,
pub allow_unknown: bool,
pub allow_empty: bool,
}
impl Default for Schema {
fn default() -> Self {
Self::new()
}
}
impl Schema {
#[must_use]
pub fn new() -> Self {
Self {
keys: BTreeMap::new(),
allow_unknown: true,
allow_empty: true,
}
}
#[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,
}
}
#[must_use]
pub fn with_key(mut self, key: impl Into<String>, policy: KeySchema) -> Self {
self.keys.insert(key.into(), policy);
self
}
#[must_use]
pub const fn with_allow_unknown(mut self, allow_unknown: bool) -> Self {
self.allow_unknown = allow_unknown;
self
}
#[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());
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);
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)"
);
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());
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"
);
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() {
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()
);
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"));
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()
);
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);
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);
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"));
}
}