diff --git a/architecture/security-policy.md b/architecture/security-policy.md index 99fcbdfd86..4f102015f2 100644 --- a/architecture/security-policy.md +++ b/architecture/security-policy.md @@ -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. diff --git a/crates/openshell-server/src/grpc/policy.rs b/crates/openshell-server/src/grpc/policy.rs index a26e903dcf..4e2acf03e0 100644 --- a/crates/openshell-server/src/grpc/policy.rs +++ b/crates/openshell-server/src/grpc/policy.rs @@ -1384,6 +1384,18 @@ async fn require_current_proposal_evaluation( chunk: &DraftChunkRecord, supplied_review_token: Option<&str>, ) -> Result { + 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) { @@ -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; @@ -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 '{}': {}", @@ -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, @@ -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; diff --git a/crates/openshell-supervisor-network/src/l7/relay.rs b/crates/openshell-supervisor-network/src/l7/relay.rs index aec52cf9cd..77aab8f249 100644 --- a/crates/openshell-supervisor-network/src/l7/relay.rs +++ b/crates/openshell-supervisor-network/src/l7/relay.rs @@ -79,6 +79,7 @@ pub struct L7EvalContext { Option>, /// Shared feature state for agent-driven policy proposals. pub(crate) agent_proposals: openshell_core::proposals::AgentProposals, + pub(crate) policy_local: Option>, } fn request_default_port(ctx: &L7EvalContext) -> Option { diff --git a/crates/openshell-supervisor-network/src/l7/rest.rs b/crates/openshell-supervisor-network/src/l7/rest.rs index 93315a671a..4cfe573450 100644 --- a/crates/openshell-supervisor-network/src/l7/rest.rs +++ b/crates/openshell-supervisor-network/src/l7/rest.rs @@ -132,6 +132,7 @@ pub(crate) struct DenyResponseContext<'a> { pub(crate) port: Option, 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> { @@ -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(), } } } @@ -2582,7 +2584,30 @@ async fn send_deny_response( redacted_target: Option<&str>, context: Option>, ) -> 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 } @@ -4051,6 +4076,7 @@ mod tests { port: Some(443), binary: Some("/usr/bin/gh"), agent_proposals_enabled: true, + policy_local: None, }), ); @@ -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"), @@ -4115,6 +4140,7 @@ mod tests { port: Some(443), binary: Some("/usr/bin/gh"), agent_proposals_enabled: false, + policy_local: None, }), ); @@ -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() @@ -4218,6 +4244,7 @@ mod tests { port: Some(443), binary: Some("/usr/bin/curl"), agent_proposals_enabled: true, + policy_local: None, }), ); @@ -4256,6 +4283,7 @@ mod tests { port: Some(443), binary: Some("/usr/bin/gh"), agent_proposals_enabled: true, + policy_local: None, }), ) .await @@ -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] diff --git a/crates/openshell-supervisor-network/src/l7/tls.rs b/crates/openshell-supervisor-network/src/l7/tls.rs index b4f6b5accd..2396ed4218 100644 --- a/crates/openshell-supervisor-network/src/l7/tls.rs +++ b/crates/openshell-supervisor-network/src/l7/tls.rs @@ -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() @@ -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::() + .and_then(|error| error.source.get_ref()) + .and_then(|source| source.downcast_ref::()) + .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 diff --git a/crates/openshell-supervisor-network/src/policy_local.rs b/crates/openshell-supervisor-network/src/policy_local.rs index 68da665c34..f2ad05a5db 100644 --- a/crates/openshell-supervisor-network/src/policy_local.rs +++ b/crates/openshell-supervisor-network/src/policy_local.rs @@ -15,7 +15,7 @@ use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::sync::Arc; use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; -use tokio::sync::RwLock; +use tokio::sync::{Mutex, RwLock}; pub const POLICY_LOCAL_HOST: &str = "policy.local"; @@ -28,7 +28,7 @@ pub use openshell_core::container_paths::POLICY_ADVISOR_SKILL_PATH as SKILL_PATH /// Human-readable guidance for agents that are more likely to follow plain /// instructions than structured next-step JSON alone. -pub const AGENT_GUIDANCE: &str = "OpenShell blocked this request with sandbox policy. If the user's task still needs this network action, do not stop here: read /etc/openshell/skills/policy_advisor.md (or $HOME/.claude/skills/policy-advisor/policy_advisor.md in a non-root sandbox), submit the narrowest policy proposal to http://policy.local/v1/proposals, wait for approval and `policy_reloaded: true`, then retry the original request."; +pub const AGENT_GUIDANCE: &str = "The supervisor observed this failure and submits a pending proposal automatically when possible. Read advisor.proposal_id in this response, tell the user what failed, and wait at http://policy.local/v1/proposals/{proposal_id}/wait?timeout=300. Retry only after approval and policy_reloaded: true. If proposal_id is null, report that no proposal was confirmed."; /// Routes served by the in-sandbox policy advisor API. /// @@ -91,6 +91,7 @@ pub struct PolicyLocalContext { sandbox_name: Option, shorthand_log_dir: PathBuf, workspace_rx: tokio::sync::watch::Receiver, + auto_proposals: Mutex>, } impl PolicyLocalContext { @@ -126,6 +127,7 @@ impl PolicyLocalContext { sandbox_name, shorthand_log_dir, workspace_rx, + auto_proposals: Mutex::new(HashMap::new()), } } @@ -149,6 +151,133 @@ impl PolicyLocalContext { pub fn agent_proposals_enabled(&self) -> bool { self.agent_proposals.enabled() } + + /// Persist an event observed by the supervisor before returning the failure + /// to the client. Holding the lock through submission makes concurrent + /// failures for one endpoint share the same card in this sandbox session. + pub async fn propose_for_event( + &self, + host: &str, + port: u16, + binary: &str, + tls_ca: bool, + l7: Option<(&str, &str)>, + ) -> Option { + if !self.agent_proposals.enabled() + || host.is_empty() + || port == 0 + || matches!( + host.to_ascii_lowercase().as_str(), + "localhost" | "localhost." + ) + || openshell_core::net::is_known_metadata_hostname(host) + || host + .parse::() + .is_ok_and(openshell_core::net::is_always_blocked_ip) + { + return None; + } + let key = (host.to_ascii_lowercase(), port); + let mut pending = self.auto_proposals.lock().await; + let endpoint = self.gateway_endpoint.as_deref()?; + let sandbox_name = self.sandbox_name.as_deref()?; + let workspace = self.workspace(); + if workspace.is_empty() { + return None; + } + let client = connect_gateway_for_rpc(endpoint, sandbox_name).await.ok()?; + client.set_workspace(workspace); + if let Some(id) = pending.get(&key) { + let chunks = client.get_draft_policy(sandbox_name, "").await.ok()?; + if chunks + .iter() + .any(|chunk| chunk.id == *id && chunk.status == "pending") + { + return Some(id.clone()); + } + pending.remove(&key); + } + let prefix = if tls_ca { + "advisor_ca" + } else { + "advisor_destination" + }; + let rule_name = format!("{prefix}_{}_{}", key.0.replace(['.', '-'], "_"), port); + let l7_path = l7.map(|(_, path)| path.split('?').next().unwrap_or(path)); + let rule = NetworkPolicyRule { + name: rule_name.clone(), + endpoints: vec![NetworkEndpoint { + host: key.0.clone(), + port: u32::from(port), + ports: vec![u32::from(port)], + advisor_proposed: true, + protocol: if l7.is_some() { + "rest".into() + } else { + String::new() + }, + enforcement: if l7.is_some() { + "enforce".into() + } else { + String::new() + }, + rules: l7 + .zip(l7_path) + .map_or_else(Vec::new, |((method, _), path)| { + vec![L7Rule { + allow: Some(L7Allow { + method: method.to_string(), + path: path.to_string(), + ..Default::default() + }), + }] + }), + ..Default::default() + }], + binaries: if binary.is_empty() || binary == "-" { + vec![] + } else { + vec![NetworkBinary { + path: binary.to_string(), + ..Default::default() + }] + }, + }; + let rationale = if tls_ca { + format!( + "Upstream TLS certificate verification failed for {}:{port}. Supply the service owner's CA PEM in upstream_ca_pem before approval.", + key.0 + ) + } else { + format!("Sandbox policy denied access to {}:{port}.", key.0) + }; + let chunk = PolicyChunk { + rule_name, + proposed_rule: Some(rule), + rationale, + stage: if tls_ca { + "upstream_tls" + } else { + "policy_denied" + } + .into(), + security_notes: if tls_ca { + "CA trust must be limited to this exact host and port; reviewer must supply a verified PEM.".into() + } else { + "Review destination and preserve baseline IP restrictions.".into() + }, + confidence: 1.0, + ..Default::default() + }; + let response = client + .submit_policy_analysis(sandbox_name, vec![], vec![chunk], vec![], "gateway_event") + .await + .ok()?; + let id = response.accepted_chunk_ids.into_iter().next()?; + emit_policy_propose_event(&id, &format!("supervisor_event {}:{port}", key.0)); + pending.insert(key, id.clone()); + Some(id) + } } pub async fn handle_forward_request( @@ -272,10 +401,9 @@ pub fn agent_next_steps(agent_proposals_enabled: bool) -> serde_json::Value { "url": format!("http://{host}{ROUTE_DENIALS}?last=5"), }, { - "action": "submit_proposal", - "method": "POST", - "url": format!("http://{host}{ROUTE_PROPOSALS}"), - "body_type": "PolicyMergeOperation", + "action": "wait_for_approval", + "method": "GET", + "url_template": format!("http://{host}{ROUTE_PROPOSALS}/{{proposal_id}}/wait?timeout=300"), }, ]) } @@ -1993,7 +2121,7 @@ mod tests { .filter_map(|v| v.get("action").and_then(serde_json::Value::as_str)) .collect(); assert!(actions.contains(&"read_skill")); - assert!(actions.contains(&"submit_proposal")); + assert!(actions.contains(&"wait_for_approval")); assert_eq!( steps[0]["alternate_path"], "$HOME/.claude/skills/policy-advisor/policy_advisor.md" @@ -2008,9 +2136,7 @@ mod tests { #[test] fn agent_guidance_points_to_policy_advisor_when_flag_on() { let guidance = agent_guidance_for(true).expect("guidance when proposals are enabled"); - assert!(guidance.contains("do not stop")); - assert!(guidance.contains("/etc/openshell/skills/policy_advisor.md")); - assert!(guidance.contains("$HOME/.claude/skills/policy-advisor/policy_advisor.md")); + assert!(guidance.contains("advisor.proposal_id")); assert!(guidance.contains("http://policy.local/v1/proposals")); assert!(guidance.contains("policy_reloaded: true")); } diff --git a/crates/openshell-supervisor-network/src/proxy.rs b/crates/openshell-supervisor-network/src/proxy.rs index f9405a9296..83ba8f6843 100644 --- a/crates/openshell-supervisor-network/src/proxy.rs +++ b/crates/openshell-supervisor-network/src/proxy.rs @@ -718,6 +718,7 @@ async fn handle_transparent_tcp_connection( // workspace is available here; matches the CONNECT path default when // policy-local context is absent. String::new(), + None, ); let middleware_gate = middleware_uninspectable_gate(&opa_engine, &ctx)?; if middleware_gate == crate::l7::middleware::UninspectableTrafficGate::Deny { @@ -1599,6 +1600,7 @@ async fn deny_connect_destination( decision: &EgressDecision, denial_tx: &Option>, activity_tx: &Option, + policy_local: Option<&PolicyLocalContext>, ) -> Result<()> { let detail = destination_denial_detail(denial.kind); ocsf_emit!(build_connect_destination_deny_ocsf_event( @@ -1619,13 +1621,20 @@ async fn deny_connect_destination( if denial.kind != DestinationDenialKind::DeclaredEndpoint { emit_activity(activity_tx, true, "ssrf"); } + let proposal_id = if let Some(local) = policy_local { + local + .propose_for_event(host, port, binary, false, None) + .await + } else { + None + }; respond( client, - &build_json_error_response( - 403, - "Forbidden", - "ssrf_denied", + &build_destination_deny_response( + host, + port, &format!("CONNECT {host}:{port} blocked: {detail}"), + proposal_id.as_deref(), ), ) .await @@ -1648,6 +1657,7 @@ async fn deny_forward_destination( decision: &EgressDecision, denial_tx: Option<&mpsc::UnboundedSender>, activity_tx: Option<&ActivitySender>, + policy_local: Option<&PolicyLocalContext>, ) -> Result<()> { let detail = destination_denial_detail(denial.kind); ocsf_emit!(build_forward_destination_deny_ocsf_event( @@ -1668,13 +1678,20 @@ async fn deny_forward_destination( if denial.kind != DestinationDenialKind::DeclaredEndpoint { emit_activity_simple(activity_tx, true, "ssrf"); } + let proposal_id = if let Some(local) = policy_local { + local + .propose_for_event(host, port, binary, false, Some((method, path))) + .await + } else { + None + }; respond( client, - &build_json_error_response( - 403, - "Forbidden", - "ssrf_denied", + &build_destination_deny_response( + host, + port, &format!("{method} {host}:{port} blocked: {detail}"), + proposal_id.as_deref(), ), ) .await @@ -1869,6 +1886,13 @@ async fn handle_tcp_connection( // Allowed connections are logged after the L7 config check (below) // so we can distinguish CONNECT (L4-only) from CONNECT_L7 (L7 follows). if matches!(decision.action, NetworkAction::Deny { .. }) { + let proposal_id = if let Some(policy_local) = policy_local_ctx.as_ref() { + policy_local + .propose_for_event(&host_lc, port, &binary_str, false, None) + .await + } else { + None + }; let event = NetworkActivityBuilder::new(openshell_ocsf::ctx::ctx()) .activity(ActivityId::Open) .action(ActionId::Denied) @@ -1898,10 +1922,13 @@ async fn handle_tcp_connection( emit_activity(&activity_tx, true, "connect_policy"); respond( &mut client, - &build_policy_deny_response( + &build_event_policy_deny_response( &format!("CONNECT {host_lc}:{port} not permitted by policy"), Some(&deny_reason), agent_proposals.enabled(), + &host_lc, + port, + proposal_id.as_deref(), ), ) .await?; @@ -1953,6 +1980,7 @@ async fn handle_tcp_connection( &decision, &denial_tx, &activity_tx, + policy_local_ctx.as_deref(), ) .await?; return Ok(()); @@ -1989,6 +2017,7 @@ async fn handle_tcp_connection( &decision, &denial_tx, &activity_tx, + policy_local_ctx.as_deref(), ) .await?; return Ok(()); @@ -2176,6 +2205,7 @@ async fn handle_tcp_connection( dynamic_credentials.clone(), agent_proposals, workspace, + policy_local_ctx.clone(), ); if effective_tls_skip { @@ -2239,9 +2269,52 @@ async fn handle_tcp_connection( // other matching nonempty CA has the same value. let endpoint_ca = supplemental_ca_from_configs(&decision.endpoint.policy_configs); let upstream_config = tls.endpoint_upstream_config(endpoint_ca)?; - let mut tls_upstream = - crate::l7::tls::tls_connect_upstream(upstream, &host_lc, &upstream_config) - .await?; + let mut tls_upstream = match crate::l7::tls::tls_connect_upstream( + upstream, + &host_lc, + &upstream_config, + ) + .await + { + Ok(stream) => stream, + Err(error) => { + let certificate_failure = + crate::l7::tls::is_certificate_verification_error(&error); + let proposal_id = if certificate_failure { + if let Some(policy_local) = policy_local_ctx.as_ref() { + policy_local + .propose_for_event(&host_lc, port, &binary_str, true, None) + .await + } else { + None + } + } else { + None + }; + let body = serde_json::json!({ + "error": "upstream_tls_failed", + "detail": if certificate_failure { + format!("Upstream TLS certificate verification failed for {host_lc}:{port}") + } else { + format!("Upstream TLS handshake failed for {host_lc}:{port}") + }, + "advisor": { + "event": if certificate_failure { "certificate_verification_failed" } else { "tls_handshake_failed" }, + "host": host_lc, + "port": port, + "remedy": if certificate_failure { "review_exact_host_ca_proposal" } else { "inspect_upstream_tls" }, + "proposal_id": proposal_id, + "next_action": if proposal_id.is_some() { "relay_to_user_and_wait_for_approval" } else { "report_failure_without_proposal" } + } + }); + tls_client + .write_all(&build_json_body_response(502, "Bad Gateway", body)) + .await + .into_diagnostic()?; + tls_client.flush().await.into_diagnostic()?; + return Ok(()); + } + }; let Some(relay_context) = relay::prepare_http_relay(l7_route, &opa_engine, &decision, &ctx) else { @@ -5006,6 +5079,13 @@ async fn handle_forward_proxy( let matched_policy = match &decision.action { NetworkAction::Allow { matched_policy } => matched_policy.clone(), NetworkAction::Deny { reason } => { + let proposal_id = if let Some(policy_local) = policy_local_ctx.as_ref() { + policy_local + .propose_for_event(&host_lc, port, &binary_str, false, None) + .await + } else { + None + }; ocsf_emit!(build_forward_policy_deny_ocsf_event( workload_addr, method, @@ -5030,10 +5110,13 @@ async fn handle_forward_proxy( emit_activity_simple(activity_tx, true, "forward_policy"); respond( client, - &build_policy_deny_response( + &build_event_policy_deny_response( &format!("{method} {host_lc}:{port}{telemetry_path} not permitted by policy"), - None, + Some(reason), agent_proposals.enabled(), + &host_lc, + port, + proposal_id.as_deref(), ), ) .await?; @@ -5161,6 +5244,7 @@ async fn handle_forward_proxy( dynamic_credentials.clone(), agent_proposals, workspace, + policy_local_ctx.clone(), ); l7_ctx.request_default_port = match scheme.as_str() { "http" => Some(80), @@ -5625,6 +5709,7 @@ async fn handle_forward_proxy( &decision, denial_tx, activity_tx, + policy_local_ctx.as_deref(), ) .await?; return Ok(()); @@ -5662,6 +5747,7 @@ async fn handle_forward_proxy( &decision, denial_tx, activity_tx, + policy_local_ctx.as_deref(), ) .await?; return Ok(()); @@ -6251,6 +6337,57 @@ fn build_policy_deny_response( build_json_body_response(403, "Forbidden", body) } +fn build_event_policy_deny_response( + detail: &str, + reason: Option<&str>, + enabled: bool, + host: &str, + port: u16, + proposal_id: Option<&str>, +) -> Vec { + let mut body = serde_json::json!({ + "error": "policy_denied", + "detail": detail, + "reason": reason.unwrap_or_default(), + "advisor": { + "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" } + } + }); + if let Some(guidance) = crate::policy_local::agent_guidance_for(enabled) { + body["agent_guidance"] = serde_json::json!(guidance); + } + build_json_body_response(403, "Forbidden", body) +} + +fn build_destination_deny_response( + host: &str, + port: u16, + detail: &str, + proposal_id: Option<&str>, +) -> Vec { + build_json_body_response( + 403, + "Forbidden", + serde_json::json!({ + "error": "ssrf_denied", + "detail": detail, + "advisor": { + "event": "destination_restriction", + "host": host, + "port": port, + "remedy": "review_allowed_ips_exception", + "proposal_id": proposal_id, + "next_action": if proposal_id.is_some() { "relay_to_user_and_wait_for_approval" } else { "report_failure_without_proposal" } + } + }), + ) +} + fn build_middleware_deny_response( policy_name: &str, denial: &openshell_supervisor_middleware::MiddlewareDenial, @@ -7022,7 +7159,10 @@ network_policies: assert_eq!(body["error"], "policy_denied"); let guidance = body["agent_guidance"].as_str().expect("guidance present"); assert!(guidance.contains("policy.local"), "guidance: {guidance}"); - assert!(guidance.contains("policy_advisor"), "guidance: {guidance}"); + assert!( + guidance.contains("advisor.proposal_id"), + "guidance: {guidance}" + ); let response = build_policy_deny_response( "CONNECT host.example:443 not permitted by policy", diff --git a/crates/openshell-supervisor-network/src/proxy/relay.rs b/crates/openshell-supervisor-network/src/proxy/relay.rs index d5d1828622..bef53fae36 100644 --- a/crates/openshell-supervisor-network/src/proxy/relay.rs +++ b/crates/openshell-supervisor-network/src/proxy/relay.rs @@ -38,6 +38,7 @@ pub(super) struct RelayContext<'a> { } /// Build the request-processing context shared by CONNECT and forward HTTP. +#[allow(clippy::too_many_arguments)] pub(super) fn http_context( decision: &EgressDecision, provider_credentials: Option, @@ -46,6 +47,7 @@ pub(super) fn http_context( dynamic_credentials: Option, agent_proposals: openshell_core::proposals::AgentProposals, workspace: String, + policy_local: Option>, ) -> L7EvalContext { // Provider-backed credentials must be acquired from the live state for // each request after middleware/token-grant awaits. Keep only the legacy @@ -89,6 +91,7 @@ pub(super) fn http_context( .map(|_| crate::l7::token_grant_injection::default_resolver()), agent_proposals, workspace, + policy_local, } } @@ -358,6 +361,7 @@ mod tests { token_grant_resolver: None, agent_proposals: openshell_core::proposals::AgentProposals::default(), workspace: String::new(), + policy_local: None, } } diff --git a/crates/openshell-supervisor-network/src/proxy/tests/compatibility.rs b/crates/openshell-supervisor-network/src/proxy/tests/compatibility.rs index 186d156086..dbfe352759 100644 --- a/crates/openshell-supervisor-network/src/proxy/tests/compatibility.rs +++ b/crates/openshell-supervisor-network/src/proxy/tests/compatibility.rs @@ -48,8 +48,13 @@ fn assert_json_response( assert!(headers.contains("Content-Type: application/json\r\n")); assert!(headers.contains(&format!("Content-Length: {}\r\n", body.len()))); assert!(headers.contains("Connection: close\r\n")); + let mut actual = serde_json::from_slice::(body).unwrap(); + if expected_error == "ssrf_denied" { + assert_eq!(actual["advisor"]["remedy"], "review_allowed_ips_exception"); + actual.as_object_mut().unwrap().remove("advisor"); + } assert_eq!( - serde_json::from_slice::(body).unwrap(), + actual, serde_json::json!({ "error": expected_error, "detail": expected_detail, @@ -100,6 +105,7 @@ async fn destination_denials_preserve_adapter_specific_wire_contracts() { &allowed_decision(EgressIntent::connect("target.example".to_string(), 8443)), &None, &None, + None, ) .await .unwrap(); @@ -133,6 +139,7 @@ async fn destination_denials_preserve_adapter_specific_wire_contracts() { )), None, None, + None, ) .await .unwrap(); diff --git a/crates/openshell-supervisor-process/src/skills/policy-advisor/SKILL.md b/crates/openshell-supervisor-process/src/skills/policy-advisor/SKILL.md index 5e2b9a924f..2546b4b72a 100644 --- a/crates/openshell-supervisor-process/src/skills/policy-advisor/SKILL.md +++ b/crates/openshell-supervisor-process/src/skills/policy-advisor/SKILL.md @@ -5,8 +5,8 @@ description: Use when an OpenShell sandbox returns policy_denied, mentions polic # OpenShell Policy Advisor -When a request fails with `policy_denied`, do not treat the denial as final if the user task still needs the request. Read `policy_advisor.md` beside this skill (also available at `/etc/openshell/skills/policy_advisor.md` on writable system installs), inspect `http://policy.local/v1/policy/current`, submit the narrowest proposal to `http://policy.local/v1/proposals`, wait on `/v1/proposals/{chunk_id}/wait?timeout=300`, and retry only after approval with `policy_reloaded: true`. +When a request fails with `policy_denied` or `upstream_tls_failed`, read the `advisor` object in the response. The supervisor creates a pending proposal and includes its `proposal_id`. Tell the user what failed and which proposal needs review. For API details, read `/etc/openshell/skills/policy_advisor.md`. Wait on `http://policy.local/v1/proposals/{proposal_id}/wait?timeout=300`; retry only after approval with `policy_reloaded: true`. For a self-signed internal HTTPS service, an endpoint proposal may include `upstream_ca_pem` containing the service owner's PEM CA certificate bundle. Scope it to the exact host and port. This requires developer review even in auto mode. -If an explicit proxy returns `200 Connection established` and the TLS handshake then resets, the destination may have an untrusted upstream certificate. Ask the user or service owner for the CA PEM; do not disable TLS verification or copy an unverified certificate from the failed connection. Once supplied, propose an exact host:port rule with `upstream_ca_pem`, wait for approval and policy reload, then retry without `--cacert` or `--insecure`. +For `upstream_tls_failed` with `certificate_verification_failed`, the draft has an empty `upstream_ca_pem` slot. Ask the user or service owner for the verified CA PEM so a reviewer can add it to the existing proposal. Do not disable TLS verification or copy an unverified certificate from the failed connection. If no `proposal_id` is present, report that proposal submission failed; do not claim a card exists. diff --git a/crates/openshell-supervisor-process/src/skills/policy_advisor.md b/crates/openshell-supervisor-process/src/skills/policy_advisor.md index db2737e6c7..2ad60f9678 100644 --- a/crates/openshell-supervisor-process/src/skills/policy_advisor.md +++ b/crates/openshell-supervisor-process/src/skills/policy_advisor.md @@ -1,13 +1,17 @@ # OpenShell Policy Advisor -Use this when OpenShell blocks a network request and the response or logs say -`policy_denied`. +Use this when OpenShell returns `policy_denied` or `upstream_tls_failed`. ## Goal -Draft the smallest policy proposal that allows the user's current task without -giving the sandbox broad new network access. The developer approves or rejects -the proposal; do not try to bypass policy. +Relay the supervisor's mechanical failure and pending proposal to the user. +The developer reviews the narrow rule; do not try to bypass policy. + +The response body includes `advisor.event`, `advisor.host`, `advisor.port`, +`advisor.remedy`, and `advisor.proposal_id`. The supervisor submits the draft +before returning the failure. A null proposal ID means submission failed; tell +the user that no pending card was confirmed. Repeated failures for one endpoint +reuse the same proposal during the sandbox session. ## Local API @@ -46,18 +50,23 @@ the service owner; never submit a private key. Keep normal TLS inspection enabled. A supplemental CA always requires developer review, including in auto mode. Retry only after approval and `policy_reloaded: true`. -An explicit proxy may return `200 Connection established` before the TLS -handshake resets. This can mean the supervisor could not verify the upstream -certificate. Ask the user or service owner for the CA PEM before proposing -trust. Do not use `--insecure`, `-k`, or an unverified certificate copied from -the failed connection. After approval and reload, retry without `--cacert`. +For an upstream certificate-verification failure, the supervisor returns a +structured 502 over the terminated client TLS connection and creates an +exact-host draft with an empty `upstream_ca_pem` slot. Ask the service owner +for a verified CA PEM so the reviewer can edit that draft. Approval is blocked +until a valid CA is supplied. Do not use `--insecure`, `-k`, or an unverified +certificate copied from the failed connection. After approval and reload, +retry without `--cacert`. ## Workflow -1. Read the denial response body. Use `layer`, `method`, `path`, `host`, - `port`, `binary`, `rule_missing`, and `detail` as evidence. -2. Fetch the current policy from `/v1/policy/current`. -3. Fetch recent denials from `/v1/denials` if the response body is incomplete. +1. Read the failure response body and its `advisor` object. Tell the user the + mechanical reason, the endpoint, and the pending proposal ID. +2. If a proposal ID exists, wait on `/v1/proposals/{proposal_id}/wait` and + retry after approval and `policy_reloaded: true`. +3. If submission failed, inspect `/v1/policy/current` and recent denials for + diagnostics. Report the failure clearly. Manual proposals remain available + through `POST /v1/proposals` when the supervisor cannot submit a draft. 4. Prefer L7 REST rules for REST APIs. **Proposals against hosts where no credential is in scope auto-approve** (see Auto-approval below). Any credentialed reach or capability change goes to human review — that is diff --git a/docs/sandboxes/policy-advisor.mdx b/docs/sandboxes/policy-advisor.mdx index 5911b32fb5..b848f5d55c 100644 --- a/docs/sandboxes/policy-advisor.mdx +++ b/docs/sandboxes/policy-advisor.mdx @@ -8,7 +8,7 @@ keywords: "Generative AI, Cybersecurity, Policy Advisor, Policy, Sandbox, policy position: 7 --- -Policy advisor lets a running sandboxed agent ask for a narrow network policy change after OpenShell denies a request. The agent submits a draft through `policy.local`, a developer approves or rejects it from outside the sandbox, and approved network policy hot-reloads into the same sandbox. +Policy advisor creates a narrow pending network policy proposal when the supervisor denies a request or cannot verify an upstream TLS certificate. The failure response includes an `advisor` object with the mechanical reason, endpoint, remedy, and proposal ID. A developer reviews the draft, and approved policy hot-reloads into the same sandbox. Policy advisor preserves OpenShell's default-deny posture. The structured rule is the approval contract, and the agent's rationale is supporting context. By default every accepted proposal lands in the draft inbox for human review. Opt-in [auto mode](#approval-modes) approves a proposal without a reviewer only when its [prover delta](#what-auto-approval-checks) is empty and the current draft rule produces no security notes. A prover finding or security note keeps the proposal pending for human review. @@ -45,7 +45,7 @@ openshell settings delete --global \ --yes ``` -Set the value before creating a sandbox when you want the first denied request to include policy advisor guidance. Running sandboxes poll settings and can enable the surface after startup, but startup enablement gives the agent the clearest first-denial path. +Set the value before creating a sandbox when you want the first denied request to create a proposal and include its ID in the failure response. Running sandboxes poll settings and can enable the surface after startup. ## Approval Modes @@ -96,12 +96,12 @@ When policy advisor is enabled, the sandbox supervisor turns on three agent-faci - It serves `http://policy.local` from inside the sandbox. - It adds `agent_guidance` and `next_steps` to L7 `policy_denied` response bodies so the agent can find the skill and local API. -The loop has seven steps: +The supervisor-driven loop is: 1. A sandboxed process attempts a network request that policy denies. -2. For inspected REST traffic, OpenShell returns a structured `403` body with fields such as `layer`, `host`, `port`, `binary`, `method`, `path`, `rule_missing`, `agent_guidance`, and `next_steps`. -3. The agent reads the policy advisor skill, inspects the current policy, and optionally reads recent denial log lines. -4. The agent submits one or more `addRule` proposals to `http://policy.local/v1/proposals`. +2. The supervisor submits a pending proposal through the existing gateway pipeline. Concurrent or repeated failures for the same host and port in one sandbox session reuse its proposal ID. +3. OpenShell returns a structured `403` denial body or a `502` upstream TLS failure body. Its `advisor` object names the endpoint, remedy, and pending `proposal_id`. +4. The agent relays that information to the user. For a certificate failure, the reviewer obtains a verified service-owner CA PEM and adds it to the draft's `upstream_ca_pem` field before approval. 5. The gateway turns the proposal into the exact effective-policy candidate it would apply. It preserves any existing L7 or provider-owned endpoint contract, adds the proposed binary as a sandbox overlay, validates the full merge, and runs the [policy prover](#what-auto-approval-checks) against that candidate. 6. The gateway stores the candidate, its prover result, any application error, and a review token tied to the live policy, provider rules, and credential metadata. Provider rules remain immutable inputs. 7. Before approval, the gateway cheaply recomputes the candidate token from live inputs. An unchanged token reuses the stored prover result. A changed token leaves the proposal pending with a refreshed candidate and requires a fresh review. Under `auto` mode, an unchanged candidate is approved only when the prover delta and security notes are empty. Under `manual` mode, every valid proposal lands in the draft inbox. @@ -128,6 +128,7 @@ OpenShell has two proposal paths: | Path | Source | Typical rule shape | |---|---|---| +| Supervisor event | A denied request or an upstream certificate-verification failure. | Creates one pending draft per host and port per sandbox session. A TLS draft has an exact-host CA slot; a REST denial can carry its method and path. | | Mechanistic mapper | Aggregated denial summaries from the sandbox. | Groups by host, port, and binary. If L7 request samples are available, it can draft REST method and path rules. Otherwise it drafts an L4 endpoint. | | Agent-authored proposal | The in-sandbox agent, using `policy.local`. | Usually a REST `addRule` with exact host, port, binary, method, and path from the structured denial. It can also omit `protocol` for endpoint-only access through the explicit proxy. | @@ -144,7 +145,7 @@ For example, a GitHub provider can explicitly declare `api.github.com:443` for r Provenance does not hide a real endpoint conflict. The same two declarations still fail validation if they disagree on connection or request-processing behavior that must have one value, such as TLS mode, `allowed_ips`, an equally specific L7 protocol or parser contract, credential binding, or enforcement mode. Authorization fields such as compatible allow and deny rules can combine. -An exact-host `upstream_ca_pem` rule may augment a broader allow rule that has no supplemental CA, including a public HTTPS allow rule on port 443. If the CA rule omits `allowed_ips`, the existing explicit IP allowlist still applies. The gateway rejects two different CAs or different explicit IP allowlists for one destination, and every supplemental CA requires human review. If a proxy CONNECT succeeds but the TLS handshake resets, ask the service owner for the CA PEM before proposing the exact host and port; do not disable certificate verification. +An exact-host `upstream_ca_pem` rule may augment a broader allow rule that has no supplemental CA, including a public HTTPS allow rule on port 443. If the CA rule omits `allowed_ips`, the existing explicit IP allowlist still applies. The gateway rejects two different CAs or different explicit IP allowlists for one destination, and every supplemental CA requires human review. When upstream certificate verification fails, the supervisor creates the exact-host draft with an empty CA slot. Obtain the verified CA PEM from the service owner and add it to that draft before approval; do not disable certificate verification. Exact-host SSRF trust requires an exact endpoint and the matching binary identity to be explicit in the same rule. An advisor-only endpoint or binary does not create that stronger trust. For example: