mogh_config 3.0.3

Utilities to merge config from multiple files / directories.
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
//! Env file (`.env`) syntax as a configuration source: a flat set
//! of `NAME=value` entries, the format Cicada renders a stack of
//! secret environments in and the one dotenv files use.
//!
//! The grammar is Cicada's (a serialized secret export parses back
//! unchanged): `#` lines are comments, blank lines are skipped, an
//! `export ` prefix is accepted, and a value is unquoted (taken
//! literally to the end of the line, trimmed), single quoted
//! (literal) or double quoted with `\n` / `\r` / `\t` / `\"` / `\\`
//! escapes. Nothing is substituted inside a value: `${VAR}` and
//! `$(cmd)` are kept as written, since env file values are secrets
//! and never templates.
//!
//! As a configuration source ([parse_env_file_object]) names are
//! lowercased to match struct fields, and dots nest:
//! `DATABASE.ADDRESS=x` fills `database.address`, so a flat set of
//! secrets can populate a structured config. A name with an empty
//! segment (`.dockerconfigjson`, `A..B`), or with more than 32
//! segments, stays one flat key.

/// The most `.` separated segments a name nests into. A name with
/// more stays one flat key: nesting without a bound lets one long
/// name (a cicada secret's, say) cost memory quadratic in its
/// length, and overflow the stack of whatever walks the object
/// next. yaml and json sources stop at 128 levels of their own.
const MAX_NESTED_SEGMENTS: usize = 32;

/// Where an env file failed to parse. The message never carries a
/// value, only what was expected.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EnvFileError {
  /// 1-based line number.
  pub line: usize,
  pub message: String,
}

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

impl std::error::Error for EnvFileError {}

fn error(line: usize, message: impl Into<String>) -> EnvFileError {
  EnvFileError {
    line,
    message: message.into(),
  }
}

/// Parses an env file into `(name, value)` pairs in file order,
/// names as written. A name given twice is an error (which of the
/// two the author meant is anyone's guess).
pub fn parse_env_file(
  content: &str,
) -> Result<Vec<(String, String)>, EnvFileError> {
  Ok(
    parse_entries(content)?
      .into_iter()
      .map(|entry| (entry.name, entry.value))
      .collect(),
  )
}

/// Parses an env file into the configuration object it describes:
/// names lowercased (`DB_PASSWORD` is the field `db_password`),
/// dots nesting (`DATABASE.ADDRESS` is `database.address`), values
/// strings (the final deserialization coerces them).
///
/// A name with an empty segment cannot nest (`.dockerconfigjson`,
/// `A..B`, `A.`, `.`), so it is kept whole as one flat key,
/// lowercased (`.dockerconfigjson`, `a..b`): Cicada accepts such
/// secret names, and one of them must not fail the whole source.
/// So is a name with more than 32 `.` separated segments: nesting
/// stops there, so one long name can't cost memory quadratic in its
/// length or overflow the stack of what walks the object next.
///
/// Errors, with the line and both names involved: a name that is
/// both a value and an object (`DATABASE=x` next to
/// `DATABASE.ADDRESS=y`), and two spellings of one name (`Db` and
/// `DB`).
pub fn parse_env_file_object(
  content: &str,
) -> Result<serde_json::Map<String, serde_json::Value>, EnvFileError>
{
  let mut object = serde_json::Map::new();
  // The entry which set each key (a value) or first nested under it
  // (an object), by its dotted path, to name both sides of a
  // conflict. A nested path never has an empty segment nor more
  // than MAX_NESTED_SEGMENTS segments, and a flat key always has
  // one or the other, so the two never share a path.
  let mut origins =
    std::collections::HashMap::<String, (String, usize)>::new();
  for entry in parse_entries(content)? {
    let name = entry.name.to_lowercase();
    let segments = if name.split('.').any(str::is_empty)
      || name.split('.').nth(MAX_NESTED_SEGMENTS).is_some()
    {
      vec![name.as_str()]
    } else {
      name.split('.').collect::<Vec<_>>()
    };
    let (last, parents) =
      segments.split_last().expect("split yields one segment");
    let mut current = &mut object;
    for (depth, segment) in parents.iter().enumerate() {
      let path = segments[..=depth].join(".");
      let slot =
        current.entry(segment.to_string()).or_insert_with(|| {
          origins
            .insert(path.clone(), (entry.name.clone(), entry.line));
          serde_json::Value::Object(Default::default())
        });
      match slot {
        serde_json::Value::Object(map) => current = map,
        _ => {
          return Err(conflict(
            &entry,
            &origins[&path],
            format!("`{path}` is both a value and an object"),
          ));
        }
      }
    }
    if let Some(existing) = current.get(*last) {
      return Err(conflict(
        &entry,
        &origins[&name],
        if existing.is_object() {
          format!("`{name}` is both a value and an object")
        } else {
          // Exact duplicates were refused while parsing the entries.
          String::from("names are case insensitive")
        },
      ));
    }
    origins.insert(name.clone(), (entry.name.clone(), entry.line));
    current.insert(
      last.to_string(),
      serde_json::Value::String(entry.value),
    );
  }
  Ok(object)
}

