Skip to content

Commit 8751e35

Browse files
authored
fix(supervisor-network): reject malformed OPA policy containers (#3337)
Validate raw OPA object and array containers before normalization and access-preset expansion can skip malformed values. Return one fixed structural error without embedding authored policy data. Preserve versionless and runtime-only OPA data and existing semantic validation. Cover initial string/file loading, middleware callback order, valid deny-rule enforcement, and rejected reload state and generation. Document the loader contract and its engine-local rejection behavior. Signed-off-by: Shiju <shiju@nvidia.com>
1 parent dbe36ea commit 8751e35

3 files changed

Lines changed: 354 additions & 1 deletion

File tree

‎architecture/security-policy.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,8 @@ supervisor polls for config revisions and attempts to load new dynamic policy
189189
into the in-process OPA engine; CLI reads of the latest sandbox policy use the
190190
same effective configuration path.
191191

192+
The OPA loader checks the object and list shapes of raw policy data before injecting runtime fields, normalizing values, or expanding access presets. It rejects the first malformed container with a fixed structural error that excludes authored keys and values. This check preserves valid versionless OPA data and runtime-only fields. A rejected OPA engine reload leaves that engine's installed policy, generation, and decisions unchanged; the supervisor separately applies its configured runtime rejection mode.
193+
192194
The supervisor validates complete effective policy generations before
193195
activation. Overlapping endpoint selectors may contribute request allow and
194196
deny rules only when their connection and request-processing metadata agree;

‎crates/openshell-supervisor-network/src/opa.rs‎

Lines changed: 349 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1381,14 +1381,87 @@ fn emit_l7_config_warnings(warnings: &[String], prefix: &str) {
13811381
}
13821382
}
13831383

