Skip to content

Commit 279ed1a

Browse files
committed
feat(policy): freeze a sandbox's effective policy for its lifetime
Closes NVIDIA#4734 Signed-off-by: Shiju <[email protected]>
1 parent 7417f75 commit 279ed1a

51 files changed

Lines changed: 4681 additions & 1680 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎crates/openshell-cli/src/main.rs‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -504,6 +504,7 @@ struct Cli {
504504
}
505505

506506
#[derive(Subcommand, Debug)]
507+
#[allow(clippy::large_enum_variant)]
507508
enum Commands {
508509
// ===================================================================
509510
// SANDBOX COMMANDS
@@ -1532,6 +1533,10 @@ enum SandboxCommands {
15321533
#[arg(long, value_hint = ValueHint::FilePath)]
15331534
policy: Option<String>,
15341535

1536+
/// Freeze the effective policy after initialization for this sandbox's lifetime.
1537+
#[arg(long)]
1538+
frozen: bool,
1539+
15351540
/// Forward a local port to the sandbox before the initial command or shell starts.
15361541
/// Accepts [`bind_address`:]port (e.g. 8080, 0.0.0.0:8080). Keeps the sandbox alive.
15371542
#[arg(long, conflicts_with = "no_keep")]
@@ -3372,6 +3377,7 @@ async fn run_async() -> Result<()> {
33723377
driver_config_json,
33733378
providers,
33743379
policy,
3380+
frozen,
33753381
forward,
33763382
expose,
33773383
expose_authorization_mode,
@@ -3460,6 +3466,7 @@ async fn run_async() -> Result<()> {
34603466
editor,
34613467
providers: &providers,
34623468
policy: policy.as_deref(),
3469+
frozen,
34633470
forward,
34643471
expose,
34653472
expose_authorization_mode: expose_authorization_mode.into(),
@@ -6232,6 +6239,38 @@ mod tests {
62326239
}
62336240
}
62346241

6242+
#[test]
6243+
fn sandbox_create_frozen_supports_inline_and_named_templates() {
6244+
for args in [
6245+
vec!["openshell", "sandbox", "create", "--frozen"],
6246+
vec![
6247+
"openshell",
6248+
"sandbox",
6249+
"create",
6250+
"--template",
6251+
"agent",
6252+
"--frozen",
6253+
],
6254+
] {
6255+
let cli = Cli::try_parse_from(args).unwrap();
6256+
assert!(matches!(
6257+
cli.command,
6258+
Some(Commands::Sandbox {
6259+
command: Some(SandboxCommands::Create { frozen: true, .. }),
6260+
..
6261+
})
6262+
));
6263+
}
6264+
let cli = Cli::try_parse_from(["openshell", "sandbox", "create"]).unwrap();
6265+
assert!(matches!(
6266+
cli.command,
6267+
Some(Commands::Sandbox {
6268+
command: Some(SandboxCommands::Create { frozen: false, .. }),
6269+
..
6270+
})
6271+
));
6272+
}
6273+
62356274
#[test]
62366275
fn sandbox_create_restart_policy_defaults_to_never() {
62376276
let cli = Cli::try_parse_from(["openshell", "sandbox", "create"]).unwrap();

‎crates/openshell-cli/src/run.rs‎

Lines changed: 105 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -430,6 +430,7 @@ async fn finalize_sandbox_create_session(
430430
/// on the function signature, following the `provider_refresh_config(server, input, tls)`
431431
/// precedent. This struct captures sandbox-specific options.
432432
#[derive(Debug)]
433+
#[allow(clippy::struct_excessive_bools)] // Independent command-line switches.
433434
pub struct SandboxCreateConfig<'a> {
434435
pub name: Option<&'a str>,
435436
pub template: Option<&'a str>,
@@ -443,6 +444,7 @@ pub struct SandboxCreateConfig<'a> {
443444
pub editor: Option<Editor>,
444445
pub providers: &'a [String],
445446
pub policy: Option<&'a str>,
447+
pub frozen: bool,
446448
pub forward: Option<ForwardSpec>,
447449
pub expose: Option<u16>,
448450
pub expose_authorization_mode: ServiceAuthorizationMode,
@@ -474,6 +476,7 @@ impl Default for SandboxCreateConfig<'_> {
474476
editor: None,
475477
providers: &[],
476478
policy: None,
479+
frozen: false,
477480
forward: None,
478481
expose: None,
479482
expose_authorization_mode: ServiceAuthorizationMode::Strip,
@@ -513,6 +516,7 @@ pub async fn sandbox_create(
513516
editor,
514517
providers,
515518
policy,
519+
frozen,
516520
forward,
517521
expose,
518522
expose_authorization_mode,
@@ -681,6 +685,7 @@ pub async fn sandbox_create(
681685
HashMap::new()
682686
},
683687
policy,
688+
frozen,
684689
providers: configured_providers,
685690
template: inline_template,
686691
command: main_command,
@@ -737,6 +742,11 @@ pub async fn sandbox_create(
737742
} else {
738743
sandbox.object_name().to_string()
739744
};
745+
if frozen && !sandbox.spec.as_ref().is_some_and(|spec| spec.frozen) {
746+
return Err(miette::miette!(
747+
"gateway did not honor --frozen for sandbox '{sandbox_name}'; upgrade the gateway before retrying. The sandbox may already be running; remove it with: openshell --workspace {workspace} sandbox delete {sandbox_name}"
748+
));
749+
}
740750

741751
// Record this sandbox as the last-used for the active gateway only when it
742752
// is expected to persist beyond the initial session.
@@ -1687,6 +1697,19 @@ where
16871697
println!(" {} {}", "Id:".dimmed(), id);
16881698
println!(" {} {}", "Name:".dimmed(), name);
16891699
println!(" {} {}", "Phase:".dimmed(), phase_name(sandbox.phase()));
1700+
if let Some(frozen) = sandbox
1701+
.status
1702+
.as_ref()
1703+
.and_then(|status| status.frozen_policy.as_ref())
1704+
{
1705+
println!(" {} frozen", "Policy state:".dimmed());
1706+
println!(" {} {}", "Frozen hash:".dimmed(), frozen.policy_hash);
1707+
if let Some(time) = &frozen.frozen_time {
1708+
println!(" {} {}", "Frozen at:".dimmed(), time);
1709+
}
1710+
} else if sandbox.spec.as_ref().is_some_and(|spec| spec.frozen) {
1711+
println!(" {} pending freeze", "Policy state:".dimmed());
1712+
}
16901713
if let Some(status) = sandbox.status.as_ref() {
16911714
for condition in &status.conditions {
16921715
if matches!(
@@ -1824,11 +1847,7 @@ where
18241847
println!(
18251848
" {} {}",
18261849
"Policy source:".dimmed(),
1827-
if policy_from_global {
1828-
"global"
1829-
} else {
1830-
"sandbox"
1831-
}
1850+
policy_source_name(config.policy_source)
18321851
);
18331852
let revision = if policy_from_global {
18341853
if config.global_policy_version > 0 {
@@ -3001,6 +3020,14 @@ pub async fn sandbox_list(
30013020
Ok(())
30023021
}
30033022

3023+
fn policy_source_name(source: i32) -> &'static str {
3024+
match PolicySource::try_from(source) {
3025+
Ok(PolicySource::Frozen) => "frozen",
3026+
Ok(PolicySource::Global) => "global",
3027+
_ => "sandbox",
3028+
}
3029+
}
3030+
30043031
fn configuration_failure_message(sandbox: &Sandbox) -> Option<&str> {
30053032
sandbox
30063033
.status
@@ -3084,6 +3111,19 @@ fn sandbox_to_json(sandbox: &Sandbox) -> serde_json::Value {
30843111
"provider_env_revision": admission.provider_env_revision,
30853112
})
30863113
});
3114+
let frozen_policy = sandbox
3115+
.status
3116+
.as_ref()
3117+
.and_then(|status| status.frozen_policy.as_ref())
3118+
.map(|frozen| {
3119+
serde_json::json!({
3120+
"version": frozen.version,
3121+
"policy_hash": frozen.policy_hash,
3122+
"frozen_time": frozen.frozen_time.as_ref().map(ToString::to_string),
3123+
"policy_source": policy_source_name(frozen.policy_source),
3124+
"global_policy_version": frozen.global_policy_version,
3125+
})
3126+
});
30873127
let provisioning = sandbox.status.as_ref().and_then(|status| status.provisioning.as_ref())
30883128
.map(|record| serde_json::json!({
30893129
"attempt_id": record.attempt_id,
@@ -3123,6 +3163,8 @@ fn sandbox_to_json(sandbox: &Sandbox) -> serde_json::Value {
31233163
"endpoint_statuses": endpoint_statuses,
31243164
"last_token_grant_failure": last_token_grant_failure,
31253165
"configuration_admission": admission,
3166+
"frozen": sandbox.spec.as_ref().is_some_and(|spec| spec.frozen),
3167+
"frozen_policy": frozen_policy,
31263168
"provisioning": provisioning,
31273169
"created_from_workload_template": created_from_workload_template,
31283170
})
@@ -3339,11 +3381,7 @@ fn sandbox_detail_to_json(
33393381
);
33403382
}
33413383

3342-
let policy_source = if config.policy_source == PolicySource::Global as i32 {
3343-
"global"
3344-
} else {
3345-
"sandbox"
3346-
};
3384+
let policy_source = policy_source_name(config.policy_source);
33473385
obj.insert("policy_source".into(), serde_json::json!(policy_source));
33483386

33493387
let policy_from_global = config.policy_source == PolicySource::Global as i32;
@@ -5340,6 +5378,12 @@ pub async fn sandbox_policy_set_global(
53405378
},
53415379
response.settings_revision,
53425380
);
5381+
if !response.frozen_sandboxes.is_empty() {
5382+
eprintln!(
5383+
"Frozen sandboxes retain their policy: {}",
5384+
response.frozen_sandboxes.join(", ")
5385+
);
5386+
}
53435387
Ok(())
53445388
}
53455389

@@ -5368,11 +5412,7 @@ pub async fn sandbox_settings_get(
53685412
return Ok(());
53695413
}
53705414

5371-
let policy_source = if response.policy_source == PolicySource::Global as i32 {
5372-
"global"
5373-
} else {
5374-
"sandbox"
5375-
};
5415+
let policy_source = policy_source_name(response.policy_source);
53765416

53775417
println!("Sandbox: {name}");
53785418
println!("Config Rev: {}", response.config_revision);
@@ -5444,11 +5484,7 @@ fn settings_to_json_sandbox(
54445484
workspace: &str,
54455485
response: &GetSandboxConfigResponse,
54465486
) -> serde_json::Value {
5447-
let policy_source = if response.policy_source == PolicySource::Global as i32 {
5448-
"global"
5449-
} else {
5450-
"sandbox"
5451-
};
5487+
let policy_source = policy_source_name(response.policy_source);
54525488

54535489
let mut settings = serde_json::Map::new();
54545490
let mut keys: Vec<_> = response.settings.keys().cloned().collect();
@@ -5599,6 +5635,12 @@ pub async fn gateway_setting_delete(
55995635
} else {
56005636
println!("{} Global setting {} not found", "!".yellow(), key);
56015637
}
5638+
if !response.frozen_sandboxes.is_empty() {
5639+
println!(
5640+
"Frozen sandboxes retain their policy: {}",
5641+
response.frozen_sandboxes.join(", ")
5642+
);
5643+
}
56025644
Ok(())
56035645
}
56045646

@@ -6116,6 +6158,7 @@ where
61166158
PolicySource::try_from(config.policy_source).unwrap_or(PolicySource::Sandbox);
61176159
let policy_source_label = match policy_source {
61186160
PolicySource::Global => "global",
6161+
PolicySource::Frozen => "frozen",
61196162
PolicySource::Sandbox => "sandbox",
61206163
PolicySource::Unspecified => "unspecified",
61216164
};
@@ -8648,6 +8691,48 @@ mod tests {
86488691
);
86498692
}
86508693

8694+
#[test]
8695+
fn sandbox_json_distinguishes_pending_and_frozen_policy() {
8696+
let mut sandbox = Sandbox {
8697+
spec: Some(SandboxSpec {
8698+
frozen: true,
8699+
..Default::default()
8700+
}),
8701+
status: Some(SandboxStatus::default()),
8702+
..Default::default()
8703+
};
8704+
let pending = super::sandbox_to_json(&sandbox);
8705+
assert_eq!(pending["frozen"], true);
8706+
assert!(pending["frozen_policy"].is_null());
8707+
sandbox.status.as_mut().unwrap().frozen_policy = Some(
8708+
openshell_core::proto::FrozenSandboxPolicy {
8709+
version: 3,
8710+
policy_hash: "accepted-hash".into(),
8711+
frozen_time: openshell_core::time::timestamp_from_millis(600_000).ok(),
8712+
policy_source: PolicySource::Global as i32,
8713+
global_policy_version: 7,
8714+
..Default::default()
8715+
}
8716+
.into(),
8717+
);
8718+
let frozen = super::sandbox_to_json(&sandbox);
8719+
assert_eq!(frozen["frozen_policy"]["policy_hash"], "accepted-hash");
8720+
assert_eq!(
8721+
frozen["frozen_policy"]["frozen_time"],
8722+
"1970-01-01T00:10:00Z"
8723+
);
8724+
assert_eq!(frozen["frozen_policy"]["policy_source"], "global");
8725+
let detail = super::sandbox_detail_to_json(
8726+
&sandbox,
8727+
&GetSandboxConfigResponse {
8728+
policy_source: PolicySource::Frozen as i32,
8729+
..Default::default()
8730+
},
8731+
)
8732+
.unwrap();
8733+
assert_eq!(detail["policy_source"], "frozen");
8734+
}
8735+
86518736
#[test]
86528737
fn sandbox_json_exposes_repair_diagnostic_and_accepted_generation() {
86538738
use openshell_core::proto::{ConfigurationAdmissionState, SandboxConfigurationAdmission};

‎crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1779,6 +1779,55 @@ async fn sandbox_create_tolerates_an_unreachable_profile_catalog() {
17791779
.await;
17801780
}
17811781

1782+
#[tokio::test]
1783+
async fn sandbox_create_rejects_gateway_that_ignores_frozen() {
1784+
let server = run_server().await;
1785+
let fake_ssh_dir = helpers::tempdir().unwrap();
1786+
let xdg_dir = helpers::tempdir().unwrap();
1787+
1788+
test_env(&fake_ssh_dir, &xdg_dir)
1789+
.run_async(async {
1790+
// This server records the requested spec but returns no spec,
1791+
// matching a gateway that ignores the new frozen field.
1792+
let error = run::sandbox_create(
1793+
&server.endpoint,
1794+
"openshell",
1795+
run::SandboxCreateConfig {
1796+
name: Some("legacy-frozen"),
1797+
frozen: true,
1798+
command: &["/opt/agent".into()],
1799+
..test_config()
1800+
},
1801+
"default",
1802+
&test_tls(&server),
1803+
)
1804+
.await
1805+
.expect_err("an unsupported freeze must stop the client workflow");
1806+
1807+
let message = error.to_string();
1808+
assert!(message.contains("gateway did not honor --frozen"));
1809+
assert!(message.contains("openshell --workspace default sandbox delete legacy-frozen"));
1810+
assert!(
1811+
create_requests(&server).await[0]
1812+
.spec
1813+
.as_ref()
1814+
.unwrap()
1815+
.frozen
1816+
);
1817+
assert_eq!(
1818+
server
1819+
.openshell
1820+
.state
1821+
.ssh_session_requests
1822+
.load(Ordering::SeqCst),
1823+
0
1824+
);
1825+
assert!(deleted_names(&server).await.is_empty());
1826+
assert_eq!(load_last_sandbox("openshell", "default"), None);
1827+
})
1828+
.await;
1829+
}
1830+
17821831
#[tokio::test]
17831832
async fn sandbox_create_keeps_command_sessions_by_default() {
17841833
let server = run_server().await;

‎crates/openshell-core/build.rs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,9 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
5151
// the build process environment. With a caller-supplied PROTOC, leave both
5252
// to prost.
5353
let mut proto_config = tonic_prost_build::Config::new();
54-
// Keep optional grant evidence off sandbox lifecycle futures' stacks.
54+
// Keep optional grant evidence and policy snapshots off lifecycle futures' stacks.
5555
proto_config.boxed(".openshell.v1.SandboxStatus.last_token_grant_failure");
56+
proto_config.boxed(".openshell.v1.SandboxStatus.frozen_policy");
5657
let proto_include = if use_vendored_protoc {
5758
proto_config.protoc_executable(protoc_bin_vendored::protoc_bin_path()?);
5859
Some(protoc_bin_vendored::include_path()?)

0 commit comments

Comments
 (0)