/// A conflict between `entry` and the earlier entry `origin` (its
/// name and line), naming both.
fn conflict(
  entry: &Entry,
  (origin, origin_line): &(String, usize),
  message: String,
) -> EnvFileError {
  error(
    entry.line,
    format!(
      "`{}` conflicts with `{origin}` (line {origin_line}): {message}",
      entry.name
    ),
  )
}

struct Entry {
  line: usize,
  name: String,
  value: String,
}

fn parse_entries(content: &str) -> Result<Vec<Entry>, EnvFileError> {
  // A byte order mark (hand written on Windows) is not part of the
  // first name.
  let content = content.strip_prefix('\u{FEFF}').unwrap_or(content);
  let mut entries: Vec<Entry> = Vec::new();
  let mut names = std::collections::HashSet::<&str>::new();
  for (idx, raw) in content.lines().enumerate() {
    let number = idx + 1;
    let line = raw.trim();
    if line.is_empty() || line.starts_with('#') {
      continue;
    }
    // Real env files often carry `export NAME=value`.
    let line = line
      .strip_prefix("export ")
      .map(str::trim_start)
      .unwrap_or(line);
    let Some((name, value)) = line.split_once('=') else {
      return Err(error(
        number,
        "expected `NAME=value`, a `#` comment, or a blank line",
      ));
    };
    let name = name.trim();
    if name.is_empty() {
      return Err(error(number, "missing name before `=`"));
    }
    if !names.insert(name) {
      return Err(error(
        number,
        format!("duplicate entry for `{name}`"),
      ));
    }
    entries.push(Entry {
      line: number,
      name: name.to_string(),
      value: parse_value(value.trim(), name, number)?,
    });
  }
  Ok(entries)
}

/// A value after `=`, already trimmed: unquoted (taken literally to
/// the end of the line), single quoted (literal), or double quoted
/// with escapes. `name` is the entry's, for the errors.
fn parse_value(
  value: &str,
  name: &str,
  line: usize,
) -> Result<String, EnvFileError> {
  let mut chars = value.chars();
  match chars.next() {
    Some('"') => {
      let mut out = String::new();
      loop {
        match chars.next() {
          Some('\\') => match chars.next() {
            Some('n') => out.push('\n'),
            Some('r') => out.push('\r'),
            Some('t') => out.push('\t'),
            Some('"') => out.push('"'),
            Some('\\') => out.push('\\'),
            // The escaped character is part of the (secret) value,
            // and so is where it sits, so the message names neither.
            Some(_) => {
              return Err(error(
                line,
                format!(
                  "unsupported escape in the value of `{name}`: \
                   a double quoted value takes `\\n`, `\\r`, `\\t`, \
                   `\\\"` and `\\\\` (a literal backslash)"
                ),
              ));
            }
            None => {
              return Err(error(
                line,
                "unterminated double quoted value",
              ));
            }
          },
          Some('"') => break,
          Some(c) => out.push(c),
          None => {
            return Err(error(
              line,
              "unterminated double quoted value",
            ));
          }
        }
      }
      if chars.next().is_some() {
        return Err(error(
          line,
          "unexpected content after closing quote",
        ));
      }
      Ok(out)
    }
    Some('\'') => {
      // Like Core: the value runs to the last quote, so `'it's'`
      // is `it's`.
      let rest = &value[1..];
      let Some(end) = rest.rfind('\'') else {
        return Err(error(line, "unterminated single quoted value"));
      };
      if !rest[end + 1..].is_empty() {
        return Err(error(
          line,
          "unexpected content after closing quote",
        ));
      }
      Ok(rest[..end].to_string())
    }
    _ => Ok(value.to_string()),
  }
}

