Skip to content

Commit d0d8d02

Browse files
committed
fix(server): skip invalid stored policies during policy history repair
The startup repair that creates version-one policy history for legacy sandboxes propagated validation failures, so a single stored policy that no longer passes current validation rules prevented the gateway from starting. Skip such sandboxes with a warning and a completion summary so they keep the pre-repair behavior where only their own configuration reads report the failure. Store errors remain fatal. Signed-off-by: Piotr Mlocek <pmlocek@nvidia.com>
1 parent ea6c689 commit d0d8d02

1 file changed

Lines changed: 110 additions & 15 deletions

File tree

‎crates/openshell-server/src/grpc/policy.rs‎

Lines changed: 110 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ use sha2::{Digest, Sha256};
8585
use std::collections::{BTreeMap, HashMap, HashSet};
8686
use std::net::{IpAddr, Ipv4Addr};
8787
use std::sync::Arc;
88-
use tonic::{Request, Response, Status};
88+
use tonic::{Code, Request, Response, Status};
8989
use tracing::{debug, info, warn};
9090

9191
use super::validation::{
@@ -2351,7 +2351,7 @@ async fn resolve_sandbox_by_name_for_principal(
23512351
};
23522352
crate::auth::guard::ensure_sandbox_scope(principal, sandbox.object_id()).map_err(
23532353
|status| {
2354-
if status.code() == tonic::Code::PermissionDenied {
2354+
if status.code() == Code::PermissionDenied {
23552355
Status::permission_denied("sandbox not found or not owned by caller")
23562356
} else {
23572357
status
@@ -2621,21 +2621,24 @@ impl InitialPolicyHistoryStatus {
26212621

26222622
/// Insert the version-one policy baseline if this sandbox still has no policy
26232623
/// history. This never modifies an existing revision or apply result.
2624+
///
2625+
/// Returns `true` when a baseline was written. Stored policies that fail the
2626+
/// current validation rules are rejected with `FailedPrecondition`.
26242627
pub async fn initialize_policy_history(
26252628
store: &Store,
26262629
sandbox: &Sandbox,
26272630
status: InitialPolicyHistoryStatus,
2628-
) -> Result<(), Status> {
2631+
) -> Result<bool, Status> {
26292632
let Some(policy) = sandbox.spec.as_ref().and_then(|spec| spec.policy.as_ref()) else {
2630-
return Ok(());
2633+
return Ok(false);
26312634
};
26322635
if store
26332636
.get_latest_policy(sandbox.object_id())
26342637
.await
26352638
.map_err(|error| Status::internal(format!("read policy history failed: {error}")))?
26362639
.is_some()
26372640
{
2638-
return Ok(());
2641+
return Ok(false);
26392642
}
26402643
let policy =
26412644
validate_and_canonicalize_stored_policy(policy.clone(), STORED_POLICY_SOURCE_SPEC)?;
@@ -2656,15 +2659,22 @@ pub async fn initialize_policy_history(
26562659
sandbox.object_workspace(),
26572660
)
26582661
.await
2659-
.map_err(|error| Status::internal(format!("initialize policy history failed: {error}")))
2662+
.map_err(|error| Status::internal(format!("initialize policy history failed: {error}")))?;
2663+
Ok(true)
26602664
}
26612665

26622666
/// Create policy-history baselines for sandboxes written by older gateways.
26632667
///
2664-
/// Snapshot reads stay pure once this startup repair has completed.
2668+
/// Snapshot reads stay pure once this startup repair has completed. A stored
2669+
/// policy that no longer passes validation is skipped rather than blocking
2670+
/// gateway startup; that sandbox keeps the pre-repair behavior where its own
2671+
/// configuration reads report the validation failure. Store errors remain
2672+
/// fatal.
26652673
pub async fn backfill_legacy_policy_history(state: &Arc<ServerState>) -> Result<(), Status> {
26662674
const PAGE_SIZE: u32 = 1000;
26672675
let mut offset = 0;
2676+
let mut repaired = 0_usize;
2677+
let mut skipped = 0_usize;
26682678
loop {
26692679
let sandboxes = state
26702680
.store
@@ -2673,23 +2683,38 @@ pub async fn backfill_legacy_policy_history(state: &Arc<ServerState>) -> Result<
26732683
.map_err(|error| {
26742684
Status::internal(format!("list sandboxes for policy repair failed: {error}"))
26752685
})?;
2676-
if sandboxes.is_empty() {
2677-
return Ok(());
2678-
}
26792686
let count = u32::try_from(sandboxes.len()).unwrap_or(PAGE_SIZE);
26802687
for sandbox in sandboxes {
2681-
initialize_policy_history(
2688+
match initialize_policy_history(
26822689
state.store.as_ref(),
26832690
&sandbox,
26842691
InitialPolicyHistoryStatus::Loaded,
26852692
)
2686-
.await?;
2693+
.await
2694+
{
2695+
Ok(true) => repaired += 1,
2696+
Ok(false) => {}
2697+
Err(status) if status.code() == Code::FailedPrecondition => {
2698+
skipped += 1;
2699+
warn!(
2700+
sandbox_id = %sandbox.object_id(),
2701+
workspace = %sandbox.object_workspace(),
2702+
error = %status.message(),
2703+
"skipping policy history repair for invalid stored policy"
2704+
);
2705+
}
2706+
Err(status) => return Err(status),
2707+
}
26872708
}
26882709
if count < PAGE_SIZE {
2689-
return Ok(());
2710+
break;
26902711
}
26912712
offset = offset.saturating_add(count);
26922713
}
2714+
if repaired > 0 || skipped > 0 {
2715+
info!(repaired, skipped, "legacy policy history repair complete");
2716+
}
2717+
Ok(())
26932718
}
26942719

26952720
#[cfg(test)]
@@ -5383,7 +5408,7 @@ async fn handle_approve_all_draft_chunks_inner(
53835408
.await
53845409
{
53855410
Ok(evaluation) => evaluation,
5386-
Err(status) if status.code() == tonic::Code::FailedPrecondition => {
5411+
Err(status) if status.code() == Code::FailedPrecondition => {
53875412
info!(
53885413
sandbox_id = %sandbox_id,
53895414
chunk_id = %chunk.id,
@@ -7362,7 +7387,6 @@ mod tests {
73627387
use std::collections::HashMap;
73637388
use std::sync::Arc;
73647389
use std::sync::atomic::{AtomicUsize, Ordering};
7365-
use tonic::Code;
73667390

73677391
/// Wrap a request with a user `Principal` so handler scope guards treat
73687392
/// the test caller as a CLI user. Most handler tests exercise
@@ -11279,6 +11303,77 @@ mod tests {
1127911303
);
1128011304
}
1128111305

11306+
#[tokio::test]
11307+
async fn legacy_policy_history_repair_skips_invalid_stored_policy() {
11308+
use openshell_core::proto::LandlockPolicy;
11309+
11310+
let state = test_server_state().await;
11311+
let valid_policy = test_policy_with_rule("valid", "valid.example.com");
11312+
state
11313+
.store
11314+
.put_message(&test_sandbox(
11315+
"sb-valid-legacy",
11316+
"valid-legacy",
11317+
valid_policy.clone(),
11318+
Vec::new(),
11319+
))
11320+
.await
11321+
.unwrap();
11322+
let mut invalid_policy = test_policy_with_rule("invalid", "invalid.example.com");
11323+
invalid_policy.landlock = Some(LandlockPolicy {
11324+
compatibility: "best-effort".to_string(),
11325+
});
11326+
state
11327+
.store
11328+
.put_message(&test_sandbox(
11329+
"sb-invalid-legacy",
11330+
"invalid-legacy",
11331+
invalid_policy,
11332+
Vec::new(),
11333+
))
11334+
.await
11335+
.unwrap();
11336+
11337+
backfill_legacy_policy_history(&state)
11338+
.await
11339+
.expect("one invalid stored policy must not block startup repair");
11340+
11341+
let repaired = state
11342+
.store
11343+
.get_latest_policy("sb-valid-legacy")
11344+
.await
11345+
.unwrap()
11346+
.expect("valid legacy sandbox gets a baseline");
11347+
assert_eq!(repaired.version, 1);
11348+
assert_eq!(repaired.status, "loaded");
11349+
assert_eq!(
11350+
repaired.policy_hash,
11351+
deterministic_policy_hash(&valid_policy)
11352+
);
11353+
assert!(
11354+
state
11355+
.store
11356+
.get_latest_policy("sb-invalid-legacy")
11357+
.await
11358+
.unwrap()
11359+
.is_none(),
11360+
"invalid stored policy must not be persisted as history"
11361+
);
11362+
11363+
let error = handle_get_sandbox_config(
11364+
&state,
11365+
with_sandbox(
11366+
Request::new(GetSandboxConfigRequest {
11367+
sandbox_id: "sb-invalid-legacy".to_string(),
11368+
}),
11369+
"sb-invalid-legacy",
11370+
),
11371+
)
11372+
.await
11373+
.expect_err("invalid stored policy still fails only its own config read");
11374+
assert_eq!(error.code(), Code::FailedPrecondition);
11375+
}
11376+
1128211377
#[tokio::test]
1128311378
async fn legacy_policy_history_repair_is_idempotent() {
1128411379
let state = test_server_state().await;

0 commit comments

Comments
 (0)