Skip to main content

chainguard_sandbox/workspaces/
client.rs

1//! The gRPC client for the Sessions API.
2
3use std::time::Duration;
4
5use tonic::metadata::MetadataValue;
6use tonic::transport::{Channel, ClientTlsConfig, Endpoint};
7
8use super::auth::{SharedTokenSource, default_token_source, env_nonempty};
9use super::orgs::{detect_instance, platform_token_source};
10use super::pb::sessions_client::SessionsClient;
11use super::{DEFAULT_URL, ENV_AUTH_TOKEN, ENV_INSTANCE, ENV_NO_DETECT_INSTANCE, ENV_SESSIONS_URL};
12use crate::{Error, Result};
13
14crate::opaque_debug!(Options);
15
16/// The user agent sent with every call unless [`Options::user_agent`] says otherwise.
17pub const DEFAULT_USER_AGENT: &str = "chainguard-sandbox-sdk-rs";
18
19/// Configures a [`Client`].
20#[derive(Clone, Default)]
21pub struct Options {
22    /// The sandbox plane's URL, e.g. `https://sessions.chainbox.dev` or `http://localhost:8080`
23    /// (plaintext). Defaults to `$CHAINCTL_SESSIONS_URL`, then [`DEFAULT_URL`].
24    pub url: String,
25    /// The organization ID, used as "instances/{instance}". If empty, `$CHAINCTL_SANDBOX_INSTANCE`
26    /// is used; if that is empty too, the organization is auto-detected (see
27    /// [`detect_instance`]) unless `no_detect_instance` is set.
28    pub instance: String,
29    /// Turns off organization auto-detection (also `$CHAINGUARD_SANDBOX_NO_DETECT_INSTANCE=1`).
30    pub no_detect_instance: bool,
31    /// Mints account-API tokens for auto-detection. Defaults to [`platform_token_source`] when
32    /// `token_source` is unset and `$CHAINCTL_AUTH_TOKEN` is empty; otherwise detection needs it.
33    pub platform_token_source: Option<SharedTokenSource>,
34    /// Supplies bearer tokens for [`DEFAULT_AUDIENCE`](super::DEFAULT_AUDIENCE). Defaults to
35    /// [`default_token_source`].
36    pub token_source: Option<SharedTokenSource>,
37    /// Sent with every call (default [`DEFAULT_USER_AGENT`]).
38    pub user_agent: String,
39}
40
41/// A connection to the Sessions service. Cloning is cheap and shares the connection.
42#[derive(Clone)]
43pub struct Client {
44    raw: SessionsClient<Channel>,
45    ts: SharedTokenSource,
46    instance: String,
47    detect_err: Option<String>,
48}
49
50impl std::fmt::Debug for Client {
51    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52        f.debug_struct("Client")
53            .field("instance", &self.instance)
54            .finish_non_exhaustive()
55    }
56}
57
58impl Client {
59    /// Connects to the sandbox plane (lazily: the connection is made on the first call).
60    pub async fn new(mut o: Options) -> Result<Client> {
61        if o.url.is_empty() {
62            o.url = env_nonempty(ENV_SESSIONS_URL).unwrap_or_else(|| DEFAULT_URL.into());
63        }
64        if o.instance.is_empty() {
65            o.instance = std::env::var(ENV_INSTANCE).unwrap_or_default();
66        }
67        let mut detect_err = None;
68        if o.instance.is_empty()
69            && !o.no_detect_instance
70            && std::env::var(ENV_NO_DETECT_INSTANCE).as_deref() != Ok("1")
71        {
72            let mut pts = o.platform_token_source.clone();
73            if pts.is_none() && o.token_source.is_none() && env_nonempty(ENV_AUTH_TOKEN).is_none() {
74                pts = Some(platform_token_source());
75            }
76            match pts {
77                None => {
78                    detect_err = Some(format!(
79                        "needs Options::platform_token_source when a custom token source or ${ENV_AUTH_TOKEN} is used"
80                    ))
81                }
82                Some(pts) => {
83                    // Room for a browser login.
84                    match tokio::time::timeout(
85                        Duration::from_secs(11 * 60),
86                        detect_instance(Some(pts)),
87                    )
88                    .await
89                    {
90                        Ok(Ok(id)) => o.instance = id,
91                        Ok(Err(e)) => detect_err = Some(e.to_string()),
92                        Err(_) => detect_err = Some("timed out".into()),
93                    }
94                }
95            }
96        } else if o.instance.is_empty() {
97            detect_err = Some("turned off".into());
98        }
99        let ts = o.token_source.clone().unwrap_or_else(default_token_source);
100        let ua = if o.user_agent.is_empty() {
101            DEFAULT_USER_AGENT.to_string()
102        } else {
103            o.user_agent.clone()
104        };
105        let channel = channel(&o.url, &ua)?;
106        Ok(Client {
107            raw: SessionsClient::new(channel),
108            ts,
109            instance: o.instance,
110            detect_err,
111        })
112    }
113
114    /// Builds a client on an existing channel. `instance` may be empty if only full resource
115    /// names are used.
116    pub fn from_channel(
117        channel: Channel,
118        ts: SharedTokenSource,
119        instance: impl Into<String>,
120    ) -> Client {
121        Client {
122            raw: SessionsClient::new(channel),
123            ts,
124            instance: instance.into(),
125            detect_err: None,
126        }
127    }
128
129    /// The generated gRPC client, for calls this crate doesn't wrap. It covers only the SDK's
130    /// subset of the Sessions API. Authorize each request with [`Client::request`].
131    pub fn raw(&self) -> SessionsClient<Channel> {
132        self.raw.clone()
133    }
134
135    /// The resource name "instances/{id}" used as the parent of sessions.
136    pub fn instance(&self) -> String {
137        super::instance_name(&self.instance)
138    }
139
140    /// The token source the client authorizes calls with.
141    pub fn token_source(&self) -> SharedTokenSource {
142        self.ts.clone()
143    }
144
145    pub(crate) fn parent(&self) -> Result<String> {
146        if self.instance.is_empty() {
147            return Err(Error::NoInstance {
148                detection: self.detect_err.clone(),
149            });
150        }
151        Ok(super::instance_name(&self.instance))
152    }
153
154    /// Wraps a message in a request carrying the bearer token.
155    pub async fn request<T>(&self, msg: T) -> Result<tonic::Request<T>> {
156        let tok = self.ts.token().await?;
157        let mut r = tonic::Request::new(msg);
158        let v: MetadataValue<_> = format!("Bearer {tok}")
159            .parse()
160            .map_err(|_| Error::other("workspaces: the token is not a valid header value"))?;
161        r.metadata_mut().insert("authorization", v);
162        Ok(r)
163    }
164
165    /// Converts a call's result, dropping the cached token when the plane rejects it.
166    pub(crate) fn check<T>(&self, r: std::result::Result<T, tonic::Status>) -> Result<T> {
167        r.map_err(|s| self.status(s))
168    }
169
170    pub(crate) fn status(&self, s: tonic::Status) -> Error {
171        if s.code() == tonic::Code::Unauthenticated {
172            self.ts.invalidate();
173        }
174        Error::Rpc(s)
175    }
176}
177
178/// Builds the channel for a URL: `https://` gets TLS with the system's roots, `http://` is
179/// plaintext, and a URL without a scheme is taken as `https://`.
180fn channel(raw: &str, ua: &str) -> Result<Channel> {
181    let raw = if raw.contains("://") {
182        raw.to_string()
183    } else {
184        format!("https://{raw}")
185    };
186    let u = url::Url::parse(&raw)
187        .map_err(|e| Error::other(format!("parsing sessions URL {raw:?}: {e}")))?;
188    let secure = match u.scheme() {
189        "https" => true,
190        "http" => false,
191        s => {
192            return Err(Error::other(format!(
193                "sessions URL {raw:?}: unsupported scheme {s:?}"
194            )));
195        }
196    };
197    let host = u
198        .host_str()
199        .ok_or_else(|| Error::other(format!("sessions URL {raw:?}: no host")))?;
200    let port = u.port().unwrap_or(if secure { 443 } else { 80 });
201    let target = format!("{}://{}:{port}", u.scheme(), host);
202    let mut ep = Endpoint::from_shared(target)
203        .map_err(|e| Error::transport(format!("dialing {raw}"), e))?
204        .user_agent(ua)
205        .map_err(|e| Error::transport(format!("dialing {raw}"), e))?
206        .connect_timeout(Duration::from_secs(30))
207        .http2_keep_alive_interval(Duration::from_secs(30))
208        .keep_alive_while_idle(true);
209    if secure {
210        let tls = ClientTlsConfig::new()
211            .with_native_roots()
212            .domain_name(host.trim_start_matches('[').trim_end_matches(']'));
213        ep = ep
214            .tls_config(tls)
215            .map_err(|e| Error::transport(format!("dialing {raw}"), e))?;
216    }
217    Ok(ep.connect_lazy())
218}