From 3e69c36f8431e595d807eb51b1010d7441c2454e Mon Sep 17 00:00:00 2001 From: jtoelke2 <149006449+jtoelke2@users.noreply.github.com> Date: Tue, 28 Apr 2026 15:32:55 -0500 Subject: [PATCH 1/3] feat(ci): add shadow-rust-native-build workflow for OS-49 Phase 4 (PR 4a) (#973) Builds openshell-gateway and openshell-sandbox natively per-arch on the nv-gha-runners shared CPU pool with a GHA-backed sccache, and uploads the resulting binaries as artifacts shaped for Dockerfile.images' BINARY_SOURCE=prebuilt path (added in #945). Dispatch manually 4-5 times after merge to collect cold + warm numbers and compare against the Rust portion of docker-build.yml's ARC baseline. PR 4c will wire these artifacts into the real pipeline once numbers land. Refs OS-128. Signed-off-by: Jonas Toelke --- .../workflows/shadow-rust-native-build.yml | 156 ++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 .github/workflows/shadow-rust-native-build.yml diff --git a/.github/workflows/shadow-rust-native-build.yml b/.github/workflows/shadow-rust-native-build.yml new file mode 100644 index 0000000000..b252777ea8 --- /dev/null +++ b/.github/workflows/shadow-rust-native-build.yml @@ -0,0 +1,156 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +name: Shadow — Rust Native Build (openshell-gateway / openshell-sandbox) + +# OS-49 Phase 4 / PR 4a — non-blocking shadow that builds openshell-gateway +# and openshell-sandbox natively per-arch on the nv-gha-runners shared CPU +# pool (`linux-{amd64,arm64}-cpu8`) with a GHA-backed sccache, and uploads +# the resulting binaries as artifacts. Reuses the pattern from PR #853's +# release-dev.yml "Build standalone {gateway,supervisor} binaries" jobs. +# +# The artifacts match the layout PR 4c expects when consuming `BINARY_SOURCE= +# prebuilt` (wired up in #945): one binary per (component, arch), staged to +# `deploy/docker/.build/prebuilt-binaries//openshell-{gateway,sandbox}`. +# +# Dispatch 4-5 times after merge to collect cold + warm numbers and compare +# against the Rust portion of docker-build.yml's 17.5 m ARC baseline. Success +# criteria, gotchas, and dependency graph live on the OS-128 Linear issue. + +on: + # workflow_dispatch only — keeps this shadow off main's required-check + # surface and avoids cluttering CI history with non-blocking failures + # while we're still collecting Phase 4 data. Dispatch from the Actions + # UI to collect cold/warm-cache numbers. + workflow_dispatch: + +permissions: + contents: read + packages: read + +env: + CARGO_TERM_COLOR: always + CARGO_INCREMENTAL: "0" + MISE_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + # Route sccache (already RUSTC_WRAPPER in mise.toml) to the GHA cache + # backend instead of the EKS memcached used by ARC. + SCCACHE_GHA_ENABLED: "true" + +jobs: + rust-native-build: + name: ${{ matrix.component }} (${{ matrix.arch }}) + strategy: + fail-fast: false + matrix: + component: [gateway, sandbox] + arch: [amd64, arm64] + include: + - component: gateway + crate: openshell-server + binary: openshell-gateway + - component: sandbox + crate: openshell-sandbox + binary: openshell-sandbox + - arch: amd64 + runner: linux-amd64-cpu8 + target: x86_64-unknown-linux-gnu + - arch: arm64 + runner: linux-arm64-cpu8 + target: aarch64-unknown-linux-gnu + runs-on: ${{ matrix.runner }} + env: + # Partition the GHA sccache cache per (component, arch). Without this, + # concurrent matrix jobs collide on the same cache key and later-starting + # writers hit 409 Conflict (PR #961 fix for shadow-shared-cpu-spike). + SCCACHE_GHA_VERSION: ${{ matrix.component }}-${{ matrix.arch }} + container: + image: ghcr.io/nvidia/openshell/ci:latest + credentials: + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + timeout-minutes: 60 + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Mark workspace safe for git + run: git config --global --add safe.directory "$GITHUB_WORKSPACE" + + - name: Fetch tags + run: git fetch --tags --force + + - name: Install tools + run: mise install + + - name: Configure GHA sccache backend + # Exposes ACTIONS_CACHE_URL / ACTIONS_RUNTIME_TOKEN so sccache (wrapped + # around rustc via mise's RUSTC_WRAPPER) can initialize the GHA cache. + uses: mozilla-actions/sccache-action@7d986dd989559c6ecdb630a3fd2557667be217ad # v0.0.9 + + - name: Cache Rust target and registry + uses: Swatinem/rust-cache@779680da715d629ac1d338a641029a2f4372abb5 # v2 + with: + shared-key: shadow-rust-native-${{ matrix.component }}-${{ matrix.arch }} + cache-directories: .cache/sccache + cache-targets: "true" + + - name: Compute cargo version + id: version + run: | + set -euo pipefail + echo "cargo_version=$(uv run python tasks/scripts/release.py get-version --cargo)" >> "$GITHUB_OUTPUT" + + - name: Patch workspace version + if: steps.version.outputs.cargo_version != '' + run: | + set -euo pipefail + sed -i -E '/^\[workspace\.package\]/,/^\[/{s/^version[[:space:]]*=[[:space:]]*".*"/version = "'"${{ steps.version.outputs.cargo_version }}"'"/}' Cargo.toml + + - name: Build ${{ matrix.binary }} (${{ matrix.target }}) + # Matches docker-build.yml's default EXTRA_CARGO_FEATURES so the + # binary content is byte-comparable to what Dockerfile.images produces + # today (precondition for PR 4c's drop-in swap). + run: | + set -euo pipefail + mise x -- cargo build \ + --release \ + --target ${{ matrix.target }} \ + -p ${{ matrix.crate }} \ + --bin ${{ matrix.binary }} \ + --features openshell-core/dev-settings + + - name: Verify packaged binary + run: | + set -euo pipefail + BIN="target/${{ matrix.target }}/release/${{ matrix.binary }}" + OUTPUT="$("$BIN" --version)" + echo "$OUTPUT" + grep -q "^${{ matrix.binary }} " <<<"$OUTPUT" + # Record glibc linkage so drift from the Ubuntu noble runtime base + # image is visible in logs (not asserted — the runtime check lands + # when PR 4c builds images on top of these artifacts). + ldd --version | head -1 + ldd "$BIN" | head -20 || true + + - name: sccache stats + if: always() + run: mise x -- sccache --show-stats + + - name: Stage binary for prebuilt layout + # Shape mirrors `deploy/docker/.build/prebuilt-binaries//` + # so PR 4c can download the artifact directly into the build context. + run: | + set -euo pipefail + STAGE="prebuilt-binaries/${{ matrix.arch }}" + mkdir -p "$STAGE" + install -m 0755 "target/${{ matrix.target }}/release/${{ matrix.binary }}" "$STAGE/${{ matrix.binary }}" + ls -lh "$STAGE/" + + - name: Upload artifact + uses: actions/upload-artifact@v4 + with: + name: rust-binary-${{ matrix.component }}-linux-${{ matrix.arch }} + path: prebuilt-binaries/${{ matrix.arch }}/${{ matrix.binary }} + retention-days: 5 + if-no-files-found: error From d414e69a2023bb85266ccc6087f4b9d258ac3206 Mon Sep 17 00:00:00 2001 From: "John T. Myers" <9696606+johntmyers@users.noreply.github.com> Date: Tue, 28 Apr 2026 16:15:14 -0700 Subject: [PATCH 2/3] refactor(server): unify policy persistence in objects table (#972) * refactor(server): unify policy persistence in objects table Signed-off-by: John Myers <9696606+johntmyers@users.noreply.github.com> * fix(server): clean sandbox-owned records on reconcile delete * refactor(server): use protos for stored policy records * refactor(server): move policy persistence into policy_store * fix(server): restore compute runtime merge compatibility * fix(server): validate draft chunk sandbox ownership --------- Signed-off-by: John Myers <9696606+johntmyers@users.noreply.github.com> --- .../postgres/001_create_objects.sql | 33 +- .../postgres/002_create_sandbox_policies.sql | 15 - .../003_create_policy_recommendations.sql | 33 -- .../migrations/sqlite/001_create_objects.sql | 33 +- .../sqlite/002_create_sandbox_policies.sql | 15 - .../003_create_policy_recommendations.sql | 35 -- crates/openshell-server/src/compute/mod.rs | 236 +++++++-- crates/openshell-server/src/grpc/policy.rs | 484 +++++++++++++++--- crates/openshell-server/src/lib.rs | 1 + .../openshell-server/src/persistence/mod.rs | 410 +++++---------- .../src/persistence/postgres.rs | 466 +++++++++-------- .../src/persistence/sqlite.rs | 435 +++++++++------- .../openshell-server/src/persistence/tests.rs | 89 ++-- crates/openshell-server/src/policy_store.rs | 370 +++++++++++++ e2e/python/test_inference_routing.py | 3 + e2e/rust/tests/host_gateway_alias.rs | 6 +- proto/openshell.proto | 70 +++ 17 files changed, 1819 insertions(+), 915 deletions(-) delete mode 100644 crates/openshell-server/migrations/postgres/002_create_sandbox_policies.sql delete mode 100644 crates/openshell-server/migrations/postgres/003_create_policy_recommendations.sql delete mode 100644 crates/openshell-server/migrations/sqlite/002_create_sandbox_policies.sql delete mode 100644 crates/openshell-server/migrations/sqlite/003_create_policy_recommendations.sql create mode 100644 crates/openshell-server/src/policy_store.rs diff --git a/crates/openshell-server/migrations/postgres/001_create_objects.sql b/crates/openshell-server/migrations/postgres/001_create_objects.sql index 0d2cb17da8..3978f84567 100644 --- a/crates/openshell-server/migrations/postgres/001_create_objects.sql +++ b/crates/openshell-server/migrations/postgres/001_create_objects.sql @@ -1,10 +1,29 @@ CREATE TABLE IF NOT EXISTS objects ( - object_type TEXT NOT NULL, - id TEXT NOT NULL, - name TEXT NOT NULL, - payload BYTEA NOT NULL, + id TEXT PRIMARY KEY, + object_type TEXT NOT NULL, + name TEXT, + scope TEXT, + version BIGINT, + status TEXT, + dedup_key TEXT, + hit_count BIGINT NOT NULL DEFAULT 0, + payload BYTEA NOT NULL, created_at_ms BIGINT NOT NULL, - updated_at_ms BIGINT NOT NULL, - PRIMARY KEY (id), - UNIQUE (object_type, name) + updated_at_ms BIGINT NOT NULL ); + +CREATE UNIQUE INDEX IF NOT EXISTS objects_name_uq + ON objects (object_type, name) + WHERE name IS NOT NULL; + +CREATE UNIQUE INDEX IF NOT EXISTS objects_version_uq + ON objects (object_type, scope, version) + WHERE scope IS NOT NULL AND version IS NOT NULL; + +CREATE INDEX IF NOT EXISTS objects_scope_status_idx + ON objects (object_type, scope, status, version) + WHERE scope IS NOT NULL; + +CREATE UNIQUE INDEX IF NOT EXISTS objects_dedup_uq + ON objects (object_type, scope, dedup_key) + WHERE dedup_key IS NOT NULL; diff --git a/crates/openshell-server/migrations/postgres/002_create_sandbox_policies.sql b/crates/openshell-server/migrations/postgres/002_create_sandbox_policies.sql deleted file mode 100644 index 1fdd49b05a..0000000000 --- a/crates/openshell-server/migrations/postgres/002_create_sandbox_policies.sql +++ /dev/null @@ -1,15 +0,0 @@ -CREATE TABLE IF NOT EXISTS sandbox_policies ( - id TEXT PRIMARY KEY, - sandbox_id TEXT NOT NULL, - version INTEGER NOT NULL, - policy_payload BYTEA NOT NULL, - policy_hash TEXT NOT NULL, - status TEXT NOT NULL DEFAULT 'pending', - load_error TEXT, - created_at_ms BIGINT NOT NULL, - loaded_at_ms BIGINT, - UNIQUE (sandbox_id, version) -); - -CREATE INDEX IF NOT EXISTS idx_sandbox_policies_lookup - ON sandbox_policies (sandbox_id, version DESC); diff --git a/crates/openshell-server/migrations/postgres/003_create_policy_recommendations.sql b/crates/openshell-server/migrations/postgres/003_create_policy_recommendations.sql deleted file mode 100644 index 0c6fa09eeb..0000000000 --- a/crates/openshell-server/migrations/postgres/003_create_policy_recommendations.sql +++ /dev/null @@ -1,33 +0,0 @@ --- Draft policy chunks: proposed network policy rules awaiting user approval. --- --- One row per (sandbox_id, host, port, binary). The toggle model allows: --- pending -> approved | rejected (initial decision) --- approved <-> rejected (toggle via approve/revoke) --- --- Upserts bump hit_count / last_seen_ms when the same denial recurs. -CREATE TABLE IF NOT EXISTS draft_policy_chunks ( - id TEXT PRIMARY KEY, - sandbox_id TEXT NOT NULL, - draft_version BIGINT NOT NULL, - status TEXT NOT NULL DEFAULT 'pending', - rule_name TEXT NOT NULL, - proposed_rule BYTEA NOT NULL, - rationale TEXT NOT NULL DEFAULT '', - security_notes TEXT NOT NULL DEFAULT '', - confidence DOUBLE PRECISION NOT NULL DEFAULT 0.0, - host TEXT NOT NULL DEFAULT '', - port INTEGER NOT NULL DEFAULT 0, - binary TEXT NOT NULL DEFAULT '', - hit_count INTEGER NOT NULL DEFAULT 1, - first_seen_ms BIGINT NOT NULL, - last_seen_ms BIGINT NOT NULL, - created_at_ms BIGINT NOT NULL, - decided_at_ms BIGINT -); - -CREATE INDEX IF NOT EXISTS idx_draft_chunks_sandbox - ON draft_policy_chunks (sandbox_id, status); - -CREATE UNIQUE INDEX IF NOT EXISTS idx_draft_chunks_endpoint - ON draft_policy_chunks (sandbox_id, host, port, binary) - WHERE status IN ('pending', 'approved', 'rejected'); diff --git a/crates/openshell-server/migrations/sqlite/001_create_objects.sql b/crates/openshell-server/migrations/sqlite/001_create_objects.sql index 26a77e9da6..749a6460e6 100644 --- a/crates/openshell-server/migrations/sqlite/001_create_objects.sql +++ b/crates/openshell-server/migrations/sqlite/001_create_objects.sql @@ -1,10 +1,29 @@ CREATE TABLE IF NOT EXISTS objects ( - object_type TEXT NOT NULL, - id TEXT NOT NULL, - name TEXT NOT NULL, - payload BLOB NOT NULL, + id TEXT PRIMARY KEY, + object_type TEXT NOT NULL, + name TEXT, + scope TEXT, + version INTEGER, + status TEXT, + dedup_key TEXT, + hit_count INTEGER NOT NULL DEFAULT 0, + payload BLOB NOT NULL, created_at_ms INTEGER NOT NULL, - updated_at_ms INTEGER NOT NULL, - PRIMARY KEY (id), - UNIQUE (object_type, name) + updated_at_ms INTEGER NOT NULL ); + +CREATE UNIQUE INDEX IF NOT EXISTS objects_name_uq + ON objects (object_type, name) + WHERE name IS NOT NULL; + +CREATE UNIQUE INDEX IF NOT EXISTS objects_version_uq + ON objects (object_type, scope, version) + WHERE scope IS NOT NULL AND version IS NOT NULL; + +CREATE INDEX IF NOT EXISTS objects_scope_status_idx + ON objects (object_type, scope, status, version) + WHERE scope IS NOT NULL; + +CREATE UNIQUE INDEX IF NOT EXISTS objects_dedup_uq + ON objects (object_type, scope, dedup_key) + WHERE dedup_key IS NOT NULL; diff --git a/crates/openshell-server/migrations/sqlite/002_create_sandbox_policies.sql b/crates/openshell-server/migrations/sqlite/002_create_sandbox_policies.sql deleted file mode 100644 index 395b1897a9..0000000000 --- a/crates/openshell-server/migrations/sqlite/002_create_sandbox_policies.sql +++ /dev/null @@ -1,15 +0,0 @@ -CREATE TABLE IF NOT EXISTS sandbox_policies ( - id TEXT PRIMARY KEY, - sandbox_id TEXT NOT NULL, - version INTEGER NOT NULL, - policy_payload BLOB NOT NULL, - policy_hash TEXT NOT NULL, - status TEXT NOT NULL DEFAULT 'pending', - load_error TEXT, - created_at_ms INTEGER NOT NULL, - loaded_at_ms INTEGER, - UNIQUE (sandbox_id, version) -); - -CREATE INDEX IF NOT EXISTS idx_sandbox_policies_lookup - ON sandbox_policies (sandbox_id, version DESC); diff --git a/crates/openshell-server/migrations/sqlite/003_create_policy_recommendations.sql b/crates/openshell-server/migrations/sqlite/003_create_policy_recommendations.sql deleted file mode 100644 index 069ce20480..0000000000 --- a/crates/openshell-server/migrations/sqlite/003_create_policy_recommendations.sql +++ /dev/null @@ -1,35 +0,0 @@ --- Draft policy chunks: proposed network policy rules awaiting user approval. --- --- One row per (sandbox_id, host, port, binary). The toggle model allows: --- pending -> approved | rejected (initial decision) --- approved <-> rejected (toggle via approve/revoke) --- --- Upserts bump hit_count / last_seen_ms when the same denial recurs. -CREATE TABLE IF NOT EXISTS draft_policy_chunks ( - id TEXT PRIMARY KEY, - sandbox_id TEXT NOT NULL, - draft_version INTEGER NOT NULL, - status TEXT NOT NULL DEFAULT 'pending', - rule_name TEXT NOT NULL, - proposed_rule BLOB NOT NULL, - rationale TEXT NOT NULL DEFAULT '', - security_notes TEXT NOT NULL DEFAULT '', - confidence REAL NOT NULL DEFAULT 0.0, - host TEXT NOT NULL DEFAULT '', - port INTEGER NOT NULL DEFAULT 0, - binary TEXT NOT NULL DEFAULT '', - hit_count INTEGER NOT NULL DEFAULT 1, - first_seen_ms INTEGER NOT NULL, - last_seen_ms INTEGER NOT NULL, - created_at_ms INTEGER NOT NULL, - decided_at_ms INTEGER -); - -CREATE INDEX IF NOT EXISTS idx_draft_chunks_sandbox - ON draft_policy_chunks (sandbox_id, status); - --- Only one active chunk per (sandbox, endpoint, binary). Covers all three --- statuses so rejected chunks block duplicate proposals until re-approved. -CREATE UNIQUE INDEX IF NOT EXISTS idx_draft_chunks_endpoint - ON draft_policy_chunks (sandbox_id, host, port, binary) - WHERE status IN ('pending', 'approved', 'rejected'); diff --git a/crates/openshell-server/src/compute/mod.rs b/crates/openshell-server/src/compute/mod.rs index 60db546666..8f3152b33d 100644 --- a/crates/openshell-server/src/compute/mod.rs +++ b/crates/openshell-server/src/compute/mod.rs @@ -8,7 +8,7 @@ pub mod vm; pub use openshell_driver_docker::DockerComputeConfig; pub use vm::VmComputeConfig; -use crate::grpc::policy::{SANDBOX_SETTINGS_OBJECT_TYPE, sandbox_settings_id}; +use crate::grpc::policy::SANDBOX_SETTINGS_OBJECT_TYPE; use crate::persistence::{ObjectId, ObjectName, ObjectRecord, ObjectType, Store}; use crate::sandbox_index::SandboxIndex; use crate::sandbox_watch::SandboxWatchBus; @@ -86,7 +86,6 @@ impl StartupResume for DockerComputeDriver { .map_err(|err| err.to_string()) } } - /// Interval between store-vs-backend reconciliation sweeps. const RECONCILE_INTERVAL: Duration = Duration::from_secs(60); @@ -480,36 +479,7 @@ impl ComputeRuntime { .map_err(|e| Status::internal(format!("persist sandbox failed: {e}")))?; self.sandbox_index.update_from_sandbox(&sandbox); self.sandbox_watch_bus.notify(&id); - - if let Ok(records) = self.store.list(SshSession::object_type(), 1000, 0).await { - for record in records { - if let Ok(session) = SshSession::decode(record.payload.as_slice()) - && session.sandbox_id == id - && let Err(e) = self - .store - .delete(SshSession::object_type(), session.object_id()) - .await - { - warn!( - session_id = %session.object_id(), - error = %e, - "Failed to delete SSH session during sandbox cleanup" - ); - } - } - } - - if let Err(e) = self - .store - .delete(SANDBOX_SETTINGS_OBJECT_TYPE, &sandbox_settings_id(&id)) - .await - { - warn!( - sandbox_id = %id, - error = %e, - "Failed to delete sandbox settings during cleanup" - ); - } + self.cleanup_sandbox_owned_records(&sandbox).await; let driver_sandbox = driver_sandbox_from_public(&sandbox); let deleted = self @@ -959,6 +929,15 @@ impl ComputeRuntime { } async fn apply_deleted_locked(&self, sandbox_id: &str) -> Result<(), String> { + let sandbox = self + .store + .get_message::(sandbox_id) + .await + .map_err(|e| e.to_string())?; + if let Some(sandbox) = sandbox.as_ref() { + self.cleanup_sandbox_owned_records(sandbox).await; + } + let _ = self .store .delete(Sandbox::object_type(), sandbox_id) @@ -970,6 +949,44 @@ impl ComputeRuntime { Ok(()) } + async fn cleanup_sandbox_owned_records(&self, sandbox: &Sandbox) { + self.cleanup_sandbox_ssh_sessions(sandbox.object_id()).await; + + if let Err(e) = self + .store + .delete_by_name(SANDBOX_SETTINGS_OBJECT_TYPE, sandbox.object_name()) + .await + { + warn!( + sandbox_id = %sandbox.object_id(), + sandbox_name = %sandbox.object_name(), + error = %e, + "Failed to delete sandbox settings during cleanup" + ); + } + } + + async fn cleanup_sandbox_ssh_sessions(&self, sandbox_id: &str) { + if let Ok(records) = self.store.list(SshSession::object_type(), 1000, 0).await { + for record in records { + if let Ok(session) = SshSession::decode(record.payload.as_slice()) + && session.sandbox_id == sandbox_id + && let Err(e) = self + .store + .delete(SshSession::object_type(), session.object_id()) + .await + { + warn!( + sandbox_id = %sandbox_id, + session_id = %session.object_id(), + error = %e, + "Failed to delete SSH session during sandbox cleanup" + ); + } + } + } + } + fn cleanup_sandbox_state(&self, sandbox_id: &str) { self.tracing_log_bus.remove(sandbox_id); self.tracing_log_bus.platform_event_bus.remove(sandbox_id); @@ -1479,6 +1496,117 @@ fn is_terminal_failure_reason(reason: &str) -> bool { !transient_reasons.contains(&reason.as_str()) } +#[cfg(test)] +#[derive(Debug, Default)] +pub(crate) struct NoopTestDriver; + +#[cfg(test)] +#[tonic::async_trait] +impl ComputeDriver for NoopTestDriver { + type WatchSandboxesStream = DriverWatchStream; + + async fn get_capabilities( + &self, + _request: Request, + ) -> Result, Status> + { + Ok(tonic::Response::new( + openshell_core::proto::compute::v1::GetCapabilitiesResponse { + driver_name: "noop-test-driver".to_string(), + driver_version: "test".to_string(), + default_image: "openshell/sandbox:test".to_string(), + supports_gpu: false, + }, + )) + } + + async fn validate_sandbox_create( + &self, + _request: Request, + ) -> Result< + tonic::Response, + Status, + > { + Ok(tonic::Response::new( + openshell_core::proto::compute::v1::ValidateSandboxCreateResponse {}, + )) + } + + async fn get_sandbox( + &self, + _request: Request, + ) -> Result, Status> + { + Err(Status::not_found("sandbox not found")) + } + + async fn list_sandboxes( + &self, + _request: Request, + ) -> Result, Status> + { + Ok(tonic::Response::new( + openshell_core::proto::compute::v1::ListSandboxesResponse { + sandboxes: Vec::new(), + }, + )) + } + + async fn create_sandbox( + &self, + _request: Request, + ) -> Result, Status> + { + Ok(tonic::Response::new( + openshell_core::proto::compute::v1::CreateSandboxResponse {}, + )) + } + + async fn stop_sandbox( + &self, + _request: Request, + ) -> Result, Status> + { + Ok(tonic::Response::new( + openshell_core::proto::compute::v1::StopSandboxResponse {}, + )) + } + + async fn delete_sandbox( + &self, + _request: Request, + ) -> Result, Status> + { + Ok(tonic::Response::new( + openshell_core::proto::compute::v1::DeleteSandboxResponse { deleted: true }, + )) + } + + async fn watch_sandboxes( + &self, + _request: Request, + ) -> Result, Status> { + Ok(tonic::Response::new(Box::pin(futures::stream::empty()))) + } +} + +#[cfg(test)] +pub(crate) async fn new_test_runtime(store: Arc) -> ComputeRuntime { + ComputeRuntime { + driver: Arc::new(NoopTestDriver), + shutdown_cleanup: None, + startup_resume: None, + _driver_process: None, + default_image: "openshell/sandbox:test".to_string(), + store, + sandbox_index: SandboxIndex::new(), + sandbox_watch_bus: SandboxWatchBus::new(), + tracing_log_bus: TracingLogBus::new(), + supervisor_sessions: Arc::new(SupervisorSessionRegistry::new()), + sync_lock: Arc::new(Mutex::new(())), + } +} + #[cfg(test)] mod tests { use super::*; @@ -1667,6 +1795,21 @@ mod tests { } } + fn ssh_session_record(id: &str, sandbox_id: &str) -> SshSession { + SshSession { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: id.to_string(), + name: format!("session-{id}"), + created_at_ms: 1000000, + labels: std::collections::HashMap::new(), + }), + sandbox_id: sandbox_id.to_string(), + token: format!("token-{id}"), + revoked: false, + expires_at_ms: 0, + } + } + fn make_driver_condition(reason: &str, message: &str) -> DriverCondition { DriverCondition { r#type: "Ready".to_string(), @@ -2318,6 +2461,19 @@ mod tests { let sandbox = sandbox_record("sb-1", "sandbox-a", SandboxPhase::Provisioning); runtime.store.put_message(&sandbox).await.unwrap(); runtime.sandbox_index.update_from_sandbox(&sandbox); + runtime + .store + .put( + SANDBOX_SETTINGS_OBJECT_TYPE, + "settings-sb-1", + sandbox.object_name(), + br#"{"revision":1,"settings":{}}"#, + None, + ) + .await + .unwrap(); + let session = ssh_session_record("session-1", sandbox.object_id()); + runtime.store.put_message(&session).await.unwrap(); let mut watch_rx = runtime.sandbox_watch_bus.subscribe(sandbox.object_id()); @@ -2340,6 +2496,22 @@ mod tests { .sandbox_id_for_sandbox_name(sandbox.object_name()) .is_none() ); + assert!( + runtime + .store + .get_by_name(SANDBOX_SETTINGS_OBJECT_TYPE, sandbox.object_name()) + .await + .unwrap() + .is_none() + ); + assert!( + runtime + .store + .get_message::(session.object_id()) + .await + .unwrap() + .is_none() + ); let _ = watch_rx.try_recv(); assert!(matches!( watch_rx.try_recv(), diff --git a/crates/openshell-server/src/grpc/policy.rs b/crates/openshell-server/src/grpc/policy.rs index b0cfc6f38a..8a867d2dad 100644 --- a/crates/openshell-server/src/grpc/policy.rs +++ b/crates/openshell-server/src/grpc/policy.rs @@ -12,6 +12,7 @@ use crate::ServerState; use crate::persistence::{DraftChunkRecord, ObjectId, ObjectName, PolicyRecord, Store}; +use crate::policy_store::PolicyStoreExt; use openshell_core::proto::policy_merge_operation; use openshell_core::proto::setting_value; use openshell_core::proto::{ @@ -62,8 +63,6 @@ use super::{MAX_PAGE_SIZE, StoredSettingValue, StoredSettings, clamp_limit, curr /// Internal object type for durable gateway-global settings. const GLOBAL_SETTINGS_OBJECT_TYPE: &str = "gateway_settings"; -/// Internal object id for the singleton global settings record. -const GLOBAL_SETTINGS_ID: &str = "gateway_settings:global"; const GLOBAL_SETTINGS_NAME: &str = "global"; /// Internal object type for durable sandbox-scoped settings. pub(crate) const SANDBOX_SETTINGS_OBJECT_TYPE: &str = "sandbox_settings"; @@ -168,6 +167,16 @@ fn summarize_cli_policy_merge_op(operation: &PolicyMergeOp) -> String { } } +fn ensure_chunk_belongs_to_sandbox( + chunk: &DraftChunkRecord, + sandbox_id: &str, +) -> Result<(), Status> { + if chunk.sandbox_id != sandbox_id { + return Err(Status::not_found("chunk not found")); + } + Ok(()) +} + fn summarize_add_endpoint(rule_name: &str, rule: &NetworkPolicyRule) -> String { let endpoints = rule .endpoints @@ -338,9 +347,10 @@ pub(super) async fn handle_get_sandbox_config( // Lazy backfill: no policy history exists yet. let spec = sandbox .spec + .as_ref() .ok_or_else(|| Status::internal("sandbox has no spec"))?; - match spec.policy { + match spec.policy.clone() { None => { debug!( sandbox_id = %sandbox_id, @@ -386,7 +396,8 @@ pub(super) async fn handle_get_sandbox_config( }; let global_settings = load_global_settings(state.store.as_ref()).await?; - let sandbox_settings = load_sandbox_settings(state.store.as_ref(), &sandbox_id).await?; + let sandbox_settings = + load_sandbox_settings(state.store.as_ref(), sandbox.object_name()).await?; let mut global_policy_version: u32 = 0; @@ -685,13 +696,12 @@ pub(super) async fn handle_update_config( } let mut sandbox_settings = - load_sandbox_settings(state.store.as_ref(), &sandbox_id).await?; + load_sandbox_settings(state.store.as_ref(), sandbox.object_name()).await?; let removed = sandbox_settings.settings.remove(key).is_some(); if removed { sandbox_settings.revision = sandbox_settings.revision.wrapping_add(1); save_sandbox_settings( state.store.as_ref(), - &sandbox_id, sandbox.object_name(), &sandbox_settings, ) @@ -718,13 +728,13 @@ pub(super) async fn handle_update_config( .ok_or_else(|| Status::invalid_argument("setting_value is required"))?; let stored = proto_setting_to_stored(key, setting)?; - let mut sandbox_settings = load_sandbox_settings(state.store.as_ref(), &sandbox_id).await?; + let mut sandbox_settings = + load_sandbox_settings(state.store.as_ref(), sandbox.object_name()).await?; let changed = upsert_setting_value(&mut sandbox_settings.settings, key, stored); if changed { sandbox_settings.revision = sandbox_settings.revision.wrapping_add(1); save_sandbox_settings( state.store.as_ref(), - &sandbox_id, sandbox.object_name(), &sandbox_settings, ) @@ -1336,6 +1346,7 @@ pub(super) async fn handle_approve_draft_chunk( .await .map_err(|e| Status::internal(format!("fetch chunk failed: {e}")))? .ok_or_else(|| Status::not_found("chunk not found"))?; + ensure_chunk_belongs_to_sandbox(&chunk, &sandbox_id)?; if chunk.status != "pending" && chunk.status != "rejected" { return Err(Status::failed_precondition(format!( @@ -1421,6 +1432,7 @@ pub(super) async fn handle_reject_draft_chunk( .await .map_err(|e| Status::internal(format!("fetch chunk failed: {e}")))? .ok_or_else(|| Status::not_found("chunk not found"))?; + ensure_chunk_belongs_to_sandbox(&chunk, &sandbox_id)?; if chunk.status != "pending" && chunk.status != "approved" { return Err(Status::failed_precondition(format!( @@ -1603,12 +1615,13 @@ pub(super) async fn handle_edit_draft_chunk( .proposed_rule .ok_or_else(|| Status::invalid_argument("proposed_rule is required"))?; - let _sandbox = state + let sandbox = state .store .get_message_by_name::(&req.name) .await .map_err(|e| Status::internal(format!("fetch sandbox failed: {e}")))? .ok_or_else(|| Status::not_found("sandbox not found"))?; + let sandbox_id = sandbox.object_id().to_string(); let chunk = state .store @@ -1616,6 +1629,7 @@ pub(super) async fn handle_edit_draft_chunk( .await .map_err(|e| Status::internal(format!("fetch chunk failed: {e}")))? .ok_or_else(|| Status::not_found("chunk not found"))?; + ensure_chunk_belongs_to_sandbox(&chunk, &sandbox_id)?; if chunk.status != "pending" { return Err(Status::failed_precondition(format!( @@ -1665,6 +1679,7 @@ pub(super) async fn handle_undo_draft_chunk( .await .map_err(|e| Status::internal(format!("fetch chunk failed: {e}")))? .ok_or_else(|| Status::not_found("chunk not found"))?; + ensure_chunk_belongs_to_sandbox(&chunk, &sandbox_id)?; if chunk.status != "approved" { return Err(Status::failed_precondition(format!( @@ -2261,8 +2276,7 @@ async fn apply_merge_operations_with_retry( return Ok((next_version, hash)); } Err(e) => { - let msg = e.to_string(); - if msg.contains("UNIQUE") || msg.contains("unique") || msg.contains("duplicate") { + if e.is_unique_violation_on("objects_version_uq") { warn!( sandbox_id = %sandbox_id, attempt, @@ -2403,7 +2417,7 @@ fn upsert_setting_value( } pub(super) async fn load_global_settings(store: &Store) -> Result { - load_settings_record(store, GLOBAL_SETTINGS_OBJECT_TYPE, GLOBAL_SETTINGS_ID).await + load_settings_record(store, GLOBAL_SETTINGS_OBJECT_TYPE, GLOBAL_SETTINGS_NAME).await } pub(super) async fn save_global_settings( @@ -2413,53 +2427,34 @@ pub(super) async fn save_global_settings( save_settings_record( store, GLOBAL_SETTINGS_OBJECT_TYPE, - GLOBAL_SETTINGS_ID, GLOBAL_SETTINGS_NAME, settings, ) .await } -/// Derive a distinct settings record ID from a sandbox UUID. -pub(crate) fn sandbox_settings_id(sandbox_id: &str) -> String { - format!("settings:{sandbox_id}") -} - pub(super) async fn load_sandbox_settings( store: &Store, - sandbox_id: &str, + sandbox_name: &str, ) -> Result { - load_settings_record( - store, - SANDBOX_SETTINGS_OBJECT_TYPE, - &sandbox_settings_id(sandbox_id), - ) - .await + load_settings_record(store, SANDBOX_SETTINGS_OBJECT_TYPE, sandbox_name).await } pub(super) async fn save_sandbox_settings( store: &Store, - sandbox_id: &str, sandbox_name: &str, settings: &StoredSettings, ) -> Result<(), Status> { - save_settings_record( - store, - SANDBOX_SETTINGS_OBJECT_TYPE, - &sandbox_settings_id(sandbox_id), - sandbox_name, - settings, - ) - .await + save_settings_record(store, SANDBOX_SETTINGS_OBJECT_TYPE, sandbox_name, settings).await } async fn load_settings_record( store: &Store, object_type: &str, - id: &str, + name: &str, ) -> Result { let record = store - .get(object_type, id) + .get_by_name(object_type, name) .await .map_err(|e| Status::internal(format!("fetch settings failed: {e}")))?; if let Some(record) = record { @@ -2473,14 +2468,19 @@ async fn load_settings_record( async fn save_settings_record( store: &Store, object_type: &str, - id: &str, name: &str, settings: &StoredSettings, ) -> Result<(), Status> { let payload = serde_json::to_vec(settings) .map_err(|e| Status::internal(format!("encode settings payload failed: {e}")))?; store - .put(object_type, id, name, &payload, None) + .put( + object_type, + &uuid::Uuid::new_v4().to_string(), + name, + &payload, + None, + ) .await .map_err(|e| Status::internal(format!("persist settings failed: {e}")))?; Ok(()) @@ -2579,7 +2579,14 @@ fn materialize_global_settings( #[cfg(test)] mod tests { use super::*; + use crate::ServerState; + use crate::compute::new_test_runtime; use crate::persistence::Store; + use crate::sandbox_index::SandboxIndex; + use crate::sandbox_watch::SandboxWatchBus; + use crate::supervisor_session::SupervisorSessionRegistry; + use crate::tracing_bus::TracingLogBus; + use openshell_core::Config; use std::collections::HashMap; use std::sync::Arc; use tonic::Code; @@ -2676,6 +2683,371 @@ mod tests { assert_eq!(policy.process.unwrap().run_as_user, "sandbox"); } + async fn test_server_state() -> Arc { + let store = Arc::new( + Store::connect("sqlite::memory:?cache=shared") + .await + .unwrap(), + ); + let compute = new_test_runtime(store.clone()).await; + Arc::new(ServerState::new( + Config::new(None) + .with_database_url("sqlite::memory:?cache=shared") + .with_ssh_handshake_secret("test-secret"), + store, + compute, + SandboxIndex::new(), + SandboxWatchBus::new(), + TracingLogBus::new(), + Arc::new(SupervisorSessionRegistry::new()), + )) + } + + #[tokio::test] + async fn draft_chunk_handler_lifecycle_round_trip() { + use openshell_core::proto::{ + GetDraftPolicyRequest, NetworkBinary, NetworkEndpoint, SandboxPhase, SandboxSpec, + }; + + let state = test_server_state().await; + let sandbox = Sandbox { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: "sb-draft-flow".to_string(), + name: "draft-flow".to_string(), + created_at_ms: 1_000_000, + labels: std::collections::HashMap::new(), + }), + spec: Some(SandboxSpec { + policy: None, + ..Default::default() + }), + phase: SandboxPhase::Ready as i32, + ..Default::default() + }; + state.store.put_message(&sandbox).await.unwrap(); + let sandbox_name = sandbox.object_name().to_string(); + + let proposed_rule = NetworkPolicyRule { + name: "allow_example".to_string(), + endpoints: vec![NetworkEndpoint { + host: "api.example.com".to_string(), + port: 443, + ..Default::default() + }], + binaries: vec![NetworkBinary { + path: "/usr/bin/curl".to_string(), + ..Default::default() + }], + }; + + let submit = handle_submit_policy_analysis( + &state, + Request::new(SubmitPolicyAnalysisRequest { + name: sandbox_name.clone(), + proposed_chunks: vec![PolicyChunk { + rule_name: "allow_example".to_string(), + proposed_rule: Some(proposed_rule.clone()), + rationale: "observed denied request".to_string(), + confidence: 0.85, + hit_count: 3, + first_seen_ms: 100, + last_seen_ms: 200, + binary: "/usr/bin/curl".to_string(), + ..Default::default() + }], + ..Default::default() + }), + ) + .await + .unwrap() + .into_inner(); + assert_eq!(submit.accepted_chunks, 1); + assert_eq!(submit.rejected_chunks, 0); + + let draft_policy = handle_get_draft_policy( + &state, + Request::new(GetDraftPolicyRequest { + name: sandbox_name.clone(), + status_filter: String::new(), + }), + ) + .await + .unwrap() + .into_inner(); + assert_eq!(draft_policy.draft_version, 1); + assert_eq!(draft_policy.chunks.len(), 1); + assert_eq!(draft_policy.chunks[0].status, "pending"); + let chunk_id = draft_policy.chunks[0].id.clone(); + + let approve = handle_approve_draft_chunk( + &state, + Request::new(ApproveDraftChunkRequest { + name: sandbox_name.clone(), + chunk_id: chunk_id.clone(), + }), + ) + .await + .unwrap() + .into_inner(); + assert_eq!(approve.policy_version, 1); + assert!(!approve.policy_hash.is_empty()); + + let history_after_approve = handle_get_draft_history( + &state, + Request::new(GetDraftHistoryRequest { + name: sandbox_name.clone(), + }), + ) + .await + .unwrap() + .into_inner(); + assert_eq!(history_after_approve.entries.len(), 2); + assert_eq!(history_after_approve.entries[0].event_type, "proposed"); + assert_eq!(history_after_approve.entries[1].event_type, "approved"); + assert_eq!(history_after_approve.entries[1].chunk_id, chunk_id); + + let policies_after_approve = handle_list_sandbox_policies( + &state, + Request::new(ListSandboxPoliciesRequest { + name: sandbox_name.clone(), + limit: 10, + offset: 0, + global: false, + }), + ) + .await + .unwrap() + .into_inner(); + assert_eq!(policies_after_approve.revisions.len(), 1); + assert_eq!(policies_after_approve.revisions[0].version, 1); + + let undo = handle_undo_draft_chunk( + &state, + Request::new(UndoDraftChunkRequest { + name: sandbox_name.clone(), + chunk_id: chunk_id.clone(), + }), + ) + .await + .unwrap() + .into_inner(); + assert_eq!(undo.policy_version, 2); + assert!(!undo.policy_hash.is_empty()); + + let draft_policy_after_undo = handle_get_draft_policy( + &state, + Request::new(GetDraftPolicyRequest { + name: sandbox_name.clone(), + status_filter: String::new(), + }), + ) + .await + .unwrap() + .into_inner(); + assert_eq!(draft_policy_after_undo.chunks.len(), 1); + assert_eq!(draft_policy_after_undo.chunks[0].status, "pending"); + + let history_after_undo = handle_get_draft_history( + &state, + Request::new(GetDraftHistoryRequest { + name: sandbox_name.clone(), + }), + ) + .await + .unwrap() + .into_inner(); + assert_eq!(history_after_undo.entries.len(), 1); + assert_eq!(history_after_undo.entries[0].event_type, "proposed"); + + let policies_after_undo = handle_list_sandbox_policies( + &state, + Request::new(ListSandboxPoliciesRequest { + name: sandbox_name.clone(), + limit: 10, + offset: 0, + global: false, + }), + ) + .await + .unwrap() + .into_inner(); + assert_eq!(policies_after_undo.revisions.len(), 2); + assert_eq!(policies_after_undo.revisions[0].version, 2); + assert_eq!(policies_after_undo.revisions[1].version, 1); + + let cleared = handle_clear_draft_chunks( + &state, + Request::new(ClearDraftChunksRequest { + name: sandbox_name.clone(), + }), + ) + .await + .unwrap() + .into_inner(); + assert_eq!(cleared.chunks_cleared, 1); + + let draft_policy_after_clear = handle_get_draft_policy( + &state, + Request::new(GetDraftPolicyRequest { + name: sandbox_name.clone(), + status_filter: String::new(), + }), + ) + .await + .unwrap() + .into_inner(); + assert!(draft_policy_after_clear.chunks.is_empty()); + + let history_after_clear = handle_get_draft_history( + &state, + Request::new(GetDraftHistoryRequest { name: sandbox_name }), + ) + .await + .unwrap() + .into_inner(); + assert!(history_after_clear.entries.is_empty()); + } + + #[tokio::test] + async fn draft_chunk_handlers_reject_cross_sandbox_chunk_ids() { + use openshell_core::proto::{NetworkBinary, NetworkEndpoint, SandboxPhase, SandboxSpec}; + + let state = test_server_state().await; + let sandbox_a = Sandbox { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: "sb-draft-owner".to_string(), + name: "draft-owner".to_string(), + created_at_ms: 1_000_000, + labels: std::collections::HashMap::new(), + }), + spec: Some(SandboxSpec { + policy: None, + ..Default::default() + }), + phase: SandboxPhase::Ready as i32, + ..Default::default() + }; + let sandbox_b = Sandbox { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: "sb-draft-other".to_string(), + name: "draft-other".to_string(), + created_at_ms: 1_000_001, + labels: std::collections::HashMap::new(), + }), + spec: Some(SandboxSpec { + policy: None, + ..Default::default() + }), + phase: SandboxPhase::Ready as i32, + ..Default::default() + }; + state.store.put_message(&sandbox_a).await.unwrap(); + state.store.put_message(&sandbox_b).await.unwrap(); + + let proposed_rule = NetworkPolicyRule { + name: "allow_example".to_string(), + endpoints: vec![NetworkEndpoint { + host: "api.example.com".to_string(), + port: 443, + ..Default::default() + }], + binaries: vec![NetworkBinary { + path: "/usr/bin/curl".to_string(), + ..Default::default() + }], + }; + + handle_submit_policy_analysis( + &state, + Request::new(SubmitPolicyAnalysisRequest { + name: sandbox_a.object_name().to_string(), + proposed_chunks: vec![PolicyChunk { + rule_name: "allow_example".to_string(), + proposed_rule: Some(proposed_rule.clone()), + rationale: "observed denied request".to_string(), + confidence: 0.85, + hit_count: 3, + first_seen_ms: 100, + last_seen_ms: 200, + binary: "/usr/bin/curl".to_string(), + ..Default::default() + }], + ..Default::default() + }), + ) + .await + .unwrap(); + + let draft_policy = handle_get_draft_policy( + &state, + Request::new(GetDraftPolicyRequest { + name: sandbox_a.object_name().to_string(), + status_filter: String::new(), + }), + ) + .await + .unwrap() + .into_inner(); + let chunk_id = draft_policy.chunks[0].id.clone(); + let other_name = sandbox_b.object_name().to_string(); + + let approve_err = handle_approve_draft_chunk( + &state, + Request::new(ApproveDraftChunkRequest { + name: other_name.clone(), + chunk_id: chunk_id.clone(), + }), + ) + .await + .unwrap_err(); + assert_eq!(approve_err.code(), Code::NotFound); + + let reject_err = handle_reject_draft_chunk( + &state, + Request::new(RejectDraftChunkRequest { + name: other_name.clone(), + chunk_id: chunk_id.clone(), + reason: "wrong sandbox".to_string(), + }), + ) + .await + .unwrap_err(); + assert_eq!(reject_err.code(), Code::NotFound); + + let edit_err = handle_edit_draft_chunk( + &state, + Request::new(EditDraftChunkRequest { + name: other_name.clone(), + chunk_id: chunk_id.clone(), + proposed_rule: Some(proposed_rule.clone()), + }), + ) + .await + .unwrap_err(); + assert_eq!(edit_err.code(), Code::NotFound); + + handle_approve_draft_chunk( + &state, + Request::new(ApproveDraftChunkRequest { + name: sandbox_a.object_name().to_string(), + chunk_id: chunk_id.clone(), + }), + ) + .await + .unwrap(); + + let undo_err = handle_undo_draft_chunk( + &state, + Request::new(UndoDraftChunkRequest { + name: other_name, + chunk_id, + }), + ) + .await + .unwrap_err(); + assert_eq!(undo_err.code(), Code::NotFound); + } + #[test] fn build_gateway_policy_audit_message_formats_ocsf_config_line() { let message = build_gateway_policy_audit_message( @@ -3401,25 +3773,9 @@ mod tests { } #[test] - fn sandbox_settings_id_has_prefix_preventing_collision() { - let sandbox_id = "abc-123"; - let settings_id = sandbox_settings_id(sandbox_id); - assert!(settings_id.starts_with("settings:")); - assert_ne!(settings_id, sandbox_id); - } - - #[test] - fn sandbox_settings_id_different_sandboxes_produce_different_ids() { - let id_a = sandbox_settings_id("sandbox-1"); - let id_b = sandbox_settings_id("sandbox-2"); - assert_ne!(id_a, id_b); - } - - #[test] - fn sandbox_settings_id_embeds_sandbox_id() { - let sandbox_id = "some-uuid-value"; - let settings_id = sandbox_settings_id(sandbox_id); - assert!(settings_id.contains(sandbox_id)); + fn sandbox_settings_names_match_sandbox_names() { + let sandbox_name = "my-sandbox"; + assert_eq!(sandbox_name, "my-sandbox"); } // ---- compute_config_revision ---- @@ -3629,17 +3985,17 @@ mod tests { .await .unwrap(); - let sandbox_id = "sb-uuid-123"; + let sandbox_name = "my-sandbox"; let mut settings = StoredSettings::default(); settings .settings .insert("dummy_int".to_string(), StoredSettingValue::Int(99)); settings.revision = 3; - save_sandbox_settings(&store, sandbox_id, "my-sandbox", &settings) + save_sandbox_settings(&store, sandbox_name, &settings) .await .unwrap(); - let loaded = load_sandbox_settings(&store, sandbox_id).await.unwrap(); + let loaded = load_sandbox_settings(&store, sandbox_name).await.unwrap(); assert_eq!(loaded.revision, 3); assert_eq!( loaded.settings.get("dummy_int"), @@ -3784,8 +4140,8 @@ mod tests { let loaded = load_global_settings(&store).await.unwrap(); assert!(!loaded.settings.contains_key("log_level")); - let sandbox_id = "test-sandbox-uuid"; - let mut sandbox_settings = load_sandbox_settings(&store, sandbox_id).await.unwrap(); + let sandbox_name = "test-sandbox"; + let mut sandbox_settings = load_sandbox_settings(&store, sandbox_name).await.unwrap(); let changed = upsert_setting_value( &mut sandbox_settings.settings, "log_level", @@ -3793,11 +4149,11 @@ mod tests { ); assert!(changed); sandbox_settings.revision = sandbox_settings.revision.wrapping_add(1); - save_sandbox_settings(&store, sandbox_id, "test-sandbox", &sandbox_settings) + save_sandbox_settings(&store, sandbox_name, &sandbox_settings) .await .unwrap(); - let reloaded = load_sandbox_settings(&store, sandbox_id).await.unwrap(); + let reloaded = load_sandbox_settings(&store, sandbox_name).await.unwrap(); assert_eq!( reloaded.settings.get("log_level"), Some(&StoredSettingValue::String("debug".to_string())), diff --git a/crates/openshell-server/src/lib.rs b/crates/openshell-server/src/lib.rs index d587c0bb3e..979bf4c1d6 100644 --- a/crates/openshell-server/src/lib.rs +++ b/crates/openshell-server/src/lib.rs @@ -27,6 +27,7 @@ mod http; mod inference; mod multiplex; mod persistence; +pub(crate) mod policy_store; mod sandbox_index; mod sandbox_watch; mod ssh_tunnel; diff --git a/crates/openshell-server/src/persistence/mod.rs b/crates/openshell-server/src/persistence/mod.rs index d64f4cdf85..80810c1732 100644 --- a/crates/openshell-server/src/persistence/mod.rs +++ b/crates/openshell-server/src/persistence/mod.rs @@ -6,14 +6,66 @@ mod postgres; mod sqlite; -use openshell_core::{Error, Result}; +pub use openshell_core::proto::{ + StoredDraftChunk as DraftChunkRecord, StoredPolicyRevision as PolicyRecord, +}; + +use openshell_core::{Error as CoreError, Result as CoreResult}; use prost::Message; use rand::Rng; use std::time::{SystemTime, UNIX_EPOCH}; +use thiserror::Error; pub use postgres::PostgresStore; pub use sqlite::SqliteStore; +pub type PersistenceResult = Result; + +/// Persistence-layer error type. +#[derive(Debug, Error, Clone)] +pub enum PersistenceError { + #[error("configuration error: {0}")] + Config(String), + #[error("database error: {0}")] + Database(String), + #[error("migration error: {0}")] + Migration(String), + #[error("decode error: {0}")] + Decode(String), + #[error("encode error: {0}")] + Encode(String), + #[error("unique violation{constraint_msg}")] + UniqueViolation { + constraint: Option, + detail: Option, + constraint_msg: String, + }, +} + +impl PersistenceError { + pub fn unique_violation(constraint: Option, detail: Option) -> Self { + let constraint_msg = constraint + .as_ref() + .map(|value| format!(" on {value}")) + .unwrap_or_default(); + Self::UniqueViolation { + constraint, + detail, + constraint_msg, + } + } + + pub fn is_unique_violation_on(&self, constraint: &str) -> bool { + matches!( + self, + Self::UniqueViolation { + constraint: Some(value), + .. + } if value == constraint + ) + } +} + /// Stored object record. #[derive(Debug, Clone)] pub struct ObjectRecord { @@ -27,20 +79,6 @@ pub struct ObjectRecord { pub labels: Option, } -/// Stored sandbox policy revision record. -#[derive(Debug, Clone)] -pub struct PolicyRecord { - pub id: String, - pub sandbox_id: String, - pub version: i64, - pub policy_payload: Vec, - pub policy_hash: String, - pub status: String, - pub load_error: Option, - pub created_at_ms: i64, - pub loaded_at_ms: Option, -} - /// Persistence store implementations. #[derive(Debug, Clone)] pub enum Store { @@ -67,23 +105,33 @@ pub fn generate_name() -> String { impl Store { /// Connect to a persistence store based on the database URL. - pub async fn connect(url: &str) -> Result { + pub async fn connect(url: &str) -> CoreResult { if url.starts_with("postgres://") || url.starts_with("postgresql://") { - let store = PostgresStore::connect(url).await?; - store.migrate().await?; + let store = PostgresStore::connect(url) + .await + .map_err(|e| CoreError::execution(e.to_string()))?; + store + .migrate() + .await + .map_err(|e| CoreError::execution(e.to_string()))?; Ok(Self::Postgres(store)) } else if url.starts_with("sqlite:") { - let store = SqliteStore::connect(url).await?; - store.migrate().await?; + let store = SqliteStore::connect(url) + .await + .map_err(|e| CoreError::execution(e.to_string()))?; + store + .migrate() + .await + .map_err(|e| CoreError::execution(e.to_string()))?; Ok(Self::Sqlite(store)) } else { - Err(Error::config(format!( + Err(CoreError::config(format!( "unsupported database URL scheme: {url}" ))) } } - /// Insert or update an object. + /// Insert or update a generic named object. pub async fn put( &self, object_type: &str, @@ -91,7 +139,7 @@ impl Store { name: &str, payload: &[u8], labels: Option<&str>, - ) -> Result<()> { + ) -> PersistenceResult<()> { match self { Self::Postgres(store) => store.put(object_type, id, name, payload, labels).await, Self::Sqlite(store) => store.put(object_type, id, name, payload, labels).await, @@ -99,7 +147,11 @@ impl Store { } /// Fetch an object by id. - pub async fn get(&self, object_type: &str, id: &str) -> Result> { + pub async fn get( + &self, + object_type: &str, + id: &str, + ) -> PersistenceResult> { match self { Self::Postgres(store) => store.get(object_type, id).await, Self::Sqlite(store) => store.get(object_type, id).await, @@ -107,7 +159,11 @@ impl Store { } /// Fetch an object by name within an object type. - pub async fn get_by_name(&self, object_type: &str, name: &str) -> Result> { + pub async fn get_by_name( + &self, + object_type: &str, + name: &str, + ) -> PersistenceResult> { match self { Self::Postgres(store) => store.get_by_name(object_type, name).await, Self::Sqlite(store) => store.get_by_name(object_type, name).await, @@ -115,7 +171,7 @@ impl Store { } /// Delete an object by id. - pub async fn delete(&self, object_type: &str, id: &str) -> Result { + pub async fn delete(&self, object_type: &str, id: &str) -> PersistenceResult { match self { Self::Postgres(store) => store.delete(object_type, id).await, Self::Sqlite(store) => store.delete(object_type, id).await, @@ -123,7 +179,7 @@ impl Store { } /// Delete an object by name within an object type. - pub async fn delete_by_name(&self, object_type: &str, name: &str) -> Result { + pub async fn delete_by_name(&self, object_type: &str, name: &str) -> PersistenceResult { match self { Self::Postgres(store) => store.delete_by_name(object_type, name).await, Self::Sqlite(store) => store.delete_by_name(object_type, name).await, @@ -136,7 +192,7 @@ impl Store { object_type: &str, limit: u32, offset: u32, - ) -> Result> { + ) -> PersistenceResult> { match self { Self::Postgres(store) => store.list(object_type, limit, offset).await, Self::Sqlite(store) => store.list(object_type, limit, offset).await, @@ -151,7 +207,7 @@ impl Store { label_selector: &str, limit: u32, offset: u32, - ) -> Result> { + ) -> PersistenceResult> { match self { Self::Postgres(store) => { store @@ -166,117 +222,6 @@ impl Store { } } - // ----------------------------------------------------------------------- - // Policy revision operations - // ----------------------------------------------------------------------- - - /// Insert a new policy revision. - pub async fn put_policy_revision( - &self, - id: &str, - sandbox_id: &str, - version: i64, - payload: &[u8], - hash: &str, - ) -> Result<()> { - match self { - Self::Postgres(store) => { - store - .put_policy_revision(id, sandbox_id, version, payload, hash) - .await - } - Self::Sqlite(store) => { - store - .put_policy_revision(id, sandbox_id, version, payload, hash) - .await - } - } - } - - /// Get the latest policy revision for a sandbox (by highest version, any status). - pub async fn get_latest_policy(&self, sandbox_id: &str) -> Result> { - match self { - Self::Postgres(store) => store.get_latest_policy(sandbox_id).await, - Self::Sqlite(store) => store.get_latest_policy(sandbox_id).await, - } - } - - /// Get the latest loaded policy revision for a sandbox. - pub async fn get_latest_loaded_policy(&self, sandbox_id: &str) -> Result> { - match self { - Self::Postgres(store) => store.get_latest_loaded_policy(sandbox_id).await, - Self::Sqlite(store) => store.get_latest_loaded_policy(sandbox_id).await, - } - } - - /// Get a specific policy revision by sandbox id and version. - pub async fn get_policy_by_version( - &self, - sandbox_id: &str, - version: i64, - ) -> Result> { - match self { - Self::Postgres(store) => store.get_policy_by_version(sandbox_id, version).await, - Self::Sqlite(store) => store.get_policy_by_version(sandbox_id, version).await, - } - } - - /// List policy revisions for a sandbox, ordered by version descending. - pub async fn list_policies( - &self, - sandbox_id: &str, - limit: u32, - offset: u32, - ) -> Result> { - match self { - Self::Postgres(store) => store.list_policies(sandbox_id, limit, offset).await, - Self::Sqlite(store) => store.list_policies(sandbox_id, limit, offset).await, - } - } - - /// Update the status of a policy revision. - pub async fn update_policy_status( - &self, - sandbox_id: &str, - version: i64, - status: &str, - load_error: Option<&str>, - loaded_at_ms: Option, - ) -> Result { - match self { - Self::Postgres(store) => { - store - .update_policy_status(sandbox_id, version, status, load_error, loaded_at_ms) - .await - } - Self::Sqlite(store) => { - store - .update_policy_status(sandbox_id, version, status, load_error, loaded_at_ms) - .await - } - } - } - - /// Mark all pending and loaded policy revisions older than `before_version` as superseded. - pub async fn supersede_older_policies( - &self, - sandbox_id: &str, - before_version: i64, - ) -> Result { - match self { - Self::Postgres(store) => { - store - .supersede_older_policies(sandbox_id, before_version) - .await - } - Self::Sqlite(store) => { - store - .supersede_older_policies(sandbox_id, before_version) - .await - } - } - } - // ----------------------------------------------------------------------- // Generic protobuf message helpers // ----------------------------------------------------------------------- @@ -285,16 +230,15 @@ impl Store { pub async fn put_message( &self, message: &T, - ) -> Result<()> { + ) -> PersistenceResult<()> { // Serialize labels to JSON let labels_map = message.object_labels(); let labels_json = if labels_map.as_ref().map_or(true, |m| m.is_empty()) { None } else { - Some( - serde_json::to_string(&labels_map) - .map_err(|e| Error::execution(format!("failed to serialize labels: {e}")))?, - ) + Some(serde_json::to_string(&labels_map).map_err(|e| { + PersistenceError::Encode(format!("failed to serialize labels: {e}")) + })?) }; self.put( @@ -308,161 +252,73 @@ impl Store { } /// Fetch and decode a protobuf message by id. - pub async fn get_message( + pub async fn get_message( &self, id: &str, - ) -> Result> { + ) -> PersistenceResult> { let record = self.get(T::object_type(), id).await?; let Some(record) = record else { return Ok(None); }; - let message = T::decode(record.payload.as_slice()) - .map_err(|e| Error::execution(format!("protobuf decode error: {e}")))?; - - // Note: labels are already in the proto message from the payload - // The database `labels` column is for filtering only - Ok(Some(message)) + T::decode(record.payload.as_slice()) + .map(Some) + .map_err(|e| PersistenceError::Decode(format!("protobuf decode error: {e}"))) } /// Fetch and decode a protobuf message by name. - pub async fn get_message_by_name( + pub async fn get_message_by_name( &self, name: &str, - ) -> Result> { + ) -> PersistenceResult> { let record = self.get_by_name(T::object_type(), name).await?; let Some(record) = record else { return Ok(None); }; - let message = T::decode(record.payload.as_slice()) - .map_err(|e| Error::execution(format!("protobuf decode error: {e}")))?; - - // Note: labels are already in the proto message from the payload - // The database `labels` column is for filtering only - Ok(Some(message)) - } - - // ----------------------------------------------------------------------- - // Draft policy chunk operations - // ----------------------------------------------------------------------- - - /// Insert a new draft policy chunk. - pub async fn put_draft_chunk(&self, chunk: &DraftChunkRecord) -> Result<()> { - match self { - Self::Postgres(store) => store.put_draft_chunk(chunk).await, - Self::Sqlite(store) => store.put_draft_chunk(chunk).await, - } - } - - /// Fetch a single draft chunk by id. - pub async fn get_draft_chunk(&self, id: &str) -> Result> { - match self { - Self::Postgres(store) => store.get_draft_chunk(id).await, - Self::Sqlite(store) => store.get_draft_chunk(id).await, - } - } - - /// List draft chunks for a sandbox, optionally filtered by status. - pub async fn list_draft_chunks( - &self, - sandbox_id: &str, - status_filter: Option<&str>, - ) -> Result> { - match self { - Self::Postgres(store) => store.list_draft_chunks(sandbox_id, status_filter).await, - Self::Sqlite(store) => store.list_draft_chunks(sandbox_id, status_filter).await, - } - } - - /// Update the status of a draft chunk. - pub async fn update_draft_chunk_status( - &self, - id: &str, - status: &str, - decided_at_ms: Option, - ) -> Result { - match self { - Self::Postgres(store) => { - store - .update_draft_chunk_status(id, status, decided_at_ms) - .await - } - Self::Sqlite(store) => { - store - .update_draft_chunk_status(id, status, decided_at_ms) - .await - } - } - } - - /// Update the proposed rule on a pending draft chunk. - pub async fn update_draft_chunk_rule(&self, id: &str, proposed_rule: &[u8]) -> Result { - match self { - Self::Postgres(store) => store.update_draft_chunk_rule(id, proposed_rule).await, - Self::Sqlite(store) => store.update_draft_chunk_rule(id, proposed_rule).await, - } - } - - /// Delete all draft chunks for a sandbox with a given status. - pub async fn delete_draft_chunks(&self, sandbox_id: &str, status: &str) -> Result { - match self { - Self::Postgres(store) => store.delete_draft_chunks(sandbox_id, status).await, - Self::Sqlite(store) => store.delete_draft_chunks(sandbox_id, status).await, - } - } - - /// Get the current maximum draft version for a sandbox. - pub async fn get_draft_version(&self, sandbox_id: &str) -> Result { - match self { - Self::Postgres(store) => store.get_draft_version(sandbox_id).await, - Self::Sqlite(store) => store.get_draft_version(sandbox_id).await, - } + T::decode(record.payload.as_slice()) + .map(Some) + .map_err(|e| PersistenceError::Decode(format!("protobuf decode error: {e}"))) } } -/// Stored draft policy chunk record. -#[derive(Debug, Clone)] -pub struct DraftChunkRecord { - pub id: String, - pub sandbox_id: String, - pub draft_version: i64, - pub status: String, - pub rule_name: String, - pub proposed_rule: Vec, - pub rationale: String, - pub security_notes: String, - pub confidence: f64, - pub created_at_ms: i64, - pub decided_at_ms: Option, - /// Denormalized endpoint host (lowercase) for DB-level dedup. - pub host: String, - /// Denormalized endpoint port for DB-level dedup. - pub port: i32, - /// Binary path that triggered the denial (for per-binary dedup). - pub binary: String, - /// How many times this endpoint has been seen across denial flush cycles. - pub hit_count: i32, - /// First time this endpoint was proposed (ms since epoch). - pub first_seen_ms: i64, - /// Most recent time this endpoint was re-proposed (ms since epoch). - pub last_seen_ms: i64, -} - -pub fn current_time_ms() -> Result { +pub fn current_time_ms() -> PersistenceResult { let now = SystemTime::now() .duration_since(UNIX_EPOCH) - .map_err(|e| Error::execution(format!("time error: {e}")))?; + .map_err(|e| PersistenceError::Database(format!("time error: {e}")))?; i64::try_from(now.as_millis()) - .map_err(|e| Error::execution(format!("time conversion error: {e}"))) + .map_err(|e| PersistenceError::Database(format!("time conversion error: {e}"))) +} + +fn map_db_error(error: &sqlx::Error) -> PersistenceError { + if let sqlx::Error::Database(db) = error { + if db.is_unique_violation() { + let constraint = db + .constraint() + .map(ToString::to_string) + .or_else(|| infer_sqlite_unique_constraint(db.message())); + return PersistenceError::unique_violation(constraint, Some(db.message().to_string())); + } + } + PersistenceError::Database(error.to_string()) } -fn map_db_error(error: &sqlx::Error) -> Error { - Error::execution(format!("database error: {error}")) +fn infer_sqlite_unique_constraint(message: &str) -> Option { + if message.contains("objects.object_type, objects.scope, objects.version") { + Some("objects_version_uq".to_string()) + } else if message.contains("objects.object_type, objects.scope, objects.dedup_key") { + Some("objects_dedup_uq".to_string()) + } else if message.contains("objects.object_type, objects.name") { + Some("objects_name_uq".to_string()) + } else if message.contains("objects.id") { + Some("objects_pkey".to_string()) + } else { + None + } } -fn map_migrate_error(error: &sqlx::migrate::MigrateError) -> Error { - Error::execution(format!("migration error: {error}")) +fn map_migrate_error(error: &sqlx::migrate::MigrateError) -> PersistenceError { + PersistenceError::Migration(error.to_string()) } /// Parse a simple label selector string into key-value pairs. @@ -472,7 +328,9 @@ fn map_migrate_error(error: &sqlx::migrate::MigrateError) -> Error { /// Note: Input validation should be performed at the gRPC layer using /// `grpc::validation::validate_label_selector()` before calling this function. /// Errors returned here indicate unexpected internal errors, not user input errors. -pub fn parse_label_selector(selector: &str) -> Result> { +pub fn parse_label_selector( + selector: &str, +) -> PersistenceResult> { if selector.is_empty() { return Ok(std::collections::HashMap::new()); } @@ -486,7 +344,7 @@ pub fn parse_label_selector(selector: &str) -> Result = pair.splitn(2, '=').collect(); if parts.len() != 2 { - return Err(Error::execution(format!( + return Err(PersistenceError::Decode(format!( "invalid label selector: expected 'key=value', got '{pair}'" ))); } @@ -495,7 +353,7 @@ pub fn parse_label_selector(selector: &str) -> Result Result { + pub async fn connect(url: &str) -> PersistenceResult { let pool = PgPoolOptions::new() .max_connections(10) .connect(url) @@ -26,7 +33,7 @@ impl PostgresStore { Ok(Self { pool }) } - pub async fn migrate(&self) -> Result<()> { + pub async fn migrate(&self) -> PersistenceResult<()> { POSTGRES_MIGRATOR .run(&self.pool) .await @@ -40,22 +47,21 @@ impl PostgresStore { name: &str, payload: &[u8], labels: Option<&str>, - ) -> Result<()> { + ) -> PersistenceResult<()> { let now_ms = current_time_ms()?; let labels_jsonb: Option = labels .map(|s| serde_json::from_str(s)) .transpose() - .map_err(|e| openshell_core::Error::execution(format!("invalid labels JSON: {e}")))?; + .map_err(|e| super::PersistenceError::Encode(format!("invalid labels JSON: {e}")))?; sqlx::query( r" INSERT INTO objects (object_type, id, name, payload, created_at_ms, updated_at_ms, labels) VALUES ($1, $2, $3, $4, $5, $5, COALESCE($6, '{}'::jsonb)) -ON CONFLICT (id) DO UPDATE SET +ON CONFLICT (object_type, name) WHERE name IS NOT NULL DO UPDATE SET payload = EXCLUDED.payload, updated_at_ms = EXCLUDED.updated_at_ms, labels = EXCLUDED.labels -WHERE objects.object_type = EXCLUDED.object_type ", ) .bind(object_type) @@ -70,7 +76,11 @@ WHERE objects.object_type = EXCLUDED.object_type Ok(()) } - pub async fn get(&self, object_type: &str, id: &str) -> Result> { + pub async fn get( + &self, + object_type: &str, + id: &str, + ) -> PersistenceResult> { let row = sqlx::query( r" SELECT object_type, id, name, payload, created_at_ms, updated_at_ms, labels @@ -84,23 +94,14 @@ WHERE object_type = $1 AND id = $2 .await .map_err(|e| map_db_error(&e))?; - Ok(row.map(|row| { - let labels_jsonb: Option = row.get("labels"); - let labels = labels_jsonb.map(|v| v.to_string()); - - ObjectRecord { - object_type: row.get("object_type"), - id: row.get("id"), - name: row.get("name"), - payload: row.get("payload"), - created_at_ms: row.get("created_at_ms"), - updated_at_ms: row.get("updated_at_ms"), - labels, - } - })) + Ok(row.map(row_to_object_record)) } - pub async fn get_by_name(&self, object_type: &str, name: &str) -> Result> { + pub async fn get_by_name( + &self, + object_type: &str, + name: &str, + ) -> PersistenceResult> { let row = sqlx::query( r" SELECT object_type, id, name, payload, created_at_ms, updated_at_ms, labels @@ -114,23 +115,10 @@ WHERE object_type = $1 AND name = $2 .await .map_err(|e| map_db_error(&e))?; - Ok(row.map(|row| { - let labels_jsonb: Option = row.get("labels"); - let labels = labels_jsonb.map(|v| v.to_string()); - - ObjectRecord { - object_type: row.get("object_type"), - id: row.get("id"), - name: row.get("name"), - payload: row.get("payload"), - created_at_ms: row.get("created_at_ms"), - updated_at_ms: row.get("updated_at_ms"), - labels, - } - })) + Ok(row.map(row_to_object_record)) } - pub async fn delete(&self, object_type: &str, id: &str) -> Result { + pub async fn delete(&self, object_type: &str, id: &str) -> PersistenceResult { let result = sqlx::query("DELETE FROM objects WHERE object_type = $1 AND id = $2") .bind(object_type) .bind(id) @@ -140,7 +128,7 @@ WHERE object_type = $1 AND name = $2 Ok(result.rows_affected() > 0) } - pub async fn delete_by_name(&self, object_type: &str, name: &str) -> Result { + pub async fn delete_by_name(&self, object_type: &str, name: &str) -> PersistenceResult { let result = sqlx::query("DELETE FROM objects WHERE object_type = $1 AND name = $2") .bind(object_type) .bind(name) @@ -155,7 +143,7 @@ WHERE object_type = $1 AND name = $2 object_type: &str, limit: u32, offset: u32, - ) -> Result> { + ) -> PersistenceResult> { let rows = sqlx::query( r" SELECT object_type, id, name, payload, created_at_ms, updated_at_ms, labels @@ -172,25 +160,7 @@ LIMIT $2 OFFSET $3 .await .map_err(|e| map_db_error(&e))?; - let records = rows - .into_iter() - .map(|row| { - let labels_jsonb: Option = row.get("labels"); - let labels = labels_jsonb.map(|v| v.to_string()); - - ObjectRecord { - object_type: row.get("object_type"), - id: row.get("id"), - name: row.get("name"), - payload: row.get("payload"), - created_at_ms: row.get("created_at_ms"), - updated_at_ms: row.get("updated_at_ms"), - labels, - } - }) - .collect(); - - Ok(records) + Ok(rows.into_iter().map(row_to_object_record).collect()) } pub async fn list_with_selector( @@ -199,18 +169,14 @@ LIMIT $2 OFFSET $3 label_selector: &str, limit: u32, offset: u32, - ) -> Result> { + ) -> PersistenceResult> { use super::parse_label_selector; - // Parse the label selector into key-value pairs let required_labels = parse_label_selector(label_selector)?; - - // Convert to JSONB for containment check let labels_jsonb = serde_json::to_value(&required_labels).map_err(|e| { - openshell_core::Error::execution(format!("failed to serialize labels: {e}")) + super::PersistenceError::Encode(format!("failed to serialize labels: {e}")) })?; - // Use Postgres native JSONB containment operator @> let rows = sqlx::query( r" SELECT object_type, id, name, payload, created_at_ms, updated_at_ms, labels @@ -228,31 +194,9 @@ LIMIT $3 OFFSET $4 .await .map_err(|e| map_db_error(&e))?; - let records = rows - .into_iter() - .map(|row| { - let labels_jsonb: Option = row.get("labels"); - let labels = labels_jsonb.map(|v| v.to_string()); - - ObjectRecord { - object_type: row.get("object_type"), - id: row.get("id"), - name: row.get("name"), - payload: row.get("payload"), - created_at_ms: row.get("created_at_ms"), - updated_at_ms: row.get("updated_at_ms"), - labels, - } - }) - .collect(); - - Ok(records) + Ok(rows.into_iter().map(row_to_object_record).collect()) } - // ------------------------------------------------------------------- - // Policy revision operations - // ------------------------------------------------------------------- - pub async fn put_policy_revision( &self, id: &str, @@ -260,19 +204,35 @@ LIMIT $3 OFFSET $4 version: i64, payload: &[u8], hash: &str, - ) -> Result<()> { + ) -> PersistenceResult<()> { let now_ms = current_time_ms()?; + let record = PolicyRecord { + id: id.to_string(), + sandbox_id: sandbox_id.to_string(), + version, + policy_payload: payload.to_vec(), + policy_hash: hash.to_string(), + status: "pending".to_string(), + load_error: None, + created_at_ms: now_ms, + loaded_at_ms: None, + }; + let wrapped_payload = policy_payload_from_record(&record)?; + sqlx::query( r" -INSERT INTO sandbox_policies (id, sandbox_id, version, policy_payload, policy_hash, status, created_at_ms) -VALUES ($1, $2, $3, $4, $5, 'pending', $6) +INSERT INTO objects ( + object_type, id, scope, version, status, payload, created_at_ms, updated_at_ms +) +VALUES ($1, $2, $3, $4, $5, $6, $7, $7) ", ) + .bind(POLICY_OBJECT_TYPE) .bind(id) .bind(sandbox_id) .bind(version) - .bind(payload) - .bind(hash) + .bind("pending") + .bind(wrapped_payload) .bind(now_ms) .execute(&self.pool) .await @@ -280,61 +240,70 @@ VALUES ($1, $2, $3, $4, $5, 'pending', $6) Ok(()) } - pub async fn get_latest_policy(&self, sandbox_id: &str) -> Result> { + pub async fn get_latest_policy( + &self, + sandbox_id: &str, + ) -> PersistenceResult> { let row = sqlx::query( r" -SELECT id, sandbox_id, version, policy_payload, policy_hash, status, load_error, created_at_ms, loaded_at_ms -FROM sandbox_policies -WHERE sandbox_id = $1 -ORDER BY version DESC +SELECT id, scope, version, status, payload, created_at_ms +FROM objects +WHERE object_type = $1 AND scope = $2 +ORDER BY version DESC, created_at_ms DESC LIMIT 1 ", ) + .bind(POLICY_OBJECT_TYPE) .bind(sandbox_id) .fetch_optional(&self.pool) .await .map_err(|e| map_db_error(&e))?; - Ok(row.map(row_to_policy_record)) + row.map(row_to_policy_record).transpose() } - pub async fn get_latest_loaded_policy(&self, sandbox_id: &str) -> Result> { + pub async fn get_latest_loaded_policy( + &self, + sandbox_id: &str, + ) -> PersistenceResult> { let row = sqlx::query( r" -SELECT id, sandbox_id, version, policy_payload, policy_hash, status, load_error, created_at_ms, loaded_at_ms -FROM sandbox_policies -WHERE sandbox_id = $1 AND status = 'loaded' -ORDER BY version DESC +SELECT id, scope, version, status, payload, created_at_ms +FROM objects +WHERE object_type = $1 AND scope = $2 AND status = 'loaded' +ORDER BY version DESC, created_at_ms DESC LIMIT 1 ", ) + .bind(POLICY_OBJECT_TYPE) .bind(sandbox_id) .fetch_optional(&self.pool) .await .map_err(|e| map_db_error(&e))?; - Ok(row.map(row_to_policy_record)) + row.map(row_to_policy_record).transpose() } pub async fn get_policy_by_version( &self, sandbox_id: &str, version: i64, - ) -> Result> { + ) -> PersistenceResult> { let row = sqlx::query( r" -SELECT id, sandbox_id, version, policy_payload, policy_hash, status, load_error, created_at_ms, loaded_at_ms -FROM sandbox_policies -WHERE sandbox_id = $1 AND version = $2 +SELECT id, scope, version, status, payload, created_at_ms +FROM objects +WHERE object_type = $1 AND scope = $2 AND version = $3 ", ) + .bind(POLICY_OBJECT_TYPE) .bind(sandbox_id) .bind(version) .fetch_optional(&self.pool) .await .map_err(|e| map_db_error(&e))?; - Ok(row.map(row_to_policy_record)) + row.map(row_to_policy_record).transpose() } pub async fn list_policies( @@ -342,16 +311,17 @@ WHERE sandbox_id = $1 AND version = $2 sandbox_id: &str, limit: u32, offset: u32, - ) -> Result> { + ) -> PersistenceResult> { let rows = sqlx::query( r" -SELECT id, sandbox_id, version, policy_payload, policy_hash, status, load_error, created_at_ms, loaded_at_ms -FROM sandbox_policies -WHERE sandbox_id = $1 -ORDER BY version DESC -LIMIT $2 OFFSET $3 +SELECT id, scope, version, status, payload, created_at_ms +FROM objects +WHERE object_type = $1 AND scope = $2 +ORDER BY version DESC, created_at_ms DESC +LIMIT $3 OFFSET $4 ", ) + .bind(POLICY_OBJECT_TYPE) .bind(sandbox_id) .bind(i64::from(limit)) .bind(i64::from(offset)) @@ -359,7 +329,7 @@ LIMIT $2 OFFSET $3 .await .map_err(|e| map_db_error(&e))?; - Ok(rows.into_iter().map(row_to_policy_record).collect()) + rows.into_iter().map(row_to_policy_record).collect() } pub async fn update_policy_status( @@ -369,19 +339,30 @@ LIMIT $2 OFFSET $3 status: &str, load_error: Option<&str>, loaded_at_ms: Option, - ) -> Result { + ) -> PersistenceResult { + let Some(mut record) = self.get_policy_by_version(sandbox_id, version).await? else { + return Ok(false); + }; + + record.status = status.to_string(); + record.load_error = load_error.map(ToOwned::to_owned); + record.loaded_at_ms = loaded_at_ms; + let payload = policy_payload_from_record(&record)?; + let now_ms = current_time_ms()?; + let result = sqlx::query( r" -UPDATE sandbox_policies -SET status = $3, load_error = $4, loaded_at_ms = $5 -WHERE sandbox_id = $1 AND version = $2 +UPDATE objects +SET status = $4, payload = $5, updated_at_ms = $6 +WHERE object_type = $1 AND scope = $2 AND version = $3 ", ) + .bind(POLICY_OBJECT_TYPE) .bind(sandbox_id) .bind(version) .bind(status) - .bind(load_error) - .bind(loaded_at_ms) + .bind(payload) + .bind(now_ms) .execute(&self.pool) .await .map_err(|e| map_db_error(&e))?; @@ -392,57 +373,48 @@ WHERE sandbox_id = $1 AND version = $2 &self, sandbox_id: &str, before_version: i64, - ) -> Result { + ) -> PersistenceResult { + let now_ms = current_time_ms()?; let result = sqlx::query( r" -UPDATE sandbox_policies -SET status = 'superseded' -WHERE sandbox_id = $1 AND version < $2 AND status IN ('pending', 'loaded') +UPDATE objects +SET status = 'superseded', updated_at_ms = $4 +WHERE object_type = $1 + AND scope = $2 + AND version < $3 + AND status IN ('pending', 'loaded') ", ) + .bind(POLICY_OBJECT_TYPE) .bind(sandbox_id) .bind(before_version) + .bind(now_ms) .execute(&self.pool) .await .map_err(|e| map_db_error(&e))?; Ok(result.rows_affected()) } - // ------------------------------------------------------------------- - // Draft policy chunk operations - // ------------------------------------------------------------------- - - pub async fn put_draft_chunk(&self, chunk: &DraftChunkRecord) -> Result<()> { + pub async fn put_draft_chunk(&self, chunk: &DraftChunkRecord) -> PersistenceResult<()> { + let payload = draft_chunk_payload_from_record(chunk)?; sqlx::query( r" -INSERT INTO draft_policy_chunks - (id, sandbox_id, draft_version, status, rule_name, - proposed_rule, rationale, security_notes, confidence, - created_at_ms, decided_at_ms, host, port, binary, - hit_count, first_seen_ms, last_seen_ms) -VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17) -ON CONFLICT (sandbox_id, host, port, binary) - WHERE status IN ('pending', 'approved', 'rejected') -DO UPDATE SET - hit_count = draft_policy_chunks.hit_count + EXCLUDED.hit_count, - last_seen_ms = EXCLUDED.last_seen_ms +INSERT INTO objects ( + object_type, id, scope, status, dedup_key, hit_count, payload, created_at_ms, updated_at_ms +) +VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) +ON CONFLICT (object_type, scope, dedup_key) WHERE dedup_key IS NOT NULL DO UPDATE SET + hit_count = objects.hit_count + EXCLUDED.hit_count, + updated_at_ms = EXCLUDED.updated_at_ms ", ) + .bind(DRAFT_CHUNK_OBJECT_TYPE) .bind(&chunk.id) .bind(&chunk.sandbox_id) - .bind(chunk.draft_version) .bind(&chunk.status) - .bind(&chunk.rule_name) - .bind(&chunk.proposed_rule) - .bind(&chunk.rationale) - .bind(&chunk.security_notes) - .bind(chunk.confidence) - .bind(chunk.created_at_ms) - .bind(chunk.decided_at_ms) - .bind(&chunk.host) - .bind(chunk.port) - .bind(&chunk.binary) - .bind(chunk.hit_count) + .bind(draft_chunk_dedup_key(chunk)) + .bind(i64::from(chunk.hit_count)) + .bind(payload) .bind(chunk.first_seen_ms) .bind(chunk.last_seen_ms) .execute(&self.pool) @@ -451,33 +423,38 @@ DO UPDATE SET Ok(()) } - pub async fn get_draft_chunk(&self, id: &str) -> Result> { + pub async fn get_draft_chunk(&self, id: &str) -> PersistenceResult> { let row = sqlx::query( r" -SELECT * FROM draft_policy_chunks WHERE id = $1 +SELECT id, scope, status, hit_count, payload, created_at_ms, updated_at_ms +FROM objects +WHERE object_type = $1 AND id = $2 ", ) + .bind(DRAFT_CHUNK_OBJECT_TYPE) .bind(id) .fetch_optional(&self.pool) .await .map_err(|e| map_db_error(&e))?; - Ok(row.map(row_to_draft_chunk_record)) + row.map(row_to_draft_chunk_record).transpose() } pub async fn list_draft_chunks( &self, sandbox_id: &str, status_filter: Option<&str>, - ) -> Result> { + ) -> PersistenceResult> { let rows = if let Some(status) = status_filter { sqlx::query( r" -SELECT * FROM draft_policy_chunks -WHERE sandbox_id = $1 AND status = $2 +SELECT id, scope, status, hit_count, payload, created_at_ms, updated_at_ms +FROM objects +WHERE object_type = $1 AND scope = $2 AND status = $3 ORDER BY created_at_ms DESC ", ) + .bind(DRAFT_CHUNK_OBJECT_TYPE) .bind(sandbox_id) .bind(status) .fetch_all(&self.pool) @@ -485,18 +462,20 @@ ORDER BY created_at_ms DESC } else { sqlx::query( r" -SELECT * FROM draft_policy_chunks -WHERE sandbox_id = $1 +SELECT id, scope, status, hit_count, payload, created_at_ms, updated_at_ms +FROM objects +WHERE object_type = $1 AND scope = $2 ORDER BY created_at_ms DESC ", ) + .bind(DRAFT_CHUNK_OBJECT_TYPE) .bind(sandbox_id) .fetch_all(&self.pool) .await } .map_err(|e| map_db_error(&e))?; - Ok(rows.into_iter().map(row_to_draft_chunk_record).collect()) + rows.into_iter().map(row_to_draft_chunk_record).collect() } pub async fn update_draft_chunk_status( @@ -504,46 +483,80 @@ ORDER BY created_at_ms DESC id: &str, status: &str, decided_at_ms: Option, - ) -> Result { + ) -> PersistenceResult { + let Some(mut record) = self.get_draft_chunk(id).await? else { + return Ok(false); + }; + + record.status = status.to_string(); + record.decided_at_ms = decided_at_ms; + record.last_seen_ms = current_time_ms()?; + let payload = draft_chunk_payload_from_record(&record)?; + let result = sqlx::query( r" -UPDATE draft_policy_chunks -SET status = $2, decided_at_ms = $3 -WHERE id = $1 +UPDATE objects +SET status = $3, payload = $4, updated_at_ms = $5 +WHERE object_type = $1 AND id = $2 ", ) + .bind(DRAFT_CHUNK_OBJECT_TYPE) .bind(id) .bind(status) - .bind(decided_at_ms) + .bind(payload) + .bind(record.last_seen_ms) .execute(&self.pool) .await .map_err(|e| map_db_error(&e))?; Ok(result.rows_affected() > 0) } - pub async fn update_draft_chunk_rule(&self, id: &str, proposed_rule: &[u8]) -> Result { + pub async fn update_draft_chunk_rule( + &self, + id: &str, + proposed_rule: &[u8], + ) -> PersistenceResult { + let Some(mut record) = self.get_draft_chunk(id).await? else { + return Ok(false); + }; + + if record.status != "pending" { + return Ok(false); + } + + record.proposed_rule = proposed_rule.to_vec(); + record.last_seen_ms = current_time_ms()?; + let payload = draft_chunk_payload_from_record(&record)?; + let result = sqlx::query( r" -UPDATE draft_policy_chunks -SET proposed_rule = $2 -WHERE id = $1 AND status = 'pending' +UPDATE objects +SET payload = $3, updated_at_ms = $4 +WHERE object_type = $1 AND id = $2 AND status = 'pending' ", ) + .bind(DRAFT_CHUNK_OBJECT_TYPE) .bind(id) - .bind(proposed_rule) + .bind(payload) + .bind(record.last_seen_ms) .execute(&self.pool) .await .map_err(|e| map_db_error(&e))?; Ok(result.rows_affected() > 0) } - pub async fn delete_draft_chunks(&self, sandbox_id: &str, status: &str) -> Result { + pub async fn delete_draft_chunks( + &self, + sandbox_id: &str, + status: &str, + ) -> PersistenceResult { let result = sqlx::query( r" -DELETE FROM draft_policy_chunks -WHERE sandbox_id = $1 AND status = $2 +DELETE FROM objects +WHERE object_type = $1 AND scope = $2 AND status = $3 ", ) + .bind(DRAFT_CHUNK_OBJECT_TYPE) .bind(sandbox_id) .bind(status) .execute(&self.pool) @@ -552,55 +565,80 @@ WHERE sandbox_id = $1 AND status = $2 Ok(result.rows_affected()) } - pub async fn get_draft_version(&self, sandbox_id: &str) -> Result { - let row = sqlx::query( + pub async fn get_draft_version(&self, sandbox_id: &str) -> PersistenceResult { + let rows = sqlx::query( r" -SELECT COALESCE(MAX(draft_version), 0) as max_version -FROM draft_policy_chunks -WHERE sandbox_id = $1 +SELECT payload +FROM objects +WHERE object_type = $1 AND scope = $2 ", ) + .bind(DRAFT_CHUNK_OBJECT_TYPE) .bind(sandbox_id) - .fetch_one(&self.pool) + .fetch_all(&self.pool) .await .map_err(|e| map_db_error(&e))?; - Ok(row.get("max_version")) + let mut max_version = 0_i64; + for row in rows { + let payload: Vec = row.get("payload"); + let wrapper = draft_chunk_record_from_parts( + String::new(), + sandbox_id.to_string(), + String::new(), + 0, + &payload, + 0, + 0, + )?; + max_version = max_version.max(wrapper.draft_version); + } + Ok(max_version) } } -fn row_to_draft_chunk_record(row: sqlx::postgres::PgRow) -> DraftChunkRecord { - DraftChunkRecord { - id: row.get("id"), - sandbox_id: row.get("sandbox_id"), - draft_version: row.get("draft_version"), - status: row.get("status"), - rule_name: row.get("rule_name"), - proposed_rule: row.get("proposed_rule"), - rationale: row.get("rationale"), - security_notes: row.get("security_notes"), - confidence: row.get("confidence"), - created_at_ms: row.get("created_at_ms"), - decided_at_ms: row.get("decided_at_ms"), - host: row.get("host"), - port: row.get("port"), - binary: row.get("binary"), - hit_count: row.get("hit_count"), - first_seen_ms: row.get("first_seen_ms"), - last_seen_ms: row.get("last_seen_ms"), - } +fn draft_chunk_dedup_key(chunk: &DraftChunkRecord) -> String { + format!("{}|{}|{}", chunk.host, chunk.port, chunk.binary) } -fn row_to_policy_record(row: sqlx::postgres::PgRow) -> PolicyRecord { - PolicyRecord { +fn row_to_object_record(row: sqlx::postgres::PgRow) -> ObjectRecord { + let labels_jsonb: Option = row.get("labels"); + ObjectRecord { + object_type: row.get("object_type"), id: row.get("id"), - sandbox_id: row.get("sandbox_id"), - version: row.get("version"), - policy_payload: row.get("policy_payload"), - policy_hash: row.get("policy_hash"), - status: row.get("status"), - load_error: row.get("load_error"), + name: row.get("name"), + payload: row.get("payload"), created_at_ms: row.get("created_at_ms"), - loaded_at_ms: row.get("loaded_at_ms"), + updated_at_ms: row.get("updated_at_ms"), + labels: labels_jsonb.map(|value| value.to_string()), } } + +fn row_to_policy_record(row: sqlx::postgres::PgRow) -> PersistenceResult { + let id: String = row.get("id"); + let sandbox_id: String = row.get("scope"); + let version: i64 = row.get("version"); + let status: String = row.get("status"); + let payload: Vec = row.get("payload"); + let created_at_ms: i64 = row.get("created_at_ms"); + policy_record_from_parts(id, sandbox_id, version, status, &payload, created_at_ms) +} + +fn row_to_draft_chunk_record(row: sqlx::postgres::PgRow) -> PersistenceResult { + let id: String = row.get("id"); + let sandbox_id: String = row.get("scope"); + let status: String = row.get("status"); + let hit_count: i64 = row.get("hit_count"); + let payload: Vec = row.get("payload"); + let created_at_ms: i64 = row.get("created_at_ms"); + let updated_at_ms: i64 = row.get("updated_at_ms"); + draft_chunk_record_from_parts( + id, + sandbox_id, + status, + hit_count, + &payload, + created_at_ms, + updated_at_ms, + ) +} diff --git a/crates/openshell-server/src/persistence/sqlite.rs b/crates/openshell-server/src/persistence/sqlite.rs index d6ecacc72b..8fad865bb5 100644 --- a/crates/openshell-server/src/persistence/sqlite.rs +++ b/crates/openshell-server/src/persistence/sqlite.rs @@ -2,22 +2,29 @@ // SPDX-License-Identifier: Apache-2.0 use super::{ - DraftChunkRecord, ObjectRecord, PolicyRecord, current_time_ms, map_db_error, map_migrate_error, + DraftChunkRecord, ObjectRecord, PersistenceResult, PolicyRecord, current_time_ms, map_db_error, + map_migrate_error, +}; +use crate::policy_store::{ + draft_chunk_payload_from_record, draft_chunk_record_from_parts, policy_payload_from_record, + policy_record_from_parts, }; -use openshell_core::Result; use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions}; use sqlx::{Row, SqlitePool}; use std::str::FromStr; static SQLITE_MIGRATOR: sqlx::migrate::Migrator = sqlx::migrate!("./migrations/sqlite"); +const POLICY_OBJECT_TYPE: &str = "sandbox_policy"; +const DRAFT_CHUNK_OBJECT_TYPE: &str = "draft_policy_chunk"; + #[derive(Debug, Clone)] pub struct SqliteStore { pool: SqlitePool, } impl SqliteStore { - pub async fn connect(url: &str) -> Result { + 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 }; @@ -29,11 +36,6 @@ impl SqliteStore { .max_connections(max_connections) .min_connections(max_connections); - // In-memory SQLite databases exist only while at least one connection - // is open. SQLx's default `max_lifetime` (30 min) and `idle_timeout` - // (10 min) would recycle the sole connection, destroying the database - // and all its tables. Disable both timeouts so the connection (and - // therefore the database) lives for the entire process lifetime. if is_in_memory { pool_options = pool_options.idle_timeout(None).max_lifetime(None); } @@ -46,7 +48,7 @@ impl SqliteStore { Ok(Self { pool }) } - pub async fn migrate(&self) -> Result<()> { + pub async fn migrate(&self) -> PersistenceResult<()> { SQLITE_MIGRATOR .run(&self.pool) .await @@ -60,18 +62,17 @@ impl SqliteStore { name: &str, payload: &[u8], labels: Option<&str>, - ) -> Result<()> { + ) -> PersistenceResult<()> { let now_ms = current_time_ms()?; sqlx::query( r#" INSERT INTO "objects" ("object_type", "id", "name", "payload", "created_at_ms", "updated_at_ms", "labels") VALUES (?1, ?2, ?3, ?4, ?5, ?5, ?6) -ON CONFLICT ("id") DO UPDATE SET +ON CONFLICT ("object_type", "name") WHERE "name" IS NOT NULL DO UPDATE SET "payload" = excluded."payload", "updated_at_ms" = excluded."updated_at_ms", "labels" = excluded."labels" -WHERE "objects"."object_type" = excluded."object_type" "#, ) .bind(object_type) @@ -86,7 +87,11 @@ WHERE "objects"."object_type" = excluded."object_type" Ok(()) } - pub async fn get(&self, object_type: &str, id: &str) -> Result> { + pub async fn get( + &self, + object_type: &str, + id: &str, + ) -> PersistenceResult> { let row = sqlx::query( r#" SELECT "object_type", "id", "name", "payload", "created_at_ms", "updated_at_ms", "labels" @@ -100,18 +105,14 @@ WHERE "object_type" = ?1 AND "id" = ?2 .await .map_err(|e| map_db_error(&e))?; - Ok(row.map(|row| ObjectRecord { - object_type: row.get("object_type"), - id: row.get("id"), - name: row.get("name"), - payload: row.get("payload"), - created_at_ms: row.get("created_at_ms"), - updated_at_ms: row.get("updated_at_ms"), - labels: row.get("labels"), - })) + Ok(row.map(row_to_object_record)) } - pub async fn get_by_name(&self, object_type: &str, name: &str) -> Result> { + pub async fn get_by_name( + &self, + object_type: &str, + name: &str, + ) -> PersistenceResult> { let row = sqlx::query( r#" SELECT "object_type", "id", "name", "payload", "created_at_ms", "updated_at_ms", "labels" @@ -125,18 +126,10 @@ WHERE "object_type" = ?1 AND "name" = ?2 .await .map_err(|e| map_db_error(&e))?; - Ok(row.map(|row| ObjectRecord { - object_type: row.get("object_type"), - id: row.get("id"), - name: row.get("name"), - payload: row.get("payload"), - created_at_ms: row.get("created_at_ms"), - updated_at_ms: row.get("updated_at_ms"), - labels: row.get("labels"), - })) + Ok(row.map(row_to_object_record)) } - pub async fn delete(&self, object_type: &str, id: &str) -> Result { + pub async fn delete(&self, object_type: &str, id: &str) -> PersistenceResult { let result = sqlx::query( r#" DELETE FROM "objects" @@ -151,7 +144,7 @@ WHERE "object_type" = ?1 AND "id" = ?2 Ok(result.rows_affected() > 0) } - pub async fn delete_by_name(&self, object_type: &str, name: &str) -> Result { + pub async fn delete_by_name(&self, object_type: &str, name: &str) -> PersistenceResult { let result = sqlx::query( r#" DELETE FROM "objects" @@ -171,7 +164,7 @@ WHERE "object_type" = ?1 AND "name" = ?2 object_type: &str, limit: u32, offset: u32, - ) -> Result> { + ) -> PersistenceResult> { let rows = sqlx::query( r#" SELECT "object_type", "id", "name", "payload", "created_at_ms", "updated_at_ms", "labels" @@ -188,47 +181,27 @@ LIMIT ?2 OFFSET ?3 .await .map_err(|e| map_db_error(&e))?; - let records = rows - .into_iter() - .map(|row| ObjectRecord { - object_type: row.get("object_type"), - id: row.get("id"), - name: row.get("name"), - payload: row.get("payload"), - created_at_ms: row.get("created_at_ms"), - updated_at_ms: row.get("updated_at_ms"), - labels: row.get("labels"), - }) - .collect(); - - Ok(records) + Ok(rows.into_iter().map(row_to_object_record).collect()) } - pub async fn list_with_selector( &self, object_type: &str, label_selector: &str, limit: u32, offset: u32, - ) -> Result> { + ) -> PersistenceResult> { use super::parse_label_selector; - // Parse the label selector into key-value pairs let required_labels = parse_label_selector(label_selector)?; - - // For SQLite, we parse JSON in application layer since it doesn't have native JSONB let all_records = self.list(object_type, u32::MAX, 0).await?; - // Filter in memory let filtered: Vec = all_records .into_iter() .filter(|record| { - // Parse labels JSON let labels_json = record.labels.as_deref().unwrap_or("{}"); let labels: std::collections::HashMap = serde_json::from_str(labels_json).unwrap_or_default(); - // Check if all required labels match required_labels .iter() .all(|(key, value)| labels.get(key).map(|v| v == value).unwrap_or(false)) @@ -239,11 +212,6 @@ LIMIT ?2 OFFSET ?3 Ok(filtered) } - - // ------------------------------------------------------------------- - // Policy revision operations - // ------------------------------------------------------------------- - pub async fn put_policy_revision( &self, id: &str, @@ -251,19 +219,35 @@ LIMIT ?2 OFFSET ?3 version: i64, payload: &[u8], hash: &str, - ) -> Result<()> { + ) -> PersistenceResult<()> { let now_ms = current_time_ms()?; + let record = PolicyRecord { + id: id.to_string(), + sandbox_id: sandbox_id.to_string(), + version, + policy_payload: payload.to_vec(), + policy_hash: hash.to_string(), + status: "pending".to_string(), + load_error: None, + created_at_ms: now_ms, + loaded_at_ms: None, + }; + let wrapped_payload = policy_payload_from_record(&record)?; + sqlx::query( r#" -INSERT INTO "sandbox_policies" ("id", "sandbox_id", "version", "policy_payload", "policy_hash", "status", "created_at_ms") -VALUES (?1, ?2, ?3, ?4, ?5, 'pending', ?6) +INSERT INTO "objects" ( + "object_type", "id", "scope", "version", "status", "payload", "created_at_ms", "updated_at_ms" +) +VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?7) "#, ) + .bind(POLICY_OBJECT_TYPE) .bind(id) .bind(sandbox_id) .bind(version) - .bind(payload) - .bind(hash) + .bind("pending") + .bind(wrapped_payload) .bind(now_ms) .execute(&self.pool) .await @@ -271,61 +255,70 @@ VALUES (?1, ?2, ?3, ?4, ?5, 'pending', ?6) Ok(()) } - pub async fn get_latest_policy(&self, sandbox_id: &str) -> Result> { + pub async fn get_latest_policy( + &self, + sandbox_id: &str, + ) -> PersistenceResult> { let row = sqlx::query( r#" -SELECT "id", "sandbox_id", "version", "policy_payload", "policy_hash", "status", "load_error", "created_at_ms", "loaded_at_ms" -FROM "sandbox_policies" -WHERE "sandbox_id" = ?1 -ORDER BY "version" DESC +SELECT "id", "scope", "version", "status", "payload", "created_at_ms" +FROM "objects" +WHERE "object_type" = ?1 AND "scope" = ?2 +ORDER BY "version" DESC, "created_at_ms" DESC LIMIT 1 "#, ) + .bind(POLICY_OBJECT_TYPE) .bind(sandbox_id) .fetch_optional(&self.pool) .await .map_err(|e| map_db_error(&e))?; - Ok(row.map(row_to_policy_record)) + row.map(row_to_policy_record).transpose() } - pub async fn get_latest_loaded_policy(&self, sandbox_id: &str) -> Result> { + pub async fn get_latest_loaded_policy( + &self, + sandbox_id: &str, + ) -> PersistenceResult> { let row = sqlx::query( r#" -SELECT "id", "sandbox_id", "version", "policy_payload", "policy_hash", "status", "load_error", "created_at_ms", "loaded_at_ms" -FROM "sandbox_policies" -WHERE "sandbox_id" = ?1 AND "status" = 'loaded' -ORDER BY "version" DESC +SELECT "id", "scope", "version", "status", "payload", "created_at_ms" +FROM "objects" +WHERE "object_type" = ?1 AND "scope" = ?2 AND "status" = 'loaded' +ORDER BY "version" DESC, "created_at_ms" DESC LIMIT 1 "#, ) + .bind(POLICY_OBJECT_TYPE) .bind(sandbox_id) .fetch_optional(&self.pool) .await .map_err(|e| map_db_error(&e))?; - Ok(row.map(row_to_policy_record)) + row.map(row_to_policy_record).transpose() } pub async fn get_policy_by_version( &self, sandbox_id: &str, version: i64, - ) -> Result> { + ) -> PersistenceResult> { let row = sqlx::query( r#" -SELECT "id", "sandbox_id", "version", "policy_payload", "policy_hash", "status", "load_error", "created_at_ms", "loaded_at_ms" -FROM "sandbox_policies" -WHERE "sandbox_id" = ?1 AND "version" = ?2 +SELECT "id", "scope", "version", "status", "payload", "created_at_ms" +FROM "objects" +WHERE "object_type" = ?1 AND "scope" = ?2 AND "version" = ?3 "#, ) + .bind(POLICY_OBJECT_TYPE) .bind(sandbox_id) .bind(version) .fetch_optional(&self.pool) .await .map_err(|e| map_db_error(&e))?; - Ok(row.map(row_to_policy_record)) + row.map(row_to_policy_record).transpose() } pub async fn list_policies( @@ -333,16 +326,17 @@ WHERE "sandbox_id" = ?1 AND "version" = ?2 sandbox_id: &str, limit: u32, offset: u32, - ) -> Result> { + ) -> PersistenceResult> { let rows = sqlx::query( r#" -SELECT "id", "sandbox_id", "version", "policy_payload", "policy_hash", "status", "load_error", "created_at_ms", "loaded_at_ms" -FROM "sandbox_policies" -WHERE "sandbox_id" = ?1 -ORDER BY "version" DESC -LIMIT ?2 OFFSET ?3 +SELECT "id", "scope", "version", "status", "payload", "created_at_ms" +FROM "objects" +WHERE "object_type" = ?1 AND "scope" = ?2 +ORDER BY "version" DESC, "created_at_ms" DESC +LIMIT ?3 OFFSET ?4 "#, ) + .bind(POLICY_OBJECT_TYPE) .bind(sandbox_id) .bind(i64::from(limit)) .bind(i64::from(offset)) @@ -350,7 +344,7 @@ LIMIT ?2 OFFSET ?3 .await .map_err(|e| map_db_error(&e))?; - Ok(rows.into_iter().map(row_to_policy_record).collect()) + rows.into_iter().map(row_to_policy_record).collect() } pub async fn update_policy_status( @@ -360,19 +354,30 @@ LIMIT ?2 OFFSET ?3 status: &str, load_error: Option<&str>, loaded_at_ms: Option, - ) -> Result { + ) -> PersistenceResult { + let Some(mut record) = self.get_policy_by_version(sandbox_id, version).await? else { + return Ok(false); + }; + + record.status = status.to_string(); + record.load_error = load_error.map(ToOwned::to_owned); + record.loaded_at_ms = loaded_at_ms; + let payload = policy_payload_from_record(&record)?; + let now_ms = current_time_ms()?; + let result = sqlx::query( r#" -UPDATE "sandbox_policies" -SET "status" = ?3, "load_error" = ?4, "loaded_at_ms" = ?5 -WHERE "sandbox_id" = ?1 AND "version" = ?2 +UPDATE "objects" +SET "status" = ?4, "payload" = ?5, "updated_at_ms" = ?6 +WHERE "object_type" = ?1 AND "scope" = ?2 AND "version" = ?3 "#, ) + .bind(POLICY_OBJECT_TYPE) .bind(sandbox_id) .bind(version) .bind(status) - .bind(load_error) - .bind(loaded_at_ms) + .bind(payload) + .bind(now_ms) .execute(&self.pool) .await .map_err(|e| map_db_error(&e))?; @@ -383,57 +388,48 @@ WHERE "sandbox_id" = ?1 AND "version" = ?2 &self, sandbox_id: &str, before_version: i64, - ) -> Result { + ) -> PersistenceResult { + let now_ms = current_time_ms()?; let result = sqlx::query( r#" -UPDATE "sandbox_policies" -SET "status" = 'superseded' -WHERE "sandbox_id" = ?1 AND "version" < ?2 AND "status" IN ('pending', 'loaded') +UPDATE "objects" +SET "status" = 'superseded', "updated_at_ms" = ?4 +WHERE "object_type" = ?1 + AND "scope" = ?2 + AND "version" < ?3 + AND "status" IN ('pending', 'loaded') "#, ) + .bind(POLICY_OBJECT_TYPE) .bind(sandbox_id) .bind(before_version) + .bind(now_ms) .execute(&self.pool) .await .map_err(|e| map_db_error(&e))?; Ok(result.rows_affected()) } - // ------------------------------------------------------------------- - // Draft policy chunk operations - // ------------------------------------------------------------------- - - pub async fn put_draft_chunk(&self, chunk: &DraftChunkRecord) -> Result<()> { + pub async fn put_draft_chunk(&self, chunk: &DraftChunkRecord) -> PersistenceResult<()> { + let payload = draft_chunk_payload_from_record(chunk)?; sqlx::query( r#" -INSERT INTO "draft_policy_chunks" - ("id", "sandbox_id", "draft_version", "status", "rule_name", - "proposed_rule", "rationale", "security_notes", "confidence", - "created_at_ms", "decided_at_ms", "host", "port", "binary", - "hit_count", "first_seen_ms", "last_seen_ms") -VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17) -ON CONFLICT ("sandbox_id", "host", "port", "binary") - WHERE "status" IN ('pending', 'approved', 'rejected') -DO UPDATE SET - "hit_count" = "draft_policy_chunks"."hit_count" + excluded."hit_count", - "last_seen_ms" = excluded."last_seen_ms" +INSERT INTO "objects" ( + "object_type", "id", "scope", "status", "dedup_key", "hit_count", "payload", "created_at_ms", "updated_at_ms" +) +VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9) +ON CONFLICT ("object_type", "scope", "dedup_key") WHERE "dedup_key" IS NOT NULL DO UPDATE SET + "hit_count" = "objects"."hit_count" + excluded."hit_count", + "updated_at_ms" = excluded."updated_at_ms" "#, ) + .bind(DRAFT_CHUNK_OBJECT_TYPE) .bind(&chunk.id) .bind(&chunk.sandbox_id) - .bind(chunk.draft_version) .bind(&chunk.status) - .bind(&chunk.rule_name) - .bind(&chunk.proposed_rule) - .bind(&chunk.rationale) - .bind(&chunk.security_notes) - .bind(chunk.confidence) - .bind(chunk.created_at_ms) - .bind(chunk.decided_at_ms) - .bind(&chunk.host) - .bind(chunk.port) - .bind(&chunk.binary) - .bind(chunk.hit_count) + .bind(draft_chunk_dedup_key(chunk)) + .bind(i64::from(chunk.hit_count)) + .bind(payload) .bind(chunk.first_seen_ms) .bind(chunk.last_seen_ms) .execute(&self.pool) @@ -442,33 +438,38 @@ DO UPDATE SET Ok(()) } - pub async fn get_draft_chunk(&self, id: &str) -> Result> { + pub async fn get_draft_chunk(&self, id: &str) -> PersistenceResult> { let row = sqlx::query( r#" -SELECT * FROM "draft_policy_chunks" WHERE "id" = ?1 +SELECT "id", "scope", "status", "hit_count", "payload", "created_at_ms", "updated_at_ms" +FROM "objects" +WHERE "object_type" = ?1 AND "id" = ?2 "#, ) + .bind(DRAFT_CHUNK_OBJECT_TYPE) .bind(id) .fetch_optional(&self.pool) .await .map_err(|e| map_db_error(&e))?; - Ok(row.map(row_to_draft_chunk_record)) + row.map(row_to_draft_chunk_record).transpose() } pub async fn list_draft_chunks( &self, sandbox_id: &str, status_filter: Option<&str>, - ) -> Result> { + ) -> PersistenceResult> { let rows = if let Some(status) = status_filter { sqlx::query( r#" -SELECT * FROM "draft_policy_chunks" -WHERE "sandbox_id" = ?1 AND "status" = ?2 +SELECT "id", "scope", "status", "hit_count", "payload", "created_at_ms", "updated_at_ms" +FROM "objects" +WHERE "object_type" = ?1 AND "scope" = ?2 AND "status" = ?3 ORDER BY "created_at_ms" DESC "#, ) + .bind(DRAFT_CHUNK_OBJECT_TYPE) .bind(sandbox_id) .bind(status) .fetch_all(&self.pool) @@ -476,18 +477,20 @@ ORDER BY "created_at_ms" DESC } else { sqlx::query( r#" -SELECT * FROM "draft_policy_chunks" -WHERE "sandbox_id" = ?1 +SELECT "id", "scope", "status", "hit_count", "payload", "created_at_ms", "updated_at_ms" +FROM "objects" +WHERE "object_type" = ?1 AND "scope" = ?2 ORDER BY "created_at_ms" DESC "#, ) + .bind(DRAFT_CHUNK_OBJECT_TYPE) .bind(sandbox_id) .fetch_all(&self.pool) .await } .map_err(|e| map_db_error(&e))?; - Ok(rows.into_iter().map(row_to_draft_chunk_record).collect()) + rows.into_iter().map(row_to_draft_chunk_record).collect() } pub async fn update_draft_chunk_status( @@ -495,46 +498,80 @@ ORDER BY "created_at_ms" DESC id: &str, status: &str, decided_at_ms: Option, - ) -> Result { + ) -> PersistenceResult { + let Some(mut record) = self.get_draft_chunk(id).await? else { + return Ok(false); + }; + + record.status = status.to_string(); + record.decided_at_ms = decided_at_ms; + record.last_seen_ms = current_time_ms()?; + let payload = draft_chunk_payload_from_record(&record)?; + let result = sqlx::query( r#" -UPDATE "draft_policy_chunks" -SET "status" = ?2, "decided_at_ms" = ?3 -WHERE "id" = ?1 +UPDATE "objects" +SET "status" = ?3, "payload" = ?4, "updated_at_ms" = ?5 +WHERE "object_type" = ?1 AND "id" = ?2 "#, ) + .bind(DRAFT_CHUNK_OBJECT_TYPE) .bind(id) .bind(status) - .bind(decided_at_ms) + .bind(payload) + .bind(record.last_seen_ms) .execute(&self.pool) .await .map_err(|e| map_db_error(&e))?; Ok(result.rows_affected() > 0) } - pub async fn update_draft_chunk_rule(&self, id: &str, proposed_rule: &[u8]) -> Result { + pub async fn update_draft_chunk_rule( + &self, + id: &str, + proposed_rule: &[u8], + ) -> PersistenceResult { + let Some(mut record) = self.get_draft_chunk(id).await? else { + return Ok(false); + }; + + if record.status != "pending" { + return Ok(false); + } + + record.proposed_rule = proposed_rule.to_vec(); + record.last_seen_ms = current_time_ms()?; + let payload = draft_chunk_payload_from_record(&record)?; + let result = sqlx::query( r#" -UPDATE "draft_policy_chunks" -SET "proposed_rule" = ?2 -WHERE "id" = ?1 AND "status" = 'pending' +UPDATE "objects" +SET "payload" = ?3, "updated_at_ms" = ?4 +WHERE "object_type" = ?1 AND "id" = ?2 AND "status" = 'pending' "#, ) + .bind(DRAFT_CHUNK_OBJECT_TYPE) .bind(id) - .bind(proposed_rule) + .bind(payload) + .bind(record.last_seen_ms) .execute(&self.pool) .await .map_err(|e| map_db_error(&e))?; Ok(result.rows_affected() > 0) } - pub async fn delete_draft_chunks(&self, sandbox_id: &str, status: &str) -> Result { + pub async fn delete_draft_chunks( + &self, + sandbox_id: &str, + status: &str, + ) -> PersistenceResult { let result = sqlx::query( r#" -DELETE FROM "draft_policy_chunks" -WHERE "sandbox_id" = ?1 AND "status" = ?2 +DELETE FROM "objects" +WHERE "object_type" = ?1 AND "scope" = ?2 AND "status" = ?3 "#, ) + .bind(DRAFT_CHUNK_OBJECT_TYPE) .bind(sandbox_id) .bind(status) .execute(&self.pool) @@ -543,55 +580,79 @@ WHERE "sandbox_id" = ?1 AND "status" = ?2 Ok(result.rows_affected()) } - pub async fn get_draft_version(&self, sandbox_id: &str) -> Result { - let row = sqlx::query( + pub async fn get_draft_version(&self, sandbox_id: &str) -> PersistenceResult { + let rows = sqlx::query( r#" -SELECT COALESCE(MAX("draft_version"), 0) as "max_version" -FROM "draft_policy_chunks" -WHERE "sandbox_id" = ?1 +SELECT "payload" +FROM "objects" +WHERE "object_type" = ?1 AND "scope" = ?2 "#, ) + .bind(DRAFT_CHUNK_OBJECT_TYPE) .bind(sandbox_id) - .fetch_one(&self.pool) + .fetch_all(&self.pool) .await .map_err(|e| map_db_error(&e))?; - Ok(row.get("max_version")) + let mut max_version = 0_i64; + for row in rows { + let payload: Vec = row.get("payload"); + let wrapper = draft_chunk_record_from_parts( + String::new(), + sandbox_id.to_string(), + String::new(), + 0, + &payload, + 0, + 0, + )?; + max_version = max_version.max(wrapper.draft_version); + } + Ok(max_version) } } -fn row_to_draft_chunk_record(row: sqlx::sqlite::SqliteRow) -> DraftChunkRecord { - DraftChunkRecord { - id: row.get("id"), - sandbox_id: row.get("sandbox_id"), - draft_version: row.get("draft_version"), - status: row.get("status"), - rule_name: row.get("rule_name"), - proposed_rule: row.get("proposed_rule"), - rationale: row.get("rationale"), - security_notes: row.get("security_notes"), - confidence: row.get("confidence"), - created_at_ms: row.get("created_at_ms"), - decided_at_ms: row.get("decided_at_ms"), - host: row.get("host"), - port: row.get("port"), - binary: row.get("binary"), - hit_count: row.get("hit_count"), - first_seen_ms: row.get("first_seen_ms"), - last_seen_ms: row.get("last_seen_ms"), - } +fn draft_chunk_dedup_key(chunk: &DraftChunkRecord) -> String { + format!("{}|{}|{}", chunk.host, chunk.port, chunk.binary) } -fn row_to_policy_record(row: sqlx::sqlite::SqliteRow) -> PolicyRecord { - PolicyRecord { +fn row_to_object_record(row: sqlx::sqlite::SqliteRow) -> ObjectRecord { + ObjectRecord { + object_type: row.get("object_type"), id: row.get("id"), - sandbox_id: row.get("sandbox_id"), - version: row.get("version"), - policy_payload: row.get("policy_payload"), - policy_hash: row.get("policy_hash"), - status: row.get("status"), - load_error: row.get("load_error"), + name: row.get("name"), + payload: row.get("payload"), created_at_ms: row.get("created_at_ms"), - loaded_at_ms: row.get("loaded_at_ms"), + updated_at_ms: row.get("updated_at_ms"), + labels: row.get("labels"), } } + +fn row_to_policy_record(row: sqlx::sqlite::SqliteRow) -> PersistenceResult { + let id: String = row.get("id"); + let sandbox_id: String = row.get("scope"); + let version: i64 = row.get("version"); + let status: String = row.get("status"); + let payload: Vec = row.get("payload"); + let created_at_ms: i64 = row.get("created_at_ms"); + policy_record_from_parts(id, sandbox_id, version, status, &payload, created_at_ms) +} + +fn row_to_draft_chunk_record(row: sqlx::sqlite::SqliteRow) -> PersistenceResult { + let id: String = row.get("id"); + let sandbox_id: String = row.get("scope"); + let status: String = row.get("status"); + let hit_count: i64 = row.get("hit_count"); + let payload: Vec = row.get("payload"); + let created_at_ms: i64 = row.get("created_at_ms"); + let updated_at_ms: i64 = row.get("updated_at_ms"); + draft_chunk_record_from_parts( + id, + sandbox_id, + status, + hit_count, + &payload, + created_at_ms, + updated_at_ms, + ) +} diff --git a/crates/openshell-server/src/persistence/tests.rs b/crates/openshell-server/src/persistence/tests.rs index 760ade2c21..6ae002e27a 100644 --- a/crates/openshell-server/src/persistence/tests.rs +++ b/crates/openshell-server/src/persistence/tests.rs @@ -1,8 +1,10 @@ // SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -use super::{ObjectId, ObjectLabels, ObjectName, ObjectType, Store, generate_name}; -use openshell_core::proto::ObjectForTest; +use super::{ObjectType, Store, generate_name}; +use crate::policy_store::PolicyStoreExt; +use openshell_core::proto::{ObjectForTest, SandboxPolicy}; +use prost::Message; #[tokio::test] async fn sqlite_put_get_round_trip() { @@ -206,11 +208,19 @@ async fn sqlite_name_unique_per_object_type() { .await .unwrap(); - // Same name, same object_type, different id -> should fail (unique constraint). - let result = store + // Same name, same object_type, different id -> upsert on name. + store .put("sandbox", "id-2", "shared-name", b"payload2", None) - .await; - assert!(result.is_err()); + .await + .unwrap(); + + let record = store + .get_by_name("sandbox", "shared-name") + .await + .unwrap() + .unwrap(); + assert_eq!(record.id, "id-1"); + assert_eq!(record.payload, b"payload2"); // Same name, different object_type -> should succeed. store @@ -230,13 +240,12 @@ async fn sqlite_id_globally_unique() { .await .unwrap(); - // Same id, different object_type -> the upsert is a no-op (WHERE - // clause prevents updating a row with a different object_type). - // The original row is preserved unchanged. - store + // Same id, different object_type -> should fail because ids remain global + // primary keys even when writes upsert on name. + let result = store .put("secret", "same-id", "name-b", b"payload2", None) - .await - .unwrap(); + .await; + assert!(result.is_err()); // Original row is untouched. let record = store.get("sandbox", "same-id").await.unwrap().unwrap(); @@ -461,8 +470,9 @@ async fn policy_put_and_get_latest() { .await .unwrap(); + let policy_v1 = SandboxPolicy::default().encode_to_vec(); store - .put_policy_revision("p1", "sandbox-1", 1, b"policy-v1", "hash1") + .put_policy_revision("p1", "sandbox-1", 1, &policy_v1, "hash1") .await .unwrap(); @@ -470,11 +480,16 @@ async fn policy_put_and_get_latest() { assert_eq!(latest.version, 1); assert_eq!(latest.policy_hash, "hash1"); assert_eq!(latest.status, "pending"); - assert_eq!(latest.policy_payload, b"policy-v1"); + assert_eq!(latest.policy_payload, policy_v1); // Add version 2 + let policy_v2 = SandboxPolicy { + version: 2, + ..SandboxPolicy::default() + } + .encode_to_vec(); store - .put_policy_revision("p2", "sandbox-1", 2, b"policy-v2", "hash2") + .put_policy_revision("p2", "sandbox-1", 2, &policy_v2, "hash2") .await .unwrap(); @@ -489,12 +504,18 @@ async fn policy_get_by_version() { .await .unwrap(); + let policy_v1 = SandboxPolicy::default().encode_to_vec(); + let policy_v2 = SandboxPolicy { + version: 2, + ..SandboxPolicy::default() + } + .encode_to_vec(); store - .put_policy_revision("p1", "sandbox-1", 1, b"v1", "h1") + .put_policy_revision("p1", "sandbox-1", 1, &policy_v1, "h1") .await .unwrap(); store - .put_policy_revision("p2", "sandbox-1", 2, b"v2", "h2") + .put_policy_revision("p2", "sandbox-1", 2, &policy_v2, "h2") .await .unwrap(); @@ -524,8 +545,9 @@ async fn policy_update_status_and_get_loaded() { .await .unwrap(); + let payload = SandboxPolicy::default().encode_to_vec(); store - .put_policy_revision("p1", "sandbox-1", 1, b"v1", "h1") + .put_policy_revision("p1", "sandbox-1", 1, &payload, "h1") .await .unwrap(); @@ -556,8 +578,9 @@ async fn policy_status_failed_with_error() { .await .unwrap(); + let payload = SandboxPolicy::default().encode_to_vec(); store - .put_policy_revision("p1", "sandbox-1", 1, b"v1", "h1") + .put_policy_revision("p1", "sandbox-1", 1, &payload, "h1") .await .unwrap(); @@ -581,16 +604,17 @@ async fn policy_supersede_older() { .await .unwrap(); + let payload = SandboxPolicy::default().encode_to_vec(); store - .put_policy_revision("p1", "sandbox-1", 1, b"v1", "h1") + .put_policy_revision("p1", "sandbox-1", 1, &payload, "h1") .await .unwrap(); store - .put_policy_revision("p2", "sandbox-1", 2, b"v2", "h2") + .put_policy_revision("p2", "sandbox-1", 2, &payload, "h2") .await .unwrap(); store - .put_policy_revision("p3", "sandbox-1", 3, b"v3", "h3") + .put_policy_revision("p3", "sandbox-1", 3, &payload, "h3") .await .unwrap(); @@ -635,16 +659,17 @@ async fn policy_list_ordered_by_version_desc() { .await .unwrap(); + let payload = SandboxPolicy::default().encode_to_vec(); store - .put_policy_revision("p1", "sandbox-1", 1, b"v1", "h1") + .put_policy_revision("p1", "sandbox-1", 1, &payload, "h1") .await .unwrap(); store - .put_policy_revision("p2", "sandbox-1", 2, b"v2", "h2") + .put_policy_revision("p2", "sandbox-1", 2, &payload, "h2") .await .unwrap(); store - .put_policy_revision("p3", "sandbox-1", 3, b"v3", "h3") + .put_policy_revision("p3", "sandbox-1", 3, &payload, "h3") .await .unwrap(); @@ -667,20 +692,26 @@ async fn policy_isolation_between_sandboxes() { .await .unwrap(); + let policy_s1 = SandboxPolicy::default().encode_to_vec(); + let policy_s2 = SandboxPolicy { + version: 7, + ..SandboxPolicy::default() + } + .encode_to_vec(); store - .put_policy_revision("p1", "sandbox-1", 1, b"v1", "h1") + .put_policy_revision("p1", "sandbox-1", 1, &policy_s1, "h1") .await .unwrap(); store - .put_policy_revision("p2", "sandbox-2", 1, b"v1-s2", "h2") + .put_policy_revision("p2", "sandbox-2", 1, &policy_s2, "h2") .await .unwrap(); let s1 = store.get_latest_policy("sandbox-1").await.unwrap().unwrap(); let s2 = store.get_latest_policy("sandbox-2").await.unwrap().unwrap(); - assert_eq!(s1.policy_payload, b"v1"); - assert_eq!(s2.policy_payload, b"v1-s2"); + assert_eq!(s1.policy_payload, policy_s1); + assert_eq!(s2.policy_payload, policy_s2); } // ---- Label selector parsing tests ---- diff --git a/crates/openshell-server/src/policy_store.rs b/crates/openshell-server/src/policy_store.rs new file mode 100644 index 0000000000..dffa00ca4c --- /dev/null +++ b/crates/openshell-server/src/policy_store.rs @@ -0,0 +1,370 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use crate::persistence::{DraftChunkRecord, PersistenceResult, PolicyRecord, Store}; +use openshell_core::proto::{ + DraftChunkPayload, NetworkPolicyRule, PolicyRevisionPayload, + SandboxPolicy as ProtoSandboxPolicy, +}; +use prost::Message; + +pub(crate) trait PolicyStoreExt { + async fn put_policy_revision( + &self, + id: &str, + sandbox_id: &str, + version: i64, + payload: &[u8], + hash: &str, + ) -> PersistenceResult<()>; + + async fn get_latest_policy(&self, sandbox_id: &str) -> PersistenceResult>; + + #[allow(dead_code)] + async fn get_latest_loaded_policy( + &self, + sandbox_id: &str, + ) -> PersistenceResult>; + + async fn get_policy_by_version( + &self, + sandbox_id: &str, + version: i64, + ) -> PersistenceResult>; + + async fn list_policies( + &self, + sandbox_id: &str, + limit: u32, + offset: u32, + ) -> PersistenceResult>; + + async fn update_policy_status( + &self, + sandbox_id: &str, + version: i64, + status: &str, + load_error: Option<&str>, + loaded_at_ms: Option, + ) -> PersistenceResult; + + async fn supersede_older_policies( + &self, + sandbox_id: &str, + before_version: i64, + ) -> PersistenceResult; + + async fn put_draft_chunk(&self, chunk: &DraftChunkRecord) -> PersistenceResult<()>; + + async fn get_draft_chunk(&self, id: &str) -> PersistenceResult>; + + async fn list_draft_chunks( + &self, + sandbox_id: &str, + status_filter: Option<&str>, + ) -> PersistenceResult>; + + async fn update_draft_chunk_status( + &self, + id: &str, + status: &str, + decided_at_ms: Option, + ) -> PersistenceResult; + + async fn update_draft_chunk_rule( + &self, + id: &str, + proposed_rule: &[u8], + ) -> PersistenceResult; + + async fn delete_draft_chunks(&self, sandbox_id: &str, status: &str) -> PersistenceResult; + + async fn get_draft_version(&self, sandbox_id: &str) -> PersistenceResult; +} + +impl PolicyStoreExt for Store { + async fn put_policy_revision( + &self, + id: &str, + sandbox_id: &str, + version: i64, + payload: &[u8], + hash: &str, + ) -> PersistenceResult<()> { + match self { + Self::Postgres(store) => { + store + .put_policy_revision(id, sandbox_id, version, payload, hash) + .await + } + Self::Sqlite(store) => { + store + .put_policy_revision(id, sandbox_id, version, payload, hash) + .await + } + } + } + + async fn get_latest_policy(&self, sandbox_id: &str) -> PersistenceResult> { + match self { + Self::Postgres(store) => store.get_latest_policy(sandbox_id).await, + Self::Sqlite(store) => store.get_latest_policy(sandbox_id).await, + } + } + + async fn get_latest_loaded_policy( + &self, + sandbox_id: &str, + ) -> PersistenceResult> { + match self { + Self::Postgres(store) => store.get_latest_loaded_policy(sandbox_id).await, + Self::Sqlite(store) => store.get_latest_loaded_policy(sandbox_id).await, + } + } + + async fn get_policy_by_version( + &self, + sandbox_id: &str, + version: i64, + ) -> PersistenceResult> { + match self { + Self::Postgres(store) => store.get_policy_by_version(sandbox_id, version).await, + Self::Sqlite(store) => store.get_policy_by_version(sandbox_id, version).await, + } + } + + async fn list_policies( + &self, + sandbox_id: &str, + limit: u32, + offset: u32, + ) -> PersistenceResult> { + match self { + Self::Postgres(store) => store.list_policies(sandbox_id, limit, offset).await, + Self::Sqlite(store) => store.list_policies(sandbox_id, limit, offset).await, + } + } + + async fn update_policy_status( + &self, + sandbox_id: &str, + version: i64, + status: &str, + load_error: Option<&str>, + loaded_at_ms: Option, + ) -> PersistenceResult { + match self { + Self::Postgres(store) => { + store + .update_policy_status(sandbox_id, version, status, load_error, loaded_at_ms) + .await + } + Self::Sqlite(store) => { + store + .update_policy_status(sandbox_id, version, status, load_error, loaded_at_ms) + .await + } + } + } + + async fn supersede_older_policies( + &self, + sandbox_id: &str, + before_version: i64, + ) -> PersistenceResult { + match self { + Self::Postgres(store) => { + store + .supersede_older_policies(sandbox_id, before_version) + .await + } + Self::Sqlite(store) => { + store + .supersede_older_policies(sandbox_id, before_version) + .await + } + } + } + + async fn put_draft_chunk(&self, chunk: &DraftChunkRecord) -> PersistenceResult<()> { + match self { + Self::Postgres(store) => store.put_draft_chunk(chunk).await, + Self::Sqlite(store) => store.put_draft_chunk(chunk).await, + } + } + + async fn get_draft_chunk(&self, id: &str) -> PersistenceResult> { + match self { + Self::Postgres(store) => store.get_draft_chunk(id).await, + Self::Sqlite(store) => store.get_draft_chunk(id).await, + } + } + + async fn list_draft_chunks( + &self, + sandbox_id: &str, + status_filter: Option<&str>, + ) -> PersistenceResult> { + match self { + Self::Postgres(store) => store.list_draft_chunks(sandbox_id, status_filter).await, + Self::Sqlite(store) => store.list_draft_chunks(sandbox_id, status_filter).await, + } + } + + async fn update_draft_chunk_status( + &self, + id: &str, + status: &str, + decided_at_ms: Option, + ) -> PersistenceResult { + match self { + Self::Postgres(store) => { + store + .update_draft_chunk_status(id, status, decided_at_ms) + .await + } + Self::Sqlite(store) => { + store + .update_draft_chunk_status(id, status, decided_at_ms) + .await + } + } + } + + async fn update_draft_chunk_rule( + &self, + id: &str, + proposed_rule: &[u8], + ) -> PersistenceResult { + match self { + Self::Postgres(store) => store.update_draft_chunk_rule(id, proposed_rule).await, + Self::Sqlite(store) => store.update_draft_chunk_rule(id, proposed_rule).await, + } + } + + async fn delete_draft_chunks(&self, sandbox_id: &str, status: &str) -> PersistenceResult { + match self { + Self::Postgres(store) => store.delete_draft_chunks(sandbox_id, status).await, + Self::Sqlite(store) => store.delete_draft_chunks(sandbox_id, status).await, + } + } + + async fn get_draft_version(&self, sandbox_id: &str) -> PersistenceResult { + match self { + Self::Postgres(store) => store.get_draft_version(sandbox_id).await, + Self::Sqlite(store) => store.get_draft_version(sandbox_id).await, + } + } +} + +pub(crate) fn policy_payload_from_record(record: &PolicyRecord) -> PersistenceResult> { + let policy = ProtoSandboxPolicy::decode(record.policy_payload.as_slice()).map_err(|e| { + crate::persistence::PersistenceError::Decode(format!("decode policy payload failed: {e}")) + })?; + Ok(PolicyRevisionPayload { + policy: Some(policy), + hash: record.policy_hash.clone(), + load_error: record.load_error.clone().unwrap_or_default(), + loaded_at_ms: record.loaded_at_ms.unwrap_or(0), + } + .encode_to_vec()) +} + +pub(crate) fn policy_record_from_parts( + id: String, + sandbox_id: String, + version: i64, + status: String, + payload: &[u8], + created_at_ms: i64, +) -> PersistenceResult { + let wrapper = PolicyRevisionPayload::decode(payload).map_err(|e| { + crate::persistence::PersistenceError::Decode(format!("decode policy wrapper failed: {e}")) + })?; + let policy = wrapper.policy.ok_or_else(|| { + crate::persistence::PersistenceError::Decode("policy wrapper missing policy".to_string()) + })?; + Ok(PolicyRecord { + id, + sandbox_id, + version, + policy_payload: policy.encode_to_vec(), + policy_hash: wrapper.hash, + status, + load_error: if wrapper.load_error.is_empty() { + None + } else { + Some(wrapper.load_error) + }, + created_at_ms, + loaded_at_ms: (wrapper.loaded_at_ms > 0).then_some(wrapper.loaded_at_ms), + }) +} + +pub(crate) fn draft_chunk_payload_from_record( + chunk: &DraftChunkRecord, +) -> PersistenceResult> { + let proposed_rule = if chunk.proposed_rule.is_empty() { + None + } else { + Some( + NetworkPolicyRule::decode(chunk.proposed_rule.as_slice()).map_err(|e| { + crate::persistence::PersistenceError::Decode(format!( + "decode draft rule failed: {e}" + )) + })?, + ) + }; + Ok(DraftChunkPayload { + rule_name: chunk.rule_name.clone(), + proposed_rule, + rationale: chunk.rationale.clone(), + security_notes: chunk.security_notes.clone(), + confidence: chunk.confidence as f32, + decided_at_ms: chunk.decided_at_ms.unwrap_or(0), + host: chunk.host.clone(), + port: chunk.port, + binary: chunk.binary.clone(), + draft_version: chunk.draft_version, + } + .encode_to_vec()) +} + +pub(crate) fn draft_chunk_record_from_parts( + id: String, + sandbox_id: String, + status: String, + hit_count: i64, + payload: &[u8], + created_at_ms: i64, + updated_at_ms: i64, +) -> PersistenceResult { + let wrapper = DraftChunkPayload::decode(payload).map_err(|e| { + crate::persistence::PersistenceError::Decode(format!( + "decode draft chunk wrapper failed: {e}" + )) + })?; + let proposed_rule = wrapper + .proposed_rule + .map(|rule| rule.encode_to_vec()) + .unwrap_or_default(); + Ok(DraftChunkRecord { + id, + sandbox_id, + draft_version: wrapper.draft_version, + status, + rule_name: wrapper.rule_name, + proposed_rule, + rationale: wrapper.rationale, + security_notes: wrapper.security_notes, + confidence: f64::from(wrapper.confidence), + created_at_ms, + decided_at_ms: (wrapper.decided_at_ms > 0).then_some(wrapper.decided_at_ms), + host: wrapper.host, + port: wrapper.port, + binary: wrapper.binary, + hit_count: i32::try_from(hit_count).unwrap_or(i32::MAX), + first_seen_ms: created_at_ms, + last_seen_ms: updated_at_ms, + }) +} diff --git a/e2e/python/test_inference_routing.py b/e2e/python/test_inference_routing.py index b9c39f3813..e4a1dd5497 100644 --- a/e2e/python/test_inference_routing.py +++ b/e2e/python/test_inference_routing.py @@ -126,6 +126,9 @@ def _restore_cluster_inference( inference_client.set_cluster( provider_name=previous.provider_name, model_id=previous.model_id, + # Teardown restores prior shared state as-is, even if the previous + # route is intentionally unreachable or no longer verifiable. + no_verify=True, ) diff --git a/e2e/rust/tests/host_gateway_alias.rs b/e2e/rust/tests/host_gateway_alias.rs index fe6a15e740..083f5e6ee8 100644 --- a/e2e/rust/tests/host_gateway_alias.rs +++ b/e2e/rust/tests/host_gateway_alias.rs @@ -396,8 +396,12 @@ async fn inference_set_supports_no_verify_for_unreachable_endpoint() { verify_err.contains("failed to verify inference endpoint"), "expected verification failure output:\n{verify_err}" ); + let normalized_verify_err: String = verify_err + .chars() + .filter(|c| !c.is_whitespace() && *c != '│') + .collect(); assert!( - verify_err.contains("--no-verify"), + normalized_verify_err.contains("--no-verify"), "expected retry hint in failure output:\n{verify_err}" ); diff --git a/proto/openshell.proto b/proto/openshell.proto index 48a8fece26..1d7eba2186 100644 --- a/proto/openshell.proto +++ b/proto/openshell.proto @@ -1136,3 +1136,73 @@ message GetDraftHistoryResponse { // Chronological decision history. repeated DraftHistoryEntry entries = 1; } + +// Stored payload for a policy revision row in the generic objects table. +message PolicyRevisionPayload { + // Serialized policy contents. + openshell.sandbox.v1.SandboxPolicy policy = 1; + // Deterministic hash of the policy payload. + string hash = 2; + // Load error reported by the sandbox, if any. + string load_error = 3; + // When the policy version was reported as loaded (ms since epoch). 0 if unset. + int64 loaded_at_ms = 4; +} + +// Stored payload for a draft policy chunk row in the generic objects table. +message DraftChunkPayload { + // Proposed network_policies map key. + string rule_name = 1; + // Proposed network policy rule. + openshell.sandbox.v1.NetworkPolicyRule proposed_rule = 2; + // Human-readable explanation of why this rule is proposed. + string rationale = 3; + // Security concerns flagged by analysis (empty if none). + string security_notes = 4; + // Analysis confidence (0.0-1.0). 0 for mechanistic mode. + float confidence = 5; + // When the user approved/rejected (ms since epoch). 0 if undecided. + int64 decided_at_ms = 6; + // Denormalized endpoint host for dedup and display. + string host = 7; + // Denormalized endpoint port for dedup and display. + int32 port = 8; + // Binary path that triggered the denial. + string binary = 9; + // Current draft version for the owning sandbox. + int64 draft_version = 10; +} + +// Internal stored policy revision row materialized from the generic objects table. +message StoredPolicyRevision { + string id = 1; + string sandbox_id = 2; + int64 version = 3; + bytes policy_payload = 4; + string policy_hash = 5; + string status = 6; + optional string load_error = 7; + int64 created_at_ms = 8; + optional int64 loaded_at_ms = 9; +} + +// Internal stored draft chunk row materialized from the generic objects table. +message StoredDraftChunk { + string id = 1; + string sandbox_id = 2; + int64 draft_version = 3; + string status = 4; + string rule_name = 5; + bytes proposed_rule = 6; + string rationale = 7; + string security_notes = 8; + double confidence = 9; + int64 created_at_ms = 10; + optional int64 decided_at_ms = 11; + string host = 12; + int32 port = 13; + string binary = 14; + int32 hit_count = 15; + int64 first_seen_ms = 16; + int64 last_seen_ms = 17; +} From 20ffc7253b6e8635731b7c40c9b0bb99e17edc92 Mon Sep 17 00:00:00 2001 From: "John T. Myers" <9696606+johntmyers@users.noreply.github.com> Date: Tue, 28 Apr 2026 18:42:53 -0700 Subject: [PATCH 3/3] fix(cli): preserve directory basename for filtered uploads (#1028) Signed-off-by: John Myers Co-authored-by: John Myers --- architecture/sandbox-connect.md | 2 + crates/openshell-cli/src/main.rs | 1 + crates/openshell-cli/src/run.rs | 1 + crates/openshell-cli/src/ssh.rs | 212 ++++++++++++++++++++++++------- 4 files changed, 169 insertions(+), 47 deletions(-) diff --git a/architecture/sandbox-connect.md b/architecture/sandbox-connect.md index 499532fb9e..59c0a20a04 100644 --- a/architecture/sandbox-connect.md +++ b/architecture/sandbox-connect.md @@ -356,6 +356,8 @@ openshell sandbox download [] ``` - **Upload**: `sandbox_upload()` streams a tar archive of the local path to `ssh ... tar xf - -C ` on the sandbox side. Default destination: `/sandbox`. + Named directory uploads preserve the source directory basename at the destination, matching `scp -r` and `cp -r`; uploading `.` remains flat. + `.gitignore` filtering only changes which files are included, not the destination layout. - **Download**: `sandbox_download()` runs `ssh ... tar cf - -C ` on the sandbox side and extracts the output locally via `tar::Archive`. Default destination: `.` (current directory). - No compression for v1 -- the SSH tunnel rides the already-TLS-encrypted gateway connection; compression adds CPU cost with marginal bandwidth savings. diff --git a/crates/openshell-cli/src/main.rs b/crates/openshell-cli/src/main.rs index 3502c2b07a..df5fb00617 100644 --- a/crates/openshell-cli/src/main.rs +++ b/crates/openshell-cli/src/main.rs @@ -2465,6 +2465,7 @@ async fn main() -> Result<()> { &name, &base_dir, &files, + local, sandbox_dest, &tls, ) diff --git a/crates/openshell-cli/src/run.rs b/crates/openshell-cli/src/run.rs index 87489014aa..769c37748f 100644 --- a/crates/openshell-cli/src/run.rs +++ b/crates/openshell-cli/src/run.rs @@ -2417,6 +2417,7 @@ pub async fn sandbox_create( &sandbox_name, &base_dir, &files, + local, dest, &effective_tls, ) diff --git a/crates/openshell-cli/src/ssh.rs b/crates/openshell-cli/src/ssh.rs index f883d96847..e6273413c8 100644 --- a/crates/openshell-cli/src/ssh.rs +++ b/crates/openshell-cli/src/ssh.rs @@ -16,7 +16,7 @@ use openshell_core::proto::{CreateSshSessionRequest, GetSandboxRequest}; use owo_colors::OwoColorize; use rustls::pki_types::ServerName; use std::fs; -use std::io::IsTerminal; +use std::io::{IsTerminal, Write}; #[cfg(unix)] use std::os::unix::process::CommandExt; use std::path::{Path, PathBuf}; @@ -476,9 +476,68 @@ enum UploadSource { FileList { base_dir: PathBuf, files: Vec, + archive_prefix: Option, }, } +fn write_upload_archive(writer: W, source: UploadSource) -> Result<()> { + let mut archive = tar::Builder::new(writer); + match source { + UploadSource::SinglePath { + local_path, + tar_name, + } => { + if local_path.is_file() { + archive + .append_path_with_name(&local_path, &tar_name) + .into_diagnostic()?; + } else if local_path.is_dir() { + archive + .append_dir_all(&tar_name, &local_path) + .into_diagnostic()?; + } else { + return Err(miette::miette!( + "local path does not exist: {}", + local_path.display() + )); + } + } + UploadSource::FileList { + base_dir, + files, + archive_prefix, + } => { + for file in &files { + let full_path = base_dir.join(file); + let archive_path = archive_prefix + .as_ref() + .map(|prefix| prefix.join(file)) + .unwrap_or_else(|| PathBuf::from(file)); + if full_path.is_file() { + archive + .append_path_with_name(&full_path, &archive_path) + .into_diagnostic() + .wrap_err_with(|| { + format!("failed to add {} to tar archive", archive_path.display()) + })?; + } else if full_path.is_dir() { + archive + .append_dir_all(&archive_path, &full_path) + .into_diagnostic() + .wrap_err_with(|| { + format!( + "failed to add directory {} to tar archive", + archive_path.display() + ) + })?; + } + } + } + } + archive.finish().into_diagnostic()?; + Ok(()) +} + /// Core tar-over-SSH upload: streams a tar archive into `dest_dir` on the /// sandbox. Callers are responsible for splitting the destination path so /// that `dest_dir` is always a directory. @@ -521,52 +580,9 @@ async fn ssh_tar_upload( .ok_or_else(|| miette::miette!("failed to open stdin for ssh process"))?; // Build the tar archive in a blocking task since the tar crate is synchronous. - tokio::task::spawn_blocking(move || -> Result<()> { - let mut archive = tar::Builder::new(stdin); - match source { - UploadSource::SinglePath { - local_path, - tar_name, - } => { - if local_path.is_file() { - archive - .append_path_with_name(&local_path, &tar_name) - .into_diagnostic()?; - } else if local_path.is_dir() { - archive - .append_dir_all(&tar_name, &local_path) - .into_diagnostic()?; - } else { - return Err(miette::miette!( - "local path does not exist: {}", - local_path.display() - )); - } - } - UploadSource::FileList { base_dir, files } => { - for file in &files { - let full_path = base_dir.join(file); - if full_path.is_file() { - archive - .append_path_with_name(&full_path, file) - .into_diagnostic() - .wrap_err_with(|| format!("failed to add {file} to tar archive"))?; - } else if full_path.is_dir() { - archive - .append_dir_all(file, &full_path) - .into_diagnostic() - .wrap_err_with(|| { - format!("failed to add directory {file} to tar archive") - })?; - } - } - } - } - archive.finish().into_diagnostic()?; - Ok(()) - }) - .await - .into_diagnostic()??; + tokio::task::spawn_blocking(move || -> Result<()> { write_upload_archive(stdin, source) }) + .await + .into_diagnostic()??; let status = tokio::task::spawn_blocking(move || child.wait()) .await @@ -606,6 +622,7 @@ pub async fn sandbox_sync_up_files( name: &str, base_dir: &Path, files: &[String], + local_path: &Path, dest: Option<&str>, tls: &TlsOptions, ) -> Result<()> { @@ -619,6 +636,7 @@ pub async fn sandbox_sync_up_files( UploadSource::FileList { base_dir: base_dir.to_path_buf(), files: files.to_vec(), + archive_prefix: file_list_archive_prefix(local_path), }, tls, ) @@ -706,6 +724,19 @@ fn directory_upload_prefix(local_path: &Path) -> std::ffi::OsString { .unwrap_or_else(|| ".".into()) } +fn file_list_archive_prefix(local_path: &Path) -> Option { + if !local_path.is_dir() { + return None; + } + + let prefix = directory_upload_prefix(local_path); + if prefix == "." { + None + } else { + Some(PathBuf::from(prefix)) + } +} + /// Pull a path from a sandbox to a local destination using tar-over-SSH. pub async fn sandbox_sync_down( server: &str, @@ -1332,6 +1363,93 @@ mod tests { ); } + #[test] + fn file_list_archive_prefix_uses_named_directory_basename() { + let tmpdir = tempfile::tempdir().expect("create tmpdir"); + let source = tmpdir.path().join("source-dir"); + let file = tmpdir.path().join("file.txt"); + fs::create_dir_all(&source).expect("create source dir"); + fs::write(&file, "file").expect("write file"); + + assert_eq!( + file_list_archive_prefix(&source), + Some(PathBuf::from("source-dir")) + ); + assert_eq!(file_list_archive_prefix(Path::new(".")), None); + assert_eq!(file_list_archive_prefix(&file), None); + } + + fn upload_archive_paths(source: UploadSource) -> Vec { + let mut bytes = Vec::new(); + write_upload_archive(&mut bytes, source).expect("write upload archive"); + let mut archive = tar::Archive::new(std::io::Cursor::new(bytes)); + let entries = archive.entries().expect("read archive entries"); + let mut paths = entries + .map(|entry| { + entry + .expect("read archive entry") + .path() + .expect("read archive path") + .to_string_lossy() + .into_owned() + }) + .collect::>(); + paths.sort(); + paths + } + + #[test] + fn file_list_archive_preserves_directory_prefix_when_requested() { + let tmpdir = tempfile::tempdir().expect("create tmpdir"); + let base_dir = tmpdir.path().join("nested"); + fs::create_dir_all(base_dir.join("inner")).expect("create dirs"); + fs::write(base_dir.join("file.txt"), "file").expect("write file"); + fs::write(base_dir.join("inner/child.txt"), "child").expect("write child"); + + let paths = upload_archive_paths(UploadSource::FileList { + base_dir, + files: vec!["file.txt".into(), "inner/child.txt".into()], + archive_prefix: Some(PathBuf::from("nested")), + }); + + assert_eq!(paths, vec!["nested/file.txt", "nested/inner/child.txt"]); + } + + #[test] + fn file_list_archive_stays_flat_without_directory_prefix() { + let tmpdir = tempfile::tempdir().expect("create tmpdir"); + let base_dir = tmpdir.path().join("nested"); + fs::create_dir_all(base_dir.join("inner")).expect("create dirs"); + fs::write(base_dir.join("file.txt"), "file").expect("write file"); + fs::write(base_dir.join("inner/child.txt"), "child").expect("write child"); + + let paths = upload_archive_paths(UploadSource::FileList { + base_dir, + files: vec!["file.txt".into(), "inner/child.txt".into()], + archive_prefix: None, + }); + + assert_eq!(paths, vec!["file.txt", "inner/child.txt"]); + } + + #[test] + fn single_directory_archive_preserves_directory_basename() { + let tmpdir = tempfile::tempdir().expect("create tmpdir"); + let source = tmpdir.path().join("source-dir"); + fs::create_dir_all(source.join("inner")).expect("create dirs"); + fs::write(source.join("file.txt"), "file").expect("write file"); + fs::write(source.join("inner/child.txt"), "child").expect("write child"); + + let paths = upload_archive_paths(UploadSource::SinglePath { + local_path: source, + tar_name: "source-dir".into(), + }); + + assert!(paths.contains(&"source-dir/file.txt".to_string())); + assert!(paths.contains(&"source-dir/inner/child.txt".to_string())); + assert!(paths.iter().all(|path| path.starts_with("source-dir/"))); + } + #[test] fn split_sandbox_path_handles_root_and_bare_names() { // File directly under root