Skip to main content

chainguard_sandbox/workspaces/
orgs.rs

1//! Organizations: listing them and choosing the one a client works in.
2//!
3//! The organization ("instance") can be given three ways, in this order:
4//!
5//! 1. explicitly: `Options::instance` (the 40-hex organization ID);
6//! 2. the environment: `$CHAINCTL_SANDBOX_INSTANCE`;
7//! 3. auto-detection: if neither is set, the client lists the organizations your identity belongs
8//!    to and uses the only one. With several, it reports them. Turn it off with
9//!    `Options::no_detect_instance` or `$CHAINGUARD_SANDBOX_NO_DETECT_INSTANCE=1`.
10
11use std::sync::Arc;
12
13use super::auth::{SharedTokenSource, cached};
14use super::login::{BrowserLoginToken, LoginOptions};
15use super::{ChainctlToken, DEFAULT_PLATFORM_URL, PLATFORM_AUDIENCE, http};
16use crate::{Error, Result};
17
18/// A Chainguard organization (a root IAM group).
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct Organization {
21    /// The organization's 40-hex ID, used as the sessions instance.
22    pub id: String,
23    pub name: String,
24}
25
26pub(crate) fn platform_url() -> String {
27    std::env::var("CHAINGUARD_SANDBOX_PLATFORM_URL")
28        .ok()
29        .filter(|v| !v.is_empty())
30        .unwrap_or_else(|| DEFAULT_PLATFORM_URL.into())
31}
32
33/// Returns the organizations visible to the token source's identity, sorted by name. `ts` must
34/// mint tokens for [`PLATFORM_AUDIENCE`]; `None` uses [`platform_token_source`]. It calls the IAM
35/// Groups API: `GET /iam/v1/groups?uidp.in_root=true`.
36pub async fn list_organizations(ts: Option<SharedTokenSource>) -> Result<Vec<Organization>> {
37    let ts = ts.unwrap_or_else(platform_token_source);
38    let tok = ts.token().await?;
39    let url = format!(
40        "{}/iam/v1/groups?uidp.in_root=true",
41        platform_url().trim_end_matches('/')
42    );
43    let req = http::client()?
44        .get(url)
45        .header("Authorization", format!("Bearer {tok}"))
46        .header("Accept", "application/json");
47    let a = http::send(req, 4 << 20, "listing organizations").await?;
48    if a.status == 401 {
49        ts.invalidate();
50    }
51    if a.status != 200 {
52        return Err(Error::Http {
53            context: "listing organizations".into(),
54            status: a.status,
55            message: http::error_message(&a.body),
56        });
57    }
58    #[derive(serde::Deserialize)]
59    struct Item {
60        #[serde(default)]
61        id: String,
62        #[serde(default)]
63        name: String,
64    }
65    #[derive(serde::Deserialize)]
66    struct List {
67        #[serde(default)]
68        items: Vec<Item>,
69    }
70    let gl: List = serde_json::from_slice(&a.body)
71        .map_err(|e| Error::other(format!("listing organizations: {e}")))?;
72    let mut orgs: Vec<Organization> = gl
73        .items
74        .into_iter()
75        .filter(|g| !g.id.is_empty() && !g.id.contains('/')) // root groups only
76        .map(|g| Organization {
77            id: g.id,
78            name: g.name,
79        })
80        .collect();
81    orgs.sort_by(|a, b| a.name.cmp(&b.name));
82    Ok(orgs)
83}
84
85/// The ID of the only organization the identity belongs to ([`Error::NoOrganization`] or
86/// [`Error::AmbiguousOrganization`] otherwise).
87pub async fn detect_instance(ts: Option<SharedTokenSource>) -> Result<String> {
88    let orgs = list_organizations(ts).await?;
89    match orgs.len() {
90        0 => Err(Error::NoOrganization),
91        1 => Ok(orgs[0].id.clone()),
92        _ => Err(Error::AmbiguousOrganization {
93            organizations: orgs,
94        }),
95    }
96}
97
98/// Mints tokens for the account API ([`PLATFORM_AUDIENCE`]) the same way
99/// [`default_token_source`](super::default_token_source) does for sessions: from the saved browser
100/// login, or with chainctl when `$CHAINGUARD_SANDBOX_AUTH=chainctl`.
101pub fn platform_token_source() -> SharedTokenSource {
102    if std::env::var("CHAINGUARD_SANDBOX_AUTH").as_deref() == Ok("chainctl") {
103        return cached(Arc::new(ChainctlToken {
104            audience: PLATFORM_AUDIENCE.into(),
105            ..Default::default()
106        }));
107    }
108    cached(Arc::new(BrowserLoginToken {
109        audience: PLATFORM_AUDIENCE.into(),
110        login: LoginOptions {
111            connection: std::env::var("CHAINGUARD_SANDBOX_SOCIAL_LOGIN").unwrap_or_default(),
112            ..Default::default()
113        },
114        no_browser: std::env::var("CHAINGUARD_SANDBOX_NO_BROWSER").as_deref() == Ok("1"),
115        ..Default::default()
116    }))
117}