Files
fermata/src/core/secrets/parser.rs
T

837 lines
29 KiB
Rust

//! Multi-format secret file parser.
//!
//! Reads secret files (`.env`, TOML, JSON, YAML, Python assignments,
//! Java `.properties`) and extracts key-value pairs as [`SecretEntry`] items.
//! Nested structures are flattened with dot-separated keys.
//!
//! A value gets one entry per spelling the file gives it: the decoded text first,
//! then the text as it stands in the file when that differs (`\n` in a JSON string,
//! a YAML block with its indentation). A tool that reads the file shows the second,
//! a program that loads it the first. [`super::manifest`] adds the derived spellings.
use globset::Glob;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use thiserror::Error;
// ---------------------------------------------------------------------------
// Errors
// ---------------------------------------------------------------------------
#[derive(Debug, Error)]
pub enum ParseError {
#[error("io error reading {path}: {source}")]
Io {
path: PathBuf,
source: std::io::Error,
},
/// `message` names the format and the line, never the line's text: a
/// parser's own message can quote it, and this one reaches logs.
#[error("parse error in {path}: {message}")]
Format { path: PathBuf, message: String },
}
impl ParseError {
/// The file that failed.
pub fn path(&self) -> &Path {
match self {
Self::Io { path, .. } | Self::Format { path, .. } => path,
}
}
}
/// `invalid <format> at line <n>`, the only text kept of a parser's error.
fn format_message(format: &str, line: Option<usize>) -> String {
match line {
Some(line) => format!("invalid {format} at line {line}"),
None => format!("invalid {format}"),
}
}
/// [`format_message`] for a TOML error over `text`.
pub(crate) fn toml_message(e: &toml::de::Error, text: &str) -> String {
let line = e.span().map(|span| text[..span.start.min(text.len())].matches('\n').count() + 1);
format_message("TOML", line)
}
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
/// A single secret extracted from a file.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SecretEntry {
/// The key name (e.g. `"DATABASE_URL"`, `"spring.datasource.password"`).
pub key: String,
/// The secret value.
pub value: String,
/// Which file the entry came from.
pub source: PathBuf,
}
/// Shortest number kept as a secret. A number under a key that looks secret is often
/// a setting (`CACHE_KEY_TTL: 3600`), and masking `3600` in every output does more harm
/// than it prevents: a secret number that short is guessed anyway. Quoted values keep
/// the general minimum of the manifest.
const MIN_NUMBER_LEN: usize = 6;
/// Supported secret-file formats.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FileFormat {
/// `.env` / dotenv files.
Env,
/// TOML files (e.g. `Secrets.toml`).
Toml,
/// JSON files.
Json,
/// YAML files.
Yaml,
/// Python-style assignments: `KEY = "value"` or `KEY = 'value'`.
PythonAssignments,
/// Java `.properties` files: `key=value` or `key: value`.
Properties,
}
impl FileFormat {
/// Guess format from file extension/name.
pub fn from_path(path: &Path) -> Option<Self> {
let name = path.file_name()?.to_str()?;
let ext = path.extension().and_then(|e| e.to_str());
// .env, .env.local, .env.production, etc.
if name.starts_with(".env") || name.ends_with(".env") {
return Some(Self::Env);
}
match ext {
Some("toml") => Some(Self::Toml),
Some("json") => Some(Self::Json),
Some("yaml" | "yml") => Some(Self::Yaml),
Some("py") => Some(Self::PythonAssignments),
Some("properties") => Some(Self::Properties),
// .key, .pem, etc. are binary/opaque — not parseable as key-value.
_ => None,
}
}
/// Parse from the `format` string used in `.botsecrets` `[[file]]` overrides.
pub fn from_hint(hint: &str) -> Option<Self> {
match hint {
"env" | "dotenv" => Some(Self::Env),
"toml" => Some(Self::Toml),
"json" => Some(Self::Json),
"yaml" | "yml" => Some(Self::Yaml),
"python-assignments" | "python" => Some(Self::PythonAssignments),
"properties" | "java-properties" => Some(Self::Properties),
_ => None,
}
}
}
// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------
/// Parse a secret file and extract key-value entries.
///
/// If `format` is `None`, auto-detects from path extension.
/// If `key_filter` is `Some`, only entries whose keys match at least one
/// glob pattern are returned.
pub fn parse_secret_file(
path: &Path,
format: Option<FileFormat>,
key_filter: Option<&[String]>,
) -> Result<Vec<SecretEntry>, ParseError> {
let content = std::fs::read_to_string(path).map_err(|e| ParseError::Io {
path: path.to_path_buf(),
source: e,
})?;
let fmt = format
.or_else(|| FileFormat::from_path(path))
.ok_or_else(|| ParseError::Format {
path: path.to_path_buf(),
message: "cannot determine file format".into(),
})?;
let entries = parse_content(&content, fmt, path)?;
match key_filter {
Some(keys) => Ok(filter_entries(entries, keys)),
None => Ok(entries),
}
}
/// Parse content string without reading from disk (useful for testing).
pub fn parse_content(
content: &str,
format: FileFormat,
source: &Path,
) -> Result<Vec<SecretEntry>, ParseError> {
match format {
FileFormat::Env => parse_env(content, source),
FileFormat::Toml => parse_toml(content, source),
FileFormat::Json => parse_json(content, source),
FileFormat::Yaml => parse_yaml(content, source),
FileFormat::PythonAssignments => parse_python_assignments(content, source),
FileFormat::Properties => parse_properties(content, source),
}
}
// ---------------------------------------------------------------------------
// Format parsers
// ---------------------------------------------------------------------------
/// Parse `.env` / dotenv files.
///
/// Supports `KEY=VALUE`, `KEY="VALUE"`, `KEY='VALUE'`, quoted values over several
/// lines, a comment after a value and the `export` prefix. Comments (`#`) and empty
/// lines are skipped.
fn parse_env(content: &str, source: &Path) -> Result<Vec<SecretEntry>, ParseError> {
let mut entries = Vec::new();
let lines: Vec<&str> = content.lines().collect();
let mut i = 0;
while i < lines.len() {
let trimmed = lines[i].trim();
i += 1;
// Skip blank lines and comments.
if trimmed.is_empty() || trimmed.starts_with('#') {
continue;
}
// Strip optional `export ` prefix.
let trimmed = trimmed
.strip_prefix("export ")
.or_else(|| trimmed.strip_prefix("export\t"))
.unwrap_or(trimmed);
// Split on first `=`.
let Some((key, raw_value)) = trimmed.split_once('=') else {
continue;
};
let key = key.trim().to_string();
if key.is_empty() {
continue;
}
let raw_value = raw_value.trim();
let (value, raw) = match quoted_env_value(raw_value, &lines[i..]) {
Some(quoted) => {
i += quoted.extra_lines;
let value = if quoted.quote == '"' { unescape(&quoted.inner) } else { quoted.inner.clone() };
(value, quoted.inner)
}
None => {
let raw = strip_env_comment(raw_value).to_string();
(unescape_shell_word(&raw), raw)
}
};
push_spellings(&mut entries, &key, value, raw, source);
}
Ok(entries)
}
/// A quoted `.env` value: the text between the quotes, as written.
struct QuotedEnvValue {
quote: char,
inner: String,
/// Lines used after the one holding the key.
extra_lines: usize,
}
/// The quoted value starting `raw`, closed on this line or on a later one.
///
/// The closing quote is one that only a comment or nothing follows, so `"a"b"` holds
/// `a"b`. A value running over lines closes at the first quote on a later line, and
/// when more text follows that quote there is no such value: an opening quote nobody
/// closed must not swallow `NEXT="value"` below it.
fn quoted_env_value(raw: &str, following: &[&str]) -> Option<QuotedEnvValue> {
let quote = raw.chars().next().filter(|c| matches!(c, '"' | '\''))?;
let body = &raw[1..];
let on_line = quote_positions(body, quote);
if let Some(&end) = on_line.iter().find(|&&end| ends_env_value(&body[end + 1..])) {
return Some(QuotedEnvValue { quote, inner: body[..end].to_string(), extra_lines: 0 });
}
if !on_line.is_empty() {
return None;
}
let mut inner = body.to_string();
for (n, line) in following.iter().enumerate() {
inner.push('\n');
if let Some(&end) = quote_positions(line, quote).first() {
if !ends_env_value(&line[end + 1..]) {
return None;
}
inner.push_str(&line[..end]);
return Some(QuotedEnvValue { quote, inner, extra_lines: n + 1 });
}
inner.push_str(line);
}
None
}
/// Byte offsets of the closing-capable quotes in `text`. A backslash escapes in double
/// quotes and is plain text in single quotes.
fn quote_positions(text: &str, quote: char) -> Vec<usize> {
let mut positions = Vec::new();
let mut chars = text.char_indices();
while let Some((at, c)) = chars.next() {
if c == '\\' && quote == '"' {
chars.next();
} else if c == quote {
positions.push(at);
}
}
positions
}
/// Whether what follows a closing quote leaves the value complete.
fn ends_env_value(rest: &str) -> bool {
let rest = rest.trim_start();
rest.is_empty() || rest.starts_with('#')
}
/// An unquoted value without its inline comment.
fn strip_env_comment(raw: &str) -> &str {
let comment = raw
.char_indices()
.find(|&(at, c)| c == '#' && raw[..at].ends_with([' ', '\t']))
.map(|(at, _)| at);
match comment {
Some(at) => raw[..at].trim_end(),
None => raw,
}
}
/// Backslash escapes as dotenv loaders and most languages read them. An unknown
/// escape stays as written.
fn unescape(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut chars = text.chars().peekable();
while let Some(c) = chars.next() {
if c != '\\' {
out.push(c);
continue;
}
match chars.next() {
Some('n') => out.push('\n'),
Some('t') => out.push('\t'),
Some('r') => out.push('\r'),
Some('u') => {
let hex: String = chars.clone().take(4).collect();
match u32::from_str_radix(&hex, 16).ok().filter(|_| hex.len() == 4).and_then(char::from_u32) {
Some(decoded) => {
out.push(decoded);
chars.nth(3);
}
None => out.push_str("\\u"),
}
}
Some(other) if other.is_ascii_punctuation() || other == ' ' => out.push(other),
Some(other) => {
out.push('\\');
out.push(other);
}
None => out.push('\\'),
}
}
out
}
/// An unquoted word as a shell reads it: a backslash keeps the next character.
fn unescape_shell_word(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut chars = text.chars();
while let Some(c) = chars.next() {
if c == '\\' {
out.extend(chars.next());
} else {
out.push(c);
}
}
out
}
/// Push `value`, and `raw` as a second entry of the same key if the file spells it
/// differently.
fn push_spellings(entries: &mut Vec<SecretEntry>, key: &str, value: String, raw: String, source: &Path) {
let differs = raw != value;
entries.push(SecretEntry { key: key.to_string(), value, source: source.to_path_buf() });
if differs {
entries.push(SecretEntry { key: key.to_string(), value: raw, source: source.to_path_buf() });
}
}
// ---------------------------------------------------------------------------
// The spellings a file gives its values
// ---------------------------------------------------------------------------
/// Adds an entry per `(decoded, raw)` token of the file whose decoded text is the value
/// of an entry. The parsers of JSON, TOML and YAML keep no source text, so the file is
/// scanned for its literals again: a literal only counts when it decodes to a known value,
/// which is why a scan that misreads a corner of the format finds nothing rather than
/// something wrong.
fn add_file_spellings(entries: &mut Vec<SecretEntry>, tokens: Vec<(String, String)>) {
let mut by_decoded: HashMap<String, Vec<String>> = HashMap::new();
for (decoded, raw) in tokens {
let raws = by_decoded.entry(decoded).or_default();
if !raws.contains(&raw) {
raws.push(raw);
}
}
add_spellings_by(entries, |value| by_decoded.get(value).map(Vec::as_slice));
}
/// Appends, for each entry, the raws that `spellings` gives for its value (those that
/// differ from it), once per key and raw.
fn add_spellings_by<'a>(entries: &mut Vec<SecretEntry>, spellings: impl Fn(&str) -> Option<&'a [String]>) {
let mut seen: HashSet<(String, String)> = HashSet::new();
let mut added = Vec::new();
for entry in entries.iter() {
for raw in spellings(&entry.value).unwrap_or_default() {
if *raw != entry.value && seen.insert((entry.key.clone(), raw.clone())) {
added.push(SecretEntry { key: entry.key.clone(), value: raw.clone(), source: entry.source.clone() });
}
}
}
entries.append(&mut added);
}
/// The string and number literals of a JSON text.
fn json_tokens(content: &str) -> Vec<(String, String)> {
let literal = regex::Regex::new(r#"(?s)"(?:[^"\\]|\\.)*"|-?[0-9][0-9.eE+-]*"#).expect("valid regex");
literal
.find_iter(content)
.filter_map(|m| {
let text = m.as_str();
if text.starts_with('"') {
let decoded: String = serde_json::from_str(text).ok()?;
Some((decoded, text[1..text.len() - 1].to_string()))
} else {
let number: serde_json::Number = serde_json::from_str(text).ok()?;
Some((number.to_string(), text.to_string()))
}
})
.collect()
}
/// The string and number literals of a TOML text. Strings and comments come first in
/// the pattern, so what they hold is not read as a number.
fn toml_tokens(content: &str) -> Vec<(String, String)> {
let literal = regex::Regex::new(
r#"(?s)"""(.*?)"""|'''(.*?)'''|"((?:[^"\\\n]|\\.)*)"|'([^'\n]*)'|#[^\n]*|([-+]?[0-9][0-9a-zA-Z_.+:-]*)"#,
)
.expect("valid regex");
literal
.captures_iter(content)
.filter_map(|caps| {
let whole = caps.get(0)?.as_str();
let inner = (1..=5).find_map(|n| caps.get(n))?.as_str();
let table: toml::Table = format!("x = {whole}").parse().ok()?;
let decoded = match table.get("x")? {
toml::Value::String(s) => s.clone(),
toml::Value::Integer(n) => n.to_string(),
toml::Value::Float(n) => n.to_string(),
_ => return None,
};
// TOML drops a newline right after the opening delimiter.
Some((decoded, inner.strip_prefix('\n').unwrap_or(inner).to_string()))
})
.collect()
}
/// The quoted strings and plain numbers of a YAML text, each where a value can begin,
/// so an apostrophe in plain text opens nothing.
fn yaml_tokens(content: &str) -> Vec<(String, String)> {
let literal = regex::Regex::new(
r#"(?m)(?:^|[ \t])#[^\n]*|(?:^[ \t]*|[:\-][ \t]+|[\[,{][ \t]*)("(?:[^"\\]|\\[\s\S])*"|'(?:[^']|'')*'|[-+.0-9][-+._0-9a-zA-Z]*)"#,
)
.expect("valid regex");
literal
.captures_iter(content)
.filter_map(|caps| {
let text = caps.get(1)?.as_str();
match serde_yaml::from_str::<serde_yaml::Value>(text).ok()? {
serde_yaml::Value::String(s) if text.starts_with(['"', '\'']) => {
Some((s, text[1..text.len() - 1].to_string()))
}
serde_yaml::Value::Number(n) => Some((n.to_string(), text.to_string())),
_ => None,
}
})
.collect()
}
/// Adds the file's text of each YAML value that runs over lines (a `|` or `>` block, a
/// plain scalar that continues below its key). Folding turns line ends into spaces and
/// indentation goes, so the decoded value is found again by its text without whitespace.
fn add_yaml_block_spellings(entries: &mut Vec<SecretEntry>, content: &str) {
fn squeezed(text: &str) -> String {
text.chars().filter(|c| !c.is_whitespace()).collect()
}
fn indent(line: &str) -> usize {
line.len() - line.trim_start_matches(' ').len()
}
let lines: Vec<&str> = content.lines().collect();
let mut blocks: Vec<(String, String)> = Vec::new();
for (i, line) in lines.iter().enumerate() {
let below: Vec<&str> = {
let taken: Vec<&str> =
lines[i + 1..].iter().take_while(|l| l.trim().is_empty() || indent(l) > indent(line)).copied().collect();
let end = taken.iter().rposition(|l| !l.trim().is_empty()).map_or(0, |last| last + 1);
taken[..end].to_vec()
};
if below.is_empty() {
continue;
}
// What the key's own line adds to the value: nothing for a block header.
let mut head = line.trim_start();
while let Some(rest) = head.strip_prefix("- ") {
head = rest.trim_start();
}
let head = head.split_once(": ").map_or(head, |(_, rest)| rest).trim();
let head = if head.starts_with(['|', '>']) || head.ends_with(':') { "" } else { head };
let mut raw = head.to_string();
for part in &below {
if !raw.is_empty() {
raw.push('\n');
}
raw.push_str(part);
}
blocks.push((squeezed(&raw), raw));
}
let mut by_text: HashMap<String, Vec<String>> = HashMap::new();
for (text, raw) in blocks {
by_text.entry(text).or_default().push(raw);
}
add_spellings_by(entries, |value| by_text.get(&squeezed(value)).map(Vec::as_slice));
}
/// A number as a secret entry, unless it is too short to be one: [`MIN_NUMBER_LEN`].
fn push_number(entries: &mut Vec<SecretEntry>, key: &str, text: String, source: &Path) {
if !key.is_empty() && text.len() >= MIN_NUMBER_LEN {
entries.push(SecretEntry { key: key.to_string(), value: text, source: source.to_path_buf() });
}
}
/// Parse TOML files. Nested tables are flattened with dot separators.
/// String and number values are extracted.
fn parse_toml(content: &str, source: &Path) -> Result<Vec<SecretEntry>, ParseError> {
let table: toml::Value = content.parse().map_err(|e: toml::de::Error| ParseError::Format {
path: source.to_path_buf(),
message: toml_message(&e, content),
})?;
let mut entries = Vec::new();
flatten_toml_value(&table, "", source, &mut entries);
add_file_spellings(&mut entries, toml_tokens(content));
Ok(entries)
}
fn flatten_toml_value(
value: &toml::Value,
prefix: &str,
source: &Path,
entries: &mut Vec<SecretEntry>,
) {
match value {
toml::Value::String(s) => {
if !prefix.is_empty() {
entries.push(SecretEntry {
key: prefix.to_string(),
value: s.clone(),
source: source.to_path_buf(),
});
}
}
toml::Value::Table(map) => {
for (k, v) in map {
let key = if prefix.is_empty() {
k.clone()
} else {
format!("{prefix}.{k}")
};
flatten_toml_value(v, &key, source, entries);
}
}
toml::Value::Array(arr) => {
for (i, v) in arr.iter().enumerate() {
let key = if prefix.is_empty() {
i.to_string()
} else {
format!("{prefix}.{i}")
};
flatten_toml_value(v, &key, source, entries);
}
}
toml::Value::Integer(n) => push_number(entries, prefix, n.to_string(), source),
toml::Value::Float(n) => push_number(entries, prefix, n.to_string(), source),
// Boolean, Datetime — skip, not secrets.
_ => {}
}
}
/// Parse JSON files. Nested objects are flattened with dot separators.
/// Arrays use numeric indices. String and number values are extracted.
fn parse_json(content: &str, source: &Path) -> Result<Vec<SecretEntry>, ParseError> {
let value: serde_json::Value =
serde_json::from_str(content).map_err(|e| ParseError::Format {
path: source.to_path_buf(),
message: format_message("JSON", Some(e.line())),
})?;
let mut entries = Vec::new();
flatten_json_value(&value, "", source, &mut entries);
add_file_spellings(&mut entries, json_tokens(content));
Ok(entries)
}
fn flatten_json_value(
value: &serde_json::Value,
prefix: &str,
source: &Path,
entries: &mut Vec<SecretEntry>,
) {
match value {
serde_json::Value::String(s) => {
if !prefix.is_empty() {
entries.push(SecretEntry {
key: prefix.to_string(),
value: s.clone(),
source: source.to_path_buf(),
});
}
}
serde_json::Value::Object(map) => {
for (k, v) in map {
let key = if prefix.is_empty() {
k.clone()
} else {
format!("{prefix}.{k}")
};
flatten_json_value(v, &key, source, entries);
}
}
serde_json::Value::Array(arr) => {
for (i, v) in arr.iter().enumerate() {
let key = if prefix.is_empty() {
i.to_string()
} else {
format!("{prefix}.{i}")
};
flatten_json_value(v, &key, source, entries);
}
}
serde_json::Value::Number(n) => push_number(entries, prefix, n.to_string(), source),
// Bool, Null — skip.
_ => {}
}
}
/// Parse YAML files. Nested mappings are flattened with dot separators.
/// String and number values are extracted.
fn parse_yaml(content: &str, source: &Path) -> Result<Vec<SecretEntry>, ParseError> {
let value: serde_yaml::Value =
serde_yaml::from_str(content).map_err(|e| ParseError::Format {
path: source.to_path_buf(),
message: format_message("YAML", e.location().map(|l| l.line())),
})?;
let mut entries = Vec::new();
flatten_yaml_value(&value, "", source, &mut entries);
add_file_spellings(&mut entries, yaml_tokens(content));
add_yaml_block_spellings(&mut entries, content);
Ok(entries)
}
fn flatten_yaml_value(
value: &serde_yaml::Value,
prefix: &str,
source: &Path,
entries: &mut Vec<SecretEntry>,
) {
match value {
serde_yaml::Value::String(s) => {
if !prefix.is_empty() {
entries.push(SecretEntry {
key: prefix.to_string(),
value: s.clone(),
source: source.to_path_buf(),
});
}
}
serde_yaml::Value::Mapping(map) => {
for (k, v) in map {
let k_str = match k {
serde_yaml::Value::String(s) => s.clone(),
other => format!("{other:?}"),
};
let key = if prefix.is_empty() {
k_str
} else {
format!("{prefix}.{k_str}")
};
flatten_yaml_value(v, &key, source, entries);
}
}
serde_yaml::Value::Sequence(arr) => {
for (i, v) in arr.iter().enumerate() {
let key = if prefix.is_empty() {
i.to_string()
} else {
format!("{prefix}.{i}")
};
flatten_yaml_value(v, &key, source, entries);
}
}
serde_yaml::Value::Number(n) => push_number(entries, prefix, n.to_string(), source),
// Bool, Null, Tagged — skip.
_ => {}
}
}
/// Parse Python-style assignment lines: `KEY = "value"` or `KEY = 'value'`.
///
/// This is heuristic — lines that don't match the pattern are silently skipped.
fn parse_python_assignments(
content: &str,
source: &Path,
) -> Result<Vec<SecretEntry>, ParseError> {
let re = regex::Regex::new(r#"(?i)^([A-Z_][A-Z0-9_]*)\s*=\s*['"](.+?)['"]\s*$"#)
.expect("valid regex");
let mut entries = Vec::new();
for line in content.lines() {
let trimmed = line.trim();
if trimmed.is_empty() || trimmed.starts_with('#') {
continue;
}
if let Some(caps) = re.captures(trimmed) {
// The file's text first: a Python value is kept as written.
push_spellings(&mut entries, &caps[1], caps[2].to_string(), unescape(&caps[2]), source);
}
}
Ok(entries)
}
/// Parse Java `.properties` files.
///
/// Supports `key=value`, `key: value`, `key value` (space separator).
/// Lines starting with `#` or `!` are comments. Continuation lines ending
/// with `\` are joined.
fn parse_properties(content: &str, source: &Path) -> Result<Vec<SecretEntry>, ParseError> {
let mut entries = Vec::new();
let mut lines = content.lines().peekable();
while let Some(line) = lines.next() {
let trimmed = line.trim();
// Skip blank lines and comments.
if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with('!') {
continue;
}
// Handle continuation lines (trailing `\`).
let mut logical_line = String::new();
let mut physical = Vec::new();
let mut current = trimmed.to_string();
while current.ends_with('\\') {
// Remove trailing backslash and append next line.
logical_line.push_str(&current[..current.len() - 1]);
physical.push(current[..current.len() - 1].to_string());
current = lines
.next()
.map(|l| l.trim_start().to_string())
.unwrap_or_default();
}
logical_line.push_str(&current);
// Split on first `=`, `:`, or whitespace.
let (key, value) = split_property_line(&logical_line);
if key.is_empty() {
continue;
}
push_spellings(&mut entries, &key, value.clone(), unescape(&value), source);
// The file holds a continued value in pieces, one per line.
if !physical.is_empty() {
physical.push(current);
physical[0] = split_property_line(&physical[0]).1;
entries.push(SecretEntry { key, value: physical.join("\n"), source: source.to_path_buf() });
}
}
Ok(entries)
}
/// Split a logical properties line into (key, value).
/// Recognises `=`, `:`, or whitespace as the separator.
fn split_property_line(line: &str) -> (String, String) {
// Find the first unescaped separator.
let mut i = 0;
let bytes = line.as_bytes();
let len = bytes.len();
while i < len {
// Skip escaped characters.
if bytes[i] == b'\\' {
i += 2;
continue;
}
if bytes[i] == b'=' || bytes[i] == b':' {
let key = line[..i].trim().to_string();
let value = line[i + 1..].trim().to_string();
return (key, value);
}
if bytes[i] == b' ' || bytes[i] == b'\t' {
let key = line[..i].trim().to_string();
let value = line[i..].trim().to_string();
return (key, value);
}
i += 1;
}
// No separator found — the entire line is a key with an empty value.
(line.trim().to_string(), String::new())
}
// ---------------------------------------------------------------------------
// Key filtering
// ---------------------------------------------------------------------------
/// Filter entries by glob patterns (case-insensitive).
fn filter_entries(entries: Vec<SecretEntry>, patterns: &[String]) -> Vec<SecretEntry> {
// Pre-compile matchers.
let matchers: Vec<_> = patterns
.iter()
.filter_map(|p| {
Glob::new(&p.to_ascii_uppercase())
.ok()
.map(|g| g.compile_matcher())
})
.collect();
if matchers.is_empty() {
return Vec::new();
}
entries
.into_iter()
.filter(|entry| {
let upper = entry.key.to_ascii_uppercase();
matchers.iter().any(|m| m.is_match(&upper))
})
.collect()
}