From c8d8c48f6de348af7e51b9572f549506538887c7 Mon Sep 17 00:00:00 2001 From: "tinycloud-bot[bot]" <348376441+tinycloud-bot[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 18:26:37 +0000 Subject: [PATCH 1/2] fix(TC-2986): do not re-verify or re-evaluate a policy mint or registration under its locks --- CHANGELOG.md | 1 + tinycloud-core/src/db.rs | 32 +++- tinycloud-node-server/src/policy_v3.rs | 242 +++++++++++++------------ 3 files changed, 154 insertions(+), 121 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 08b58464..d83f8542 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ - `/invoke`: a KV invocation that writes (`kv/put` or `kv/del`) and also reads (`kv/get`, `kv/list`, `kv/metadata` or `tinycloud.capabilities/read`) is refused with the same `501` as before, but now before any work: nothing is written and the signed request is not spent. Before, the write committed and only then was the invocation answered `501`, since `/invoke` returns one outcome. Internal callers that still mix the two get their reads after the write commits, holding no database transaction, row lock or write order. A `kv/get` answers the value the invocation wrote. If such a read fails, the error says the write was saved. Details: TC-2986. - `POST /delegate` and `POST /revoke` check the signature (and, for a renewal lease, the signature of the stored original it renews) before taking any lock. A forged or slow-to-verify request no longer holds the delegation's chain guards, its spaces' write order or a database transaction while it is checked; it is refused at once. A renewal lease whose original is not stored is also refused before any lock. Inside the transaction only the signed time window is checked again. A resubmitted delegation that is already stored is now also signature-checked before it is answered as existing. Details: TC-2986. - Add opt-in PostgreSQL checkpoint parts for SQL persistence, with explicit artifact/account capacities and streamed hydration. A database stored in parts loads in bounded statements and is not held to the single-row read limit (`storage.sql.max_artifact_read_bytes`); a load that keeps the whole database in memory (a DuckDB export) still waits for one of the large-transfer slots. Details: TC-2917. +- Policy/v3: minting a session and registering a policy no longer re-verify signatures or re-run the claim, presentation, credential admission and allow evaluations while holding their spaces' write order and row locks. Under the locks they check that the challenge, registration and roots are unchanged; those decisions were made before the locks, at the same time, from the same inputs. Refusal codes are unchanged, except that `credential-evaluation-changed` and `policy-evaluation-changed` can no longer occur. Details: TC-2986. - SQLite stamp replay deadlines now use the same timestamp encoding as cleanup (TC-2920). - PostgreSQL database artifacts use uncompressed external storage for new writes to avoid repeated decompression during chunked reads (TC-2917). Existing large artifacts require an operator re-toast; verify both storage settings after rollout and follow `scripts/tc2917-README.md` if lock contention deferred the migration. - Encryption: v2 column format with key ids, per-purpose keys and recorded format metadata. Optional strict reads are off by default. Details: TC-2516, TC-2517. diff --git a/tinycloud-core/src/db.rs b/tinycloud-core/src/db.rs index 05c8dd88..0dc3a977 100644 --- a/tinycloud-core/src/db.rs +++ b/tinycloud-core/src/db.rs @@ -2408,6 +2408,18 @@ where &self, tx: &DatabaseTransaction, delegations: Vec, + ) -> Result> { + self.delegate_batch_in_transaction_verified(tx, delegations, &PreVerified::default()) + .await + } + + /// As [`Self::delegate_batch_in_transaction`], with the signatures + /// `verified` holds checked before `tx` opened (TC-2986). + pub async fn delegate_batch_in_transaction_verified( + &self, + tx: &DatabaseTransaction, + delegations: Vec, + verified: &PreVerified, ) -> Result> { if let Some(seed) = self.secrets.renewal_seed() { let renewer_did = crate::renewal::renewal_identity_from_seed(seed).0; @@ -2422,7 +2434,7 @@ where )); } } - transact( + transact_verified( tx, &self.storage, &self.secrets, @@ -2436,10 +2448,20 @@ where &[], self.delegated_sql_caveats, self.named_keys, + verified, ) .await } + /// Check `delegation`'s signature outside any transaction (TC-2986), for + /// [`Self::delegate_batch_in_transaction_verified`]. + pub async fn preverify_delegation( + &self, + delegation: &Delegation, + ) -> Result> { + PreVerified::delegation(&self.conn, delegation, self.encryption.as_ref()).await + } + pub async fn revoke(&self, revocation: Revocation) -> Result> { // TC-2986: the signature is checked before any lock. let verified = PreVerified::revocation(&revocation).await?; @@ -4321,13 +4343,19 @@ async fn stored_revocation_target(db: &C, target: Hash) -> R /// signature never runs under a space lock. A hash names exact signed bytes, /// so a check cannot carry over to other bytes. #[derive(Default)] -pub(crate) struct PreVerified(HashSet); +pub struct PreVerified(HashSet); impl PreVerified { pub(crate) fn contains(&self, hash: &Hash) -> bool { self.0.contains(hash) } + /// Both sets of checked signatures. + pub fn union(mut self, other: PreVerified) -> Self { + self.0.extend(other.0); + self + } + /// Check `delegation`'s signature on `db`, outside any transaction; for a /// renewal lease, also the signature of the original it renews. pub(crate) async fn delegation( diff --git a/tinycloud-node-server/src/policy_v3.rs b/tinycloud-node-server/src/policy_v3.rs index ef224998..85c30803 100644 --- a/tinycloud-node-server/src/policy_v3.rs +++ b/tinycloud-node-server/src/policy_v3.rs @@ -1008,6 +1008,45 @@ async fn validate_persisted_root( policy_cid: &str, node_did: &str, ) -> Result<(), &'static str> { + let event = persisted_root_projection(root, root_cid, policy_cid, node_did)?; + verify_signed_delegation(&event.0.delegation) + .await + .map_err(|_| "policy-root-signature-invalid")?; + for space in event.0.spaces() { + tinycloud_core::request_telemetry::observe_space(space); + } + Ok(()) +} + +/// [`validate_persisted_root`] for a root whose signature was verified before +/// the caller's transaction (TC-2986): everything but the signature, which +/// `root_cid` binds to those same bytes, plus the time window. +fn validate_verified_persisted_root( + root: &policy_v3_root::Model, + root_cid: &str, + policy_cid: &str, + node_did: &str, +) -> Result<(), &'static str> { + let event = persisted_root_projection(root, root_cid, policy_cid, node_did)?; + let TinyCloudDelegation::Ucan(ucan) = &event.0.delegation else { + return Err("policy-root-signature-invalid"); + }; + ucan.payload() + .validate_time(None) + .map_err(|_| "policy-root-signature-invalid")?; + for space in event.0.spaces() { + tinycloud_core::request_telemetry::observe_space(space); + } + Ok(()) +} + +/// The stored root, checked against its CID, policy, node and role. +fn persisted_root_projection( + root: &policy_v3_root::Model, + root_cid: &str, + policy_cid: &str, + node_did: &str, +) -> Result { let encoded = std::str::from_utf8(&root.authorization_bytes).map_err(|_| "policy-root-invalid")?; let event = decode_delegation(encoded).map_err(|_| "policy-root-invalid")?; @@ -1029,13 +1068,7 @@ async fn validate_persisted_root( if fact(&event.0.delegation, "role") != Some(expected_role) { return Err("policy-root-role-invalid"); } - verify_signed_delegation(&event.0.delegation) - .await - .map_err(|_| "policy-root-signature-invalid")?; - for space in event.0.spaces() { - tinycloud_core::request_telemetry::observe_space(space); - } - Ok(()) + Ok(event) } /// Observe only content-addressed root bytes already authenticated by durable @@ -2126,17 +2159,18 @@ pub async fn register_policy( } let (policy_root_cid, policy_root) = decode_root(&request.policy_root)?; let (enforcement_root_cid, enforcement_root) = decode_root(&request.enforcement_root)?; - verify_signed_delegation(&policy_root.0.delegation) - .await - .map_err(|_| (Status::Forbidden, "policy-root-signature-invalid".into()))?; - verify_signed_delegation(&enforcement_root.0.delegation) - .await - .map_err(|_| { - ( - Status::Forbidden, - "enforcement-root-signature-invalid".into(), + // TC-2986: verified once, before any lock; the registration's + // transaction does not verify them again. + let verified = preverify_root(tinycloud, &policy_root, "policy-root-signature-invalid") + .await? + .union( + preverify_root( + tinycloud, + &enforcement_root, + "enforcement-root-signature-invalid", ) - })?; + .await?, + ); if !is_policy_root(&policy_root.0.delegation) || !is_policy_root(&enforcement_root.0.delegation) { return Err((Status::Forbidden, "root-fact-schema-invalid".into())); @@ -2283,7 +2317,7 @@ pub async fn register_policy( enforcement_status, ), ]; - let written = register_policy_writes( + let written = register_policy_writes_verified( &txn, tinycloud, &sequence_spaces, @@ -2291,6 +2325,7 @@ pub async fn register_policy( registration, &request.policy_cid, roots, + &verified, ) .await; // The owner was shown above to hold decrypt on this exact key, so the @@ -2318,6 +2353,7 @@ pub async fn register_policy( /// The writes of `register_policy`, inside the transaction its caller opened. /// The caller commits when this returns `Ok` and rolls back on `Err`. +#[cfg(test)] async fn register_policy_writes( txn: &DatabaseTransaction, tinycloud: &crate::TinyCloud, @@ -2326,6 +2362,32 @@ async fn register_policy_writes( registration: policy_v3_registration::ActiveModel, policy_cid: &str, roots: [(String, &'static str, Vec, Vec); 2], +) -> Result<(), (Status, String)> { + register_policy_writes_verified( + txn, + tinycloud, + sequence_spaces, + root_delegations, + registration, + policy_cid, + roots, + &tinycloud_core::db::PreVerified::default(), + ) + .await +} + +/// As `register_policy_writes`, with the roots' signatures in `verified` +/// checked before `txn` opened (TC-2986). +#[allow(clippy::too_many_arguments)] +async fn register_policy_writes_verified( + txn: &DatabaseTransaction, + tinycloud: &crate::TinyCloud, + sequence_spaces: &[SpaceId], + root_delegations: Vec, + registration: policy_v3_registration::ActiveModel, + policy_cid: &str, + roots: [(String, &'static str, Vec, Vec); 2], + verified: &tinycloud_core::db::PreVerified, ) -> Result<(), (Status, String)> { tinycloud_core::kv_sync::lock_space_sequences(txn, sequence_spaces) .await @@ -2333,7 +2395,7 @@ async fn register_policy_writes( // The normal graph rows, abilities, and signed-byte projections share one // SQL transaction. A failure in either side leaves no partial authority. tinycloud - .delegate_batch_in_transaction(txn, root_delegations) + .delegate_batch_in_transaction_verified(txn, root_delegations, verified) .await .map_err(|error| (Status::Forbidden, error.to_string()))?; registration @@ -2849,6 +2911,11 @@ pub async fn mint( // TC-732: per-space sequence locks before the row locks below; see // `register_policy`. let sequence_spaces = event.0.spaces().cloned().collect::>(); + // TC-2986: the node-signed session is verified before the locks below. + let verified = tinycloud + .preverify_delegation(&event) + .await + .map_err(|error| (Status::Forbidden, error.to_string()))?; let _sequence_guards = tinycloud .acquire_space_sequence_guards(&sequence_spaces) .await; @@ -2890,7 +2957,7 @@ pub async fn mint( .await .map_err(db_error)? .ok_or((Status::Conflict, "policy-registration-changed".into()))?; - let locked_policy = validate_registration_projection(&locked_registration)?; + validate_registration_projection(&locked_registration)?; if locked_registration.policy_bytes != registration.policy_bytes || locked_registration.policy_root_cid != registration.policy_root_cid || locked_registration.enforcement_root_cid != registration.enforcement_root_cid @@ -2899,7 +2966,6 @@ pub async fn mint( { return Err((Status::Conflict, "policy-registration-changed".into())); } - let mut locked_root_events = Vec::with_capacity(2); for root_cid in [ ®istration.policy_root_cid, ®istration.enforcement_root_cid, @@ -2910,17 +2976,19 @@ pub async fn mint( .await .map_err(db_error)? .ok_or((Status::Forbidden, "policy-root-missing".into()))?; - validate_persisted_root(&root, root_cid, ®istration.policy_cid, &runtime.node_did) - .await - .map_err(|error| (Status::Forbidden, error.into()))?; + // TC-2986: `authorize_roots` verified this CID's signature before + // BEGIN, and the CID binds the bytes; only the projection, time + // window and liveness are checked under the locks. + validate_verified_persisted_root( + &root, + root_cid, + ®istration.policy_cid, + &runtime.node_did, + ) + .map_err(|error| (Status::Forbidden, error.into()))?; validate_root_liveness(&txn, &root, root_cid, &runtime.node_did, now, true) .await .map_err(authorization_failure)?; - let current_event = decode_delegation( - std::str::from_utf8(&root.authorization_bytes) - .map_err(|_| (Status::Forbidden, "policy-root-invalid".into()))?, - )?; - locked_root_events.push(current_event); if root.revoked_at.is_some() || root.revocation_bytes.is_some() || root @@ -2948,95 +3016,12 @@ pub async fn mint( return Err((Status::Conflict, "policy-root-state-changed".into())); } } - let locked_claim_context = ClaimPresentationContext { - challenge_id: &request.challenge_id, - nonce: &request.nonce, - policy_cid: &request.policy_cid, - owner_did: fact(&locked_root_events[0].0.delegation, "ownerDid") - .ok_or((Status::Forbidden, "policy-owner-missing".into()))?, - recipient_did: &locked_challenge.recipient_did, - authenticated_account_owner: account_owner_proof - .as_ref() - .map(|proof| proof.owner_did.as_str()), - now, - }; - let locked_credential_admission_result = if credential_admission { - let locked_requested = locked_challenge - .requested_capabilities - .as_array() - .ok_or((Status::Forbidden, "requested-capabilities-invalid".into()))?; - Some(if accountless_credential_admission { - validate_credential_admission_v4( - &request.requirement, - &request.credential, - &request.presentation, - &locked_policy, - &locked_claim_context, - runtime, - locked_requested, - )? - } else { - validate_credential_admission_v3( - &request.requirement, - &request.credential, - &request.presentation, - &locked_policy, - &locked_claim_context, - runtime, - locked_requested, - )? - }) - } else { - validate_claim_and_presentation( - &request.claim, - &request.presentation, - &locked_claim_context, - )?; - None - }; - if credential_admission_result - .as_ref() - .zip(locked_credential_admission_result.as_ref()) - .is_some_and(|(before, after)| { - before.claim_jti != after.claim_jti - || before.credential_id != after.credential_id - || before.presentation_jti != after.presentation_jti - || before.credential_digest != after.credential_digest - || before.envelope_digest_hex != after.envelope_digest_hex - || before.presentation_digest_hex != after.presentation_digest_hex - || before.credential_space_owner_did != after.credential_space_owner_did - }) - { - return Err((Status::Conflict, "credential-evaluation-changed".into())); - } - validate_requested_policy_capabilities( - locked_challenge - .requested_capabilities - .as_array() - .ok_or((Status::Forbidden, "requested-capabilities-invalid".into()))?, - locked_policy - .get("capabilityCeiling") - .and_then(Value::as_array) - .ok_or((Status::Forbidden, "policy-registration-corrupt".into()))?, - )?; - let final_allow = evaluate_current_allow( - (!credential_admission).then_some(&request.claim), - &request.presentation, - &CurrentAllowContext { - challenge: &locked_challenge, - policy_root: &locked_root_events[0].0.delegation, - enforcement_root: &locked_root_events[1].0.delegation, - policy_root_cid: &locked_registration.policy_root_cid, - enforcement_root_cid: &locked_registration.enforcement_root_cid, - node_did: &runtime.node_did, - now, - }, - )?; - if canonical_value_set(&final_allow.approved_capabilities) - != canonical_value_set(&allow.approved_capabilities) - { - return Err((Status::Conflict, "policy-evaluation-changed".into())); - } + // TC-2986: the claim, presentation and credential admission, the + // requested capabilities and the allow decision were evaluated before + // BEGIN, at this same `now`, from inputs shown equal under the locks + // above: the challenge's fields, the registration's policy bytes and + // root CIDs, and the roots those CIDs content-address. Their result + // cannot differ here, so they are not run again while holding the locks. let reserved = policy_v3_challenge::Entity::update_many() .col_expr( policy_v3_challenge::Column::ConsumedAt, @@ -3058,7 +3043,7 @@ pub async fn mint( ) })?; tinycloud - .delegate_batch_in_transaction(&txn, vec![event]) + .delegate_batch_in_transaction_verified(&txn, vec![event], &verified) .await .map_err(|error| (Status::Forbidden, error.to_string()))?; txn.commit().await.map_err(db_error)?; @@ -4713,6 +4698,25 @@ async fn verify_signed_delegation(delegation: &TinyCloudDelegation) -> Result<() ucan.payload().validate_time(None).map_err(|_| ()) } +/// Verify a policy root before any lock (TC-2986): a UCAN within its time +/// window, whose signature the core checks and records so the root's +/// registration transaction does not check it again. +async fn preverify_root( + tinycloud: &crate::TinyCloud, + root: &Delegation, + refusal: &'static str, +) -> Result { + let refused = || (Status::Forbidden, refusal.to_owned()); + let TinyCloudDelegation::Ucan(ucan) = &root.0.delegation else { + return Err(refused()); + }; + ucan.payload().validate_time(None).map_err(|_| refused())?; + tinycloud + .preverify_delegation(root) + .await + .map_err(|_| refused()) +} + struct RegistrationProjections { content_source_digest_hex: String, capability_ceiling_hash_hex: String, From 520cc64e59c566247d3096527880776f57b512e1 Mon Sep 17 00:00:00 2001 From: "tinycloud-bot[bot]" <348376441+tinycloud-bot[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 19:27:50 +0000 Subject: [PATCH 2/2] test(TC-2986): a mint input changed before the locks refuses the mint --- tinycloud-node-server/src/policy_v3.rs | 4 + .../src/policy_v3/mint_locked_inputs_tests.rs | 282 ++++++++++++++++++ 2 files changed, 286 insertions(+) create mode 100644 tinycloud-node-server/src/policy_v3/mint_locked_inputs_tests.rs diff --git a/tinycloud-node-server/src/policy_v3.rs b/tinycloud-node-server/src/policy_v3.rs index 85c30803..964db0c4 100644 --- a/tinycloud-node-server/src/policy_v3.rs +++ b/tinycloud-node-server/src/policy_v3.rs @@ -12323,3 +12323,7 @@ mod share_key_record_tests; #[cfg(test)] #[path = "policy_v3/policy_root_proof_tests.rs"] mod policy_root_proof_tests; + +#[cfg(test)] +#[path = "policy_v3/mint_locked_inputs_tests.rs"] +mod mint_locked_inputs_tests; diff --git a/tinycloud-node-server/src/policy_v3/mint_locked_inputs_tests.rs b/tinycloud-node-server/src/policy_v3/mint_locked_inputs_tests.rs new file mode 100644 index 00000000..e9703e97 --- /dev/null +++ b/tinycloud-node-server/src/policy_v3/mint_locked_inputs_tests.rs @@ -0,0 +1,282 @@ +//! TC-2986 (F): a policy mint no longer re-runs credential admission, the +//! requested-capability check or the allow decision under its locks. It +//! shows their inputs unchanged instead: the challenge's fields, the +//! registration's bytes, and the roots' state. A change to any of them +//! after the checks and before the locks refuses the mint, and stores no +//! session. +//! +//! Each test holds the content space's write order, sends the mint, and +//! changes the input once the mint has passed its checks and waits for that +//! order. The challenge and registration changes are ones the checks accept, +//! so a change that landed before the checks would let the mint succeed and +//! fail the test; only the comparison under the locks refuses them. + +use super::test_harness::*; +use super::*; +use std::future::Future; +use tinycloud_core::sea_orm::PaginatorTrait; + +/// How long the write order stays held after the mint is sent: far longer +/// than the mint's checks before it, which take milliseconds. +const HOLD: std::time::Duration = std::time::Duration::from_millis(1500); + +async fn registered(h: &Harness) -> anyhow::Result { + h.grant_owner(Window::until(now() + Duration::days(2))) + .await?; + h.register_ok(policy_window()).await +} + +/// Mints for the holder while the content space's write order is held, and +/// applies `change` once the mint waits for it. +async fn mint_changed_while_waiting( + h: &Harness, + policy: &Registered, + change: F, +) -> anyhow::Result> +where + F: FnOnce() -> Fut, + Fut: Future>, +{ + let tinycloud = h.client.rocket().state::().unwrap(); + let held = tinycloud + .acquire_space_sequence_guards(std::slice::from_ref(&h.content_space)) + .await; + let (minted, changed) = tokio::join!(h.mint(policy), async move { + tokio::time::sleep(HOLD).await; + let changed = change().await; + drop(held); + changed + }); + changed?; + minted +} + +async fn sessions(h: &Harness) -> anyhow::Result { + let runtime = h.client.rocket().state::().unwrap(); + Ok(policy_v3_session::Entity::find() + .count(&runtime.conn) + .await?) +} + +/// The challenge's expiry moves later while the mint waits: still a live +/// challenge, but not the one the mint checked. +async fn a_challenge_changed_while_the_mint_waits_is_refused( + backend: Backend, +) -> anyhow::Result<()> { + let Some(h) = Harness::new( + backend, + Shape::KeySession, + "a_challenge_changed_while_the_mint_waits_is_refused", + ) + .await? + else { + return Ok(()); + }; + let policy = registered(&h).await?; + let runtime = h.client.rocket().state::().unwrap(); + let minted = mint_changed_while_waiting(&h, &policy, || async { + let changed = policy_v3_challenge::Entity::update_many() + .col_expr( + policy_v3_challenge::Column::ExpiresAt, + Expr::value(format_time(now() + Duration::seconds(600))), + ) + .filter(policy_v3_challenge::Column::PolicyCid.eq(policy.policy_cid.clone())) + .exec(&runtime.conn) + .await?; + anyhow::ensure!(changed.rows_affected == 1, "one challenge"); + Ok(()) + }) + .await?; + assert_eq!( + minted.unwrap_err(), + (Status::Unauthorized, "challenge-invalid".to_owned()) + ); + assert_eq!(sessions(&h).await?, 0); + Ok(()) +} +on_both_backends!(a_challenge_changed_while_the_mint_waits_is_refused); + +/// The registration's attested enforcer binding is rewritten as the same +/// JSON with other whitespace while the mint waits: it still parses and +/// verifies, but the bytes the mint checked changed. +async fn a_registration_changed_while_the_mint_waits_is_refused( + backend: Backend, +) -> anyhow::Result<()> { + let Some(h) = Harness::new( + backend, + Shape::KeySession, + "a_registration_changed_while_the_mint_waits_is_refused", + ) + .await? + else { + return Ok(()); + }; + let policy = registered(&h).await?; + let runtime = h.client.rocket().state::().unwrap(); + let minted = mint_changed_while_waiting(&h, &policy, || async { + let registration = policy_v3_registration::Entity::find_by_id(policy.policy_cid.clone()) + .one(&runtime.conn) + .await? + .ok_or_else(|| anyhow::anyhow!("registration"))?; + let binding: Value = serde_json::from_slice(®istration.attested_enforcer_binding_bytes)?; + let rewritten = serde_json::to_vec_pretty(&binding)?; + anyhow::ensure!(rewritten != registration.attested_enforcer_binding_bytes); + policy_v3_registration::Entity::update_many() + .col_expr( + policy_v3_registration::Column::AttestedEnforcerBindingBytes, + Expr::value(rewritten), + ) + .filter(policy_v3_registration::Column::PolicyCid.eq(policy.policy_cid.clone())) + .exec(&runtime.conn) + .await?; + Ok(()) + }) + .await?; + assert_eq!( + minted.unwrap_err(), + (Status::Conflict, "policy-registration-changed".to_owned()) + ); + assert_eq!(sessions(&h).await?, 0); + Ok(()) +} +on_both_backends!(a_registration_changed_while_the_mint_waits_is_refused); + +/// The policy root is revoked while the mint waits, after its signature and +/// state were checked: the mint is refused under the locks. +async fn a_root_revoked_while_the_mint_waits_is_refused(backend: Backend) -> anyhow::Result<()> { + let Some(h) = Harness::new( + backend, + Shape::KeySession, + "a_root_revoked_while_the_mint_waits_is_refused", + ) + .await? + else { + return Ok(()); + }; + let policy = registered(&h).await?; + let runtime = h.client.rocket().state::().unwrap(); + let root: tinycloud_auth::ipld_core::cid::Cid = policy.policy_root_cid.parse()?; + let minted = mint_changed_while_waiting(&h, &policy, || async { + // The row a generic revocation of the root stores. + revocation::ActiveModel { + id: Set(hash(policy.policy_root_cid.as_bytes())), + revoker: Set(h.owner.did().to_owned()), + revoked: Set(tinycloud_core::hash::Hash::from(root)), + serialization: Set(b"tc-2986-revocation".to_vec()), + revoked_at: Set(Some(now())), + } + .insert(&runtime.conn) + .await?; + Ok(()) + }) + .await?; + assert_eq!( + minted.unwrap_err(), + (Status::Forbidden, "root-revoked".to_owned()) + ); + assert_eq!(sessions(&h).await?, 0); + Ok(()) +} +on_both_backends!(a_root_revoked_while_the_mint_waits_is_refused); + +/// The registration is repointed at another registered, live policy root +/// while the mint waits: the root CIDs it checked are not the registration's +/// any more. +async fn a_registration_repointed_while_the_mint_waits_is_refused( + backend: Backend, +) -> anyhow::Result<()> { + let Some(h) = Harness::new( + backend, + Shape::KeySession, + "a_registration_repointed_while_the_mint_waits_is_refused", + ) + .await? + else { + return Ok(()); + }; + let policy = registered(&h).await?; + let other = h.register_ok(policy_window()).await?; + anyhow::ensure!(other.policy_root_cid != policy.policy_root_cid); + let runtime = h.client.rocket().state::().unwrap(); + let minted = mint_changed_while_waiting(&h, &policy, || async { + let changed = policy_v3_registration::Entity::update_many() + .col_expr( + policy_v3_registration::Column::PolicyRootCid, + Expr::value(other.policy_root_cid.clone()), + ) + .filter(policy_v3_registration::Column::PolicyCid.eq(policy.policy_cid.clone())) + .exec(&runtime.conn) + .await?; + anyhow::ensure!(changed.rows_affected == 1, "one registration"); + Ok(()) + }) + .await?; + assert_eq!( + minted.unwrap_err(), + (Status::Conflict, "policy-registration-changed".to_owned()) + ); + assert_eq!(sessions(&h).await?, 0); + Ok(()) +} +on_both_backends!(a_registration_repointed_while_the_mint_waits_is_refused); + +/// A compact JWT with one signature character changed: the same header, +/// payload and facts, a signature that does not verify, and another CID. +fn forge_signature(jwt: &str) -> String { + let at = jwt.rfind('.').unwrap() + 6; + let mut bytes = jwt.as_bytes().to_vec(); + bytes[at] = if bytes[at] == b'A' { b'B' } else { b'A' }; + String::from_utf8(bytes).unwrap() +} + +/// The policy root's stored bytes are replaced, while the mint waits, by the +/// same root under a forged signature. The signature is no longer checked +/// under the locks: the root bytes must still hash to the registration's +/// root CID, whose signature was checked before them (Bobbie's #596 review, +/// mutation M2b). +async fn root_bytes_replaced_while_the_mint_waits_are_refused( + backend: Backend, +) -> anyhow::Result<()> { + let Some(h) = Harness::new( + backend, + Shape::KeySession, + "root_bytes_replaced_while_the_mint_waits_are_refused", + ) + .await? + else { + return Ok(()); + }; + let policy = registered(&h).await?; + let runtime = h.client.rocket().state::().unwrap(); + let minted = mint_changed_while_waiting(&h, &policy, || async { + let row = policy_v3_root::Entity::find_by_id(policy.policy_root_cid.clone()) + .one(&runtime.conn) + .await? + .ok_or_else(|| anyhow::anyhow!("root row"))?; + let forged = forge_signature(std::str::from_utf8(&row.authorization_bytes)?); + let decoded = decode_delegation(&forged).map_err(|(_, error)| anyhow::anyhow!(error))?; + anyhow::ensure!(decoded.serialized_bytes() == forged.as_bytes()); + anyhow::ensure!(decoded.content_hash().to_cid(0x55).to_string() != policy.policy_root_cid); + let changed = policy_v3_root::Entity::update_many() + .col_expr( + policy_v3_root::Column::AuthorizationBytes, + Expr::value(forged.into_bytes()), + ) + .filter(policy_v3_root::Column::RootCid.eq(policy.policy_root_cid.clone())) + .exec(&runtime.conn) + .await?; + anyhow::ensure!(changed.rows_affected == 1, "one root"); + Ok(()) + }) + .await?; + assert_eq!( + minted.unwrap_err(), + ( + Status::Forbidden, + "policy-root-projection-mismatch".to_owned() + ) + ); + assert_eq!(sessions(&h).await?, 0); + Ok(()) +} +on_both_backends!(root_bytes_replaced_while_the_mint_waits_are_refused);