//! Story 3.8 / AT-3.8-04: real concurrency between the live read guard and the revoke //! transition (owner decision A). //! //! Every scenario drives the *production* registry operations on separate multi-connection //! registries over one test schema. The orchestration is a PostgreSQL barrier: each backend //! carries its own `application_name`, `pg_blocking_pids` names the actual blocker, and a //! test-only advisory-lock trigger parks the revoke transaction after it took its row lock. //! Nothing here waits on timing alone, and no helper stubs the product. //! //! - revoke-first: a read that starts after the revoke took its lock waits, then is denied //! (`Revoked`) without ever receiving a publication, so no artifact byte can be opened; //! - read-first: the revoke waits for the in-flight guard and only then commits, so a read //! linearized before the revoke may still finish; //! - two first revokes on different connections produce exactly one audit event and keep the //! first actor/correlation; //! - dropping a guard releases the lock, and cancelling a waiting revoke leaves no tombstone. use std::str::FromStr; use std::time::Duration; use crank_core::WorkspaceId; use crank_core::ids::ResourceId; use crank_core::resource::ResourceError; use crank_registry::model::resource::RevokeResourceRequest; use crank_registry::{PostgresPoolConfig, PostgresRegistry}; use sqlx::postgres::PgConnectOptions; use sqlx::{PgPool, Row}; use time::OffsetDateTime; use super::*; /// Advisory gate key used by the test-only tombstone-insert trigger (test schema only). pub(super) const REVOCATION_GATE_KEY: i64 = 3821; /// A registry whose backends are identifiable in `pg_stat_activity` by `application_name`. pub(super) async fn attributed_registry( sandbox: &Sandbox, application_name: &str, ) -> PostgresRegistry { let base_url = crank_test_support::postgres_database_url().await; let schema: String = sqlx::query_scalar("select current_schema()") .fetch_one(&sandbox.pool) .await .expect("the test schema must be resolvable"); let url = format!( "{base_url}?options=-csearch_path%3D{schema}%20-capplication_name%3D{application_name}" ); let options = PgConnectOptions::from_str(&url).expect("attributed connect options must parse"); PostgresRegistry::connect_with_options_and_pool_config( options, PostgresPoolConfig { max_connections: 6, min_connections: 0, acquire_timeout_ms: 10_000, idle_timeout_ms: 600_000, max_lifetime_ms: 1_800_000, }, ) .await .expect("the attributed test registry must connect") } /// Install a test-only gate: a BEFORE trigger on `table` parks the writing transaction on an /// advisory lock, so the operation observably holds every lock it already took while the test /// starts the competitor. The trigger lives only in this test's private schema. pub(super) async fn install_advisory_gate( sandbox: &Sandbox, function: &str, table: &str, key: i64, ) { let sql = format!( "create function {function}() returns trigger language plpgsql as $$ begin perform pg_advisory_xact_lock({key}); return new; end $$; create trigger {function}_gate before insert or update on {table} for each row execute function {function}();" ); sqlx::raw_sql(sqlx::AssertSqlSafe(sql)) .execute(&sandbox.pool) .await .expect("the test-only advisory gate trigger must install"); } /// Install the gate inside the audited tombstone insert. pub(super) async fn install_revocation_gate(sandbox: &Sandbox) { install_advisory_gate( sandbox, "crank_test_gate_revocation_insert", "resource_security_revocations", REVOCATION_GATE_KEY, ) .await; } /// Take the session-level advisory lock a gate function waits for. pub(super) async fn take_gate(sandbox: &Sandbox, key: i64) -> PgPool { let base_url = crank_test_support::postgres_database_url().await; let schema: String = sqlx::query_scalar("select current_schema()") .fetch_one(&sandbox.pool) .await .expect("the test schema must be resolvable"); let url = format!("{base_url}?options=-csearch_path%3D{schema}%20-capplication_name%3Dstory38-gate"); let pool = PgPool::connect(&url) .await .expect("the gate pool must connect to the test schema"); sqlx::query("select pg_advisory_lock($1)") .bind(key) .execute(&pool) .await .expect("the gate advisory lock must be taken"); pool } pub(super) async fn release_gate(gate: PgPool, key: i64) { sqlx::query("select pg_advisory_unlock($1)") .bind(key) .execute(&gate) .await .expect("the gate advisory lock must be releasable"); drop(gate); } /// Precise barrier: `waiter` is blocked by a backend whose `application_name` is `blocker`. /// Returns false after the deadline so the caller turns a missing wait into a real assertion. pub(super) async fn await_blocked_by(pool: &PgPool, waiter: &str, blocker: &str) -> bool { let deadline = tokio::time::Instant::now() + Duration::from_secs(15); loop { let waiters: Vec = sqlx::query_scalar( "select pid from pg_stat_activity where datname = current_database() and application_name = $1", ) .bind(waiter) .fetch_all(pool) .await .expect("pg_stat_activity must be observable"); for pid in waiters { let blockers: Vec = sqlx::query_scalar("select unnest(pg_blocking_pids($1))") .bind(pid) .fetch_all(pool) .await .expect("pg_blocking_pids must be observable"); if blockers.is_empty() { continue; } let names: Vec = sqlx::query_scalar( "select application_name from pg_stat_activity where pid = any($1)", ) .bind(&blockers) .fetch_all(pool) .await .expect("blocking backends must be observable"); if names.iter().any(|name| name == blocker) { return true; } } if tokio::time::Instant::now() >= deadline { return false; } tokio::time::sleep(Duration::from_millis(10)).await; } } pub(super) fn revoke_request(resource: &ResourceId, request_id: &str) -> RevokeResourceRequest { RevokeResourceRequest { workspace_id: WorkspaceId::new("ws_default"), resource_id: resource.clone(), actor_user_id: "user_default_owner".to_owned(), request_id: request_id.to_owned(), trace_id: format!("{request_id}-trace"), revoked_at: OffsetDateTime::now_utc(), } } /// Draft → Published v1 with a caller-chosen unique name (the fixture name is unique per /// workspace, so a second Resource in the same schema needs its own). async fn published_named_resource( sandbox: &Sandbox, workspace: &str, resource_id: &str, uri: &str, name: &str, bytes: &[u8], ) -> ResourceId { let resource = ResourceId::new(resource_id); sandbox .registry .create_resource_draft( crank_registry::model::resource::CreateResourceDraftRequest { workspace_id: WorkspaceId::new(workspace), resource_id: resource.clone(), uri: uri.to_owned(), name: name.to_owned(), description: String::new(), kind: "text".to_owned(), mime_type: "text/plain".to_owned(), sensitivity: "internal".to_owned(), artifact: registered(sandbox, bytes), created_at: OffsetDateTime::now_utc(), }, ) .await .expect("the named resource draft must be created"); publish_current_resource(sandbox, workspace, &resource, bytes).await; resource } pub(super) async fn tombstone_rows(pool: &PgPool) -> i64 { sqlx::query_scalar("select count(*) from resource_security_revocations") .fetch_one(pool) .await .expect("tombstones must be queryable") } /// Revoke wins: the read that starts behind the revoke lock is denied before any publication /// (and therefore before any artifact read), while the revoke itself is a normal 204 path. #[tokio::test] async fn story38_revoke_first_denies_a_waiting_read_without_a_publication() { let sandbox = sandbox("revocation_race_revoke_first").await; let resource = published_resource( &sandbox, "ws_default", "res_race_revoke_first", "crank://race/revoke-first", b"revoke first v1", ) .await; install_revocation_gate(&sandbox).await; let gate = take_gate(&sandbox, REVOCATION_GATE_KEY).await; let revoker = attributed_registry(&sandbox, "story38-revoker").await; let revoke_resource = resource.clone(); let revoke = tokio::spawn(async move { revoker .revoke_resource(revoke_request( &revoke_resource, "story38-race-revoke-first", )) .await }); assert!( await_blocked_by(&sandbox.pool, "story38-revoker", "story38-gate").await, "the revoke transaction must reach its tombstone insert and hold the Resource row lock" ); // This read starts after the revoke took `resources FOR UPDATE`: it cannot pass the guard. let reader = attributed_registry(&sandbox, "story38-reader").await; let read_resource = resource.clone(); let read = tokio::spawn(async move { reader .begin_authorized_resource_read("ws_default", &read_resource, 1) .await .map(|guard| guard.publication().publication.uri.clone()) }); assert!( await_blocked_by(&sandbox.pool, "story38-reader", "story38-revoker").await, "the read must wait for the in-flight revoke instead of racing it" ); assert!( !read.is_finished(), "a read behind the revoke must not complete while the revoke holds the row" ); release_gate(gate, REVOCATION_GATE_KEY).await; tokio::time::timeout(Duration::from_secs(15), revoke) .await .expect("revoke must finish once the gate is released") .expect("revoke task must not panic") .expect("revoke must commit"); let outcome = tokio::time::timeout(Duration::from_secs(15), read) .await .expect("the waiting read must finish after the revoke commits") .expect("read task must not panic"); assert!( matches!(outcome, Err(ResourceError::Revoked)), "revoke-first must deny the read with the typed Revoked outcome, got {outcome:?}" ); assert_eq!(tombstone_rows(&sandbox.pool).await, 1); sandbox.cleanup().await; } /// Read wins: the revoke waits for the in-flight guard and commits afterwards; the read is /// linearized before the revoke and only post-revoke reads see `Revoked`. #[tokio::test] async fn story38_read_first_serializes_a_revoke_after_the_in_flight_guard() { let sandbox = sandbox("revocation_race_read_first").await; let resource = published_resource( &sandbox, "ws_default", "res_race_read_first", "crank://race/read-first", b"read first v1", ) .await; let reader = attributed_registry(&sandbox, "story38-reader").await; let guard = reader .begin_authorized_resource_read("ws_default", &resource, 1) .await .expect("an unrevoked Resource must open the live guard"); assert_eq!( guard.publication().publication.uri, "crank://race/read-first" ); let revoker = attributed_registry(&sandbox, "story38-revoker").await; let revoke_resource = resource.clone(); let revoke = tokio::spawn(async move { revoker .revoke_resource(revoke_request(&revoke_resource, "story38-race-read-first")) .await }); assert!( await_blocked_by(&sandbox.pool, "story38-revoker", "story38-reader").await, "revoke must wait for the in-flight read guard, not bypass its shared lock" ); assert!( !revoke.is_finished(), "revoke must not commit while the read guard still holds the row" ); guard.commit().await.expect("the read must commit"); tokio::time::timeout(Duration::from_secs(15), revoke) .await .expect("revoke must finish once the guard is released") .expect("revoke task must not panic") .expect("revoke must commit after the read"); assert_eq!(tombstone_rows(&sandbox.pool).await, 1); let after = reader .begin_authorized_resource_read("ws_default", &resource, 1) .await .map(|_| ()); assert!( matches!(after, Err(ResourceError::Revoked)), "a read that starts after the committed revoke must be denied: {after:?}" ); sandbox.cleanup().await; } /// Two first revokes on different connections: both succeed, exactly one event is written and /// the first actor/correlation/time survive the second command. #[tokio::test] async fn story38_two_first_revokes_on_different_connections_write_one_event() { let sandbox = sandbox("revocation_race_first_event").await; let resource = published_resource( &sandbox, "ws_default", "res_race_first_event", "crank://race/first-event", b"first event v1", ) .await; install_revocation_gate(&sandbox).await; let gate = take_gate(&sandbox, REVOCATION_GATE_KEY).await; let first = attributed_registry(&sandbox, "story38-revoker-a").await; let first_resource = resource.clone(); let first_revoke = tokio::spawn(async move { first .revoke_resource(revoke_request(&first_resource, "story38-first-a")) .await }); assert!( await_blocked_by(&sandbox.pool, "story38-revoker-a", "story38-gate").await, "the first revoke must hold its row lock inside the audited insert" ); let second = attributed_registry(&sandbox, "story38-revoker-b").await; let second_resource = resource.clone(); let second_revoke = tokio::spawn(async move { second .revoke_resource(revoke_request(&second_resource, "story38-first-b")) .await }); assert!( await_blocked_by(&sandbox.pool, "story38-revoker-b", "story38-revoker-a").await, "the second first-revoke must wait for the row lock of the first" ); release_gate(gate, REVOCATION_GATE_KEY).await; for (name, handle) in [("a", first_revoke), ("b", second_revoke)] { tokio::time::timeout(Duration::from_secs(15), handle) .await .unwrap_or_else(|_| panic!("revoke {name} must finish")) .unwrap_or_else(|_| panic!("revoke {name} task must not panic")) .unwrap_or_else(|error| panic!("revoke {name} must succeed: {error:?}")); } assert_eq!(tombstone_rows(&sandbox.pool).await, 1, "one audit event"); let row = sqlx::query( "select actor_user_id, request_id, trace_id, revoked_at from resource_security_revocations", ) .fetch_one(&sandbox.pool) .await .expect("the single tombstone must be readable"); assert_eq!( row.try_get::("request_id").unwrap(), "story38-first-a", "the first correlation must be preserved" ); assert_eq!( row.try_get::("actor_user_id").unwrap(), "user_default_owner" ); assert_eq!( row.try_get::("trace_id").unwrap(), "story38-first-a-trace" ); sandbox.cleanup().await; } /// A guard dropped without commit releases the row lock; a cancelled waiting revoke leaves no /// audit event and no stuck lock. #[tokio::test] async fn story38_dropped_guard_and_cancelled_revoke_leave_no_stuck_lock() { let sandbox = sandbox("revocation_race_cancel").await; let resource = published_resource( &sandbox, "ws_default", "res_race_cancel", "crank://race/cancel", b"cancel v1", ) .await; let reader = attributed_registry(&sandbox, "story38-reader").await; let guard = reader .begin_authorized_resource_read("ws_default", &resource, 1) .await .expect("the guard must open before the revoke"); drop(guard); let revoker = attributed_registry(&sandbox, "story38-revoker").await; let revoke_resource = resource.clone(); tokio::time::timeout( Duration::from_secs(15), revoker.revoke_resource(revoke_request(&revoke_resource, "story38-after-drop")), ) .await .expect("a revoke after a dropped guard must not hang") .expect("the revoke must succeed once the guard is dropped"); assert_eq!(tombstone_rows(&sandbox.pool).await, 1); // Second Resource: a revoke cancelled while waiting must not write anything. let other = published_named_resource( &sandbox, "ws_default", "res_race_cancel_two", "crank://race/cancel-two", "cancel_two_doc", b"cancel v2", ) .await; install_revocation_gate(&sandbox).await; let gate = take_gate(&sandbox, REVOCATION_GATE_KEY).await; let cancelled = attributed_registry(&sandbox, "story38-revoker-cancelled").await; let cancelled_resource = other.clone(); let waiting = tokio::spawn(async move { cancelled .revoke_resource(revoke_request(&cancelled_resource, "story38-cancelled")) .await }); assert!( await_blocked_by(&sandbox.pool, "story38-revoker-cancelled", "story38-gate").await, "the cancelled revoke must be waiting inside its insert" ); waiting.abort(); let _ = waiting.await; release_gate(gate, REVOCATION_GATE_KEY).await; tokio::time::timeout( Duration::from_secs(15), revoker.revoke_resource(revoke_request(&other, "story38-retry-after-cancel")), ) .await .expect("the retry must not hang behind the cancelled command") .expect("the retry must succeed"); let rows: i64 = sqlx::query_scalar( "select count(*) from resource_security_revocations where resource_id = $1", ) .bind(other.as_str()) .fetch_one(&sandbox.pool) .await .expect("tombstones must be queryable"); assert_eq!(rows, 1, "a cancelled revoke must leave no event behind"); sandbox.cleanup().await; } /// A COMMIT that PostgreSQL itself refuses is a safe unavailable outcome: the read returns no /// prepared content, no tombstone is written, and a fresh read still works. #[tokio::test] async fn story38_read_guard_commit_failure_is_a_safe_unavailable() { let sandbox = sandbox("revocation_race_guard_commit").await; let resource = published_resource( &sandbox, "ws_default", "res_race_guard_commit", "crank://race/guard-commit", b"guard commit v1", ) .await; let base_url = crank_test_support::postgres_database_url().await; let schema: String = sqlx::query_scalar("select current_schema()") .fetch_one(&sandbox.pool) .await .expect("the test schema must be resolvable"); let url = format!( "{base_url}?options=-csearch_path%3D{schema}%20-capplication_name%3Dstory38-guard-commit" ); let options = PgConnectOptions::from_str(&url).expect("guard connect options must parse"); let registry = PostgresRegistry::connect_with_options_and_pool_config( options, PostgresPoolConfig { max_connections: 1, min_connections: 0, acquire_timeout_ms: 10_000, idle_timeout_ms: 600_000, max_lifetime_ms: 1_800_000, }, ) .await .expect("the single-connection guard registry must connect"); let guard = registry .begin_authorized_resource_read("ws_default", &resource, 1) .await .expect("the guard must open on an unrevoked Resource"); let pids: Vec = sqlx::query_scalar( "select pid from pg_stat_activity where datname = current_database() and application_name = 'story38-guard-commit'", ) .fetch_all(&sandbox.pool) .await .expect("the guard backend must be observable"); assert_eq!(pids.len(), 1, "exactly one guard backend must exist"); let terminated: bool = sqlx::query_scalar("select pg_terminate_backend($1)") .bind(pids[0]) .fetch_one(&sandbox.pool) .await .expect("the guard backend must be terminable"); assert!(terminated); let outcome = guard.commit().await; assert!( matches!(outcome, Err(ResourceError::StorageUnavailable)), "a refused COMMIT must be a safe unavailable outcome, got {outcome:?}" ); assert_eq!( tombstone_rows(&sandbox.pool).await, 0, "a failed read commit must not be recorded as a revoke" ); // Positive control on a fresh registry: nothing was revoked by the failed commit. let reader = attributed_registry(&sandbox, "story38-reader").await; let fresh = reader .begin_authorized_resource_read("ws_default", &resource, 1) .await .map(|_| ()); assert!( fresh.is_ok(), "an unrevoked Resource must still open a guard after the failed commit: {fresh:?}" ); sandbox.cleanup().await; }