/// Whether a config path is an env file: named `.env`, or with the
/// `env` extension (`app.env`). `Path::extension` is `None` for
/// `.env`, hence the file name check.
pub fn is_env_file(path: &std::path::Path) -> bool {
  let name = path
    .file_name()
    .and_then(|name| name.to_str())
    .unwrap_or_default();
  name == ".env"
    || path
      .extension()
      .and_then(|ext| ext.to_str())
      .is_some_and(|ext| ext.eq_ignore_ascii_case("env"))
}

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

  #[test]
  fn parses_the_cicada_grammar() {
    let file = "\
# A comment
export DB_PASSWORD=hunter2
PORT = 8080

# The description of B
B=\"escaped\\nnewline \\\"quoted\\\" \\\\ #tag\"
SINGLE='it's literal ${NOT_EXPANDED}'
EMPTY=
UNQUOTED=$(not run) ${NOT_EXPANDED} # not a comment
";
    let entries = parse_env_file(file).unwrap();
    assert_eq!(
      entries,
      vec![
        ("DB_PASSWORD".to_string(), "hunter2".to_string()),
        ("PORT".to_string(), "8080".to_string()),
        (
          "B".to_string(),
          "escaped\nnewline \"quoted\" \\ #tag".to_string()
        ),
        (
          "SINGLE".to_string(),
          "it's literal ${NOT_EXPANDED}".to_string()
        ),
        ("EMPTY".to_string(), String::new()),
        (
          "UNQUOTED".to_string(),
          "$(not run) ${NOT_EXPANDED} # not a comment".to_string()
        ),
      ]
    );
  }

  #[test]
  fn errors_name_the_line_and_never_the_value() {
    for (file, expected) in [
      ("A=1\nnot an entry", "line 2: expected `NAME=value`"),
      ("=1", "line 1: missing name"),
      ("A=1\nA=2", "line 2: duplicate entry for `A`"),
      (
        "A=\"bad \\x escape\"",
        "line 1: unsupported escape in the value of `A`",
      ),
      (
        "A=\"unterminated",
        "line 1: unterminated double quoted value",
      ),
      (
        "A='unterminated",
        "line 1: unterminated single quoted value",
      ),
      (
        "A=\"secret\" trailing",
        "line 1: unexpected content after closing quote",
      ),
      (
        "A='secret' trailing",
        "line 1: unexpected content after closing quote",
      ),
    ] {
      let err = parse_env_file(file).unwrap_err().to_string();
      assert!(err.starts_with(expected), "{file:?}: {err}");
      assert!(!err.contains("secret"), "{err}");
    }
  }

  /// The escaped character is a character of the (secret) value:
  /// the message is the same whichever it is, and wherever it sits.
  #[test]
  fn unsupported_escapes_never_name_the_escaped_character() {
    let expected = parse_env_file("DB_PASSWORD=\"\\q\"")
      .unwrap_err()
      .to_string();
    assert!(
      expected.starts_with(
        "line 1: unsupported escape in the value of `DB_PASSWORD`"
      ),
      "{expected}"
    );
    assert!(!expected.contains("\\q"), "{expected}");
    let escaped = ('!'..='~')
      .chain([' ', 'é', '€', '😀'])
      .filter(|c| !matches!(c, 'n' | 'r' | 't' | '"' | '\\'));
    for c in escaped {
      for file in [
        format!("DB_PASSWORD=\"\\{c}\""),
        format!("DB_PASSWORD=\"p4ss\\{c}w0rd\""),
        format!("DB_PASSWORD=\"{}\\{c}\"", "p".repeat(40)),
      ] {
        let err = parse_env_file(&file).unwrap_err();
        assert_eq!(err.line, 1);
        assert_eq!(err.to_string(), expected, "{file:?}");
      }
    }
  }

  #[test]
  fn a_byte_order_mark_is_not_part_of_the_first_name() {
    assert_eq!(
      parse_env_file("\u{FEFF}A=1\nB=2").unwrap(),
      vec![
        ("A".to_string(), "1".to_string()),
        ("B".to_string(), "2".to_string()),
      ]
    );
  }

  #[test]
  fn objects_lowercase_names_and_nest_on_dots() {
    let object = parse_env_file_object(
      "TITLE=app\nDATABASE.ADDRESS=db:5432\nDATABASE.CREDENTIALS.USERNAME=u\nDatabase.Credentials.Password=\"p\"\nPORT=8080\n",
    )
    .unwrap();
    assert_eq!(
      serde_json::Value::Object(object),
      serde_json::json!({
        "title": "app",
        "port": "8080",
        "database": {
          "address": "db:5432",
          "credentials": { "username": "u", "password": "p" },
        },
      })
    );
    assert_eq!(
      serde_json::Value::Object(parse_env_file_object("").unwrap()),
      serde_json::json!({})
    );
  }

  #[test]
  fn objects_refuse_conflicts_naming_the_line_and_both_names() {
    for (file, expected) in [
      (
        "DATABASE=x\nDATABASE.ADDRESS=y",
        "line 2: `DATABASE.ADDRESS` conflicts with `DATABASE` (line 1): `database` is both a value and an object",
      ),
      (
        "DATABASE.ADDRESS=y\nDATABASE=x",
        "line 2: `DATABASE` conflicts with `DATABASE.ADDRESS` (line 1): `database` is both a value and an object",
      ),
      (
        "A.B=1\nA.B.C=2",
        "line 2: `A.B.C` conflicts with `A.B` (line 1): `a.b` is both a value and an object",
      ),
      (
        "A.B.C=1\nA.X=2\nA.B=3",
        "line 3: `A.B` conflicts with `A.B.C` (line 1): `a.b` is both a value and an object",
      ),
      (
        "Db=1\nDB=2",
        "line 2: `DB` conflicts with `Db` (line 1): names are case insensitive",
      ),
      (
        "Database.Address=1\nDATABASE.ADDRESS=2",
        "line 2: `DATABASE.ADDRESS` conflicts with `Database.Address` (line 1): names are case insensitive",
      ),
      (
        ".DockerConfigJson=1\n.dockerconfigjson=2",
        "line 2: `.dockerconfigjson` conflicts with `.DockerConfigJson` (line 1): names are case insensitive",
      ),
    ] {
      let err = parse_env_file_object(file).unwrap_err().to_string();
      assert_eq!(err, expected, "{file:?}");
    }
    // Values never appear in the messages.
    let err = parse_env_file_object("A=secretvalue\nA.B=1")
      .unwrap_err()
      .to_string();
    assert!(!err.contains("secretvalue"), "{err}");
  }

  /// Cicada accepts secret names which cannot nest: each is one
  /// flat key, and the rest of the file still nests.
  #[test]
  fn names_with_an_empty_segment_stay_flat() {
    let object = parse_env_file_object(
      ".DockerConfigJson={\"auths\":{}}\nA..B=1\nX.=2\n.=3\nA.B=4\nDATABASE.ADDRESS=db:5432\n",
    )
    .unwrap();
    assert_eq!(
      serde_json::Value::Object(object),
      serde_json::json!({
        ".dockerconfigjson": "{\"auths\":{}}",
        "a..b": "1",
        "x.": "2",
        ".": "3",
        "a": { "b": "4" },
        "database": { "address": "db:5432" },
      })
    );
  }

  /// Nesting stops at [MAX_NESTED_SEGMENTS]: a longer name is one
  /// flat key, parsed in time and memory linear in its length.
  #[test]
  fn names_nest_up_to_the_segment_limit() {
    let nested = vec!["a"; MAX_NESTED_SEGMENTS].join(".");
    let object =
      parse_env_file_object(&format!("{nested}=1")).unwrap();
    let mut value = &serde_json::Value::Object(object);
    for _ in 0..MAX_NESTED_SEGMENTS {
      value = &value["a"];
    }
    assert_eq!(value, "1");

    let flat = vec!["a"; MAX_NESTED_SEGMENTS + 1].join(".");
    let object =
      parse_env_file_object(&format!("{flat}=1\nA.B=2")).unwrap();
    assert_eq!(
      serde_json::Value::Object(object),
      serde_json::json!({ flat.clone(): "1", "a": { "b": "2" } })
    );

    // 10k segments (20KB, 300MB of nesting before the limit): one
    // flat key, fast.
    let long = vec!["a"; 10_000].join(".");
    let started = std::time::Instant::now();
    let object = parse_env_file_object(&format!("{long}=1")).unwrap();
    assert!(object.contains_key(&long));
    assert!(started.elapsed() < std::time::Duration::from_secs(5));
  }

  #[test]
  fn many_entries_parse_in_linear_time() {
    let file = (0..100_000)
      .map(|i| format!("NAME_{i}=value"))
      .collect::<Vec<_>>()
      .join("\n");
    let started = std::time::Instant::now();
    assert_eq!(parse_env_file(&file).unwrap().len(), 100_000);
    assert!(started.elapsed() < std::time::Duration::from_secs(5));
    // Duplicates are still found.
    let err =
      parse_env_file(&format!("{file}\nNAME_7=x")).unwrap_err();
    assert_eq!(err.line, 100_001);
  }

  #[test]
  fn env_files_are_recognized_by_name_or_extension() {
    use std::path::Path;
    assert!(is_env_file(Path::new(".env")));
    assert!(is_env_file(Path::new("/etc/app/.env")));
    assert!(is_env_file(Path::new("app.env")));
    assert!(is_env_file(Path::new("APP.ENV")));
    assert!(!is_env_file(Path::new("config.toml")));
    assert!(!is_env_file(Path::new(".envrc")));
    assert!(!is_env_file(Path::new("env")));
  }
}