Cotton code
619 lines · 25.5 KB · RustRaw
//! `ctg_` — the code credential every Mac of a household can verify, signed//! rather than stored.//!//! **WHY THIS EXISTS.** A `ctg_` used to be 32 random bytes whose SHA-256 sat//! in the MINTING Mac's `registry.db`. Every Mac runs the whole server, but//! the relay hands the name to exactly ONE of them and a routine restart moves//! it (Cotton note "Server address — how a device knows which server holds its data"). So on 22 Sep 2026, three times,//! one hand-over took the household's entire code surface down at once: every//! `git` remote and every `pnpm forge` call answered `401 bad_credential`,//! every runner read *"this runner is not registered with this server"*, and//! git's own credential store ERASED what it held on that first refusal.//! Nothing was wrong with any of those credentials. They were rows on a Mac//! that had stopped answering the name.//!//! [`crate::vault::tokens`] met exactly this for `cta_`/`ctr_` and settled it//! in one direction: **a credential every Mac must verify is a credential no//! Mac stores.** It carries its own claims under a MAC keyed off the workspace//! key every paired device derives, and the thing the FILE holds is the//! grant — `cotton_code_credentials`, a synced row whose `revoked_at` is the//! revocation every Mac reads. Since store version 44 it also keeps the//! token's [`digest`], which nobody can present and which only matters once//! the key the token was signed under has been rotated away (below).//!//! ```text//! body  = scheme(1) ‖ vmk_version(4) ‖ issued_at_ms(8) ‖ expires_at_ms(8)//!         ‖ scope(1)//!         ‖ len(workspace_id)(1)  ‖ workspace_id//!         ‖ len(credential_id)(1) ‖ credential_id//!         ‖ len(device_id)(1)     ‖ device_id//!         ‖ len(repo_id)(1)       ‖ repo_id        (length 0 = no repository)//!         ‖ nonce(16)                               (scheme 2 only)//! tag   = HMAC-SHA256(key, "cotton-code-credential-v1\0" ‖ body)//! token = "ctg_" ‖ base64url_nopad(body ‖ tag)//! key   = cotton_core::vault::tokens::token_key(vmk, workspace_id, vmk_version)//! ```//!//! **THE KEY IS THE OAUTH FAMILY'S; THE MAC DOMAIN IS NOT.** One derivation//! means one place decides whether this Mac can answer for a workspace at all//! (`cotton-server/src/oauth/signing.rs`, and with it the rule that no key is a//! `503` and never a `401`). A DIFFERENT [`MAC_DOMAIN`] is what keeps the//! families apart: a `cta_`'s bytes can never be made to verify here and a//! `ctg_`'s can never be spent at `/v1/mcp`, whatever prefix somebody writes in//! front of them. Sharing a key and separating the domain is the right split//! because the trust boundary is identical — both are "the household's", and//! every paired device can derive either.//!//! **THE KEY ID IS THE VMK VERSION**, and revoking a device ROTATES the master//! key. A token signed under a version older than the workspace's is past//! the point where its TAG can prove anything: every device that held the old//! key — the revoked one included — can sign a fresh token naming any//! credential id it reads in the file. So an old-version token is not//! verified at all. It is admitted only by its grant row's [`digest`] — the//! SHA-256 of the exact token that was minted, stored on the row at mint —//! compared in constant time ([`digest_matches`]), with the row live. Holding//! the old key buys nothing there: the digest names one token, and the only//! copy of that token is wherever it was handed out. A rotation therefore no//! longer retires every credential in one stroke (on 28 Sep 2026 it did, and//! took every Mac's git and every runner down with it); a revoked device's//! OWN credentials are retired by their rows' `revoked_at`, which the device//! revocation stamps.//!//! **THE TOKEN CARRIES 16 RANDOM BYTES (scheme 2), AND THAT IS WHAT MAKES//! THE DIGEST A FENCE.** Every other field of the body is on the grant row —//! id, workspace, device, scope, and `created_at` to the millisecond — so a//! scheme-1 token is a pure function of the old key and a row every device//! replicates: a device that held the key could re-sign it EXACTLY, and its//! digest would match. The nonce is drawn at mint and kept nowhere but in the//! token, so neither the key nor the file rebuilds it. Scheme 1 still VERIFIES//! by its tag under the current key (every token minted before this build),//! but is never admitted by a digest.//!//! **A TOKEN MINTED BEFORE THE DIGEST COLUMN (store version 44) HAS NO DIGEST,//! and stays refused after a rotation** — there is nothing to compare it with,//! and accepting it on the row alone is the forgery above.//!//! **EVERY RULE THE MINTER KEEPS IS CHECKED AT VERIFICATION.** A rule only the//! minter keeps is not a rule: the holder of the key is not always the server,//! because every paired device can unwrap the master key. So a `run` token//! names a repository or is refused, an OWNER's token (`device`, `script`)//! names none, and only a credential whose life is a ROW somebody removes//! (`device`, `runner`) may claim to live for ever — checked in [`verify_with`],//! not only in [`mint`]. A `runner` token MAY name a repository, and it means//! something else there: not the rows it reaches (it reaches none) but the one//! repository the machine it registers will take jobs from.//!//! **PURE.** No clock, no database, no randomness: bytes in, bytes out. Whether//! a verified credential is still LIVE is the grant row's answer//! (`cotton_code_credentials.revoked_at`), read by whichever Mac is asked.use base64::engine::general_purpose::URL_SAFE_NO_PAD;use base64::Engine as _;use hmac::{Hmac, Mac};use sha2::Digest as _;use sha2::Sha256;use subtle::ConstantTimeEq;/// The prefix, unchanged from the registry era on purpose: `transforms::redact`'s/// patterns, the keychain installer and every runbook sentence keep their test.pub const CREDENTIAL_PREFIX: &str = "ctg_";/// What the MAC is taken over, before the body. Different from the OAuth/// family's, which is the whole of what keeps a `cta_` and a `ctg_` from ever/// being mistaken for one another under a shared key.const MAC_DOMAIN: &[u8] = b"cotton-code-credential-v1\0";/// The body layout this build mints: scheme 1's fields followed by/// [`NONCE_LEN`] random bytes (module header). A scheme this build does not/// know is refused rather than guessed at.pub const SCHEME: u8 = 2;/// The layout builds before store version 44 minted — the same fields and no/// nonce. Still verified by its tag under the current key, so no credential/// already handed out stops working; never admitted by a digest after a/// rotation, because it is a function of the key and the grant row.pub const SCHEME_UNSALTED: u8 = 1;/// How many random bytes a scheme-2 body ends with.pub const NONCE_LEN: usize = 16;const TAG_LEN: usize = 32;/// scheme ‖ vmk_version ‖ issued ‖ expires ‖ scope ‖ four lengths.const FIXED_LEN: usize = 1 + 4 + 8 + 8 + 1 + 1 + 1 + 1 + 1;/// The longest a `run` token may claim to live, whoever minted it.////// A job's credential is revoked when the job ends (`ci::handout::close`); this/// is the ceiling underneath that, so a `run` token whose revocation was lost/// dies of its own accord within the day.pub const MAX_RUN_LIFE_MS: i64 = 24 * 60 * 60_000;/// The longest any other expiring token may claim.////// A year. The owner route's own ceiling is the same number of days, and this/// is the SCHEME's: the server may issue shorter whenever it likes without a/// change here, and a token that claims a century is refused rather than/// honoured.pub const MAX_LIFE_MS: i64 = 365 * 24 * 60 * 60_000;/// What a credential is FOR. A closed set, carried as one byte, so a scope this/// build does not know is a token it refuses rather than a string it compares.////// `Ord` is the declaration order and means nothing but "a census can sort/// this": a test comparing two scope lists should not have to care which way/// round either was written.#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]pub enum Scope {    /// A Mac's own, in its login keychain. Revoked from Settings or with the    /// device, never by a clock.    Device,    /// An owner's, minted from Settings for a machine with no device identity.    Script,    /// ONE job's, naming the one repository that job runs for.    Run,    /// A runner's registration (which carries a clock), or the token a    /// registered runner then polls with (which does not — its life is the    /// runner row, deleted when the owner forgets the machine). Reaches no    /// repository's bytes and no `/v1/code/*` row.    Runner,    /// Run state and logs only; never git or a writing code route.    Read,}/// Every scope, in the order the wire byte numbers them.pub const SCOPES: [Scope; 5] = [    Scope::Device,    Scope::Script,    Scope::Run,    Scope::Runner,    Scope::Read,];/// The scopes a person may ask for. `run` and `runner` are the server's own.pub const OWNER_MINTABLE: [Scope; 3] = [Scope::Device, Scope::Script, Scope::Read];impl Scope {    /// The word a row, a route and a refusal all spell it with.    #[must_use]    pub fn as_str(self) -> &'static str {        match self {            Scope::Device => "device",            Scope::Script => "script",            Scope::Run => "run",            Scope::Runner => "runner",            Scope::Read => "read",        }    }    /// The scope a word names, or `None` — never a guess and never a default.    #[must_use]    pub fn parse(word: &str) -> Option<Scope> {        SCOPES.into_iter().find(|scope| scope.as_str() == word)    }    /// The frozen grant CHECK has only the original words. Read narrows a script grant.    #[must_use]    pub fn stored(self) -> (&'static str, i64) {        if self == Scope::Read { ("script", 1) } else { (self.as_str(), 0) }    }    /// Decode the stored pair without broadening a malformed or unknown grant.    #[must_use]    pub fn from_stored(word: &str, read_only: i64) -> Option<Self> {        match (word, read_only) {            ("script", 1) => Some(Scope::Read),            ("device" | "script" | "runner", 0) => Self::parse(word),            _ => None,        }    }    /// Does this scope stand for the PERSON, reaching every repository they    /// hold? `device` and `script` do; `read` observes CI, `run` is one job's and `runner` is none.    #[must_use]    pub fn is_owner(self) -> bool {        matches!(self, Scope::Device | Scope::Script)    }    fn byte(self) -> u8 {        match self {            Scope::Device => 1,            Scope::Script => 2,            Scope::Run => 3,            Scope::Runner => 4,            Scope::Read => 5,        }    }    fn from_byte(byte: u8) -> Option<Scope> {        match byte {            1 => Some(Scope::Device),            2 => Some(Scope::Script),            3 => Some(Scope::Run),            4 => Some(Scope::Runner),            5 => Some(Scope::Read),            _ => None,        }    }}impl std::fmt::Display for Scope {    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        f.write_str(self.as_str())    }}/// What a `ctg_` says about itself, once its MAC has been checked.#[derive(Debug, Clone, PartialEq, Eq)]pub struct CodeClaims {    /// Which version of the workspace's master key signed it.    pub vmk_version: u32,    /// Milliseconds since the epoch.    pub issued_at_ms: i64,    /// Milliseconds since the epoch, or ZERO for a `device` credential, which    /// is the one kind that has no expiry (a Mac's checkouts must not start    /// failing at an hour nobody chose; it is revoked from Settings or with    /// the device instead).    pub expires_at_ms: i64,    pub scope: Scope,    pub workspace_id: String,    /// The `cotton_code_credentials` row this token is the key to.    pub credential_id: String,    /// The device the credential belongs to — a Mac's own id, or the server's    /// own marker for the ones it mints itself.    pub device_id: String,    /// The ONE repository a `run` token may reach. `None` for every other    /// scope, and a `run` without one does not verify.    pub repo_id: Option<String>,}impl CodeClaims {    /// Has this token's own clock run out? A zero expiry never has.    ///    /// The GRANT's state is a different question with a different answer    /// (`revoked_at` on the row), and both have to be true.    #[must_use]    pub fn expired_at(&self, now_ms: i64) -> bool {        self.expires_at_ms != 0 && self.expires_at_ms <= now_ms    }}/// The two fields a verifier must read BEFORE it has a key — which workspace's/// key, and which version of it.////// The same move a `kid` header is: the answer only selects a key, and a wrong/// selection ends in a failed MAC like any other forgery. Nothing else in the/// body is looked at until the tag checks out.#[derive(Debug, Clone, PartialEq, Eq)]pub struct CodeSelector {    pub scheme: u8,    pub vmk_version: u32,    pub workspace_id: String,}/// Whether a string is shaped like one of this scheme's credentials at all.////// A `true` promises nothing about validity — it says only that the caller/// should reach for [`selector`] rather than refusing on the spot.#[must_use]pub fn is_signed_credential(token: &str) -> bool {    selector(token).is_some()}/// The workspace and key version a credential names, or `None`.#[must_use]pub fn selector(token: &str) -> Option<CodeSelector> {    let body = token.strip_prefix(CREDENTIAL_PREFIX)?;    let bytes = URL_SAFE_NO_PAD.decode(body).ok()?;    if bytes.len() < FIXED_LEN + TAG_LEN {        return None;    }    let (scheme, claims) = read_body(&bytes[..bytes.len() - TAG_LEN])?;    Some(CodeSelector {        scheme,        vmk_version: claims.vmk_version,        workspace_id: claims.workspace_id,    })}/// Mint a credential for these claims under this key, with a nonce from the/// operating system's generator.////// `None` for a claim this scheme cannot carry — an id longer than a byte can/// measure, a `run` with no repository or any other scope with one, an expiry/// that precedes its own issue, a life past the ceiling, or a scope other than/// `device` asking to live for ever.#[must_use]pub fn mint(key: &[u8; 32], claims: &CodeClaims) -> Option<String> {    use rand::RngCore as _;    let mut nonce = [0u8; NONCE_LEN];    rand::rngs::OsRng.fill_bytes(&mut nonce);    mint_with_nonce(key, claims, &nonce)}/// [`mint`] with the caller's nonce — for a server that draws its randomness/// through a seam. The nonce MUST be fresh random bytes: it is the only part/// of the token that neither the key nor the grant row can rebuild.#[must_use]pub fn mint_with_nonce(    key: &[u8; 32],    claims: &CodeClaims,    nonce: &[u8; NONCE_LEN],) -> Option<String> {    sign(key, claims, Some(nonce))}/// A token in the layout builds before store version 44 minted/// ([`SCHEME_UNSALTED`]). **Nothing in production calls this**; it exists so/// tests can present the tokens already handed out.#[must_use]pub fn mint_scheme_1(key: &[u8; 32], claims: &CodeClaims) -> Option<String> {    sign(key, claims, None)}fn sign(key: &[u8; 32], claims: &CodeClaims, nonce: Option<&[u8; NONCE_LEN]>) -> Option<String> {    check(claims)?;    let body = write_body_with(claims, nonce)?;    let mut out = Vec::with_capacity(body.len() + TAG_LEN);    out.extend_from_slice(&body);    out.extend_from_slice(&tag_of(key, &body));    Some(format!(        "{CREDENTIAL_PREFIX}{}",        URL_SAFE_NO_PAD.encode(&out)    ))}/// The claims a credential carries, IF its tag verifies under this key.////// `None` covers every failure with one answer — wrong prefix, wrong scheme,/// bad base64, a truncated body, a tampered field and a wrong key alike —/// because the holder of a credential that does not verify learns nothing from/// which. The comparison is constant-time.////// It does NOT read a clock: expiry is [`CodeClaims::expired_at`] and/// revocation is the grant row's, both decided by the caller that has one.#[must_use]pub fn verify_with(token: &str, key: &[u8; 32]) -> Option<CodeClaims> {    let body = token.strip_prefix(CREDENTIAL_PREFIX)?;    let bytes = URL_SAFE_NO_PAD.decode(body).ok()?;    if bytes.len() < FIXED_LEN + TAG_LEN {        return None;    }    let split = bytes.len() - TAG_LEN;    let (signed, presented) = bytes.split_at(split);    let expected = tag_of(key, signed);    if expected.ct_eq(presented).unwrap_u8() != 1 {        return None;    }    let (scheme, claims) = read_body(signed)?;    if scheme != SCHEME && scheme != SCHEME_UNSALTED {        return None;    }    // **EVERY RULE `mint` ENFORCES IS ENFORCED HERE TOO**, for the reason the    // OAuth family states: the minter is not always the server, because every    // paired device can unwrap the master key.    check(&claims)?;    Some(claims)}/// How long [`digest`]'s answer is: SHA-256, as lowercase hex.pub const DIGEST_HEX_LEN: usize = 64;/// The digest a grant row keeps of the token minted for it: SHA-256 of the/// WHOLE token string — prefix, body and tag — as lowercase hex.////// It is not a credential: a server hashes what is PRESENTED, so the digest/// itself cannot be spent. Nor does it let anyone who reads the file find the/// token: a scheme-2 token carries [`NONCE_LEN`] random bytes kept nowhere/// else, so even a device holding the key it was signed under has 2^128/// candidates to hash. (A scheme-1 token has no such part, and is never/// admitted by its digest — [`claims_unverified`].) It exists for one question —/// "is this the token that was minted for that row?" — which an old-version/// token has to answer because its tag no longer can (module header).#[must_use]pub fn digest(token: &str) -> String {    hex::encode(Sha256::digest(token.as_bytes()))}/// Whether `token` is the one `stored` is the [`digest`] of, compared in/// constant time.////// A stored value of the wrong length matches nothing — the length of a/// digest is public, so answering early on it tells a caller nothing.#[must_use]pub fn digest_matches(token: &str, stored: &str) -> bool {    let presented = digest(token);    if stored.len() != presented.len() {        return false;    }    presented.as_bytes().ct_eq(stored.as_bytes()).unwrap_u8() == 1}/// The claims a credential CARRIES, read without checking its tag.////// **NOTHING HERE IS TRUSTED.** It is for a token signed under a key version/// this workspace has rotated past, where the tag can prove nothing (module/// header): the caller must match the token against its grant row's/// [`digest`] before believing a word of it. The scheme and every rule/// [`mint`] keeps are still applied, so a body no minter would have written/// is refused here as it is everywhere.////// **ONLY SCHEME 2.** A scheme-1 token has no nonce, so it is a function of/// the old key and the grant row, and a digest of it proves nothing (module/// header). It reads as `None` here, which refuses it.#[must_use]pub fn claims_unverified(token: &str) -> Option<CodeClaims> {    let body = token.strip_prefix(CREDENTIAL_PREFIX)?;    let bytes = URL_SAFE_NO_PAD.decode(body).ok()?;    if bytes.len() < FIXED_LEN + TAG_LEN {        return None;    }    let (scheme, claims) = read_body(&bytes[..bytes.len() - TAG_LEN])?;    if scheme != SCHEME {        return None;    }    check(&claims)?;    Some(claims)}/// The rules both halves keep. `None` is "this is not a credential this scheme/// can express", and it is the same answer whichever half asked.fn check(claims: &CodeClaims) -> Option<()> {    match claims.scope {        // ONE REPOSITORY, and it is the whole of what makes a job's credential        // the narrowest this server issues. Reading a missing repository as        // "no limit" is how a narrow credential becomes a broad one in silence.        Scope::Run if claims.repo_id.is_none() => return None,        Scope::Run => {}        // A REGISTRATION MAY NAME ONE, and it means something different: not        // "the rows this credential reaches" — a `runner` token reaches none —        // but the one repository the machine it registers will take jobs from.        // `None` is a runner that takes work from every repository in the        // workspace, which is what the owner's own Macs are.        Scope::Runner => {}        // A `device` or a `script` credential IS the person and reaches every        // repository they hold, so one naming a repository would be a narrower        // credential the routes do not know how to narrow.        _ if claims.repo_id.is_some() => return None,        _ => {}    }    if claims.expires_at_ms == 0 {        // **A CREDENTIAL WITH NO EXPIRY IS ONE WHOSE LIFE IS A ROW SOMEBODY        // REMOVES.** A Mac's own (`device`) and a registered runner's        // (`runner`) are both that: they are revoked from Settings, or with the        // machine, and one that lapsed would break every checkout — or stop        // every build — at an hour nobody chose. A `script` sits on a disk        // where nobody will notice it and a `run` belongs to a job, so both        // carry a clock.        if !matches!(claims.scope, Scope::Device | Scope::Runner) {            return None;        }    } else {        let life = claims.expires_at_ms.checked_sub(claims.issued_at_ms)?;        let ceiling = if claims.scope == Scope::Run {            MAX_RUN_LIFE_MS        } else {            MAX_LIFE_MS        };        if !(0..=ceiling).contains(&life) {            return None;        }    }    if claims.issued_at_ms < 0 || claims.expires_at_ms < 0 {        return None;    }    Some(())}fn tag_of(key: &[u8; 32], body: &[u8]) -> [u8; TAG_LEN] {    let mut mac = <Hmac<Sha256> as Mac>::new_from_slice(key)        .expect("HMAC-SHA256 takes a key of any length, 32 bytes included");    mac.update(MAC_DOMAIN);    mac.update(body);    mac.finalize().into_bytes().into()}/// A scheme-1 body — what the tests write by hand.#[cfg(test)]fn write_body(claims: &CodeClaims) -> Option<Vec<u8>> {    write_body_with(claims, None)}/// The body for `claims`: scheme 2 ending in `nonce` when there is one,/// scheme 1 when there is not.fn write_body_with(claims: &CodeClaims, nonce: Option<&[u8; NONCE_LEN]>) -> Option<Vec<u8>> {    let workspace = claims.workspace_id.as_bytes();    let credential = claims.credential_id.as_bytes();    let device = claims.device_id.as_bytes();    let repo = claims.repo_id.as_deref().unwrap_or("").as_bytes();    if workspace.is_empty() || credential.is_empty() || device.is_empty() {        return None;    }    if workspace.len() > 255 || credential.len() > 255 || device.len() > 255 || repo.len() > 255 {        return None;    }    // A `run` token's repository is `Some("")` nowhere: an empty string would    // encode identically to `None` and the two would stop being tellable apart.    if claims.repo_id.is_some() && repo.is_empty() {        return None;    }    let mut body = Vec::with_capacity(        FIXED_LEN + workspace.len() + credential.len() + device.len() + repo.len(),    );    body.push(if nonce.is_some() {        SCHEME    } else {        SCHEME_UNSALTED    });    body.extend_from_slice(&claims.vmk_version.to_be_bytes());    body.extend_from_slice(&claims.issued_at_ms.to_be_bytes());    body.extend_from_slice(&claims.expires_at_ms.to_be_bytes());    body.push(claims.scope.byte());    for part in [workspace, credential, device, repo] {        body.push(part.len() as u8);        body.extend_from_slice(part);    }    if let Some(nonce) = nonce {        body.extend_from_slice(nonce);    }    Some(body)}/// The body's fields, with no judgement about the tag. Every read is/// length-checked and nothing is allocated before the lengths agree.fn read_body(body: &[u8]) -> Option<(u8, CodeClaims)> {    if body.len() < FIXED_LEN {        return None;    }    let scheme = body[0];    let vmk_version = u32::from_be_bytes(body[1..5].try_into().ok()?);    let issued_at_ms = i64::from_be_bytes(body[5..13].try_into().ok()?);    let expires_at_ms = i64::from_be_bytes(body[13..21].try_into().ok()?);    let scope = Scope::from_byte(body[21])?;    let mut at = 22;    let mut parts: [String; 4] = Default::default();    for part in &mut parts {        if body.len() < at + 1 {            return None;        }        let len = body[at] as usize;        at += 1;        let end = at.checked_add(len)?;        if body.len() < end {            return None;        }        *part = std::str::from_utf8(&body[at..end]).ok()?.to_string();        at = end;    }    // A scheme-2 body ends in exactly its nonce, which says nothing and is    // read by nobody — it is there to be unguessable.    if scheme == SCHEME {        at = at.checked_add(NONCE_LEN)?;    }    // EXACT, not "at least": trailing bytes inside the signed region would be a    // second body the tag also covers, and two readings of one token is how a    // parser and a verifier come to disagree.    if at != body.len() {        return None;    }    let [workspace_id, credential_id, device_id, repo_id] = parts;    if workspace_id.is_empty() || credential_id.is_empty() || device_id.is_empty() {        return None;    }    Some((        scheme,        CodeClaims {            vmk_version,            issued_at_ms,            expires_at_ms,            scope,            workspace_id,            credential_id,            device_id,            repo_id: (!repo_id.is_empty()).then_some(repo_id),        },    ))}#[cfg(test)]#[path = "code_tokens_tests.rs"]mod code_tokens_tests;