//! What a `ctg_` is allowed to be, and every way one is refused. use super::*; use crate::vault::seal::Vmk; use crate::vault::tokens::token_key; const WORKSPACE: &str = "ws-1"; const NOW: i64 = 1_700_000_000_000; fn key() -> [u8; 32] { let vmk = Vmk::from_bytes([7u8; 32]); *token_key(&vmk, WORKSPACE, 3) } fn device() -> CodeClaims { CodeClaims { vmk_version: 3, issued_at_ms: NOW, expires_at_ms: 0, scope: Scope::Device, workspace_id: WORKSPACE.to_string(), credential_id: "cred-1".to_string(), device_id: "dev-1".to_string(), repo_id: None, } } fn script() -> CodeClaims { CodeClaims { expires_at_ms: NOW + 90 * 24 * 60 * 60_000, scope: Scope::Script, ..device() } } fn run() -> CodeClaims { CodeClaims { expires_at_ms: NOW + 60 * 60_000, scope: Scope::Run, repo_id: Some("repo-1".to_string()), ..device() } } #[test] fn a_minted_credential_verifies_under_the_same_key_and_reads_back_verbatim() { for claims in [device(), script(), run()] { let token = mint(&key(), &claims).expect("mints"); assert!(token.starts_with(CREDENTIAL_PREFIX), "{token}"); assert_eq!(verify_with(&token, &key()).as_ref(), Some(&claims)); } } #[test] fn the_selector_names_the_workspace_and_the_key_version_before_any_key_is_held() { let token = mint(&key(), &device()).expect("mints"); let selector = selector(&token).expect("a selector"); assert_eq!(selector.scheme, SCHEME); assert_eq!(selector.vmk_version, 3); assert_eq!(selector.workspace_id, WORKSPACE); assert!(is_signed_credential(&token)); } #[test] fn another_workspaces_key_does_not_verify_it() { let token = mint(&key(), &device()).expect("mints"); let other = *token_key(&Vmk::from_bytes([7u8; 32]), "ws-2", 3); assert_eq!(verify_with(&token, &other), None); } #[test] fn another_key_version_does_not_verify_it() { // The revocation rule, as arithmetic: rotating the master key retires every // credential minted under the old one. let token = mint(&key(), &device()).expect("mints"); let rotated = *token_key(&Vmk::from_bytes([9u8; 32]), WORKSPACE, 4); assert_eq!(verify_with(&token, &rotated), None); } #[test] fn an_oauth_token_of_the_same_key_never_verifies_as_a_code_credential() { // The MAC domain is what keeps the two families apart under ONE key. use crate::vault::tokens::{self, TokenClaims, TokenKind}; let oauth = tokens::mint( &key(), &TokenClaims { kind: TokenKind::Access, vmk_version: 3, issued_at_ms: NOW, expires_at_ms: NOW + 3_600_000, generation: 0, workspace_id: WORKSPACE.to_string(), grant_id: "grant-1".to_string(), }, ) .expect("mints"); let dressed = format!( "{CREDENTIAL_PREFIX}{}", oauth.strip_prefix("cta_").expect("an access token") ); assert_eq!(verify_with(&dressed, &key()), None); // And the other way: a `ctg_` wearing a `cta_` prefix is not an access // token either. let code = mint(&key(), &device()).expect("mints"); let disguised = format!( "cta_{}", code.strip_prefix(CREDENTIAL_PREFIX).expect("a credential") ); assert_eq!(tokens::verify_with(&disguised, &key()), None); } #[test] fn one_flipped_byte_anywhere_refuses() { let token = mint(&key(), &run()).expect("mints"); let body = token.strip_prefix(CREDENTIAL_PREFIX).expect("a body"); let mut bytes = base64::Engine::decode(&URL_SAFE_NO_PAD, body).expect("base64"); for index in 0..bytes.len() { bytes[index] ^= 0x01; let tampered = format!( "{CREDENTIAL_PREFIX}{}", base64::Engine::encode(&URL_SAFE_NO_PAD, &bytes) ); assert_eq!(verify_with(&tampered, &key()), None, "byte {index}"); bytes[index] ^= 0x01; } } #[test] fn a_run_credential_names_a_repository_or_is_refused() { let no_repo = CodeClaims { repo_id: None, ..run() }; assert_eq!(mint(&key(), &no_repo), None); } #[test] fn an_owner_s_credential_names_no_repository() { // `device` and `script` ARE the person and reach every repository they // hold; one naming a repository would be a narrower credential no route // knows how to narrow. for scope in [Scope::Device, Scope::Script] { let claims = CodeClaims { scope, expires_at_ms: NOW + 60_000, repo_id: Some("repo-1".to_string()), ..device() }; assert_eq!(mint(&key(), &claims), None, "{scope}"); } } #[test] fn a_registration_may_name_the_one_repository_its_machine_will_serve() { // A `runner` token reaches no repository's ROWS. What the id means here is // which repository the machine it registers takes jobs from, and `None` is // every one in the workspace. for repo in [None, Some("repo-1".to_string())] { let claims = CodeClaims { scope: Scope::Runner, expires_at_ms: NOW + 30 * 24 * 60 * 60_000, repo_id: repo.clone(), ..device() }; let token = mint(&key(), &claims).expect("mints"); assert_eq!(verify_with(&token, &key()).and_then(|read| read.repo_id), repo); } } #[test] fn only_a_credential_whose_life_is_a_row_may_live_for_ever() { // A Mac's own and a registered runner's are removed from Settings or with // the machine; one that lapsed would break every checkout, or stop every // build, at an hour nobody chose. for scope in [Scope::Device, Scope::Runner] { let claims = CodeClaims { scope, expires_at_ms: 0, ..device() }; let token = mint(&key(), &claims).expect("mints"); assert_eq!(verify_with(&token, &key()).as_ref(), Some(&claims), "{scope}"); } // A `script` sits on a disk where nobody will notice it, and a `run` // belongs to a job. Both carry a clock or are not credentials at all. let forever_script = CodeClaims { scope: Scope::Script, expires_at_ms: 0, ..device() }; assert_eq!(mint(&key(), &forever_script), None); let job = CodeClaims { expires_at_ms: 0, ..run() }; assert_eq!(mint(&key(), &job), None); } #[test] fn a_life_past_the_scheme_s_ceiling_is_refused_by_the_minter_and_the_verifier() { let century = CodeClaims { expires_at_ms: NOW + MAX_LIFE_MS + 1, ..script() }; assert_eq!(mint(&key(), ¢ury), None); let long_job = CodeClaims { expires_at_ms: NOW + MAX_RUN_LIFE_MS + 1, ..run() }; assert_eq!(mint(&key(), &long_job), None); // AND THE VERIFIER, not only the minter: a paired device holds the key, so // a hand-rolled token claiming a century must not be honoured. let forged = write_body(&CodeClaims { expires_at_ms: NOW + MAX_LIFE_MS + 1, ..script() }) .expect("a body this scheme can write"); let mut bytes = forged.clone(); bytes.extend_from_slice(&tag_of(&key(), &forged)); let token = format!( "{CREDENTIAL_PREFIX}{}", base64::Engine::encode(&URL_SAFE_NO_PAD, &bytes) ); assert_eq!(verify_with(&token, &key()), None); } #[test] fn an_expiry_that_precedes_its_own_issue_is_refused() { let backwards = CodeClaims { expires_at_ms: NOW - 1, ..script() }; assert_eq!(mint(&key(), &backwards), None); } #[test] fn a_zero_expiry_never_runs_out_and_every_other_one_does() { assert!(!device().expired_at(NOW + MAX_LIFE_MS * 10)); assert!(!script().expired_at(NOW)); assert!(script().expired_at(script().expires_at_ms)); assert!(script().expired_at(script().expires_at_ms + 1)); } #[test] fn nothing_that_is_not_this_scheme_reads_as_one() { for not_one in [ "", "ctg_", "ctg_!!!!", "cta_abc", "ctn_abc", "ctg_AAAA", "not a token at all", ] { assert_eq!(selector(not_one), None, "{not_one}"); assert_eq!(verify_with(not_one, &key()), None, "{not_one}"); assert!(!is_signed_credential(not_one), "{not_one}"); } } #[test] fn trailing_bytes_inside_the_signed_region_are_refused() { let body = write_body(&device()).expect("a body"); let mut padded = body.clone(); padded.push(0); let mut bytes = padded.clone(); bytes.extend_from_slice(&tag_of(&key(), &padded)); let token = format!( "{CREDENTIAL_PREFIX}{}", base64::Engine::encode(&URL_SAFE_NO_PAD, &bytes) ); assert_eq!(verify_with(&token, &key()), None); } #[test] fn an_empty_or_over_long_id_is_not_a_credential_this_scheme_can_carry() { for claims in [ CodeClaims { credential_id: String::new(), ..device() }, CodeClaims { device_id: String::new(), ..device() }, CodeClaims { workspace_id: String::new(), ..device() }, CodeClaims { credential_id: "x".repeat(256), ..device() }, CodeClaims { repo_id: Some(String::new()), ..run() }, ] { assert_eq!(mint(&key(), &claims), None); } } #[test] fn every_scope_word_round_trips_and_nothing_else_parses() { for scope in SCOPES { assert_eq!(Scope::parse(scope.as_str()), Some(scope)); assert_eq!(scope.to_string(), scope.as_str()); } for word in ["", "Device", "admin", "runners", "RUN"] { assert_eq!(Scope::parse(word), None, "{word}"); } for scope in OWNER_MINTABLE { assert!(scope.is_owner() || scope == Scope::Read); } assert!(!Scope::Run.is_owner()); assert!(!Scope::Runner.is_owner()); } // ── the digest a grant row keeps, and the claims read without a key ───────── #[test] fn a_digest_is_the_sha256_of_the_whole_token_in_lowercase_hex() { let token = mint(&key(), &device()).expect("mints"); let digest = digest(&token); assert_eq!(digest.len(), DIGEST_HEX_LEN); assert!(digest.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))); // The WHOLE token, prefix and tag included: two tokens that differ only in // their tag are two digests, which is what makes a forged tag worthless. use sha2::Digest as _; assert_eq!(digest, hex::encode(Sha256::digest(token.as_bytes()))); } #[test] fn a_digest_matches_only_the_token_it_was_taken_of() { let token = mint(&key(), &device()).expect("mints"); let stored = digest(&token); assert!(digest_matches(&token, &stored)); // The same claims under ANOTHER key — the forgery a device that held the // old key could produce for a live row's id — are another digest. let other_key = *token_key(&Vmk::from_bytes([8u8; 32]), WORKSPACE, 3); let forged = mint(&other_key, &device()).expect("mints"); assert!(!digest_matches(&forged, &stored)); // A stored value that is not a digest at all matches nothing, the empty // string included. assert!(!digest_matches(&token, "")); assert!(!digest_matches(&token, &stored[..DIGEST_HEX_LEN - 1])); assert!(!digest_matches(&token, &stored.to_uppercase())); } #[test] fn claims_read_without_a_key_are_what_was_minted_and_the_scheme_rules_still_hold() { for claims in [device(), script(), run()] { let token = mint(&key(), &claims).expect("mints"); assert_eq!(claims_unverified(&token).as_ref(), Some(&claims)); } // A body no key could have minted is not readable this way either: the // rules `mint` keeps are `check`'s, and this path runs `check`. let mut runless = run(); runless.repo_id = None; let token = forge_body(&runless); assert_eq!(claims_unverified(&token), None); assert_eq!(claims_unverified("ctg_not-base64!"), None); assert_eq!(claims_unverified("cta_whatever"), None); } /// A token whose body skips `mint`'s own refusal — what somebody writing bytes /// by hand could send. The tag is 32 zero bytes: nothing here checks one. fn forge_body(claims: &CodeClaims) -> String { let mut bytes = write_body_with(claims, Some(&[9u8; NONCE_LEN])).expect("a body"); bytes.extend_from_slice(&[0u8; TAG_LEN]); format!("{CREDENTIAL_PREFIX}{}", URL_SAFE_NO_PAD.encode(&bytes)) } // ── the nonce: what the key and the grant row cannot rebuild ──────────────── #[test] fn two_mints_of_the_same_claims_under_the_same_key_are_two_tokens() { // The digest on a grant row names ONE token only if the key and the claims // (all of which the row holds) do not determine it. let first = mint(&key(), &device()).expect("mints"); let second = mint(&key(), &device()).expect("mints"); assert_ne!(first, second); assert_ne!(digest(&first), digest(&second)); assert_eq!(selector(&first).map(|s| s.scheme), Some(SCHEME)); assert_eq!(verify_with(&first, &key()).as_ref(), Some(&device())); } #[test] fn a_scheme_1_token_still_verifies_by_its_tag_but_is_not_read_without_a_key() { // Every token minted before this build is scheme 1: it keeps working under // the key it was signed with, and it is never admitted by a digest. let unsalted = mint_scheme_1(&key(), &device()).expect("mints"); assert_eq!(selector(&unsalted).map(|s| s.scheme), Some(SCHEME_UNSALTED)); assert_eq!(verify_with(&unsalted, &key()).as_ref(), Some(&device())); assert_eq!(claims_unverified(&unsalted), None); // And it IS a function of the key and the claims — the reason. assert_eq!(mint_scheme_1(&key(), &device()), Some(unsalted)); } #[test] fn a_scheme_2_body_with_a_short_or_long_nonce_is_refused() { let full = write_body_with(&device(), Some(&[3u8; NONCE_LEN])).expect("a body"); for body in [ full[..full.len() - 1].to_vec(), [full.clone(), vec![0]].concat(), ] { let mut bytes = body.clone(); bytes.extend_from_slice(&tag_of(&key(), &body)); let token = format!("{CREDENTIAL_PREFIX}{}", URL_SAFE_NO_PAD.encode(&bytes)); assert_eq!(verify_with(&token, &key()), None); assert_eq!(claims_unverified(&token), None); } } /// RULE: Read credentials round-trip as their own wire scope and cannot claim git authority, a repository or an unlimited lifetime. #[test] fn read_scope_is_expiring_and_separate_from_full_authority() { let mut claims = script(); claims.scope = Scope::Read; let token = mint(&key(), &claims).expect("a read credential mints"); assert_eq!(verify_with(&token, &key()), Some(claims.clone())); assert!(!Scope::Read.is_owner()); claims.expires_at_ms = 0; assert!(mint(&key(), &claims).is_none()); claims = script(); claims.scope = Scope::Read; claims.repo_id = Some("a-repository".into()); assert!(mint(&key(), &claims).is_none()); } /// RULE: Read is a typed narrowing of a stored script grant; malformed stored pairs never gain authority, and every wire scope remains unchanged. #[test] fn read_scope_is_a_narrowed_frozen_grant_word() { for scope in [Scope::Device, Scope::Script, Scope::Runner, Scope::Read] { let (word, flag) = scope.stored(); assert_eq!(Scope::from_stored(word, flag), Some(scope)); } for (word, flag) in [("read",0),("device",1),("runner",1),("script",-1),("script",2)] { assert_eq!(Scope::from_stored(word, flag), None); } assert_eq!(Scope::Read.as_str(), "read"); assert!(!Scope::Read.is_owner()); }