use std::collections::BTreeMap;
use std::net::{IpAddr, SocketAddr};
use adotenv::{AssignmentState, Document, Duplicates, Entry};
use crate::{Finding, Fix, 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>),
IpAddr,
Host,
SocketAddr,
Email,
}
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),
Self::IpAddr => value.parse::<IpAddr>().is_ok(),
Self::Host => is_valid_host(value),
Self::SocketAddr => value.parse::<SocketAddr>().is_ok(),
Self::Email => is_valid_email(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",
Self::IpAddr => "value is not a valid IP address",
Self::Host => "value is not a valid host name or IP address",
Self::SocketAddr => "value is not a valid socket address",
Self::Email => "value is not a valid email address",
}
}
}
#[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,
pub description: Option<String>,
pub deprecated: bool,
pub deprecation_note: Option<String>,
pub prefix: Option<String>,
pub suffix: Option<String>,
pub min_len: Option<usize>,
pub max_len: Option<usize>,
}
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,
description: None,
deprecated: false,
deprecation_note: None,
prefix: None,
suffix: None,
min_len: None,
max_len: None,
}
}
#[must_use]
pub const fn optional() -> Self {
Self {
required: false,
allow_empty: None,
allow_bare: false,
shape: ValueShape::Any,
description: None,
deprecated: false,
deprecation_note: None,
prefix: None,
suffix: None,
min_len: None,
max_len: None,
}
}
#[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
}
#[must_use]
pub fn with_description(mut self, description: impl Into<String>) -> Self {
self.description = Some(description.into());
self
}
#[must_use]
pub fn with_deprecated(mut self, deprecated: bool) -> Self {
self.deprecated = deprecated;
if !deprecated {
self.deprecation_note = None;
}
self
}
#[must_use]
pub fn with_deprecation_note(mut self, note: impl Into<String>) -> Self {
self.deprecated = true;
self.deprecation_note = Some(note.into());
self
}
#[must_use]
pub fn with_prefix(mut self, prefix: impl Into<String>) -> Self {
self.prefix = Some(prefix.into());
self
}
#[must_use]
pub fn with_suffix(mut self, suffix: impl Into<String>) -> Self {
self.suffix = Some(suffix.into());
self
}
#[must_use]
pub const fn with_min_len(mut self, min_len: usize) -> Self {
self.min_len = Some(min_len);
self
}
#[must_use]
pub const fn with_max_len(mut self, max_len: usize) -> Self {
self.max_len = Some(max_len);
self
}
pub(crate) fn effective_allow_empty(&self, schema_default: bool) -> bool {
if let Some(explicit) = self.allow_empty {
return explicit;
}
let bounds_require_non_empty = self.min_len.is_some_and(|min| min > 0)
|| self.prefix.as_deref().is_some_and(|p| !p.is_empty())
|| self.suffix.as_deref().is_some_and(|s| !s.is_empty());
if bounds_require_non_empty {
return false;
}
match &self.shape {
ValueShape::Any => schema_default,
ValueShape::OneOf(allowed) => allowed.iter().any(String::is_empty),
_ => false,
}
}
pub(crate) fn check_literal_bounds(&self, value: &str) -> Option<(&'static str, String)> {
if let Some(prefix) = &self.prefix {
if !value.starts_with(prefix.as_str()) {
return Some((
"value does not start with the required prefix",
format!("expected prefix {prefix:?}"),
));
}
}
if let Some(suffix) = &self.suffix {
if !value.ends_with(suffix.as_str()) {
return Some((
"value does not end with the required suffix",
format!("expected suffix {suffix:?}"),
));
}
}
if self.min_len.is_some() || self.max_len.is_some() {
let len = value.chars().count();
if let Some(min) = self.min_len {
if len < min {
let unit = if min == 1 { "character" } else { "characters" };
return Some((
"value is shorter than the minimum length",
format!("expected at least {min} {unit}"),
));
}
}
if let Some(max) = self.max_len {
if len > max {
let unit = if max == 1 { "character" } else { "characters" };
return Some((
"value exceeds the maximum length",
format!("expected at most {max} {unit}"),
));
}
}
}
None
}
}
#[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);
deprecated_schema_findings(document, options, schema, findings);
undeclared_schema_findings(document, &winners, options, schema, findings);
}
fn deprecated_schema_findings(
document: &Document<'_>,
options: LintOptions,
schema: &Schema,
findings: &mut Vec<Finding>,
) {
if !options.deprecated_keys {
return;
}
for entry in document.entries() {
let key = entry.key();
if let Some(spec) = schema.keys.get(key).filter(|spec| spec.deprecated) {
findings.push(Finding::with_detail(
Rule::DeprecatedKey,
"key is deprecated",
options.severity_for_rule(Rule::DeprecatedKey),
entry.key_span(),
entry.line(),
Some(key),
spec.deprecation_note
.as_deref()
.filter(|note| !note.trim().is_empty()),
None,
));
}
}
}
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 {
let fix = (!key.is_empty()).then(|| Fix::InsertEmpty { key: key.clone() });
findings.push(Finding::new(
Rule::MissingKey,
"required key is missing",
options.severity_for_rule(Rule::MissingKey),
doc_start..doc_start,
1,
Some(key),
fix,
));
}
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 {
if !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,
));
} else if let Some((message, detail)) = spec.check_literal_bounds(value) {
findings.push(Finding::with_detail(
Rule::InvalidValue,
message,
options.severity_for_rule(Rule::InvalidValue),
entry.value_span().unwrap_or_else(|| entry.key_span()),
entry.line(),
Some(entry.key()),
Some(&detail),
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()
}
fn is_valid_host(value: &str) -> bool {
value.parse::<IpAddr>().is_ok() || is_valid_hostname(value)
}
fn is_valid_hostname(value: &str) -> bool {
let trimmed = value.strip_suffix('.').unwrap_or(value);
if trimmed.is_empty() || trimmed.len() > 253 || !trimmed.is_ascii() {
return false;
}
let mut last_label = "";
for label in trimmed.split('.') {
let bytes = label.as_bytes();
if bytes.is_empty() || bytes.len() > 63 {
return false;
}
if !bytes[0].is_ascii_alphanumeric() || !bytes[bytes.len() - 1].is_ascii_alphanumeric() {
return false;
}
if !bytes
.iter()
.all(|byte| byte.is_ascii_alphanumeric() || *byte == b'-')
{
return false;
}
last_label = label;
}
!last_label.bytes().all(|byte| byte.is_ascii_digit())
}
fn is_valid_email(value: &str) -> bool {
if value.is_empty() || value.len() > 254 || !value.is_ascii() {
return false;
}
let Some((local, domain)) = value.split_once('@') else {
return false;
};
if local.is_empty()
|| local.len() > 64
|| local.starts_with('.')
|| local.ends_with('.')
|| local.contains("..")
|| domain.contains('@')
|| domain.ends_with('.')
|| !domain.contains('.')
{
return false;
}
let local_ok = local.bytes().all(|byte| {
byte.is_ascii_alphanumeric()
|| matches!(
byte,
b'!' | b'#'
| b'$'
| b'%'
| b'&'
| b'\''
| b'*'
| b'+'
| b'-'
| b'/'
| b'='
| b'?'
| b'^'
| b'_'
| b'`'
| b'{'
| b'|'
| b'}'
| b'~'
| b'.'
)
});
local_ok && is_valid_hostname(domain)
}
#[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 v04_value_shapes_validate_exact_boundaries() {
assert!(ValueShape::IpAddr.matches("127.0.0.1"));
assert!(ValueShape::IpAddr.matches("0.0.0.0"));
assert!(ValueShape::IpAddr.matches("::1"));
assert!(ValueShape::IpAddr.matches("2001:db8::1"));
assert!(ValueShape::IpAddr.matches("::ffff:192.0.2.1"));
assert!(!ValueShape::IpAddr.matches(""));
assert!(!ValueShape::IpAddr.matches("localhost"));
assert!(!ValueShape::IpAddr.matches("127.0.0.1:8080"));
assert!(!ValueShape::IpAddr.matches("[::1]"));
assert!(!ValueShape::IpAddr.matches("256.0.0.1"));
assert!(!ValueShape::IpAddr.matches("127.0.0.1/24"));
assert!(ValueShape::Host.matches("localhost"));
assert!(ValueShape::Host.matches("example.com"));
assert!(ValueShape::Host.matches("sub.example.com."));
assert!(ValueShape::Host.matches("a"));
assert!(ValueShape::Host.matches("db-1"));
assert!(ValueShape::Host.matches("1db"));
assert!(ValueShape::Host.matches("3com.com"));
assert!(ValueShape::Host.matches("127.0.0.1"));
assert!(ValueShape::Host.matches("::1"));
let label_63 = "a".repeat(63);
let label_64 = "a".repeat(64);
assert!(ValueShape::Host.matches(&label_63));
assert!(!ValueShape::Host.matches(&label_64));
let host_253 = format!("{label_63}.{label_63}.{label_63}.{}", "a".repeat(61));
assert_eq!(host_253.len(), 253);
assert!(ValueShape::Host.matches(&host_253));
assert!(ValueShape::Host.matches(&format!("{host_253}.")));
let host_254 = format!("{label_63}.{label_63}.{label_63}.{}", "a".repeat(62));
assert_eq!(host_254.len(), 254);
assert!(!ValueShape::Host.matches(&host_254));
assert!(!ValueShape::Host.matches(""));
assert!(!ValueShape::Host.matches("."));
assert!(!ValueShape::Host.matches(".example.com"));
assert!(!ValueShape::Host.matches("example.com.."));
assert!(!ValueShape::Host.matches("a..b"));
assert!(!ValueShape::Host.matches("-bad"));
assert!(!ValueShape::Host.matches("bad-"));
assert!(!ValueShape::Host.matches("bad_host"));
assert!(!ValueShape::Host.matches("12345"));
assert!(!ValueShape::Host.matches("999.999.999.999"));
assert!(!ValueShape::Host.matches("127.0.0.1."));
assert!(!ValueShape::Host.matches("[::1]"));
assert!(!ValueShape::Host.matches("café.com"));
assert!(ValueShape::SocketAddr.matches("127.0.0.1:8080"));
assert!(ValueShape::SocketAddr.matches("0.0.0.0:0"));
assert!(ValueShape::SocketAddr.matches("[::1]:8080"));
assert!(ValueShape::SocketAddr.matches("[2001:db8::1]:443"));
assert!(!ValueShape::SocketAddr.matches(""));
assert!(!ValueShape::SocketAddr.matches("localhost:8080"));
assert!(!ValueShape::SocketAddr.matches("::1:8080"));
assert!(!ValueShape::SocketAddr.matches("127.0.0.1"));
assert!(!ValueShape::SocketAddr.matches("127.0.0.1:65536"));
assert!(!ValueShape::SocketAddr.matches("127.0.0.1:+80"));
assert!(ValueShape::Email.matches("user@example.com"));
assert!(ValueShape::Email.matches("a.b+tag_1!#$%&'*/=?^`{|}~-@sub.example.co.uk"));
let local_64 = "a".repeat(64);
let local_65 = "a".repeat(65);
assert!(ValueShape::Email.matches(&format!("{local_64}@example.com")));
assert!(!ValueShape::Email.matches(&format!("{local_65}@example.com")));
let email_domain_189 = format!("{label_63}.{label_63}.{}", "a".repeat(61));
let email_254 = format!("{local_64}@{email_domain_189}");
assert_eq!(email_254.len(), 254);
assert!(ValueShape::Email.matches(&email_254));
let email_255 = format!("{local_64}@{label_63}.{label_63}.{}", "a".repeat(62));
assert_eq!(email_255.len(), 255);
assert!(!ValueShape::Email.matches(&email_255));
assert!(!ValueShape::Email.matches(""));
assert!(!ValueShape::Email.matches("user"));
assert!(!ValueShape::Email.matches("@example.com"));
assert!(!ValueShape::Email.matches("user@"));
assert!(!ValueShape::Email.matches("user@localhost"));
assert!(!ValueShape::Email.matches("user@example.com."));
assert!(!ValueShape::Email.matches(".user@example.com"));
assert!(!ValueShape::Email.matches("user.@example.com"));
assert!(!ValueShape::Email.matches("a..b@example.com"));
assert!(!ValueShape::Email.matches("a@b@example.com"));
assert!(!ValueShape::Email.matches("user name@example.com"));
assert!(!ValueShape::Email.matches("user@example.com\n"));
assert!(!ValueShape::Email.matches("user@example.com\x7f"));
assert!(!ValueShape::Email.matches("user@example.123"));
assert!(!ValueShape::Email.matches("usér@example.com"));
assert!(!ValueShape::Email.matches("u(s)er@example.com"));
assert_eq!(
ValueShape::IpAddr.mismatch_message(),
"value is not a valid IP address"
);
assert_eq!(
ValueShape::Host.mismatch_message(),
"value is not a valid host name or IP address"
);
assert_eq!(
ValueShape::SocketAddr.mismatch_message(),
"value is not a valid socket address"
);
assert_eq!(
ValueShape::Email.mismatch_message(),
"value is not a valid email address"
);
}
#[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"));
}
#[test]
fn schema_metadata_deprecation_literal_bounds_and_missing_fix_work_value_free() {
let key_spec = KeySchema::optional()
.with_description("API token")
.with_deprecation_note("use NEW_TOKEN")
.with_prefix("sk_")
.with_suffix("_v1")
.with_min_len(8)
.with_max_len(12);
assert_eq!(key_spec.description.as_deref(), Some("API token"));
assert!(key_spec.deprecated);
assert_eq!(key_spec.deprecation_note.as_deref(), Some("use NEW_TOKEN"));
let cleared = key_spec.clone().with_deprecated(false);
assert!(!cleared.deprecated);
assert_eq!(cleared.deprecation_note, None);
}
#[test]
fn deprecation_and_bounds_findings_are_value_free() {
let schema = Schema::new()
.with_key("REQ_KEY", KeySchema::new())
.with_key(
"OLD_KEY",
KeySchema::optional().with_deprecation_note("use NEW_KEY"),
)
.with_key(
"OLD_BARE",
KeySchema::optional()
.with_deprecated(true)
.with_allow_bare(false),
)
.with_key(
"OLD_EMPTY_NOTE",
KeySchema::optional().with_deprecation_note(""),
)
.with_key(
"TOKEN",
KeySchema::optional()
.with_prefix("sk_")
.with_suffix("_v1")
.with_min_len(8)
.with_max_len(10),
)
.with_key(
"SHORT_ONE",
KeySchema::optional().with_min_len(1).with_max_len(1),
);
let doc = parse_strict(
"OLD_KEY=secret-old\nOLD_BARE\nOLD_EMPTY_NOTE=\nTOKEN=bad_secret_val\nSHORT_ONE=ab\n",
)
.unwrap();
let findings = lint_with_schema(
&doc,
LintOptions::new()
.with_duplicate_keys(false)
.with_severity(Rule::DeprecatedKey, Severity::Error),
&schema,
);
let summary: Vec<_> = findings
.iter()
.map(|f| (f.rule(), f.key(), f.detail()))
.collect();
assert_eq!(
summary,
[
(Rule::DeprecatedKey, Some("OLD_KEY"), Some("use NEW_KEY")),
(Rule::MissingKey, Some("REQ_KEY"), None),
(Rule::DeprecatedKey, Some("OLD_BARE"), None),
(Rule::EmptyValue, Some("OLD_BARE"), None),
(Rule::DeprecatedKey, Some("OLD_EMPTY_NOTE"), None),
(
Rule::InvalidValue,
Some("TOKEN"),
Some("expected prefix \"sk_\"")
),
(
Rule::InvalidValue,
Some("SHORT_ONE"),
Some("expected at most 1 character")
),
]
);
assert_eq!(findings[0].severity(), Severity::Error);
assert_eq!(findings[1].severity(), Severity::Warning);
assert_eq!(findings.iter().filter(|f| f.fix().is_some()).count(), 1);
assert_eq!(
findings[1].fix(),
Some(&Fix::InsertEmpty {
key: "REQ_KEY".to_owned(),
})
);
let debug = format!("{findings:?}");
assert!(!debug.contains("secret-old"), "{debug}");
assert!(!debug.contains("bad_secret_val"), "{debug}");
}
#[test]
fn literal_bounds_empty_inheritance_checks_each_bound() {
let schema = Schema::new()
.with_key(
"ALLOW_EMPTY_PREFIX",
KeySchema::optional()
.with_allow_empty(true)
.with_prefix("pre_"),
)
.with_key("REQ_PREFIX", KeySchema::optional().with_prefix("pre_"))
.with_key("REQ_SUFFIX", KeySchema::optional().with_suffix("_suf"))
.with_key("REQ_MIN", KeySchema::optional().with_min_len(2))
.with_key(
"ZERO_BOUNDS",
KeySchema::optional()
.with_prefix("")
.with_suffix("")
.with_min_len(0),
);
let doc =
parse_strict("ALLOW_EMPTY_PREFIX=\nREQ_PREFIX=\nREQ_SUFFIX=\nREQ_MIN=\nZERO_BOUNDS=\n")
.unwrap();
let findings =
lint_with_schema(&doc, LintOptions::new().with_duplicate_keys(false), &schema);
let keys: Vec<_> = findings.iter().map(|f| (f.rule(), f.key())).collect();
assert_eq!(
keys,
vec![
(Rule::EmptyValue, Some("REQ_PREFIX")),
(Rule::EmptyValue, Some("REQ_SUFFIX")),
(Rule::EmptyValue, Some("REQ_MIN")),
]
);
}
#[test]
fn literal_bounds_precedence_unicode_length_and_deprecation_toggle_work() {
let schema = Schema::new()
.with_key("REQ_KEY", KeySchema::new())
.with_key(
"OLD_KEY",
KeySchema::optional().with_deprecation_note("use NEW_KEY"),
)
.with_key(
"TOKEN",
KeySchema::optional()
.with_prefix("sk_")
.with_suffix("_v1")
.with_min_len(8)
.with_max_len(10),
)
.with_key(
"SHORT_ONE",
KeySchema::optional().with_min_len(1).with_max_len(1),
)
.with_key(
"UNICODE_LEN",
KeySchema::optional().with_min_len(2).with_max_len(2),
);
for (source, expected_msg, expected_detail) in [
(
"REQ_KEY=ok\nTOKEN=sk_secret\n",
"value does not end with the required suffix",
"expected suffix \"_v1\"",
),
(
"REQ_KEY=ok\nTOKEN=sk__v1\n",
"value is shorter than the minimum length",
"expected at least 8 characters",
),
(
"REQ_KEY=ok\nTOKEN=sk_1234567_v1\n",
"value exceeds the maximum length",
"expected at most 10 characters",
),
(
"REQ_KEY=ok\nUNICODE_LEN=é\n",
"value is shorter than the minimum length",
"expected at least 2 characters",
),
(
"REQ_KEY=ok\nUNICODE_LEN=ééé\n",
"value exceeds the maximum length",
"expected at most 2 characters",
),
] {
let sub = parse_strict(source).unwrap();
let sub_findings =
lint_with_schema(&sub, LintOptions::new().with_duplicate_keys(false), &schema);
assert_eq!(sub_findings.len(), 1, "{source:?}");
assert_eq!(sub_findings[0].rule(), Rule::InvalidValue, "{source:?}");
assert_eq!(sub_findings[0].message(), expected_msg, "{source:?}");
assert_eq!(
sub_findings[0].detail(),
Some(expected_detail),
"{source:?}"
);
}
let valid =
parse_strict("REQ_KEY=ok\nTOKEN=sk_12_v1\nSHORT_ONE=x\nUNICODE_LEN=éé\n").unwrap();
assert_eq!(
lint_with_schema(
&valid,
LintOptions::new().with_duplicate_keys(false),
&schema
),
Vec::new()
);
}
#[test]
fn schema_deprecation_toggle_empty_key_and_shape_precedence_work() {
let schema = Schema::new()
.with_key("REQ_KEY", KeySchema::new())
.with_key(
"OLD_KEY",
KeySchema::optional().with_deprecation_note("use NEW_KEY"),
);
let dep_only_doc = parse_strict("REQ_KEY=ok\nOLD_KEY=1\n").unwrap();
assert_eq!(
lint_with_schema(
&dep_only_doc,
LintOptions::new()
.with_duplicate_keys(false)
.with_deprecated_keys(false),
&schema,
),
Vec::new()
);
let dup_dep_schema = Schema::new()
.with_key(
"OLD_KEY",
KeySchema::optional().with_deprecation_note("use NEW_KEY"),
)
.with_key(
"WS_NOTE",
KeySchema::optional().with_deprecation_note(" \t "),
);
let dup_dep_doc = parse_strict("OLD_KEY=1\nOLD_KEY=2\nWS_NOTE=3\n").unwrap();
let dup_dep_findings = lint_with_schema(
&dup_dep_doc,
LintOptions::new().with_duplicate_keys(false),
&dup_dep_schema,
);
let dup_summary: Vec<_> = dup_dep_findings
.iter()
.map(|f| (f.rule(), f.key(), f.line(), f.detail()))
.collect();
assert_eq!(
dup_summary,
[
(Rule::DeprecatedKey, Some("OLD_KEY"), 1, Some("use NEW_KEY")),
(Rule::DeprecatedKey, Some("OLD_KEY"), 2, Some("use NEW_KEY")),
(Rule::DeprecatedKey, Some("WS_NOTE"), 3, None),
]
);
let empty_key_schema = Schema::new().with_key("", KeySchema::new());
let empty_key_findings = lint_with_schema(
&parse_strict("A=1\n").unwrap(),
LintOptions::new().with_duplicate_keys(false),
&empty_key_schema,
);
assert_eq!(empty_key_findings.len(), 1);
assert_eq!(empty_key_findings[0].rule(), Rule::MissingKey);
assert_eq!(empty_key_findings[0].fix(), None);
let typed_and_bounded = Schema::new().with_key(
"HOST",
KeySchema::new()
.with_shape(ValueShape::Host)
.with_prefix("api."),
);
let bad_host = parse_strict("HOST=not a host\n").unwrap();
let bad_host_findings = lint_with_schema(
&bad_host,
LintOptions::new().with_duplicate_keys(false),
&typed_and_bounded,
);
assert_eq!(bad_host_findings.len(), 1);
assert_eq!(
bad_host_findings[0].message(),
"value is not a valid host name or IP address"
);
assert_eq!(bad_host_findings[0].detail(), None);
assert_eq!(
KeySchema::new().with_min_len(1).check_literal_bounds(""),
Some((
"value is shorter than the minimum length",
"expected at least 1 character".to_owned(),
))
);
}
}