1use std::fmt;
19use std::sync::Arc;
20
21use crate::commands::CommandResult;
22use crate::workspaces::{Organization, PlatformError, TermsDocument};
23
24pub type Result<T, E = Error> = std::result::Result<T, E>;
26
27#[derive(Debug, Clone, thiserror::Error)]
30#[non_exhaustive]
31pub enum Error {
32 #[error("{}", command_exit_message(.0))]
35 CommandExit(CommandResult),
36
37 #[error("sandbox: {what} not found: {name}")]
40 NotFound { what: String, name: String },
41
42 #[error("sandbox: {path}: {reason}")]
44 InvalidPath { path: String, reason: String },
45
46 #[error("{}", timeout_message(.op, .detail))]
49 Timeout {
50 op: String,
51 detail: String,
52 result: Option<CommandResult>,
53 },
54
55 #[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 #[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 #[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 #[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 #[error("sandbox: the organization has not accepted the terms Workspaces is offered under: {}", terms_list(.missing))]
87 TermsNotAccepted { missing: Vec<TermsDocument> },
88
89 #[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 #[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 #[error("rpc error: code = {} desc = {}", code_name(.0.code()), .0.message())]
109 Rpc(tonic::Status),
110
111 #[error("{context}: {error}")]
113 Platform {
114 context: String,
115 error: PlatformError,
116 },
117
118 #[error("{context}: HTTP {status}: {message}")]
120 Http {
121 context: String,
122 status: u16,
123 message: String,
124 },
125
126 #[error("{context}: {message}")]
128 Transport { context: String, message: String },
129
130 #[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 #[error("workspaces: the saved login has expired or was revoked: {detail}")]
136 LoginExpired { detail: String },
137
138 #[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 #[error("workspaces: your identity belongs to no Chainguard organization")]
146 NoOrganization,
147
148 #[error("{}", ambiguous_orgs(.organizations))]
150 AmbiguousOrganization { organizations: Vec<Organization> },
151
152 #[error("{}", no_instance(.detection))]
155 NoInstance { detection: Option<String> },
156
157 #[error("workspaces: reference matches more than one session: {reference:?}")]
159 Ambiguous { reference: String },
160
161 #[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 #[error("workspaces: another client took over the session")]
173 Detached,
174
175 #[error("{context}: {source}")]
177 Io {
178 context: String,
179 source: Arc<std::io::Error>,
180 },
181
182 #[error("{0}")]
184 Other(String),
185}
186
187impl Error {
188 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 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 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
257fn 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
329pub(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}