fix(import): подтвердить обязательные гарантии второго эпика
This commit is contained in:
1 parent
31f6f00d3b
commit
ad23cd9a46
33 files changed
+3328
-18
No files matched your search
@@ -367,6 +367,8 @@ impl ExternalReferenceFetcher {
|
||||
fn outbound_client(policy: &OutboundHttpPolicy) -> Result<Client, Arc<str>> {
|
||||
let resolver = Arc::new(PolicyDnsResolver {
|
||||
policy: policy.clone(),
|
||||
#[cfg(test)]
|
||||
lookup: None,
|
||||
});
|
||||
Client::builder()
|
||||
.redirect(redirect::Policy::none())
|
||||
@@ -611,23 +613,43 @@ impl OutboundHttpPolicy {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
#[derive(Clone)]
|
||||
struct PolicyDnsResolver {
|
||||
policy: OutboundHttpPolicy,
|
||||
// Test-local DNS answers exercise the actual policy resolver and connector.
|
||||
// Neither this field nor an injection API exists in production builds.
|
||||
#[cfg(test)]
|
||||
lookup: Option<Arc<dyn Resolve>>,
|
||||
}
|
||||
|
||||
impl PolicyDnsResolver {
|
||||
fn lookup(&self, name: Name) -> Resolving {
|
||||
#[cfg(test)]
|
||||
if let Some(lookup) = &self.lookup {
|
||||
return lookup.resolve(name);
|
||||
}
|
||||
let host = normalize_host(name.as_str());
|
||||
Box::pin(async move {
|
||||
let addresses = tokio::net::lookup_host((host.as_str(), 0))
|
||||
.await
|
||||
.map_err(|error| Box::new(error) as Box<dyn std::error::Error + Send + Sync>)?;
|
||||
let addresses: Vec<_> = addresses.collect();
|
||||
Ok(Box::new(addresses.into_iter()) as Addrs)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Resolve for PolicyDnsResolver {
|
||||
fn resolve(&self, name: Name) -> Resolving {
|
||||
let host = normalize_host(name.as_str());
|
||||
let policy = self.policy.clone();
|
||||
let resolver = self.clone();
|
||||
Box::pin(async move {
|
||||
policy
|
||||
.validate_host(&host)
|
||||
.map_err(|error| boxed_io_error(error.to_string()))?;
|
||||
let explicitly_allowed = policy.is_explicitly_allowed(&host);
|
||||
let resolved = tokio::net::lookup_host((host.as_str(), 0))
|
||||
.await
|
||||
.map_err(|error| Box::new(error) as Box<dyn std::error::Error + Send + Sync>)?;
|
||||
let resolved = resolver.lookup(name).await?;
|
||||
let addresses = resolved
|
||||
.filter(|address| {
|
||||
!policy.is_denied_ip(address.ip())
|
||||
@@ -969,3 +991,7 @@ fn to_reqwest_method(method: HttpMethod) -> reqwest::Method {
|
||||
HttpMethod::Options => reqwest::Method::OPTIONS,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "client_dns_tests.rs"]
|
||||
mod dns_tests;
|
||||
@@ -0,0 +1,155 @@
|
||||
//! Use the production policy resolver in reqwest's real connector. DNS can
|
||||
//! change immediately after lookup; only the validated returned addresses may
|
||||
//! be connected to, and a subsequent resolution must enforce policy again.
|
||||
|
||||
use super::*;
|
||||
use axum::{Router, routing::get};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
struct ChangingLookup {
|
||||
calls: AtomicUsize,
|
||||
answers: Vec<Vec<SocketAddr>>,
|
||||
}
|
||||
impl Resolve for ChangingLookup {
|
||||
fn resolve(&self, _: Name) -> Resolving {
|
||||
// Advancing before the connector receives this iterator models a DNS
|
||||
// answer changing between validation and the socket connection.
|
||||
let call = self.calls.fetch_add(1, Ordering::SeqCst);
|
||||
let addresses = self.answers[call.min(self.answers.len() - 1)].clone();
|
||||
Box::pin(async move { Ok(Box::new(addresses.into_iter()) as Addrs) })
|
||||
}
|
||||
}
|
||||
|
||||
struct Listeners(Vec<tokio::task::JoinHandle<()>>);
|
||||
impl Drop for Listeners {
|
||||
fn drop(&mut self) {
|
||||
for handle in &self.0 {
|
||||
handle.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn fixture() -> (u16, Arc<AtomicUsize>, Arc<AtomicUsize>, Listeners) {
|
||||
let allowed = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = allowed.local_addr().unwrap().port();
|
||||
let denied = tokio::net::TcpListener::bind((Ipv4Addr::new(127, 0, 0, 2), port))
|
||||
.await
|
||||
.unwrap();
|
||||
let allowed_count = Arc::new(AtomicUsize::new(0));
|
||||
let denied_count = Arc::new(AtomicUsize::new(0));
|
||||
let mut handles = Vec::new();
|
||||
for (listener, count) in [
|
||||
(allowed, Arc::clone(&allowed_count)),
|
||||
(denied, Arc::clone(&denied_count)),
|
||||
] {
|
||||
handles.push(tokio::spawn(async move {
|
||||
let app = Router::new().route(
|
||||
"/document",
|
||||
get(move || {
|
||||
let count = Arc::clone(&count);
|
||||
async move {
|
||||
count.fetch_add(1, Ordering::SeqCst);
|
||||
"snapshot"
|
||||
}
|
||||
}),
|
||||
);
|
||||
axum::serve(listener, app).await.unwrap();
|
||||
}));
|
||||
}
|
||||
(port, allowed_count, denied_count, Listeners(handles))
|
||||
}
|
||||
|
||||
fn policy_client(lookup: Arc<ChangingLookup>) -> Client {
|
||||
let policy = OutboundHttpPolicy::try_new(
|
||||
vec!["reference.invalid".into()],
|
||||
vec!["127.0.0.2".into()],
|
||||
1024,
|
||||
)
|
||||
.unwrap();
|
||||
Client::builder()
|
||||
.no_proxy()
|
||||
.redirect(redirect::Policy::none())
|
||||
.pool_max_idle_per_host(0)
|
||||
.timeout(Duration::from_secs(3))
|
||||
.dns_resolver(Arc::new(PolicyDnsResolver {
|
||||
policy,
|
||||
lookup: Some(lookup),
|
||||
}))
|
||||
.build()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dns_rebinding_pins_the_validated_connection_then_rejects_changed_denied_answer() {
|
||||
let (port, allowed, denied, _listeners) = fixture().await;
|
||||
let lookup = Arc::new(ChangingLookup {
|
||||
calls: AtomicUsize::new(0),
|
||||
answers: vec![
|
||||
vec!["127.0.0.1:0".parse().unwrap()],
|
||||
vec!["127.0.0.2:0".parse().unwrap()],
|
||||
],
|
||||
});
|
||||
let client = policy_client(Arc::clone(&lookup));
|
||||
let url = format!("http://reference.invalid:{port}/document");
|
||||
let body = client
|
||||
.get(&url)
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
.error_for_status()
|
||||
.unwrap()
|
||||
.text()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(body, "snapshot");
|
||||
assert_eq!(
|
||||
lookup.calls.load(Ordering::SeqCst),
|
||||
1,
|
||||
"one validated answer is pinned for this connection"
|
||||
);
|
||||
assert_eq!(allowed.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(denied.load(Ordering::SeqCst), 0);
|
||||
|
||||
// Disable idle pooling above so a new connection really asks for the new
|
||||
// answer; no timing or external DNS configuration is involved.
|
||||
let error = client.get(&url).send().await.unwrap_err();
|
||||
assert!(error.is_connect());
|
||||
assert!(
|
||||
!error.is_timeout(),
|
||||
"must reject the new DNS answer, not merely time out"
|
||||
);
|
||||
assert_eq!(lookup.calls.load(Ordering::SeqCst), 2);
|
||||
assert_eq!(allowed.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(
|
||||
denied.load(Ordering::SeqCst),
|
||||
0,
|
||||
"deny must win over hostname allowlist"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mixed_dns_answers_never_pass_denied_address_to_the_connector() {
|
||||
let (port, allowed, denied, _listeners) = fixture().await;
|
||||
let lookup = Arc::new(ChangingLookup {
|
||||
calls: AtomicUsize::new(0),
|
||||
answers: vec![vec![
|
||||
"127.0.0.2:0".parse().unwrap(),
|
||||
"127.0.0.1:0".parse().unwrap(),
|
||||
]],
|
||||
});
|
||||
let client = policy_client(Arc::clone(&lookup));
|
||||
assert_eq!(
|
||||
client
|
||||
.get(format!("http://reference.invalid:{port}/document"))
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
.text()
|
||||
.await
|
||||
.unwrap(),
|
||||
"snapshot"
|
||||
);
|
||||
assert_eq!(lookup.calls.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(allowed.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(denied.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
@@ -30,6 +30,18 @@ pub enum FaultAction {
|
||||
Hold,
|
||||
}
|
||||
|
||||
/// Terminates a debug test process at an explicitly armed transaction boundary.
|
||||
/// Release builds contain neither this hook nor its callers. The checkpoint
|
||||
/// is in-memory only; a request or environment variable cannot arm it.
|
||||
#[cfg(debug_assertions)]
|
||||
pub fn crash_if_checkpointed(stage: &str) {
|
||||
if action(stage) == Some(FaultAction::Exit) {
|
||||
// Deliberately skip destructors/atexit, as a lost process would. Test
|
||||
// containers belong to the parent process, not this child.
|
||||
unsafe { libc::_exit(86) }
|
||||
}
|
||||
}
|
||||
|
||||
struct State {
|
||||
checkpoint: Option<(String, FaultAction, usize)>,
|
||||
hits: BTreeMap<String, usize>,
|
||||
|
||||
@@ -643,6 +643,47 @@ fn corrupted_or_symlinked_final_never_returns_bytes() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncated_published_blob_is_integrity_failure_with_safe_diagnostics() {
|
||||
let root = TestRoot::new("truncated-final");
|
||||
let store = ArtifactStore::open(&root.0).unwrap();
|
||||
let source = b"published blob truncated tail".as_slice();
|
||||
let stored = store.put(source).unwrap();
|
||||
let path = root
|
||||
.0
|
||||
.join("sha256")
|
||||
.join(&stored.artifact_ref.digest_hex()[..2])
|
||||
.join(stored.artifact_ref.digest_hex());
|
||||
assert_eq!(
|
||||
fs::metadata(&path).unwrap().permissions().mode() & 0o777,
|
||||
0o400
|
||||
);
|
||||
|
||||
// Publishing leaves the blob read-only. Reopen it writable only long enough
|
||||
// to truncate the tail, then restore the exact private mode the verified
|
||||
// reader validates before it compares length and digest.
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap();
|
||||
fs::File::options()
|
||||
.write(true)
|
||||
.open(&path)
|
||||
.unwrap()
|
||||
.set_len(u64::try_from(source.len() - 4).unwrap())
|
||||
.unwrap();
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(0o400)).unwrap();
|
||||
assert_eq!(
|
||||
fs::metadata(&path).unwrap().permissions().mode() & 0o777,
|
||||
0o400
|
||||
);
|
||||
|
||||
let error = store.read(&stored.artifact_ref).unwrap_err();
|
||||
assert_eq!(error, ArtifactError::Integrity);
|
||||
assert_eq!(error.to_string(), "artifact integrity verification failed");
|
||||
let diagnostic = format!("{error} {error:?}");
|
||||
assert!(!diagnostic.contains(stored.artifact_ref.digest_hex()));
|
||||
assert!(!diagnostic.contains(root.0.to_string_lossy().as_ref()));
|
||||
assert!(!diagnostic.contains("published"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directory_at_final_digest_is_integrity_failure() {
|
||||
let root = TestRoot::new("directory-final");
|
||||
|
||||
@@ -355,16 +355,19 @@ fn real_process_write_limit_leaves_no_partial_final_blob() {
|
||||
}
|
||||
|
||||
let root = TestRoot::new("real-write-limit");
|
||||
let status = Command::new(std::env::current_exe().unwrap())
|
||||
// Capture the child's stdout/stderr with pipes: the child lowers
|
||||
// RLIMIT_FSIZE to 1 byte, which would otherwise make libtest's own
|
||||
// result write fail with EFBIG against an inherited regular log file.
|
||||
let output = Command::new(std::env::current_exe().unwrap())
|
||||
.args([
|
||||
"--exact",
|
||||
"real_process_write_limit_leaves_no_partial_final_blob",
|
||||
"--nocapture",
|
||||
])
|
||||
.env("CRANK_ARTIFACTS_CHILD_ROOT", &root.0)
|
||||
.status()
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(status.success());
|
||||
assert!(output.status.success(), "child status: {}", output.status);
|
||||
|
||||
let store = ArtifactStore::open(&root.0).unwrap();
|
||||
let expected =
|
||||
|
||||
@@ -140,6 +140,51 @@ fn swagger2_projects_basic_and_api_key_header_and_query() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swagger2_cookie_api_key_is_explicitly_unsupported_at_operation_and_preview() {
|
||||
let document = json!({
|
||||
"swagger": "2.0",
|
||||
"info": { "title": "Unsupported Swagger cookie", "version": "1" },
|
||||
"host": "security.example.test",
|
||||
"schemes": ["https"],
|
||||
"securityDefinitions": {
|
||||
"CookieKey": { "type": "apiKey", "in": "cookie", "name": "session" }
|
||||
},
|
||||
"security": [{ "CookieKey": [] }],
|
||||
"paths": { "/private": { "get": {
|
||||
"responses": { "200": { "description": "ok" } }
|
||||
}}}
|
||||
});
|
||||
let ir = normalize(&document);
|
||||
let operation = operation(&ir, "/private");
|
||||
assert!(matches!(
|
||||
ir.security_schemes["CookieKey"].kind,
|
||||
NormalizedSecuritySchemeKind::Unsupported { .. }
|
||||
));
|
||||
assert!(!operation.security_requirements.alternatives[0].supported);
|
||||
assert!(
|
||||
operation
|
||||
.findings
|
||||
.iter()
|
||||
.any(|finding| finding.code == "unsupported_security_scheme")
|
||||
);
|
||||
assert!(
|
||||
operation
|
||||
.findings
|
||||
.iter()
|
||||
.any(|finding| finding.code == "unsupported_security_requirements")
|
||||
);
|
||||
let preview = candidates(&ir);
|
||||
let candidate = candidate(&preview, "GET /private");
|
||||
assert!(
|
||||
candidate
|
||||
.findings
|
||||
.iter()
|
||||
.any(|finding| finding.code == "unsupported_security_requirements")
|
||||
);
|
||||
assert!(candidate.draft.input_mapping.rules.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effective_requirements_inherit_override_and_allow_explicit_no_auth() {
|
||||
let document = json!({
|
||||
|
||||
@@ -354,7 +354,11 @@ impl PostgresRegistry {
|
||||
let outcome = apply_import_plan_transaction(&mut transaction, request).await;
|
||||
match outcome {
|
||||
Ok((replayed, report)) => {
|
||||
#[cfg(debug_assertions)]
|
||||
crank_artifacts::test_support::crash_if_checkpointed("apply_before_commit");
|
||||
transaction.commit().await?;
|
||||
#[cfg(debug_assertions)]
|
||||
crank_artifacts::test_support::crash_if_checkpointed("apply_after_commit");
|
||||
Ok(ApplyImportPlanResult { replayed, report })
|
||||
}
|
||||
Err(ApplyTxFailure::KeyConflict) => {
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
use super::*;
|
||||
use sqlx::Row;
|
||||
use std::collections::HashMap;
|
||||
|
||||
mod exhaustive_v12;
|
||||
|
||||
#[tokio::test]
|
||||
async fn healthy_v11_upgrades_to_v13_without_rewriting_prior_ledger() {
|
||||
@@ -216,3 +220,523 @@ async fn v13_guard_rejects_wrong_cleanup_index_order_and_predicate() {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const V12_BLOB_COLUMNS: &[&str] = &[
|
||||
"digest",
|
||||
"artifact_ref",
|
||||
"size_bytes",
|
||||
"storage_lifecycle",
|
||||
"claim_token",
|
||||
"claim_expires_at",
|
||||
"created_at",
|
||||
"updated_at",
|
||||
];
|
||||
const V12_SOURCE_COLUMNS: &[&str] = &[
|
||||
"workspace_id",
|
||||
"source_id",
|
||||
"blob_digest",
|
||||
"mime_type",
|
||||
"sensitivity",
|
||||
"lifecycle",
|
||||
"created_at",
|
||||
"updated_at",
|
||||
"detached_at",
|
||||
];
|
||||
const V12_BLOB_DEFAULTS: &[(&str, Option<&str>)] = &[
|
||||
("digest", None),
|
||||
("artifact_ref", None),
|
||||
("size_bytes", None),
|
||||
("storage_lifecycle", Some("'available'::text")),
|
||||
("claim_token", None),
|
||||
("claim_expires_at", None),
|
||||
("created_at", None),
|
||||
("updated_at", None),
|
||||
];
|
||||
const V12_SOURCE_DEFAULTS: &[(&str, Option<&str>)] = &[
|
||||
("workspace_id", None),
|
||||
("source_id", None),
|
||||
("blob_digest", None),
|
||||
("mime_type", None),
|
||||
("sensitivity", None),
|
||||
("lifecycle", Some("'active'::text")),
|
||||
("created_at", None),
|
||||
("updated_at", None),
|
||||
("detached_at", None),
|
||||
];
|
||||
// PostgreSQL normalizes `set default null` into "no default", so each column
|
||||
// that legitimately has no default needs a concrete typed expression to prove
|
||||
// the guard rejects a newly introduced default.
|
||||
const V12_BLOB_NO_DEFAULT_DRIFT: &[(&str, &str)] = &[
|
||||
("digest", "'crank_drift'::text"),
|
||||
("artifact_ref", "'crank_drift'::text"),
|
||||
("size_bytes", "1"),
|
||||
("claim_token", "'crank_drift'::text"),
|
||||
("claim_expires_at", "'2000-01-01 00:00:00+00'::timestamptz"),
|
||||
("created_at", "'2000-01-01 00:00:00+00'::timestamptz"),
|
||||
("updated_at", "'2000-01-01 00:00:00+00'::timestamptz"),
|
||||
];
|
||||
const V12_SOURCE_NO_DEFAULT_DRIFT: &[(&str, &str)] = &[
|
||||
("workspace_id", "'crank_drift'::text"),
|
||||
("source_id", "'crank_drift'::text"),
|
||||
("blob_digest", "'crank_drift'::text"),
|
||||
("mime_type", "'crank_drift'::text"),
|
||||
("sensitivity", "'crank_drift'::text"),
|
||||
("created_at", "'2000-01-01 00:00:00+00'::timestamptz"),
|
||||
("updated_at", "'2000-01-01 00:00:00+00'::timestamptz"),
|
||||
("detached_at", "'2000-01-01 00:00:00+00'::timestamptz"),
|
||||
];
|
||||
const V12_BLOB_CONSTRAINTS: &[&str] = &[
|
||||
"artifact_blobs_artifact_ref_key",
|
||||
"artifact_blobs_claim_shape_check",
|
||||
"artifact_blobs_claim_token_check",
|
||||
"artifact_blobs_digest_check",
|
||||
"artifact_blobs_lifecycle_check",
|
||||
"artifact_blobs_pkey",
|
||||
"artifact_blobs_ref_check",
|
||||
"artifact_blobs_size_check",
|
||||
"artifact_blobs_timestamps_check",
|
||||
];
|
||||
const V12_SOURCE_CONSTRAINTS: &[&str] = &[
|
||||
"artifact_sources_blob_digest_fkey",
|
||||
"artifact_sources_id_check",
|
||||
"artifact_sources_lifecycle_check",
|
||||
"artifact_sources_mime_type_check",
|
||||
"artifact_sources_pkey",
|
||||
"artifact_sources_sensitivity_check",
|
||||
"artifact_sources_state_check",
|
||||
"artifact_sources_timestamps_check",
|
||||
"artifact_sources_workspace_id_fkey",
|
||||
];
|
||||
const V12_OWNED_RELATIONS: &[(&str, &str)] = &[
|
||||
("artifact_blobs", "r"),
|
||||
("artifact_blobs_artifact_ref_key", "i"),
|
||||
("artifact_blobs_expired_claim_idx", "i"),
|
||||
("artifact_blobs_pkey", "i"),
|
||||
("artifact_sources", "r"),
|
||||
("artifact_sources_blob_lifecycle_detached_idx", "i"),
|
||||
("artifact_sources_openapi_dangling_idx", "i"),
|
||||
("artifact_sources_pkey", "i"),
|
||||
("artifact_sources_workspace_created_idx", "i"),
|
||||
];
|
||||
|
||||
fn owned_names(values: &[&str]) -> Vec<String> {
|
||||
values.iter().map(|value| (*value).to_owned()).collect()
|
||||
}
|
||||
|
||||
fn owned_defaults(values: &[(&str, Option<&str>)]) -> Vec<(String, Option<String>)> {
|
||||
values
|
||||
.iter()
|
||||
.map(|(name, default)| ((*name).to_owned(), default.map(str::to_owned)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn catalog_columns(pool: &sqlx::PgPool, table: &str) -> Vec<String> {
|
||||
sqlx::query(
|
||||
"select column_name
|
||||
from information_schema.columns
|
||||
where table_schema = current_schema() and table_name = $1
|
||||
order by ordinal_position",
|
||||
)
|
||||
.bind(table)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|row| row.get::<String, _>("column_name"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn catalog_column_defaults(
|
||||
pool: &sqlx::PgPool,
|
||||
table: &str,
|
||||
) -> Vec<(String, Option<String>)> {
|
||||
sqlx::query(
|
||||
"select column_name, column_default
|
||||
from information_schema.columns
|
||||
where table_schema = current_schema() and table_name = $1
|
||||
order by ordinal_position",
|
||||
)
|
||||
.bind(table)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|row| {
|
||||
(
|
||||
row.get::<String, _>("column_name"),
|
||||
row.get::<Option<String>, _>("column_default"),
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn catalog_constraints(pool: &sqlx::PgPool, table: &str) -> Vec<String> {
|
||||
sqlx::query(
|
||||
"select c.conname
|
||||
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 = $1
|
||||
order by c.conname",
|
||||
)
|
||||
.bind(table)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|row| row.get::<String, _>("conname"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn catalog_indexes(pool: &sqlx::PgPool) -> Vec<String> {
|
||||
sqlx::query(
|
||||
"select idx.relname
|
||||
from pg_catalog.pg_index i
|
||||
join pg_catalog.pg_class idx on idx.oid = i.indexrelid
|
||||
join pg_catalog.pg_class t on t.oid = i.indrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
|
||||
where n.nspname = current_schema()
|
||||
and t.relname in ('artifact_blobs', 'artifact_sources')
|
||||
order by idx.relname",
|
||||
)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|row| row.get::<String, _>("relname"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn catalog_owned_relations(pool: &sqlx::PgPool) -> Vec<(String, String)> {
|
||||
sqlx::query(
|
||||
r"select c.relname, c.relkind::text as relkind
|
||||
from pg_catalog.pg_class c
|
||||
join pg_catalog.pg_namespace n on n.oid = c.relnamespace
|
||||
where n.nspname = current_schema()
|
||||
and c.relname like 'artifact\_%' escape '\'
|
||||
order by c.relname",
|
||||
)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|row| {
|
||||
(
|
||||
row.get::<String, _>("relname"),
|
||||
row.get::<String, _>("relkind"),
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn catalog_constraint_definitions(pool: &sqlx::PgPool) -> HashMap<String, String> {
|
||||
sqlx::query(
|
||||
"select c.conname, 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 in ('artifact_blobs', 'artifact_sources')",
|
||||
)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|row| {
|
||||
(
|
||||
row.get::<String, _>("conname"),
|
||||
row.get::<String, _>("definition"),
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn assert_v12_drift(pool: &sqlx::PgPool, drift: &str, restore: &str) {
|
||||
sqlx::raw_sql(sqlx::AssertSqlSafe(drift.to_owned()))
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let error = MigrationAuthority::preflight(pool).await.unwrap_err();
|
||||
assert_eq!(error.code(), "partial_sequence", "drift: {drift}");
|
||||
assert_eq!(error.version(), Some(12), "drift: {drift}");
|
||||
sqlx::raw_sql(sqlx::AssertSqlSafe(restore.to_owned()))
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 15 },
|
||||
"restore: {restore}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn v12_guard_rejects_exhaustive_catalog_drift_for_both_tables() {
|
||||
let database_url = crank_test_support::postgres_schema_url("test_v12_exhaustive_drift").await;
|
||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||
MigrationAuthority::apply(&pool).await.unwrap();
|
||||
|
||||
// Fixed catalog snapshots. These are hard assertions over the complete
|
||||
// matrix, so a disappeared object fails the test instead of silently
|
||||
// dropping out of the drift loop below.
|
||||
assert_eq!(
|
||||
catalog_columns(&pool, "artifact_blobs").await,
|
||||
owned_names(V12_BLOB_COLUMNS)
|
||||
);
|
||||
assert_eq!(
|
||||
catalog_columns(&pool, "artifact_sources").await,
|
||||
owned_names(V12_SOURCE_COLUMNS)
|
||||
);
|
||||
assert_eq!(
|
||||
V12_BLOB_COLUMNS.len() + V12_SOURCE_COLUMNS.len(),
|
||||
17,
|
||||
"the V12 column matrix is exactly seventeen columns"
|
||||
);
|
||||
assert_eq!(
|
||||
catalog_column_defaults(&pool, "artifact_blobs").await,
|
||||
owned_defaults(V12_BLOB_DEFAULTS)
|
||||
);
|
||||
assert_eq!(
|
||||
catalog_column_defaults(&pool, "artifact_sources").await,
|
||||
owned_defaults(V12_SOURCE_DEFAULTS)
|
||||
);
|
||||
assert_eq!(
|
||||
V12_BLOB_DEFAULTS.len() + V12_SOURCE_DEFAULTS.len(),
|
||||
17,
|
||||
"the V12 default matrix is exactly seventeen columns"
|
||||
);
|
||||
assert_eq!(
|
||||
V12_BLOB_DEFAULTS
|
||||
.iter()
|
||||
.chain(V12_SOURCE_DEFAULTS)
|
||||
.filter(|(_, default)| default.is_none())
|
||||
.count(),
|
||||
15,
|
||||
"fifteen V12 columns must declare no default"
|
||||
);
|
||||
assert_eq!(
|
||||
catalog_constraints(&pool, "artifact_blobs").await,
|
||||
owned_names(V12_BLOB_CONSTRAINTS)
|
||||
);
|
||||
assert_eq!(
|
||||
catalog_constraints(&pool, "artifact_sources").await,
|
||||
owned_names(V12_SOURCE_CONSTRAINTS)
|
||||
);
|
||||
assert_eq!(
|
||||
V12_BLOB_CONSTRAINTS.len() + V12_SOURCE_CONSTRAINTS.len(),
|
||||
18,
|
||||
"the V12 constraint matrix is exactly eighteen constraints"
|
||||
);
|
||||
assert_eq!(
|
||||
catalog_indexes(&pool).await,
|
||||
owned_names(&[
|
||||
"artifact_blobs_artifact_ref_key",
|
||||
"artifact_blobs_expired_claim_idx",
|
||||
"artifact_blobs_pkey",
|
||||
"artifact_sources_blob_lifecycle_detached_idx",
|
||||
"artifact_sources_openapi_dangling_idx",
|
||||
"artifact_sources_pkey",
|
||||
"artifact_sources_workspace_created_idx",
|
||||
])
|
||||
);
|
||||
assert_eq!(
|
||||
catalog_owned_relations(&pool).await,
|
||||
V12_OWNED_RELATIONS
|
||||
.iter()
|
||||
.map(|(name, kind)| ((*name).to_owned(), (*kind).to_owned()))
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
|
||||
// Every column of both tables: rename it away and restore the name.
|
||||
for (table, column) in V12_BLOB_COLUMNS
|
||||
.iter()
|
||||
.map(|column| ("artifact_blobs", *column))
|
||||
.chain(
|
||||
V12_SOURCE_COLUMNS
|
||||
.iter()
|
||||
.map(|column| ("artifact_sources", *column)),
|
||||
)
|
||||
{
|
||||
let drift = format!("alter table {table} rename column {column} to {column}_crank_drift;");
|
||||
let restore =
|
||||
format!("alter table {table} rename column {column}_crank_drift to {column};");
|
||||
assert_v12_drift(&pool, &drift, &restore).await;
|
||||
}
|
||||
|
||||
// Every column of both tables: change its type and restore the original,
|
||||
// then toggle nullability and restore it. The primary-key members are a
|
||||
// special case because PostgreSQL rejects dropping their NOT NULL while the
|
||||
// key exists; that rejection is asserted and the nullable shape is reached
|
||||
// through a dropped/restored primary key.
|
||||
exhaustive_v12::assert_column_type_drift(&pool).await;
|
||||
exhaustive_v12::assert_column_nullability_drift(&pool).await;
|
||||
|
||||
// Every declared default: swap in a different typed default, then restore.
|
||||
for (table, column, replacement, original) in [
|
||||
(
|
||||
"artifact_blobs",
|
||||
"storage_lifecycle",
|
||||
"'unavailable'",
|
||||
"'available'",
|
||||
),
|
||||
("artifact_sources", "lifecycle", "'detached'", "'active'"),
|
||||
] {
|
||||
let drift = format!("alter table {table} alter column {column} set default {replacement};");
|
||||
let restore = format!("alter table {table} alter column {column} set default {original};");
|
||||
assert_v12_drift(&pool, &drift, &restore).await;
|
||||
}
|
||||
|
||||
// Every V12 column that declares no default: introduce a concrete typed
|
||||
// default, prove the guard rejects it, then drop the default and prove the
|
||||
// schema returns to Current. A bare `set default null` would be folded back
|
||||
// into "no default" by PostgreSQL, so the drift list is fixed and compared
|
||||
// against the default inventory to keep a missing field from dropping out.
|
||||
assert_eq!(
|
||||
V12_BLOB_NO_DEFAULT_DRIFT
|
||||
.iter()
|
||||
.map(|(column, _)| *column)
|
||||
.collect::<Vec<_>>(),
|
||||
V12_BLOB_DEFAULTS
|
||||
.iter()
|
||||
.filter(|(_, default)| default.is_none())
|
||||
.map(|(column, _)| *column)
|
||||
.collect::<Vec<_>>(),
|
||||
"every defaultless artifact_blobs column must have a drift case"
|
||||
);
|
||||
assert_eq!(
|
||||
V12_SOURCE_NO_DEFAULT_DRIFT
|
||||
.iter()
|
||||
.map(|(column, _)| *column)
|
||||
.collect::<Vec<_>>(),
|
||||
V12_SOURCE_DEFAULTS
|
||||
.iter()
|
||||
.filter(|(_, default)| default.is_none())
|
||||
.map(|(column, _)| *column)
|
||||
.collect::<Vec<_>>(),
|
||||
"every defaultless artifact_sources column must have a drift case"
|
||||
);
|
||||
for (table, column, drift) in V12_BLOB_NO_DEFAULT_DRIFT
|
||||
.iter()
|
||||
.map(|(column, drift)| ("artifact_blobs", *column, *drift))
|
||||
.chain(
|
||||
V12_SOURCE_NO_DEFAULT_DRIFT
|
||||
.iter()
|
||||
.map(|(column, drift)| ("artifact_sources", *column, *drift)),
|
||||
)
|
||||
{
|
||||
let set = format!("alter table {table} alter column {column} set default {drift};");
|
||||
let restore = format!("alter table {table} alter column {column} drop default;");
|
||||
assert_v12_drift(&pool, &set, &restore).await;
|
||||
}
|
||||
|
||||
// Every constraint: drop it, then restore it from its own catalog
|
||||
// definition. The foreign key that depends on the artifact_blobs primary
|
||||
// key is dropped first and restored after it.
|
||||
let definitions = catalog_constraint_definitions(&pool).await;
|
||||
for (table, constraint) in V12_BLOB_CONSTRAINTS
|
||||
.iter()
|
||||
.map(|constraint| ("artifact_blobs", *constraint))
|
||||
.chain(
|
||||
V12_SOURCE_CONSTRAINTS
|
||||
.iter()
|
||||
.map(|constraint| ("artifact_sources", *constraint)),
|
||||
)
|
||||
{
|
||||
let definition = definitions
|
||||
.get(constraint)
|
||||
.unwrap_or_else(|| panic!("missing definition for {constraint}"));
|
||||
if constraint == "artifact_blobs_pkey" {
|
||||
let fk = definitions
|
||||
.get("artifact_sources_blob_digest_fkey")
|
||||
.expect("the dependent foreign key definition must be captured");
|
||||
let drift = "alter table artifact_sources drop constraint artifact_sources_blob_digest_fkey;\n\
|
||||
alter table artifact_blobs drop constraint artifact_blobs_pkey;";
|
||||
let restore = format!(
|
||||
"alter table artifact_blobs add constraint artifact_blobs_pkey {definition};\n\
|
||||
alter table artifact_sources add constraint artifact_sources_blob_digest_fkey {fk};"
|
||||
);
|
||||
assert_v12_drift(&pool, drift, &restore).await;
|
||||
} else {
|
||||
let drift = format!("alter table {table} drop constraint {constraint};");
|
||||
let restore = format!("alter table {table} add constraint {constraint} {definition};");
|
||||
assert_v12_drift(&pool, &drift, &restore).await;
|
||||
}
|
||||
}
|
||||
|
||||
// Every constraint again, this time keeping its name and `contype` while
|
||||
// changing only its definition: same-name `check (true)`, foreign keys with
|
||||
// a different delete action, and primary key/unique constraints with
|
||||
// rewritten members. Each mutation must be rejected before the original
|
||||
// captured definition is replayed.
|
||||
exhaustive_v12::assert_constraint_definition_drift(&pool).await;
|
||||
|
||||
// The standalone V12 index: change its definition, then remove it.
|
||||
let index_definition: String = sqlx::query_scalar(
|
||||
"select pg_get_indexdef(i.indexrelid)
|
||||
from pg_catalog.pg_index i
|
||||
join pg_catalog.pg_class idx on idx.oid = i.indexrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = idx.relnamespace
|
||||
where n.nspname = current_schema()
|
||||
and idx.relname = 'artifact_sources_workspace_created_idx'",
|
||||
)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_v12_drift(
|
||||
&pool,
|
||||
"drop index artifact_sources_workspace_created_idx;
|
||||
create index artifact_sources_workspace_created_idx
|
||||
on artifact_sources(workspace_id, source_id, created_at);",
|
||||
&format!("drop index artifact_sources_workspace_created_idx;\n{index_definition};"),
|
||||
)
|
||||
.await;
|
||||
|
||||
// Every standalone index must be rejected when removed and restorable from
|
||||
// its own catalog definition. The V12 guard validates the whole expanded
|
||||
// name set, so each removal is a version 12 partial sequence.
|
||||
for index in [
|
||||
"artifact_blobs_expired_claim_idx",
|
||||
"artifact_sources_blob_lifecycle_detached_idx",
|
||||
"artifact_sources_openapi_dangling_idx",
|
||||
"artifact_sources_workspace_created_idx",
|
||||
] {
|
||||
let definition: String = sqlx::query_scalar(
|
||||
"select pg_get_indexdef(i.indexrelid)
|
||||
from pg_catalog.pg_index i
|
||||
join pg_catalog.pg_class idx on idx.oid = i.indexrelid
|
||||
join pg_catalog.pg_namespace n on n.oid = idx.relnamespace
|
||||
where n.nspname = current_schema()
|
||||
and idx.relname = $1",
|
||||
)
|
||||
.bind(index)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_v12_drift(
|
||||
&pool,
|
||||
&format!("drop index {index};"),
|
||||
&format!("{definition};"),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
// Extra owned objects of every kind must be rejected by the exact inventory.
|
||||
assert_v12_drift(
|
||||
&pool,
|
||||
"create table artifact_crank_drift_owned(id integer);",
|
||||
"drop table artifact_crank_drift_owned;",
|
||||
)
|
||||
.await;
|
||||
assert_v12_drift(
|
||||
&pool,
|
||||
"create index artifact_crank_drift_owned_idx on artifact_blobs(digest);",
|
||||
"drop index artifact_crank_drift_owned_idx;",
|
||||
)
|
||||
.await;
|
||||
assert_v12_drift(
|
||||
&pool,
|
||||
"create view artifact_crank_drift_owned_view as select digest from artifact_blobs;",
|
||||
"drop view artifact_crank_drift_owned_view;",
|
||||
)
|
||||
.await;
|
||||
}
|
||||
+426
@@ -0,0 +1,426 @@
|
||||
use crank_registry::{MigrationAuthority, MigrationPreflight};
|
||||
|
||||
// V12 changed-type coverage. Every column gets a reachable `alter column ...
|
||||
// type` drift whose `information_schema.data_type` differs from the frozen
|
||||
// guard expectation, plus the exact expression that puts the original type
|
||||
// back. `character varying` is chosen for the text columns and `timestamp`
|
||||
// for the timestamptz columns because both are binary-compatible rewrites:
|
||||
// PostgreSQL applies them even while the primary key, unique, foreign key,
|
||||
// default, check and index objects stay in place, so the guard rejection is
|
||||
// genuinely caused by the type drift and not by a missing dependent object.
|
||||
const COLUMN_TYPE_DRIFT: &[(&str, &str, &str, &str)] = &[
|
||||
("artifact_blobs", "digest", "character varying", "text"),
|
||||
(
|
||||
"artifact_blobs",
|
||||
"artifact_ref",
|
||||
"character varying",
|
||||
"text",
|
||||
),
|
||||
("artifact_blobs", "size_bytes", "integer", "bigint"),
|
||||
(
|
||||
"artifact_blobs",
|
||||
"storage_lifecycle",
|
||||
"character varying",
|
||||
"text",
|
||||
),
|
||||
("artifact_blobs", "claim_token", "character varying", "text"),
|
||||
(
|
||||
"artifact_blobs",
|
||||
"claim_expires_at",
|
||||
"timestamp",
|
||||
"timestamp with time zone",
|
||||
),
|
||||
(
|
||||
"artifact_blobs",
|
||||
"created_at",
|
||||
"timestamp",
|
||||
"timestamp with time zone",
|
||||
),
|
||||
(
|
||||
"artifact_blobs",
|
||||
"updated_at",
|
||||
"timestamp",
|
||||
"timestamp with time zone",
|
||||
),
|
||||
(
|
||||
"artifact_sources",
|
||||
"workspace_id",
|
||||
"character varying",
|
||||
"text",
|
||||
),
|
||||
("artifact_sources", "source_id", "character varying", "text"),
|
||||
(
|
||||
"artifact_sources",
|
||||
"blob_digest",
|
||||
"character varying",
|
||||
"text",
|
||||
),
|
||||
("artifact_sources", "mime_type", "character varying", "text"),
|
||||
(
|
||||
"artifact_sources",
|
||||
"sensitivity",
|
||||
"character varying",
|
||||
"text",
|
||||
),
|
||||
("artifact_sources", "lifecycle", "character varying", "text"),
|
||||
(
|
||||
"artifact_sources",
|
||||
"created_at",
|
||||
"timestamp",
|
||||
"timestamp with time zone",
|
||||
),
|
||||
(
|
||||
"artifact_sources",
|
||||
"updated_at",
|
||||
"timestamp",
|
||||
"timestamp with time zone",
|
||||
),
|
||||
(
|
||||
"artifact_sources",
|
||||
"detached_at",
|
||||
"timestamp",
|
||||
"timestamp with time zone",
|
||||
),
|
||||
];
|
||||
|
||||
// Columns that legitimately carry `null` in V12. The remaining non-primary-key
|
||||
// columns are `not null`, and the primary-key members cannot have `not null`
|
||||
// dropped while the key exists.
|
||||
const V12_NULLABLE_COLUMNS: &[(&str, &str)] = &[
|
||||
("artifact_blobs", "claim_token"),
|
||||
("artifact_blobs", "claim_expires_at"),
|
||||
("artifact_sources", "detached_at"),
|
||||
];
|
||||
|
||||
const V12_PRIMARY_KEY_COLUMNS: &[(&str, &str)] = &[
|
||||
("artifact_blobs", "digest"),
|
||||
("artifact_sources", "workspace_id"),
|
||||
("artifact_sources", "source_id"),
|
||||
];
|
||||
|
||||
// V12 changed-definition coverage. Each entry keeps the original constraint
|
||||
// name and `pg_constraint.contype` and only changes the definition: every
|
||||
// check becomes `check (true)`, both foreign keys change their delete action,
|
||||
// and the primary key/unique members are rewritten while staying the same
|
||||
// kind. The original definition is captured from the catalog and replayed to
|
||||
// restore the exact prior shape.
|
||||
const CONSTRAINT_DEFINITION_DRIFT: &[(&str, &str, &str)] = &[
|
||||
(
|
||||
"artifact_blobs",
|
||||
"artifact_blobs_artifact_ref_key",
|
||||
"unique (digest)",
|
||||
),
|
||||
(
|
||||
"artifact_blobs",
|
||||
"artifact_blobs_claim_shape_check",
|
||||
"check (true)",
|
||||
),
|
||||
(
|
||||
"artifact_blobs",
|
||||
"artifact_blobs_claim_token_check",
|
||||
"check (true)",
|
||||
),
|
||||
(
|
||||
"artifact_blobs",
|
||||
"artifact_blobs_digest_check",
|
||||
"check (true)",
|
||||
),
|
||||
(
|
||||
"artifact_blobs",
|
||||
"artifact_blobs_lifecycle_check",
|
||||
"check (true)",
|
||||
),
|
||||
(
|
||||
"artifact_blobs",
|
||||
"artifact_blobs_pkey",
|
||||
"primary key (digest) include (artifact_ref)",
|
||||
),
|
||||
("artifact_blobs", "artifact_blobs_ref_check", "check (true)"),
|
||||
(
|
||||
"artifact_blobs",
|
||||
"artifact_blobs_size_check",
|
||||
"check (true)",
|
||||
),
|
||||
(
|
||||
"artifact_blobs",
|
||||
"artifact_blobs_timestamps_check",
|
||||
"check (true)",
|
||||
),
|
||||
(
|
||||
"artifact_sources",
|
||||
"artifact_sources_blob_digest_fkey",
|
||||
"foreign key (blob_digest) references artifact_blobs(digest) on delete cascade",
|
||||
),
|
||||
(
|
||||
"artifact_sources",
|
||||
"artifact_sources_id_check",
|
||||
"check (true)",
|
||||
),
|
||||
(
|
||||
"artifact_sources",
|
||||
"artifact_sources_lifecycle_check",
|
||||
"check (true)",
|
||||
),
|
||||
(
|
||||
"artifact_sources",
|
||||
"artifact_sources_mime_type_check",
|
||||
"check (true)",
|
||||
),
|
||||
(
|
||||
"artifact_sources",
|
||||
"artifact_sources_pkey",
|
||||
"primary key (source_id, workspace_id)",
|
||||
),
|
||||
(
|
||||
"artifact_sources",
|
||||
"artifact_sources_sensitivity_check",
|
||||
"check (true)",
|
||||
),
|
||||
(
|
||||
"artifact_sources",
|
||||
"artifact_sources_state_check",
|
||||
"check (true)",
|
||||
),
|
||||
(
|
||||
"artifact_sources",
|
||||
"artifact_sources_timestamps_check",
|
||||
"check (true)",
|
||||
),
|
||||
(
|
||||
"artifact_sources",
|
||||
"artifact_sources_workspace_id_fkey",
|
||||
"foreign key (workspace_id) references workspaces(id) on delete restrict",
|
||||
),
|
||||
];
|
||||
|
||||
async fn catalog_nullable(pool: &sqlx::PgPool, table: &str, column: &str) -> bool {
|
||||
sqlx::query_scalar::<_, String>(
|
||||
"select is_nullable
|
||||
from information_schema.columns
|
||||
where table_schema = current_schema() and table_name = $1 and column_name = $2",
|
||||
)
|
||||
.bind(table)
|
||||
.bind(column)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.unwrap()
|
||||
== "YES"
|
||||
}
|
||||
|
||||
pub(super) async fn assert_column_type_drift(pool: &sqlx::PgPool) {
|
||||
assert_eq!(
|
||||
COLUMN_TYPE_DRIFT.len(),
|
||||
17,
|
||||
"every V12 column needs a changed-type drift case"
|
||||
);
|
||||
for (table, column, drift_type, restore_type) in COLUMN_TYPE_DRIFT {
|
||||
let drift = format!("alter table {table} alter column {column} type {drift_type};");
|
||||
let restore = format!("alter table {table} alter column {column} type {restore_type};");
|
||||
super::assert_v12_drift(pool, &drift, &restore).await;
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn assert_column_nullability_drift(pool: &sqlx::PgPool) {
|
||||
let mut covered = 0usize;
|
||||
for (table, column) in super::V12_BLOB_COLUMNS
|
||||
.iter()
|
||||
.map(|column| ("artifact_blobs", *column))
|
||||
.chain(
|
||||
super::V12_SOURCE_COLUMNS
|
||||
.iter()
|
||||
.map(|column| ("artifact_sources", *column)),
|
||||
)
|
||||
{
|
||||
covered += 1;
|
||||
let nullable = catalog_nullable(pool, table, column).await;
|
||||
let expected_nullable = V12_NULLABLE_COLUMNS.contains(&(table, column));
|
||||
assert_eq!(
|
||||
nullable, expected_nullable,
|
||||
"nullability inventory drift for {table}.{column}"
|
||||
);
|
||||
if V12_PRIMARY_KEY_COLUMNS.contains(&(table, column)) {
|
||||
assert_primary_key_nullability(pool, table, column).await;
|
||||
} else if nullable {
|
||||
let drift = format!("alter table {table} alter column {column} set not null;");
|
||||
let restore = format!("alter table {table} alter column {column} drop not null;");
|
||||
super::assert_v12_drift(pool, &drift, &restore).await;
|
||||
} else {
|
||||
let drift = format!("alter table {table} alter column {column} drop not null;");
|
||||
let restore = format!("alter table {table} alter column {column} set not null;");
|
||||
super::assert_v12_drift(pool, &drift, &restore).await;
|
||||
}
|
||||
}
|
||||
assert_eq!(covered, 17, "every V12 column needs a nullability case");
|
||||
assert_eq!(
|
||||
V12_PRIMARY_KEY_COLUMNS.len() + V12_NULLABLE_COLUMNS.len(),
|
||||
6,
|
||||
"the V12 nullability exceptions are exactly the three primary-key members and three nullable columns"
|
||||
);
|
||||
}
|
||||
|
||||
// PostgreSQL refuses `drop not null` on a primary-key member outright, so this
|
||||
// case cannot be reached with the key in place. The rejection is asserted
|
||||
// explicitly instead of being skipped, then the nullable shape is reached by
|
||||
// dropping the primary key (and the dependent foreign key for artifact_blobs),
|
||||
// toggling nullability, and replaying the captured definitions in dependency
|
||||
// order.
|
||||
async fn assert_primary_key_nullability(pool: &sqlx::PgPool, table: &str, column: &str) {
|
||||
let direct = format!("alter table {table} alter column {column} drop not null;");
|
||||
let error = sqlx::raw_sql(sqlx::AssertSqlSafe(direct))
|
||||
.execute(pool)
|
||||
.await
|
||||
.expect_err("PostgreSQL must reject dropping NOT NULL on a primary key member");
|
||||
assert!(
|
||||
error.to_string().contains("is in a primary key"),
|
||||
"unexpected rejection for {table}.{column}: {error}"
|
||||
);
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 15 },
|
||||
"a rejected primary-key nullability change must leave the schema current"
|
||||
);
|
||||
|
||||
let definitions = super::catalog_constraint_definitions(pool).await;
|
||||
let (drift, restore) = if table == "artifact_blobs" {
|
||||
let pkey = definitions
|
||||
.get("artifact_blobs_pkey")
|
||||
.expect("artifact_blobs primary key definition must be captured");
|
||||
let fk = definitions
|
||||
.get("artifact_sources_blob_digest_fkey")
|
||||
.expect("the foreign key that depends on artifact_blobs_pkey must be captured");
|
||||
(
|
||||
"alter table artifact_sources drop constraint artifact_sources_blob_digest_fkey;\n\
|
||||
alter table artifact_blobs drop constraint artifact_blobs_pkey;\n\
|
||||
alter table artifact_blobs alter column digest drop not null;"
|
||||
.to_owned(),
|
||||
format!(
|
||||
"alter table artifact_blobs alter column digest set not null;\n\
|
||||
alter table artifact_blobs add constraint artifact_blobs_pkey {pkey};\n\
|
||||
alter table artifact_sources add constraint artifact_sources_blob_digest_fkey {fk};"
|
||||
),
|
||||
)
|
||||
} else {
|
||||
let pkey = definitions
|
||||
.get("artifact_sources_pkey")
|
||||
.expect("artifact_sources primary key definition must be captured");
|
||||
(
|
||||
format!(
|
||||
"alter table artifact_sources drop constraint artifact_sources_pkey;\n\
|
||||
alter table artifact_sources alter column {column} drop not null;"
|
||||
),
|
||||
format!(
|
||||
"alter table artifact_sources alter column {column} set not null;\n\
|
||||
alter table artifact_sources add constraint artifact_sources_pkey {pkey};"
|
||||
),
|
||||
)
|
||||
};
|
||||
super::assert_v12_drift(pool, &drift, &restore).await;
|
||||
}
|
||||
|
||||
pub(super) async fn assert_constraint_definition_drift(pool: &sqlx::PgPool) {
|
||||
assert_eq!(
|
||||
CONSTRAINT_DEFINITION_DRIFT.len(),
|
||||
18,
|
||||
"every V12 constraint needs a same-name/kind changed-definition case"
|
||||
);
|
||||
let definitions = super::catalog_constraint_definitions(pool).await;
|
||||
for (table, constraint, drift_definition) in CONSTRAINT_DEFINITION_DRIFT {
|
||||
let original = definitions
|
||||
.get(*constraint)
|
||||
.unwrap_or_else(|| panic!("missing original definition for {constraint}"));
|
||||
if *constraint == "artifact_blobs_pkey" {
|
||||
let fk = definitions
|
||||
.get("artifact_sources_blob_digest_fkey")
|
||||
.expect("the foreign key that depends on artifact_blobs_pkey must be captured");
|
||||
let drift = format!(
|
||||
"alter table artifact_sources drop constraint artifact_sources_blob_digest_fkey;\n\
|
||||
alter table artifact_blobs drop constraint artifact_blobs_pkey;\n\
|
||||
alter table artifact_blobs add constraint artifact_blobs_pkey {drift_definition};\n\
|
||||
alter table artifact_sources add constraint artifact_sources_blob_digest_fkey {fk};"
|
||||
);
|
||||
let restore = format!(
|
||||
"alter table artifact_sources drop constraint artifact_sources_blob_digest_fkey;\n\
|
||||
alter table artifact_blobs drop constraint artifact_blobs_pkey;\n\
|
||||
alter table artifact_blobs add constraint artifact_blobs_pkey {original};\n\
|
||||
alter table artifact_sources add constraint artifact_sources_blob_digest_fkey {fk};"
|
||||
);
|
||||
assert_definition_only_drift(pool, constraint, &drift, &restore).await;
|
||||
} else {
|
||||
let drift = format!(
|
||||
"alter table {table} drop constraint {constraint};\n\
|
||||
alter table {table} add constraint {constraint} {drift_definition};"
|
||||
);
|
||||
let restore = format!(
|
||||
"alter table {table} drop constraint {constraint};\n\
|
||||
alter table {table} add constraint {constraint} {original};"
|
||||
);
|
||||
assert_definition_only_drift(pool, constraint, &drift, &restore).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A definition test must not pass merely because a dependent constraint went
|
||||
// missing. Assert that exactly the named definition changed, with the complete
|
||||
// name/kind inventory preserved, before asking the production guard to reject it.
|
||||
async fn assert_definition_only_drift(
|
||||
pool: &sqlx::PgPool,
|
||||
changed: &str,
|
||||
drift: &str,
|
||||
restore: &str,
|
||||
) {
|
||||
let before = super::catalog_constraint_definitions(pool).await;
|
||||
let kinds = constraint_kinds(pool).await;
|
||||
sqlx::raw_sql(sqlx::AssertSqlSafe(drift.to_owned()))
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let after = super::catalog_constraint_definitions(pool).await;
|
||||
assert_eq!(
|
||||
constraint_kinds(pool).await,
|
||||
kinds,
|
||||
"all constraint names and kinds must survive: {changed}"
|
||||
);
|
||||
assert_ne!(
|
||||
after.get(changed),
|
||||
before.get(changed),
|
||||
"definition must actually change: {changed}"
|
||||
);
|
||||
for (name, definition) in &before {
|
||||
if name != changed {
|
||||
assert_eq!(
|
||||
after.get(name),
|
||||
Some(definition),
|
||||
"unrelated definition changed: {name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
let error = MigrationAuthority::preflight(pool).await.unwrap_err();
|
||||
assert_eq!(
|
||||
error.code(),
|
||||
"partial_sequence",
|
||||
"definition drift: {changed}"
|
||||
);
|
||||
assert_eq!(error.version(), Some(12), "definition drift: {changed}");
|
||||
sqlx::raw_sql(sqlx::AssertSqlSafe(restore.to_owned()))
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(super::catalog_constraint_definitions(pool).await, before);
|
||||
assert_eq!(
|
||||
MigrationAuthority::preflight(pool).await.unwrap(),
|
||||
MigrationPreflight::Current { version: 15 }
|
||||
);
|
||||
}
|
||||
|
||||
async fn constraint_kinds(pool: &sqlx::PgPool) -> Vec<(String, String)> {
|
||||
sqlx::query_as(
|
||||
"select c.conname::text, c.contype::text 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 in ('artifact_blobs', 'artifact_sources') order by c.conname",
|
||||
)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
Reference in new issue
Block a user