chainguard_sandbox/workspaces/
client.rs1use 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
16pub const DEFAULT_USER_AGENT: &str = "chainguard-sandbox-sdk-rs";
18
19#[derive(Clone, Default)]
21pub struct Options {
22 pub url: String,
25 pub instance: String,
29 pub no_detect_instance: bool,
31 pub platform_token_source: Option<SharedTokenSource>,
34 pub token_source: Option<SharedTokenSource>,
37 pub user_agent: String,
39}
40
41#[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 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 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 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 pub fn raw(&self) -> SessionsClient<Channel> {
132 self.raw.clone()
133 }
134
135 pub fn instance(&self) -> String {
137 super::instance_name(&self.instance)
138 }
139
140 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 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 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
178fn 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}