Cotton code
285 lines · 11.2 KB · RustRaw
//! Passwords handed over by another app, read into the logins they carry.//!//! ```text//! read_csv (text) → PasswordImport { format, passwords[], skipped[], unnamed[] }//! ```//!//! **One rule for every exporter**: the formats are data//! (`password_csv_formats.json`): Apple Passwords, 1Password, Bitwarden,//! Chrome, Dashlane, LastPass and Firefox, each the header columns that//! identify it (`requires`) and which columns hold the title, address, user//! name, password, notes, one-time code, favourite and made date. The header//! is sniffed: of the formats whose required columns the first line holds//! (any case, any order), the one requiring the most wins, so LastPass's//! `url,username,password,extra,name,grouping` is never read as Chrome's//! `name,url,username,password`. A row a format marks as a secure note//! (Bitwarden `type=note`, LastPass `url=http://sn`) lands as a note.//! The file is RFC 4180: fields quoted with `"`, a quote doubled inside one,//! line breaks inside a quoted field, CRLF or LF rows, a UTF-8 byte order mark//! allowed. A header column this reader does not name is reported by name in//! `unnamed`, never by value.//!//! The Credential Exchange half (a `basic-auth` credential, CXF 1.0 §3.3.2) is//! [`super::cxf`]'s, landing in the same [`ImportedPassword`].//!//! The header is the file's frame: a file without it refuses whole//! ([`ImportError`]). A row that is broken (no password, a field too long for//! its column) lands in `skipped` with words and the rest is still read.//! **Pure**; the values live in the returned payloads and nowhere else.use crate::vault::columns::{fits, shorten, NAME_MAX, SITE_MAX, USERNAME_MAX};use crate::vault::payload::SecretPayload;/// One login an import carried, ready to be sealed into a `secret` row.#[derive(Debug, Clone, PartialEq, Eq)]pub struct ImportedPassword {    /// The row's `name`: the title, or the site when the title is blank.    pub name: String,    /// The row's `site`: the host of the address it is used at.    pub site: Option<String>,    pub username: Option<String>,    /// What is sealed: `{kind: login, password, notes?, totp?}`.    pub payload: SecretPayload,    /// When it was made at the exporter, UNIX seconds, when it says.    pub created_at: Option<u64>,    /// The exporter marked it a favourite.    pub favourite: bool,}/// Something in an import that was not imported, and why.#[derive(Debug, Clone, PartialEq, Eq)]pub struct Skipped {    /// The row's title, or empty when it has none.    pub title: String,    pub reason: String,}/// An import, read.#[derive(Debug, Default)]pub struct PasswordImport {    /// Which exporter the header says: `apple`, `1password`, `bitwarden`, `chrome`, `dashlane`, `lastpass`, `firefox`.    pub format: &'static str,    pub passwords: Vec<ImportedPassword>,    pub skipped: Vec<Skipped>,    /// Header columns the reader does not name, by name.    pub unnamed: Vec<String>,}/// Why a whole import was refused, in words.#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]pub enum ImportError {    #[error("this is not a Passwords export: {0}")]    NotAnExport(String),}/// The exporters' CSV shapes, as data.pub const FORMATS: &str = include_str!("password_csv_formats.json");/// One exporter's CSV shape.#[derive(Debug, Clone, serde::Deserialize)]#[serde(deny_unknown_fields)]pub struct CsvFormat {    pub id: String,    pub name: String,    pub requires: Vec<String>,    /// What each column of a login is called here, first present wins.    pub fields: std::collections::BTreeMap<String, Vec<String>>,    #[serde(default)]    pub note_when: Option<NoteWhen>,}/// The column and value that mark a row a secure note.#[derive(Debug, Clone, serde::Deserialize)]#[serde(deny_unknown_fields)]pub struct NoteWhen {    pub column: String,    pub equals: String,}#[derive(Debug, serde::Deserialize)]#[serde(deny_unknown_fields)]struct Formats {    formats: Vec<CsvFormat>,    yes: Vec<String>,}fn formats() -> &'static Formats {    static READ: std::sync::OnceLock<Formats> = std::sync::OnceLock::new();    READ.get_or_init(|| serde_json::from_str(FORMATS).expect("the shipped CSV formats read"))}/// Every exporter the reader knows, in the file's order.pub fn csv_formats() -> &'static [CsvFormat] {    &formats().formats}/// The format a header names: of those whose required columns it holds, the/// one requiring the most.pub fn sniff(header: &[String]) -> Option<&'static CsvFormat> {    csv_formats()        .iter()        .filter(|format| format.requires.iter().all(|column| header.contains(column)))        .max_by_key(|format| format.requires.len())}/// The host of an address, lower case: `https://Mail.Example.test/login` →/// `mail.example.test`. A bare host is read as one; text that is no address/// is kept as written, so nothing typed is lost.pub fn site_of(address: &str) -> Option<String> {    let address = address.trim();    if address.is_empty() {        return None;    }    let parsed = url::Url::parse(address).or_else(|_| url::Url::parse(&format!("https://{address}")));    match parsed.ok().and_then(|url| url.host_str().map(str::to_lowercase)) {        Some(host) if !host.is_empty() => Some(host),        _ => Some(address.to_string()),    }}/// One login, its plain columns held to their lengths. `Err` is the words a/// skip says.pub fn login(    title: &str,    address: Option<&str>,    username: Option<&str>,    password: &str,    notes: Option<&str>,    totp: Option<&str>,    created_at: Option<u64>,) -> Result<ImportedPassword, String> {    if password.is_empty() {        return Err("it has no password".to_string());    }    let present = |value: Option<&str>| value.map(str::trim).filter(|value| !value.is_empty()).map(str::to_string);    let site = address.and_then(site_of);    if let Some(site) = &site {        if !fits(site, SITE_MAX) {            return Err(format!("its address is longer than {SITE_MAX} characters"));        }    }    let username = present(username);    if let Some(username) = &username {        if !fits(username, USERNAME_MAX) {            return Err(format!("its user name is longer than {USERNAME_MAX} characters"));        }    }    let shown = title.trim();    let name = if shown.is_empty() { site.clone().or_else(|| username.clone()).unwrap_or_else(|| "Login".to_string()) } else { shown.to_string() };    Ok(ImportedPassword {        name: shorten(&name, NAME_MAX),        site,        username,        payload: SecretPayload::Login { password: password.to_string(), notes: present(notes), totp: present(totp), urls: None },        created_at,        favourite: false,    })}/// Read a password manager's CSV export into its logins and notes.pub fn read_csv(text: &str) -> Result<PasswordImport, ImportError> {    let text = text.strip_prefix('\u{feff}').unwrap_or(text);    let rows = records(text).map_err(ImportError::NotAnExport)?;    let mut rows = rows.into_iter();    let header = rows.next().ok_or_else(|| ImportError::NotAnExport("the file is empty".to_string()))?;    let named: Vec<String> = header.iter().map(|name| name.trim().to_lowercase()).collect();    let format = sniff(&named).ok_or_else(|| {        let names: Vec<&str> = csv_formats().iter().map(|format| format.name.as_str()).collect();        ImportError::NotAnExport(format!("its first line is not the header of an export from {}", names.join(", ")))    })?;    let read_columns: std::collections::HashSet<&str> =        format.fields.values().flatten().map(String::as_str).chain(format.requires.iter().map(String::as_str)).chain(format.note_when.iter().map(|when| when.column.as_str())).collect();    let at = |column: &str| named.iter().position(|name| name == column);    let mut out = PasswordImport { format: format.id.as_str(), ..Default::default() };    for (index, name) in named.iter().enumerate() {        if !read_columns.contains(name.as_str()) {            out.unnamed.push(header[index].trim().to_string());        }    }    let yes = &formats().yes;    for row in rows {        if row.iter().all(|field| field.trim().is_empty()) {            continue;        }        let raw = |column: &str| at(column).and_then(|index| row.get(index)).map(String::as_str);        let field = |slot: &str| -> Option<&str> {            format.fields.get(slot)?.iter().filter_map(|column| raw(column)).find(|value| !value.trim().is_empty())        };        let title = field("title").unwrap_or("");        let is_note = format.note_when.as_ref().is_some_and(|when| raw(&when.column).is_some_and(|value| value.trim().eq_ignore_ascii_case(&when.equals)));        let created_at = field("created_ms").and_then(|ms| ms.trim().parse::<u64>().ok()).map(|ms| ms / 1000);        let favourite = field("favourite").is_some_and(|value| yes.iter().any(|word| word.eq_ignore_ascii_case(value.trim())));        let landed = if is_note {            note(title, field("notes"))        } else {            login(title, field("url"), field("username"), field("password").unwrap_or(""), field("notes"), field("totp"), created_at)        };        match landed {            Ok(mut item) => {                item.favourite = favourite;                out.passwords.push(item);            }            Err(reason) => out.skipped.push(Skipped { title: title.trim().to_string(), reason }),        }    }    Ok(out)}/// A secure note: its title and its body.pub fn note(title: &str, body: Option<&str>) -> Result<ImportedPassword, String> {    let body = body.map(str::trim).filter(|body| !body.is_empty()).ok_or_else(|| "it is a note with nothing in it".to_string())?;    let shown = title.trim();    Ok(ImportedPassword {        name: shorten(if shown.is_empty() { "Note" } else { shown }, NAME_MAX),        site: None,        username: None,        payload: SecretPayload::Note { body: body.to_string() },        created_at: None,        favourite: false,    })}/// RFC 4180 records: quoted fields, doubled quotes, line breaks in quotes,/// CRLF or LF. A quote left open is refused, never read past.pub(crate) fn records(text: &str) -> Result<Vec<Vec<String>>, String> {    let mut rows = Vec::new();    let mut row = Vec::new();    let mut field = String::new();    let mut quoted = false;    let mut chars = text.chars().peekable();    while let Some(ch) = chars.next() {        if quoted {            match ch {                '"' if chars.peek() == Some(&'"') => {                    chars.next();                    field.push('"');                }                '"' => quoted = false,                _ => field.push(ch),            }            continue;        }        match ch {            '"' if field.is_empty() => quoted = true,            ',' => row.push(std::mem::take(&mut field)),            '\r' if chars.peek() == Some(&'\n') => {}            '\n' | '\r' => {                row.push(std::mem::take(&mut field));                rows.push(std::mem::take(&mut row));            }            _ => field.push(ch),        }    }    if quoted {        return Err("a quoted field is never closed".to_string());    }    if !field.is_empty() || !row.is_empty() {        row.push(field);        rows.push(row);    }    Ok(rows)}#[cfg(test)]#[path = "password_import_tests.rs"]mod tests;