Skip to main content

rightkit_browser/
cookies.rs

1//! Netscape `cookies.txt` parsing and the CDP mapping that imports the cookies into the
2//! current browser profile ([`BrowserPage::import_cookies`](crate::BrowserPage::import_cookies)).
3//!
4//! Cookie values are credentials. They are held in a redacting wrapper, never appear in
5//! `Debug` output, never appear in a [`CookieParseError`] (errors carry a line number only) and
6//! are scrubbed from the error text of a failed import. This module filters nothing by domain
7//! and asks for no consent: which cookies reach the browser, and whether the user agreed, is
8//! the caller's decision.
9
10use chromiumoxide::cdp::browser_protocol::network::{CookieParam, TimeSinceEpoch};
11use std::fmt;
12use thiserror::Error;
13
14/// Largest `cookies.txt` text [`parse_netscape`] accepts, in bytes (4 MiB).
15pub const MAX_COOKIES_FILE_BYTES: usize = 4 * 1024 * 1024;
16/// Most cookies [`parse_netscape`] returns and
17/// [`BrowserPage::import_cookies`](crate::BrowserPage::import_cookies) sets in one call.
18pub const MAX_COOKIES: usize = 10_000;
19
20/// A cookie value. `Debug` prints a fixed placeholder; there is no `Display` or `Serialize`.
21#[derive(Clone, PartialEq, Eq)]
22struct SecretValue(String);
23
24impl fmt::Debug for SecretValue {
25    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26        f.write_str("<redacted>")
27    }
28}
29
30/// One cookie from a Netscape `cookies.txt` file.
31///
32/// `Debug` prints every field except the value, which is shown as `<redacted>`. Read the value
33/// with [`NetscapeCookie::value`] only to hand it to the browser.
34#[derive(Clone, PartialEq, Eq)]
35#[non_exhaustive]
36pub struct NetscapeCookie {
37    /// Host, ASCII-lowercased, without a leading dot (see `include_subdomains`).
38    pub domain: String,
39    /// The cookie also matches subdomains (flag column `TRUE`, or a leading dot on the host).
40    pub include_subdomains: bool,
41    /// Cookie path; `/` when the file leaves it empty.
42    pub path: String,
43    pub secure: bool,
44    /// Set by the `#HttpOnly_` host prefix.
45    pub http_only: bool,
46    /// Expiry in seconds since the Unix epoch; `None` is a session cookie (file value `0`).
47    pub expires: Option<i64>,
48    pub name: String,
49    value: SecretValue,
50}
51
52/// A cookie field refused by [`NetscapeCookie::new`] or one of its builder methods. Names the
53/// field only, never its text, because cookie values are secrets.
54#[derive(Clone, Debug, PartialEq, Eq, Error)]
55#[error("the {field} field is empty or malformed")]
56#[non_exhaustive]
57pub struct CookieFieldError {
58    pub field: &'static str,
59}
60
61fn field_error(field: &'static str) -> CookieFieldError {
62    CookieFieldError { field }
63}
64
65/// A host the cookie file can carry: non-empty, no whitespace, control characters, slash,
66/// backslash, `;` or `,`, and not a comment marker.
67pub(crate) fn domain_ok(domain: &str) -> bool {
68    !domain.is_empty()
69        && !domain.starts_with('#')
70        && !domain
71            .chars()
72            .any(|c| c.is_whitespace() || c.is_control() || matches!(c, '/' | '\\' | ';' | ','))
73}
74
75fn path_ok(path: &str) -> bool {
76    path.starts_with('/') && !path.chars().any(|c| c.is_control() || c == ';')
77}
78
79fn name_ok(name: &str) -> bool {
80    !name.is_empty() && !name.chars().any(|c| c.is_control() || c == ';' || c == '=')
81}
82
83fn value_ok(value: &str) -> bool {
84    !value.chars().any(|c| c.is_control())
85}
86
87impl NetscapeCookie {
88    /// The cookie value. A credential: do not log it.
89    pub fn value(&self) -> &str {
90        &self.value.0
91    }
92
93    /// Build a cookie to export (see `CookieExport`, feature `cookie-export`) from a browser's
94    /// cookie store.
95    ///
96    /// `domain` is trimmed and ASCII-lowercased; a leading dot is dropped and turns
97    /// `include_subdomains` on (without one it starts `false`, a host-only cookie). The path
98    /// starts as `/`, `secure` and `http_only` as `false` and the cookie as a session cookie.
99    /// Set the rest with the `with_*` methods. Every field is checked against the same rules
100    /// [`parse_netscape`] applies, so a cookie built here round-trips through the file format.
101    /// The error names the field, never its text.
102    pub fn new(domain: &str, name: &str, value: &str) -> Result<Self, CookieFieldError> {
103        let host = domain.trim();
104        let had_dot = host.starts_with('.');
105        let domain = host.trim_start_matches('.').to_ascii_lowercase();
106        if !domain_ok(&domain) {
107            return Err(field_error("domain"));
108        }
109        if !name_ok(name) {
110            return Err(field_error("name"));
111        }
112        if !value_ok(value) {
113            return Err(field_error("value"));
114        }
115        Ok(Self {
116            domain,
117            include_subdomains: had_dot,
118            path: "/".to_string(),
119            secure: false,
120            http_only: false,
121            expires: None,
122            name: name.to_string(),
123            value: SecretValue(value.to_string()),
124        })
125    }
126
127    /// Match subdomains of the domain (`true`, written with a leading dot) or only the exact host.
128    #[must_use]
129    pub fn with_include_subdomains(mut self, include_subdomains: bool) -> Self {
130        self.include_subdomains = include_subdomains;
131        self
132    }
133
134    /// Set the cookie path. It must start with `/` and hold no control character or `;`.
135    pub fn with_path(mut self, path: &str) -> Result<Self, CookieFieldError> {
136        if !path_ok(path) {
137            return Err(field_error("path"));
138        }
139        self.path = path.to_string();
140        Ok(self)
141    }
142
143    #[must_use]
144    pub fn with_secure(mut self, secure: bool) -> Self {
145        self.secure = secure;
146        self
147    }
148
149    #[must_use]
150    pub fn with_http_only(mut self, http_only: bool) -> Self {
151        self.http_only = http_only;
152        self
153    }
154
155    /// Set the expiry in seconds since the Unix epoch; `None` is a session cookie. Zero or below
156    /// is refused (the file format reserves `0` for a session cookie).
157    pub fn with_expires(mut self, expires: Option<i64>) -> Result<Self, CookieFieldError> {
158        if matches!(expires, Some(e) if e <= 0) {
159            return Err(field_error("expires"));
160        }
161        self.expires = expires;
162        Ok(self)
163    }
164
165    /// The first field the file format cannot carry, if any. The public fields can be changed
166    /// after construction, so an export checks again.
167    #[cfg_attr(not(feature = "cookie-export"), allow(dead_code))]
168    pub(crate) fn invalid_field(&self) -> Option<&'static str> {
169        if !domain_ok(&self.domain) {
170            Some("domain")
171        } else if !path_ok(&self.path) {
172            Some("path")
173        } else if !name_ok(&self.name) {
174            Some("name")
175        } else if !value_ok(&self.value.0) {
176            Some("value")
177        } else if matches!(self.expires, Some(e) if e <= 0) {
178            Some("expires")
179        } else {
180            None
181        }
182    }
183}
184
185impl fmt::Debug for NetscapeCookie {
186    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
187        f.debug_struct("NetscapeCookie")
188            .field("domain", &self.domain)
189            .field("include_subdomains", &self.include_subdomains)
190            .field("path", &self.path)
191            .field("secure", &self.secure)
192            .field("http_only", &self.http_only)
193            .field("expires", &self.expires)
194            .field("name", &self.name)
195            .field("value", &self.value)
196            .finish()
197    }
198}
199
200/// Why [`parse_netscape`] refused its input. Line numbers are 1-based; no variant carries any
201/// text from the file, because cookie values are secrets.
202#[derive(Clone, Debug, PartialEq, Eq, Error)]
203#[non_exhaustive]
204pub enum CookieParseError {
205    #[error("cookies file is {bytes} bytes; the limit is {limit}")]
206    InputTooLarge { bytes: usize, limit: usize },
207    #[error("cookies file holds more than {limit} cookies")]
208    TooManyCookies { limit: usize },
209    #[error("line {line}: expected 7 tab-separated fields, found {found}")]
210    BadFieldCount { line: usize, found: usize },
211    #[error("line {line}: the {field} field must be TRUE or FALSE")]
212    BadFlag { line: usize, field: &'static str },
213    #[error("line {line}: the expiry field must be a non-negative integer")]
214    BadExpires { line: usize },
215    #[error("line {line}: the {field} field is empty or malformed")]
216    BadField { line: usize, field: &'static str },
217}
218
219const HTTP_ONLY_PREFIX: &str = "#HttpOnly_";
220
221fn parse_flag(raw: &str, line: usize, field: &'static str) -> Result<bool, CookieParseError> {
222    if raw.eq_ignore_ascii_case("TRUE") {
223        Ok(true)
224    } else if raw.eq_ignore_ascii_case("FALSE") {
225        Ok(false)
226    } else {
227        Err(CookieParseError::BadFlag { line, field })
228    }
229}
230
231fn bad_field(line: usize, field: &'static str) -> CookieParseError {
232    CookieParseError::BadField { line, field }
233}
234
235/// Parse Netscape `cookies.txt` text.
236///
237/// Each cookie line has seven tab-separated fields: host, include-subdomains flag, path, secure
238/// flag, expiry (Unix seconds, `0` for a session cookie), name, value. Lines starting with `#`
239/// are comments except the `#HttpOnly_` host prefix, which marks the cookie HttpOnly. Blank
240/// lines are skipped and CRLF is accepted. Flags are case-insensitive. Input over
241/// [`MAX_COOKIES_FILE_BYTES`] or more than [`MAX_COOKIES`] cookies is refused.
242pub fn parse_netscape(text: &str) -> Result<Vec<NetscapeCookie>, CookieParseError> {
243    if text.len() > MAX_COOKIES_FILE_BYTES {
244        return Err(CookieParseError::InputTooLarge {
245            bytes: text.len(),
246            limit: MAX_COOKIES_FILE_BYTES,
247        });
248    }
249    let text = text.strip_prefix('\u{feff}').unwrap_or(text);
250    let mut out = Vec::new();
251    for (idx, raw_line) in text.split('\n').enumerate() {
252        let line_no = idx + 1;
253        let line = raw_line.strip_suffix('\r').unwrap_or(raw_line);
254        if line.trim().is_empty() {
255            continue;
256        }
257        let (line, http_only) = match line.strip_prefix(HTTP_ONLY_PREFIX) {
258            Some(rest) => (rest, true),
259            None if line.starts_with('#') => continue,
260            None => (line, false),
261        };
262        let fields: Vec<&str> = line.split('\t').collect();
263        if fields.len() != 7 {
264            return Err(CookieParseError::BadFieldCount {
265                line: line_no,
266                found: fields.len(),
267            });
268        }
269        if out.len() >= MAX_COOKIES {
270            return Err(CookieParseError::TooManyCookies { limit: MAX_COOKIES });
271        }
272        let host = fields[0].trim();
273        let had_dot = host.starts_with('.');
274        let domain = host.trim_start_matches('.').to_ascii_lowercase();
275        if !domain_ok(&domain) {
276            return Err(bad_field(line_no, "domain"));
277        }
278        let flag = parse_flag(fields[1].trim(), line_no, "include-subdomains")?;
279        let path = match fields[2] {
280            "" => "/".to_string(),
281            p if path_ok(p) => p.to_string(),
282            _ => return Err(bad_field(line_no, "path")),
283        };
284        let secure = parse_flag(fields[3].trim(), line_no, "secure")?;
285        let expires = match fields[4].trim().parse::<i64>() {
286            Ok(0) => None,
287            Ok(n) if n > 0 => Some(n),
288            _ => return Err(CookieParseError::BadExpires { line: line_no }),
289        };
290        let name = fields[5];
291        if !name_ok(name) {
292            return Err(bad_field(line_no, "name"));
293        }
294        let value = fields[6];
295        if !value_ok(value) {
296            return Err(bad_field(line_no, "value"));
297        }
298        out.push(NetscapeCookie {
299            domain,
300            include_subdomains: flag || had_dot,
301            path,
302            secure,
303            http_only,
304            expires,
305            name: name.to_string(),
306            value: SecretValue(value.to_string()),
307        });
308    }
309    Ok(out)
310}
311
312/// Map parsed cookies to CDP `Network.CookieParam`s. A subdomain-matching cookie gets a leading
313/// dot on its domain; a host-only cookie gets none. The result holds the values in clear text
314/// and its `Debug` prints them: pass it straight to the browser and never format it.
315pub(crate) fn to_cdp_params(cookies: &[NetscapeCookie]) -> Vec<CookieParam> {
316    cookies
317        .iter()
318        .map(|c| {
319            let mut p = CookieParam::new(c.name.clone(), c.value().to_string());
320            p.domain = Some(if c.include_subdomains {
321                format!(".{}", c.domain)
322            } else {
323                c.domain.clone()
324            });
325            p.path = Some(c.path.clone());
326            p.secure = Some(c.secure);
327            p.http_only = Some(c.http_only);
328            p.expires = c.expires.map(|e| TimeSinceEpoch::new(e as f64));
329            p
330        })
331        .collect()
332}
333
334/// Admission detail for an import: the cookie count and the distinct domains. Names and values
335/// are left out.
336pub(crate) fn admission_detail(cookies: &[NetscapeCookie]) -> String {
337    let mut domains: Vec<&str> = cookies.iter().map(|c| c.domain.as_str()).collect();
338    domains.sort_unstable();
339    domains.dedup();
340    format!(
341        "import_cookies count={} domains={}",
342        cookies.len(),
343        domains.join(",")
344    )
345}
346
347/// Replace every cookie value of four or more characters found in `message` with
348/// `[redacted]`, so an error text from the browser cannot echo a credential.
349pub(crate) fn scrub(message: &str, cookies: &[NetscapeCookie]) -> String {
350    let mut out = message.to_string();
351    for c in cookies {
352        let v = c.value();
353        if v.chars().count() >= 4 {
354            out = out.replace(v, "[redacted]");
355        }
356    }
357    out
358}