Skip to content
Closed
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
11 changes: 11 additions & 0 deletions architecture/security-policy.md
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,17 @@ because it changes the effective access model for every sandbox on the gateway.
The policy advisor pipeline turns observed denials into draft policy
recommendations. There are two proposers (sandbox-side mechanistic mapper,
agent-authored via `policy.local`); the gateway is the single referee.

Supervisor-observed policy denials and upstream TLS certificate-verification
failures also enter the existing draft pipeline as `gateway_event` proposals.
The supervisor submits before returning a structured failure body to the
client. A sandbox-session map keyed by normalized host and port reuses one
proposal ID for repeated failures. These event drafts always await human
review, including when auto approval is enabled. Upstream TLS drafts reserve
an empty `upstream_ca_pem` slot; approval requires an exact host and a
verified PEM supplied through draft editing. The supervisor never trusts a
certificate captured from the failed connection. Existing CA conflict and
IP allowlist validation still run when the edited draft is approved.
When enabled, L7 `policy_denied` responses include both structured
`next_steps` and a short `agent_guidance` string so generic agents can continue
through the proposal loop instead of treating the denial as terminal.
Expand Down
142 changes: 133 additions & 9 deletions crates/openshell-server/src/grpc/policy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1384,6 +1384,18 @@ async fn require_current_proposal_evaluation(
chunk: &DraftChunkRecord,
supplied_review_token: Option<&str>,
) -> Result<ProposalEvaluation, Status> {
if chunk.rule_name.starts_with("advisor_ca_") {
let rule = decode_draft_chunk_rule(chunk)?;
if rule.as_ref().is_none_or(|rule| {
rule.endpoints.len() != 1
|| rule.endpoints[0].host.contains('*')
|| rule.endpoints[0].upstream_ca_pem.is_empty()
}) {
return Err(Status::failed_precondition(
"verified upstream_ca_pem for one exact host is required before approval",
));
}
}
if !chunk.review_token.is_empty()
&& supplied_review_token.is_some_and(|token| token != chunk.review_token)
{
Expand Down Expand Up @@ -4386,14 +4398,12 @@ pub(super) async fn handle_submit_policy_analysis(
}

let rule_ref = chunk.proposed_rule.as_ref().expect("checked above");
if req.analysis_mode == "agent_authored"
&& let Some(reason) = rule_ref.endpoints.iter().find_map(|endpoint| {
openshell_policy::agent_authored_transport_rejection(
&endpoint.protocol,
&endpoint.tls,
)
})
{
if matches!(
req.analysis_mode.as_str(),
"agent_authored" | "gateway_event"
) && let Some(reason) = rule_ref.endpoints.iter().find_map(|endpoint| {
openshell_policy::agent_authored_transport_rejection(&endpoint.protocol, &endpoint.tls)
}) {
rejected += 1;
rejection_reasons.push(format!("chunk '{}': {reason}", chunk.rule_name));
continue;
Expand Down Expand Up @@ -4478,7 +4488,21 @@ pub(super) async fn handle_submit_policy_analysis(
None,
);
}
if req.analysis_mode != "mechanistic" && !evaluation.application_error.is_empty() {
let awaiting_ca = req.analysis_mode == "gateway_event"
&& chunk.stage == "upstream_tls"
&& rule_ref
.endpoints
.iter()
.all(|endpoint| endpoint.upstream_ca_pem.is_empty());
if awaiting_ca {
evaluation.application_error =
"verified upstream_ca_pem required before approval".to_string();
evaluation.review_token.clear();
}
if req.analysis_mode != "mechanistic"
&& !awaiting_ca
&& !evaluation.application_error.is_empty()
{
rejected += 1;
rejection_reasons.push(format!(
"chunk '{}': {}",
Expand Down Expand Up @@ -4605,6 +4629,7 @@ pub(super) async fn handle_submit_policy_analysis(
// string means findings or infrastructure error, both of which
// require human attention.
if auto_approve_enabled
&& req.analysis_mode != "gateway_event"
&& let Err(err) = Box::pin(auto_approve_chunk(
state,
&effective_id,
Expand Down Expand Up @@ -13280,6 +13305,105 @@ mod tests {
assert!(!policy_covers_rule(&policy, &proposed_rule));
}

#[tokio::test]
async fn gateway_tls_event_waits_for_verified_ca_even_in_auto_mode() {
let state = test_server_state().await;
let sandbox_name = "gateway-ca-event";
state
.store
.put_message(&test_sandbox(
"sb-gateway-ca",
sandbox_name,
ProtoSandboxPolicy::default(),
vec![],
))
.await
.unwrap();
seed_sandbox_approval_mode(&state, sandbox_name, "auto").await;
let rule = NetworkPolicyRule {
name: "advisor_ca_internal_443".into(),
endpoints: vec![NetworkEndpoint {
host: "internal.example.test".into(),
port: 443,
..Default::default()
}],
..Default::default()
};
let response = handle_submit_policy_analysis(
&state,
with_user(Request::new(SubmitPolicyAnalysisRequest {
name: sandbox_name.into(),
analysis_mode: "gateway_event".into(),
proposed_chunks: vec![PolicyChunk {
rule_name: rule.name.clone(),
proposed_rule: Some(rule.clone()),
stage: "upstream_tls".into(),
..Default::default()
}],
..Default::default()
})),
)
.await
.unwrap()
.into_inner();
let id = response.accepted_chunk_ids[0].clone();
let draft = state.store.get_draft_chunk(&id).await.unwrap().unwrap();
assert_eq!(draft.status, "pending");
let error = handle_approve_draft_chunk(
&state,
authed_request(ApproveDraftChunkRequest {
name: sandbox_name.into(),
chunk_id: id.clone(),
workspace: "default".into(),
..Default::default()
}),
)
.await
.unwrap_err();
assert!(error.message().contains("upstream_ca_pem"));

let mut reviewed_rule = rule;
reviewed_rule.endpoints[0].upstream_ca_pem =
rcgen::generate_simple_self_signed(vec!["internal.example.test".into()])
.unwrap()
.cert
.pem();
handle_edit_draft_chunk(
&state,
authed_request(EditDraftChunkRequest {
name: sandbox_name.into(),
chunk_id: id.clone(),
proposed_rule: Some(reviewed_rule),
workspace: "default".into(),
}),
)
.await
.unwrap();
let reviewed = state.store.get_draft_chunk(&id).await.unwrap().unwrap();
assert!(!reviewed.review_token.is_empty());
handle_approve_draft_chunk(
&state,
authed_request(ApproveDraftChunkRequest {
name: sandbox_name.into(),
chunk_id: id.clone(),
workspace: "default".into(),
review_token: reviewed.review_token,
}),
)
.await
.unwrap();
assert_eq!(
state
.store
.get_draft_chunk(&id)
.await
.unwrap()
.unwrap()
.status,
"approved"
);
}

#[tokio::test]
async fn mechanistic_dedup_auto_approval_rechecks_edited_stored_rule() {
let state = test_server_state().await;
Expand Down
1 change: 1 addition & 0 deletions crates/openshell-supervisor-network/src/l7/relay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ pub struct L7EvalContext {
Option<Arc<dyn crate::l7::token_grant_injection::TokenGrantResolver>>,
/// Shared feature state for agent-driven policy proposals.
pub(crate) agent_proposals: openshell_core::proposals::AgentProposals,
pub(crate) policy_local: Option<Arc<crate::policy_local::PolicyLocalContext>>,
}

fn request_default_port(ctx: &L7EvalContext) -> Option<u16> {
Expand Down
40 changes: 34 additions & 6 deletions crates/openshell-supervisor-network/src/l7/rest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ pub(crate) struct DenyResponseContext<'a> {
pub(crate) port: Option<u16>,
pub(crate) binary: Option<&'a str>,
pub(crate) agent_proposals_enabled: bool,
pub(crate) policy_local: Option<&'a crate::policy_local::PolicyLocalContext>,
}

impl<'a> DenyResponseContext<'a> {
Expand All @@ -142,6 +143,7 @@ impl<'a> DenyResponseContext<'a> {
port: Some(ctx.port),
binary: Some(&ctx.binary_path),
agent_proposals_enabled: ctx.agent_proposals.enabled(),
policy_local: ctx.policy_local.as_deref(),
}
}
}
Expand Down Expand Up @@ -2582,7 +2584,30 @@ async fn send_deny_response<C: AsyncWrite + Unpin>(
redacted_target: Option<&str>,
context: Option<DenyResponseContext<'_>>,
) -> Result<()> {
let body = deny_response_body(req, policy_name, reason, redacted_target, context);
let mut body = deny_response_body(req, policy_name, reason, redacted_target, context);
if let Some(context) = context
&& let (Some(local), Some(host), Some(port)) =
(context.policy_local, context.host, context.port)
{
let path = redacted_target.unwrap_or(&req.target);
let proposal_id = local
.propose_for_event(
host,
port,
context.binary.unwrap_or_default(),
false,
Some((&req.action, path)),
)
.await;
body["advisor"] = serde_json::json!({
"event": "policy_denied",
"host": host,
"port": port,
"remedy": "review_destination_exception",
"proposal_id": proposal_id,
"next_action": if proposal_id.is_some() { "relay_to_user_and_wait_for_approval" } else { "report_failure_without_proposal" }
});
}
send_forbidden_json(policy_name, body, client).await
}

Expand Down Expand Up @@ -4051,6 +4076,7 @@ mod tests {
port: Some(443),
binary: Some("/usr/bin/gh"),
agent_proposals_enabled: true,
policy_local: None,
}),
);

Expand Down Expand Up @@ -4082,12 +4108,11 @@ mod tests {
body["next_steps"][0]["path"],
"/etc/openshell/skills/policy_advisor.md"
);
assert_eq!(body["next_steps"][3]["body_type"], "PolicyMergeOperation");
assert_eq!(body["next_steps"][3]["action"], "wait_for_approval");
let guidance = body["agent_guidance"]
.as_str()
.expect("agent_guidance is present when proposals are enabled");
assert!(guidance.contains("do not stop"));
assert!(guidance.contains("/etc/openshell/skills/policy_advisor.md"));
assert!(guidance.contains("advisor.proposal_id"));
assert!(guidance.contains("http://policy.local/v1/proposals"));
assert!(
!body.to_string().contains("secret-token"),
Expand Down Expand Up @@ -4115,6 +4140,7 @@ mod tests {
port: Some(443),
binary: Some("/usr/bin/gh"),
agent_proposals_enabled: false,
policy_local: None,
}),
);

Expand Down Expand Up @@ -4185,7 +4211,7 @@ mod tests {
Some(DenyResponseContext::from_l7_context(&l7_ctx)),
);
assert_eq!(deny_body["next_steps"][0]["action"], "read_skill");
assert_eq!(deny_body["next_steps"][3]["action"], "submit_proposal");
assert_eq!(deny_body["next_steps"][3]["action"], "wait_for_approval");
assert!(
deny_body["agent_guidance"]
.as_str()
Expand Down Expand Up @@ -4218,6 +4244,7 @@ mod tests {
port: Some(443),
binary: Some("/usr/bin/curl"),
agent_proposals_enabled: true,
policy_local: None,
}),
);

Expand Down Expand Up @@ -4256,6 +4283,7 @@ mod tests {
port: Some(443),
binary: Some("/usr/bin/gh"),
agent_proposals_enabled: true,
policy_local: None,
}),
)
.await
Expand All @@ -4278,7 +4306,7 @@ mod tests {
assert_eq!(body["path"], "/user/repos");
assert_eq!(body["rule_missing"]["host"], "api.github.com");
assert_eq!(body["next_steps"][2]["action"], "inspect_recent_denials");
assert!(body["agent_guidance"].as_str().unwrap().contains("retry"));
assert!(body["agent_guidance"].as_str().unwrap().contains("Retry"));
}

#[test]
Expand Down
30 changes: 23 additions & 7 deletions crates/openshell-supervisor-network/src/l7/tls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -265,12 +265,11 @@ mod endpoint_ca_tests {
.await
.expect("endpoint CA should verify upstream");
let stream = TcpStream::connect(address).await.unwrap();
assert!(
tls_connect_upstream(stream, "private.example.test", client.upstream_config())
.await
.is_err(),
"default upstream config must not trust endpoint CA"
);
let error = tls_connect_upstream(stream, "private.example.test", client.upstream_config())
.await
.err()
.expect("default upstream config must not trust endpoint CA");
assert!(is_certificate_verification_error(&error));
assert!(Arc::ptr_eq(
&scoped,
&client.endpoint_upstream_config(&pem).unwrap()
Expand Down Expand Up @@ -454,10 +453,27 @@ pub async fn tls_connect_upstream(
let tls_stream = connector
.connect(server_name, upstream)
.await
.into_diagnostic()?;
.map_err(|source| miette::Report::new(UpstreamTlsHandshakeError { source }))?;
Ok(tls_stream)
}

#[derive(Debug, thiserror::Error, miette::Diagnostic)]
#[error("upstream TLS handshake failed: {source}")]
struct UpstreamTlsHandshakeError {
#[source]
source: std::io::Error,
}

/// Identify the verifier's typed certificate error, rather than inferring a
/// trust failure from curl's reset message or from a stringified IO error.
pub fn is_certificate_verification_error(error: &miette::Report) -> bool {
error
.downcast_ref::<UpstreamTlsHandshakeError>()
.and_then(|error| error.source.get_ref())
.and_then(|source| source.downcast_ref::<rustls::Error>())
.is_some_and(|source| matches!(source, rustls::Error::InvalidCertificate(_)))
}

/// Build a rustls `ClientConfig` using the configured CA root source.
///
/// In `bundled-ca-roots` mode this uses Mozilla roots from `webpki-roots` overlaid
Expand Down
Loading
Loading