Cotton code
111 lines · 5.0 KB · RustRaw
//! WHICH DATABASE a device-signed request acts on — named by the request, never//! guessed by the server.//!//! One Mac can serve several databases. A request that did not say which one it//! meant left the server to walk every file it holds and take the first row//! that matched the key, which is a guess the moment a device belongs to two.//! So every device-signed request carries `?database=<workspace id>` in its//! query, and the server opens THAT file and no other.//!//! **It is in the QUERY, and the query is signed** (`signature.rs`: the path is//! `pathname + search`, raw as sent). So the database a request names is//! covered by the signature with no change to the signed string's format, and a//! captured request cannot be replayed against another database.//!//! Both ends spell it here: the client adds it ([`naming_database`]) in the one//! place it signs, and the server reads it back ([`database_named`]) in the one//! chokepoint that admits a device.//!//! **Not every signed route names one.** The pairing routes are called by a//! device BEFORE it has a database, and [`DATABASES_PATH`] is the one route//! that asks across files — "which databases is this key in?" — so naming one//! there would be answering the question in the asking. [`names_no_database`]//! is that list, and it is short on purpose./// The query parameter a device-signed request names its database in.pub const DATABASE_PARAM: &str = "database";/// `GET /v1/me/databases` — the served databases this device's key is live in.pub const DATABASES_PATH: &str = "/v1/me/databases";/// The header every answer to a request that named a database echoes it in, so/// a device reading a refusal knows WHICH database refused it (a 403 for one/// database is not a verdict on the others). An answer to a request that named/// none carries none.pub const DATABASE_HEADER: &str = "x-cotton-database";/// The refusal a signed request that names no database gets — `400`.pub const DATABASE_REQUIRED: &str = "database_required";/// The refusal an exchange whose body names a different database than its/// query gets — `400`.pub const DATABASE_MISMATCH: &str = "database_mismatch";/// The sentence beside [`DATABASE_REQUIRED`]. A build that does not name its/// database is a build from before this rule, and the way out is to update it/// and join again.pub const DATABASE_REQUIRED_SENTENCE: &str =    "this request does not say which database it is for — update the app and rejoin this server";/// The database `path_and_search` names, or `None` when it names none.////// Decoded (`application/x-www-form-urlencoded`), so a client that/// percent-encoded the id and one that did not name the same database. An/// empty value names nothing. Two values is a caller that is confused, and/// confusion names nothing either — the server must not pick one of them.pub fn database_named(path_and_search: &str) -> Option<String> {    let without_fragment = path_and_search.split('#').next().unwrap_or("");    let (_, query) = without_fragment.split_once('?')?;    let mut named = url::form_urlencoded::parse(query.as_bytes())        .filter(|(key, _)| key == DATABASE_PARAM)        .map(|(_, value)| value.into_owned());    let first = named.next()?;    if named.next().is_some() || first.is_empty() {        return None;    }    Some(first)}/// `path` with `database=<id>` added to its query — or `path` unchanged when it/// already names one, or is a route that names none ([`names_no_database`]).////// An explicit `database` the caller already wrote WINS: the join names the/// database it was just approved for before the device has remembered one, and/// a test names the wrong one on purpose.pub fn naming_database(path: &str, database: &str) -> String {    if names_no_database(path) || path_names_a_database(path) {        return path.to_string();    }    let encoded: String = url::form_urlencoded::byte_serialize(database.as_bytes()).collect();    let separator = match path.split_once('?') {        None => '?',        Some((_, "")) => return format!("{path}{DATABASE_PARAM}={encoded}"),        Some(_) => '&',    };    format!("{path}{separator}{DATABASE_PARAM}={encoded}")}/// The device-signed routes that name NO database: the pairing routes (called/// before the device has one) and [`DATABASES_PATH`] (which asks across them).pub fn names_no_database(path: &str) -> bool {    let route = path.split(['?', '#']).next().unwrap_or("");    if route == DATABASES_PATH {        return true;    }    match route.strip_prefix("/v1/devices/pair") {        Some(rest) => rest.is_empty() || rest.starts_with('/'),        None => false,    }}fn path_names_a_database(path: &str) -> bool {    let without_fragment = path.split('#').next().unwrap_or("");    let Some((_, query)) = without_fragment.split_once('?') else {        return false;    };    url::form_urlencoded::parse(query.as_bytes()).any(|(key, _)| key == DATABASE_PARAM)}#[cfg(test)]#[path = "database_tests.rs"]mod tests;