feat: harden community production foundation through story 1.5

This commit is contained in:
bsodfather committed 2026-08-14 00:21:59 +03:00
1 parent c30461cc92
commit f6fc2e5c9b
161 files changed
+16758 -2515

No files matched your search

@@ -0,0 +1,451 @@
use sqlx::{PgConnection, Row, query};
use super::authority::MigrationError;
pub(super) const OWNED_RELATIONS: &[&str] = &[
"__crank_core_migrations",
"__crank_migrations",
"__crank_migration_legacy_audit",
"__crank_mcp_migrations",
"__crank_ext_migrations",
"mcp_transport_sessions",
"workspaces",
"users",
"memberships",
"user_sessions",
"invitation_tokens",
"platform_api_keys",
"operations",
"operation_versions",
"published_operations",
"operation_samples",
"descriptors",
"agents",
"agent_versions",
"published_agents",
"agent_operation_bindings",
"secrets",
"secret_versions",
"auth_profiles",
"workspace_upstreams",
"yaml_import_jobs",
"import_jobs",
"approval_requests",
"invocation_logs",
"usage_rollups",
];
const REQUIRED_COLUMNS: &[(&str, &[&str])] = &[
(
"__crank_core_migrations",
&["version", "description", "checksum", "applied_at"],
),
(
"__crank_migrations",
&[
"version",
"name",
"checksum",
"phase",
"compatibility",
"applied_at",
],
),
(
"__crank_migration_legacy_audit",
&["source", "source_version", "source_checksum", "imported_at"],
),
(
"__crank_mcp_migrations",
&["version", "checksum", "applied_at"],
),
(
"__crank_ext_migrations",
&["extension_name", "version", "checksum", "applied_at"],
),
(
"mcp_transport_sessions",
&[
"id",
"protocol_version",
"initialized",
"supports_elicitation",
"workspace_slug",
"agent_slug",
"created_at",
"updated_at",
"expires_at",
],
),
];
const REQUIRED_COLUMN_TYPES: &[(&str, &str, &str, bool)] = &[
("__crank_core_migrations", "version", "integer", false),
("__crank_core_migrations", "description", "text", false),
("__crank_core_migrations", "checksum", "text", false),
(
"__crank_core_migrations",
"applied_at",
"timestamp with time zone",
false,
),
("__crank_migrations", "version", "bigint", false),
("__crank_migrations", "name", "text", false),
("__crank_migrations", "checksum", "text", false),
("__crank_migrations", "phase", "text", false),
("__crank_migrations", "compatibility", "text", false),
(
"__crank_migrations",
"applied_at",
"timestamp with time zone",
false,
),
("__crank_migration_legacy_audit", "source", "text", false),
(
"__crank_migration_legacy_audit",
"source_version",
"bigint",
false,
),
(
"__crank_migration_legacy_audit",
"source_checksum",
"text",
false,
),
(
"__crank_migration_legacy_audit",
"imported_at",
"timestamp with time zone",
false,
),
("__crank_mcp_migrations", "version", "integer", false),
("__crank_mcp_migrations", "checksum", "text", false),
(
"__crank_mcp_migrations",
"applied_at",
"timestamp with time zone",
false,
),
("__crank_ext_migrations", "extension_name", "text", false),
("__crank_ext_migrations", "version", "integer", false),
("__crank_ext_migrations", "checksum", "text", true),
(
"__crank_ext_migrations",
"applied_at",
"timestamp with time zone",
false,
),
("mcp_transport_sessions", "id", "text", false),
("mcp_transport_sessions", "protocol_version", "text", false),
("mcp_transport_sessions", "initialized", "boolean", false),
(
"mcp_transport_sessions",
"supports_elicitation",
"boolean",
false,
),
("mcp_transport_sessions", "workspace_slug", "text", false),
("mcp_transport_sessions", "agent_slug", "text", false),
(
"mcp_transport_sessions",
"created_at",
"timestamp with time zone",
false,
),
(
"mcp_transport_sessions",
"updated_at",
"timestamp with time zone",
false,
),
(
"mcp_transport_sessions",
"expires_at",
"timestamp with time zone",
true,
),
];
pub(super) async fn relation_exists(
connection: &mut PgConnection,
relation: &str,
) -> Result<bool, MigrationError> {
query("select to_regclass(format('%I.%I', current_schema(), $1))::text is not null as present")
.bind(relation)
.fetch_one(connection)
.await
.map_err(|_| MigrationError::storage("preflight.inventory"))?
.try_get::<bool, _>("present")
.map_err(|_| MigrationError::storage("preflight.inventory"))
}
pub(super) async fn validate_required_relations(
connection: &mut PgConnection,
relations: &[&str],
version: i64,
) -> Result<(), MigrationError> {
for relation in relations {
if !relation_exists(connection, relation).await? {
return Err(schema_error(version));
}
let kind = query(
"select c.relkind::text as kind
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 = $1",
)
.bind(relation)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.try_get::<String, _>("kind")
.map_err(|_| MigrationError::storage("preflight.schema"))?;
if !matches!(kind.as_str(), "r" | "p") {
return Err(schema_error(version));
}
}
Ok(())
}
pub(super) async fn validate_schema_fingerprint(
connection: &mut PgConnection,
current_version: i64,
) -> Result<(), MigrationError> {
for (table, required) in REQUIRED_COLUMNS {
if !relation_exists(connection, table).await? {
continue;
}
let rows = query(
"select column_name from information_schema.columns
where table_schema = current_schema() and table_name = $1
order by ordinal_position limit 257",
)
.bind(table)
.fetch_all(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let actual = rows
.iter()
.filter_map(|row| row.try_get::<String, _>("column_name").ok())
.collect::<Vec<_>>();
if actual.len() != required.len()
|| required
.iter()
.any(|column| !actual.iter().any(|actual| actual == column))
{
return Err(schema_error(current_version));
}
}
for (table, column, data_type, nullable) in REQUIRED_COLUMN_TYPES {
if !relation_exists(connection, table).await? {
continue;
}
let row = query(
"select data_type, is_nullable from information_schema.columns
where table_schema = current_schema() and table_name = $1 and column_name = $2",
)
.bind(table)
.bind(column)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<String, _>("data_type").ok().as_deref() == Some(*data_type)
&& row.try_get::<String, _>("is_nullable").ok().as_deref()
== Some(if *nullable { "YES" } else { "NO" })
});
if !valid {
return Err(schema_error(current_version));
}
}
if current_version < 3 {
let trace_column_present = query(
"select exists (
select 1 from information_schema.columns
where table_schema = current_schema()
and table_name = 'invocation_logs'
and column_name = 'trace_id'
) as present",
)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.try_get::<bool, _>("present")
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let trace_constraint_present = named_constraint_exists(
connection,
"invocation_logs",
"invocation_logs_trace_id_format_check",
)
.await?;
let v3_index_present =
relation_exists(connection, "invocation_logs_workspace_request_id_idx").await?
|| relation_exists(connection, "invocation_logs_workspace_trace_id_idx").await?;
if trace_column_present || trace_constraint_present || v3_index_present {
return Err(schema_error(current_version));
}
} else {
let trace_id = query(
"select data_type, is_nullable from information_schema.columns
where table_schema = current_schema()
and table_name = 'invocation_logs'
and column_name = 'trace_id'",
)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = trace_id.is_some_and(|row| {
row.try_get::<String, _>("data_type").ok().as_deref() == Some("text")
&& row.try_get::<String, _>("is_nullable").ok().as_deref() == Some("YES")
});
if !valid {
return Err(schema_error(current_version));
}
let constraint = query(
"select pg_get_expr(c.conbin, c.conrelid) as expression, c.convalidated
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 = 'invocation_logs'
and c.conname = 'invocation_logs_trace_id_format_check'
and c.contype = 'c'",
)
.fetch_optional(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let constraint_valid = constraint.is_some_and(|row| {
row.try_get::<String, _>("expression")
.ok()
.is_some_and(|value| {
normalize_definition(&value)
== "trace_idisnullortrace_id~'^[0-9a-f]{32}$'::textandtrace_id<>'00000000000000000000000000000000'::text"
})
&& row.try_get::<bool, _>("convalidated").ok() == Some(false)
});
if !constraint_valid {
return Err(schema_error(current_version));
}
}
let required_indexes = [
"mcp_transport_sessions_workspace_agent_idx",
"mcp_transport_sessions_expires_at_idx",
];
for index in required_indexes {
let present = query(
"select exists (select 1 from pg_catalog.pg_indexes
where schemaname = current_schema() and indexname = $1) as present",
)
.bind(index)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.try_get::<bool, _>("present")
.map_err(|_| MigrationError::storage("preflight.schema"))?;
if !present {
return Err(schema_error(current_version));
}
}
if current_version >= 3 {
validate_index(
connection,
"invocation_logs_workspace_request_id_idx",
"request_id",
"request_idisnotnullandoctet_lengthrequest_id<=128",
)
.await?;
validate_index(
connection,
"invocation_logs_workspace_trace_id_idx",
"trace_id",
"trace_idisnotnull",
)
.await?;
}
Ok(())
}
async fn named_constraint_exists(
connection: &mut PgConnection,
table: &str,
constraint: &str,
) -> Result<bool, MigrationError> {
query(
"select exists (
select 1 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
and c.conname = $2
) as present",
)
.bind(table)
.bind(constraint)
.fetch_one(connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?
.try_get::<bool, _>("present")
.map_err(|_| MigrationError::storage("preflight.schema"))
}
async fn validate_index(
connection: &mut PgConnection,
index: &str,
second_column: &str,
expected_predicate: &str,
) -> Result<(), MigrationError> {
let row = query(
"select
t.relname as table_name,
am.amname as access_method,
i.indisvalid,
i.indisready,
i.indisunique,
pg_get_indexdef(i.indexrelid, 1, true) as first_column,
pg_get_indexdef(i.indexrelid, 2, true) as second_column,
pg_get_expr(i.indpred, i.indrelid) as predicate
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
join pg_catalog.pg_am am on am.oid = idx.relam
where n.nspname = current_schema() and idx.relname = $1",
)
.bind(index)
.fetch_optional(connection)
.await
.map_err(|_| MigrationError::storage("preflight.schema"))?;
let valid = row.is_some_and(|row| {
row.try_get::<String, _>("table_name").ok().as_deref() == Some("invocation_logs")
&& row.try_get::<String, _>("access_method").ok().as_deref() == Some("btree")
&& row.try_get::<bool, _>("indisvalid").ok() == Some(true)
&& row.try_get::<bool, _>("indisready").ok() == Some(true)
&& row.try_get::<bool, _>("indisunique").ok() == Some(false)
&& row.try_get::<String, _>("first_column").ok().as_deref() == Some("workspace_id")
&& row.try_get::<String, _>("second_column").ok().as_deref() == Some(second_column)
&& row
.try_get::<String, _>("predicate")
.ok()
.is_some_and(|value| normalize_definition(&value) == expected_predicate)
});
if valid { Ok(()) } else { Err(schema_error(3)) }
}
fn normalize_definition(value: &str) -> String {
value
.chars()
.filter(|character| !character.is_ascii_whitespace() && !matches!(character, '(' | ')'))
.flat_map(char::to_lowercase)
.collect()
}
fn schema_error(version: i64) -> MigrationError {
MigrationError::new(
"partial_sequence",
"preflight.schema",
Some(version),
"restore_known_good_backup",
)
}