chainguard_sandbox/
setup.rs1use std::time::Duration;
9
10use crate::workspaces::{self, MessageSink, SharedTokenSource, TermsDocument, UrlOpener};
11use crate::{Error, Result};
12
13crate::opaque_debug!(SetupOptions);
14
15#[derive(Clone, Default)]
17pub struct SetupOptions {
18 pub instance: String,
21 pub token_source: Option<SharedTokenSource>,
23 pub accept_terms: bool,
27 pub github_account: String,
30 pub github_port: u16,
32 pub no_browser: bool,
35 pub out: Option<MessageSink>,
37 pub open_url: Option<UrlOpener>,
39}
40
41#[derive(Debug, Clone, Default)]
43pub struct WorkspacesStatus {
44 pub organization: String,
46 pub enabled: bool,
49 pub missing_terms: Vec<TermsDocument>,
52 pub github_accounts: Vec<String>,
55 pub plan: String,
57 pub max_sandboxes: i64,
59 pub max_sandboxes_per_user: i64,
60}
61
62impl WorkspacesStatus {
63 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
81pub 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 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 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
115pub 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 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 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
177async 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}