#![allow(clippy::unwrap_used, clippy::panic)]
use std::{collections::BTreeSet, fs, process::Command};
use fraiseql_core::{runtime::RuntimeConfig, schema::CompiledSchema};
use tempfile::TempDir;
fn compile(types_json: &str, toml_config: &str) -> String {
let temp_dir = TempDir::new().unwrap();
let types_path = temp_dir.path().join("types.json");
let toml_path = temp_dir.path().join("fraiseql.toml");
let output_path = temp_dir.path().join("schema.compiled.json");
fs::write(&types_path, types_json).unwrap();
fs::write(&toml_path, toml_config).unwrap();
let cli_path = env!("CARGO_BIN_EXE_fraiseql-cli");
let output = Command::new(cli_path)
.args([
"compile",
toml_path.to_str().unwrap(),
"--types",
types_path.to_str().unwrap(),
"--output",
output_path.to_str().unwrap(),
])
.output()
.expect("failed to run fraiseql-cli");
assert!(
output.status.success(),
"CLI compile failed.\nstdout: {}\nstderr: {}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
fs::read_to_string(&output_path).expect("compiled schema missing")
}
const TYPES_JSON: &str = r#"
{
"types": [
{
"name": "Order",
"sql_source": "v_order",
"fields": [
{"name": "id", "type": "ID", "nullable": false},
{"name": "amount", "type": "Float", "nullable": false}
]
}
],
"queries": [
{
"name": "orders",
"return_type": "Order",
"returns_list": true,
"nullable": false,
"sql_source": "v_order",
"cache_ttl_seconds": 300,
"inject_params": {"tenant_id": "jwt:tenant_id"}
}
],
"mutations": [
{
"name": "createOrder",
"return_type": "Order",
"sql_source": "fn_create_order",
"invalidates_views": ["v_order"]
}
]
}
"#;
#[test]
fn enterprise_audit_toggle_survives_emit_parse_runtime() {
let toml = r#"
[schema]
name = "contract_audit"
version = "1.0.0"
database_target = "postgresql"
[database]
url = "postgresql://localhost/test"
[security]
[security.enterprise]
rate_limiting_enabled = false
audit_logging_enabled = true
"#;
let compiled_json = compile(TYPES_JSON, toml);
let schema = CompiledSchema::from_json(&compiled_json, false)
.expect("core must parse CLI-produced schema");
let runtime = RuntimeConfig::from_compiled_schema(&schema)
.expect("RuntimeConfig::from_compiled_schema must accept compiler output");
assert!(
runtime.audit_mutations,
"audit_logging_enabled=true must survive emit→parse→runtime (it was consumed)"
);
}
#[test]
fn enterprise_audit_toggle_off_is_respected() {
let toml = r#"
[schema]
name = "contract_audit_off"
version = "1.0.0"
database_target = "postgresql"
[database]
url = "postgresql://localhost/test"
[security]
[security.enterprise]
rate_limiting_enabled = false
audit_logging_enabled = false
"#;
let compiled_json = compile(TYPES_JSON, toml);
let schema = CompiledSchema::from_json(&compiled_json, false).unwrap();
let runtime = RuntimeConfig::from_compiled_schema(&schema).unwrap();
assert!(!runtime.audit_mutations, "audit_logging_enabled=false must be respected");
}
#[test]
fn every_emitted_field_survives_parse_roundtrip() {
let toml = r#"
[schema]
name = "contract_roundtrip"
version = "1.0.0"
database_target = "postgresql"
[database]
url = "postgresql://localhost/test"
[queries.getOrder]
return_type = "Order"
return_array = false
sql_source = "v_order"
[[queries.getOrder.args]]
name = "orderId"
type = "ID"
required = true
[security]
# Note: [[security.rules]] / [[security.policies]] / [security] default_policy are
# intentionally absent — declared-but-unenforced authorization is rejected
# (#612 item 4 / #626 / #983). The emit↔parse contract this test guards is exercised
# by the remaining security fields (enterprise).
[security.enterprise]
rate_limiting_enabled = true
audit_logging_enabled = true
"#;
let compiled_json = compile(TYPES_JSON, toml);
let emitted: serde_json::Value = serde_json::from_str(&compiled_json).unwrap();
let schema = CompiledSchema::from_json(&compiled_json, false).unwrap();
let reparsed = serde_json::to_value(&schema).unwrap();
let mut emitted_paths = BTreeSet::new();
collect_nonnull_paths(&emitted, "", &mut emitted_paths);
let mut reparsed_paths = BTreeSet::new();
collect_nonnull_paths(&reparsed, "", &mut reparsed_paths);
let dropped: Vec<&String> = emitted_paths
.iter()
.filter(|p| !p.starts_with("/_content_hash"))
.filter(|p| !reparsed_paths.contains(*p))
.collect();
assert!(
dropped.is_empty(),
"core parse silently dropped {} compiler-emitted field(s); the emit↔parse \
contract has drifted (a field added to the compiler is not consumed by \
CompiledSchema). Dropped paths:\n {}",
dropped.len(),
dropped.iter().map(|p| p.as_str()).collect::<Vec<_>>().join("\n ")
);
}
#[test]
fn persisted_queries_only_survives_emit_parse() {
let toml = r#"
[schema]
name = "contract_pqo"
version = "1.0.0"
database_target = "postgresql"
[database]
url = "postgresql://localhost/test"
[security]
persisted_queries_only = true
"#;
let compiled_json = compile(TYPES_JSON, toml);
let schema = CompiledSchema::from_json(&compiled_json, false)
.expect("core must parse CLI-produced schema");
let security = schema.security.expect("security must be present");
assert!(
security.persisted_queries_only,
"persisted_queries_only=true must survive emit→parse into the typed field"
);
}
#[test]
fn persisted_queries_only_defaults_false() {
let toml = r#"
[schema]
name = "contract_pqo_off"
version = "1.0.0"
database_target = "postgresql"
[database]
url = "postgresql://localhost/test"
[security]
"#;
let compiled_json = compile(TYPES_JSON, toml);
let schema = CompiledSchema::from_json(&compiled_json, false).unwrap();
let security = schema.security.expect("security must be present");
assert!(
!security.persisted_queries_only,
"omitting the flag must compile to false, not strict-by-default"
);
}
#[test]
fn cost_budget_survives_emit_parse_into_typed_field() {
let toml = r#"
[schema]
name = "contract_cost_budget"
version = "1.0.0"
database_target = "postgresql"
[database]
url = "postgresql://localhost/test"
[security]
[security.cost_budget]
per_request_max = 50
per_tenant_per_minute_default = 1000
"#;
let compiled_json = compile(TYPES_JSON, toml);
let schema = CompiledSchema::from_json(&compiled_json, false)
.expect("core must parse CLI-produced schema");
let security = schema.security.expect("security must be present");
let budget = security.cost_budget.expect("cost_budget must land in the typed field");
assert_eq!(budget.per_request_max, Some(50));
assert_eq!(budget.per_tenant_per_minute_default, Some(1000));
}
#[test]
fn cost_budget_defaults_to_absent() {
let toml = r#"
[schema]
name = "contract_cost_budget_off"
version = "1.0.0"
database_target = "postgresql"
[database]
url = "postgresql://localhost/test"
[security]
"#;
let compiled_json = compile(TYPES_JSON, toml);
let schema = CompiledSchema::from_json(&compiled_json, false).unwrap();
let security = schema.security.expect("security must be present");
assert!(
security.cost_budget.is_none(),
"omitting [security.cost_budget] must mean no budget, got {:?}",
security.cost_budget
);
}
fn collect_nonnull_paths(value: &serde_json::Value, prefix: &str, out: &mut BTreeSet<String>) {
match value {
serde_json::Value::Object(map) => {
for (k, v) in map {
let path = format!("{prefix}/{k}");
if !v.is_null() {
out.insert(path.clone());
}
collect_nonnull_paths(v, &path, out);
}
},
serde_json::Value::Array(items) => {
for (i, v) in items.iter().enumerate() {
let path = format!("{prefix}/{i}");
if !v.is_null() {
out.insert(path.clone());
}
collect_nonnull_paths(v, &path, out);
}
},
_ => {},
}
}
const CACHING_TYPES_JSON: &str = r#"
{
"types": [
{
"name": "Order",
"sql_source": "v_order",
"fields": [
{"name": "id", "type": "ID", "nullable": false}
]
},
{
"name": "Inventory",
"sql_source": "v_inventory",
"fields": [
{"name": "id", "type": "ID", "nullable": false}
]
}
],
"queries": [
{
"name": "orders",
"return_type": "Order",
"returns_list": true,
"nullable": false,
"sql_source": "v_order"
},
{
"name": "inventory",
"return_type": "Inventory",
"returns_list": true,
"nullable": false,
"sql_source": "v_inventory"
}
],
"mutations": [
{
"name": "createOrder",
"return_type": "Order",
"sql_source": "fn_create_order"
}
]
}
"#;
const CACHING_TOML_HEAD: &str = r#"
[schema]
name = "contract_caching"
version = "1.0.0"
database_target = "postgresql"
[database]
url = "postgresql://localhost/test"
"#;
#[test]
fn caching_rule_lowers_ttl_and_invalidation_triggers() {
let toml = format!(
r#"{CACHING_TOML_HEAD}
[caching]
enabled = true
[[caching.rules]]
query = "inventory"
ttl_seconds = 120
invalidation_triggers = ["createOrder"]
"#
);
let compiled_json = compile(CACHING_TYPES_JSON, &toml);
let schema = CompiledSchema::from_json(&compiled_json, false)
.expect("core must parse CLI-produced schema");
let query = schema
.queries
.iter()
.find(|q| q.name == "inventory")
.expect("inventory query present");
assert_eq!(query.cache_ttl_seconds, Some(120), "rule TTL must land on the query");
let mutation = schema
.mutations
.iter()
.find(|m| m.name == "createOrder")
.expect("createOrder mutation present");
assert!(
mutation.invalidates_views.iter().any(|v| v == "v_inventory"),
"the trigger mutation must gain the rule query's view in invalidates_views, got {:?}",
mutation.invalidates_views
);
}
#[test]
fn caching_rule_with_unknown_query_fails_compile() {
let toml = format!(
r#"{CACHING_TOML_HEAD}
[caching]
enabled = true
[[caching.rules]]
query = "no_such_query"
ttl_seconds = 60
invalidation_triggers = []
"#
);
let err = compile_err(CACHING_TYPES_JSON, &toml);
assert!(err.contains("no_such_query"), "the error must name the unknown query: {err}");
}
#[test]
fn caching_rule_with_unknown_trigger_fails_compile() {
let toml = format!(
r#"{CACHING_TOML_HEAD}
[caching]
enabled = true
[[caching.rules]]
query = "inventory"
ttl_seconds = 60
invalidation_triggers = ["no_such_mutation"]
"#
);
let err = compile_err(CACHING_TYPES_JSON, &toml);
assert!(
err.contains("no_such_mutation"),
"the error must name the unknown trigger mutation: {err}"
);
}
#[test]
fn caching_rule_conflicting_with_sdk_ttl_fails_compile() {
let toml = format!(
r#"{CACHING_TOML_HEAD}
[caching]
enabled = true
[[caching.rules]]
query = "orders"
ttl_seconds = 60
invalidation_triggers = []
"#
);
let err = compile_err(TYPES_JSON, &toml);
assert!(
err.contains("orders") && err.contains("cache_ttl_seconds"),
"the error must name the doubly-declared query and field: {err}"
);
}
#[test]
fn caching_dishonest_configurations_fail_compile() {
let disabled_with_rules = format!(
r#"{CACHING_TOML_HEAD}
[caching]
enabled = false
[[caching.rules]]
query = "inventory"
ttl_seconds = 60
invalidation_triggers = []
"#
);
let err = compile_err(CACHING_TYPES_JSON, &disabled_with_rules);
assert!(err.contains("enabled"), "disabled-with-rules must be refused: {err}");
let enabled_without_rules = format!(
r"{CACHING_TOML_HEAD}
[caching]
enabled = true
"
);
let err = compile_err(CACHING_TYPES_JSON, &enabled_without_rules);
assert!(
err.contains("rules"),
"enabled-without-rules does nothing and must be refused: {err}"
);
let redis_backend = format!(
r#"{CACHING_TOML_HEAD}
[caching]
enabled = true
backend = "redis"
[[caching.rules]]
query = "inventory"
ttl_seconds = 60
invalidation_triggers = []
"#
);
let err = compile_err(CACHING_TYPES_JSON, &redis_backend);
assert!(
err.contains("redis"),
"a backend with no runtime counterpart must be refused: {err}"
);
}
fn compile_err(types_json: &str, toml_config: &str) -> String {
let temp_dir = TempDir::new().unwrap();
let types_path = temp_dir.path().join("types.json");
let toml_path = temp_dir.path().join("fraiseql.toml");
let output_path = temp_dir.path().join("schema.compiled.json");
fs::write(&types_path, types_json).unwrap();
fs::write(&toml_path, toml_config).unwrap();
let cli_path = env!("CARGO_BIN_EXE_fraiseql-cli");
let output = Command::new(cli_path)
.args([
"compile",
toml_path.to_str().unwrap(),
"--types",
types_path.to_str().unwrap(),
"--output",
output_path.to_str().unwrap(),
])
.output()
.expect("failed to run fraiseql-cli");
assert!(
!output.status.success(),
"compile must fail for this configuration; stdout: {} stderr: {}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
format!(
"{}{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
)
}
#[test]
fn analytics_query_lowers_to_a_served_query() {
let toml = format!(
r#"{CACHING_TOML_HEAD}
[analytics]
enabled = true
[[analytics.queries]]
name = "daily_orders"
return_type = "Order"
sql_source = "v_daily_orders"
description = "orders rolled up by day"
"#
);
let compiled_json = compile(CACHING_TYPES_JSON, &toml);
let schema = CompiledSchema::from_json(&compiled_json, false)
.expect("core must parse CLI-produced schema");
let query = schema
.queries
.iter()
.find(|q| q.name == "daily_orders")
.expect("analytics query must be compiled as a query");
assert_eq!(query.sql_source.as_deref(), Some("v_daily_orders"));
assert_eq!(query.return_type, "Order");
assert!(query.returns_list, "analytics queries return row sets");
}
#[test]
fn analytics_query_with_unknown_return_type_fails_compile() {
let toml = format!(
r#"{CACHING_TOML_HEAD}
[analytics]
enabled = true
[[analytics.queries]]
name = "daily_orders"
return_type = "NoSuchType"
sql_source = "v_daily_orders"
"#
);
let err = compile_err(CACHING_TYPES_JSON, &toml);
assert!(err.contains("NoSuchType"), "must name the unknown type: {err}");
}
#[test]
fn analytics_query_reserved_or_colliding_names_fail_compile() {
let colliding = format!(
r#"{CACHING_TOML_HEAD}
[analytics]
enabled = true
[[analytics.queries]]
name = "orders"
return_type = "Order"
sql_source = "v_daily_orders"
"#
);
let err = compile_err(CACHING_TYPES_JSON, &colliding);
assert!(err.contains("orders"), "must name the colliding query: {err}");
let reserved = format!(
r#"{CACHING_TOML_HEAD}
[analytics]
enabled = true
[[analytics.queries]]
name = "sales_aggregate"
return_type = "Order"
sql_source = "v_sales"
"#
);
let err = compile_err(CACHING_TYPES_JSON, &reserved);
assert!(err.contains("_aggregate"), "must explain the reserved suffix: {err}");
}
#[test]
fn analytics_query_with_injection_shaped_sql_source_fails_compile() {
let toml = format!(
r#"{CACHING_TOML_HEAD}
[analytics]
enabled = true
[[analytics.queries]]
name = "daily_orders"
return_type = "Order"
sql_source = "v_daily; DROP TABLE tb_user --"
"#
);
let err = compile_err(CACHING_TYPES_JSON, &toml);
assert!(
err.to_lowercase().contains("identifier") || err.contains("sql_source"),
"must be refused as an invalid identifier: {err}"
);
}
#[test]
fn analytics_dishonest_configurations_fail_compile() {
let disabled_with_queries = format!(
r#"{CACHING_TOML_HEAD}
[analytics]
enabled = false
[[analytics.queries]]
name = "daily_orders"
return_type = "Order"
sql_source = "v_daily_orders"
"#
);
let err = compile_err(CACHING_TYPES_JSON, &disabled_with_queries);
assert!(err.contains("enabled"), "disabled-with-queries must be refused: {err}");
let enabled_without_queries = format!(
r"{CACHING_TOML_HEAD}
[analytics]
enabled = true
"
);
let err = compile_err(CACHING_TYPES_JSON, &enabled_without_queries);
assert!(
err.contains("queries"),
"enabled-without-queries does nothing and must be refused: {err}"
);
}
#[test]
fn the_compiler_stamps_its_own_build_and_the_seam_requires_it() {
let toml = r#"
[schema]
name = "contract_producer_version"
version = "1.0.0"
database_target = "postgresql"
[database]
url = "postgresql://localhost/test"
"#;
let compiled_json = compile(TYPES_JSON, toml);
let emitted: serde_json::Value = serde_json::from_str(&compiled_json).unwrap();
assert_eq!(
emitted.get("fraiseql_version").and_then(serde_json::Value::as_str),
Some(env!("CARGO_PKG_VERSION")),
"the compiler must stamp the build it is part of into the artifact it writes"
);
let schema = CompiledSchema::from_json(&compiled_json, false).unwrap();
RuntimeConfig::from_compiled_schema(&schema)
.expect("this build must accept the artifact this build compiled");
let mut stripped = emitted;
stripped.as_object_mut().unwrap().remove("fraiseql_version");
let stripped = CompiledSchema::from_json(&stripped.to_string(), false)
.expect("it must still parse, so the operator meets the build refusal");
let err = RuntimeConfig::from_compiled_schema(&stripped)
.expect_err("an artifact naming no build must be refused");
assert!(err.contains("Recompile"), "{err}");
}