Skip to main content

chainguard_sandbox/workspaces/
setup.rs

1//! Turning Workspaces on for an organization.
2//!
3//! Sessions can be created only in an organization that is entitled to Workspaces.
4//! `chainctl develop init` gets an organization there in these steps, each a call to Chainguard's
5//! platform API ([`DEFAULT_PLATFORM_URL`](super::DEFAULT_PLATFORM_URL)):
6//!
7//! 1. Find out which legal documents the organization has accepted:
8//!    `GET /iam/v1/terms/{org}` ([`accepted_terms`])
9//! 2. Accept the ones turning it on needs ([`ENABLE_TERMS`]):
10//!    `POST /iam/v1/terms/{org}` ([`accept_terms`])
11//! 3. Link a GitHub account (an organization, or your own user) to the organization. The service
12//!    refuses step 4 without it. The Chainguard GitHub App must be installed on that account
13//!    ([`GITHUB_APP_INSTALL_URL`]).
14//!    `GET /guardener/v1alpha1/githubAssociations/{org}` ([`linked_github_organizations`]),
15//!    `GET /guardener/v1alpha1/githubAssociations:begin` ([`begin_github_oauth`]),
16//!    GitHub's authorize page, back to a loopback port ([`authorize_github`]),
17//!    `POST /guardener/v1alpha1/githubAssociations/{org}:link` ([`link_github_organization`])
18//! 4. Turn the feature on, with the plan's allowance:
19//!    `POST /entitlements/v1alpha1/features/{org}:enableSandbox` ([`enable_sandbox`])
20//! 5. Read the result: `GET /entitlements/v2beta1/organizationEntitlements?parent={org}`
21//!    ([`workspaces_entitlement`])
22//!
23//! Creating the organization itself (sign-up) is not covered: use the Chainguard Console.
24//!
25//! All of these need a token for the platform API ([`platform_token_source`]), and steps 2 to 4
26//! need the owner role in the organization. Step 3 also needs you to own the GitHub account.
27
28use std::sync::{Arc, Mutex};
29
30use base64::Engine as _;
31use sha2::Digest as _;
32use tokio::sync::oneshot;
33
34use super::auth::SharedTokenSource;
35use super::http;
36use super::login::{MessageSink, UrlOpener, open_browser, say};
37use super::loopback::{LoopbackReply, LoopbackServer};
38use super::orgs::{platform_token_source, platform_url};
39use crate::{Error, Result};
40
41crate::opaque_debug!(GitHubAuthorizeOptions);
42
43/// A legal document an organization accepts.
44#[derive(Debug, Clone, PartialEq, Eq, Default)]
45pub struct TermsDocument {
46    pub id: String,
47    pub label: String,
48    pub url: String,
49}
50
51/// The documents an organization must accept to use Workspaces: the Secured Platform Terms and
52/// the Master Service and License Agreement.
53pub const WORKSPACES_TERMS: &[&str] = &["secure-platform-terms.v1", "msla.v1"];
54
55/// The documents an organization accepts when Workspaces is turned on the way
56/// `chainctl develop init` does it: the Workspaces terms, the Code Analysis Terms (the same switch
57/// turns on Chainguard Checks), and the Terms of Service and Data Privacy Agreement that linking
58/// a GitHub account requires.
59pub const ENABLE_TERMS: &[&str] = &[
60    "secure-platform-terms.v1",
61    "msla.v1",
62    "code-analysis-terms.v1",
63    "guardener-tos.v1",
64    "sfdpa.v1",
65];
66
67/// Where the Chainguard GitHub App is installed on a GitHub organization or user.
68pub const GITHUB_APP_INSTALL_URL: &str = "https://github.com/apps/chainguard/installations/new";
69
70/// The loopback port the GitHub authorization redirects to (the one chainctl uses).
71pub const DEFAULT_GITHUB_OAUTH_PORT: u16 = 8989;
72
73/// The label and URL of a known document ID, or a document with only the ID set.
74pub fn terms_document_info(id: &str) -> TermsDocument {
75    let known = |label: &str, url: &str| TermsDocument {
76        id: id.into(),
77        label: label.into(),
78        url: url.into(),
79    };
80    match id {
81        "secure-platform-terms.v1" => known(
82            "Secured Platform Terms",
83            "https://www.chainguard.dev/legal/secure-platform-terms",
84        ),
85        "msla.v1" => known(
86            "Master Service and License Agreement",
87            "https://www.chainguard.dev/legal/master-service-and-license-agreement",
88        ),
89        "code-analysis-terms.v1" => known(
90            "Code Analysis Terms",
91            "https://www.chainguard.dev/legal/code-analysis-terms",
92        ),
93        "guardener-tos.v1" => known(
94            "Terms of Service",
95            "https://www.chainguard.dev/legal/guardener",
96        ),
97        "sfdpa.v1" => known(
98            "Data Privacy Agreement",
99            "https://www.chainguard.dev/legal/supplemental-dpa",
100        ),
101        _ => TermsDocument {
102            id: id.into(),
103            ..Default::default()
104        },
105    }
106}
107
108/// A non-2xx answer from the platform API.
109#[derive(Debug, Clone, Default)]
110pub struct PlatformError {
111    /// The response status.
112    pub http_status: u16,
113    /// The gRPC status code the gateway reports (7 = permission denied, 9 = failed precondition).
114    pub code: i64,
115    pub message: String,
116    /// The machine-readable reason, when the service gives one.
117    pub reason: String,
118    /// Set when the call was refused because the organization has not accepted these documents.
119    pub missing_terms: Vec<TermsDocument>,
120}
121
122impl PlatformError {
123    /// The organization has to link a GitHub account first.
124    pub fn github_link_required(&self) -> bool {
125        self.reason == "GUARDENER_GITHUB_LINK_REQUIRED"
126            || self.message.contains("must link a GitHub organization")
127    }
128    /// The Chainguard GitHub App is not installed on the GitHub account.
129    pub fn github_app_not_installed(&self) -> bool {
130        self.reason.ends_with("GITHUB_APP_NOT_INSTALLED")
131            || self.message.contains("must be installed on the GitHub")
132    }
133    /// The GitHub account is linked to another Chainguard organization.
134    pub fn github_already_linked(&self) -> bool {
135        self.reason == "GUARDENER_GITHUB_ALREADY_LINKED"
136            || self.message.contains("already linked to a different")
137    }
138}
139
140impl std::fmt::Display for PlatformError {
141    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
142        write!(
143            f,
144            "platform API: HTTP {}: {}",
145            self.http_status, self.message
146        )
147    }
148}
149
150impl std::error::Error for PlatformError {}
151
152/// Sends one JSON request to the platform API and returns the decoded answer. `context` prefixes
153/// errors ("listing accepted terms: platform API: HTTP 403: ...").
154async fn platform_call(
155    ts: &Option<SharedTokenSource>,
156    method: reqwest::Method,
157    path: &str,
158    body: Option<serde_json::Value>,
159    context: &str,
160) -> Result<serde_json::Value> {
161    let ts = ts.clone().unwrap_or_else(platform_token_source);
162    let tok = ts.token().await?;
163    let url = format!("{}{}", platform_url().trim_end_matches('/'), path);
164    let mut req = http::client()?
165        .request(method, url)
166        .header("Authorization", format!("Bearer {tok}"))
167        .header("Accept", "application/json");
168    if let Some(b) = &body {
169        req = req
170            .header("Content-Type", "application/json")
171            .body(b.to_string());
172    }
173    let a = http::send(req, 4 << 20, context).await?;
174    if a.status == 401 {
175        ts.invalidate();
176    }
177    if a.status / 100 != 2 {
178        return Err(Error::Platform {
179            context: context.into(),
180            error: parse_platform_error(a.status, &a.body),
181        });
182    }
183    if a.body.is_empty() {
184        return Ok(serde_json::Value::Null);
185    }
186    serde_json::from_slice(&a.body).map_err(|e| Error::other(format!("{context}: {e}")))
187}
188
189pub(crate) fn parse_platform_error(status: u16, data: &[u8]) -> PlatformError {
190    let v: serde_json::Value = serde_json::from_slice(data).unwrap_or_default();
191    let mut e = PlatformError {
192        http_status: status,
193        code: v.get("code").and_then(|c| c.as_i64()).unwrap_or(0),
194        message: v
195            .get("message")
196            .and_then(|m| m.as_str())
197            .unwrap_or_default()
198            .to_string(),
199        ..Default::default()
200    };
201    if e.message.is_empty() {
202        e.message = String::from_utf8_lossy(data).trim().to_string();
203    }
204    // A refusal for unaccepted terms carries a detail listing the missing documents.
205    for d in v
206        .get("details")
207        .and_then(|d| d.as_array())
208        .into_iter()
209        .flatten()
210    {
211        if let Some(r) = d.get("reason").and_then(|r| r.as_str())
212            && !r.is_empty()
213            && e.reason.is_empty()
214        {
215            e.reason = r.to_string();
216        }
217        for m in d
218            .get("missing")
219            .and_then(|m| m.as_array())
220            .into_iter()
221            .flatten()
222        {
223            let field = |k: &str| {
224                m.get(k)
225                    .or_else(|| m.get(k.to_uppercase()))
226                    .or_else(|| m.get(format!("{}{}", &k[..1].to_uppercase(), &k[1..])))
227                    .and_then(|x| x.as_str())
228                    .unwrap_or_default()
229                    .to_string()
230            };
231            let mut doc = terms_document_info(&field("id"));
232            let (label, url) = (field("label"), field("url"));
233            if !label.is_empty() {
234                doc.label = label;
235            }
236            if !url.is_empty() {
237                doc.url = url;
238            }
239            e.missing_terms.push(doc);
240        }
241    }
242    e
243}
244
245fn org_path(org: &str) -> Result<String> {
246    if org.is_empty() || org.contains('?') || org.contains('#') {
247        return Err(Error::other(format!(
248            "workspaces: invalid organization ID {org:?}"
249        )));
250    }
251    Ok(http::path_escape(org))
252}
253
254/// The IDs of the legal documents the organization has accepted. `ts` must mint platform tokens
255/// (`None`: [`platform_token_source`]).
256pub async fn accepted_terms(ts: Option<SharedTokenSource>, org: &str) -> Result<Vec<String>> {
257    let p = org_path(org)?;
258    let out = platform_call(
259        &ts,
260        reqwest::Method::GET,
261        &format!("/iam/v1/terms/{p}"),
262        None,
263        "listing accepted terms",
264    )
265    .await?;
266    Ok(out
267        .get("items")
268        .and_then(|i| i.as_array())
269        .into_iter()
270        .flatten()
271        .filter_map(|it| it.get("docId").and_then(|d| d.as_str()).map(String::from))
272        .collect())
273}
274
275/// The documents Workspaces needs that the organization has not accepted yet.
276pub async fn missing_workspaces_terms(
277    ts: Option<SharedTokenSource>,
278    org: &str,
279) -> Result<Vec<TermsDocument>> {
280    let have = accepted_terms(ts, org).await?;
281    Ok(WORKSPACES_TERMS
282        .iter()
283        .filter(|id| !have.iter().any(|h| h == *id))
284        .map(|id| terms_document_info(id))
285        .collect())
286}
287
288/// Records that the organization accepts the documents with these IDs. This is a legal act on the
289/// organization's behalf: call it only when the person running your program has agreed to the
290/// documents. It needs the owner role; accepting a document again changes nothing.
291pub async fn accept_terms(
292    ts: Option<SharedTokenSource>,
293    org: &str,
294    document_ids: &[String],
295) -> Result<()> {
296    let p = org_path(org)?;
297    if document_ids.is_empty() {
298        return Err(Error::other("workspaces: no documents to accept"));
299    }
300    let body = serde_json::json!({ "documentIds": document_ids });
301    platform_call(
302        &ts,
303        reqwest::Method::POST,
304        &format!("/iam/v1/terms/{p}"),
305        Some(body),
306        "accepting terms",
307    )
308    .await?;
309    Ok(())
310}
311
312/// Turns on Checks and Workspaces for the organization, with its plan's monthly allowance. An
313/// allowance Chainguard already granted is kept. It needs the owner role, and the organization
314/// must have accepted the terms first: otherwise the error's [`PlatformError::missing_terms`]
315/// lists the documents.
316pub async fn enable_sandbox(ts: Option<SharedTokenSource>, org: &str) -> Result<()> {
317    let p = org_path(org)?;
318    let path = format!("/entitlements/v1alpha1/features/{p}:enableSandbox");
319    platform_call(
320        &ts,
321        reqwest::Method::POST,
322        &path,
323        Some(serde_json::json!({})),
324        "turning on Workspaces",
325    )
326    .await?;
327    Ok(())
328}
329
330/// An organization's Workspaces entitlement.
331#[derive(Debug, Clone, Default)]
332pub struct Entitlement {
333    /// The plan's ID ("starter", "team", ...).
334    pub plan: String,
335    /// The plan's display name.
336    pub plan_name: String,
337    /// Whether Workspaces is turned on.
338    pub active: bool,
339    /// The raw state ("STATE_ACTIVE", "STATE_NOT_INCLUDED", or "" when the product isn't listed).
340    pub state: String,
341    /// The concurrent-session limits (0: not reported).
342    pub max_sandboxes: i64,
343    pub max_sandboxes_per_user: i64,
344}
345
346/// Whether Workspaces is turned on for the organization, its plan, and its session limits.
347pub async fn workspaces_entitlement(
348    ts: Option<SharedTokenSource>,
349    org: &str,
350) -> Result<Entitlement> {
351    org_path(org)?;
352    let q = http::query(&[("parent", org), ("products", "PRODUCT_SANDBOX_WORKSPACES")]);
353    let out = platform_call(
354        &ts,
355        reqwest::Method::GET,
356        &format!("/entitlements/v2beta1/organizationEntitlements?{q}"),
357        None,
358        "reading the organization's entitlements",
359    )
360    .await?;
361    let s = |v: &serde_json::Value, k: &str| {
362        v.get(k)
363            .and_then(|x| x.as_str())
364            .unwrap_or_default()
365            .to_string()
366    };
367    let plan = out.get("plan").cloned().unwrap_or_default();
368    let mut e = Entitlement {
369        plan: s(&plan, "id"),
370        plan_name: s(&plan, "displayName"),
371        ..Default::default()
372    };
373    for p in out
374        .get("products")
375        .and_then(|p| p.as_array())
376        .into_iter()
377        .flatten()
378    {
379        if s(p, "product") != "PRODUCT_SANDBOX_WORKSPACES" {
380            continue;
381        }
382        e.state = s(p, "state");
383        e.active = e.state == "STATE_ACTIVE";
384        for l in p
385            .get("limits")
386            .and_then(|l| l.as_array())
387            .into_iter()
388            .flatten()
389        {
390            let n: i64 = match l.get("max") {
391                Some(serde_json::Value::String(m)) => m.trim().parse().unwrap_or(0),
392                Some(serde_json::Value::Number(m)) => m.as_i64().unwrap_or(0),
393                _ => 0,
394            };
395            match s(l, "displayName").as_str() {
396                "concurrent workspaces" => e.max_sandboxes = n,
397                "concurrent workspaces per user" => e.max_sandboxes_per_user = n,
398                _ => {}
399            }
400        }
401    }
402    Ok(e)
403}
404
405/// A GitHub account linked to a Chainguard organization.
406#[derive(Debug, Clone, PartialEq, Eq)]
407pub struct LinkedGitHub {
408    /// The GitHub login: an organization, or a user.
409    pub organization: String,
410}
411
412/// The GitHub accounts linked to the organization.
413pub async fn linked_github_organizations(
414    ts: Option<SharedTokenSource>,
415    org: &str,
416) -> Result<Vec<LinkedGitHub>> {
417    let p = org_path(org)?;
418    let out = platform_call(
419        &ts,
420        reqwest::Method::GET,
421        &format!("/guardener/v1alpha1/githubAssociations/{p}"),
422        None,
423        "listing linked GitHub accounts",
424    )
425    .await?;
426    Ok(out
427        .get("organizations")
428        .and_then(|o| o.as_array())
429        .into_iter()
430        .flatten()
431        .map(|o| LinkedGitHub {
432            organization: o
433                .get("organization")
434                .and_then(|x| x.as_str())
435                .unwrap_or_default()
436                .to_string(),
437        })
438        .collect())
439}
440
441/// What the service hands out to start a GitHub authorization: the Chainguard GitHub App's OAuth
442/// client ID, and a state value the service signed and checks again when the account is linked.
443#[derive(Debug, Clone)]
444pub struct GitHubOAuthStart {
445    pub client_id: String,
446    pub state: String,
447}
448
449/// Starts a GitHub authorization.
450pub async fn begin_github_oauth(ts: Option<SharedTokenSource>) -> Result<GitHubOAuthStart> {
451    let ctx = "starting the GitHub authorization";
452    let out = platform_call(
453        &ts,
454        reqwest::Method::GET,
455        "/guardener/v1alpha1/githubAssociations:begin",
456        None,
457        ctx,
458    )
459    .await?;
460    let s = |k: &str| {
461        out.get(k)
462            .and_then(|x| x.as_str())
463            .unwrap_or_default()
464            .to_string()
465    };
466    let (client_id, state) = (s("clientId"), s("state"));
467    if client_id.is_empty() || state.is_empty() {
468        return Err(Error::other(format!(
469            "{ctx}: the service returned no client ID or state"
470        )));
471    }
472    Ok(GitHubOAuthStart { client_id, state })
473}
474
475/// The result of [`authorize_github`]. It holds no GitHub token: the service exchanges the code
476/// itself when the account is linked.
477#[derive(Clone)]
478pub struct GitHubAuthorization {
479    pub code: String,
480    pub redirect_uri: String,
481    pub verifier: String,
482    pub state: String,
483}
484
485impl std::fmt::Debug for GitHubAuthorization {
486    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
487        f.debug_struct("GitHubAuthorization")
488            .field("redirect_uri", &self.redirect_uri)
489            .finish_non_exhaustive()
490    }
491}
492
493/// Configures [`authorize_github`].
494#[derive(Clone, Default)]
495pub struct GitHubAuthorizeOptions {
496    /// The loopback port to receive GitHub's redirect on (0: [`DEFAULT_GITHUB_OAUTH_PORT`]).
497    pub port: u16,
498    /// Print the URL instead of opening a browser.
499    pub no_browser: bool,
500    /// Opens the authorization page; returns false if it couldn't (the URL is then printed).
501    /// Defaults to [`open_browser`].
502    pub open_url: Option<UrlOpener>,
503    /// Receives the instructions (default stderr).
504    pub out: Option<MessageSink>,
505}
506
507/// Sends the person to GitHub to authorize the Chainguard GitHub App and waits for GitHub's
508/// redirect to a loopback port. It is the flow chainctl uses: PKCE with S256, the account picker
509/// forced, and the state checked on return. Bound it with `tokio::time::timeout`.
510pub async fn authorize_github(
511    start: &GitHubOAuthStart,
512    o: GitHubAuthorizeOptions,
513) -> Result<GitHubAuthorization> {
514    let port = if o.port == 0 {
515        DEFAULT_GITHUB_OAUTH_PORT
516    } else {
517        o.port
518    };
519    let redirect = format!("http://127.0.0.1:{port}/callback");
520    let mut raw = [0u8; 32];
521    getrandom::fill(&mut raw).map_err(|e| Error::other(e.to_string()))?;
522    let verifier = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(raw);
523    let challenge = base64::engine::general_purpose::URL_SAFE_NO_PAD
524        .encode(sha2::Sha256::digest(verifier.as_bytes()));
525    let auth_url = format!(
526        "https://github.com/login/oauth/authorize?{}",
527        http::query(&[
528            ("client_id", &start.client_id),
529            ("redirect_uri", &redirect),
530            ("response_type", "code"),
531            ("state", &start.state),
532            ("code_challenge", &challenge),
533            ("code_challenge_method", "S256"),
534            ("prompt", "select_account"),
535            ("allow_signup", "false"),
536        ])
537    );
538
539    let (tx, rx) = oneshot::channel::<Result<String>>();
540    let tx = Arc::new(Mutex::new(Some(tx)));
541    let want_state = start.state.clone();
542    let server = LoopbackServer::bind(port, move |req| {
543        if req.path != "/callback" {
544            return LoopbackReply::text(404, &[], "404 page not found");
545        }
546        let q = |k: &str| req.query.get(k).cloned().unwrap_or_default();
547        // "Connection: close" (always sent): the browser must not keep this connection for a
548        // later attempt, which gets a new server on the same port.
549        let (reply, res) = if !q("error").is_empty() {
550            (
551                LoopbackReply::text(400, &[], "Authorization was denied. You can close this window."),
552                Err(Error::other(format!("GitHub refused the authorization: {}: {}", q("error"), q("error_description")))),
553            )
554        } else if q("state") != want_state {
555            (
556                LoopbackReply::text(400, &[], "Authorization state mismatch. You can close this window."),
557                Err(Error::other("GitHub's redirect carried the wrong state")),
558            )
559        } else if q("code").is_empty() {
560            (
561                LoopbackReply::text(400, &[], "Missing authorization code. You can close this window."),
562                Err(Error::other("GitHub's redirect carried no authorization code")),
563            )
564        } else {
565            (LoopbackReply::text(200, &[], "Authorization complete. You can close this window and return to the terminal.\n"), Ok(q("code")))
566        };
567        if let Some(tx) = tx.lock().unwrap().take() {
568            let _ = tx.send(res);
569        }
570        reply
571    })
572    .await
573    .map_err(|e| {
574        Error::io(format!("listening on loopback port {port} for GitHub's redirect (choose another port if it is taken)"), e)
575    })?;
576
577    let opened = !o.no_browser
578        && match &o.open_url {
579            Some(f) => f(&auth_url),
580            None => open_browser(&auth_url),
581        };
582    if opened {
583        say(
584            &o.out,
585            &format!(
586                "Opened a browser to authorize with GitHub. If it didn't open, visit:\n  {auth_url}"
587            ),
588        );
589    } else {
590        say(
591            &o.out,
592            &format!("Open this URL in a browser to authorize with GitHub:\n  {auth_url}"),
593        );
594    }
595    let res = rx.await.unwrap_or_else(|_| {
596        Err(Error::other(
597            "waiting for the GitHub authorization: the server stopped",
598        ))
599    });
600    // Let the browser finish loading the result page.
601    tokio::time::sleep(std::time::Duration::from_millis(100)).await;
602    server.stop();
603    let code = res?;
604    Ok(GitHubAuthorization {
605        code,
606        redirect_uri: redirect,
607        verifier,
608        state: start.state.clone(),
609    })
610}
611
612/// Links a GitHub account to the Chainguard organization, using an authorization from
613/// [`authorize_github`]. `github_login` is the account to link, an organization or a user; empty
614/// means the GitHub user who authorized. The Chainguard GitHub App must be installed on the
615/// account (otherwise [`PlatformError::github_app_not_installed`]), and you must own it. An
616/// account can be linked to one Chainguard organization at a time.
617pub async fn link_github_organization(
618    ts: Option<SharedTokenSource>,
619    org: &str,
620    github_login: &str,
621    a: &GitHubAuthorization,
622) -> Result<LinkedGitHub> {
623    let p = org_path(org)?;
624    let mut body = serde_json::json!({ "code": a.code, "redirectUri": a.redirect_uri, "codeVerifier": a.verifier, "state": a.state });
625    if !github_login.is_empty() {
626        body["organization"] = serde_json::Value::String(github_login.into());
627    }
628    let path = format!("/guardener/v1alpha1/githubAssociations/{p}:link");
629    let out = platform_call(
630        &ts,
631        reqwest::Method::POST,
632        &path,
633        Some(body),
634        "linking the GitHub account",
635    )
636    .await?;
637    Ok(LinkedGitHub {
638        organization: out
639            .get("organization")
640            .and_then(|x| x.as_str())
641            .unwrap_or_default()
642            .to_string(),
643    })
644}