//! V19 schema guard: immutable Resource security revocation tombstones (Story 3.8). //! //! Проверяет, что схема V19 либо полностью отсутствует (миграция ещё не //! применена), либо присутствует ровно в ожидаемой форме: одна таблица //! `resource_security_revocations` с составным PK, FK на `resources` и `users` //! без каскадного удаления и trigger неизменяемости. Bounded request/trace //! значения задаются серверными типами (`RequestId`/`TraceContext`), а не //! пользовательским вводом. use sqlx::{PgConnection, Row, query}; use super::authority::MigrationError; use super::schema_guard::{normalize_definition, relation_exists}; const OWNED_RELATIONS: &[&str] = &["resource_security_revocations"]; const COLUMNS: &[(&str, &str, bool)] = &[ ("workspace_id", "text", false), ("resource_id", "text", false), ("revoked_at", "timestamp with time zone", false), ("actor_user_id", "text", false), ("request_id", "text", false), ("trace_id", "text", false), ]; const DEFINITIONS: &[(&str, &str, &str, &str)] = &[ ( "resource_security_revocations_pkey", "p", "v19.pkey", "primary key (workspace_id, resource_id)", ), ( "resource_security_revocations_resource_fkey", "f", "v19.resource_fkey", "foreign key (workspace_id, resource_id) references resources(workspace_id, resource_id) on delete restrict", ), ( "resource_security_revocations_actor_fkey", "f", "v19.actor_fkey", "foreign key (actor_user_id) references users(id) on delete restrict", ), ]; fn v19_error(stage: &'static str) -> MigrationError { MigrationError::new( "partial_sequence", stage, Some(19), "restore_known_good_backup", ) } /// Схема V19 отсутствует целиком (для current_version < 19). pub(super) async fn validate_v19_absent( connection: &mut PgConnection, ) -> Result { for relation in OWNED_RELATIONS { if relation_exists(connection, relation).await? { return Ok(false); } } if guard_function_exists(connection).await? { return Ok(false); } Ok(!trigger_exists(connection).await?) } /// Схема V19 присутствует в ожидаемой форме (для current_version >= 19). pub(super) async fn validate_v19_resource_security_revocations( connection: &mut PgConnection, ) -> Result<(), MigrationError> { for relation in OWNED_RELATIONS { if !relation_exists(connection, relation).await? { return Err(v19_error("v19.relations")); } } let column_count: i64 = query( "select count(*)::bigint as count from information_schema.columns where table_schema = current_schema() and table_name = 'resource_security_revocations'", ) .fetch_one(&mut *connection) .await .map_err(|_| MigrationError::storage("preflight.schema"))? .try_get("count") .map_err(|_| MigrationError::storage("preflight.schema"))?; if column_count != i64::try_from(COLUMNS.len()).unwrap_or_default() { return Err(v19_error("v19.columns")); } for (column, data_type, nullable) in COLUMNS { let row = query( "select data_type, is_nullable from information_schema.columns where table_schema = current_schema() and table_name = 'resource_security_revocations' and column_name = $1", ) .bind(column) .fetch_optional(&mut *connection) .await .map_err(|_| MigrationError::storage("preflight.schema"))?; let valid = row.is_some_and(|row| { row.try_get::("data_type").ok().as_deref() == Some(*data_type) && row.try_get::("is_nullable").ok().as_deref() == Some(if *nullable { "YES" } else { "NO" }) }); if !valid { return Err(v19_error("v19.columns")); } } for (constraint, kind, stage, expected) in DEFINITIONS { let row = query( "select c.contype::text as kind, c.convalidated, pg_get_constraintdef(c.oid, true) as definition from pg_catalog.pg_constraint c join pg_catalog.pg_class t on t.oid = c.conrelid join pg_catalog.pg_namespace n on n.oid = t.relnamespace where n.nspname = current_schema() and t.relname = 'resource_security_revocations' and c.conname = $1", ) .bind(constraint) .fetch_optional(&mut *connection) .await .map_err(|_| MigrationError::storage("preflight.schema"))?; let valid = row.is_some_and(|row| { row.try_get::("kind").ok().as_deref() == Some(*kind) && row.try_get::("convalidated").ok() == Some(true) && row .try_get::("definition") .ok() .is_some_and(|definition| { normalize_definition(&definition) == normalize_definition(expected) }) }); if !valid { return Err(v19_error(stage)); } } if !trigger_exists(connection).await? { return Err(v19_error("v19.immutable_trigger")); } if !guard_function_exists(connection).await? { return Err(v19_error("v19.immutable_trigger")); } Ok(()) } async fn trigger_exists(connection: &mut PgConnection) -> Result { query( "select exists ( select 1 from pg_catalog.pg_trigger tg join pg_catalog.pg_class t on t.oid = tg.tgrelid join pg_catalog.pg_namespace n on n.oid = t.relnamespace join pg_catalog.pg_proc p on p.oid = tg.tgfoid where n.nspname = current_schema() and t.relname = 'resource_security_revocations' and tg.tgname = 'resource_security_revocations_immutable_guard' and p.proname = 'crank_reject_resource_security_revocation_mutation' and not tg.tgisinternal ) as present", ) .fetch_one(&mut *connection) .await .map_err(|_| MigrationError::storage("preflight.schema"))? .try_get::("present") .map_err(|_| MigrationError::storage("preflight.schema")) } async fn guard_function_exists(connection: &mut PgConnection) -> Result { query( "select exists ( select 1 from pg_catalog.pg_proc p join pg_catalog.pg_namespace n on n.oid = p.pronamespace where n.nspname = current_schema() and p.proname = 'crank_reject_resource_security_revocation_mutation' ) as present", ) .fetch_one(&mut *connection) .await .map_err(|_| MigrationError::storage("preflight.schema"))? .try_get::("present") .map_err(|_| MigrationError::storage("preflight.schema")) }