Skip to main content

chainguard_sandbox/
setup.rs

1//! Turning Workspaces on for an organization.
2//!
3//! Workspaces has to be turned on for an organization before sandboxes can be created in it.
4//! [`workspaces_status`] reports whether it is, and [`enable_workspaces`] turns it on: the same
5//! steps `chainctl develop init --parent ORG` takes for an organization that already exists
6//! (accept the terms, link a GitHub account, then turn the feature on).
7
8use std::time::Duration;
9
10use crate::workspaces::{self, MessageSink, SharedTokenSource, TermsDocument, UrlOpener};
11use crate::{Error, Result};
12
13crate::opaque_debug!(SetupOptions);
14
15/// Selects the organization for [`workspaces_status`] and [`enable_workspaces`].
16#[derive(Clone, Default)]
17pub struct SetupOptions {
18    /// The organization ID. If empty, `$CHAINCTL_SANDBOX_INSTANCE` is used, and failing that the
19    /// only organization you belong to.
20    pub instance: String,
21    /// Mints tokens for the platform API (default: the saved login).
22    pub token_source: Option<SharedTokenSource>,
23    /// Lets [`enable_workspaces`] accept, on the organization's behalf, the legal documents it has
24    /// not accepted yet. Set it only when the person running your program has read and agreed to
25    /// them ([`workspaces_status`] lists them, with URLs). Status ignores it.
26    pub accept_terms: bool,
27    /// The GitHub organization or user to link when the organization has none linked (enable
28    /// only). Empty means the GitHub user who authorizes in the browser.
29    pub github_account: String,
30    /// The loopback port for GitHub's redirect (0: 8989).
31    pub github_port: u16,
32    /// Stops enabling from opening a browser for the GitHub authorization; it then fails with
33    /// [`Error::GitHubLinkRequired`] if a link is needed.
34    pub no_browser: bool,
35    /// Receives instructions during the GitHub authorization (default stderr).
36    pub out: Option<MessageSink>,
37    /// Opens GitHub's authorization page (default: the system browser).
38    pub open_url: Option<UrlOpener>,
39}
40
41/// An organization's Workspaces setup.
42#[derive(Debug, Clone, Default)]
43pub struct WorkspacesStatus {
44    /// The organization ID the status is for.
45    pub organization: String,
46    /// Whether Workspaces is turned on. Sandboxes can be created when it is and `missing_terms`
47    /// is empty.
48    pub enabled: bool,
49    /// The required legal documents not accepted yet. While Workspaces is off these are all the
50    /// documents turning it on needs.
51    pub missing_terms: Vec<TermsDocument>,
52    /// The GitHub organizations or users linked to the organization. Turning Workspaces on needs
53    /// at least one.
54    pub github_accounts: Vec<String>,
55    /// The organization's plan ("Starter", ...).
56    pub plan: String,
57    /// The plan's limits on sandboxes existing at once (0: not reported).
58    pub max_sandboxes: i64,
59    pub max_sandboxes_per_user: i64,
60}
61
62impl WorkspacesStatus {
63    /// Whether sandboxes can be created.
64    pub fn ready(&self) -> bool {
65        self.enabled && self.missing_terms.is_empty()
66    }
67}
68
69async fn setup_org(o: &SetupOptions) -> Result<String> {
70    if !o.instance.is_empty() {
71        return Ok(o.instance.clone());
72    }
73    if let Ok(v) = std::env::var(workspaces::ENV_INSTANCE)
74        && !v.is_empty()
75    {
76        return Ok(v);
77    }
78    workspaces::detect_instance(o.token_source.clone()).await
79}
80
81/// Whether Workspaces is turned on for the organization and which required terms it still has to
82/// accept. It changes nothing.
83pub async fn workspaces_status(o: &SetupOptions) -> Result<WorkspacesStatus> {
84    let org = setup_org(o).await?;
85    let ts = o.token_source.clone();
86    let ent = workspaces::workspaces_entitlement(ts.clone(), &org).await?;
87    let mut st = WorkspacesStatus {
88        organization: org.clone(),
89        enabled: ent.active,
90        plan: ent.plan_name,
91        max_sandboxes: ent.max_sandboxes,
92        max_sandboxes_per_user: ent.max_sandboxes_per_user,
93        ..Default::default()
94    };
95    // Once Workspaces is on, only its own terms matter. While it is off, list everything turning
96    // it on will need, so it can all be agreed to up front.
97    let required = if ent.active {
98        workspaces::WORKSPACES_TERMS
99    } else {
100        workspaces::ENABLE_TERMS
101    };
102    let have = workspaces::accepted_terms(ts.clone(), &org).await?;
103    st.missing_terms = required
104        .iter()
105        .filter(|id| !have.iter().any(|h| h == *id))
106        .map(|id| workspaces::terms_document_info(id))
107        .collect();
108    // A member who may not list the links still gets the rest of the status.
109    if let Ok(linked) = workspaces::linked_github_organizations(ts, &org).await {
110        st.github_accounts = linked.into_iter().map(|l| l.organization).collect();
111    }
112    Ok(st)
113}
114
115/// Turns Workspaces on for the organization, so sandboxes can be created in it. It is what
116/// `chainctl develop init --parent ORG` does for an existing organization, without chainctl. It
117/// needs the owner role, and does nothing if everything is already in place. The steps:
118///
119/// 1. Accept the terms. Only with `accept_terms`; without it, an organization with unaccepted
120///    terms gets [`Error::TermsNotAccepted`] listing them.
121/// 2. Link a GitHub account, if the organization has none: the service requires one. This opens a
122///    browser on GitHub, where you choose the account, and waits for you to finish (up to 10
123///    minutes). The Chainguard GitHub App must be installed on the account; if it is not, the
124///    error is [`Error::GitHubAppNotInstalled`] with the page to install it from.
125/// 3. Turn the feature on with the plan's allowance. This also turns on Chainguard Checks, which
126///    the same switch controls.
127pub async fn enable_workspaces(o: &SetupOptions) -> Result<WorkspacesStatus> {
128    let st = workspaces_status(o).await?;
129    if st.ready() {
130        return Ok(st);
131    }
132    let ts = o.token_source.clone();
133    let accept = async |docs: &[TermsDocument]| -> Result<()> {
134        if !o.accept_terms {
135            return Err(Error::TermsNotAccepted {
136                missing: docs.to_vec(),
137            });
138        }
139        let ids: Vec<String> = docs.iter().map(|d| d.id.clone()).collect();
140        workspaces::accept_terms(ts.clone(), &st.organization, &ids).await
141    };
142    if !st.missing_terms.is_empty() {
143        accept(&st.missing_terms).await?;
144    }
145    if !st.enabled && st.github_accounts.is_empty() {
146        link_github(o, &st.organization).await?;
147    }
148    if !st.enabled {
149        let mut r = workspaces::enable_sandbox(ts.clone(), &st.organization).await;
150        // The link could not be listed (or was removed meanwhile): make it now.
151        if let Err(e) = &r
152            && e.platform_error().is_some_and(|p| p.github_link_required())
153            && !st.github_accounts.is_empty()
154        {
155            r = match link_github(o, &st.organization).await {
156                Ok(()) => workspaces::enable_sandbox(ts.clone(), &st.organization).await,
157                Err(e) => Err(e),
158            };
159        }
160        // The switch also covers Checks, whose terms the service may ask for too.
161        if let Err(e) = &r
162            && let Some(missing) = e
163                .platform_error()
164                .map(|p| p.missing_terms.clone())
165                .filter(|m| !m.is_empty())
166        {
167            r = match accept(&missing).await {
168                Ok(()) => workspaces::enable_sandbox(ts.clone(), &st.organization).await,
169                Err(e) => Err(e),
170            };
171        }
172        r?;
173    }
174    workspaces_status(o).await
175}
176
177/// Links a GitHub account to the organization: start the authorization, send the person to
178/// GitHub, and hand the result to the service.
179async fn link_github(o: &SetupOptions, org: &str) -> Result<()> {
180    if o.no_browser {
181        return Err(Error::GitHubLinkRequired {
182            organization: org.into(),
183        });
184    }
185    let start = workspaces::begin_github_oauth(o.token_source.clone()).await?;
186    let ao = workspaces::GitHubAuthorizeOptions {
187        port: o.github_port,
188        out: o.out.clone(),
189        open_url: o.open_url.clone(),
190        no_browser: false,
191    };
192    let auth = tokio::time::timeout(
193        Duration::from_secs(600),
194        workspaces::authorize_github(&start, ao),
195    )
196    .await
197    .map_err(|_| {
198        Error::other("waiting for the GitHub authorization: no answer within 10 minutes")
199    })??;
200    match workspaces::link_github_organization(
201        o.token_source.clone(),
202        org,
203        &o.github_account,
204        &auth,
205    )
206    .await
207    {
208        Err(e)
209            if e.platform_error()
210                .is_some_and(|p| p.github_app_not_installed()) =>
211        {
212            Err(Error::GitHubAppNotInstalled {
213                install_url: workspaces::GITHUB_APP_INSTALL_URL.into(),
214                cause: Box::new(e),
215            })
216        }
217        r => r.map(|_| ()),
218    }
219}