Skip to main content

chainguard_sandbox/
sandbox.rs

1//! Sandboxes: create, connect, list, delete, pause.
2
3use std::collections::HashMap;
4use std::sync::Arc;
5use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
6
7use crate::commands::Commands;
8use crate::files::Files;
9use crate::workspaces::{self, Client, ListOptions, Options, Session, pb::Phase};
10use crate::{Error, Result};
11
12/// The toolchain a sandbox gets when [`CreateOptions::packages`] is `None`: a shell, the core
13/// tools, git, curl, jq, Python and Node.js. Package names are Chainguard (Wolfi) package names,
14/// e.g. "python-3.12", "go", "nodejs-22", "bun", "rust".
15pub const DEFAULT_PACKAGES: &[&str] = &[
16    "bash",
17    "coreutils",
18    "curl",
19    "git",
20    "jq",
21    "python-3.13",
22    "nodejs-22",
23];
24
25/// Where commands run and relative paths resolve.
26pub const DEFAULT_WORKDIR: &str = "/work";
27
28/// Marks sessions created by this package (the workspace label).
29const LABEL_PREFIX: &str = "/chainguard-sandbox/";
30
31/// Starts the sandbox from a GitHub repository instead of an empty tree: the plane clones it into
32/// /work (no upload).
33#[derive(Debug, Clone, Default)]
34pub struct GitSource {
35    /// A github.com repository (`github.com/o/r`, `https://github.com/o/r`, `git@github.com:o/r.git`).
36    pub url: String,
37    /// The revision to check out; empty means the default branch.
38    pub revision: String,
39}
40
41/// Configures [`Sandbox::create`]. The default is a sandbox with [`DEFAULT_PACKAGES`] and open
42/// egress.
43#[derive(Clone, Default)]
44pub struct CreateOptions {
45    /// Packages installed in the sandbox (Chainguard package names). `None` means
46    /// [`DEFAULT_PACKAGES`]; `Some(vec![])` means none beyond the base system. They are resolved
47    /// when the sandbox is created; an unknown package fails `create`.
48    pub packages: Option<Vec<String>>,
49    /// Environment variables for every command (per-command ones override them). They are kept
50    /// client-side, in this `Sandbox` value.
51    pub envs: HashMap<String, String>,
52    /// Labels the sandbox. Its display name becomes `<name>/<word-word>`. Defaults to "sandbox".
53    pub name: String,
54    /// The outbound allowlist (hostnames; "*" allows all). `None` means `["*"]`. The platform
55    /// always blocks cloud metadata, loopback and private ranges.
56    pub egress: Option<Vec<String>>,
57    /// What happens to a connection outside `egress`: "deny" (refuse it; the default) or
58    /// "destroy" (tear the sandbox down).
59    pub egress_policy: String,
60    /// Replaces the generated environment document entirely (a .chainguard/ci.yaml-style
61    /// document). `packages`, `egress` and `egress_policy` are then ignored.
62    pub document: Option<Vec<u8>>,
63    /// Starts from a GitHub repository instead of an empty tree.
64    pub source: Option<GitSource>,
65    /// Bounds waiting for the guest to start (default 3 minutes).
66    pub start_timeout: Option<Duration>,
67    /// The Workspaces client to use. `None` creates one with the default login and the
68    /// organization from `instance`.
69    pub client: Option<Client>,
70    /// The organization ID (used when `client` is `None`). If empty, `$CHAINCTL_SANDBOX_INSTANCE`
71    /// is used; if that's empty too, the organization is auto-detected when you belong to exactly
72    /// one (turn off with `$CHAINGUARD_SANDBOX_NO_DETECT_INSTANCE=1`). List IDs with
73    /// [`list_organizations`], `chainguard-sandbox orgs` or `chainctl iam organizations list`.
74    pub instance: String,
75}
76
77/// Configures [`Sandbox::connect`], [`list`] and [`kill`].
78#[derive(Clone, Default)]
79pub struct ConnectOptions {
80    /// Environment variables for every command on the returned sandbox (not stored remotely).
81    pub envs: HashMap<String, String>,
82    pub client: Option<Client>,
83    pub instance: String,
84}
85
86pub(crate) struct Inner {
87    pub client: Client,
88    pub id: String,
89    pub name: String,
90    pub envs: HashMap<String, String>,
91}
92
93/// A handle to one sandbox. Cloning is cheap; clones refer to the same sandbox. The sandbox runs
94/// one command at a time: concurrent calls queue in the plane.
95///
96/// Deleting is explicit: call [`Sandbox::kill`], or use [`Sandbox::with`], which deletes the
97/// sandbox when its closure returns. Dropping a `Sandbox` leaves the sandbox running (it parks
98/// when idle and is discarded after 5 days).
99#[derive(Clone)]
100pub struct Sandbox {
101    /// The short ID (8 hex characters), usable with [`Sandbox::connect`].
102    pub id: String,
103    /// The full resource name (`instances/<org>/sessions/<id>`).
104    pub name: String,
105    /// Runs commands in the sandbox.
106    pub commands: Commands,
107    /// Reads and writes the sandbox's filesystem.
108    pub files: Files,
109    inner: Arc<Inner>,
110}
111
112impl std::fmt::Debug for Sandbox {
113    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
114        f.debug_struct("Sandbox")
115            .field("id", &self.id)
116            .field("name", &self.name)
117            .finish_non_exhaustive()
118    }
119}
120
121/// Describes a sandbox.
122#[derive(Debug, Clone, Default)]
123pub struct Info {
124    pub id: String,
125    pub name: String,
126    pub display_name: String,
127    /// "creating", "running", "paused" or "stopped".
128    pub state: String,
129    pub region: String,
130    pub created_at: Option<SystemTime>,
131    /// When a paused sandbox is discarded.
132    pub expires_at: Option<SystemTime>,
133    pub cpus: i32,
134    pub memory_mib: i64,
135}
136
137async fn client_for(c: &Option<Client>, instance: &str) -> Result<Client> {
138    match c {
139        Some(c) => Ok(c.clone()),
140        None => {
141            Client::new(Options {
142                instance: instance.into(),
143                ..Default::default()
144            })
145            .await
146        }
147    }
148}
149
150/// The environment document [`Sandbox::create`] would send for `o`.
151pub fn document(o: &CreateOptions) -> Vec<u8> {
152    if let Some(d) = &o.document {
153        return d.clone();
154    }
155    let defaults: Vec<String> = DEFAULT_PACKAGES.iter().map(|p| p.to_string()).collect();
156    let pkgs = o.packages.as_ref().unwrap_or(&defaults);
157    let all = vec!["*".to_string()];
158    let egress = o.egress.as_ref().unwrap_or(&all);
159    let policy = if o.egress_policy.is_empty() {
160        "deny"
161    } else {
162        &o.egress_policy
163    };
164    let mut b = String::from(
165        "# Generated by chainguard-sandbox-sdk.\nversion: 1\nenvironment:\n  packages:\n",
166    );
167    for p in pkgs {
168        b.push_str(&format!("    - {}\n", yaml_string(p)));
169    }
170    b.push_str("checks:\n  develop:\n    network:\n      egress:");
171    if egress.is_empty() {
172        b.push_str(" []\n");
173    } else {
174        b.push('\n');
175        for h in egress {
176            b.push_str(&format!("        - {}\n", yaml_string(h)));
177        }
178    }
179    b.push_str(&format!("      policy: {}\n", yaml_string(policy)));
180    b.into_bytes()
181}
182
183/// Quotes s as a YAML double-quoted scalar.
184fn yaml_string(s: &str) -> String {
185    format!(
186        "\"{}\"",
187        s.replace('\\', "\\\\")
188            .replace('"', "\\\"")
189            .replace('\n', "\\n")
190    )
191}
192
193/// Timings, adjustable by tests.
194pub(crate) mod timings {
195    use std::sync::atomic::{AtomicU64, Ordering};
196    use std::time::Duration;
197
198    static PLACEMENT_GRACE_MS: AtomicU64 = AtomicU64::new(30_000);
199    static START_POLL_MS: AtomicU64 = AtomicU64::new(1_000);
200    static KILL_WAIT_MS: AtomicU64 = AtomicU64::new(30_000);
201    static KILL_POLL_MS: AtomicU64 = AtomicU64::new(500);
202
203    /// How long "starting guest failed" may show before giving up on a host.
204    pub fn placement_grace() -> Duration {
205        Duration::from_millis(PLACEMENT_GRACE_MS.load(Ordering::Relaxed))
206    }
207    /// Between GetSession calls while starting.
208    pub fn start_poll() -> Duration {
209        Duration::from_millis(START_POLL_MS.load(Ordering::Relaxed))
210    }
211    /// How long kill waits for the session to disappear.
212    pub fn kill_wait() -> Duration {
213        Duration::from_millis(KILL_WAIT_MS.load(Ordering::Relaxed))
214    }
215    /// Between GetSession calls while deleting.
216    pub fn kill_poll() -> Duration {
217        Duration::from_millis(KILL_POLL_MS.load(Ordering::Relaxed))
218    }
219
220    /// Shortens every timing (tests only).
221    #[doc(hidden)]
222    pub fn shorten(placement_grace: u64, start_poll: u64, kill_wait: u64, kill_poll: u64) {
223        PLACEMENT_GRACE_MS.store(placement_grace, Ordering::Relaxed);
224        START_POLL_MS.store(start_poll, Ordering::Relaxed);
225        KILL_WAIT_MS.store(kill_wait, Ordering::Relaxed);
226        KILL_POLL_MS.store(kill_poll, Ordering::Relaxed);
227    }
228}
229
230#[doc(hidden)]
231pub use timings::shorten as shorten_timings_for_tests;
232
233/// Maps lower-level errors to the sandbox API's (like Go's `wrapErr`).
234pub(crate) fn wrap(e: Error) -> Error {
235    if matches!(e, Error::OutcomeUnknown { .. }) {
236        return e;
237    }
238    if workspaces::is_guest_held(&e) {
239        return Error::Busy { cause: Box::new(e) };
240    }
241    if let Error::Rpc(s) = &e {
242        if s.code() == tonic::Code::PermissionDenied
243            && s.message()
244                .contains("not entitled to Chainguard Workspaces")
245        {
246            return Error::NotEnabled { cause: Box::new(e) };
247        }
248        if s.code() == tonic::Code::ResourceExhausted {
249            return Error::LimitReached {
250                message: s.message().to_string(),
251            };
252        }
253    }
254    e
255}
256
257impl Sandbox {
258    fn from_session(client: Client, s: &Session, envs: HashMap<String, String>) -> Sandbox {
259        let inner = Arc::new(Inner {
260            client,
261            id: s.short_id.clone(),
262            name: s.name.clone(),
263            envs,
264        });
265        Sandbox {
266            id: inner.id.clone(),
267            name: inner.name.clone(),
268            commands: Commands::new(inner.clone()),
269            files: Files::new(inner.clone()),
270            inner,
271        }
272    }
273
274    /// Starts a new sandbox and returns when it can run commands (about 8–20 seconds). On failure
275    /// it deletes anything it created. A session the plane places on a host that never starts is
276    /// deleted and recreated (up to three attempts).
277    pub async fn create(o: CreateOptions) -> Result<Sandbox> {
278        let c = client_for(&o.client, &o.instance).await?;
279        let doc = document(&o);
280        let name = if o.name.is_empty() {
281            "sandbox"
282        } else {
283            &o.name
284        };
285        if name.contains('/') || name.contains('\n') {
286            return Err(Error::other(format!(
287                "sandbox: name {name:?} must not contain '/' or newlines"
288            )));
289        }
290        let start_timeout = o
291            .start_timeout
292            .filter(|d| !d.is_zero())
293            .unwrap_or(Duration::from_secs(180));
294        let mut last_err = String::new();
295        for _attempt in 1..=3 {
296            let req = match &o.source {
297                Some(src) => {
298                    let mut s = workspaces::repository_session(&src.url, &src.revision);
299                    if let Some(workspaces::pb::session::Environment::Source(so)) =
300                        &mut s.environment
301                    {
302                        so.fallback_document = doc.clone();
303                    }
304                    s
305                }
306                None => workspaces::workspace_session(
307                    &format!("{LABEL_PREFIX}{name}"),
308                    "",
309                    "",
310                    Some(doc.clone()),
311                ),
312            };
313            let s = c.create(req).await.map_err(wrap)?;
314            let created = s.name.clone();
315            let cleanup = || async {
316                let _ = tokio::time::timeout(Duration::from_secs(30), c.delete(&created)).await;
317            };
318            let s = match wait_started(&c, &created, start_timeout).await {
319                Err(Placement(msg)) => {
320                    cleanup().await;
321                    last_err = msg;
322                    continue;
323                }
324                Ok(Err(e)) => {
325                    cleanup().await;
326                    return Err(e);
327                }
328                Ok(Ok(s)) => s,
329            };
330            if s.workspace_pending
331                && let Err(e) = empty_upload(&c, &s.name).await
332            {
333                cleanup().await;
334                return Err(e);
335            }
336            return Ok(Sandbox::from_session(c, &s, o.envs.clone()));
337        }
338        Err(Error::other(format!(
339            "sandbox: the plane could not start a guest in 3 attempts: the guest failed to start: {last_err}"
340        )))
341    }
342
343    /// Creates a sandbox, runs `f` with it, and deletes the sandbox afterwards, whether `f`
344    /// succeeds or fails. If the returned future is dropped early or `f` panics, the delete is
345    /// started in the background instead.
346    ///
347    /// ```no_run
348    /// # async fn g() -> chainguard_sandbox::Result<()> {
349    /// use chainguard_sandbox::{CreateOptions, Sandbox};
350    /// let out = Sandbox::with(CreateOptions::default(), async |sbx| {
351    ///     Ok(sbx.commands.run("echo hi").await?.stdout)
352    /// })
353    /// .await?;
354    /// # Ok(()) }
355    /// ```
356    pub async fn with<T, F>(o: CreateOptions, f: F) -> Result<T>
357    where
358        F: AsyncFnOnce(&Sandbox) -> Result<T>,
359    {
360        let sbx = Sandbox::create(o).await?;
361        let mut guard = KillOnDrop(Some(sbx.clone()));
362        let r = f(&sbx).await;
363        guard.0 = None;
364        let k = sbx.kill().await;
365        let v = r?;
366        k?;
367        Ok(v)
368    }
369
370    /// Returns a handle to an existing sandbox by short ID, display name or resource name. A
371    /// paused sandbox resumes on its first command.
372    pub async fn connect(id: &str, o: ConnectOptions) -> Result<Sandbox> {
373        let c = client_for(&o.client, &o.instance).await?;
374        let s = match c.resolve(id).await {
375            Err(Error::NotFound { .. }) => {
376                return Err(Error::NotFound {
377                    what: "sandbox".into(),
378                    name: id.into(),
379                });
380            }
381            Err(e) => return Err(wrap(e)),
382            Ok(s) => s,
383        };
384        if s.workspace_pending {
385            empty_upload(&c, &s.name).await?;
386        }
387        Ok(Sandbox::from_session(c, &s, o.envs))
388    }
389
390    /// Deletes the sandbox and everything in it, and returns once it is gone, so the session slot
391    /// is free for a new sandbox. Returns false if the sandbox was already gone. If it still
392    /// exists 30 seconds after the delete request (or its disappearance can't be confirmed), the
393    /// error is [`Error::Timeout`] with op "kill": the deletion was requested but the slot may not
394    /// be free yet.
395    pub async fn kill(&self) -> Result<bool> {
396        delete_and_wait(&self.inner.client, &self.inner.name).await
397    }
398
399    /// Snapshots the sandbox (memory and disk) and stops it. Running processes, including
400    /// background commands, resume where they were on the next command or file operation.
401    pub async fn pause(&self) -> Result<()> {
402        self.inner
403            .client
404            .park(&self.inner.name)
405            .await
406            .map_err(wrap)?;
407        Ok(())
408    }
409
410    /// Asks the plane to hold the sandbox running (not park it when idle) for `d`. An idle
411    /// sandbox parks after about 10 minutes, and a parked one is discarded after 5 days.
412    pub async fn keep_alive(&self, d: Duration) -> Result<()> {
413        self.inner
414            .client
415            .heartbeat(&self.inner.name, d)
416            .await
417            .map_err(wrap)?;
418        Ok(())
419    }
420
421    /// Fetches the sandbox's current state.
422    pub async fn get_info(&self) -> Result<Info> {
423        match self.inner.client.get(&self.inner.name).await {
424            Ok(s) => Ok(info(&s)),
425            Err(e) if e.grpc_code() == Some(tonic::Code::NotFound) => Err(Error::NotFound {
426                what: "sandbox".into(),
427                name: self.id.clone(),
428            }),
429            Err(e) => Err(wrap(e)),
430        }
431    }
432
433    /// Whether the sandbox is running (not paused, stopped or still starting).
434    pub async fn is_running(&self) -> Result<bool> {
435        match self.get_info().await {
436            Ok(i) => Ok(i.state == "running"),
437            Err(Error::NotFound { .. }) => Ok(false),
438            Err(e) => Err(e),
439        }
440    }
441
442    /// The underlying Workspaces client, for anything this API doesn't wrap.
443    pub fn client(&self) -> &Client {
444        &self.inner.client
445    }
446}
447
448/// Deletes the sandbox in the background if the scope it guards is left abnormally.
449struct KillOnDrop(Option<Sandbox>);
450
451impl Drop for KillOnDrop {
452    fn drop(&mut self) {
453        if let Some(sbx) = self.0.take()
454            && let Ok(h) = tokio::runtime::Handle::try_current()
455        {
456            h.spawn(async move {
457                let _ = sbx.kill().await;
458            });
459        }
460    }
461}
462
463/// The session landed on a host that keeps failing to start it.
464struct Placement(String);
465
466/// Polls until the guest has started. `limit` bounds the whole wait, including each GetSession
467/// call: a call that stalls is cut off at the deadline, so a late answer can never be reported as
468/// a start in time.
469async fn wait_started(
470    c: &Client,
471    name: &str,
472    limit: Duration,
473) -> std::result::Result<Result<Session>, Placement> {
474    let t0 = Instant::now();
475    let deadline = t0 + limit;
476    let mut last: Option<Session> = None;
477    let expired = |last: &Option<Session>| {
478        let mut detail = format!("the guest did not start within {}", go_duration(limit));
479        if let Some(s) = last {
480            let phase = Phase::try_from(s.phase)
481                .map(|p| p.as_str_name())
482                .unwrap_or("PHASE_UNSPECIFIED");
483            detail.push_str(&format!(" (phase {phase}: {})", s.message));
484        }
485        Err(Error::Timeout {
486            op: "start".into(),
487            detail,
488            result: None,
489        })
490    };
491    loop {
492        let remaining = deadline.saturating_duration_since(Instant::now());
493        let s = match tokio::time::timeout(remaining, c.get(name)).await {
494            Err(_) => return Ok(expired(&last)),
495            Ok(Err(e)) => return Ok(Err(wrap(e))),
496            Ok(Ok(s)) => s,
497        };
498        if s.guest_started_time.is_some() {
499            return Ok(Ok(s));
500        }
501        if s.message.contains("starting guest failed") && t0.elapsed() > timings::placement_grace()
502        {
503            return Err(Placement(s.message));
504        }
505        last = Some(s);
506        let remaining = deadline.saturating_duration_since(Instant::now());
507        if remaining.is_zero() {
508            return Ok(expired(&last));
509        }
510        tokio::time::sleep(timings::start_poll().min(remaining)).await;
511        if Instant::now() >= deadline {
512            return Ok(expired(&last));
513        }
514    }
515}
516
517/// Go's `time.Duration` formatting for the durations used in messages ("3m0s", "30s", "1.5s").
518pub(crate) fn go_duration(d: Duration) -> String {
519    let ms = d.as_millis();
520    if ms % 1000 != 0 {
521        return format!("{}s", d.as_secs_f64());
522    }
523    let s = d.as_secs();
524    match (s / 3600, (s / 60) % 60, s % 60) {
525        (0, 0, sec) => format!("{sec}s"),
526        (0, m, sec) => format!("{m}m{sec}s"),
527        (h, m, sec) => format!("{h}h{m}m{sec}s"),
528    }
529}
530
531/// Completes the first attach with an empty tree. The plane refuses Exec until a shell attach has
532/// uploaded the workspace.
533async fn empty_upload(c: &Client, name: &str) -> Result<()> {
534    match c.complete_first_attach(name).await {
535        Ok(()) => Ok(()),
536        Err(e @ Error::Timeout { .. }) => Err(e),
537        Err(e) => Err(Error::other(format!(
538            "sandbox: completing the first attach: {}",
539            wrap(e)
540        ))),
541    }
542}
543
544/// Returns the sandboxes this API created (sessions with a sandbox label) in the instance.
545pub async fn list(o: ConnectOptions) -> Result<Vec<Info>> {
546    let c = client_for(&o.client, &o.instance).await?;
547    let ss = c.list(&ListOptions::default()).await.map_err(wrap)?;
548    Ok(ss
549        .iter()
550        .filter(|s| match &s.environment {
551            Some(workspaces::pb::session::Environment::Workspace(w)) => {
552                w.label.starts_with(LABEL_PREFIX)
553            }
554            _ => false,
555        })
556        .map(info)
557        .collect())
558}
559
560/// Deletes the sandbox with the given ID (short ID, display name or resource name). Returns false
561/// if there was none. Unlike [`Sandbox::connect`] it does not attach to the sandbox first, so it
562/// also deletes one that never started or cannot be attached to. Errors as for
563/// [`Sandbox::kill`].
564pub async fn kill(id: &str, o: ConnectOptions) -> Result<bool> {
565    let c = client_for(&o.client, &o.instance).await?;
566    match c.resolve(id).await {
567        Err(Error::NotFound { .. }) => Ok(false),
568        Err(e) if e.grpc_code() == Some(tonic::Code::NotFound) => Ok(false),
569        Err(e) => Err(wrap(e)),
570        Ok(s) => delete_and_wait(&c, &s.name).await,
571    }
572}
573
574/// Sends the delete request and waits until the session is gone.
575async fn delete_and_wait(c: &Client, name: &str) -> Result<bool> {
576    match c.delete(name).await {
577        Err(e) if e.grpc_code() == Some(tonic::Code::NotFound) => return Ok(false),
578        Err(e) => return Err(wrap(e)),
579        Ok(()) => {}
580    }
581    // Deletion is asynchronous (the session disappears 1-8 s later). Each check runs under the
582    // deadline, so a stalled call can't stretch the wait.
583    let wait = timings::kill_wait();
584    let deadline = Instant::now() + wait;
585    let mut last_err: Option<Error> = None;
586    loop {
587        let remaining = deadline.saturating_duration_since(Instant::now());
588        match tokio::time::timeout(remaining, c.get(name)).await {
589            Ok(Err(e)) if e.grpc_code() == Some(tonic::Code::NotFound) => return Ok(true),
590            Ok(Err(e)) => last_err = Some(wrap(e)),
591            Ok(Ok(_)) => last_err = None,
592            Err(_) => {}
593        }
594        let remaining = deadline.saturating_duration_since(Instant::now());
595        if remaining.is_zero() {
596            let detail = match &last_err {
597                Some(e) if e.grpc_code() != Some(tonic::Code::DeadlineExceeded) => {
598                    format!(
599                        "could not confirm the sandbox is gone within {} (last check: {e})",
600                        go_duration(wait)
601                    )
602                }
603                _ => format!(
604                    "the sandbox still exists {} after the delete request",
605                    go_duration(wait)
606                ),
607            };
608            return Err(Error::Timeout {
609                op: "kill".into(),
610                detail,
611                result: None,
612            });
613        }
614        tokio::time::sleep(timings::kill_poll().min(remaining)).await;
615    }
616}
617
618fn timestamp(t: &Option<prost_types::Timestamp>) -> Option<SystemTime> {
619    t.as_ref()
620        .map(|t| UNIX_EPOCH + Duration::new(t.seconds.max(0) as u64, t.nanos.max(0) as u32))
621}
622
623pub(crate) fn info(s: &Session) -> Info {
624    let rc = s.max_resource_class.unwrap_or_default();
625    let state = match Phase::try_from(s.phase) {
626        Ok(Phase::Creating) => "creating",
627        Ok(Phase::Attached) | Ok(Phase::Idle) => "running",
628        Ok(Phase::Parked) => "paused",
629        _ => "stopped",
630    };
631    Info {
632        id: s.short_id.clone(),
633        name: s.name.clone(),
634        display_name: s.display_name.clone(),
635        state: state.into(),
636        region: s.region.clone(),
637        created_at: timestamp(&s.create_time),
638        expires_at: timestamp(&s.expire_time),
639        cpus: rc.cpus,
640        memory_mib: rc.memory_mib,
641    }
642}
643
644/// Resolves p against [`DEFAULT_WORKDIR`].
645pub(crate) fn guest_path(p: &str) -> String {
646    if p.is_empty() {
647        DEFAULT_WORKDIR.into()
648    } else {
649        workspaces::guest_path(p)
650    }
651}
652
653/// A Chainguard organization a sandbox can live in.
654pub use crate::workspaces::Organization;
655
656crate::opaque_debug!(CreateOptions, ConnectOptions);
657
658/// The organizations you belong to (their IDs are what [`CreateOptions::instance`] and
659/// `$CHAINCTL_SANDBOX_INSTANCE` take). With exactly one, [`Sandbox::create`] uses it automatically
660/// when no organization is set. It uses the saved login's account-API token.
661pub async fn list_organizations() -> Result<Vec<Organization>> {
662    workspaces::list_organizations(None).await
663}