1384-
/// Preprocess YAML policy data: parse, normalize, validate, expand access presets, return JSON.
1384+
/// Validate containers before normalizers or Rego can skip malformed policy data.
1385+
///
1386+
/// OPA-native data can contain runtime fields and omit authored-policy sections.
1387+
/// Validate only the shapes consumed here; existing validators own field semantics.
1388+
/// Return the first fixed structural diagnostic so errors cannot grow with the
1389+
/// input or expose authored names, paths, or values.
1390+
fn validate_opa_data_structure(data: &serde_json::Value) -> Result<()> {
1391+
let root = data
1392+
.as_object()
1393+
.ok_or_else(|| miette::miette!("OPA policy data must be an object"))?;
1394+
1395+
for field in ["filesystem_policy", "landlock", "process"] {
1396+
if root.get(field).is_some_and(|value| !value.is_object()) {
1397+
return Err(miette::miette!("{field} must be an object"));
1398+
}
1399+
}
1400+
1401+
if let Some(middlewares) = root.get("network_middlewares") {
1402+
let middlewares = middlewares
1403+
.as_object()
1404+
.ok_or_else(|| miette::miette!("network_middlewares must be an object"))?;
1405+
if middlewares.values().any(|value| !value.is_object()) {
1406+
return Err(miette::miette!(
1407+
"network middleware entries must be objects"
1408+
));
1409+
}
1410+
}
1411+
1412+
// Omitted collections retain their existing defaults. Present malformed
1413+
// collections must not be mistaken for an omitted configuration.
1414+
let Some(policies) = root.get("network_policies") else {
1415+
return Ok(());
1416+
};
1417+
let policies = policies
1418+
.as_object()
1419+
.ok_or_else(|| miette::miette!("network_policies must be an object"))?;
1420+
for policy in policies.values() {
1421+
let policy = policy
1422+
.as_object()
1423+
.ok_or_else(|| miette::miette!("network policy entries must be objects"))?;
1424+
let endpoints =
1425+
validate_opa_object_array(policy.get("endpoints"), "network policy endpoints")?;
1426+
for endpoint in endpoints {
1427+
validate_opa_object_array(endpoint.get("rules"), "network endpoint rules")?;
1428+
validate_opa_object_array(endpoint.get("deny_rules"), "network endpoint deny_rules")?;
1429+
}
1430+
validate_opa_object_array(policy.get("binaries"), "network policy binaries")?;
1431+
}
1432+
1433+
Ok(())
1434+
}
1435+
1436+
/// Return an optional collection only after validating its traversal contract.
1437+
///
1438+
/// Callers supply fixed schema labels, never identifiers from policy data, so
1439+
/// both error variants remain bounded and contain no author-controlled values.
1440+
fn validate_opa_object_array<'a>(
1441+
value: Option<&'a serde_json::Value>,
1442+
field: &'static str,
1443+
) -> Result<&'a [serde_json::Value]> {
1444+
let Some(value) = value else {
1445+
return Ok(&[]);
1446+
};
1447+
let entries = value
1448+
.as_array()
1449+
.ok_or_else(|| miette::miette!("{field} must be an array"))?;
1450+
if entries.iter().any(|entry| !entry.is_object()) {
1451+
return Err(miette::miette!("{field} entries must be objects"));
1452+
}
1453+
Ok(entries)
1454+
}
1455+
1456+
/// Preprocess YAML policy data: parse, validate shapes, normalize, expand presets, return JSON.
13851457
fn preprocess_yaml_data(
13861458
yaml_str: &str,
13871459
require_binary_identity: bool,
13881460
validate_middleware_config: Option<&MiddlewareConfigValidator>,
13891461
) -> Result<String> {
13901462
let mut data: serde_json::Value = serde_yml::from_str(yaml_str)
13911463
.map_err(|e| miette::miette!("failed to parse YAML data: {e}"))?;
1464+
validate_opa_data_structure(&data)?;
13921465
inject_runtime_policy_data(&mut data, require_binary_identity);
13931466
normalize_endpoint_protocols(&mut data);
13941467

@@ -2324,6 +2397,281 @@ mod tests {
23242397
OpaEngine::from_strings(TEST_POLICY, TEST_DATA_YAML).expect("Failed to load test policy")
23252398
}
23262399

2400+
fn opa_container_policy() -> serde_json::Value {
2401+
serde_json::json!({
2402+
"filesystem_policy": {},
2403+
"landlock": {},
2404+
"process": {},
2405+
"network_middlewares": {},
2406+
"network_policies": {
2407+
"admin": {
2408+
"endpoints": [{
2409+
"host": "admin.example.test",
2410+
"port": 443,
2411+
"protocol": "rest",
2412+
"enforcement": "enforce",
2413+
"access": "full",
2414+
"deny_rules": [{"method": "DELETE", "path": "/admin/**"}],
2415+
}],
2416+
"binaries": [{"path": "/usr/bin/curl"}],
2417+
},
2418+
},
2419+
})
2420+
}
2421+
2422+
#[test]
2423+
fn yaml_containers_reject_malformed_objects_and_collections() {
2424+
let valid = opa_container_policy();
2425+
OpaEngine::from_strings(TEST_POLICY, &valid.to_string())
2426+
.expect("control policy must load before changing one container");
2427+
let invalid_objects = [
2428+
serde_json::Value::Null,
2429+
serde_json::json!([]),
2430+
serde_json::json!("untrusted-marker"),
2431+
serde_json::json!(42),
2432+
serde_json::json!(false),
2433+
];
2434+
for invalid in &invalid_objects {
2435+
let error = OpaEngine::from_strings(TEST_POLICY, &invalid.to_string())
2436+
.err()
2437+
.expect("non-object root must reject");
2438+
assert_eq!(error.to_string(), "OPA policy data must be an object");
2439+
}
2440+
2441+
let object_cases = [
2442+
("/filesystem_policy", "filesystem_policy must be an object"),
2443+
("/landlock", "landlock must be an object"),
2444+
("/process", "process must be an object"),
2445+
("/network_policies", "network_policies must be an object"),
2446+
(
2447+
"/network_policies/admin",
2448+
"network policy entries must be objects",
2449+
),
2450+
(
2451+
"/network_middlewares",
2452+
"network_middlewares must be an object",
2453+
),
2454+
(
2455+
"/network_middlewares/untrusted-marker",
2456+
"network middleware entries must be objects",
2457+
),
2458+
];
2459+
for (pointer, expected) in object_cases {
2460+
for invalid in &invalid_objects {
2461+
let mut candidate = valid.clone();
2462+
let (parent, field) = pointer.rsplit_once('/').expect("field pointer");
2463+
candidate
2464+
.pointer_mut(parent)
2465+
.and_then(serde_json::Value::as_object_mut)
2466+
.expect("container parent must be an object")
2467+
.insert(field.to_string(), invalid.clone());
2468+
let error = OpaEngine::from_strings(TEST_POLICY, &candidate.to_string())
2469+
.err()
2470+
.expect("malformed object must reject");
2471+
assert_eq!(error.to_string(), expected, "{pointer}: {invalid}");
2472+
}
2473+
}
2474+
2475+
let collection_cases = [
2476+
(
2477+
"/network_policies/admin/endpoints",
2478+
"network policy endpoints",
2479+
),
2480+
(
2481+
"/network_policies/admin/binaries",
2482+
"network policy binaries",
2483+
),
2484+
(
2485+
"/network_policies/admin/endpoints/0/rules",
2486+
"network endpoint rules",
2487+
),
2488+
(
2489+
"/network_policies/admin/endpoints/0/deny_rules",
2490+
"network endpoint deny_rules",
2491+
),
2492+
];
2493+
for (pointer, field_label) in collection_cases {
2494+
for invalid in [
2495+
serde_json::Value::Null,
2496+
serde_json::json!({"untrusted-marker": "value"}),
2497+
serde_json::json!("untrusted-marker"),
2498+
serde_json::json!(42),
2499+
serde_json::json!(false),
2500+
serde_json::json!([null]),
2501+
serde_json::json!(["untrusted-marker"]),
2502+
serde_json::json!([{}, false]),
2503+
] {
2504+
let mut candidate = valid.clone();
2505+
let (parent, field) = pointer.rsplit_once('/').expect("field pointer");
2506+
candidate
2507+
.pointer_mut(parent)
2508+
.and_then(serde_json::Value::as_object_mut)
2509+
.expect("collection parent must be an object")
2510+
.insert(field.to_string(), invalid.clone());
2511+
let error = OpaEngine::from_strings(TEST_POLICY, &candidate.to_string())
2512+
.err()
2513+
.expect("malformed collection must reject");
2514+
let expected = if invalid.is_array() {
2515+
format!("{field_label} entries must be objects")
2516+
} else {
2517+
format!("{field_label} must be an array")
2518+
};
2519+
assert_eq!(error.to_string(), expected, "{pointer}: {invalid}");
2520+
assert!(error.to_string().len() <= 128);
2521+
assert!(!error.to_string().contains("untrusted-marker"));
2522+
}
2523+
}
2524+
}
2525+
2526+
#[test]
2527+
fn yaml_containers_preserve_valid_denials_and_rejected_reload_generation() {
2528+
let valid = opa_container_policy();
2529+
let engine = OpaEngine::from_strings(TEST_POLICY, &valid.to_string())
2530+
.expect("valid deny-rule list must load");
2531+
let allowed = l7_input("admin.example.test", 443, "GET", "/public");
2532+
let denied = l7_input("admin.example.test", 443, "DELETE", "/admin/users");
2533+
assert!(eval_l7(&engine, &allowed));
2534+
assert!(!eval_l7(&engine, &denied));
2535+
let generation = engine.current_generation();
2536+
2537+
let mut malformed = valid.clone();
2538+
malformed["network_policies"]["admin"]["endpoints"][0]["deny_rules"] =
2539+
serde_json::json!({"method": "DELETE", "path": "/admin/**"});
2540+
let error = engine
2541+
.reload(TEST_POLICY, &malformed.to_string())
2542+
.expect_err("mapping-shaped deny_rules must reject before access expansion");
2543+
assert_eq!(
2544+
error.to_string(),
2545+
"network endpoint deny_rules must be an array"
2546+
);
2547+
assert_eq!(engine.current_generation(), generation);
2548+
assert!(eval_l7(&engine, &allowed));
2549+
assert!(!eval_l7(&engine, &denied));
2550+
2551+
// A later valid replacement must still install and notify consumers.
2552+
let mut repaired = valid;
2553+
repaired["network_policies"]["admin"]["endpoints"][0]["deny_rules"][0]["path"] =
2554+
"/other/**".into();
2555+
engine
2556+
.reload(TEST_POLICY, &repaired.to_string())
2557+
.expect("valid replacement must install after a rejected reload");
2558+
assert_eq!(engine.current_generation(), generation + 1);
2559+
assert!(eval_l7(&engine, &denied));
2560+
}
2561+
2562+
#[test]
2563+
fn yaml_containers_file_and_middleware_loaders_reject_before_config_validation() {
2564+
let directory = tempfile::tempdir().expect("temporary policy directory");
2565+
let rules_path = directory.path().join("policy.rego");
2566+
let data_path = directory.path().join("policy.yaml");
2567+
std::fs::write(&rules_path, TEST_POLICY).expect("write policy rules");
2568+
let mut valid = opa_container_policy();
2569+
valid["network_middlewares"]["guard"] = serde_json::json!({
2570+
"middleware": "openshell/regex",
2571+
"order": 1,
2572+
"endpoints": {"include": ["admin.example.test"]},
2573+
"config": {},
2574+
});
2575+
let config_calls = Arc::new(AtomicU64::new(0));
2576+
let observed_calls = Arc::clone(&config_calls);
2577+
let count_config: &MiddlewareConfigValidator = &move |_, _| {
2578+
observed_calls.fetch_add(1, Ordering::Relaxed);
2579+
Ok(())
2580+
};
2581+
OpaEngine::from_strings_with_middleware_config(
2582+
TEST_POLICY,
2583+
&valid.to_string(),
2584+
Some(count_config),
2585+
)
2586+
.expect("valid control must reach middleware configuration validation");
2587+
assert_eq!(config_calls.load(Ordering::Relaxed), 1);
2588+
2589+
let mut malformed = valid;
2590+
malformed["network_policies"]["admin"]["endpoints"][0]["deny_rules"] =
2591+
serde_json::json!({"method": "DELETE", "path": "/admin/**"});
2592+
std::fs::write(&data_path, malformed.to_string()).expect("write malformed policy");
2593+
let validate_config: &MiddlewareConfigValidator =
2594+
&|_, _| panic!("structural rejection must precede middleware implementation callbacks");
2595+
for result in [
2596+
OpaEngine::from_files(&rules_path, &data_path),
2597+
OpaEngine::from_files_with_middleware_config(
2598+
&rules_path,
2599+
&data_path,
2600+
Some(validate_config),
2601+
),
2602+
OpaEngine::from_strings_with_middleware_config(
2603+
TEST_POLICY,
2604+
&malformed.to_string(),
2605+
Some(validate_config),
2606+
),
2607+
] {
2608+
assert_eq!(
2609+
result.err().expect("raw loader must reject").to_string(),
2610+
"network endpoint deny_rules must be an array"
2611+
);
2612+
}
2613+
2614+
std::fs::write(&data_path, opa_container_policy().to_string())
2615+
.expect("write repaired policy");
2616+
let engine = OpaEngine::from_files(&rules_path, &data_path)
2617+
.expect("valid raw file must load after repair");
2618+
assert!(eval_l7(
2619+
&engine,
2620+
&l7_input("admin.example.test", 443, "GET", "/public")
2621+
));
2622+
assert!(!eval_l7(
2623+
&engine,
2624+
&l7_input("admin.example.test", 443, "DELETE", "/admin/users")
2625+
));
2626+
}
2627+
2628+
#[test]
2629+
fn yaml_containers_preserve_opa_only_data_and_existing_semantic_validation() {
2630+
for data in [
2631+
"{}",
2632+
"network_policies: {}",
2633+
"filesystem_policy: {}\nlandlock: {}\nprocess: {}\nnetwork_middlewares: {}",
2634+
"network_policies: { empty: { endpoints: [], binaries: [] } }",
2635+
"runtime_extension: { values: [null, true, 1, custom] }",
2636+
] {
2637+
OpaEngine::from_strings(TEST_POLICY, data)
2638+
.expect("valid versionless OPA data and omitted containers must remain supported");
2639+
}
2640+
2641+
let mut data = opa_container_policy();
2642+
data["runtime_extension"] = serde_json::json!({"values": [null, true, 1, "custom"]});
2643+
let loaded = preprocess_yaml_data(&data.to_string(), false, None)
2644+
.expect("supported runtime data must preprocess");
2645+
let loaded: serde_json::Value = serde_json::from_str(&loaded).expect("OPA JSON data");
2646+
assert_eq!(loaded["runtime_extension"], data["runtime_extension"]);
2647+
2648+
data["network_policies"]["admin"]["endpoints"][0]["deny_rules"] = serde_json::json!([]);
2649+
let error = OpaEngine::from_strings(TEST_POLICY, &data.to_string())
2650+
.err()
2651+
.expect("an empty deny-rule list remains semantically invalid");
2652+
assert!(
2653+
error
2654+
.to_string()
2655+
.contains("deny_rules list cannot be empty")
2656+
);
2657+
}
2658+
2659+
#[test]
2660+
fn yaml_containers_structural_errors_are_fixed_for_large_untrusted_input() {
2661+
let mut data = opa_container_policy();
2662+
let marker = "sensitive-\u{1f980}".repeat(1024);
2663+
data["network_policies"]["admin"]["endpoints"] =
2664+
serde_json::Value::Array(vec![serde_json::json!({"deny_rules": marker}); 1024]);
2665+
let error = OpaEngine::from_strings(TEST_POLICY, &data.to_string())
2666+
.err()
2667+
.expect("malformed denial collections must reject");
2668+
let message = error.to_string();
2669+
assert_eq!(message, "network endpoint deny_rules must be an array");
2670+
assert!(message.len() <= 128);
2671+
assert_eq!(message.lines().count(), 1);
2672+
assert!(!message.contains("sensitive"));
2673+
}
2674+
23272675
fn test_proto() -> ProtoSandboxPolicy {
23282676
let mut network_policies = std::collections::HashMap::new();
23292677
network_policies.insert(

‎docs/reference/policy-schema.mdx‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@ network_middlewares: { ... }
3232
| `network_policies` | map | No | Dynamic | Declares which binaries can reach which network endpoints. |
3333
| `network_middlewares` | map | No | Dynamic | Attaches ordered middleware by destination host; each implementation's manifest selects its supported HTTP and WebSocket operations. |
3434

35+
The YAML root and each present top-level section listed as an object or map must be mappings. Each named network policy or middleware entry must also be a mapping. The OPA loader rejects the first malformed container before normalization or access preset expansion, with a structural error that excludes authored keys and values.
36+
3537
Static fields are set at sandbox creation time. Changing them requires destroying and recreating the sandbox. Dynamic fields can be updated on a running sandbox with `openshell policy update` for incremental merges or `openshell policy set` for full replacement, and take effect without restarting.
3638

3739
## Version
@@ -193,6 +195,7 @@ Each endpoint defines a reachable destination and optional inspection rules.
193195

194196
**Validation constraints:**
195197

198+
- When present, `endpoints`, `binaries`, `rules`, and `deny_rules` must be lists of objects, even when they contain only one entry. `null` cannot replace a list or an object entry.
196199
- `access` and `rules` are mutually exclusive; setting both is rejected.
197200
- `protocol: tcp` requires a valid DNS hostname. Hostless `allowed_ips`, IP-literal hosts, trailing-dot names, and malformed DNS selectors are rejected with a policy-validation error.
198201
- `protocol: tcp` requires at least one port and rejects L7-only fields, including `path`, `enforcement`, `access`, `rules`, `deny_rules`, request rewriting and credential signing fields, and GraphQL, JSON-RPC, or MCP options.

0 commit comments

Comments
 (0)