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
1 change: 1 addition & 0 deletions Cargo.lock

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

69 changes: 66 additions & 3 deletions crates/openshell-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -663,6 +663,21 @@ impl ProviderProfileOutput {
}
}

#[derive(Clone, Debug, ValueEnum)]
enum PolicyGetOutput {
Table,
Json,
}

impl PolicyGetOutput {
fn as_str(&self) -> &'static str {
match self {
Self::Table => "table",
Self::Json => "json",
}
}
}

#[derive(Clone, Debug, ValueEnum)]
enum CliEditor {
Vscode,
Expand Down Expand Up @@ -1487,10 +1502,14 @@ enum PolicyCommands {
#[arg(long = "rev", default_value_t = 0)]
rev: u32,

/// Print the full policy as YAML.
/// Include the full policy payload.
#[arg(long)]
full: bool,

/// Output format.
#[arg(short = 'o', long = "output", value_enum, default_value_t = PolicyGetOutput::Table)]
output: PolicyGetOutput,

/// Show the global policy revision.
#[arg(long)]
global: bool,
Expand Down Expand Up @@ -2167,13 +2186,29 @@ async fn main() -> Result<()> {
name,
rev,
full,
output,
global,
} => {
if global {
run::sandbox_policy_get_global(&ctx.endpoint, rev, full, &tls).await?;
run::sandbox_policy_get_global(
&ctx.endpoint,
rev,
full,
output.as_str(),
&tls,
)
.await?;
} else {
let name = resolve_sandbox_name(name, &ctx.name)?;
run::sandbox_policy_get(&ctx.endpoint, &name, rev, full, &tls).await?;
run::sandbox_policy_get(
&ctx.endpoint,
&name,
rev,
full,
output.as_str(),
&tls,
)
.await?;
}
}
PolicyCommands::List {
Expand Down Expand Up @@ -3557,6 +3592,34 @@ mod tests {
}
}

#[test]
fn policy_get_json_output_parses() {
let cli = Cli::try_parse_from([
"openshell",
"policy",
"get",
"my-sandbox",
"--full",
"-o",
"json",
])
.expect("policy get -o json should parse");

match cli.command {
Some(Commands::Policy {
command:
Some(PolicyCommands::Get {
name, full, output, ..
}),
}) => {
assert_eq!(name.as_deref(), Some("my-sandbox"));
assert!(full);
assert!(matches!(output, PolicyGetOutput::Json));
}
other => panic!("expected policy get command, got: {other:?}"),
}
}

#[test]
fn policy_delete_global_parses() {
let cli = Cli::try_parse_from(["openshell", "policy", "delete", "--global", "--yes"])
Expand Down
143 changes: 132 additions & 11 deletions crates/openshell-cli/src/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5653,7 +5653,34 @@ pub async fn sandbox_policy_get(
name: &str,
version: u32,
full: bool,
output: &str,
tls: &TlsOptions,
) -> Result<()> {
let mut stdout = std::io::stdout().lock();
let mut stderr = std::io::stderr().lock();
sandbox_policy_get_to_writer(
server,
name,
version,
full,
output,
tls,
&mut stdout,
&mut stderr,
)
.await
}

#[doc(hidden)]
pub async fn sandbox_policy_get_to_writer<W: Write, E: Write>(
server: &str,
name: &str,
version: u32,
full: bool,
output: &str,
tls: &TlsOptions,
stdout: &mut W,
stderr: &mut E,
) -> Result<()> {
let mut client = grpc_client(server, tls).await?;

Expand All @@ -5669,32 +5696,55 @@ pub async fn sandbox_policy_get(
let inner = status_resp.into_inner();
if let Some(rev) = inner.revision {
let status = PolicyStatus::try_from(rev.status).unwrap_or(PolicyStatus::Unspecified);
println!("Version: {}", rev.version);
println!("Hash: {}", rev.policy_hash);
println!("Status: {status:?}");
println!("Active: {}", inner.active_version);
match output {
"json" => {
let obj = policy_revision_to_json(
"sandbox",
Some(name),
Some(inner.active_version),
&rev,
status,
full,
)?;
writeln!(
stdout,
"{}",
serde_json::to_string_pretty(&obj).into_diagnostic()?
)
.into_diagnostic()?;
return Ok(());
}
"table" => {}
_ => return Err(miette!("unsupported output format: {output}")),
}

writeln!(stdout, "Version: {}", rev.version).into_diagnostic()?;
writeln!(stdout, "Hash: {}", rev.policy_hash).into_diagnostic()?;
writeln!(stdout, "Status: {status:?}").into_diagnostic()?;
writeln!(stdout, "Active: {}", inner.active_version).into_diagnostic()?;
if rev.created_at_ms > 0 {
println!("Created: {} ms", rev.created_at_ms);
writeln!(stdout, "Created: {} ms", rev.created_at_ms).into_diagnostic()?;
}
if rev.loaded_at_ms > 0 {
println!("Loaded: {} ms", rev.loaded_at_ms);
writeln!(stdout, "Loaded: {} ms", rev.loaded_at_ms).into_diagnostic()?;
}
if !rev.load_error.is_empty() {
println!("Error: {}", rev.load_error);
writeln!(stdout, "Error: {}", rev.load_error).into_diagnostic()?;
}

if full {
if let Some(ref policy) = rev.policy {
println!("---");
writeln!(stdout, "---").into_diagnostic()?;
let yaml_str = openshell_policy::serialize_sandbox_policy(policy)
.wrap_err("failed to serialize policy to YAML")?;
print!("{yaml_str}");
write!(stdout, "{yaml_str}").into_diagnostic()?;
} else {
eprintln!("Policy payload not available for this version");
writeln!(stderr, "Policy payload not available for this version")
.into_diagnostic()?;
}
}
} else {
eprintln!("No policy history found for sandbox '{name}'");
writeln!(stderr, "No policy history found for sandbox '{name}'").into_diagnostic()?;
}

Ok(())
Expand All @@ -5704,6 +5754,7 @@ pub async fn sandbox_policy_get_global(
server: &str,
version: u32,
full: bool,
output: &str,
tls: &TlsOptions,
) -> Result<()> {
let mut client = grpc_client(server, tls).await?;
Expand All @@ -5720,6 +5771,16 @@ pub async fn sandbox_policy_get_global(
let inner = status_resp.into_inner();
if let Some(rev) = inner.revision {
let status = PolicyStatus::try_from(rev.status).unwrap_or(PolicyStatus::Unspecified);
match output {
"json" => {
let obj = policy_revision_to_json("global", None, None, &rev, status, full)?;
println!("{}", serde_json::to_string_pretty(&obj).into_diagnostic()?);
return Ok(());
}
"table" => {}
_ => return Err(miette!("unsupported output format: {output}")),
}

println!("Scope: global");
println!("Version: {}", rev.version);
println!("Hash: {}", rev.policy_hash);
Expand Down Expand Up @@ -5748,6 +5809,66 @@ pub async fn sandbox_policy_get_global(
Ok(())
}

fn policy_status_json_name(status: PolicyStatus) -> &'static str {
match status {
PolicyStatus::Unspecified => "unspecified",
PolicyStatus::Pending => "pending",
PolicyStatus::Loaded => "loaded",
PolicyStatus::Failed => "failed",
PolicyStatus::Superseded => "superseded",
}
}

fn policy_revision_to_json(
scope: &str,
sandbox: Option<&str>,
active_version: Option<u32>,
rev: &openshell_core::proto::SandboxPolicyRevision,
status: PolicyStatus,
full: bool,
) -> Result<serde_json::Value> {
let mut obj = serde_json::Map::new();
obj.insert("scope".to_string(), serde_json::json!(scope));
if let Some(sandbox) = sandbox {
obj.insert("sandbox".to_string(), serde_json::json!(sandbox));
}
obj.insert("version".to_string(), serde_json::json!(rev.version));
obj.insert("hash".to_string(), serde_json::json!(rev.policy_hash));
obj.insert(
"status".to_string(),
serde_json::json!(policy_status_json_name(status)),
);
if let Some(active_version) = active_version {
obj.insert(
"active_version".to_string(),
serde_json::json!(active_version),
);
}
if rev.created_at_ms > 0 {
obj.insert(
"created_at_ms".to_string(),
serde_json::json!(rev.created_at_ms),
);
}
if rev.loaded_at_ms > 0 {
obj.insert(
"loaded_at_ms".to_string(),
serde_json::json!(rev.loaded_at_ms),
);
}
if !rev.load_error.is_empty() {
obj.insert("load_error".to_string(), serde_json::json!(rev.load_error));
}
if full {
let policy = match rev.policy.as_ref() {
Some(policy) => openshell_policy::sandbox_policy_to_json_value(policy)?,
None => serde_json::Value::Null,
};
obj.insert("policy".to_string(), policy);
}
Ok(serde_json::Value::Object(obj))
}

pub async fn sandbox_policy_list(
server: &str,
name: &str,
Expand Down
Loading
Loading