From 6203ce48a4caf7bdda2a5ffb114dda68578f15a9 Mon Sep 17 00:00:00 2001 From: "tinycloud-bot[bot]" <348376441+tinycloud-bot[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 03:19:17 +0000 Subject: [PATCH 1/2] fix(TC-3000): refuse /delegate and /revoke requests without standing before any lock; check the signature before policy admission --- CHANGELOG.md | 6 + tinycloud-core/src/db.rs | 59 ++- .../src/db/signature_before_locks_tests.rs | 362 ++++++++++++++++++ tinycloud-core/src/models/delegation.rs | 211 +++++++--- tinycloud-core/src/models/revocation.rs | 76 ++-- tinycloud-core/src/renewal.rs | 70 +++- .../src/policy_v3/policy_root_proof_tests.rs | 42 ++ tinycloud-node-server/src/routes/mod.rs | 33 +- 8 files changed, 760 insertions(+), 99 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1363f22c..5712f8d3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## [Unreleased] ### Changes +- `POST /delegate` and `POST /revoke` refuse a validly signed request that has no standing, or is outside its signed time window, before taking any lock. Before, it took the guards of the delegation chain it cited, queued for the write order of the spaces it named and, on PostgreSQL, held a pooled connection in an open transaction until it was refused. Now it is refused at once: + - a delegation whose issuer neither owns the spaces it names nor holds a stored parent granted to it; + - a revocation by someone who may not revoke its target, or of a target that is not stored; + - a renewal lease not issued by the delegator of the original it renews; + - an expired or not-yet-valid delegation or revocation. + The checks run again inside the transaction, which decides. A delegation already stored still answers as registered when posted again, even after it has expired. Refusal messages are unchanged, except that a stranger's renewal lease is now refused as unauthorized even where its window or shape was also wrong. `/delegate` also checks the request's signature before the Policy/v3 admission reads the graph, so a badly signed delegation citing a policy root answers 401 `Failed to verify signature` instead of 403. Details: TC-3000. - 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 0dc3a977..76c73660 100644 --- a/tinycloud-core/src/db.rs +++ b/tinycloud-core/src/db.rs @@ -2299,6 +2299,21 @@ where } pub async fn delegate(&self, delegation: Delegation) -> Result> { + // TC-2986: the signature is checked before any lock, so a forged or + // slow one never holds the guards or the spaces' write order. + let verified = self.preverify_delegation(&delegation).await?; + self.delegate_verified(delegation, &verified).await + } + + /// As [`Self::delegate`], with the signature `verified` holds, from + /// [`Self::preverify_delegation`] on these exact bytes, so a caller can + /// check it before its own reads (TC-3000). Bytes `verified` does not + /// cover have their signature checked inside the transaction instead. + pub async fn delegate_verified( + &self, + delegation: Delegation, + verified: &PreVerified, + ) -> Result> { if self.secrets.renewal_seed().is_some_and(|seed| { crate::renewal::renewal_identity_from_seed(seed).0 == delegation.0.delegator }) { @@ -2307,10 +2322,6 @@ where )); } let renewal_lease = crate::renewal::lease_original_from_signed(&delegation)?.is_some(); - // TC-2986: the signature is checked before any lock, so a forged or - // slow one never holds the guards or the spaces' write order. - let verified = - PreVerified::delegation(&self.conn, &delegation, self.encryption.as_ref()).await?; let parent_hashes: Vec = delegation .0 .parents @@ -2319,6 +2330,41 @@ where .map(Hash::from) .collect(); let retained_hash = delegation.content_hash(); + // TC-3000: its time window and its issuer's standing are checked on + // the pool too, so a stranger's or an expired delegation never queues + // behind the guards and write order of the chain and spaces it names. + let precheck = if renewal_lease { + delegation::check_owner_renewal_lease(&delegation).map_err(TxError::from) + } else { + delegation::precheck( + &self.conn, + &delegation, + self.delegated_sql_caveats, + self.named_keys, + self.renewal_identity + .as_ref() + .map(|identity| identity.renewer_did.as_str()), + ) + .await + .map_err(TxError::from) + }; + if let Err(refused) = precheck { + // A delegation already stored answers as before, even once it + // has expired: these exact signed bytes are already registered. + if !renewal_lease + && delegation::Entity::find_by_id(retained_hash) + .one(&self.conn) + .await + .map_err(TxError::Db)? + .is_some() + { + for space in delegation.0.spaces() { + crate::request_telemetry::observe_space(space); + } + return Ok(already_registered_result(retained_hash)); + } + return Err(refused); + } // Capture expected row counts before consuming the delegation. let expected_ability_count = delegation.0.capabilities.len() as u64; let expected_parent_count = parent_hashes.len() as u64; @@ -2350,7 +2396,7 @@ where Err(e) => return Err(TxError::Db(e)), } match self - .transact_verified(vec![Event::Delegation(Box::new(delegation))], &verified) + .transact_verified(vec![Event::Delegation(Box::new(delegation))], verified) .await { Err(TxError::EpochInsert(epoch_err)) => { @@ -2465,6 +2511,9 @@ where pub async fn revoke(&self, revocation: Revocation) -> Result> { // TC-2986: the signature is checked before any lock. let verified = PreVerified::revocation(&revocation).await?; + // TC-3000: and its time window, target and revoker, on the pool, so a + // stranger's or an expired revocation takes no lock. + revocation::precheck(&self.conn, &revocation).await?; let mut roots = vec![Hash::from(revocation.0.revoked)]; roots.extend(revocation.0.parents.iter().copied().map(Hash::from)); let revocation_start = Instant::now(); diff --git a/tinycloud-core/src/db/signature_before_locks_tests.rs b/tinycloud-core/src/db/signature_before_locks_tests.rs index b247f20a..dc78eb65 100644 --- a/tinycloud-core/src/db/signature_before_locks_tests.rs +++ b/tinycloud-core/src/db/signature_before_locks_tests.rs @@ -707,4 +707,366 @@ mod binding { ); lock.rollback().await.unwrap(); } + + // TC-3000 (F1): a validly signed request without standing, or out of its + // time window, is refused before it takes any lock. Bobbie's #595 + // residual probes, inverted. + + const QUICK: std::time::Duration = std::time::Duration::from_secs(5); + const BRIEF: std::time::Duration = std::time::Duration::from_millis(500); + + /// A stranger's root grant on another tenant's space. + #[tokio::test] + async fn a_stranger_signed_delegation_is_refused_without_waiting_for_the_victim_space() { + let f = sqlite_fx().await; + let stranger = JWK::generate_ed25519().unwrap(); + let token = ucan( + &stranger, + &stranger, + &did_vm(&f.holder).0, + &kv(&f.space), + "tinycloud.kv/get", + ); + let held = + f.db.acquire_space_sequence_guards(std::slice::from_ref(&f.space)) + .await; + let r = tokio::time::timeout(QUICK, f.db.delegate(deleg(&token))) + .await + .expect("a stranger's delegation must not wait for the victim's write order"); + assert!( + matches!( + r, + Err(TxError::InvalidDelegation( + delegation::DelegationError::MissingParents + )) + ), + "{}", + short(&r) + ); + drop(held); + } + + /// A stranger's revocation of another tenant's delegation. + #[tokio::test] + async fn a_stranger_signed_revocation_is_refused_without_waiting_for_the_victim_space() { + let f = sqlite_fx().await; + let g = ucan( + &f.owner, + &f.owner, + &did_vm(&f.holder).0, + &kv(&f.space), + "tinycloud.kv/get", + ); + f.db.delegate(deleg(&g)) + .await + .map_err(|e| e.to_string()) + .unwrap(); + let stranger = JWK::generate_ed25519().unwrap(); + let (node, _) = did_vm(&JWK::generate_ed25519().unwrap()); + let token = ucan( + &stranger, + &stranger, + &node, + &format!("urn:cid:{}", cid_of(&g)), + "tinycloud.delegation/revoke", + ); + let held = + f.db.acquire_space_sequence_guards(std::slice::from_ref(&f.space)) + .await; + let r = tokio::time::timeout(QUICK, f.db.revoke(revoc(&token))) + .await + .expect("a stranger's revocation must not wait for the victim's write order"); + assert!( + matches!( + r, + Err(TxError::InvalidRevocation( + revocation::RevocationError::UnauthorizedRevoker(_) + )) + ), + "{}", + short(&r) + ); + drop(held); + } + + /// The owner's own delegation, signed but already expired. + #[tokio::test] + async fn an_expired_delegation_is_refused_without_waiting_for_its_space() { + let f = sqlite_fx().await; + let token = ucan_full( + &f.owner, + &f.owner, + &did_vm(&f.holder).0, + &kv(&f.space), + "tinycloud.kv/get", + vec![], + now() - 7200, + now() - 3600, + ); + let held = + f.db.acquire_space_sequence_guards(std::slice::from_ref(&f.space)) + .await; + let r = tokio::time::timeout(QUICK, f.db.delegate(deleg(&token))) + .await + .expect("an expired delegation must not wait for its space's write order"); + assert!( + matches!( + r, + Err(TxError::InvalidDelegation( + delegation::DelegationError::InvalidTime + )) + ), + "{}", + short(&r) + ); + drop(held); + } + + /// The owner's own revocation, signed but already expired. + #[tokio::test] + async fn an_expired_revocation_is_refused_without_waiting_for_its_target() { + let f = sqlite_fx().await; + let g = ucan( + &f.owner, + &f.owner, + &did_vm(&f.holder).0, + &kv(&f.space), + "tinycloud.kv/get", + ); + f.db.delegate(deleg(&g)) + .await + .map_err(|e| e.to_string()) + .unwrap(); + let victim = cid_of(&g); + let (node, _) = did_vm(&JWK::generate_ed25519().unwrap()); + let token = ucan_full( + &f.owner, + &f.owner, + &node, + &format!("urn:cid:{victim}"), + "tinycloud.delegation/revoke", + vec![], + now() - 7200, + now() - 3600, + ); + let held = + f.db.acquire_chain_guards(&[Hash::from(victim)]) + .await + .ok() + .expect("guard"); + let r = tokio::time::timeout(QUICK, f.db.revoke(revoc(&token))) + .await + .expect("an expired revocation must not wait for its target's chain guard"); + assert!( + matches!( + r, + Err(TxError::InvalidRevocation( + revocation::RevocationError::InvalidTime + )) + ), + "{}", + short(&r) + ); + drop(held); + } + + /// A child citing a stored grant made to someone else, while that + /// grant's chain guard is held, and a child citing a parent that is not + /// stored, while its space's write order is held. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn a_child_without_a_parent_granted_to_its_issuer_is_refused_without_waiting() { + let f = sqlite_fx().await; + let g = ucan( + &f.owner, + &f.owner, + &did_vm(&f.holder).0, + &kv(&f.space), + "tinycloud.kv/get", + ); + f.db.delegate(deleg(&g)) + .await + .map_err(|e| e.to_string()) + .unwrap(); + let victim = cid_of(&g); + let stranger = JWK::generate_ed25519().unwrap(); + let audience = did_vm(&JWK::generate_ed25519().unwrap()).0; + let not_granted = ucan_full( + &stranger, + &stranger, + &audience, + &kv(&f.space), + "tinycloud.kv/get", + vec![victim], + now() - 30, + now() + 300, + ); + let held = + f.db.acquire_chain_guards(&[Hash::from(victim)]) + .await + .ok() + .expect("guard"); + let r = tokio::time::timeout(QUICK, f.db.delegate(deleg(¬_granted))) + .await + .expect("a child of a grant to someone else must not wait for its chain guard"); + assert!( + matches!( + r, + Err(TxError::InvalidDelegation( + delegation::DelegationError::UnauthorizedDelegator(_) + )) + ), + "{}", + short(&r) + ); + drop(held); + + let missing = ucan_full( + &stranger, + &stranger, + &audience, + &kv(&f.space), + "tinycloud.kv/get", + vec![cid_of("tc3000-not-stored")], + now() - 30, + now() + 300, + ); + let held = + f.db.acquire_space_sequence_guards(std::slice::from_ref(&f.space)) + .await; + let r = tokio::time::timeout(QUICK, f.db.delegate(deleg(&missing))) + .await + .expect("a child of a missing parent must not wait for its space's write order"); + assert!( + matches!( + r, + Err(TxError::InvalidDelegation( + delegation::DelegationError::MissingParents + )) + ), + "{}", + short(&r) + ); + drop(held); + } + + /// The pre-check refuses only what has no standing: the owner's grant and + /// its holder's child still queue for their locks and are admitted. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn delegations_with_standing_still_wait_for_their_locks_and_are_admitted() { + let f = sqlite_fx().await; + let holder = did_vm(&f.holder).0; + let grant = ucan( + &f.owner, + &f.owner, + &holder, + &kv(&f.space), + "tinycloud.kv/get", + ); + let held = + f.db.acquire_space_sequence_guards(std::slice::from_ref(&f.space)) + .await; + let db = f.db.clone(); + let pending = { + let grant = grant.clone(); + tokio::spawn(async move { short(&db.delegate(deleg(&grant)).await) }) + }; + tokio::time::sleep(BRIEF).await; + assert!( + !pending.is_finished(), + "the owner's grant must wait for its space's write order" + ); + drop(held); + assert_eq!(pending.await.unwrap(), "Ok"); + + let parent = cid_of(&grant); + let child = ucan_full( + &f.holder, + &f.holder, + &did_vm(&JWK::generate_ed25519().unwrap()).0, + &kv(&f.space), + "tinycloud.kv/get", + vec![parent], + now() - 30, + now() + 300, + ); + let held = + f.db.acquire_chain_guards(&[Hash::from(parent)]) + .await + .ok() + .expect("guard"); + let db = f.db.clone(); + let pending = tokio::spawn(async move { short(&db.delegate(deleg(&child)).await) }); + tokio::time::sleep(BRIEF).await; + assert!( + !pending.is_finished(), + "the holder's child must wait for its parent's chain guard" + ); + drop(held); + assert_eq!(pending.await.unwrap(), "Ok"); + } + + /// A delegation already stored answers as registered when posted again, + /// even after it has expired, as it did before the pre-check. + #[tokio::test] + async fn a_stored_delegation_posted_again_after_it_expired_is_still_registered() { + let f = sqlite_fx().await; + let token = ucan_full( + &f.owner, + &f.owner, + &did_vm(&f.holder).0, + &kv(&f.space), + "tinycloud.kv/get", + vec![], + now() - 30, + now() + 2, + ); + f.db.delegate(deleg(&token)) + .await + .map_err(|e| e.to_string()) + .unwrap(); + tokio::time::sleep(std::time::Duration::from_secs(3)).await; + let r = f.db.delegate(deleg(&token)).await; + assert_eq!(short(&r), "Ok"); + assert_eq!( + r.ok().map(|result| result.delegation_cids), + Some(vec![crate::hash::hash(token.as_bytes())]) + ); + } + + /// TC-3000 on PostgreSQL: a stranger's delegation does not open a + /// transaction to wait for the database-side space lock. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn postgres_a_stranger_signed_delegation_is_refused_while_the_database_space_lock_is_held( + ) { + let Some(f) = pg_fx( + "postgres_a_stranger_signed_delegation_is_refused_while_the_database_space_lock_is_held", + ) + .await + else { + return; + }; + let stranger = JWK::generate_ed25519().unwrap(); + let token = ucan( + &stranger, + &stranger, + &did_vm(&f.holder).0, + &kv(&f.space), + "tinycloud.kv/get", + ); + let lock = hold_pg_space_lock(&f).await; + let r = tokio::time::timeout(QUICK, f.db.delegate(deleg(&token))) + .await + .expect("a stranger's delegation must not wait for the DB space lock"); + assert!( + matches!( + r, + Err(TxError::InvalidDelegation( + delegation::DelegationError::MissingParents + )) + ), + "{}", + short(&r) + ); + lock.rollback().await.unwrap(); + } } diff --git a/tinycloud-core/src/models/delegation.rs b/tinycloud-core/src/models/delegation.rs index 5338e4d0..9f100eff 100644 --- a/tinycloud-core/src/models/delegation.rs +++ b/tinycloud-core/src/models/delegation.rs @@ -10,7 +10,7 @@ use sea_orm::ActiveValue::Set; use sea_orm::{ entity::prelude::*, sea_query::{Alias, CommonTableExpression, Expr, OnConflict, Query, WithClause}, - ConnectionTrait, DbBackend, QueryTrait, Statement, + ConnectionTrait, DbBackend, QuerySelect, QueryTrait, Statement, }; use std::collections::BTreeMap; use time::OffsetDateTime; @@ -272,13 +272,7 @@ pub(crate) async fn save_owner_renewal_lease( if !signature_verified { check_signature(&delegation.0.delegation).await?; } - verify_time(&delegation.0.delegation)?; - if !delegation.0.parents.is_empty() - || !crate::renewal::lease_original_from_signed(delegation) - .is_ok_and(|original| original.is_some()) - { - return Err(DelegationError::MissingParents.into()); - } + check_owner_renewal_lease(delegation)?; save(db, delegation.0.clone(), delegation.1.clone(), encryption).await } @@ -484,57 +478,11 @@ async fn validate_with( if renewal_identity.is_some_and(|(_, renewer_did, _)| delegation.delegator == renewer_did) { return Err(DelegationError::UnauthorizedDelegator(delegation.delegator.clone()).into()); } - for parent in &delegation.parents { - let parent_id = Hash::from(*parent); - let is_renewal_lease = db - .query_one(Statement::from_sql_and_values( - db.get_database_backend(), - "SELECT 1 AS lease FROM renewal_lease WHERE lease_cid = $1 LIMIT 1", - [sea_orm::sea_query::Value::Bytes(Some(Box::new( - parent_id.as_ref().to_vec(), - )))], - )) - .await?; - if is_renewal_lease.is_some() { - return Err(DelegationError::MissingParents.into()); - } - } - // Without named keys, a capability on a key or key prefix is refused for - // every delegation, before the root-authority filter, so a delegation - // issued by the key's owner is covered too. - if !named_keys - && delegation - .capabilities - .iter() - .any(|cap| cap.resource.is_named_key()) - { - return Err(DelegationError::NamedKeysUnavailable.into()); - } - check_app_id_domain_binding(delegation)?; - // TC-1791: SQL and DuckDB caveats are checked for every delegation, - // before the root-authority filter. - for cap in &delegation.capabilities { - check_sql_caveats_supported(cap, delegated_sql_caveats)?; - } - // Key deletion is never delegated, including by the key's owner. - if delegation.capabilities.iter().any(|cap| { - crate::policy_capability::ability_matches( - &cap.ability.to_string(), - "tinycloud.encryption/key.delete", - ) - }) { - return Err(DelegationError::KeyDeleteNotDelegable.into()); - } + refuse_renewal_lease_parents(db, delegation).await?; + check_capability_rules(delegation, delegated_sql_caveats, named_keys)?; // get caps which rely on delegated caps - let dependant_caps: Vec<_> = delegation - .capabilities - .iter() - .filter(|c| { - // remove caps for which the delegator is the root authority - !is_root_authority(c, &delegation.delegator) - }) - .collect(); + let dependant_caps = dependant_capabilities(delegation); match (dependant_caps.is_empty(), delegation.parents.is_empty()) { // no dependant caps, no parents needed, must be valid @@ -841,6 +789,155 @@ async fn validate_with( } } +/// A renewal lease is never a parent: a child citing one is refused as if the +/// parent were missing. +async fn refuse_renewal_lease_parents( + db: &C, + delegation: &util::DelegationInfo, +) -> Result<(), Error> { + for parent in &delegation.parents { + let parent_id = Hash::from(*parent); + let is_renewal_lease = db + .query_one(Statement::from_sql_and_values( + db.get_database_backend(), + "SELECT 1 AS lease FROM renewal_lease WHERE lease_cid = $1 LIMIT 1", + [sea_orm::sea_query::Value::Bytes(Some(Box::new( + parent_id.as_ref().to_vec(), + )))], + )) + .await?; + if is_renewal_lease.is_some() { + return Err(DelegationError::MissingParents.into()); + } + } + Ok(()) +} + +/// The rules on a delegation's own capabilities that hold whoever issues it. +fn check_capability_rules( + delegation: &util::DelegationInfo, + delegated_sql_caveats: bool, + named_keys: bool, +) -> Result<(), Error> { + // Without named keys, a capability on a key or key prefix is refused for + // every delegation, before the root-authority filter, so a delegation + // issued by the key's owner is covered too. + if !named_keys + && delegation + .capabilities + .iter() + .any(|cap| cap.resource.is_named_key()) + { + return Err(DelegationError::NamedKeysUnavailable.into()); + } + check_app_id_domain_binding(delegation)?; + // TC-1791: SQL and DuckDB caveats are checked for every delegation, + // before the root-authority filter. + for cap in &delegation.capabilities { + check_sql_caveats_supported(cap, delegated_sql_caveats)?; + } + // Key deletion is never delegated, including by the key's owner. + if delegation.capabilities.iter().any(|cap| { + crate::policy_capability::ability_matches( + &cap.ability.to_string(), + "tinycloud.encryption/key.delete", + ) + }) { + return Err(DelegationError::KeyDeleteNotDelegable.into()); + } + Ok(()) +} + +/// The capabilities the issuer does not hold as a root authority, which a +/// parent or an owner revoke grant has to support. +fn dependant_capabilities(delegation: &util::DelegationInfo) -> Vec<&util::Capability> { + delegation + .capabilities + .iter() + .filter(|c| !is_root_authority(c, &delegation.delegator)) + .collect() +} + +/// The checks of [`process_with`] that need no lock, run on the pool before +/// a delegation takes any chain guard, space write order or transaction +/// (TC-3000): its signed time window, and the issuer's standing. A stranger +/// naming another tenant's space or parent, or an expired delegation, is +/// refused here instead of queueing behind that tenant's locks. +/// +/// The issuer has standing when it is the root authority for every +/// capability, or holds an owner revoke grant on each other capability, or +/// each cited parent is stored and was granted to it. Every check runs again +/// inside the transaction, which stays the authority. In error order this +/// follows [`process_with`], except that a cited parent is read directly +/// instead of through the transaction's graph snapshot. +pub(crate) async fn precheck( + db: &C, + delegation: &Delegation, + delegated_sql_caveats: bool, + named_keys: bool, + renewer_did: Option<&str>, +) -> Result<(), Error> { + verify_time(&delegation.0.delegation)?; + let delegation = &delegation.0; + if renewer_did.is_some_and(|renewer_did| delegation.delegator == renewer_did) { + return Err(DelegationError::UnauthorizedDelegator(delegation.delegator.clone()).into()); + } + refuse_renewal_lease_parents(db, delegation).await?; + check_capability_rules(delegation, delegated_sql_caveats, named_keys)?; + let dependant_caps = dependant_capabilities(delegation); + if dependant_caps.is_empty() { + return Ok(()); + } + if delegation.parents.is_empty() { + if is_policy_root(&delegation.delegation) { + return Ok(()); + } + for cap in &dependant_caps { + if !revocation::owner_controls_target(db, &delegation.delegator, cap).await? { + return Err(DelegationError::MissingParents.into()); + } + } + return Ok(()); + } + let parent_ids: Vec = delegation.parents.iter().copied().map(Hash::from).collect(); + let delegatees: std::collections::HashMap = Entity::find() + .select_only() + .column(Column::Id) + .column(Column::Delegatee) + .filter(Column::Id.is_in(parent_ids.iter().copied())) + .into_tuple::<(Hash, String)>() + .all(db) + .await? + .into_iter() + .collect(); + let policy_session = is_policy_session(&delegation.delegation); + for id in &parent_ids { + let Some(delegatee) = delegatees.get(id) else { + return Err(DelegationError::MissingParents.into()); + }; + if !policy_session && *delegatee != delegation.delegator { + return Err( + DelegationError::UnauthorizedDelegator(delegation.delegator.clone()).into(), + ); + } + } + Ok(()) +} + +/// The checks of [`save_owner_renewal_lease`] that need neither the database +/// nor a lock: the lease's time window, no cited parents, and a signed +/// original to renew. +pub(crate) fn check_owner_renewal_lease(delegation: &Delegation) -> Result<(), Error> { + verify_time(&delegation.0.delegation)?; + if !delegation.0.parents.is_empty() + || !crate::renewal::lease_original_from_signed(delegation) + .is_ok_and(|original| original.is_some()) + { + return Err(DelegationError::MissingParents.into()); + } + Ok(()) +} + fn is_policy_session(delegation: &TinyCloudDelegation) -> bool { let TinyCloudDelegation::Ucan(ucan) = delegation else { return false; diff --git a/tinycloud-core/src/models/revocation.rs b/tinycloud-core/src/models/revocation.rs index 1aedfff0..0f036cab 100644 --- a/tinycloud-core/src/models/revocation.rs +++ b/tinycloud-core/src/models/revocation.rs @@ -744,8 +744,6 @@ pub(crate) async fn process_with( ) -> Result { let (r, serialization) = (revocation.0, revocation.1); - let t = OffsetDateTime::now_utc(); - // W1 (audit P0 finding 5): verify both CACAO and did:key/UCAN format // revocations. The route accepts either suite so the Policy Engine // active_cutoff loop can rely on a single endpoint regardless of @@ -753,32 +751,8 @@ pub(crate) async fn process_with( if !signature_verified { check_signature(&r.revocation).await?; } - let in_window = match &r.revocation { - TinyCloudRevocation::Cacao(c) => c.payload().valid_at(&t), - TinyCloudRevocation::Ucan(u) => u.payload().validate_time(None).is_ok(), - }; - if !in_window { - return Err(RevocationError::InvalidTime.into()); - } - + let delegation = check_standing(db, &r).await?; let hash: Hash = hash(&serialization); - let requested = Hash::from(r.revoked); - let delegation = target_for_cid(db, requested) - .await? - .ok_or(RevocationError::MissingParents)?; - - // W1 (audit P0 finding 5) and TC-1436: authorized revokers are - // 1. the delegator that issued this delegation (an intermediate - // delegator revokes the descendants it issued), or - // 2. the owner of a space the delegation's persisted abilities - // target (owner-authorized active_cutoff), or - // 3. the holder of a current revoke control grant issued by one of - // the above. - // The delegatee alone is never authorized: it may hold a key that - // others share, and revoking would cut them off as well. - if !revoker_is_authorized(db, &delegation, &requested, &r.revoker, &r.parents).await? { - return Err(RevocationError::UnauthorizedRevoker(r.revoker).into()); - }; match Entity::insert(ActiveModel::from(Model { id: hash, @@ -811,6 +785,54 @@ pub(crate) async fn process_with( Ok(hash) } +/// The checks of [`process_with`] after the signature: the revocation's time +/// window now, its target is stored, and the revoker may revoke it. Returns +/// the stored target. +async fn check_standing( + db: &C, + r: &crate::util::RevocationInfo, +) -> Result { + let t = OffsetDateTime::now_utc(); + let in_window = match &r.revocation { + TinyCloudRevocation::Cacao(c) => c.payload().valid_at(&t), + TinyCloudRevocation::Ucan(u) => u.payload().validate_time(None).is_ok(), + }; + if !in_window { + return Err(RevocationError::InvalidTime.into()); + } + + let requested = Hash::from(r.revoked); + let delegation = target_for_cid(db, requested) + .await? + .ok_or(RevocationError::MissingParents)?; + + // W1 (audit P0 finding 5) and TC-1436: authorized revokers are + // 1. the delegator that issued this delegation (an intermediate + // delegator revokes the descendants it issued), or + // 2. the owner of a space the delegation's persisted abilities + // target (owner-authorized active_cutoff), or + // 3. the holder of a current revoke control grant issued by one of + // the above. + // The delegatee alone is never authorized: it may hold a key that + // others share, and revoking would cut them off as well. + if !revoker_is_authorized(db, &delegation, &requested, &r.revoker, &r.parents).await? { + return Err(RevocationError::UnauthorizedRevoker(r.revoker.clone()).into()); + } + Ok(delegation) +} + +/// The checks of [`process_with`] after the signature, run on the pool +/// before a revocation takes any chain guard, space write order or +/// transaction (TC-3000): a stranger or an expired revocation is refused here +/// instead of queueing behind the target's locks. They run again inside the +/// transaction, which stays the authority. +pub(crate) async fn precheck( + db: &C, + revocation: &Revocation, +) -> Result<(), Error> { + check_standing(db, &revocation.0).await.map(|_| ()) +} + /// Check a revocation's signature: CPU, or a DID resolution when network /// methods are on. Runs before any lock (TC-2986). pub(crate) async fn check_signature(revocation: &TinyCloudRevocation) -> Result<(), Error> { diff --git a/tinycloud-core/src/renewal.rs b/tinycloud-core/src/renewal.rs index bc2e8a14..d7331bed 100644 --- a/tinycloud-core/src/renewal.rs +++ b/tinycloud-core/src/renewal.rs @@ -804,8 +804,10 @@ async fn register_lease_at( /// Check the stored original a renewal lease renews, on `db`, before the /// lease's transaction (TC-2986): it must be stored, match its address and -/// verify, as the transaction requires. Returns its content hash. The -/// lease's own signature is checked by the caller. +/// verify, as the transaction requires, and the lease must be issued by the +/// original's delegator (TC-3000), so a stranger's lease takes no lock. +/// Returns its content hash. The lease's own signature is checked by the +/// caller. pub(crate) async fn preverify_lease_original( db: &C, lease_event: &crate::events::Delegation, @@ -817,7 +819,11 @@ pub(crate) async fn preverify_lease_original( let (original_bytes, _) = stored_original(db, original, encryption) .await? .ok_or(RenewalStoreError::InvalidInput)?; - verify_signed_signature(&signed_delegation_info(&original_bytes)?).await?; + let original_info = signed_delegation_info(&original_bytes)?; + verify_signed_signature(&original_info).await?; + if lease_event.0.delegator != original_info.delegator { + return Err(RenewalStoreError::Unauthorized); + } Ok(original) } @@ -2312,4 +2318,62 @@ mod tests { ); tx.rollback().await.unwrap(); } + + /// TC-3000 (F5): a stored original is used only when its bytes hash to + /// the address the lease names, so a replaced or tampered row is refused + /// before and inside the lease's transaction. + #[tokio::test] + async fn a_stored_original_whose_bytes_do_not_match_its_address_is_refused() { + let db = Database::connect(ConnectOptions::new("sqlite::memory:".to_owned())) + .await + .unwrap(); + crate::migrations::Migrator::up(&db, None).await.unwrap(); + let fixture: serde_json::Value = serde_json::from_str(include_str!( + "../../tinycloud-node-server/tests/fixtures/renewal-lease-v1.json" + )) + .unwrap(); + let original_bytes = fixture["originalToken"] + .as_str() + .unwrap() + .as_bytes() + .to_vec(); + let original = hash(&original_bytes); + let info = signed_delegation_info(&original_bytes).unwrap(); + for actor in [&info.delegator, &info.delegate] { + db.execute(Statement::from_sql_and_values( + DatabaseBackend::Sqlite, + "INSERT INTO actor (id) VALUES ($1)", + [Value::String(Some(Box::new(actor.clone())))], + )) + .await + .unwrap(); + } + let store = |serialization: Vec| { + Statement::from_sql_and_values( + DatabaseBackend::Sqlite, + "INSERT INTO delegation (id, delegator, delegatee, expiry, issued_at, not_before, facts, serialization, serialization_format) VALUES ($1,$2,$3,NULL,NULL,NULL,NULL,$4,0) ON CONFLICT (id) DO UPDATE SET serialization = excluded.serialization", + [ + Value::Bytes(Some(Box::new(Vec::::from(original)))), + Value::String(Some(Box::new(info.delegator.clone()))), + Value::String(Some(Box::new(info.delegate.clone()))), + Value::Bytes(Some(Box::new(serialization))), + ], + ) + }; + + db.execute(store(original_bytes.clone())).await.unwrap(); + let (stored, _) = stored_original(&db, original, None) + .await + .unwrap() + .expect("stored"); + assert_eq!(stored, original_bytes); + + let mut tampered = original_bytes.clone(); + *tampered.last_mut().unwrap() ^= 1; + db.execute(store(tampered)).await.unwrap(); + assert!(matches!( + stored_original(&db, original, None).await, + Err(RenewalStoreError::InvalidInput) + )); + } } diff --git a/tinycloud-node-server/src/policy_v3/policy_root_proof_tests.rs b/tinycloud-node-server/src/policy_v3/policy_root_proof_tests.rs index 9c5a68e7..7e91075e 100644 --- a/tinycloud-node-server/src/policy_v3/policy_root_proof_tests.rs +++ b/tinycloud-node-server/src/policy_v3/policy_root_proof_tests.rs @@ -805,3 +805,45 @@ async fn delivery_holds_a_session_to_its_conditions(backend: Backend) -> anyhow: Ok(()) } on_both_backends!(delivery_holds_a_session_to_its_conditions); + +/// TC-3000 (F6): `/delegate` checks the request's own signature before the +/// policy admission reads anything. A delegation citing a registered root is +/// refused by the admission when it is well signed, and as badly signed, +/// before the admission, when its signature does not verify. +async fn delegate_checks_the_signature_before_policy_admission( + backend: Backend, +) -> anyhow::Result<()> { + let Some(h) = Harness::new( + backend, + Shape::KeySession, + "delegate_checks_the_signature_before_policy_admission", + ) + .await? + else { + return Ok(()); + }; + h.grant_owner(policy_window()).await?; + let policy = h.register_ok(policy_window()).await?; + let root: Cid = policy.policy_root_cid.parse()?; + let grant = [(h.content_resource.to_string(), "tinycloud.kv/get")]; + let signed = h + .enforcer + .delegate(h.enforcer.did(), &grant, policy_window(), &[root])?; + assert_eq!( + h.delegate(signed.clone()).await, + ( + Status::Forbidden, + "policy-root-cannot-be-ordinary-parent".to_owned() + ) + ); + + // The same claims under another key's signature. + let (claims, _) = signed.rsplit_once('.').expect("a JWT"); + let other = Signer::key().delegate(h.enforcer.did(), &grant, policy_window(), &[root])?; + let (_, signature) = other.rsplit_once('.').expect("a JWT"); + let (status, body) = h.delegate(format!("{claims}.{signature}")).await; + assert_eq!(status, Status::Unauthorized, "{body}"); + assert!(body.contains("Failed to verify signature"), "{body}"); + Ok(()) +} +on_both_backends!(delegate_checks_the_signature_before_policy_admission); diff --git a/tinycloud-node-server/src/routes/mod.rs b/tinycloud-node-server/src/routes/mod.rs index 6304df89..ad46925e 100644 --- a/tinycloud-node-server/src/routes/mod.rs +++ b/tinycloud-node-server/src/routes/mod.rs @@ -263,6 +263,22 @@ where } } +/// The answer to a refused `/delegate`: a revocation refusal carries its +/// code (TC-2381); anything else is [`delegation_failure`]. +fn delegate_refusal( + error: &TxError, + write_may_have_applied: bool, +) -> InvokeError +where + S::Error: std::fmt::Display, + K::Error: std::fmt::Display, +{ + match error.revocation_code() { + Some(code) => InvokeError::Revoked(code, error.to_string()), + None => delegation_failure(error, write_may_have_applied).into(), + } +} + /// `/invoke` and `/delegate` failure: plain text for everything except /// storage rejections, which carry the structured TC-619 JSON body, and /// revocation refusals, which carry a stable `code` (TC-2381). @@ -835,8 +851,15 @@ pub async fn delegate( let span = info_span!(parent: &req_span.0, "delegate", action = %action_label); // Instrumenting async block to handle yielding properly async move { + let delegation = d.0; + // TC-3000: the request's own signature is checked first, so the + // policy admission's reads never run for a forged one. + let verified = tinycloud + .preverify_delegation(&delegation) + .await + .map_err(|e| delegate_refusal(&e, false))?; policy_v3 - .ordinary_admission_allowed(tinycloud, &d.0) + .ordinary_admission_allowed(tinycloud, &delegation) .await .map_err(crate::policy_v3::authorization_failure)?; let timer = crate::prometheus::enabled().then(|| { @@ -846,19 +869,15 @@ pub async fn delegate( }); // One retry of the whole operation after a connection lost before // any write (TC-2346); see `track_writes_retrying`. - let delegation = d.0; let (res, write_may_have_applied) = track_writes_retrying( "delegate", tinycloud.connection().retry_window(), - || tinycloud.delegate(delegation.clone()), + || tinycloud.delegate_verified(delegation.clone(), &verified), tx_database_error, ) .await; let res = res - .map_err(|e| match e.revocation_code() { - Some(code) => InvokeError::Revoked(code, e.to_string()), - None => delegation_failure(&e, write_may_have_applied).into(), - }) + .map_err(|e| delegate_refusal(&e, write_may_have_applied)) .and_then(|result: TransactResult| { let TransactResult { commits, From 3bd810ca11174c420820481a5d41e8ac5ed07ff0 Mon Sep 17 00:00:00 2001 From: "tinycloud-bot[bot]" <348376441+tinycloud-bot[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 04:11:20 +0000 Subject: [PATCH 2/2] test(TC-3000): pin the in-transaction revoker and time checks and the stranger-lease pre-check; preverify uncovered bytes in delegate_verified --- CHANGELOG.md | 2 +- tinycloud-core/src/db.rs | 20 ++- .../src/db/signature_before_locks_tests.rs | 161 ++++++++++++++++++ 3 files changed, 176 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5712f8d3..e67926c3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ - a revocation by someone who may not revoke its target, or of a target that is not stored; - a renewal lease not issued by the delegator of the original it renews; - an expired or not-yet-valid delegation or revocation. - The checks run again inside the transaction, which decides. A delegation already stored still answers as registered when posted again, even after it has expired. Refusal messages are unchanged, except that a stranger's renewal lease is now refused as unauthorized even where its window or shape was also wrong. `/delegate` also checks the request's signature before the Policy/v3 admission reads the graph, so a badly signed delegation citing a policy root answers 401 `Failed to verify signature` instead of 403. Details: TC-3000. + The checks run again inside the transaction, which decides. A delegation already stored still answers as registered when posted again, even after it has expired. **Clients that post a child without waiting for its parent's response must retry:** a child whose parent is not yet stored is now refused at once with 401 `Cannot find parent delegation`. Before, it could sometimes wait for the parent's write and be admitted. Refusal messages are unchanged, except that a stranger's renewal lease is now refused as unauthorized even where its window or shape was also wrong. `/delegate` also checks the request's signature before the Policy/v3 admission reads the graph, so a badly signed delegation citing a policy root answers 401 `Failed to verify signature` instead of 403. Details: TC-3000. - 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 76c73660..70741f23 100644 --- a/tinycloud-core/src/db.rs +++ b/tinycloud-core/src/db.rs @@ -2299,16 +2299,15 @@ where } pub async fn delegate(&self, delegation: Delegation) -> Result> { - // TC-2986: the signature is checked before any lock, so a forged or - // slow one never holds the guards or the spaces' write order. - let verified = self.preverify_delegation(&delegation).await?; - self.delegate_verified(delegation, &verified).await + self.delegate_verified(delegation, &PreVerified::default()) + .await } /// As [`Self::delegate`], with the signature `verified` holds, from /// [`Self::preverify_delegation`] on these exact bytes, so a caller can - /// check it before its own reads (TC-3000). Bytes `verified` does not - /// cover have their signature checked inside the transaction instead. + /// check it before its own reads (TC-3000). When `verified` does not + /// cover these bytes, their signature is checked here, still before any + /// read or lock. pub async fn delegate_verified( &self, delegation: Delegation, @@ -2322,6 +2321,15 @@ where )); } let renewal_lease = crate::renewal::lease_original_from_signed(&delegation)?.is_some(); + // TC-2986: the signature is checked before any lock, so a forged or + // slow one never holds the guards or the spaces' write order. + let checked; + let verified = if verified.contains(&delegation.content_hash()) { + verified + } else { + checked = self.preverify_delegation(&delegation).await?; + &checked + }; let parent_hashes: Vec = delegation .0 .parents diff --git a/tinycloud-core/src/db/signature_before_locks_tests.rs b/tinycloud-core/src/db/signature_before_locks_tests.rs index dc78eb65..02db533a 100644 --- a/tinycloud-core/src/db/signature_before_locks_tests.rs +++ b/tinycloud-core/src/db/signature_before_locks_tests.rs @@ -1069,4 +1069,165 @@ mod binding { ); lock.rollback().await.unwrap(); } + + /// TC-3000 (Bobbie's #610 review, R4): the transaction decides the + /// revoker's standing. A revocation authorized by a revoke control grant + /// passes the pre-check and waits for its target's chain guard; the + /// control grant is revoked meanwhile, and the transaction refuses it. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn a_revocation_whose_control_grant_is_revoked_while_it_waits_is_refused() { + use sea_orm::{ActiveModelTrait, ActiveValue::Set}; + let f = sqlite_fx().await; + let g = ucan( + &f.owner, + &f.owner, + &did_vm(&f.holder).0, + &kv(&f.space), + "tinycloud.kv/get", + ); + f.db.delegate(deleg(&g)) + .await + .map_err(|e| e.to_string()) + .unwrap(); + let device = JWK::generate_ed25519().unwrap(); + let target = format!("urn:cid:{}", cid_of(&g)); + let control = ucan( + &f.owner, + &f.owner, + &did_vm(&device).0, + &target, + "tinycloud.delegation/revoke", + ); + f.db.delegate(deleg(&control)) + .await + .map_err(|e| e.to_string()) + .unwrap(); + let (node, _) = did_vm(&JWK::generate_ed25519().unwrap()); + let revocation = ucan_full( + &device, + &device, + &node, + &target, + "tinycloud.delegation/revoke", + vec![cid_of(&control)], + now() - 30, + now() + 300, + ); + let held = + f.db.acquire_chain_guards(&[Hash::from(cid_of(&g))]) + .await + .ok() + .expect("guard"); + let db = f.db.clone(); + let pending = tokio::spawn(async move { short(&db.revoke(revoc(&revocation)).await) }); + tokio::time::sleep(BRIEF).await; + assert!( + !pending.is_finished(), + "the revocation must pass the pre-check and wait for its target's chain guard" + ); + revocation::ActiveModel { + id: Set(crate::hash::hash(b"tc3000-control-revocation")), + revoker: Set(did_vm(&f.owner).0), + revoked: Set(Hash::from(cid_of(&control))), + serialization: Set(b"tc3000-control-revocation".to_vec()), + revoked_at: Set(Some(OffsetDateTime::now_utc())), + } + .insert(&f.db.conn) + .await + .unwrap(); + drop(held); + let out = pending.await.unwrap(); + assert!( + out.starts_with("Err(") && out.contains("Unauthorized Revoker"), + "revocation admitted on a revoked control grant: {out}" + ); + } + + /// TC-3000 (Bobbie's #610 review, R2): a stranger's renewal lease of a + /// stored original is refused before its own chain guard and the SQLite + /// writer lock. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn a_stranger_renewal_lease_is_refused_before_its_locks() { + let f = sqlite_fx().await; + let g = ucan( + &f.owner, + &f.owner, + &did_vm(&f.holder).0, + &kv(&f.space), + "tinycloud.kv/get", + ); + f.db.delegate(deleg(&g)) + .await + .map_err(|e| e.to_string()) + .unwrap(); + let stranger = JWK::generate_ed25519().unwrap(); + let lease = ucan_full( + &stranger, + &stranger, + &did_vm(&JWK::generate_ed25519().unwrap()).0, + &format!("urn:cid:{}", cid_of(&g)), + "tinycloud.delegation/renew", + vec![], + now() - 30, + now() + 300, + ); + assert!(crate::renewal::lease_original_from_signed(&deleg(&lease)) + .unwrap() + .is_some()); + let held_guard = + f.db.acquire_chain_guards(&[crate::hash::hash(lease.as_bytes())]) + .await + .ok() + .expect("guard"); + let held_writer = + f.db.writer_lock + .as_ref() + .expect("SQLite writer lock") + .clone() + .lock_owned() + .await; + let r = tokio::time::timeout(QUICK, f.db.delegate(deleg(&lease))).await; + drop(held_writer); + drop(held_guard); + let r = r.expect("a stranger's lease must not wait for its chain guard or the writer lock"); + assert!( + matches!( + r, + Err(TxError::Renewal( + crate::renewal::RenewalStoreError::Unauthorized + )) + ), + "{}", + short(&r) + ); + } + + /// TC-3000 (Bobbie's #610 review): a path with no pre-check (a policy + /// registration's `delegate_batch`) is held to the delegation's time + /// window by the transaction itself. + #[tokio::test] + async fn an_expired_delegation_is_refused_without_a_pre_check() { + let f = sqlite_fx().await; + let token = ucan_full( + &f.owner, + &f.owner, + &did_vm(&f.holder).0, + &kv(&f.space), + "tinycloud.kv/get", + vec![], + now() - 7200, + now() - 3600, + ); + let r = f.db.delegate_batch(vec![deleg(&token)]).await; + assert!( + matches!( + r, + Err(TxError::InvalidDelegation( + delegation::DelegationError::InvalidTime + )) + ), + "{}", + short(&r) + ); + } }