Repository navigation
Move files in and out of a tenant's sandbox box; create_artifact reads from the box #8558
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
37 commits
Select commit
Hold shift + click to select a range
ae2558b
test(sandbox): back scripted driver boxes with host directories
senamakel 937e1f1
chore(sandbox): register files module in openshell sandbox
senamakel 8335f3f
feat(sandbox): add file transfer helpers for sandbox boxes
senamakel 5c5102b
fix(sandbox): report incomplete writes and drop unsupported test flag
senamakel f8aec81
feat(sandbox): expose openshell file read and write helpers
senamakel f02e55e
test(sandbox): cover which backends keep boxes between commands
senamakel 75888e3
test(artifacts): add tests for box source resolution
senamakel 50cabb6
feat(artifacts): source created artifacts from the sandbox box
senamakel fef6ef7
feat(embed): add sandbox module for tenant-scoped file access
senamakel a90d99e
docs(sandbox): document moving files in and out of a box
senamakel 84adc72
docs(artifacts): document box-sourced artifact creation
senamakel eb13f02
test(openshell): remove unused base64 import from files tests
senamakel a32200c
fix(sandbox): harden openshell file transfers against path and race a…
senamakel c5e5438
fix(artifacts): fail closed when the sandbox configuration cannot be …
senamakel 5ef1266
test(artifacts): cover unreadable box configuration as a tool error
senamakel aaa1ef0
test(artifacts): assert on tool output text in box source test
senamakel 51cf68d
test(openshell): update file transfer tests for relative paths and st…
senamakel a5f9168
test(openshell): remove unused host boxes setup from staging test
senamakel d94161a
style: reformat openshell file transfer code and tests
senamakel 895dc09
test(openshell): reuse a single config in the concurrent write test
senamakel f5e29ea
test(artifacts): expect relative paths prefixed with ./ in box commands
senamakel 7c49b9b
fix(sandbox): isolate box file transfers and fail closed on unreadabl…
senamakel 4957c02
fix(sandbox): stage part files under a fixed short name
senamakel 2ffa9bd
feat(artifacts): extend box-sourced wrapper to update_artifact
senamakel 555dddf
test(artifacts): cover box-sourced updates and staged copy cleanup
senamakel a62659d
refactor(artifacts): rename box source wrapper to box sourced
senamakel ee82b86
test(artifacts): import create artifact tool in box source tests
senamakel 7bfee1c
docs(artifacts): note box_source also wraps update_artifact
senamakel cde4e90
fix(sandbox): follow symlinks when statting files for reads
senamakel 4ffa74c
fix(sandbox): drop stat -L so symlink reads report the link's own size
senamakel b8c5d69
fix(sandbox): dereference symlinks when statting files for reads
senamakel 448b940
fix(artifacts): fail the call when the artifact record cannot be read
senamakel 36875ee
fix(sandbox): reclaim stale part files on the next write
senamakel 8df5bd4
test(openshell): locate part file by uuid marker in write commands
senamakel 877a0be
fix(sandbox): narrow stale part-file sweep to transfer files
senamakel 3369e3a
test(sandbox): cover refusal of transfer-reserved file names
senamakel a4f5d5f
test(openshell): match part file marker against question mark
senamakel File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,321 @@ | ||
| //! `create_artifact` and `update_artifact` for a sandbox that keeps boxes: a | ||
| //! file `path` names a file in the calling tenant's box, not on the host. | ||
| //! | ||
| //! With a backend that keeps one box per tenant (`openshell`; see | ||
| //! [`SandboxBackendKind::keeps_boxes`](crate::sandbox::types::SandboxBackendKind::keeps_boxes)), | ||
| //! the files an agent makes live in its box, and the host has never seen | ||
| //! them. [`BoxSourced`] wraps the artifact crate's `create_artifact` | ||
| //! tool (and likewise `update_artifact`, whose artifact kind comes from its | ||
| //! stored record): for an `image` or `file` artifact it reads the file out of the | ||
| //! caller's box ([`crate::sandbox::openshell::read_file`]), stages the bytes in | ||
| //! a folder artifacts may reference, hands the staged path to the crate's tool | ||
| //! unchanged, and removes the staged copy. Everything after that is | ||
| //! [`create_artifact`](tiny_artifacts::CreateArtifactTool) as ever: the same | ||
| //! checks, the same versioned record, the same card. | ||
| //! | ||
| //! Every other call (text artifacts, and every call under a backend that keeps | ||
| //! no boxes) goes straight to the crate's tool and reads the host disk as it | ||
| //! always did. | ||
|
|
||
| use std::path::{Path, PathBuf}; | ||
| use std::sync::Arc; | ||
|
|
||
| use async_trait::async_trait; | ||
| use serde_json::Value; | ||
| use tiny_artifacts::{ArtifactKind, Artifacts}; | ||
| use tinytools::{PermissionLevel, Tool, ToolResult}; | ||
|
|
||
| use super::tiny_store::version_files_dir; | ||
| use crate::core::runtime::{DispatchCtx, NoTenant, Tenant}; | ||
| use crate::sandbox::openshell::BoxError; | ||
| use crate::sandbox::MAX_BOX_FILE_BYTES; | ||
|
|
||
| /// Where a call's box files are read from, and whether they are. | ||
| #[async_trait] | ||
| pub(crate) trait BoxFiles: Send + Sync { | ||
| /// Whether this call's sandbox keeps a box per tenant, so a file `path` | ||
| /// names a file in it. | ||
| /// | ||
| /// # Errors | ||
| /// | ||
| /// When the configuration cannot be read: the call's source is then | ||
| /// unknown, and it must not fall back to reading the host's disk. | ||
| async fn keeps_boxes(&self) -> Result<bool, BoxError>; | ||
|
|
||
| /// The file at `path` in `tenant`'s box. | ||
| async fn read( | ||
| &self, | ||
| tenant: Result<Tenant, NoTenant>, | ||
| path: &str, | ||
| max_bytes: u64, | ||
| ) -> Result<Vec<u8>, BoxError>; | ||
| } | ||
|
|
||
| /// The process's own boxes, for the call running under `ctx`. | ||
| pub(crate) struct SandboxBoxFiles { | ||
| ctx: DispatchCtx, | ||
| } | ||
|
|
||
| impl SandboxBoxFiles { | ||
| pub(crate) fn new(ctx: DispatchCtx) -> Self { | ||
| Self { ctx } | ||
| } | ||
| } | ||
|
|
||
| #[async_trait] | ||
| impl BoxFiles for SandboxBoxFiles { | ||
| async fn keeps_boxes(&self) -> Result<bool, BoxError> { | ||
| let config = | ||
| self.ctx.load_config().await.map_err(|error| { | ||
| BoxError::Driver(format!("cannot read the configuration: {error}")) | ||
| })?; | ||
| Ok(crate::sandbox::ops::sandbox_keeps_boxes(&self.ctx, &config)) | ||
| } | ||
|
|
||
| async fn read( | ||
| &self, | ||
| tenant: Result<Tenant, NoTenant>, | ||
| path: &str, | ||
| max_bytes: u64, | ||
| ) -> Result<Vec<u8>, BoxError> { | ||
| let tenant = crate::sandbox::openshell::tenant_for_box(tenant)?; | ||
| let config = | ||
| self.ctx.load_config().await.map_err(|error| { | ||
| BoxError::Driver(format!("cannot read the configuration: {error}")) | ||
| })?; | ||
| crate::sandbox::read_box_file(Ok(tenant), &config, path, max_bytes).await | ||
| } | ||
| } | ||
|
|
||
| /// Where a box file is staged on the host: a folder under the kept copies, | ||
| /// which artifacts may always reference. | ||
| pub(crate) fn staging_dir(workspace_dir: &Path) -> PathBuf { | ||
| version_files_dir(workspace_dir).join(".box-incoming") | ||
| } | ||
|
|
||
| /// `path` as a name relative to the box's work folder: an agent in the box | ||
| /// knows that folder by its absolute name, so one under it is accepted. | ||
| fn box_path(path: &str) -> &str { | ||
| let work_folder = crate::sandbox::openshell::BOX_WORKDIR; | ||
| path.strip_prefix(work_folder) | ||
| .and_then(|rest| rest.strip_prefix('/')) | ||
| .filter(|rest| !rest.is_empty()) | ||
| .unwrap_or(path) | ||
| } | ||
|
|
||
| /// The kind of an existing artifact, from its stored record. | ||
| #[async_trait] | ||
| pub(crate) trait RecordKinds: Send + Sync { | ||
| /// The kind of artifact `id` names; `None` when there is no such artifact. | ||
| /// | ||
| /// # Errors | ||
| /// | ||
| /// The store's message when it cannot be read. | ||
| async fn kind_of(&self, id: &str) -> Result<Option<ArtifactKind>, String>; | ||
| } | ||
|
|
||
| #[async_trait] | ||
| impl RecordKinds for Artifacts { | ||
| async fn kind_of(&self, id: &str) -> Result<Option<ArtifactKind>, String> { | ||
| self.get(id) | ||
| .await | ||
| .map(|record| record.map(|record| record.kind)) | ||
| .map_err(|error| error.to_string()) | ||
| } | ||
| } | ||
|
|
||
| /// Where the kind of artifact a call writes comes from. | ||
| pub(crate) enum KindSource { | ||
| /// A new artifact: the call's own `kind`. | ||
| Args, | ||
| /// An existing artifact: the kind of the record `artifact_id` names. | ||
| Record(Arc<dyn RecordKinds>), | ||
| } | ||
|
|
||
| /// One of the crate's artifact tools (`create_artifact` or `update_artifact`), | ||
| /// reading a file `path` from the caller's box when the sandbox keeps one. | ||
| pub(crate) struct BoxSourced { | ||
| inner: Box<dyn Tool>, | ||
| kinds: KindSource, | ||
| boxes: Arc<dyn BoxFiles>, | ||
| tenant: Result<Tenant, NoTenant>, | ||
| staging: PathBuf, | ||
| } | ||
|
|
||
| impl BoxSourced { | ||
| /// `tenant` is the calling tenant (its box is read); `staging` is the | ||
| /// folder (see [`staging_dir`]) a box file is copied into for the crate. | ||
| pub(crate) fn new( | ||
| inner: impl Tool + 'static, | ||
| kinds: KindSource, | ||
| boxes: Arc<dyn BoxFiles>, | ||
| tenant: Result<Tenant, NoTenant>, | ||
| staging: PathBuf, | ||
| ) -> Self { | ||
| Self { | ||
| inner: Box::new(inner), | ||
| kinds, | ||
| boxes, | ||
| tenant, | ||
| staging, | ||
| } | ||
| } | ||
|
|
||
| /// The kind of artifact this call writes, when it can be told. | ||
| /// | ||
| /// # Errors | ||
| /// | ||
| /// When the stored record cannot be read: the call must then fail, not | ||
| /// fall back to the host's disk. | ||
| async fn kind(&self, args: &Value) -> Result<Option<ArtifactKind>, BoxError> { | ||
| match &self.kinds { | ||
| KindSource::Args => Ok(args | ||
| .get("kind") | ||
| .and_then(Value::as_str) | ||
| .and_then(ArtifactKind::parse)), | ||
| KindSource::Record(records) => { | ||
| // A missing argument or an unknown id is the crate's tool to report. | ||
| let Some(id) = args.get("artifact_id").and_then(Value::as_str) else { | ||
| return Ok(None); | ||
| }; | ||
| records | ||
| .kind_of(id) | ||
| .await | ||
| .map_err(|error| BoxError::Driver(format!("cannot read the artifact: {error}"))) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// The file to read from the box, when this call is one that does: an | ||
| /// `image` or `file` artifact, under a sandbox that keeps boxes. (A call | ||
| /// the crate would reject is left to it.) | ||
| /// | ||
| /// # Errors | ||
| /// | ||
| /// When it cannot be told whether the sandbox keeps boxes. | ||
| async fn box_file(&self, args: &Value) -> Result<Option<String>, BoxError> { | ||
| let Some(kind) = self.kind(args).await? else { | ||
| return Ok(None); | ||
| }; | ||
| if !kind.holds_file() { | ||
| return Ok(None); | ||
| } | ||
| // The crate takes `body` as the path too, for callers that predate `path`. | ||
| let path = ["path", "body"] | ||
| .iter() | ||
| .filter_map(|key| args.get(key).and_then(Value::as_str)) | ||
| .map(str::trim) | ||
| .find(|path| !path.is_empty()); | ||
| let Some(path) = path else { | ||
| return Ok(None); | ||
| }; | ||
| Ok(self | ||
| .boxes | ||
| .keeps_boxes() | ||
| .await? | ||
| .then(|| box_path(path).to_owned())) | ||
| } | ||
| } | ||
|
|
||
| #[async_trait] | ||
| impl Tool for BoxSourced { | ||
| fn name(&self) -> &str { | ||
| self.inner.name() | ||
| } | ||
|
|
||
| fn description(&self) -> &str { | ||
| self.inner.description() | ||
| } | ||
|
|
||
| fn parameters_schema(&self) -> Value { | ||
| self.inner.parameters_schema() | ||
| } | ||
|
|
||
| fn permission_level(&self) -> PermissionLevel { | ||
| self.inner.permission_level() | ||
| } | ||
|
|
||
| fn is_concurrency_safe(&self, args: &Value) -> bool { | ||
| self.inner.is_concurrency_safe(args) | ||
| } | ||
|
|
||
| async fn execute(&self, mut args: Value) -> anyhow::Result<ToolResult> { | ||
| let path = match self.box_file(&args).await { | ||
| Ok(Some(path)) => path, | ||
| Ok(None) => return self.inner.execute(args).await, | ||
| Err(error) => return Ok(ToolResult::error(error.to_string())), | ||
| }; | ||
| let bytes = match self | ||
| .boxes | ||
| .read(self.tenant.clone(), &path, MAX_BOX_FILE_BYTES) | ||
| .await | ||
| { | ||
| Ok(bytes) => bytes, | ||
| Err(error) => return Ok(ToolResult::error(error.to_string())), | ||
| }; | ||
| let staged = match stage(&self.staging, &path, &bytes) { | ||
| Ok(staged) => staged, | ||
| Err(error) => { | ||
| tracing::warn!(%error, "[artifacts] could not stage a sandbox file"); | ||
| return Ok(ToolResult::error( | ||
| "the file could not be copied out of the sandbox", | ||
| )); | ||
| } | ||
| }; | ||
| args["path"] = Value::String(staged.file.display().to_string()); | ||
| // `staged` removes its folder when dropped, so a call cancelled while | ||
| // the crate's tool runs leaves nothing behind either. | ||
| self.inner.execute(args).await | ||
| } | ||
| } | ||
|
|
||
| /// A box file copied onto the host for one call. Dropping it removes the copy, | ||
| /// whether the call finished or was cancelled. | ||
| struct Staged { | ||
| dir: PathBuf, | ||
| file: PathBuf, | ||
| } | ||
|
|
||
| impl Drop for Staged { | ||
| fn drop(&mut self) { | ||
| match std::fs::remove_dir_all(&self.dir) { | ||
| Ok(()) => {} | ||
| // Nothing was made yet (a failed or cancelled stage). | ||
| Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} | ||
| Err(error) => { | ||
| tracing::warn!(%error, "[artifacts] could not remove a staged sandbox file") | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// Copy `bytes` into a folder of its own under `staging`, as `file` plus the | ||
| /// box file's extension (which decides the artifact's media type). The name is | ||
| /// generated, so a box name the host's filesystem rejects (`?` on Windows) | ||
| /// still stages. | ||
| /// | ||
| /// The folder is owned by the returned [`Staged`] from before it exists, and | ||
| /// nothing here awaits, so a call cancelled at any point leaves no copy behind. | ||
| fn stage(staging: &Path, box_path: &str, bytes: &[u8]) -> std::io::Result<Staged> { | ||
| let name = match Path::new(box_path) | ||
| .extension() | ||
| .and_then(|extension| extension.to_str()) | ||
| .filter(|extension| { | ||
| extension.len() <= 16 && extension.chars().all(|c| c.is_ascii_alphanumeric()) | ||
| }) { | ||
| Some(extension) => format!("file.{extension}"), | ||
| None => "file".to_owned(), | ||
| }; | ||
| let dir = staging.join(uuid::Uuid::new_v4().simple().to_string()); | ||
| let staged = Staged { | ||
| file: dir.join(name), | ||
| dir, | ||
| }; | ||
| std::fs::create_dir_all(&staged.dir)?; | ||
| std::fs::write(&staged.file, bytes)?; | ||
| Ok(staged) | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| #[path = "box_source_tests.rs"] | ||
| mod tests; | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.