1use 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#[derive(Debug, Clone, PartialEq, Eq, Default)]
45pub struct TermsDocument {
46 pub id: String,
47 pub label: String,
48 pub url: String,
49}
50
51pub const WORKSPACES_TERMS: &[&str] = &["secure-platform-terms.v1", "msla.v1"];
54
55pub 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
67pub const GITHUB_APP_INSTALL_URL: &str = "https://github.com/apps/chainguard/installations/new";
69
70pub const DEFAULT_GITHUB_OAUTH_PORT: u16 = 8989;
72
73pub 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#[derive(Debug, Clone, Default)]
110pub struct PlatformError {
111 pub http_status: u16,
113 pub code: i64,
115 pub message: String,
116 pub reason: String,
118 pub missing_terms: Vec<TermsDocument>,
120}
121
122impl PlatformError {
123 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 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 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
152async 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 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
254pub 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
275pub 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
288pub 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
312pub 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#[derive(Debug, Clone, Default)]
332pub struct Entitlement {
333 pub plan: String,
335 pub plan_name: String,
337 pub active: bool,
339 pub state: String,
341 pub max_sandboxes: i64,
343 pub max_sandboxes_per_user: i64,
344}
345
346pub 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#[derive(Debug, Clone, PartialEq, Eq)]
407pub struct LinkedGitHub {
408 pub organization: String,
410}
411
412pub 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#[derive(Debug, Clone)]
444pub struct GitHubOAuthStart {
445 pub client_id: String,
446 pub state: String,
447}
448
449pub 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#[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#[derive(Clone, Default)]
495pub struct GitHubAuthorizeOptions {
496 pub port: u16,
498 pub no_browser: bool,
500 pub open_url: Option<UrlOpener>,
503 pub out: Option<MessageSink>,
505}
506
507pub 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 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 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
612pub 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}