Repository navigation
feat(box): add reload library API - #217
gautamsirdeshmukh merged 16 commits into
Conversation
## Problem A library caller cannot reach the policy engine that its running box uses. Boxy needs to replace that policy without restarting the workload. ## Solution Add reload(&[Policy]) beside run, with ReloadFailed over the existing BoxError. The private run path holds a reference to its existing engine during workload supervision. Reload withdrawal waits for an active call before the box lock is released. The run signature, RunOptions, and policy engine stay unchanged. The library guide and architecture describe the added surface and its lifetime. ## Tests Ran just check across the workspace. Final changes passed just build, just fmt-check, just clippy, and cargo test -p strands-box --all-features. All commands used RUSTFLAGS='-C debuginfo=0', as CI does. box_library::reload_tests::running_box covers live deny/allow/deny changes, invalid replacements, default-deny, unchanged policy files, and reload refusal outside the run. The workload keeps its process ID throughout the probe. The existing fatal_durable_staging_stops_the_supervised_workload_and_withdraws_live_state test now pins ownership until explicit teardown. Both negative controls failed as expected: a no-op reload leaves the read denied, and an early ownership release fails the live-state assertion. Both restored tests passed. Feature-critic reported no remaining findings. Existing ignored tests remain ignored. Linux and separate example and containment harnesses were not run locally.
|
Assessment: Request Changes This review covers head Review Categories
Checked and held:
|
kevin-orellana
left a comment
There was a problem hiding this comment.
I reproduced a case where reload reports success, but a previously forbidden tool becomes allowed after discovery finishes.
The replacement rule forbids two tools. One tool’s definition is available; the other is still missing. Reload accepts the replacement and temporarily blocks the known tool. If discovery ends without the missing definition, the known tool becomes allowed.
The replacement is invalid when checked against both definitions. Before this change, reload rejects it and preserves the original prohibition.
Could we reject invalid replacements without changing the active policy, and ensure unresolved rules keep their tools blocked after discovery? A regression covering this sequence would help. I am requesting changes because this can remove a working authorization restriction.
Steps to reproduce
- Use a clean checkout at
68389401911fb967e42488f12debd14e90449650. - Save the test below as
crates/policy/tests/review_reload.rs. - From the repository root, run:
env -u REVIEW_EXPECT_REJECT CARGO_PROFILE_DEV_DEBUG=0 CARGO_PROFILE_TEST_DEBUG=0 cargo test --locked -p strands-box-policy --all-features --test review_reload -- --nocaptureThe test opens a policy engine and loads only Alpha’s tool definition. It installs a working prohibition on alpha/read. It then reloads a replacement that forbids both alpha/read and beta/read, without loading Beta’s definition. Finally, it ends discovery and checks Alpha again.
Expected: Reject the invalid replacement and preserve the original prohibition. If a replacement remains pending, discovery completion must not make its affected tool callable.
Actual: Reload succeeds. Alpha is initially denied with PolicyPending, but becomes Allow after discovery ends. The final assertion fails:
pending=Deny { reason: PolicyPending, rule: RuleId("<policy-pending>"), resource: "alpha/read" }; degraded=["alpha", "beta"]; after=Allow { rule: RuleId("<default-deny>"), resource: "alpha/read" }
Reproduction test
//! Review probes for reload and tool discovery.
use policy::{GovernedBox, Operator, Policy, PolicyEngine, Principal, generate_mcp_schema};
fn source(text: &str) -> Vec<Policy> {
vec![Policy {
origin: "review.dw".into(),
text: text.into(),
}]
}
#[test]
fn pending_forbid_keeps_known_tool_denied_when_discovery_ends() {
let history = tempfile::tempdir().unwrap();
let engine = PolicyEngine::open_staged(
&Operator::unanchored(),
source("permit(principal, action, resource);"),
&history.path().join("history"),
)
.unwrap();
let schema = generate_mcp_schema(
"alpha",
r#"{"result":{"tools":[{"name":"read","inputSchema":{"type":"object","properties":{}}}]}}"#,
)
.unwrap();
engine.stage_mcp_schema("alpha", schema.clone()).unwrap();
let forbidden = source(
r#"permit(principal, action, resource);
forbid(principal, action == alpha::Action::"read", resource);"#,
);
engine.reload(&forbidden).unwrap();
let call = || {
engine.refine_tool_call(
&GovernedBox::assigned("review"),
&Principal::agent(),
"alpha",
"read",
&serde_json::json!({}),
)
};
assert!(!call().is_allow(), "the original forbid must deny alpha");
let replacement = source(
r#"permit(principal, action, resource);
forbid(principal, action in [alpha::Action::"read", beta::Action::"read"], resource);"#,
);
let beta_schema = generate_mcp_schema(
"beta",
r#"{"result":{"tools":[{"name":"read","inputSchema":{"type":"object","properties":{}}}]}}"#,
)
.unwrap();
let fully_checked = PolicyEngine::validate_with_mcp_schemas(
&Operator::unanchored(),
&replacement,
&[schema, beta_schema],
);
assert!(fully_checked.is_err(), "the replacement mixes incompatible action types");
eprintln!("complete validation refuses replacement: {fully_checked:?}");
let reload = engine.reload(&replacement);
if std::env::var_os("REVIEW_EXPECT_REJECT").is_some() {
assert!(reload.is_err(), "the baseline must refuse this replacement");
assert!(!call().is_allow(), "the old forbid must remain installed");
eprintln!("baseline refused replacement and preserved deny: {reload:?}");
return;
}
reload.unwrap();
let pending = call();
assert!(!pending.is_allow(), "the pending forbid must deny alpha");
let degraded = engine.finish_mcp_discovery().unwrap();
let after = call();
eprintln!("pending={pending:?}; degraded={degraded:?}; after={after:?}");
assert!(
!after.is_allow(),
"finishing discovery must not turn the unresolved forbid into an allow"
);
}I ran this through the real policy library on macOS. The 25 existing authority tests pass. Restoring the base authority implementation rejects the replacement and preserves the denial. A temporary early check for degraded tools also prevents the demonstrated permission. That check alone does not fix acceptance of invalid replacement text. Restoring this PR’s production code reproduces the failure again.
|
Assessment: Request Changes This review covers head Review Categories
Checked and held this round:
|
|
Assessment: Comment This review covers head Checked and held this round:
|
|
Assessment: Comment This review covers head Review Categories
Checked and held this round:
|
|
Assessment: Comment This review covers head Checked and held this round:
|
|
Assessment: Comment (no new findings) This review covers head Checked and held this round:
Still open: the PR has no |
Description
A library caller cannot change the policy of a running box. It must stop the box and start a new one, and that ends the agent's work.
This PR adds
strands_box::reload(&[Policy]) -> Result<(), ReloadRefused>. It replaces the running box's policy in the same process, and the workload keeps running.Decisions:
PolicyEngine::reload, and its signature does not change. The new policy must validate in full, or Box refuses it and the old policy stays. A rule about one MCP server's tool can only be checked after the agent has used that server. Before that, the reload is refused. The README states this limit. An earlier version of this PR kept such rules pending. That design let a forbidden tool become allowed, so this PR removes it.HostedBox::openpublishes the box's policy engine in a private static, andDropclears it. feat(box): reach a running box's policy from a library caller #149 left open whether reload is an in-process call or a request to another process. This PR answers it for the current in-process library. A cross-process design would need a new call.ReloadRefusedwraps the internalBoxError, asCheckFailedandGrantRefuseddo.BoxErrorstays private.ReloadRefused::is_not_running()tells a caller that no box is open yet, so the caller can retry.policy_installedorpolicy_refusedcontrol record.policy_refusedcan now also mean a refused reload, not only a box that did not start.main. When discovery ends with a rule still waiting, Box blocks that rule's tools. But if the tool's server had already reported its tools, a call to it was allowed. Now the tool stays blocked, and a successful reload removes the block. The check now runs under one lock, so a reload cannot change the state in the middle of a decision.API approval: this PR adds
reload,ReloadRefused,ReloadRefused::is_not_running, and a re-export ofPolicyto the frozenstrands-boxsurface. It also widens whatpolicy_refusedmeans. These need maintainer approval.Deferred:
"can still get past the block, because the scan for typed actions stops at the first quote. This is also onmain, and it needs its own fix.main.Related Issues
Covers the library reload use case in #149.
Type of Change
New feature
Testing
just check, orcargo test --workspace --all-features)cargo fmt --allandcargo clippy --workspace --all-targets --all-features -- -D warningsOn macOS: the policy crate tests, the live library reload test, clippy, and fmt pass. The containment suite passes (121 passed, 12 Linux cases skipped). Linux runs in CI only.
main's code. Removing the block, or removing the clear on reload, makes it fail.Checklist
By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.