Cotton code
628 lines · 26.4 KB · RustRaw
//! The OAuth credentials a person's Macs can all verify — `cta_` and `ctr_`,//! signed rather than stored.//!//! **WHY THIS EXISTS.** Every Mac of a household 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"). A credential that only the machine//! that minted it could recognise made that hand-over a SIGN-OUT: the newly//! active Mac had never seen the connector's token, so a call answered `401//! invalid_token` and a refresh answered `400 invalid_grant`. The consent had//! travelled; the credential had not.//!//! So a token carries its own claims and a MAC over them, under a key every//! Mac of the household can derive and nobody else can. Nothing about it is//! looked up. A Mac that can open the workspace can verify one; a Mac that//! cannot says so by name (`503`), never with an auth-shaped refusal.//!//! ```text//! body  = scheme(1) ‖ kind(1) ‖ vmk_version(4) ‖ issued_at_ms(8)//!         ‖ expires_at_ms(8) ‖ generation(4)//!         ‖ len(workspace_id)(1) ‖ workspace_id//!         ‖ len(grant_id)(1)     ‖ grant_id//! tag   = HMAC-SHA256(key, "cotton-oauth-token-v1\0" ‖ body)//! token = prefix ‖ base64url_nopad(body ‖ tag)//! key   = HKDF-SHA256(ikm = vmk,//!                     salt = "cotton-oauth-token-key",//!                     info = "cotton-oauth-token-key-v1" ‖ 0 ‖ workspace_id//!                            ‖ 0 ‖ vmk_version, 32)//!//! scheme 2 (a refresh token, since store version 45)://! body  = the scheme-1 fields above, with scheme = 2, ‖ nonce(16)//! nonce = 16 random bytes at a chain's birth, and after that//!         SHA-256("cotton-oauth-refresh-successor-v1\0" ‖ predecessor)[..16]//! ```//!//! **WHY A REFRESH TOKEN CARRIES A NONCE (scheme 2).** Every field of a scheme-1//! refresh token is on the synced grant row, so it is a pure function of the//! key and the row. Once a rotation retires key N, every device that held N —//! the one just revoked included — could rebuild the token the chain stands at.//! The grant's `refresh_digest` (store version 45) is what lets a Mac honour//! that one token after the rotation without the old key, so the token must//! hold something the key and the row do not: sixteen bytes that are in no//! row. A chain is born with random ones. Each successor's are derived from//! the whole PREDECESSOR token, which is exactly as secret as the chain itself//! and stored nowhere — so two presentations of one token, on any Mac, arrive//! at the very same successor (which is how a Mac that cannot check the old tag//! still PROVES a token was already spent: its successor is the one the digest//! names), and nobody who lacks a token of the chain can compute the next one. A successor of a token the key alone could have made (a//! SCHEME-1 token, or one no digest vouched for) is the exception: its nonce//! is a KEYED hash of the predecessor ([`rebuildable_successor_nonce`]), so a//! retry still arrives at the same successor, and the server stores no digest//! for it (`cotton_server::oauth::grant`) — it never outlives a rotation.//!//! **THE KEY IS THE WORKSPACE'S, NOT THE MACHINE'S.** It is derived from the//! vault master key ([`crate::vault::seal::Vmk`]) — the 32 bytes each of the//! person's devices unwraps with its own vault key, which the serving Mac//! already opens unattended from its Keychain (Cotton note "The vault — the honest sentence").//! HKDF with its own salt AND its own info means the token key and the sealing//! key are different keys derived from one secret: a token can never be made to//! open a password and a password's ciphertext can never be made to verify as a//! token.//!//! **THE KEY ID IS THE VMK VERSION**, and that is deliberate rather than//! incidental. Revoking a device ROTATES the master key, so every token minted//! under the old one stops verifying — which is exactly right: a revoked phone//! kept its copy of the old master key, and without the rotation it could go on//! minting valid access tokens for every grant in the file for ever. A//! revocation therefore signs the connectors out too, and they reconnect//! against a consent that is still standing.//!//! **A REFRESH TOKEN CARRIES NO CLOCK, ON PURPOSE.** Its `issued_at` and//! `expires_at` are zero and [`verify_with`] refuses one that is not, because//! its expiry is a fact of the GRANT — the sliding ninety days and the hard//! year, both read off the row — and because zeroing them makes the token a//! pure function of `(grant, generation, key, nonce)`, and the nonce a pure//! function of the predecessor. That is what lets two Macs, or//! two concurrent presentations on one Mac, arrive at the SAME successor rather//! than forking the chain — and a presentation of a token whose successor//! has already been spent, or one outside the short retry window, is reuse,//! which revokes the grant (`cotton_core::transforms::oauth_grants`). An//! access token does carry its hour, because nothing on the row//! bounds one.//!//! **PURE.** No clock, no database, no randomness: bytes in, bytes out. The//! generation's meaning — what a presented one is allowed to be — is//! [`crate::transforms::oauth_grants`], and the state it is compared against is the//! synced grant row.use base64::engine::general_purpose::URL_SAFE_NO_PAD;use base64::Engine as _;use hkdf::Hkdf;use hmac::{Hmac, Mac};use sha2::{Digest, Sha256};use subtle::ConstantTimeEq;use zeroize::Zeroizing;use super::seal::Vmk;/// Access token — the only one of these ever spent at `/v1/mcp`.pub const ACCESS_PREFIX: &str = "cta_";/// Refresh token — spent at `/oauth/token` and nowhere else.pub const REFRESH_PREFIX: &str = "ctr_";/// HKDF's salt. Fixed and public; the secret is the master key.const KEY_SALT: &[u8] = b"cotton-oauth-token-key";/// HKDF's domain separator, carrying the DERIVATION's version — so a later/// scheme derives a different key from the same master key rather than quietly/// sharing one.const KEY_INFO: &[u8] = b"cotton-oauth-token-key-v1";/// What the MAC is taken over, before the body. A tag computed here can never/// be mistaken for one computed anywhere else in this product.const MAC_DOMAIN: &[u8] = b"cotton-oauth-token-v1\0";/// The body layout of an access token, and of a refresh token minted before/// store version 45. A token naming a layout this build does not know is/// refused rather than guessed at.pub const SCHEME: u8 = 1;/// The body layout of a refresh token since store version 45: scheme 1's/// fields followed by [`NONCE_LEN`] bytes that are in no row. Only a refresh/// token is ever minted in it.pub const SCHEME_SEALED: u8 = 2;/// The bytes a scheme-2 refresh token carries beyond its claims — 128 bits.pub const NONCE_LEN: usize = 16;/// The domain a successor's nonce is derived under, so the derivation can be/// mistaken for no other hash of a token.const SUCCESSOR_DOMAIN: &[u8] = b"cotton-oauth-refresh-successor-v1\0";const KIND_ACCESS: u8 = 1;const KIND_REFRESH: u8 = 2;/// The longest life an access token may claim, whoever minted it.////// The server's own `ACCESS_TTL_MS` is an hour; this is the SCHEME's ceiling,/// checked at verification so a token that claims a century is refused rather/// than honoured. It is deliberately looser than the server's own choice — the/// server may shorten its tokens whenever it likes without a change here — and/// the point is that there IS a ceiling: every paired device can unwrap the/// master key, so "the minter is the server" is an assumption and not a fact.pub const MAX_ACCESS_LIFE_MS: i64 = 24 * 60 * 60_000;const TAG_LEN: usize = 32;/// scheme ‖ kind ‖ vmk_version ‖ issued ‖ expires ‖ generation ‖ two lengths.const FIXED_LEN: usize = 1 + 1 + 4 + 8 + 8 + 4 + 1 + 1;/// Which family a token belongs to. The prefix is a function of this and never/// a second opinion about it.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum TokenKind {    Access,    Refresh,}impl TokenKind {    pub fn prefix(self) -> &'static str {        match self {            TokenKind::Access => ACCESS_PREFIX,            TokenKind::Refresh => REFRESH_PREFIX,        }    }    fn byte(self) -> u8 {        match self {            TokenKind::Access => KIND_ACCESS,            TokenKind::Refresh => KIND_REFRESH,        }    }    fn from_byte(byte: u8) -> Option<TokenKind> {        match byte {            KIND_ACCESS => Some(TokenKind::Access),            KIND_REFRESH => Some(TokenKind::Refresh),            _ => None,        }    }}/// What a token says about itself, once its MAC has been checked.#[derive(Debug, Clone, PartialEq, Eq)]pub struct TokenClaims {    pub kind: TokenKind,    /// Which version of the workspace's master key signed it.    pub vmk_version: u32,    /// Milliseconds since the epoch. ZERO on a refresh token, whose clock is    /// the grant row's.    pub issued_at_ms: i64,    /// Milliseconds since the epoch. ZERO on a refresh token.    pub expires_at_ms: i64,    /// The refresh chain's position. Zero on an access token, which has no    /// chain of its own.    pub generation: u32,    pub workspace_id: String,    pub grant_id: String,}/// The fields a verifier must read BEFORE it has a key — which workspace's/// key, and which version of it — and the grant the body names.////// Reading them off an unverified body is 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 TokenSelector {    pub kind: TokenKind,    pub scheme: u8,    pub vmk_version: u32,    pub workspace_id: String,    /// The grant the body names, UNVERIFIED like the rest. Read for one thing    /// only: when the key version is one a rotation retired, so no tag can be    /// checked, whether a consent the person still has stands behind the    /// token — the difference between "signed out by a security update" and    /// the one answer every other dead token gets.    pub grant_id: String,}/// Whether a string is shaped like one of this scheme's tokens at all.////// A `true` here promises nothing about validity — it says only that the/// caller should reach for [`selector`] rather than the legacy opaque path.pub fn is_signed_token(token: &str) -> bool {    selector(token).is_some()}/// The workspace and key version a token names, or `None`.pub fn selector(token: &str) -> Option<TokenSelector> {    let (kind, body) = split_prefix(token)?;    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 claims.kind != kind {        // The prefix and the body disagree about what this is. Refuse rather        // than believe either: a `ctr_` whose body says `access` would be a        // refresh token spent at `/v1/mcp`.        return None;    }    Some(TokenSelector {        kind,        scheme,        vmk_version: claims.vmk_version,        workspace_id: claims.workspace_id,        grant_id: claims.grant_id,    })}/// The token key for one workspace at one version of its master key.////// Every Mac that can unwrap the master key arrives at the same 32 bytes, and/// nothing else can: that is the whole of why a token minted on one Mac/// verifies on the next.pub fn token_key(vmk: &Vmk, workspace_id: &str, vmk_version: u32) -> Zeroizing<[u8; 32]> {    let mut info = Vec::with_capacity(KEY_INFO.len() + workspace_id.len() + 8);    info.extend_from_slice(KEY_INFO);    info.push(0);    info.extend_from_slice(workspace_id.as_bytes());    info.push(0);    info.extend_from_slice(&vmk_version.to_be_bytes());    let mut key = Zeroizing::new([0u8; 32]);    Hkdf::<Sha256>::new(Some(KEY_SALT), vmk.expose())        .expand(&info, key.as_mut())        // HKDF-SHA256 refuses only an output longer than 255 hashes, so 32        // bytes cannot fail — and swallowing the failure would not avoid the        // unreachable case, it would replace an unreachable panic with an        // all-zero key every Mac derives identically and anyone can forge        // under. A signing key is the last place for a silent fallback.        .expect("HKDF-SHA256 gives 32 bytes for any input material");    key}/// Mint a token for these claims under this key.////// `None` for a claim this scheme cannot carry: an id longer than a byte can/// measure, or a refresh token that was handed a clock.pub fn mint(key: &[u8; 32], claims: &TokenClaims) -> Option<String> {    if claims.kind == TokenKind::Refresh && (claims.issued_at_ms != 0 || claims.expires_at_ms != 0)    {        return None;    }    if claims.kind == TokenKind::Access {        if claims.generation != 0 {            return None;        }        let life = claims.expires_at_ms.checked_sub(claims.issued_at_ms)?;        if !(0..=MAX_ACCESS_LIFE_MS).contains(&life) {            return None;        }    }    let body = write_body(claims, SCHEME)?;    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!(        "{}{}",        claims.kind.prefix(),        URL_SAFE_NO_PAD.encode(&out)    ))}/// Mint a scheme-2 refresh token: these claims and `nonce`, under this key.////// `None` for anything that is not a refresh token with no clock, and for a/// claim the body cannot carry. The nonce is the caller's: random at a chain's/// birth, [`successor_nonce`] of the presented token after that.pub fn mint_refresh(    key: &[u8; 32],    claims: &TokenClaims,    nonce: &[u8; NONCE_LEN],) -> Option<String> {    if claims.kind != TokenKind::Refresh || claims.issued_at_ms != 0 || claims.expires_at_ms != 0    {        return None;    }    let mut body = write_body(claims, SCHEME_SEALED)?;    body.extend_from_slice(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!(        "{}{}",        claims.kind.prefix(),        URL_SAFE_NO_PAD.encode(&out)    ))}/// The nonce of the refresh token that succeeds `presented`.////// A function of the WHOLE presented string — so two Macs, or a second/// presentation, arrive at the same successor — and of nothing a row or a key holds, so only a/// holder of a token of the chain can compute it. Meaningful only for a/// predecessor nobody can rebuild: a scheme-2 token, or an opaque one from/// before store version 21. A predecessor the key alone could have made takes/// [`rebuildable_successor_nonce`] instead.pub fn successor_nonce(presented: &str) -> [u8; NONCE_LEN] {    let mut hasher = Sha256::new();    hasher.update(SUCCESSOR_DOMAIN);    hasher.update(presented.as_bytes());    let digest = hasher.finalize();    let mut nonce = [0u8; NONCE_LEN];    nonce.copy_from_slice(&digest[..NONCE_LEN]);    nonce}/// The domain a successor's nonce is derived under when its predecessor is/// a token the key alone could have made — keyed, and never the same bytes as/// [`successor_nonce`] of the same string.const REBUILDABLE_SUCCESSOR_DOMAIN: &[u8] = b"cotton-oauth-refresh-rebuildable-successor-v1\0";/// The nonce of the refresh token that succeeds a predecessor the KEY ALONE/// could have made — a scheme-1 token, or a scheme-2 one no digest vouched/// for. HMAC-SHA256 under the token key, of the whole presented string.////// **DETERMINISTIC SO A RETRY IS NOT A REPLAY.** It used to be random, so a/// client whose answer was lost could never be handed the same successor/// again. It launders nothing: such a successor still carries NO digest, so/// it is never admitted after a rotation, and anyone who can compute it holds/// the key and could sign a token at that generation anyway.pub fn rebuildable_successor_nonce(key: &[u8; 32], presented: &str) -> [u8; NONCE_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(REBUILDABLE_SUCCESSOR_DOMAIN);    mac.update(presented.as_bytes());    let tag = mac.finalize().into_bytes();    let mut nonce = [0u8; NONCE_LEN];    nonce.copy_from_slice(&tag[..NONCE_LEN]);    nonce}/// How long the part of a stored refresh digest that NAMES THE TOKEN is:/// ten digits of generation, a colon, 64 hex characters.pub const DIGEST_BODY_LEN: usize = 75;/// The longest device id a stored refresh digest names as its writer.pub const DIGEST_WRITER_MAX: usize = 128;/// What `cotton_oauth_grants.refresh_digest` holds for the token a chain/// stands at: `<generation, ten digits>:<SHA-256 hex of the whole token>:<the/// device id of the Mac that wrote it>`.////// The generation leads, zero-padded, so the text order is the generation/// order and the store's `MaxNonNull` keeps the digest paired with it.////// **THE WRITER TRAILS, AND IT IS WHO THE DIGEST DIES WITH.** The refresh/// chain moves on whichever Mac is serving, so the Mac that wrote the digest/// is not always the Mac that minted the grant — and the Mac that wrote it/// minted the token it names, so it could have kept that token. The sync/// route accepts a digest only from the device it names as its writer/// (`cotton_server::sync::oauth_grant_rows`), revoking a device revokes every/// grant whose current digest it wrote, and a Mac refuses to admit a token by/// a digest whose writer is revoked. A digest planted over sync therefore/// names the device that planted it, and ends with it.pub fn refresh_digest(generation: u32, token: &str, writer: &str) -> String {    format!(        "{generation:010}:{}:{writer}",        hex::encode(Sha256::digest(token.as_bytes()))    )}/// The device a stored refresh digest names as its writer, if the value is/// well formed — the body [`DIGEST_BODY_LEN`] long, a colon, and a device id/// of 1 to [`DIGEST_WRITER_MAX`] characters from `[A-Za-z0-9_.:-]` (base64url,/// which is what a device id is, and the `device:` / `server:` author shapes).pub fn refresh_digest_writer(stored: &str) -> Option<&str> {    let body = stored.get(..DIGEST_BODY_LEN)?;    let (generation, hash) = body.split_once(':')?;    if generation.len() != 10 || !generation.bytes().all(|byte| byte.is_ascii_digit()) {        return None;    }    if hash.len() != 64        || !hash            .bytes()            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))    {        return None;    }    let writer = stored.get(DIGEST_BODY_LEN..)?.strip_prefix(':')?;    let well_formed = !writer.is_empty()        && writer.len() <= DIGEST_WRITER_MAX        && writer            .bytes()            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.' | b':'));    well_formed.then_some(writer)}/// Whether `stored` is the digest of `token` at `generation`, whoever wrote/// it. Constant time over the part that names the token; a value that is not/// well formed (a public fact: the format is fixed) is answered at once./// WHO wrote it is the caller's question ([`refresh_digest_writer`]).pub fn refresh_digest_matches(stored: &str, generation: u32, token: &str) -> bool {    if refresh_digest_writer(stored).is_none() {        return false;    }    let expected = format!(        "{generation:010}:{}",        hex::encode(Sha256::digest(token.as_bytes()))    );    stored.as_bytes()[..DIGEST_BODY_LEN]        .ct_eq(expected.as_bytes())        .unwrap_u8()        == 1}/// The claims of a scheme-2 refresh token, WITHOUT checking its tag.////// For one caller and one reason: the token names a key version the household/// has rotated past, so no Mac can check the tag any more, and what admits it/// instead is the grant's `refresh_digest` — a SHA-256 of the whole string./// Every rule of the scheme is still applied, and only scheme 2 is read: a/// scheme-1 token is a pure function of the key and the synced row, so a/// device that kept the old key could rebuild it, and a digest must never/// admit one.pub fn claims_unverified(token: &str) -> Option<TokenClaims> {    let (kind, body) = split_prefix(token)?;    if kind != TokenKind::Refresh {        return None;    }    let bytes = URL_SAFE_NO_PAD.decode(body).ok()?;    if bytes.len() < FIXED_LEN + NONCE_LEN + TAG_LEN {        return None;    }    let (scheme, claims, _) = read_body(&bytes[..bytes.len() - TAG_LEN])?;    if scheme != SCHEME_SEALED || claims.kind != kind {        return None;    }    if claims.issued_at_ms != 0 || claims.expires_at_ms != 0 {        return None;    }    Some(claims)}/// The claims a token 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 token that does not verify learns nothing from/// which. The comparison is constant-time.pub fn verify_with(token: &str, key: &[u8; 32]) -> Option<TokenClaims> {    let (kind, body) = split_prefix(token)?;    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 claims.kind != kind {        return None;    }    // Scheme 1 for either kind — every access token, and a refresh token from    // before store version 45, which keeps working under the key it names.    // Scheme 2 for a refresh token only.    match scheme {        SCHEME => {}        SCHEME_SEALED if claims.kind == TokenKind::Refresh => {}        _ => return None,    }    if claims.kind == TokenKind::Refresh && (claims.issued_at_ms != 0 || claims.expires_at_ms != 0)    {        // A refresh token's clock is the grant row's. One that carries its own        // was minted by something that is not this scheme.        return None;    }    // **EVERY RULE `mint` ENFORCES IS ENFORCED HERE TOO.** A rule the minter    // keeps and the verifier does not is not a rule — it binds the honest    // path and nothing else, and the holder of the key is not always the    // server: every paired device can unwrap the master key. So an access    // token's generation must be zero, and its life must be the life this    // scheme grants, whoever minted it.    if claims.kind == TokenKind::Access {        if claims.generation != 0 {            return None;        }        let life = claims.expires_at_ms.checked_sub(claims.issued_at_ms)?;        if !(0..=MAX_ACCESS_LIFE_MS).contains(&life) {            return None;        }    }    Some(claims)}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()}fn split_prefix(token: &str) -> Option<(TokenKind, &str)> {    if let Some(rest) = token.strip_prefix(ACCESS_PREFIX) {        return Some((TokenKind::Access, rest));    }    token        .strip_prefix(REFRESH_PREFIX)        .map(|rest| (TokenKind::Refresh, rest))}fn write_body(claims: &TokenClaims, scheme: u8) -> Option<Vec<u8>> {    let workspace = claims.workspace_id.as_bytes();    let grant = claims.grant_id.as_bytes();    if workspace.is_empty() || grant.is_empty() || workspace.len() > 255 || grant.len() > 255 {        return None;    }    let mut body = Vec::with_capacity(FIXED_LEN + workspace.len() + grant.len() + NONCE_LEN);    body.push(scheme);    body.push(claims.kind.byte());    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.extend_from_slice(&claims.generation.to_be_bytes());    body.push(workspace.len() as u8);    body.extend_from_slice(workspace);    body.push(grant.len() as u8);    body.extend_from_slice(grant);    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. A/// scheme-2 body answers its nonce too.fn read_body(body: &[u8]) -> Option<(u8, TokenClaims, Option<[u8; NONCE_LEN]>)> {    if body.len() < FIXED_LEN {        return None;    }    let scheme = body[0];    let kind = TokenKind::from_byte(body[1])?;    let vmk_version = u32::from_be_bytes(body[2..6].try_into().ok()?);    let issued_at_ms = i64::from_be_bytes(body[6..14].try_into().ok()?);    let expires_at_ms = i64::from_be_bytes(body[14..22].try_into().ok()?);    let generation = u32::from_be_bytes(body[22..26].try_into().ok()?);    let workspace_len = body[26] as usize;    let grant_start = 27 + workspace_len;    if body.len() < grant_start + 1 {        return None;    }    let grant_len = body[grant_start] as usize;    let end = grant_start + 1 + grant_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. Scheme 2's nonce is the one    // thing that may follow the claims, and it is exactly its length.    let nonce = match scheme {        SCHEME_SEALED => {            if body.len() != end + NONCE_LEN {                return None;            }            let mut nonce = [0u8; NONCE_LEN];            nonce.copy_from_slice(&body[end..]);            Some(nonce)        }        _ => {            if body.len() != end {                return None;            }            None        }    };    let workspace_id = std::str::from_utf8(&body[27..grant_start]).ok()?.to_string();    let grant_id = std::str::from_utf8(&body[grant_start + 1..end])        .ok()?        .to_string();    if workspace_id.is_empty() || grant_id.is_empty() {        return None;    }    Some((        scheme,        TokenClaims {            kind,            vmk_version,            issued_at_ms,            expires_at_ms,            generation,            workspace_id,            grant_id,        },        nonce,    ))}#[cfg(test)]#[path = "tokens_tests.rs"]mod tokens_tests;