Skip to main content

chainguard_sandbox/
error.rs

1//! The crate's error type.
2//!
3//! Every fallible call returns [`Error`]. Match on its variants the way the Go SDK's callers use
4//! `errors.As` and `errors.Is`:
5//!
6//! ```no_run
7//! # async fn f(sbx: &chainguard_sandbox::Sandbox) {
8//! use chainguard_sandbox::Error;
9//! match sbx.commands.run("false").await {
10//!     Ok(r) => println!("{}", r.stdout),
11//!     Err(Error::CommandExit(r)) => println!("exited {}: {}", r.exit_code, r.stderr),
12//!     Err(Error::Busy { .. }) => println!("another client is attached"),
13//!     Err(e) => println!("{e}"),
14//! }
15//! # }
16//! ```
17
18use std::fmt;
19use std::sync::Arc;
20
21use crate::commands::CommandResult;
22use crate::workspaces::{Organization, PlatformError, TermsDocument};
23
24/// `Result` with this crate's [`Error`].
25pub type Result<T, E = Error> = std::result::Result<T, E>;
26
27/// Everything that can go wrong. The variants mirror the typed errors of the Go, Python and
28/// TypeScript SDKs (`CommandExitError`, `NotFoundError`, `ErrBusy`, ...).
29#[derive(Debug, Clone, thiserror::Error)]
30#[non_exhaustive]
31pub enum Error {
32    // ---- the sandbox API -------------------------------------------------------------------
33    /// A command exited with a non-zero code. Holds the full result.
34    #[error("{}", command_exit_message(.0))]
35    CommandExit(CommandResult),
36
37    /// A file, directory, path, background command or sandbox does not exist. `what` is
38    /// "file", "directory", "path", "command", "sandbox" or "session".
39    #[error("sandbox: {what} not found: {name}")]
40    NotFound { what: String, name: String },
41
42    /// The path exists but is the wrong kind; `reason` is "is a directory" or "not a directory".
43    #[error("sandbox: {path}: {reason}")]
44    InvalidPath { path: String, reason: String },
45
46    /// A deadline passed. `op` is "command", "start" or "kill". For a command, `result` holds the
47    /// output received before it was stopped.
48    #[error("{}", timeout_message(.op, .detail))]
49    Timeout {
50        op: String,
51        detail: String,
52        result: Option<CommandResult>,
53    },
54
55    /// The sandbox is held by another controller, typically an interactive shell attached with
56    /// chainctl. Commands can't run until it detaches.
57    #[error(
58        "sandbox: busy: another client is attached to this sandbox (an interactive shell); commands run once it detaches ({cause})"
59    )]
60    Busy { cause: Box<Error> },
61
62    /// The organization is at its session limit. Kill a sandbox first.
63    #[error(
64        "sandbox: session limit reached (one sandbox per user during the Workspaces beta); kill an existing sandbox first ({message})"
65    )]
66    LimitReached { message: String },
67
68    /// The connection ended, or failed, before the command reported an exit status. It may or
69    /// may not have run, in part or in full. `cause` is the transport error, when there was one;
70    /// `result` holds the output received before the stream ended.
71    #[error("sandbox: the command's outcome is unknown (the connection ended before it reported an exit status){}", cause_suffix(.cause))]
72    OutcomeUnknown {
73        cause: Option<Box<Error>>,
74        result: Option<CommandResult>,
75    },
76
77    /// Workspaces is not turned on for the organization. An owner can turn it on with
78    /// [`enable_workspaces`](crate::enable_workspaces) or `chainguard-sandbox enable`.
79    #[error(
80        "sandbox: Workspaces is not turned on for this organization; an owner can turn it on with enable_workspaces or `chainguard-sandbox enable`: {cause}"
81    )]
82    NotEnabled { cause: Box<Error> },
83
84    /// The organization has not accepted the legal documents Workspaces is offered under.
85    /// [`enable_workspaces`](crate::enable_workspaces) accepts them when `accept_terms` is set.
86    #[error("sandbox: the organization has not accepted the terms Workspaces is offered under: {}", terms_list(.missing))]
87    TermsNotAccepted { missing: Vec<TermsDocument> },
88
89    /// The organization has no GitHub account linked, which the service requires before it turns
90    /// Workspaces on, and enabling was not allowed to open a browser to link one.
91    #[error(
92        "sandbox: organization {organization} has to link a GitHub account before Workspaces can be turned on; run enable_workspaces where it can open a browser, or `chainguard-sandbox enable`"
93    )]
94    GitHubLinkRequired { organization: String },
95
96    /// The Chainguard GitHub App is not installed on the GitHub account being linked. Install it
97    /// at `install_url`, then enable again.
98    #[error(
99        "sandbox: the Chainguard GitHub App is not installed on that GitHub account; install it at {install_url} and try again ({cause})"
100    )]
101    GitHubAppNotInstalled {
102        install_url: String,
103        cause: Box<Error>,
104    },
105
106    // ---- the lower layer -------------------------------------------------------------------
107    /// The sandbox plane answered a call with a gRPC error.
108    #[error("rpc error: code = {} desc = {}", code_name(.0.code()), .0.message())]
109    Rpc(tonic::Status),
110
111    /// The platform (account) API answered with an error. `context` says which call.
112    #[error("{context}: {error}")]
113    Platform {
114        context: String,
115        error: PlatformError,
116    },
117
118    /// An HTTP call answered with an error status.
119    #[error("{context}: HTTP {status}: {message}")]
120    Http {
121        context: String,
122        status: u16,
123        message: String,
124    },
125
126    /// An HTTP or gRPC connection could not be made or broke off.
127    #[error("{context}: {message}")]
128    Transport { context: String, message: String },
129
130    /// There is no saved login and the token source may not open a browser.
131    #[error("workspaces: not logged in (run `chainguard-sandbox login`, or use a BrowserLoginToken that may open a browser){}", detail_suffix(.detail))]
132    LoginRequired { detail: Option<String> },
133
134    /// The saved login was refused (expired, revoked or already spent); log in again.
135    #[error("workspaces: the saved login has expired or was revoked: {detail}")]
136    LoginExpired { detail: String },
137
138    /// The issuer knows no Chainguard account for the person who logged in.
139    #[error(
140        "workspaces: login: no Chainguard account for this login (sign up for Workspaces at https://console.chainguard.dev/workspaces/signup, or register with `chainctl auth login`)"
141    )]
142    AccountNotFound,
143
144    /// The identity belongs to no Chainguard organization.
145    #[error("workspaces: your identity belongs to no Chainguard organization")]
146    NoOrganization,
147
148    /// The identity belongs to several organizations; choose one explicitly.
149    #[error("{}", ambiguous_orgs(.organizations))]
150    AmbiguousOrganization { organizations: Vec<Organization> },
151
152    /// No organization was set and none could be detected. `detection` says why detection
153    /// didn't pick one.
154    #[error("{}", no_instance(.detection))]
155    NoInstance { detection: Option<String> },
156
157    /// A session reference matched more than one session.
158    #[error("workspaces: reference matches more than one session: {reference:?}")]
159    Ambiguous { reference: String },
160
161    /// A lower-level helper (`output`, `shell`, `write_file`) ran a command that exited non-zero
162    /// or timed out.
163    #[error("{}", exit_message(*.exit_code, *.timed_out, .stderr))]
164    Exit {
165        exit_code: i32,
166        timed_out: bool,
167        stdout: Vec<u8>,
168        stderr: Vec<u8>,
169    },
170
171    /// Another client attached to the session and took it over during the first attach.
172    #[error("workspaces: another client took over the session")]
173    Detached,
174
175    /// A local file operation failed.
176    #[error("{context}: {source}")]
177    Io {
178        context: String,
179        source: Arc<std::io::Error>,
180    },
181
182    /// Anything else, described by its message.
183    #[error("{0}")]
184    Other(String),
185}
186
187impl Error {
188    /// The gRPC status code behind the error, looking through `Busy`, `NotEnabled`,
189    /// `OutcomeUnknown` and `GitHubAppNotInstalled` (like Go's `status.Code(err)`).
190    pub fn grpc_code(&self) -> Option<tonic::Code> {
191        match self {
192            Error::Rpc(s) => Some(s.code()),
193            Error::Busy { cause }
194            | Error::NotEnabled { cause }
195            | Error::GitHubAppNotInstalled { cause, .. } => cause.grpc_code(),
196            Error::OutcomeUnknown { cause: Some(c), .. } => c.grpc_code(),
197            _ => None,
198        }
199    }
200
201    /// The platform API's error, if this is (or wraps) one.
202    pub fn platform_error(&self) -> Option<&PlatformError> {
203        match self {
204            Error::Platform { error, .. } => Some(error),
205            Error::GitHubAppNotInstalled { cause, .. } | Error::NotEnabled { cause } => {
206                cause.platform_error()
207            }
208            _ => None,
209        }
210    }
211
212    /// The command result an error carries: a non-zero exit, a timeout, or the partial output
213    /// of a command whose outcome is unknown.
214    pub fn command_result(&self) -> Option<&CommandResult> {
215        match self {
216            Error::CommandExit(r) => Some(r),
217            Error::Timeout { result, .. } | Error::OutcomeUnknown { result, .. } => result.as_ref(),
218            _ => None,
219        }
220    }
221
222    pub(crate) fn other(msg: impl Into<String>) -> Error {
223        Error::Other(msg.into())
224    }
225
226    pub(crate) fn io(context: impl Into<String>, e: std::io::Error) -> Error {
227        Error::Io {
228            context: context.into(),
229            source: Arc::new(e),
230        }
231    }
232
233    pub(crate) fn transport(context: impl Into<String>, e: impl fmt::Display) -> Error {
234        Error::Transport {
235            context: context.into(),
236            message: e.to_string(),
237        }
238    }
239}
240
241impl From<tonic::Status> for Error {
242    fn from(s: tonic::Status) -> Self {
243        Error::Rpc(s)
244    }
245}
246
247fn command_exit_message(r: &CommandResult) -> String {
248    let msg = r.stderr.trim();
249    let msg = last_bytes(msg, 500);
250    if msg.is_empty() {
251        format!("sandbox: command exited with code {}", r.exit_code)
252    } else {
253        format!("sandbox: command exited with code {}: {msg}", r.exit_code)
254    }
255}
256
257/// The last `n` bytes of s, moved forward to a character boundary.
258fn last_bytes(s: &str, n: usize) -> &str {
259    if s.len() <= n {
260        return s;
261    }
262    let mut i = s.len() - n;
263    while !s.is_char_boundary(i) {
264        i += 1;
265    }
266    &s[i..]
267}
268
269fn timeout_message(op: &str, detail: &str) -> String {
270    if detail.is_empty() {
271        format!("sandbox: {op} timed out")
272    } else {
273        format!("sandbox: timeout: {detail}")
274    }
275}
276
277fn cause_suffix(c: &Option<Box<Error>>) -> String {
278    c.as_ref().map(|c| format!(": {c}")).unwrap_or_default()
279}
280
281fn detail_suffix(d: &Option<String>) -> String {
282    d.as_ref().map(|d| format!(": {d}")).unwrap_or_default()
283}
284
285fn terms_list(docs: &[TermsDocument]) -> String {
286    docs.iter()
287        .map(|d| format!("{} ({})", d.label, d.url))
288        .collect::<Vec<_>>()
289        .join("; ")
290}
291
292fn ambiguous_orgs(orgs: &[Organization]) -> String {
293    let mut s = format!(
294        "workspaces: you belong to several organizations; choose one with the instance option or ${}:",
295        crate::workspaces::ENV_INSTANCE
296    );
297    for o in orgs {
298        s.push_str(&format!("\n  {}  {}", o.id, o.name));
299    }
300    s
301}
302
303fn no_instance(detection: &Option<String>) -> String {
304    let mut msg = format!(
305        "workspaces: no organization configured. Set one of:\n  \
306         - the instance option (Go: Options.Instance, Python: instance=, TypeScript: instance) to the organization ID\n  \
307         - ${}=<organization ID>\n  \
308         - or let it be auto-detected when you belong to exactly one organization\n\
309         List your organization IDs with `chainguard-sandbox orgs` or `chainctl iam organizations list`.",
310        crate::workspaces::ENV_INSTANCE
311    );
312    if let Some(d) = detection {
313        msg.push_str("\nAuto-detection: ");
314        msg.push_str(d);
315    }
316    msg
317}
318
319fn exit_message(code: i32, timed_out: bool, stderr: &[u8]) -> String {
320    let msg = String::from_utf8_lossy(stderr);
321    let msg = msg.trim();
322    if timed_out {
323        format!("command timed out: {msg}")
324    } else {
325        format!("command exited {code}: {msg}")
326    }
327}
328
329/// The gRPC code's name as Go prints it ("Unavailable", "NotFound", ...).
330pub(crate) fn code_name(c: tonic::Code) -> &'static str {
331    use tonic::Code::*;
332    match c {
333        Ok => "OK",
334        Cancelled => "Canceled",
335        Unknown => "Unknown",
336        InvalidArgument => "InvalidArgument",
337        DeadlineExceeded => "DeadlineExceeded",
338        NotFound => "NotFound",
339        AlreadyExists => "AlreadyExists",
340        PermissionDenied => "PermissionDenied",
341        ResourceExhausted => "ResourceExhausted",
342        FailedPrecondition => "FailedPrecondition",
343        Aborted => "Aborted",
344        OutOfRange => "OutOfRange",
345        Unimplemented => "Unimplemented",
346        Internal => "Internal",
347        Unavailable => "Unavailable",
348        DataLoss => "DataLoss",
349        Unauthenticated => "Unauthenticated",
350    }
351}
352
353#[cfg(test)]
354mod tests {
355    use super::*;
356
357    #[test]
358    fn command_exit_message_keeps_the_last_500_bytes_on_a_boundary() {
359        let long = format!("{}€end", "x".repeat(600));
360        let e = Error::CommandExit(CommandResult {
361            exit_code: 2,
362            stdout: String::new(),
363            stderr: long,
364        });
365        let m = e.to_string();
366        assert!(m.starts_with("sandbox: command exited with code 2: "));
367        assert!(m.ends_with("€end"));
368        let e = Error::CommandExit(CommandResult {
369            exit_code: 3,
370            stdout: String::new(),
371            stderr: " \n".into(),
372        });
373        assert_eq!(e.to_string(), "sandbox: command exited with code 3");
374    }
375
376    #[test]
377    fn grpc_code_looks_through_wrappers() {
378        let e = Error::OutcomeUnknown {
379            cause: Some(Box::new(Error::Rpc(tonic::Status::unavailable("x")))),
380            result: None,
381        };
382        assert_eq!(e.grpc_code(), Some(tonic::Code::Unavailable));
383        assert!(
384            e.to_string()
385                .contains("rpc error: code = Unavailable desc = x")
386        );
387    }
388}