Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/openshell-cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ openshell-policy = { path = "../openshell-policy" }
openshell-providers = { path = "../openshell-providers" }
openshell-sdk = { path = "../openshell-sdk" }
openshell-tui = { path = "../openshell-tui" }
openshell-supervisor-middleware-builtins = { path = "../openshell-supervisor-middleware-builtins" }
serde = { workspace = true }
serde_json = { workspace = true }
serde_yml = { workspace = true }
Expand Down
11 changes: 11 additions & 0 deletions crates/openshell-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2155,6 +2155,13 @@ enum DraftCommands {

#[derive(Subcommand, Debug)]
enum PolicyCommands {
/// Validate an authored policy file offline, without a gateway.
#[command(help_template = LEAF_HELP_TEMPLATE)]
Lint {
/// Path to the authored policy YAML file.
#[arg(value_hint = ValueHint::FilePath)]
policy: String,
},
/// Update policy on a live sandbox.
#[command(help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")]
Set {
Expand Down Expand Up @@ -3062,13 +3069,17 @@ async fn run_async() -> Result<()> {
// -----------------------------------------------------------
// Top-level policy (was `sandbox policy`)
// -----------------------------------------------------------
Some(Commands::Policy {
command: Some(PolicyCommands::Lint { policy }),
}) => run::sandbox_policy_lint(&policy)?,
Some(Commands::Policy {
command: Some(policy_cmd),
}) => {
let ctx = resolve_gateway(&cli.gateway, &cli.gateway_endpoint)?;
let mut tls = tls.with_gateway_name(&ctx.name);
apply_auth(&mut tls, &ctx.name)?;
match policy_cmd {
PolicyCommands::Lint { .. } => unreachable!("offline lint is dispatched above"),
PolicyCommands::Set {
name,
policy,
Expand Down
29 changes: 29 additions & 0 deletions crates/openshell-cli/src/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5408,6 +5408,35 @@ pub async fn sandbox_upload(
// Sandbox policy commands
// ---------------------------------------------------------------------------

pub fn sandbox_policy_lint(policy_path: &str) -> Result<()> {
let policy = openshell_policy::parse_sandbox_policy_file(Path::new(policy_path))?;
let mut violations: Vec<String> = openshell_policy::find_endpoint_ambiguities(&policy)
.iter()
.map(ToString::to_string)
.collect();
let mut middlewares: Vec<_> = policy.network_middlewares.iter().collect();
middlewares.sort_by_key(|(name, _)| *name);
for (name, middleware) in middlewares {
if middleware.middleware.starts_with("openshell/")
&& let Err(error) = openshell_supervisor_middleware_builtins::validate_config(
&middleware.middleware,
&middleware.config.clone().unwrap_or_default(),
)
{
violations.push(format!("middleware config '{name}' is invalid: {error}"));
}
}
if let Err(error) = openshell_policy::validate_and_canonicalize_authored_policy(policy) {
violations.extend(error);
}
if !violations.is_empty() {
miette::bail!("policy is invalid:\n- {}", violations.join("\n- "));
}
println!("Policy is valid (offline): {policy_path}");
println!("Gateway checks for providers, external middleware, images and drivers are not run.");
Ok(())
}

pub async fn sandbox_policy_set_global(
server: &str,
policy_path: &str,
Expand Down
100 changes: 100 additions & 0 deletions crates/openshell-cli/tests/policy_lint_integration.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

mod common;

#[test]
fn policy_lint_runs_offline_and_reports_file_errors() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("policy.yaml");
let path = file.to_str().unwrap();
let cases = [
(
"version: 1\n",
true,
vec!["Policy is valid (offline)", "Gateway checks"],
),
("process: {}\n", false, vec!["version"]),
("version: 1\nunknown: true\n", false, vec!["unknown"]),
(
"version: 1\nprocess:\n run_as_user: '0'\n run_as_group: root\nfilesystem_policy:\n read_write: [relative, /]\n",
false,
vec![
"run_as_user",
"run_as_group",
"path must be absolute",
"overly broad",
],
),
(
"version: 1\nnetwork_policies:\n _provider_private:\n endpoints: []\n",
false,
vec!["reserved '_provider_'", "--base"],
),
(
"version: 1\nnetwork_policies:\n bound:\n endpoints:\n - host: example.com\n port: 443\n credential_binding: {provider: ' '}\n",
false,
vec!["credential_binding.provider"],
),
(
"version: 1\nprocess:\n run_as_user: '0'\nnetwork_middlewares:\n redact:\n middleware: openshell/regex\n order: 1\n endpoints: {include: [example.com]}\n config: {mode: allow}\n",
false,
vec!["mode: redact", "run_as_user"],
),
(
"version: 1\nnetwork_policies:\n conflict:\n endpoints:\n - {host: example.com, port: 443}\n - {host: example.com, port: 443, tls: skip}\n",
false,
vec!["overlap", "conflicting"],
),
];
for (yaml, valid, messages) in cases {
std::fs::write(&file, yaml).unwrap();
for args in [
vec!["policy", "lint", path],
vec![
"--gateway-endpoint",
"http://127.0.0.1:1",
"policy",
"lint",
path,
],
] {
let output = common::run_isolated(&args);
assert_eq!(output.code == 0, valid, "{yaml}\n{}", output.combined);
assert!(
!output.combined.contains("failed to connect"),
"{}",
output.combined
);
for message in &messages {
assert!(
output.combined.contains(message),
"expected {message}: {}",
output.combined
);
}
}
}
std::fs::write(
&file,
format!(
"version: 1\nnetwork_policies:\n large:\n name: {}\n",
"x".repeat(openshell_policy::MAX_AUTHORED_POLICY_SIZE)
),
)
.unwrap();
let oversized = common::run_isolated(&["policy", "lint", path]);
assert_ne!(oversized.code, 0);
assert!(
oversized
.combined
.contains("policy serialized size exceeds maximum"),
"{}",
oversized.combined
);
let missing = dir.path().join("missing.yaml");
assert_ne!(
common::run_isolated(&["policy", "lint", missing.to_str().unwrap()]).code,
0
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -138,3 +138,48 @@ async fn policy_only_preserves_all_process_identity_combinations_through_gateway
}
}
}

#[tokio::test]
async fn authored_policy_lint_matches_gateway_file_validation() {
let server = run_server().await;
let cases = [
(
"identity",
"process:\n run_as_user: '0'\nfilesystem_policy:\n read_write: [relative]\n",
),
("reserved", "network_policies:\n _provider_private: {}\n"),
(
"binding",
"network_policies:\n bound:\n endpoints:\n - host: example.com\n port: 443\n credential_binding: {provider: ' '}\n",
),
];
for (name, body) in cases {
let policy =
openshell_policy::parse_sandbox_policy(&format!("version: 1\n{body}")).unwrap();
let violations =
openshell_policy::validate_and_canonicalize_authored_policy(policy.clone())
.unwrap_err();
let mut client = grpc_client(&server.endpoint, &server.tls).await.unwrap();
let error = client
.create_sandbox(CreateSandboxRequest {
name: name.to_string(),
spec: Some(SandboxSpec {
policy: Some(policy),
..Default::default()
}),
workspace_scope: Some(openshell_core::proto::workspace_selector(
"default".to_string(),
)),
..Default::default()
})
.await
.expect_err("invalid authored file must be rejected by the gateway too");
assert_eq!(error.code(), tonic::Code::InvalidArgument);
for violation in violations {
assert!(
error.message().contains(&violation),
"{name}: {error} did not report {violation}"
);
}
}
}
1 change: 1 addition & 0 deletions crates/openshell-policy/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ serde = { workspace = true }
serde_json = { workspace = true }
miette = { workspace = true }
prost-types = { workspace = true }
prost = { workspace = true }

[lints]
workspace = true
Loading
Loading