Cotton code
181 lines · 8.8 KB · RustRaw
//! No synced table carries a credential anybody could present.//!//! **THE FILE TRAVELS.** It syncs to every phone of the household and to every//! Mac, it is backed up, and a copy of it is an ordinary file on a disk. A//! token or a hash of one sitting in it would be a bearer at rest on every one//! of those, and the whole reason `cta_`/`ctr_` are SIGNED rather than stored//! (`cotton_core::vault::tokens`) is that they then live nowhere at all — the//! grant row carries an id, a counter and two timestamps, and a Mac that can//! open the workspace verifies a token from those without looking anything up.//!//! So this is a NAME sweep over `TABLE_SPECS`, and a name sweep is the right//! shape: a column called `refresh_token`, `token_hash` or `secret` is either a//! credential or a column somebody should rename, and both are worth stopping//! at review time rather than at a leak.//!//! **EVERY EXEMPTION IS WRITTEN DOWN, with its argument**, and a new one has to//! be argued for here in the same PR as the column it lets through.use cotton_store::schema::decl::TableSpec;use cotton_store::schema::table_specs::TABLE_SPECS;/// The words a column carrying something presentable would be called.const BEARER_WORDS: &[&str] = &[    "access_token",    "api_key",    "bearer",    "client_secret",    "credential",    "password",    "refresh_token",    "secret_hash",    "token_digest",    "token_hash",];/// Columns whose name trips the sweep and which are NOT a credential.////// * `cotton_oauth_clients.secret_hash` — the hash of a DYNAMIC CLIENT///   REGISTRATION secret, which is a client's own password to the token///   endpoint. It travels on purpose: a confidential client has to be able to///   authenticate on whichever Mac takes the household over, and there is no///   other copy of it once the registering Mac stops answering. It is a hash,///   it is not presentable AS a Cotton credential, and it grants nothing on its///   own — holding it lets somebody impersonate the CLIENT at `/oauth/token`,///   which still buys nothing without a code or a refresh token./// * `cotton_invites.secret_hash` (version 57) — the hash of an invite's///   secret. A server hashes the secret the invitee PRESENTS and compares, so///   the digest itself cannot be spent; it travels because whichever Mac///   answers the household must be able to admit the invitee. This holds only///   while the secret carries enough random bytes that its hash cannot be///   searched back to it, and the invite row is signed and lapses at///   `expires_at`./// * `cotton_secrets.value_enc` — the vault. The bytes are sealed under a key///   the file does not contain (Cotton note "The vault — the honest sentence"), which is what///   makes a replica a backup rather than a widening./// * `cotton_google_accounts.refresh_token_enc` — Google's own refresh token,///   and the `_enc` is the point: it is sealed, never plaintext, and it is a///   credential to GOOGLE rather than one anybody can present to this server./// * `cotton_mcp_tokens.token_hash` — the hash of a pasted `ctn_`, which is a///   family Cotton deliberately keeps: the person types that one into a config///   file themselves, so there is no signing key that could replace it, and a///   SHA-256 of a 256-bit random is not something an attacker walks back. On an///   OAuth grant's row it is the hash of a random generated, never returned and///   discarded on the spot — so the row cannot be spent as a pasted token at///   all, which is the whole reason it is written that way./// * `cotton_code_credentials.token_digest` and `cotton_repo_jobs.token_digest`///   (version 44) — the SHA-256 of a signed `ctg_`, the same argument as///   `cotton_mcp_tokens.token_hash`: a server hashes what is PRESENTED, so the///   digest cannot be spent. The tag is NOT what makes it safe to replicate:///   every device that held the old key can recompute a tag, and every other///   field of the body is on the grant row. What does is the 16 random bytes///   a scheme-2 token carries and nothing else keeps///   (`cotton_core::vault::code_tokens::NONCE_LEN`); a scheme-1 token is never///   admitted by its digest. It is what admits a LIVE credential after///   the workspace key it was signed under has been rotated away — a token///   whose tag can no longer be checked is admitted only when it IS the one///   token the row was minted for — and it has to travel for the same reason///   the grant row does: whichever Mac answers the household must be able to///   ask. The fold refuses a patch that changes a grant's digest after its row///   exists (`fold::no_grant_rewrite`)./// * `cotton_repo_runners.credential_id` — an ID, pointing at a `ctg_` whose///   hash lives in the serving Mac's registry. The row names it; it does not///   carry it./// * `cotton_serving_machine.device_credential_id` (version 49) — an ID too:///   the `cotton_devices` row of the machine serving that epoch. The device's///   credential is its Ed25519 key, whose private half never leaves it; the///   row names the device, it does not carry anything presentable./// * `cotton_documents.password` — a KNOWN legacy column, and the one entry///   here that is not an argument. The vault's §5.4 sweep moves every plaintext///   document password into `cotton_secrets` and points the document at it;///   the column is emptied by the follow-up rung once that sweep reports zero///   everywhere (Cotton note "The vault — the honest sentence"). It is listed rather than ignored///   so the follow-up has somewhere to delete a line from.const NOT_A_BEARER: &[(&str, &str)] = &[    ("cotton_code_credentials", "token_digest"),    ("cotton_documents", "password"),    ("cotton_google_accounts", "refresh_token_enc"),    ("cotton_invites", "secret_hash"),    ("cotton_mcp_tokens", "token_hash"),    ("cotton_oauth_clients", "secret_hash"),    ("cotton_repo_jobs", "token_digest"),    ("cotton_repo_runners", "credential_id"),    ("cotton_secrets", "value_enc"),    ("cotton_serving_machine", "device_credential_id"),];fn exempt(table: &str, column: &str) -> bool {    NOT_A_BEARER        .iter()        .any(|(owner, name)| *owner == table && *name == column)}#[test]fn no_synced_column_is_named_like_a_credential() {    let mut offenders: Vec<String> = Vec::new();    for spec in TABLE_SPECS {        let spec: &TableSpec = spec;        for (column, _) in spec.columns {            if exempt(spec.name, column) {                continue;            }            if BEARER_WORDS.iter().any(|word| column.contains(word)) {                offenders.push(format!("{}.{column}", spec.name));            }        }    }    assert!(        offenders.is_empty(),        "these synced columns are named like a credential: {offenders:?}. The file travels to \         every device — a token or a hash of one in it is a bearer at rest on all of them. If the \         column is genuinely not presentable, say why in `NOT_A_BEARER` in this file."    );}#[test]fn the_oauth_grant_carries_only_what_verifying_a_signed_token_needs() {    let grants = TABLE_SPECS        .iter()        .find(|spec| spec.name == "cotton_oauth_grants")        .expect("the grants table is specced");    let columns: Vec<&str> = grants.columns.iter().map(|(name, _)| *name).collect();    assert_eq!(        columns,        vec![            "id",            "workspace_id",            "client_id",            "client_name",            "scope",            "created_at",            "revoked_at",            "token_id",            "refresh_generation",            "refresh_rotated_at",            "refresh_digest",            "minted_by",        ],        "the standing consent, the row it minted, where the refresh chain got to, the digest \         of the token it stands at and the Mac that minted it — and nothing that could be handed to a server as a \         credential. A column added here has to be readable by anyone who opens a backup of this \         file. `refresh_digest` is readable: a SHA-256 is not presentable, and the token under it \         carries sixteen random bytes that are in no row, so the file plus the old key cannot \         rebuild it (`cotton_core::vault::tokens`, scheme 2)."    );}#[test]fn every_exemption_names_a_column_that_still_exists() {    // A written reason for a column that moved is a reason nobody is reading —    // the repo's own landmine about a guard going quiet rather than red.    for (table, column) in NOT_A_BEARER {        let spec = TABLE_SPECS            .iter()            .find(|spec| spec.name == *table)            .unwrap_or_else(|| panic!("`NOT_A_BEARER` names a table that is gone: {table}"));        assert!(            spec.columns.iter().any(|(name, _)| name == column),            "`NOT_A_BEARER` names a column that is gone: {table}.{column}"        );    }}