Skip to main content

halephant_core/auth/
pgpass.rs

1use std::path::Path;
2
3/// Parsed `.pgpass` file entries for upstream password lookup.
4pub struct Pgpass {
5    entries: Vec<Entry>,
6}
7
8struct Entry {
9    hostname: Pattern,
10    port: Pattern,
11    database: Pattern,
12    username: Pattern,
13    password: String,
14}
15
16enum Pattern {
17    Any,
18    Exact(String),
19}
20
21impl Pattern {
22    fn parse(s: &str) -> Self {
23        if s == "*" {
24            Self::Any
25        } else {
26            Self::Exact(s.to_owned())
27        }
28    }
29
30    fn matches(&self, value: &str) -> bool {
31        match self {
32            Self::Any => true,
33            Self::Exact(v) => v == value,
34        }
35    }
36}
37
38impl Pgpass {
39    /// Load and parse a `.pgpass` file. Returns an empty set on I/O errors
40    /// (matching PostgreSQL behavior — a missing file is not fatal).
41    pub fn load(path: &Path) -> Self {
42        match std::fs::read_to_string(path) {
43            Ok(content) => Self::parse(&content),
44            Err(_) => Self {
45                entries: Vec::new(),
46            },
47        }
48    }
49
50    /// Parse `.pgpass` content from a string.
51    pub fn parse(content: &str) -> Self {
52        // Trim each line before the blank/comment check so a
53        // whitespace-only line like "   " is dropped here rather
54        // than deep inside `parse_line`'s field-count check. Today
55        // both paths happen to reject the line, but making the
56        // intent explicit at the filter step means a future
57        // tightening of `parse_line` (for example to return an
58        // error instead of `None` on malformed input) will not
59        // regress on whitespace handling.
60        let entries = content
61            .lines()
62            .filter(|line| {
63                let trimmed = line.trim();
64                !trimmed.is_empty() && !trimmed.starts_with('#')
65            })
66            .filter_map(parse_line)
67            .collect();
68        Self { entries }
69    }
70
71    /// Look up a password for the given connection parameters. Returns the
72    /// password from the first matching entry, or `None` if no entry matches.
73    pub fn lookup(
74        &self,
75        hostname: &str,
76        port: &str,
77        database: &str,
78        username: &str,
79    ) -> Option<&str> {
80        self.entries
81            .iter()
82            .find(|e| {
83                e.hostname.matches(hostname)
84                    && e.port.matches(port)
85                    && e.database.matches(database)
86                    && e.username.matches(username)
87            })
88            .map(|e| e.password.as_str())
89    }
90
91    /// Look up a password by `host:port` address (or bracketed IPv6).
92    /// Convenience wrapper around [`Pgpass::lookup`] that handles the
93    /// host/port split so call sites don't repeat the same three-line
94    /// dance.
95    pub fn lookup_addr(&self, addr: &str, database: &str, username: &str) -> Option<&str> {
96        let (host, port) = crate::addr::split_addr::split_host_port(addr);
97        self.lookup(host, port, database, username)
98    }
99
100    /// Returns true if no entries are loaded.
101    pub fn is_empty(&self) -> bool {
102        self.entries.is_empty()
103    }
104}
105
106/// Parse a single `.pgpass` line into an entry. The format is:
107/// `hostname:port:database:username:password`
108///
109/// Backslash escapes `:` and `\` within fields. The password field is
110/// everything after the fourth unescaped colon (including colons).
111fn parse_line(line: &str) -> Option<Entry> {
112    let mut fields = Vec::with_capacity(5);
113    let mut current = String::new();
114    let chars = line.chars();
115    let mut escaped = false;
116
117    for ch in chars {
118        if escaped {
119            current.push(ch);
120            escaped = false;
121        } else if ch == '\\' {
122            escaped = true;
123        } else if ch == ':' && fields.len() < 4 {
124            fields.push(std::mem::take(&mut current));
125        } else {
126            current.push(ch);
127        }
128    }
129    fields.push(current); // password (5th field)
130
131    if fields.len() != 5 {
132        return None;
133    }
134
135    Some(Entry {
136        hostname: Pattern::parse(&fields[0]),
137        port: Pattern::parse(&fields[1]),
138        database: Pattern::parse(&fields[2]),
139        username: Pattern::parse(&fields[3]),
140        password: fields[4].clone(),
141    })
142}