Files
khadhroony-solana-project/crates/ksp-store-lib/tests/hardening_completeness.rs
2026-08-30 23:46:37 +02:00

324 lines
12 KiB
Rust

// file: crates/ksp-store-lib/tests/hardening_completeness.rs
// version: 6
#![warn(missing_docs)]
#![deny(unreachable_pub)]
#![forbid(unsafe_code)]
//! Hardening, exact-surface and feature-matrix canaries for the common Store facade.
const SECRET_CANARY: &str = "KSP-STORE-SECRET-CANARY-PRE009";
fn poll_ready<T>(future: impl std::future::Future<Output = T>) -> T {
let mut future = std::boxed::Box::pin(future);
let waker = std::task::Waker::noop();
let mut context = std::task::Context::from_waker(waker);
return match std::future::Future::poll(future.as_mut(), &mut context) {
std::task::Poll::Ready(value) => value,
std::task::Poll::Pending => panic!("Store hardening pre-I/O rejection unexpectedly became pending"),
};
}
fn valid_network() -> ksp_store_lib::RawNetworkId {
return match ksp_store_lib::RawNetworkId::new("devnet") {
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => panic!("valid hardening network rejected: {error:?}"),
};
}
fn hostile_settings(connection_uri: &str) -> ksp_store_lib::StoreSettings {
let postgres = ksp_store_lib::PostgresStoreSettings::new(
connection_uri,
ksp_store_lib::PostgresPoolSettings::default(),
ksp_store_lib::PostgresTlsMode::VerifyFull,
ksp_store_lib::PostgresBootstrapSettings::default(),
);
return ksp_store_lib::StoreSettings::with_default_shutdown(valid_network(), ksp_store_lib::StoreBackendSettings::Postgres(postgres));
}
fn public_reexport_names(source: &str) -> std::vec::Vec<&str> {
let mut names = std::vec::Vec::new();
for line in source.lines() {
let trimmed = line.trim();
if !trimmed.starts_with("pub use ") || !trimmed.ends_with(';') {
continue;
}
let without_semicolon = trimmed.trim_end_matches(';');
let name = match without_semicolon.rsplit("::").next() {
std::option::Option::Some(value) => value,
std::option::Option::None => continue,
};
names.push(name);
}
names.sort_unstable();
return names;
}
fn manifest_dependency_names(source: &str) -> std::vec::Vec<&str> {
let dependencies_tail = match source.split("[dependencies]").nth(1) {
std::option::Option::Some(value) => value,
std::option::Option::None => return std::vec::Vec::new(),
};
let dependencies = match dependencies_tail.split("[lints]").next() {
std::option::Option::Some(value) => value,
std::option::Option::None => return std::vec::Vec::new(),
};
let mut names = std::vec::Vec::new();
for line in dependencies.lines() {
let content = match line.split('#').next() {
std::option::Option::Some(value) => value.trim(),
std::option::Option::None => continue,
};
if content.is_empty() {
continue;
}
let key = match content.split('=').next() {
std::option::Option::Some(value) => value.trim().trim_end_matches(".workspace"),
std::option::Option::None => continue,
};
if !key.is_empty() {
names.push(key);
}
}
names.sort_unstable();
return names;
}
fn raw_capability_trait_names<'a>(source: &'a str, implementor: &str) -> std::vec::Vec<&'a str> {
let mut names = std::vec::Vec::new();
for line in source.lines() {
let trimmed = line.trim();
if !trimmed.starts_with("impl ksp_store_api::Raw") || !trimmed.contains(implementor) {
continue;
}
let trait_tail = match trimmed.strip_prefix("impl ksp_store_api::") {
std::option::Option::Some(value) => value,
std::option::Option::None => continue,
};
let trait_name = match trait_tail.split(" for ").next() {
std::option::Option::Some(value) => value,
std::option::Option::None => continue,
};
names.push(trait_name);
}
names.sort_unstable();
return names;
}
#[test]
fn pre_009_facade_modules_and_crate_root_exports_are_exact() {
let crate_root = include_str!("../src/lib.rs");
for required in ["mod constants;", "mod error;", "mod health;", "mod settings;", "mod store;"] {
assert!(crate_root.contains(required), "missing Store facade module: {required}");
}
assert!(!crate_root.contains("pub mod "));
let actual = public_reexport_names(crate_root);
let mut expected = [
"ERROR_CODE_BACKEND_CLOSED",
"ERROR_CODE_BACKEND_NOT_COMPILED",
"ERROR_CODE_BACKEND_OPEN_FAILED",
"ERROR_CODE_POSTGRES_CONFIG_INVALID",
"ERROR_CODE_POSTGRES_CONNECT_FAILED",
"ERROR_CODE_POSTGRES_DATA_INVALID",
"ERROR_CODE_POSTGRES_HEALTH_FAILED",
"ERROR_CODE_POSTGRES_MIGRATION_FAILED",
"ERROR_CODE_POSTGRES_MIGRATION_MISMATCH",
"ERROR_CODE_POSTGRES_PAGE_LIMIT_UNSUPPORTED",
"ERROR_CODE_POSTGRES_POOL_TIMEOUT",
"ERROR_CODE_POSTGRES_READ_FAILED",
"ERROR_CODE_POSTGRES_RETENTION_COMPACTION_UNSUPPORTED",
"ERROR_CODE_POSTGRES_SCHEMA_NEWER",
"ERROR_CODE_POSTGRES_TLS_FAILED",
"ERROR_CODE_POSTGRES_WRITE_FAILED",
"ERROR_CODE_RAW_CONFLICT",
"ERROR_CODE_RAW_MODEL_INVALID",
"ERROR_CODE_RAW_PAYLOAD_INVALID",
"ERROR_CODE_RAW_PROVENANCE_INVALID",
"ERROR_CODE_RAW_QUERY_INVALID",
"ERROR_CODE_RAW_REFERENCE_NOT_FOUND",
"ERROR_CODE_RAW_RETENTION_INVALID",
"ERROR_CODE_SETTINGS_INVALID",
"ERROR_CODE_SHUTDOWN_TIMEOUT",
"ERROR_CODE_WRONG_NETWORK",
"Error",
"ErrorCode",
"ErrorContext",
"MAX_RAW_ACCOUNT_DATA_BYTES",
"MAX_RAW_CODE_BYTES",
"MAX_RAW_PAGE_CURSOR_BYTES",
"MAX_RAW_PAYLOAD_BYTES",
"MAX_RAW_SOURCE_PAYLOAD_BYTES",
"MAX_RAW_UNIX_MILLIS",
"PostgresBootstrapSettings",
"PostgresPoolSettings",
"PostgresStoreSettings",
"PostgresTlsMode",
"Pubkey",
"RawAccountObservation",
"RawAccountObservationRead",
"RawAccountObservationWrite",
"RawAccountState",
"RawAccountStateQuery",
"RawAccountStateRead",
"RawAccountStateReference",
"RawAccountStateWrite",
"RawAcquisitionOrigin",
"RawAcquisitionProvenance",
"RawAcquisitionWriteOutcome",
"RawContentHash",
"RawEntityWriteOutcome",
"RawFormatId",
"RawNetworkId",
"RawObservationKey",
"RawObservationWriteOutcome",
"RawPage",
"RawPageCursor",
"RawPageLimit",
"RawPageRequest",
"RawPayload",
"RawProvenanceCode",
"RawRetentionState",
"RawRetentionWriteOutcome",
"RawSlotRange",
"RawSortDirection",
"RawTimestamp",
"RawTransaction",
"RawTransactionAcquisitionMode",
"RawTransactionObservation",
"RawTransactionObservationRead",
"RawTransactionObservationWrite",
"RawTransactionQuery",
"RawTransactionRead",
"RawTransactionReference",
"RawTransactionRetentionRead",
"RawTransactionRetentionTransition",
"RawTransactionRetentionWrite",
"RawTransactionSignature",
"RawTransactionTombstone",
"RawTransactionWrite",
"Result",
"Store",
"StoreApiFuture",
"StoreBackendKind",
"StoreBackendSettings",
"StoreHealthSnapshot",
"StoreHealthState",
"StoreRuntimeSnapshot",
"StoreSettings",
];
expected.sort_unstable();
assert_eq!(actual.as_slice(), expected.as_slice());
assert_eq!(actual.len(), 91);
return;
}
#[test]
fn pre_009_facade_manifest_and_feature_contract_are_exact() {
let manifest = include_str!("../Cargo.toml");
assert!(manifest.contains("default = [\"postgres\"]"));
assert!(manifest.contains("postgres = [\"dep:ksp-store-postgres-lib\"]"));
let actual = manifest_dependency_names(manifest);
let expected = ["ksp-logging-lib", "ksp-store-api", "ksp-store-postgres-lib"];
assert_eq!(actual.as_slice(), expected.as_slice());
for forbidden in ["tokio-postgres", "deadpool-postgres", "rustls", "sqlx", "ksp-config-lib", "ksp-onchain-transport-lib", "ksp-offchain-transport-lib"] {
assert!(!manifest.contains(forbidden), "forbidden Store facade dependency detected: {forbidden}");
}
return;
}
#[test]
fn pre_009_secret_canary_never_crosses_settings_or_pre_io_error_debug() {
let malformed = std::format!("not-a-postgresql-uri-{SECRET_CANARY}");
let settings = hostile_settings(malformed.as_str());
let rendered = std::format!("{settings:?}");
assert!(!rendered.contains(SECRET_CANARY));
assert!(rendered.contains("<redacted>"));
let result = poll_ready(ksp_store_lib::Store::open(settings));
let error = match result {
std::result::Result::Err(value) => value,
std::result::Result::Ok(_) => panic!("hostile Store settings unexpectedly opened"),
};
#[cfg(feature = "postgres")]
assert_eq!(error.code(), ksp_store_lib::ERROR_CODE_POSTGRES_CONFIG_INVALID);
#[cfg(not(feature = "postgres"))]
assert_eq!(error.code(), ksp_store_lib::ERROR_CODE_BACKEND_NOT_COMPILED);
assert!(!std::format!("{error}").contains(SECRET_CANARY));
assert!(!std::format!("{error:?}").contains(SECRET_CANARY));
return;
}
#[test]
fn pre_009_facade_production_sources_keep_config_env_physical_sql_and_backend_handles_out() {
let production = std::format!(
"{}
{}
{}
{}",
include_str!("../src/error.rs"),
include_str!("../src/health.rs"),
include_str!("../src/settings.rs"),
include_str!("../src/store.rs")
);
for forbidden in [
"ksp_config_lib",
"std::env",
"dotenv",
"PGHOST",
"PGPORT",
"PGUSER",
"PGPASSWORD",
".pgpass",
"tokio_postgres::Client",
"tokio_postgres::Row",
"tokio_postgres::Statement",
"deadpool_postgres::Pool",
"sqlx::",
"CREATE TABLE",
"INSERT INTO",
"UPDATE ",
"DELETE FROM",
] {
assert!(!production.contains(forbidden), "forbidden facade ownership/runtime material detected: {forbidden}");
}
return;
}
#[test]
fn pre_010_facade_raw_capability_inventory_is_exactly_ten() {
let store = include_str!("../src/store.rs");
let capability_impls = [
"impl ksp_store_api::RawAccountObservationRead for Store",
"impl ksp_store_api::RawAccountObservationWrite for Store",
"impl ksp_store_api::RawAccountStateRead for Store",
"impl ksp_store_api::RawAccountStateWrite for Store",
"impl ksp_store_api::RawTransactionObservationRead for Store",
"impl ksp_store_api::RawTransactionObservationWrite for Store",
"impl ksp_store_api::RawTransactionRead for Store",
"impl ksp_store_api::RawTransactionRetentionRead for Store",
"impl ksp_store_api::RawTransactionRetentionWrite for Store",
"impl ksp_store_api::RawTransactionWrite for Store",
];
for implementation in capability_impls {
assert_eq!(store.matches(implementation).count(), 1, "unexpected Store capability implementation inventory: {implementation}");
}
assert_eq!(store.matches("impl ksp_store_api::Raw").count(), 10);
assert_eq!(store.matches("validate_operation_network(").count(), 14);
return;
}
#[test]
fn pre_010_facade_and_backend_raw_capability_sets_match_exactly_without_account_retention() {
let store = include_str!("../src/store.rs");
let backend = include_str!("../../ksp-store-postgres-lib/src/runtime.rs");
let store_traits = raw_capability_trait_names(store, " for Store");
let backend_traits = raw_capability_trait_names(backend, " for PostgresBackend");
assert_eq!(store_traits.len(), 10);
assert_eq!(backend_traits.len(), 10);
assert_eq!(store_traits, backend_traits);
for forbidden in ["RawAccountRetentionRead", "RawAccountRetentionWrite", "RawAccountDelete", "RawAccountCompaction"] {
assert!(!store_traits.contains(&forbidden), "unexpected account capability added to Store: {forbidden}");
assert!(!backend_traits.contains(&forbidden), "unexpected account capability added to PostgreSQL backend: {forbidden}");
}
return;
}