diff --git a/GOVERNANCE.md b/GOVERNANCE.md new file mode 100644 index 0000000000..e2c7cfbbef --- /dev/null +++ b/GOVERNANCE.md @@ -0,0 +1,166 @@ +# OpenShell Project Governance + +OpenShell is dedicated to creating safe, private, policy-governed runtimes for autonomous AI agents. This document explains how the project is governed. + +## Values + +OpenShell and its leadership embrace the following values: + +- **Openness:** Communication and decision-making happen in the open and remain discoverable for future reference. As much as possible, discussions and work take place in public forums and repositories. +- **Fairness:** All stakeholders may provide feedback and submit contributions. The project considers contributions on their merits. +- **Community over product or company:** Sustaining and growing the community takes priority over shipping code or advancing one sponsor's organizational goals. Contributors participate as individuals. +- **Vendor neutrality:** No single organization controls project direction or decisions. Maintainer selection, roadmap priorities, and release decisions are based on the interests of the project rather than employer affiliation. +- **Inclusivity:** Different perspectives and skills make OpenShell better. The project provides a welcoming and respectful environment for participation. +- **Participation:** Responsibilities and privileges are earned through sustained participation, demonstrated judgment, and earned community trust. + +## Contributor Ladder + +OpenShell uses a contributor ladder to provide a path from participation to project leadership. Movement through the ladder reflects increasing trust, responsibility, and project-wide stewardship. Contributions may include code, documentation, design, testing, issue triage, reviews, release work, community support, and other work that advances the project. + +### Contributor + +A Contributor is anyone who participates constructively in the OpenShell community. + +Contributors are responsible for: + +- Following the project Code of Conduct and contribution guidelines. +- Taking responsibility for the correctness and provenance of their work, including work created with AI tools or agents. +- Engaging constructively with reviewers, users, and other contributors. + +Contributors may: + +- Participate in project discussions. +- Submit issues, designs, code, documentation, tests, and reviews. +- Help other contributors and users. + +### Reviewer + +A Reviewer is a trusted Contributor with demonstrated knowledge in one or more project areas. Reviewers help maintain quality and provide consistent, actionable feedback, but do not receive project-wide merge or voting rights by virtue of this role. + +Reviewers are responsible for: + +- Regularly reviewing contributions in their areas of knowledge. +- Reviewing for correctness, security, maintainability, tests, documentation, and consistency with project direction. +- Supporting new and occasional contributors and helping them improve useful contributions. +- Escalating decisions that require broader expertise or project-wide input. + +A Reviewer demonstrates: + +- A record of constructive, technically valuable reviews. +- A working knowledge of the relevant project areas and their operational context. +- Reliable collaboration and follow-through. +- Judgment exercised for the good of OpenShell, independent of employer, product, or team interests. + +An existing Maintainer may nominate a Contributor to become a Reviewer. A simple majority vote of the Maintainers approves the nomination. Maintainers may grant the GitHub permissions needed for the Reviewer's responsibilities. + +### Maintainer + +Maintainers have project-wide write, merge, and voting privileges. They are collectively responsible for steering OpenShell in a positive direction and for managing project resources and contributor access. The current Maintainers are listed in [MAINTAINERS.md](MAINTAINERS.md). + +Maintainer status is held by individual humans. AI agents, automated systems, service accounts, companies, and other organizations cannot be Maintainers or exercise Maintainer votes. + +Maintainers are responsible for: + +- Reviewing and merging contributions across the project. +- Protecting project quality, security, architectural coherence, and long-term maintainability. +- Participating in project-wide technical, governance, roadmap, and release decisions. +- Seeking review from the people most knowledgeable about affected areas. +- Mentoring Contributors, Reviewers, and prospective Maintainers. +- Supporting contributions that benefit the broader community, including work outside their employer's immediate priorities. +- Following through on regressions and other issues arising from decisions they approve. +- Representing OpenShell and its community responsibly. + +Maintainers may: + +- Approve and merge changes after applicable review and automated checks. +- Vote on project matters. +- Nominate Contributors for Reviewer or Maintainer roles. +- Represent OpenShell in public and communicate with the CNCF on behalf of the project. + +The collective team of Maintainers is the Maintainer Council, the governing body for OpenShell. + +## Becoming a Maintainer + +Maintainer status reflects established trust and readiness to steward the whole project. Activity metrics are an eligibility floor, not a scorecard, an automatic promotion mechanism, or sufficient evidence of readiness. + +A candidate must first meet all of the following minimum participation requirements: + +- At least three months of sustained participation in OpenShell discussions, contributions, reviews, or other project work. +- At least three substantial pull requests merged into the project. +- Constructive reviews of at least five substantial pull requests. +- Demonstrated contribution to the general core product through reviews and feedback on third-party contributions beyond a feature, product, or project primarily needed by the candidate or their organization. + +For these requirements, a substantial pull request is work that requires meaningful technical or project judgment. Mechanical changes, generated volume, lines changed, and a series of closely related pull requests do not by themselves demonstrate substance. Maintainers evaluate the scope, difficulty, quality, impact, and judgment shown by the work in context. + +Meeting the minimum participation requirements only establishes eligibility. A candidate must also demonstrate: + +- Deep understanding of OpenShell in one or more project areas, including how those areas interact with the broader platform. +- Sound technical and product judgment, including an ability to identify risk, evaluate tradeoffs, and preserve long-term maintainability. +- Consistently high-quality implementation or documentation work and technically useful reviews. +- Understanding of project architecture, contribution policies, testing, security expectations, review practices, and development workflows. +- Reliable collaboration, respectful communication, and follow-through. +- Support for new and occasional contributors. +- A community-first perspective and an ability to act independently of the candidate's employer, friends, team, product, or organizational priorities. +- Personal accountability for contributions and reviews, including the ability to explain, validate, and take responsibility for work produced with AI tools or agents. +- Direct participation in OpenShell community calls, sufficient for the community to know the person behind the contributions and for Maintainers to assess the candidate's understanding, judgment, communication, and accountability. + +The use of AI or agents neither qualifies nor disqualifies a candidate. The Maintainer Council evaluates the candidate's demonstrated understanding, judgment, accountability, community participation, and the value they add to the project's human review and decision-making capacity. Raw contribution velocity, lines of code, and activity counts beyond the eligibility floor are not proxies for those qualities. + +Community call attendance is qualitative evidence, not an attendance quota or substitute for the other requirements. Candidates who cannot reasonably attend the regular call because of time zone, accessibility, or similar constraints may arrange equivalent direct, synchronous participation with community members and Maintainers. Video participation is not required. + +An existing Maintainer must nominate a candidate by sending a message to the [project mailing list](mailto:openshell-maintainers@ai-openshell.org). A simple majority vote of all active Maintainers approves the nomination. Nominations are evaluated without prejudice to employer or demographics and should consider the organizational diversity of the Maintainer Council. + +Approved Maintainers receive the GitHub rights needed for the role, are added to [MAINTAINERS.md](MAINTAINERS.md), and are invited to Maintainer communication channels. + +## Removing a Maintainer + +A Maintainer may resign at any time when they can no longer fulfill the role. + +A Maintainer may also be removed for inactivity, persistent failure to fulfill Maintainer responsibilities, a Code of Conduct violation, behavior detrimental to the project, or other cause. Inactivity means six months of very low or no project activity without a definite plan to resume active participation. Non-code project work counts as activity. + +Removal requires a two-thirds vote of the remaining active Maintainers. A Maintainer whose removal is under consideration may participate in the discussion but does not vote on their own removal. + +### Emeritus Maintainers + +Depending on the circumstances of a resignation or removal, a Maintainer may move to Emeritus status. Emeritus Maintainers are recognized for past contributions and may be consulted on project matters, but they do not have voting rights or merge access. They are listed separately in [MAINTAINERS.md](MAINTAINERS.md). + +An Emeritus Maintainer may return to active status through the standard Maintainer nomination and voting process, provided they meet the current requirements and can commit to active participation. + +## Meetings and Communication + +Project governance ordinarily takes place through public GitHub issues, discussions, and pull requests so decisions are visible and discoverable. Anyone interested in OpenShell may join the [OpenShell Community Google Group](https://groups.google.com/a/ai-openshell.org/g/openshell-community/about) to receive the community meeting invitation and view the community meeting agenda. Consequential decisions made during a meeting must be recorded in a public project artifact. + +Maintainers may meet privately when handling security reports, Code of Conduct reports, personnel matters, or other sensitive information. All Maintainers must be invited except anyone whose participation would create a conflict of interest, including a Maintainer who is the subject of a report. + +## CNCF Resources + +Any Maintainer may propose a request for CNCF resources through the [project mailing list](mailto:openshell-maintainers@ai-openshell.org) or a project meeting. A simple majority vote of active Maintainers approves the request. The Maintainer Council may delegate CNCF coordination to a non-Maintainer community member and arrange the access needed for that work. + +## Code of Conduct + +OpenShell follows the [CNCF Code of Conduct](https://github.com/cncf/foundation/blob/main/code-of-conduct.md). The Maintainer Council handles reports privately and coordinates with the CNCF Code of Conduct Committee when appropriate. If a Maintainer is directly involved in a report, that Maintainer is excluded from its handling, and the remaining Maintainers designate at least two uninvolved Maintainers to coordinate the response. + +## Security Response + +Security reports are handled according to the project [security policy](SECURITY.md). The Maintainer Council appoints or recognizes the people responsible for coordinating security responses and reviews the response process and membership at least annually. + +## Voting + +OpenShell uses [lazy consensus](https://community.apache.org/committers/decisionMaking.html#lazy-consensus) for most decisions: a proposal proceeds when there is general agreement and no unresolved, reasoned objection. Maintainers should allow time appropriate to the impact and urgency of a decision so that affected contributors across time zones can participate. + +Any Maintainer may call for a formal vote on the [project mailing list](mailto:openshell-maintainers@ai-openshell.org) or at a project meeting. Unless this document states otherwise, a proposal requires a simple majority of all active Maintainers to pass. A two-thirds vote requires support from at least two-thirds of all active Maintainers. Maintainers must disclose relevant conflicts of interest and recuse themselves when they cannot act solely in the project's interest. + +## Evolving This Governance + +The Maintainer Council should revisit this model as OpenShell grows. Signals that the project may need working groups, area-specific approvers, subproject governance, organization-balanced voting, or an elected steering body include: + +- Decisions routinely stall because the Maintainer Council is too large or different project areas need delegated authority. +- Contributors cannot find a clear path to greater responsibility. +- One organization dominates project decisions or Maintainer membership. +- Subprojects develop distinct contributor communities or release cadences. + +Such changes are a sign of project growth rather than governance failure. + +## Modifying This Governance + +Changes to this governance document and its supporting governance documents require a two-thirds vote of all active Maintainers. diff --git a/architecture/gateway.md b/architecture/gateway.md index ba325ccc2c..769f57f6a0 100644 --- a/architecture/gateway.md +++ b/architecture/gateway.md @@ -336,6 +336,10 @@ This keeps the gateway data model portable across storage backends and leaves room for future stores that can provide the same object, label, version, and scope semantics. +For in-memory SQLite, the adapter retains a dedicated keepalive connection for +the store lifetime. Operational connection replacement therefore preserves the +shared in-memory schema and objects instead of creating an empty database. + The SQLite adapter tightens the on-disk database file to mode `0o600` on every connect so that provider API keys, SSH session tokens, and sandbox metadata are not readable by other local users on shared hosts. The same restriction is diff --git a/architecture/security-policy.md b/architecture/security-policy.md index 9203ba3178..62f5837e70 100644 --- a/architecture/security-policy.md +++ b/architecture/security-policy.md @@ -97,6 +97,13 @@ raw relay by default. A `protocol: rest` endpoint can opt in to after an allowed `101` upgrade; server-to-client traffic and all other upgraded protocols remain raw passthrough. +A `protocol: tcp` hostname is a connection-routing constraint, not an +application-authority boundary. Transparent capture validates the approved DNS +name, pinned destination address, port, and calling binary before opening the +stream, but it does not inspect TLS SNI, HTTP `Host`, or another protocol-level +destination. Compatible shared infrastructure can therefore let a client +select another tenant, virtual host, or service behind the approved front door. + ## Credentialed Endpoints OpenShell keeps provider credentials on paths it can inspect or rewrite by @@ -216,6 +223,12 @@ through the proposal loop instead of treating the denial as terminal. 1. **Submit.** Both proposers POST through the same `SubmitPolicyAnalysis` path. Each chunk is persisted with its `analysis_mode` for audit provenance. + Agent-authored chunks cannot request `protocol: tcp` or `tls: skip`; the + sandbox-local API rejects those transport choices for immediate feedback, + and the gateway repeats the check before persistence. + Omitted-protocol endpoints remain available through the explicit proxy with + default TLS termination and HTTP authority checks. Administrators can still + author native TCP and raw TLS policy directly. 2. **Build and validate the candidate.** The gateway first canonicalizes a mechanistic proposal against the live effective policy. If an endpoint is already governed by an inspected or provider-owned contract, the candidate diff --git a/crates/openshell-core/src/settings.rs b/crates/openshell-core/src/settings.rs index b7bf72c3d3..84702c9aa0 100644 --- a/crates/openshell-core/src/settings.rs +++ b/crates/openshell-core/src/settings.rs @@ -106,6 +106,14 @@ pub const PROPOSAL_APPROVAL_MODE_KEY: &str = "proposal_approval_mode"; /// fail-closes on unknown persisted values for defense in depth. pub const PROPOSAL_APPROVAL_MODE_VALUES: &[&str] = &["manual", "auto"]; +/// Allowed values for `ocsf_schema_version`. +/// +/// Only versions with actual downgrade transforms in +/// `openshell_ocsf::format::downgrade` are accepted. Empty string disables +/// downgrade (equivalent to unsetting the key). Malformed or unsupported +/// versions (e.g. `"banana"`, `"1.6"`) are rejected at configure time. +pub const OCSF_SCHEMA_VERSION_VALUES: &[&str] = &["", "1.1", "1.3"]; + pub const REGISTERED_SETTINGS: &[RegisteredSetting] = &[ // When true the sandbox writes OCSF v1.8.0 JSONL records to // `/var/log/openshell-ocsf*.log` (daily rotation, 3 files) in addition @@ -115,6 +123,14 @@ pub const REGISTERED_SETTINGS: &[RegisteredSetting] = &[ kind: SettingValueKind::Bool, allowed_string_values: None, }, + // Target OCSF schema version for JSONL downgrade. When set (e.g. "1.1" + // or "1.3"), the JSONL layer strips fields and profiles that don't exist + // in the target version. Empty or unset means no downgrade. + RegisteredSetting { + key: "ocsf_schema_version", + kind: SettingValueKind::String, + allowed_string_values: Some(OCSF_SCHEMA_VERSION_VALUES), + }, // Sandbox-level opt-in for the agent-driven policy proposal surface. // See AGENT_POLICY_PROPOSALS_ENABLED_KEY for details. Defaults to false. RegisteredSetting { @@ -160,8 +176,9 @@ pub fn parse_bool_like(raw: &str) -> Option { #[cfg(test)] mod tests { use super::{ - PROPOSAL_APPROVAL_MODE_KEY, PROPOSAL_APPROVAL_MODE_VALUES, REGISTERED_SETTINGS, - RegisteredSetting, SettingValueKind, parse_bool_like, registered_keys_csv, setting_for_key, + OCSF_SCHEMA_VERSION_VALUES, PROPOSAL_APPROVAL_MODE_KEY, PROPOSAL_APPROVAL_MODE_VALUES, + REGISTERED_SETTINGS, RegisteredSetting, SettingValueKind, parse_bool_like, + registered_keys_csv, setting_for_key, }; #[test] @@ -226,6 +243,36 @@ mod tests { } } + // ---- ocsf_schema_version validation ---- + + #[test] + fn ocsf_schema_version_accepts_supported_versions() { + let setting = setting_for_key("ocsf_schema_version") + .expect("ocsf_schema_version should be registered"); + assert_eq!(setting.kind, SettingValueKind::String); + assert_eq!( + setting.allowed_string_values, + Some(OCSF_SCHEMA_VERSION_VALUES) + ); + assert!(setting.validate_string_value("").is_ok()); + assert!(setting.validate_string_value("1.1").is_ok()); + assert!(setting.validate_string_value("1.3").is_ok()); + } + + #[test] + fn ocsf_schema_version_rejects_malformed_and_unsupported() { + let setting = setting_for_key("ocsf_schema_version") + .expect("ocsf_schema_version should be registered"); + for bad in [ + "banana", "1.6", "1.5", "1.7", "1.7.0", "1.1.0", "2.0", " 1.1", "1.1 ", "v1.1", + ] { + let err = setting + .validate_string_value(bad) + .expect_err(&format!("expected '{bad}' to be rejected")); + assert_eq!(err, OCSF_SCHEMA_VERSION_VALUES); + } + } + // ---- parse_bool_like ---- #[test] diff --git a/crates/openshell-ocsf/src/format/downgrade.rs b/crates/openshell-ocsf/src/format/downgrade.rs new file mode 100644 index 0000000000..97f2fe88ea --- /dev/null +++ b/crates/openshell-ocsf/src/format/downgrade.rs @@ -0,0 +1,248 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! OCSF schema version downgrade filter. +//! +//! Transforms serialized OCSF JSON events to conform to older schema versions +//! by stripping fields and profiles that don't exist in the target version. + +use serde_json::Value; + +/// Fields to strip when downgrading to v1.3.0 or earlier. +const STRIP_FOR_V1_3: &[&str] = &["ai_model", "container", "observation_point_id"]; + +/// Profile names to remove from `metadata.profiles` when downgrading to v1.3.0 or earlier. +const STRIP_PROFILES_V1_3: &[&str] = &["ai_operation", "container"]; + +/// Downgrade a serialized OCSF event to the target schema version. +/// +/// Modifies the JSON in place: strips fields that don't exist in the target +/// version, removes unknown profile names from `metadata.profiles`, and +/// rewrites `metadata.version` to match. +/// +/// Returns `true` if the event was modified, `false` if no changes were needed +/// (target is current version or newer). +pub fn downgrade_event(event: &mut Value, target_version: &str) -> bool { + let target = parse_version(target_version); + let v1_3 = (1, 3, 0); + + if target >= parse_version(crate::OCSF_VERSION) { + return false; + } + + let Some(obj) = event.as_object_mut() else { + return false; + }; + + let mut modified = false; + + if target <= v1_3 { + for field in STRIP_FOR_V1_3 { + if obj.remove(*field).is_some() { + modified = true; + } + } + + if let Some(profiles) = obj + .get_mut("metadata") + .and_then(Value::as_object_mut) + .and_then(|m| m.get_mut("profiles")) + .and_then(Value::as_array_mut) + { + let before = profiles.len(); + profiles.retain(|p| !p.as_str().is_some_and(|s| STRIP_PROFILES_V1_3.contains(&s))); + if profiles.len() != before { + modified = true; + } + } + } + + if let Some(metadata) = obj.get_mut("metadata").and_then(Value::as_object_mut) { + let original_version = metadata + .get("version") + .and_then(Value::as_str) + .unwrap_or(crate::OCSF_VERSION) + .to_string(); + metadata.insert( + "version".to_string(), + Value::String(target_version.to_string()), + ); + modified = true; + + let unmapped = obj + .entry("unmapped") + .or_insert_with(|| Value::Object(serde_json::Map::new())); + if let Some(u) = unmapped.as_object_mut() { + u.insert( + "downgraded_from".to_string(), + Value::String(original_version), + ); + } + } + + modified +} + +fn parse_version(v: &str) -> (u32, u32, u32) { + let parts: Vec = v.split('.').filter_map(|s| s.parse().ok()).collect(); + ( + parts.first().copied().unwrap_or(0), + parts.get(1).copied().unwrap_or(0), + parts.get(2).copied().unwrap_or(0), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn test_event() -> Value { + serde_json::json!({ + "class_uid": 4002, + "class_name": "HTTP Activity", + "time": 1_234_567_890, + "severity_id": 1, + "metadata": { + "version": crate::OCSF_VERSION, + "profiles": ["security_control", "network_proxy", "container", "host"] + }, + "device": {"hostname": "sandbox-1"}, + "container": {"name": "test-sandbox"}, + "observation_point_id": 2, + "unmapped": {"key": "value"} + }) + } + + #[test] + fn test_downgrade_to_v1_3_strips_fields() { + let mut event = test_event(); + let modified = downgrade_event(&mut event, "1.3.0"); + + assert!(modified); + assert!(event.get("container").is_none()); + assert!(event.get("observation_point_id").is_none()); + assert!(event.get("device").is_some()); + assert!(event.get("unmapped").is_some()); + } + + #[test] + fn test_downgrade_to_v1_1_strips_fields() { + let mut event = test_event(); + let modified = downgrade_event(&mut event, "1.1.0"); + + assert!(modified); + assert!(event.get("container").is_none()); + assert!(event.get("observation_point_id").is_none()); + } + + #[test] + fn test_downgrade_strips_profiles() { + let mut event = test_event(); + downgrade_event(&mut event, "1.3.0"); + + let profiles = event["metadata"]["profiles"].as_array().unwrap(); + assert!(!profiles.iter().any(|p| p == "container")); + assert!(profiles.iter().any(|p| p == "security_control")); + assert!(profiles.iter().any(|p| p == "host")); + } + + #[test] + fn test_downgrade_rewrites_version() { + let mut event = test_event(); + downgrade_event(&mut event, "1.1.0"); + + assert_eq!(event["metadata"]["version"], "1.1.0"); + assert_eq!(event["unmapped"]["downgraded_from"], crate::OCSF_VERSION); + } + + #[test] + fn test_no_downgrade_for_current_version() { + let mut event = test_event(); + let modified = downgrade_event(&mut event, crate::OCSF_VERSION); + + assert!(!modified); + assert_eq!(event["metadata"]["version"], crate::OCSF_VERSION); + } + + #[test] + fn test_no_downgrade_for_newer_version() { + let mut event = test_event(); + let modified = downgrade_event(&mut event, "1.9.0"); + + assert!(!modified); + } + + #[test] + fn test_downgrade_strips_ai_model_when_present() { + let mut event = serde_json::json!({ + "class_uid": 6003, + "metadata": { + "version": "1.8.0", + "profiles": ["container", "host", "ai_operation"] + }, + "ai_model": {"name": "claude-3-haiku", "ai_provider": "anthropic"}, + "unmapped": {"latency_ms": 701} + }); + let modified = downgrade_event(&mut event, "1.3.0"); + + assert!(modified); + assert!(event.get("ai_model").is_none()); + assert!( + !event["metadata"]["profiles"] + .as_array() + .unwrap() + .iter() + .any(|p| p == "ai_operation") + ); + assert_eq!(event["metadata"]["version"], "1.3.0"); + assert_eq!(event["unmapped"]["downgraded_from"], "1.8.0"); + assert_eq!(event["unmapped"]["latency_ms"], 701); + } + + #[test] + fn test_downgrade_creates_unmapped_when_absent() { + let mut event = serde_json::json!({ + "class_uid": 4001, + "metadata": { + "version": crate::OCSF_VERSION, + "profiles": ["container"] + }, + "container": {"name": "sandbox-1"} + }); + let modified = downgrade_event(&mut event, "1.1.0"); + + assert!(modified); + assert_eq!(event["unmapped"]["downgraded_from"], crate::OCSF_VERSION); + } + + #[test] + fn test_downgrade_rewrites_version_without_strippable_fields() { + let mut event = serde_json::json!({ + "class_uid": 0, + "metadata": { + "version": crate::OCSF_VERSION, + "profiles": ["host"] + } + }); + + let modified = downgrade_event(&mut event, "1.3.0"); + + assert!(modified); + assert_eq!(event["metadata"]["version"], "1.3.0"); + assert_eq!(event["unmapped"]["downgraded_from"], crate::OCSF_VERSION); + } + + #[test] + fn test_no_downgrade_omits_breadcrumb() { + let mut event = test_event(); + downgrade_event(&mut event, crate::OCSF_VERSION); + + assert!( + event + .get("unmapped") + .and_then(Value::as_object) + .and_then(|u| u.get("downgraded_from")) + .is_none() + ); + } +} diff --git a/crates/openshell-ocsf/src/format/mod.rs b/crates/openshell-ocsf/src/format/mod.rs index 084a013d94..17518a5617 100644 --- a/crates/openshell-ocsf/src/format/mod.rs +++ b/crates/openshell-ocsf/src/format/mod.rs @@ -3,5 +3,6 @@ //! OCSF event formatters: shorthand (human-readable) and JSONL. +pub mod downgrade; pub mod jsonl; pub mod shorthand; diff --git a/crates/openshell-ocsf/src/tracing_layers/jsonl_layer.rs b/crates/openshell-ocsf/src/tracing_layers/jsonl_layer.rs index 920483700a..9414c74172 100644 --- a/crates/openshell-ocsf/src/tracing_layers/jsonl_layer.rs +++ b/crates/openshell-ocsf/src/tracing_layers/jsonl_layer.rs @@ -12,6 +12,7 @@ use tracing::Subscriber; use tracing_subscriber::Layer; use tracing_subscriber::layer::Context; +use crate::format::downgrade::downgrade_event; use crate::tracing_layers::event_bridge::{OCSF_TARGET, clone_current_event}; /// A tracing `Layer` that intercepts OCSF events and writes JSONL output. @@ -23,9 +24,15 @@ use crate::tracing_layers::event_bridge::{OCSF_TARGET, clone_current_event}; /// `false`, the layer short-circuits without writing. This allows the sandbox /// to hot-toggle OCSF JSONL output at runtime via the `ocsf_json_enabled` /// setting without rebuilding the subscriber. +/// +/// An optional target schema version can be set via +/// [`with_target_version`](Self::with_target_version). When set, events are +/// downgraded to the target version before writing (stripping fields and +/// profiles that don't exist in older schema versions). pub struct OcsfJsonlLayer { writer: Mutex, enabled: Option>, + target_version: Option>>, } impl OcsfJsonlLayer { @@ -35,6 +42,7 @@ impl OcsfJsonlLayer { Self { writer: Mutex::new(writer), enabled: None, + target_version: None, } } @@ -47,6 +55,16 @@ impl OcsfJsonlLayer { self.enabled = Some(flag); self } + + /// Attach a shared target schema version for downgrade filtering. + /// + /// When set, events are downgraded to the target version before writing. + /// The version can be changed at runtime via the shared mutex. + #[must_use] + pub fn with_target_version(mut self, version: Arc>) -> Self { + self.target_version = Some(version); + self + } } impl Layer for OcsfJsonlLayer @@ -67,9 +85,29 @@ where } if let Some(ocsf_event) = clone_current_event() - && let Ok(line) = ocsf_event.to_json_line() && let Ok(mut w) = self.writer.lock() { + let line = if let Some(ref target) = self.target_version + && let Ok(version) = target.lock() + && !version.is_empty() + { + let Ok(mut json) = serde_json::to_value(&ocsf_event) else { + return; + }; + downgrade_event(&mut json, &version); + match serde_json::to_string(&json) { + Ok(mut s) => { + s.push('\n'); + s + } + Err(_) => return, + } + } else { + match ocsf_event.to_json_line() { + Ok(l) => l, + Err(_) => return, + } + }; let _ = w.write_all(line.as_bytes()); } } diff --git a/crates/openshell-policy/src/l7_validate.rs b/crates/openshell-policy/src/l7_validate.rs index d60491c4bb..fe07df123f 100644 --- a/crates/openshell-policy/src/l7_validate.rs +++ b/crates/openshell-policy/src/l7_validate.rs @@ -49,6 +49,26 @@ pub fn is_explicit_tcp_protocol(protocol: &str) -> bool { protocol.eq_ignore_ascii_case("tcp") } +/// Reject transport choices that an in-sandbox agent must not grant itself. +/// +/// An omitted protocol remains allowed: it uses the established explicit +/// proxy, which canonicalizes forward HTTP authorities and terminates TLS by +/// default. Native transparent TCP and `tls: skip` bypass those application +/// authority checks, so only an administrator may author them directly. +pub fn agent_authored_transport_rejection(protocol: &str, tls: &str) -> Option<&'static str> { + if is_explicit_tcp_protocol(protocol) { + return Some( + "agent-authored proposals cannot request protocol tcp; ask an administrator to add native TCP access explicitly", + ); + } + if tls.eq_ignore_ascii_case("skip") { + return Some( + "agent-authored proposals cannot request tls: skip; ask an administrator to add raw TLS access explicitly", + ); + } + None +} + /// Reject additional L7-only fields represented outside /// [`L7EndpointFields`] by the runtime and provider-profile schemas. /// @@ -69,6 +89,24 @@ pub fn validate_explicit_tcp_additional_fields( )] } +#[cfg(test)] +mod agent_transport_tests { + use super::agent_authored_transport_rejection; + + #[test] + fn omitted_protocol_with_default_tls_remains_available_to_agents() { + assert_eq!(agent_authored_transport_rejection("", ""), None); + } + + #[test] + fn agent_cannot_request_native_tcp_or_skip_tls_inspection() { + assert!(agent_authored_transport_rejection("tcp", "").is_some()); + assert!(agent_authored_transport_rejection("TCP", "terminate").is_some()); + assert!(agent_authored_transport_rejection("", "skip").is_some()); + assert!(agent_authored_transport_rejection("rest", "SKIP").is_some()); + } +} + /// Fields extracted from an endpoint definition needed for L7 semantic /// validation. Both profile lint and the runtime validator construct this /// from their own data representation. diff --git a/crates/openshell-policy/src/lib.rs b/crates/openshell-policy/src/lib.rs index 5be8173e3e..3dcbdf3d32 100644 --- a/crates/openshell-policy/src/lib.rs +++ b/crates/openshell-policy/src/lib.rs @@ -37,8 +37,8 @@ pub use compose::{ is_provider_rule_name, provider_rule_name, strip_provider_rule_names, }; pub use l7_validate::{ - L7EndpointFields, L7Protocol, validate_explicit_tcp_additional_fields, - validate_l7_endpoint_semantics, + L7EndpointFields, L7Protocol, agent_authored_transport_rejection, + validate_explicit_tcp_additional_fields, validate_l7_endpoint_semantics, }; pub use merge::{ PolicyMergeError, PolicyMergeOp, PolicyMergeResult, PolicyMergeWarning, diff --git a/crates/openshell-sandbox/src/lib.rs b/crates/openshell-sandbox/src/lib.rs index 41c6ca3c94..7afae200b5 100644 --- a/crates/openshell-sandbox/src/lib.rs +++ b/crates/openshell-sandbox/src/lib.rs @@ -124,6 +124,7 @@ pub async fn run_sandbox( _health_port: u16, inference_routes: Option, ocsf_enabled: Arc, + ocsf_schema_version: Arc>, network_enabled: bool, process_enabled: bool, upstream_proxy_args: openshell_supervisor_network::upstream_proxy::UpstreamProxyArgs, @@ -744,6 +745,7 @@ pub async fn run_sandbox( let poll_endpoint = endpoint.to_string(); let poll_engine = engine.clone(); let poll_ocsf_enabled = ocsf_enabled.clone(); + let poll_ocsf_schema_version = ocsf_schema_version.clone(); let poll_pid = entrypoint_pid.clone(); let poll_provider_credentials = provider_credentials.clone(); let poll_policy_local = networking.as_ref().map(|n| n.policy_local_ctx.clone()); @@ -759,6 +761,7 @@ pub async fn run_sandbox( entrypoint_pid: poll_pid, interval_secs: poll_interval_secs, ocsf_enabled: poll_ocsf_enabled, + ocsf_schema_version: poll_ocsf_schema_version, provider_credentials: poll_provider_credentials, policy_local_ctx: poll_policy_local, agent_proposals: agent_proposals.clone(), @@ -3339,6 +3342,7 @@ struct PolicyPollLoopContext { entrypoint_pid: Arc, interval_secs: u64, ocsf_enabled: Arc, + ocsf_schema_version: Arc>, provider_credentials: ProviderCredentialState, policy_local_ctx: Option>, agent_proposals: AgentProposals, @@ -3781,6 +3785,7 @@ async fn run_policy_poll_loop_with_client( match initial_poll_disposition(&ctx.loaded_policy_origin, &result) { InitialPollDisposition::Acknowledge(candidate) => { apply_ocsf_json_setting(&ctx.ocsf_enabled, &result.settings); + apply_ocsf_schema_version_setting(&ctx.ocsf_schema_version, &result.settings); apply_agent_proposals_enabled( &ctx.agent_proposals, agent_proposals_enabled_from_settings(&result.settings), @@ -3808,6 +3813,7 @@ async fn run_policy_poll_loop_with_client( InitialPollDisposition::Reconcile => pending_result = Some(result), InitialPollDisposition::TrackOnly => { apply_ocsf_json_setting(&ctx.ocsf_enabled, &result.settings); + apply_ocsf_schema_version_setting(&ctx.ocsf_schema_version, &result.settings); apply_agent_proposals_enabled( &ctx.agent_proposals, agent_proposals_enabled_from_settings(&result.settings), @@ -4296,6 +4302,7 @@ async fn run_policy_poll_loop_with_client( // Apply OCSF JSON toggle from the `ocsf_json_enabled` setting. apply_ocsf_json_setting(&ctx.ocsf_enabled, &result.settings); + apply_ocsf_schema_version_setting(&ctx.ocsf_schema_version, &result.settings); // Apply the agent-proposals feature toggle. On a false→true transition // we lazily install the skill so a sandbox that started with the flag @@ -4350,6 +4357,37 @@ fn extract_bool_setting( }) } +fn apply_ocsf_schema_version_setting( + version: &std::sync::Mutex, + settings: &std::collections::HashMap, +) { + let new_version = extract_string_setting(settings, "ocsf_schema_version").unwrap_or_default(); + if let Ok(mut current) = version.lock() + && *current != new_version + { + info!( + ocsf_schema_version = %new_version, + "OCSF schema version target changed" + ); + *current = new_version; + } +} + +fn extract_string_setting( + settings: &std::collections::HashMap, + key: &str, +) -> Option { + use openshell_core::proto::setting_value; + settings + .get(key) + .and_then(|es| es.value.as_ref()) + .and_then(|sv| sv.value.as_ref()) + .and_then(|v| match v { + setting_value::Value::StringValue(s) => Some(s.clone()), + _ => None, + }) +} + fn agent_proposals_enabled_from_settings( settings: &std::collections::HashMap, ) -> bool { @@ -5045,6 +5083,7 @@ network_policies: entrypoint_pid: Arc::new(AtomicU32::new(0)), interval_secs: 0, ocsf_enabled: Arc::new(AtomicBool::new(false)), + ocsf_schema_version: Arc::new(std::sync::Mutex::new(String::new())), provider_credentials: ProviderCredentialState::from_child_env_snapshot( 0, std::collections::HashMap::new(), diff --git a/crates/openshell-sandbox/src/main.rs b/crates/openshell-sandbox/src/main.rs index e7a0948718..1ad69e1070 100644 --- a/crates/openshell-sandbox/src/main.rs +++ b/crates/openshell-sandbox/src/main.rs @@ -602,6 +602,7 @@ fn main() -> Result<()> { // `ocsf_json_enabled` setting changes. The JSONL layer checks it // on each event and short-circuits when false. let ocsf_enabled = Arc::new(AtomicBool::new(false)); + let ocsf_schema_version = Arc::new(std::sync::Mutex::new(String::new())); // Keep guards alive for the entire process. When a guard is dropped the // non-blocking writer flushes remaining logs. @@ -620,7 +621,9 @@ fn main() -> Result<()> { .ok() .map(|roller| { let (writer, guard) = tracing_appender::non_blocking(roller); - let layer = OcsfJsonlLayer::new(writer).with_enabled_flag(ocsf_enabled.clone()); + let layer = OcsfJsonlLayer::new(writer) + .with_enabled_flag(ocsf_enabled.clone()) + .with_target_version(ocsf_schema_version.clone()); (layer, guard) }); let (jsonl_layer, jsonl_guard) = match jsonl_logging { @@ -716,6 +719,7 @@ fn main() -> Result<()> { args.health_port, args.inference_routes, ocsf_enabled, + ocsf_schema_version, args.mode.network, args.mode.process, upstream_proxy_args, diff --git a/crates/openshell-server/src/grpc/policy.rs b/crates/openshell-server/src/grpc/policy.rs index 0e4c74af95..f1f57c2f5b 100644 --- a/crates/openshell-server/src/grpc/policy.rs +++ b/crates/openshell-server/src/grpc/policy.rs @@ -4306,6 +4306,18 @@ 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, + ) + }) + { + rejected += 1; + rejection_reasons.push(format!("chunk '{}': {reason}", chunk.rule_name)); + continue; + } let incoming_observation_key = rule_ref.endpoints.first().and_then(|endpoint| { rule_ref.binaries.first().map(|binary| { ( @@ -11298,7 +11310,7 @@ mod tests { } #[tokio::test] - async fn approve_all_skips_later_tls_conflict_and_applies_compatible_prefix() { + async fn approve_all_skips_later_endpoint_conflict_and_applies_compatible_prefix() { let state = test_server_state().await; let sandbox_id = "sb-approve-all-conflict"; let sandbox_name = "approve-all-conflict"; @@ -11339,13 +11351,15 @@ mod tests { ..Default::default() }, PolicyChunk { - rule_name: "passthrough".to_string(), + rule_name: "conflicting".to_string(), proposed_rule: Some(NetworkPolicyRule { - name: "passthrough".to_string(), + name: "conflicting".to_string(), endpoints: vec![NetworkEndpoint { host: "shared.example.com".to_string(), port: 443, - tls: "skip".to_string(), + protocol: "graphql".to_string(), + enforcement: "enforce".to_string(), + access: "read-only".to_string(), advisor_proposed: true, ..Default::default() }], @@ -11423,7 +11437,7 @@ mod tests { .unwrap(); let policy = ProtoSandboxPolicy::decode(revision.policy_payload.as_slice()).unwrap(); assert!(policy.network_policies.contains_key("inspected")); - assert!(!policy.network_policies.contains_key("passthrough")); + assert!(!policy.network_policies.contains_key("conflicting")); } #[tokio::test] @@ -13886,6 +13900,91 @@ mod tests { ); } + #[tokio::test] + async fn agent_authored_submit_rejects_native_tcp_and_tls_skip_but_allows_explicit_proxy() { + use openshell_core::proto::{NetworkBinary, NetworkEndpoint, NetworkPolicyRule}; + + let state = test_server_state().await; + let sandbox_name = "reject-agent-raw-transports"; + state + .store + .put_message(&test_sandbox( + "sb-reject-agent-raw-transports", + sandbox_name, + ProtoSandboxPolicy::default(), + vec![], + )) + .await + .unwrap(); + + let endpoint = |protocol: &str, tls: &str| NetworkEndpoint { + host: "api.example.com".to_string(), + port: 443, + protocol: protocol.to_string(), + tls: tls.to_string(), + ..Default::default() + }; + let chunk = |name: &str, endpoint: NetworkEndpoint| PolicyChunk { + rule_name: name.to_string(), + proposed_rule: Some(NetworkPolicyRule { + name: name.to_string(), + endpoints: vec![endpoint], + binaries: vec![NetworkBinary { + path: "/usr/bin/curl".to_string(), + ..Default::default() + }], + }), + ..Default::default() + }; + + let response = handle_submit_policy_analysis( + &state, + with_user(Request::new(SubmitPolicyAnalysisRequest { + name: sandbox_name.to_string(), + analysis_mode: "agent_authored".to_string(), + proposed_chunks: vec![ + chunk("native_tcp", endpoint("tcp", "")), + chunk("raw_tls", endpoint("", "skip")), + chunk("explicit_proxy", endpoint("", "")), + ], + ..Default::default() + })), + ) + .await + .unwrap() + .into_inner(); + + assert_eq!(response.accepted_chunks, 1); + assert_eq!(response.rejected_chunks, 2); + assert_eq!(response.rejection_reasons.len(), 2); + assert!( + response + .rejection_reasons + .iter() + .any(|reason| reason.contains("protocol tcp")) + ); + assert!( + response + .rejection_reasons + .iter() + .any(|reason| reason.contains("tls: skip")) + ); + + let draft = handle_get_draft_policy( + &state, + with_user(Request::new(GetDraftPolicyRequest { + name: sandbox_name.to_string(), + status_filter: String::new(), + workspace: "default".to_string(), + })), + ) + .await + .unwrap() + .into_inner(); + assert_eq!(draft.chunks.len(), 1); + assert_eq!(draft.chunks[0].rule_name, "explicit_proxy"); + } + #[tokio::test] async fn approve_draft_chunk_rejects_stored_reserved_provider_rule_name() { use openshell_core::proto::{NetworkBinary, NetworkEndpoint, NetworkPolicyRule}; diff --git a/crates/openshell-server/src/persistence/sqlite.rs b/crates/openshell-server/src/persistence/sqlite.rs index c945c417f9..3e96040e34 100644 --- a/crates/openshell-server/src/persistence/sqlite.rs +++ b/crates/openshell-server/src/persistence/sqlite.rs @@ -14,35 +14,57 @@ use openshell_core::SetResourceVersion; use openshell_core::paths::set_file_owner_only; use openshell_core::proto::Sandbox; use prost::Message; -use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions}; +use sqlx::sqlite::{SqliteConnectOptions, SqliteConnection, SqlitePoolOptions}; use sqlx::{Connection, QueryBuilder, Row, Sqlite, SqlitePool}; use std::path::{Path, PathBuf}; use std::str::FromStr; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; +use tokio::sync::Mutex; static SQLITE_MIGRATOR: sqlx::migrate::Migrator = sqlx::migrate!("./migrations/sqlite"); +static IN_MEMORY_DB_SEQUENCE: AtomicU64 = AtomicU64::new(0); use super::{DELETE_MANY_BATCH_SIZE, DRAFT_CHUNK_OBJECT_TYPE, POLICY_OBJECT_TYPE}; #[derive(Debug, Clone)] pub struct SqliteStore { pool: SqlitePool, + #[cfg_attr(not(any(test, feature = "test-support")), allow(dead_code))] + in_memory_keepalive: Option>>>, +} + +#[cfg(test)] +pub(super) async fn replace_pool_connection(store: &SqliteStore) -> PersistenceResult<()> { + let connection = store.pool.acquire().await.map_err(|e| map_db_error(&e))?; + connection.close().await.map_err(|e| map_db_error(&e)) } impl SqliteStore { /// Closes the connection pool. #[cfg(test)] pub(crate) async fn close_for_test(&self) { - self.pool.close().await; + self.close().await; } pub async fn connect(url: &str) -> PersistenceResult { let is_in_memory = url.contains(":memory:") || url.contains("mode=memory"); let max_connections = if is_in_memory { 1 } else { 5 }; - let options = SqliteConnectOptions::from_str(url) + let mut options = SqliteConnectOptions::from_str(url) .map_err(|e| map_db_error(&e))? .create_if_missing(true); + if is_in_memory { + if options.get_filename().as_os_str().is_empty() + || options.get_filename() == Path::new(":memory:") + { + let sequence = IN_MEMORY_DB_SEQUENCE.fetch_add(1, Ordering::Relaxed); + options = options.filename(format!("file:openshell-in-memory-{sequence}")); + } + options = options.shared_cache(true); + } + let mut pool_options = SqlitePoolOptions::new() .max_connections(max_connections) .min_connections(max_connections); @@ -55,6 +77,15 @@ impl SqliteStore { // so we can restrict the permissions after the database is connected. let db_path = (!is_in_memory).then(|| options.get_filename().to_path_buf()); + let in_memory_keepalive = if is_in_memory { + let connection = SqliteConnection::connect_with(&options) + .await + .map_err(|e| map_db_error(&e))?; + Some(Arc::new(Mutex::new(Some(connection)))) + } else { + None + }; + let pool = pool_options .connect_with(options) .await @@ -65,7 +96,10 @@ impl SqliteStore { restrict_db_file_permissions(&path)?; } - Ok(Self { pool }) + Ok(Self { + pool, + in_memory_keepalive, + }) } pub async fn migrate(&self) -> PersistenceResult<()> { @@ -88,6 +122,12 @@ impl SqliteStore { #[cfg(any(test, feature = "test-support"))] pub async fn close(&self) { self.pool.close().await; + if let Some(keepalive) = &self.in_memory_keepalive { + let connection = keepalive.lock().await.take(); + if let Some(connection) = connection { + let _ = connection.close().await; + } + } } pub async fn put( diff --git a/crates/openshell-server/src/persistence/tests.rs b/crates/openshell-server/src/persistence/tests.rs index 7882c9246c..37fc469d66 100644 --- a/crates/openshell-server/src/persistence/tests.rs +++ b/crates/openshell-server/src/persistence/tests.rs @@ -132,6 +132,58 @@ async fn sqlite_connect_runs_embedded_migrations() { assert!(records.is_empty()); } +#[tokio::test] +async fn sqlite_in_memory_store_survives_pool_connection_replacement() { + for url in ["sqlite::memory:", "sqlite://?mode=memory"] { + let store = super::sqlite::SqliteStore::connect(url) + .await + .expect("connect to in-memory SQLite"); + store.migrate().await.expect("migrate in-memory SQLite"); + store + .put( + "sandbox", + "before-replacement", + "before-replacement", + "default", + b"before", + None, + ) + .await + .expect("write before connection replacement"); + + super::sqlite::replace_pool_connection(&store) + .await + .expect("replace operational pool connection"); + + let preserved = store + .get("sandbox", "before-replacement") + .await + .expect("schema survives connection replacement") + .expect("existing object survives connection replacement"); + assert_eq!(preserved.payload, b"before", "database URL: {url}"); + + store + .put( + "sandbox", + "after-replacement", + "after-replacement", + "default", + b"after", + None, + ) + .await + .expect("write after connection replacement"); + assert!( + store + .get("sandbox", "after-replacement") + .await + .expect("read after connection replacement") + .is_some(), + "database URL: {url}" + ); + } +} + #[cfg(unix)] #[tokio::test] async fn sqlite_connect_restricts_db_file_permissions() { diff --git a/crates/openshell-supervisor-network/src/policy_local.rs b/crates/openshell-supervisor-network/src/policy_local.rs index ef899b666e..6a42eafb8a 100644 --- a/crates/openshell-supervisor-network/src/policy_local.rs +++ b/crates/openshell-supervisor-network/src/policy_local.rs @@ -1112,6 +1112,11 @@ fn network_endpoint_from_json( if endpoint.host.trim().is_empty() { return Err("endpoint.host is required".to_string()); } + if let Some(reason) = + openshell_policy::agent_authored_transport_rejection(&endpoint.protocol, &endpoint.tls) + { + return Err(reason.to_string()); + } let mut ports = endpoint.ports; if ports.is_empty() && endpoint.port > 0 { @@ -1484,6 +1489,47 @@ mod tests { assert!(!error.contains("secret")); } + #[test] + fn proposal_chunks_from_body_rejects_native_tcp_and_tls_skip() { + for endpoint in [ + r#"{"host":"db.example.com","port":5432,"protocol":"tcp"}"#, + r#"{"host":"api.example.com","port":443,"tls":"skip"}"#, + ] { + let body = format!( + r#"{{ + "operations": [{{ + "addRule": {{ + "ruleName": "raw_transport", + "rule": {{"endpoints": [{endpoint}]}} + }} + }}] + }}"# + ); + + let error = proposal_chunks_from_body(body.as_bytes()).unwrap_err(); + assert!(error.contains("administrator"), "unexpected error: {error}"); + } + } + + #[test] + fn proposal_chunks_from_body_accepts_omitted_protocol_with_default_tls() { + let body = br#"{ + "operations": [{ + "addRule": { + "ruleName": "explicit_proxy", + "rule": { + "endpoints": [{"host":"api.example.com","port":443}] + } + } + }] + }"#; + + let chunks = proposal_chunks_from_body(body).unwrap(); + let endpoint = &chunks[0].proposed_rule.as_ref().unwrap().endpoints[0]; + assert!(endpoint.protocol.is_empty()); + assert!(endpoint.tls.is_empty()); + } + #[test] fn parse_last_query_clamps_to_max() { assert_eq!(parse_last_query("last=5"), Some(5)); diff --git a/crates/openshell-supervisor-process/src/skills/policy_advisor.md b/crates/openshell-supervisor-process/src/skills/policy_advisor.md index 4b7074f6dd..8d792aaedb 100644 --- a/crates/openshell-supervisor-process/src/skills/policy_advisor.md +++ b/crates/openshell-supervisor-process/src/skills/policy_advisor.md @@ -50,10 +50,12 @@ operations. Each `addRule` carries a complete narrow `NetworkPolicyRule`. credential is in scope auto-approve** (see Auto-approval below). Any credentialed reach or capability change goes to human review — that is the design. L7 is still the agent-speed path because the prover can - precisely describe the change (which method was added on which path); - L4 to a credentialed host loses that precision. Use L4 only when the - binary's wire protocol is opaque to L7 inspection (`ssh`, `nc`, - `git-remote-http`) or the host has no documented REST surface. + precisely describe the change (which method was added on which path). + When a client can use the explicit proxy but its wire protocol is opaque + to L7 inspection (`ssh`, `nc`, `git-remote-http`), omit `protocol` and + retain default TLS handling. Never propose `protocol: tcp` or `tls: skip`: + those choices bypass application-authority inspection and require an + administrator to add the rule explicitly. 5. Draft the narrowest rule: exact host, exact port, exact binary when known, exact method, and the smallest safe path. 6. Submit the proposal, save `accepted_chunk_ids` from the response, and @@ -207,6 +209,8 @@ The new submission wins by structural overlap. `fe80::/10`) or known metadata hostnames such as `metadata.google.internal`. Cloud-metadata endpoints there can hand out the host's credentials. +- Do not propose `protocol: tcp` or `tls: skip`. If the task requires native + TCP or a raw TLS tunnel, ask an administrator to add that access explicitly. - Do not include query strings, tokens, credentials, or secret values in paths. - Explain uncertainty in `intent_summary` instead of widening the rule. diff --git a/crates/openshell-tui/src/ui/mod.rs b/crates/openshell-tui/src/ui/mod.rs index 2521184320..cf5c187364 100644 --- a/crates/openshell-tui/src/ui/mod.rs +++ b/crates/openshell-tui/src/ui/mod.rs @@ -74,8 +74,8 @@ fn draw_sandbox_screen(frame: &mut Frame<'_>, app: &mut App, area: Rect) { let chunks = Layout::default() .direction(Direction::Vertical) .constraints([ - Constraint::Percentage(20), // metadata - Constraint::Percentage(80), // policy or logs + Constraint::Length(sandbox_detail::required_height(app)), // metadata + Constraint::Min(0), // policy or logs ]) .split(area); @@ -737,4 +737,29 @@ mod tests { assert_eq!(rendered, expected); assert!(!rendered.contains("ALPHA")); } + + #[tokio::test] + async fn sandbox_delete_confirmation_is_visible_in_standard_terminal() { + let mut app = test_app(); + app.screen = Screen::Sandbox; + app.focus = Focus::SandboxPolicy; + app.sandbox_names = vec!["test-sandbox".to_string()]; + app.sandbox_count = 1; + app.confirm_delete = true; + let mut terminal = Terminal::new(TestBackend::new(100, 24)).unwrap(); + + terminal.draw(|frame| draw(frame, &mut app)).unwrap(); + + let text: String = terminal + .backend() + .buffer() + .content() + .iter() + .map(ratatui::buffer::Cell::symbol) + .collect(); + assert!( + text.contains("Delete sandbox 'test-sandbox'?"), + "sandbox screen was: {text:?}" + ); + } } diff --git a/crates/openshell-tui/src/ui/sandbox_detail.rs b/crates/openshell-tui/src/ui/sandbox_detail.rs index 4ff78617f0..a398797e40 100644 --- a/crates/openshell-tui/src/ui/sandbox_detail.rs +++ b/crates/openshell-tui/src/ui/sandbox_detail.rs @@ -8,6 +8,37 @@ use ratatui::widgets::{Block, Borders, Padding, Paragraph}; use crate::app::App; +const BASE_CONTENT_ROWS: u16 = 6; +const BORDER_ROWS: u16 = 2; + +fn pending_draft_count(app: &App) -> usize { + let cached = app + .sandbox_draft_counts + .get(app.sandbox_selected) + .copied() + .unwrap_or(0); + if cached > 0 { + cached + } else { + app.draft_chunks + .iter() + .filter(|chunk| chunk.status == "pending") + .count() + } +} + +/// Return the rows needed to render every metadata line without clipping. +pub(super) fn required_height(app: &App) -> u16 { + let policy_rows = u16::from(app.sandbox_policy_is_global); + let action_rows = if app.confirm_delete { + 2 // spacer plus confirmation + } else { + u16::from(pending_draft_count(app) > 0) + }; + + BASE_CONTENT_ROWS + policy_rows + action_rows + BORDER_ROWS +} + /// Draw a compact metadata pane for the currently selected sandbox. /// /// This is non-interactive (no focus state) — always rendered with the @@ -37,16 +68,8 @@ pub fn draw(frame: &mut Frame<'_>, app: &App, area: Rect) { }; // Count pending draft recommendations for this sandbox. - let pending_count = app.sandbox_draft_counts.get(idx).copied().unwrap_or(0); - // Also check the live draft_chunks when on the sandbox screen (more up-to-date). - let pending_count = if pending_count > 0 { - pending_count - } else { - app.draft_chunks - .iter() - .filter(|c| c.status == "pending") - .count() - }; + // Fall back to the live chunks when the dashboard cache has no pending count. + let pending_count = pending_draft_count(app); // Row 1: Name + Status + optional draft badge let mut row1_spans = vec![ diff --git a/docs/images/splunk-cim-v1.1-downgrade.png b/docs/images/splunk-cim-v1.1-downgrade.png new file mode 100644 index 0000000000..feb8e21683 Binary files /dev/null and b/docs/images/splunk-cim-v1.1-downgrade.png differ diff --git a/docs/observability/ocsf-json-export.mdx b/docs/observability/ocsf-json-export.mdx index bb85ff6cfc..ab76ead8a7 100644 --- a/docs/observability/ocsf-json-export.mdx +++ b/docs/observability/ocsf-json-export.mdx @@ -3,7 +3,7 @@ # SPDX-License-Identifier: Apache-2.0 title: "OCSF JSON Export" sidebar-title: "OCSF JSON Export" -description: "How to enable full OCSF JSON logging for SIEM integration, compliance, and structured analysis." +description: "How to enable full OCSF JSON logging for SIEM integration, compliance, and structured analysis. Includes schema version downgrade for AWS Security Lake, Splunk, and CrowdStrike compatibility." keywords: "Generative AI, Cybersecurity, OCSF, JSON, SIEM, Compliance, Observability" --- @@ -168,14 +168,66 @@ The shorthand log renders this as: OCSF API:INFERENCE [INFO] Success claude-haiku-4-5-20251001 via https://api.anthropic.com/v1 701ms [POST /v1/messages] ``` +## SIEM Schema Version Compatibility + +OpenShell emits OCSF v1.8.0 events internally, but many SIEMs only support older schema versions. The `ocsf_schema_version` setting tells the JSONL layer to downgrade events before writing, stripping fields and profiles that don't exist in the target version. + +Set the target version globally: + +```shell +openshell settings set --global --key ocsf_schema_version --value "1.1" +``` + +Or per-sandbox: + +```shell +openshell settings set my-sandbox --key ocsf_schema_version --value "1.3" +``` + +The setting takes effect on the next poll cycle, by default every 10 seconds. No sandbox restart is required. + +Supported target versions are `1.1` and `1.3`. When set, the JSONL layer applies the following transformations: + +- Strips fields added after the target version: `ai_model`, `container`, `observation_point_id` +- Removes unknown profile names from `metadata.profiles`: `ai_operation`, `container` +- Rewrites `metadata.version` to match the target version + +The shorthand log output is unaffected. The internal event model stays at v1.8.0; only the serialized JSONL is transformed. + +When unset or empty, no downgrade is applied and events are written at the current schema version. + +| SIEM | Required OCSF Version | `ocsf_schema_version` Value | +|---|---|---| +| AWS Security Lake | v1.1.0 | `1.1` | +| Splunk CIM Add-On | v1.1-v1.3 | `1.1` or `1.3` | +| CrowdStrike FDR | v1.5.0 | Not yet supported | +| Datadog Cloud SIEM | v1.5.0 (selectable) | Not yet supported | + + +Downgrading is lossy. The `ai_model` field and `ai_operation` profile are stripped for v1.1 and v1.3 targets, so AI model attribution is not present in downgraded events. If your audit workflow requires knowing which model handled a request, use the full schema version (leave `ocsf_schema_version` unset). OpenShell supports OCSF v1.8.0 natively; upgrade your SIEM's OCSF schema if you need AI attribution alongside backward-compatible ingestion. + + +Downgraded events include a `downgraded_from` marker in the `unmapped` object so auditors can distinguish "no model was involved" from "model attribution was stripped": + +```json +{ + "unmapped": { + "downgraded_from": "1.8.0" + } +} +``` + +The core OCSF event structure (class UIDs, activity IDs, network and HTTP fields) is identical across v1.1 through v1.8. The stripped fields are all profile-gated additions. + ## Integration with External Tools The JSONL file can be shipped to any tool that accepts OCSF-formatted data: | Tool | Integration Path | |---|---| -| Splunk | Use the [Splunk OCSF Add-on](https://splunkbase.splunk.com/app/6943) to ingest OCSF JSONL files. | -| Amazon Security Lake | OCSF is the native schema for Security Lake. | +| Splunk | Use the [Splunk OCSF Add-on](https://splunkbase.splunk.com/app/6943) to ingest OCSF JSONL files. Set `ocsf_schema_version` to `1.3` for CIM Add-On compatibility. | +| Amazon Security Lake | OCSF is the native schema for Security Lake. Set `ocsf_schema_version` to `1.1` for v1.1.0 compatibility. | +| CrowdStrike FDR | Ship JSONL files to Falcon Data Replicator. v1.5 downgrade target is not yet supported. | | Elastic | Use Filebeat to ship JSONL files with the OCSF field mappings. | | Custom pipelines | Parse the JSONL file with `jq`, Python, or any JSON-capable tool. | @@ -188,7 +240,7 @@ cat /var/log/openshell-ocsf.2026-04-01.log | \ ## Relationship to Shorthand Logs -The shorthand format in `openshell.YYYY-MM-DD.log` and the JSON format in `openshell-ocsf.YYYY-MM-DD.log` are derived from the same OCSF events. The shorthand is a human-readable projection; the JSON is the complete record. Both are generated at the same time from the same event data. +The shorthand format in `openshell.YYYY-MM-DD.log` and the JSON format in `openshell-ocsf.YYYY-MM-DD.log` are derived from the same OCSF events. The shorthand is a human-readable projection; the JSON is the full structured record when no schema downgrade is configured. When `ocsf_schema_version` is set, the JSON export is a lossy projection of the internal event model. Both formats are generated at the same time from the same event data. The shorthand log is always active. The JSON export is opt-in through `ocsf_json_enabled`. diff --git a/docs/reference/policy-schema.mdx b/docs/reference/policy-schema.mdx index a0c5d29737..0ef627cf2b 100644 --- a/docs/reference/policy-schema.mdx +++ b/docs/reference/policy-schema.mdx @@ -193,8 +193,10 @@ Each endpoint defines a reachable destination and optional inspection rules. - `access` and `rules` are mutually exclusive; setting both is rejected. - `protocol: tcp` requires a valid DNS hostname. Hostless `allowed_ips`, IP-literal hosts, trailing-dot names, and malformed DNS selectors are rejected with a policy-validation error. - `protocol: tcp` requires at least one port and rejects L7-only fields, including `path`, `enforcement`, `access`, `rules`, `deny_rules`, request rewriting and credential signing fields, and GraphQL, JSON-RPC, or MCP options. +- A `protocol: tcp` hostname constrains connection routing, not application authority. OpenShell does not inspect TLS SNI, HTTP `Host`, or another protocol-level destination in the stream. Compatible shared infrastructure can therefore expose other tenants, virtual hosts, or services behind an allowed hostname. - A sandbox runtime must support policy DNS and transparent TCP capture before it can activate a policy containing `protocol: tcp`. Docker and Podman provide this runtime support. - Adding the first `protocol: tcp` endpoint to a running sandbox that started without one is rejected atomically because its DNS and capture substrate is startup infrastructure. Recreate the sandbox with a TCP endpoint. A sandbox that started with the substrate can remove and re-add TCP endpoints dynamically. +- Policy-advisor agent proposals cannot request `protocol: tcp` or `tls: skip`. Add native TCP or raw TLS access through an administrator-authored policy. Agent proposals may omit `protocol` to use the explicit proxy with its default TLS termination and HTTP authority checks. - When `protocol` is set, at least one of `access` or `rules` is required for `rest`, `websocket`, `graphql`, and `sql`. - `mcp` and `json-rpc` reject `access` presets; use explicit `rules`. - `json-rpc` requires explicit `rules` with `allow.method`. diff --git a/docs/sandboxes/policies.mdx b/docs/sandboxes/policies.mdx index c5a34db14f..1deb76548e 100644 --- a/docs/sandboxes/policies.mdx +++ b/docs/sandboxes/policies.mdx @@ -131,6 +131,8 @@ network_policies: OpenShell answers DNS only for hostnames eligible under an active `protocol: tcp` endpoint. It validates upstream answers against destination and SSRF controls, returns a supervisor-owned synthetic address, and records the validated real addresses. When the application connects to the synthetic address, OpenShell recovers the hostname and port, evaluates the calling process against the current policy generation, and dials only an address pinned by that DNS result. +Treat that hostname as a connection-routing constraint, not an application-authority boundary. OpenShell does not inspect TLS SNI, HTTP `Host`, or another protocol-level destination inside a `protocol: tcp` stream. If the approved hostname reaches compatible shared infrastructure, a client may be able to select another tenant, virtual host, or service behind the same front door. Use native TCP only when the trust boundary includes every destination that the shared infrastructure can expose; use an inspected protocol when application authority must remain constrained. + Applications must honor the returned DNS TTL and resolve the hostname again before reconnecting after that TTL expires. A client that caches the synthetic address indefinitely can receive a connection failure after the mapping expires. Docker and Podman currently advertise only IPv4 egress for this feature, so OpenShell returns an empty successful answer for AAAA queries and lets dual-stack clients use the working A record. DNS resolution does not authorize a connection by itself. Unknown names, wrong ports, stale mappings, disallowed destination addresses, and binaries outside the matching policy fail closed. Applications cannot inherit access by connecting directly to a real IP returned by an upstream resolver. diff --git a/docs/sandboxes/policy-advisor.mdx b/docs/sandboxes/policy-advisor.mdx index eeb13058e1..80884620d5 100644 --- a/docs/sandboxes/policy-advisor.mdx +++ b/docs/sandboxes/policy-advisor.mdx @@ -129,7 +129,7 @@ OpenShell has two proposal paths: | Path | Source | Typical rule shape | |---|---|---| | 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 propose L4 rules for opaque protocols. | +| 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. | ### How proposal provenance works @@ -189,7 +189,7 @@ For REST APIs, prefer L7 rules over broad L4 access. A good proposal allows one } ``` -The current `policy.local` JSON shape covers L4 endpoints and REST method or path rules. Use [Customize Sandbox Policies](/sandboxes/policies) or [Policy Schema Reference](/reference/policy-schema) for policy fields that are not part of the agent-authored proposal surface, such as WebSocket credential rewrite, GraphQL operation matching, endpoint path scoping, and provider-owned policy bundles. +The current `policy.local` JSON shape covers explicit-proxy endpoints and REST method or path rules. Agent-authored proposals cannot set `protocol: tcp` or `tls: skip`, because those modes bypass application-authority inspection. When a task requires native TCP or a raw TLS tunnel, a developer must add the rule through the normal policy-authoring workflow. Omitting `protocol` remains supported and retains the explicit proxy's default TLS termination and HTTP authority checks. Use [Customize Sandbox Policies](/sandboxes/policies) or [Policy Schema Reference](/reference/policy-schema) for policy fields that are not part of the agent-authored proposal surface, such as WebSocket credential rewrite, GraphQL operation matching, endpoint path scoping, and provider-owned policy bundles. Policy advisor proposals do not add `allowed_ips` automatically. If an advisor-proposed hostname resolves to an internal or private address, OpenShell's SSRF protections still block the connection until a developer explicitly adds the required `allowed_ips` entry. diff --git a/skills/generate-sandbox-policy/SKILL.md b/skills/generate-sandbox-policy/SKILL.md index 0b2ce7f7bb..73c0863df7 100644 --- a/skills/generate-sandbox-policy/SKILL.md +++ b/skills/generate-sandbox-policy/SKILL.md @@ -404,7 +404,7 @@ Evaluate the generated policy for overly broad access and **include warnings in | Condition | Warning to show | |-----------|----------------| -| **L4-only** (no `protocol`, or `protocol: tcp`) | "This policy allows all application methods and paths without inspection. An omitted protocol uses explicit-proxy behavior; `protocol: tcp` enables policy DNS and transparent TCP only on a runtime that advertises the complete substrate (currently Docker and Podman). Consider `protocol: rest` with a preset if you want HTTP method-level control." | +| **L4-only** (no `protocol`, or `protocol: tcp`) | "This policy allows all application methods and paths without inspection. An omitted protocol uses explicit-proxy behavior. `protocol: tcp` enables policy DNS and transparent TCP only on a runtime that advertises the complete substrate (currently Docker and Podman); its hostname constrains connection routing, not application authority, so compatible shared infrastructure may expose other tenants or services. Consider `protocol: rest` with a preset if you want HTTP method-level or authority control." | | **`access: full`** | "This policy allows all HTTP methods (including DELETE) on all paths. If you don't need DELETE, `read-write` is safer. If you only need to read, `read-only` is the most restrictive option." | | **`access: full` + `enforcement: audit`** | "Full access in audit mode provides no actual restriction — all traffic flows through. This is effectively a monitoring-only policy." | | **`access: read-write`** when user hasn't confirmed write need | "This policy allows POST, PUT, and PATCH on all paths. If you only need to read data, `read-only` is more restrictive." | diff --git a/skills/openshell-cli/SKILL.md b/skills/openshell-cli/SKILL.md index 48f84fa653..c46f569789 100644 --- a/skills/openshell-cli/SKILL.md +++ b/skills/openshell-cli/SKILL.md @@ -770,6 +770,9 @@ openshell settings delete work-session --key ocsf_json_enabled openshell settings get --global --json openshell settings set --global --key ocsf_json_enabled --value true + +# OCSF schema version downgrade for SIEM compatibility (allowed: "1.1", "1.3") +openshell settings set --global --key ocsf_schema_version --value "1.1" ``` Global mutations prompt for confirmation. Use `--yes` only in reviewed automation. diff --git a/tasks/scripts/gateway-docker.sh b/tasks/scripts/gateway-docker.sh index 6826829fd8..5a6fb62887 100644 --- a/tasks/scripts/gateway-docker.sh +++ b/tasks/scripts/gateway-docker.sh @@ -226,7 +226,6 @@ signing_key_path = "${TLS_DIR}/jwt/signing.pem" public_key_path = "${TLS_DIR}/jwt/public.pem" kid_path = "${TLS_DIR}/jwt/kid" gateway_id = "${GATEWAY_NAME}" -ttl_secs = 3600 [openshell.drivers.docker] default_image = "${SANDBOX_IMAGE}" diff --git a/tasks/scripts/gateway-vm.sh b/tasks/scripts/gateway-vm.sh index 3818dca364..80d723eb11 100755 --- a/tasks/scripts/gateway-vm.sh +++ b/tasks/scripts/gateway-vm.sh @@ -351,7 +351,6 @@ signing_key_path = "${TLS_DIR}/jwt/signing.pem" public_key_path = "${TLS_DIR}/jwt/public.pem" kid_path = "${TLS_DIR}/jwt/kid" gateway_id = "${GATEWAY_NAME}" -ttl_secs = 3600 [openshell.drivers.vm] default_image = "${SANDBOX_IMAGE}" diff --git a/tasks/scripts/gateway.sh b/tasks/scripts/gateway.sh index 019d1b1b63..906379df79 100644 --- a/tasks/scripts/gateway.sh +++ b/tasks/scripts/gateway.sh @@ -242,6 +242,15 @@ CONFIG_PATH="${STATE_DIR}/gateway.toml" # The config may reference credential-bearing material (e.g. proxy_auth_file); # keep it owner-only regardless of the ambient umask. install -m 600 /dev/null "${CONFIG_PATH}" + +# Kubernetes is a shared deployment, so its sandbox JWTs must expire. Local +# drivers omit ttl_secs and inherit the gateway's non-expiring default, so a +# sandbox restarted while the gateway is down can still reconnect. +GATEWAY_JWT_TTL_CONFIG="" +if [[ "${DRIVER}" == "kubernetes" ]]; then + GATEWAY_JWT_TTL_CONFIG="ttl_secs = 3600" +fi + cat >"${CONFIG_PATH}" <>"${CONFIG_PATH}" <