Skip to main content

one/
client.rs

1use crate::{
2    retry::{RetrySchedule, Retryable},
3    transport::types::PaginatedVaultConnectionView,
4    webhooks::Webhooks
5};
6use bytes::Bytes;
7use handlebars::Handlebars;
8use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, utf8_percent_encode};
9use reqwest::{
10    Client as HttpClient, Error as ReqwestError, RequestBuilder,
11    header::{AUTHORIZATION, CONTENT_TYPE, HeaderMap, RETRY_AFTER}
12};
13pub use reqwest::{Method, StatusCode};
14use secrecy::{ExposeSecret, SecretBox, SecretString};
15use serde::{Serialize, de::DeserializeOwned};
16use serde_json::{Error as JsonError, Map, Value, from_slice, to_value, to_vec};
17use std::{
18    collections::BTreeMap,
19    env::var,
20    error::Error as StdError,
21    fmt,
22    marker::PhantomData,
23    sync::{Arc, Once},
24    time::Duration
25};
26
27use rustls::{ClientConfig, RootCertStore, crypto::ring::default_provider};
28use tokio::time::sleep;
29use webpki_roots::TLS_SERVER_ROOTS;
30
31/// A connection record from the vault, typed straight from the One API schema.
32pub use crate::transport::types::PaginatedVaultConnectionViewRowsItem as Connection;
33
34const SECRET_HEADER: &str = "X-One-Secret";
35const BEARER_PREFIX: &str = "Bearer ";
36const CONNECTION_KEY_HEADER: &str = "X-One-Connection-Key";
37const ACTION_ID_HEADER: &str = "X-One-Action-Id";
38const ORGANIZATION_ID_HEADER: &str = "X-One-Organization-Id";
39const PROJECT_ID_HEADER: &str = "X-One-Project-Id";
40const DEFAULT_BASE_URL: &str = "https://api.picaos.com";
41const SECRET_ENV: &str = "ONE_SECRET";
42const ACCESS_TOKEN_ENV: &str = "ONE_ACCESS_TOKEN";
43const BASE_URL_ENV: &str = "ONE_BASE_URL";
44const VAULT_CONNECTIONS_PATH: &str = "/v1/vault/connections";
45const CONNECTION_KEY_PARAM: &str = "key";
46const PAGE_PARAM: &str = "page";
47const LIMIT_PARAM: &str = "limit";
48const APPLICATION_JSON: &str = "application/json";
49const NON_OBJECT_INPUT: &str = "the input must be a JSON object";
50
51/// Characters to percent-encode in a path-parameter value: everything except
52/// the RFC 3986 unreserved set (`ALPHA / DIGIT / - . _ ~`). This keeps a value
53/// like `a/b` as a single path segment (`a%2Fb`) instead of letting `/`, `?`,
54/// `#`, or spaces re-shape the URL.
55pub(crate) const PATH_SEGMENT: &AsciiSet = &NON_ALPHANUMERIC.remove(b'-').remove(b'.').remove(b'_').remove(b'~');
56
57/// The value of an environment variable that was actually configured, treating
58/// "set but blank" as unset.
59///
60/// A leftover `ONE_SECRET=` in a shell profile, a compose file, or a CI matrix
61/// is how an environment says *not this one* - but `env::var` reports it as a
62/// present value, so it would win the credential precedence over the
63/// `ONE_ACCESS_TOKEN` sitting beside it and then fail the build as a missing
64/// secret. Nothing here has a meaningful blank value, so every read goes
65/// through this.
66fn configured(key: &str) -> Option<String> {
67    var(key).ok().filter(|value| !value.trim().is_empty())
68}
69
70/// Errors returned by SDK calls.
71///
72/// `#[non_exhaustive]`: new variants may be added in future releases, so
73/// downstream `match` statements must include a `_ =>` arm.
74#[derive(Debug, thiserror::Error)]
75#[non_exhaustive]
76pub enum Error {
77    /// The request could not be sent (DNS, TLS, connect).
78    #[error("transport error: {0}")]
79    Transport(ReqwestError),
80    /// The request exceeded its configured timeout.
81    #[error("request timed out")]
82    Timeout,
83    /// The response body could not be read.
84    #[error("failed to read response body: {0}")]
85    Body(ReqwestError),
86    /// The platform returned a non-2xx status; the raw body is preserved.
87    #[error("upstream returned status {status}")]
88    Status { status: StatusCode, body: Bytes },
89    /// A response body could not be deserialized into the requested type.
90    #[error("failed to decode response: {0}")]
91    Decode(JsonError),
92    /// No connection matched the requested key.
93    #[error("no connection found for the given key")]
94    NotFound,
95    /// The client was built without a credential.
96    #[error(
97        "a credential is required: a secret key (.secret() or ONE_SECRET) or an OAuth access token (.access_token() \
98         or ONE_ACCESS_TOKEN)"
99    )]
100    MissingSecret,
101    /// A path template referenced a variable not supplied in the path object.
102    #[error("path template error: {0}")]
103    PathTemplate(String),
104    /// A generated action's input is missing a required field or holds an
105    /// invalid value; the source is the builder's or the router's own error.
106    #[error("invalid action input: {0}")]
107    InvalidInput(#[source] Box<dyn StdError + Send + Sync>)
108}
109
110/// A part of an action request that a flat input field is routed into.
111#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
112pub enum Part {
113    Path,
114    Query,
115    Headers,
116    Body
117}
118
119/// Where one field of a generated action's flat input goes in the request.
120#[derive(Debug, Clone, Copy)]
121pub struct Route {
122    /// The field's name in the serialized input.
123    pub field: &'static str,
124    /// The request part it belongs to.
125    pub part:  Part,
126    /// Its key within that part, or `None` when the field is the whole part.
127    pub key:   Option<&'static str>
128}
129
130/// How a generated action's flat input maps onto its request.
131#[derive(Debug, Clone, Copy)]
132pub struct Routing {
133    /// Where each field goes.
134    pub routes:         &'static [Route],
135    /// Object parts the action requires, sent as `{}` when no field sets them.
136    pub required_parts: &'static [Part]
137}
138
139/// Anything [`ConnectionScope::run`] executes: an [`Operation`], or a
140/// generated action's input or builder.
141pub trait IntoOperation {
142    /// The type the response decodes to.
143    type Output;
144
145    /// Builds the operation, failing when the input does not validate.
146    fn into_operation(self) -> Result<Operation<Self::Output>, Error>;
147}
148
149impl<Out> IntoOperation for Operation<Out> {
150    type Output = Out;
151
152    fn into_operation(self) -> Result<Self, Error> {
153        Ok(self)
154    }
155}
156
157impl Retryable for Error {
158    fn is_transient(&self) -> bool {
159        match self {
160            Self::Transport(e) => e.is_timeout() || e.is_connect() || e.is_request(),
161            Self::Timeout => true,
162            Self::Status { status, .. } => status.is_server_error() || *status == StatusCode::TOO_MANY_REQUESTS,
163            Self::Body(_)
164            | Self::Decode(_)
165            | Self::NotFound
166            | Self::MissingSecret
167            | Self::PathTemplate(_)
168            | Self::InvalidInput(_) => false
169        }
170    }
171}
172
173/// A successful (2xx) response, tagged with the action's default output type
174/// `Out` (the io_schema output, or [`Value`] for raw calls). Holds the raw
175/// body; [`CallResponse::output`] decodes the default, [`CallResponse::json`]
176/// any caller type.
177pub struct CallResponse<Out = Value> {
178    status:  StatusCode,
179    headers: BTreeMap<String, String>,
180    body:    Bytes,
181    _out:    PhantomData<fn() -> Out>
182}
183
184impl<Out> Clone for CallResponse<Out> {
185    fn clone(&self) -> Self {
186        Self {
187            status:  self.status,
188            headers: self.headers.clone(),
189            body:    self.body.clone(),
190            _out:    PhantomData
191        }
192    }
193}
194
195impl<Out> CallResponse<Out> {
196    /// The HTTP status of the response.
197    pub fn status(&self) -> StatusCode {
198        self.status
199    }
200
201    /// The response headers (rate-limit, request-id, `ETag`, `Link`, …), header
202    /// names mapped to their value.
203    pub fn headers(&self) -> &BTreeMap<String, String> {
204        &self.headers
205    }
206
207    /// The raw response body.
208    pub fn bytes(&self) -> &Bytes {
209        &self.body
210    }
211
212    /// The response body as a UTF-8 string (lossy).
213    pub fn text(&self) -> String {
214        String::from_utf8_lossy(&self.body).into_owned()
215    }
216
217    /// Decodes the body into a caller-supplied type — the override for when the
218    /// synced output is wrong.
219    pub fn json<T: DeserializeOwned>(&self) -> Result<T, Error> {
220        from_slice(&self.body).map_err(Error::Decode)
221    }
222
223    /// Re-tags the response with a different output type. The engine attaches
224    /// the operation's `Out` here.
225    fn retype<U>(self) -> CallResponse<U> {
226        CallResponse {
227            status:  self.status,
228            headers: self.headers,
229            body:    self.body,
230            _out:    PhantomData
231        }
232    }
233}
234
235impl<Out: DeserializeOwned> CallResponse<Out> {
236    /// Decodes the body into the action's default output type.
237    pub fn output(&self) -> Result<Out, Error> {
238        from_slice(&self.body).map_err(Error::Decode)
239    }
240}
241
242type SuccessHook = Arc<dyn Fn(&CallResponse) + Send + Sync>;
243type ErrorHook = Arc<dyn Fn(&Error) + Send + Sync>;
244
245/// What the client authenticates with.
246///
247/// Two credentials reach the same API by different headers, and a request
248/// carries exactly one. Modelling it as a choice rather than two optional
249/// fields means "both set" and "neither set" are states that cannot be built.
250///
251/// Both arms hold the value in [`SecretBox`], so a credential is redacted in
252/// `Debug` and zeroized on drop. It is exposed only in [`Self::apply`], at the
253/// moment the header is written.
254#[derive(Clone)]
255pub enum Credential {
256    /// A One secret key, sent as `X-One-Secret`. The long-lived agency
257    /// credential.
258    Secret(Arc<SecretBox<String>>),
259    /// An OAuth access token, sent as `Authorization: Bearer`. What an app
260    /// holding an end user's grant uses; the reachable surface is whatever that
261    /// grant consented to, not the whole account.
262    AccessToken(Arc<SecretBox<String>>)
263}
264
265impl fmt::Debug for Credential {
266    /// Names which credential is in play and never its value, so a client
267    /// dumped into a log or a panic cannot leak the token.
268    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
269        match self {
270            Self::Secret(_) => f.write_str("Credential::Secret(<redacted>)"),
271            Self::AccessToken(_) => f.write_str("Credential::AccessToken(<redacted>)")
272        }
273    }
274}
275
276impl Credential {
277    /// A One secret key.
278    pub fn secret(secret: impl Into<String>) -> Self {
279        Self::Secret(Arc::new(SecretBox::new(Box::new(secret.into()))))
280    }
281
282    /// An OAuth access token.
283    pub fn access_token(token: impl Into<String>) -> Self {
284        Self::AccessToken(Arc::new(SecretBox::new(Box::new(token.into()))))
285    }
286
287    /// Adds this credential to a request. The one place either header is
288    /// written, and the only place the value is exposed.
289    fn apply(&self, request: RequestBuilder) -> RequestBuilder {
290        match self {
291            Self::Secret(secret) => request.header(SECRET_HEADER, secret.expose_secret()),
292            Self::AccessToken(token) => {
293                request.header(AUTHORIZATION, format!("{BEARER_PREFIX}{}", token.expose_secret()))
294            }
295        }
296    }
297
298    /// Whether this carries nothing usable.
299    ///
300    /// Blank counts, matching [`configured`]: a credential of spaces is a
301    /// misconfiguration however it arrives, and the builder exists to catch it
302    /// here rather than at the first 401. The two doors must agree - the same
303    /// `"  "` cannot be unset when it comes from the environment and a valid
304    /// secret when it comes from the builder.
305    fn is_empty(&self) -> bool {
306        match self {
307            Self::Secret(value) | Self::AccessToken(value) => value.expose_secret().trim().is_empty()
308        }
309    }
310}
311
312/// The tenant a request acts within: an organization, optionally narrowed to
313/// one of its projects. Empty means the caller's own personal scope.
314///
315/// **A secret key does not need this and an access token does.** A key is
316/// bound to its tenant server-side, so the API reads tenancy off the key and
317/// ignores what the request claims. A bearer is not: one token can hold grants
318/// on several organizations, so the tenant is decided per request from these
319/// headers - and a request that sends neither resolves to the personal tier no
320/// matter what the token was granted. That is why an org-owned connection is
321/// simply absent from a bearer's results until this is set.
322#[derive(Clone, Debug, Default)]
323pub struct Tenancy {
324    organization: Option<String>,
325    project:      Option<String>
326}
327
328impl Tenancy {
329    /// Adds the tenant headers to a request. The one place either is written.
330    fn apply(&self, request: RequestBuilder) -> RequestBuilder {
331        let request = match &self.organization {
332            Some(id) => request.header(ORGANIZATION_ID_HEADER, id),
333            None => request
334        };
335        match &self.project {
336            Some(id) => request.header(PROJECT_ID_HEADER, id),
337            None => request
338        }
339    }
340}
341
342/// The One SDK client.
343///
344/// Holds the credential, base URL, default retry schedule, and global
345/// success/error hooks. Cheap to clone; wraps a shared `reqwest` client.
346#[derive(Clone)]
347pub struct One {
348    http:       HttpClient,
349    base_url:   String,
350    credential: Credential,
351    tenancy:    Tenancy,
352    retry:      RetrySchedule,
353    timeout:    Option<Duration>,
354    on_success: Option<SuccessHook>,
355    on_error:   Option<ErrorHook>
356}
357
358impl One {
359    /// Starts a request carrying this client's credential and tenant scope.
360    ///
361    /// The one door every call goes through, so a new endpoint cannot ship
362    /// having attached one and forgotten the other - which for tenancy fails
363    /// silently, as a request with no tenant headers is a valid personal-scope
364    /// request that simply cannot see the tenant's rows.
365    fn request(&self, method: Method, url: &str) -> RequestBuilder {
366        self.tenancy
367            .apply(self.credential.apply(self.http.request(method, url)))
368    }
369
370    /// Creates a client from a One secret key, targeting the default base URL.
371    /// Panics if `secret` is empty; use [`OneBuilder::build`] for a fallible
372    /// path.
373    pub fn new(secret: impl Into<String>) -> Self {
374        Self::builder()
375            .secret(secret)
376            .build()
377            .expect("One::new requires a non-empty secret")
378    }
379
380    /// Creates a client from the environment: a credential (required) and
381    /// `ONE_BASE_URL` (optional, defaults to the production base URL).
382    ///
383    /// The credential is `ONE_SECRET`, or `ONE_ACCESS_TOKEN` for an OAuth
384    /// grant. `ONE_SECRET` wins if both are set, because it is the
385    /// longer-standing variable and silently preferring the newer one would
386    /// change what an existing environment authenticates as. Set-but-blank does
387    /// not count as set - see [`configured`].
388    pub fn from_env() -> Result<Self, Error> {
389        let credential = configured(SECRET_ENV)
390            .map(Credential::secret)
391            .or_else(|| configured(ACCESS_TOKEN_ENV).map(Credential::access_token))
392            .ok_or(Error::MissingSecret)?;
393
394        let mut builder = Self::builder().credential(credential);
395        if let Some(base_url) = configured(BASE_URL_ENV) {
396            builder = builder.base_url(base_url);
397        }
398        builder.build()
399    }
400
401    /// Starts building a client with full configuration.
402    pub fn builder() -> OneBuilder {
403        OneBuilder::default()
404    }
405
406    /// Scopes subsequent calls to a connection by its key.
407    pub fn connection(&self, key: impl Into<String>) -> ConnectionScope<'_> {
408        ConnectionScope {
409            one: self,
410            key: key.into()
411        }
412    }
413
414    /// Starts building a webhook listener, verified with `signing_secret`.
415    ///
416    /// The listener owns a clone of this client: it is mounted into an HTTP
417    /// server and outlives any single request, so it cannot borrow.
418    pub fn webhooks(&self, signing_secret: SecretString) -> Webhooks {
419        Webhooks::new(self.clone(), signing_secret)
420    }
421
422    /// Sends an authenticated `PUT` with a JSON body to a One API path and
423    /// preserves the response metadata for the webhook bindings.
424    pub(crate) async fn put_json_response<B: Serialize, Out>(
425        &self,
426        path: &str,
427        body: &B
428    ) -> Result<CallResponse<Out>, Error> {
429        let url = format!("{}{path}", self.base_url);
430        let payload = to_vec(body).map_err(Error::Decode)?;
431
432        let response = self
433            .execute(self.retry, None, &[], || {
434                let mut request = self
435                    .request(Method::PUT, &url)
436                    .header(CONTENT_TYPE, APPLICATION_JSON)
437                    .body(payload.clone());
438                if let Some(timeout) = self.timeout {
439                    request = request.timeout(timeout);
440                }
441                request
442            })
443            .await?;
444
445        Ok(response.retype())
446    }
447
448    /// The one place a request is sent, retried, and reported.
449    ///
450    /// Applies `retry` honoring `Retry-After`, treats the transient set plus
451    /// `retry_on` as retryable, and fires the client hooks followed by the
452    /// per-call ones. Both the action engine and the management calls route
453    /// through this, so a transport or retry fix lands once.
454    pub(crate) async fn execute<F>(
455        &self,
456        retry: RetrySchedule,
457        on_call: Option<(&Option<SuccessHook>, &Option<ErrorHook>)>,
458        retry_on: &[StatusCode],
459        build: F
460    ) -> Result<CallResponse<Value>, Error>
461    where
462        F: Fn() -> reqwest::RequestBuilder
463    {
464        let send = || {
465            let request = build();
466            async move {
467                let response = match request.send().await {
468                    Ok(response) => response,
469                    Err(error) => {
470                        let mapped = if error.is_timeout() {
471                            Error::Timeout
472                        } else {
473                            Error::Transport(error)
474                        };
475                        return Err((mapped, None));
476                    }
477                };
478                let status = response.status();
479                let headers: BTreeMap<String, String> = response
480                    .headers()
481                    .iter()
482                    .filter_map(|(name, value)| {
483                        value
484                            .to_str()
485                            .ok()
486                            .map(|value| (name.as_str().to_string(), value.to_string()))
487                    })
488                    .collect();
489                let retry_after = Self::retry_after(response.headers());
490                let body = match response.bytes().await {
491                    Ok(body) => body,
492                    Err(error) => return Err((Error::Body(error), None))
493                };
494                if status.is_success() {
495                    Ok(CallResponse {
496                        status,
497                        headers,
498                        body,
499                        _out: PhantomData
500                    })
501                } else {
502                    Err((Error::Status { status, body }, retry_after))
503                }
504            }
505        };
506
507        let attempts = retry.max_attempts.max(1);
508        let result: Result<CallResponse<Value>, Error> = 'attempts: {
509            for attempt in 1..=attempts {
510                match send().await {
511                    Ok(response) => break 'attempts Ok(response),
512                    Err((error, retry_after)) => {
513                        if attempt == attempts || !Self::is_retryable(&error, retry_on) {
514                            break 'attempts Err(error);
515                        }
516                        sleep(retry_after.unwrap_or_else(|| retry.delay(attempt))).await;
517                    }
518                }
519            }
520            unreachable!("loop runs at least once and breaks on every path")
521        };
522
523        match &result {
524            Ok(response) => {
525                if let Some(hook) = &self.on_success {
526                    hook(response);
527                }
528                if let Some(hook) = on_call.and_then(|(success, _)| success.as_ref()) {
529                    hook(response);
530                }
531            }
532            Err(error) => {
533                if let Some(hook) = &self.on_error {
534                    hook(error);
535                }
536                if let Some(hook) = on_call.and_then(|(_, failure)| failure.as_ref()) {
537                    hook(error);
538                }
539            }
540        }
541
542        result
543    }
544
545    /// Whether a failed attempt should be retried: the general transient set
546    /// plus any per-call `retry_on` statuses.
547    fn is_retryable(error: &Error, retry_on: &[StatusCode]) -> bool {
548        error.is_transient() || matches!(error, Error::Status { status, .. } if retry_on.contains(status))
549    }
550
551    /// Parses a `Retry-After` header expressed as a whole number of seconds.
552    fn retry_after(headers: &HeaderMap) -> Option<Duration> {
553        headers
554            .get(RETRY_AFTER)?
555            .to_str()
556            .ok()?
557            .trim()
558            .parse::<u64>()
559            .ok()
560            .map(Duration::from_secs)
561    }
562}
563
564/// Builder for [`One`].
565#[derive(Default)]
566pub struct OneBuilder {
567    base_url:   Option<String>,
568    credential: Option<Credential>,
569    tenancy:    Tenancy,
570    retry:      Option<RetrySchedule>,
571    timeout:    Option<Duration>,
572    on_success: Option<SuccessHook>,
573    on_error:   Option<ErrorHook>
574}
575
576impl OneBuilder {
577    /// Sets the secret key (`X-One-Secret`).
578    pub fn secret(mut self, secret: impl Into<String>) -> Self {
579        self.credential = Some(Credential::secret(secret));
580        self
581    }
582
583    /// Sets the credential directly, for callers that already have one in
584    /// hand. [`Self::secret`] and [`Self::access_token`] are the usual doors.
585    pub fn credential(mut self, credential: Credential) -> Self {
586        self.credential = Some(credential);
587        self
588    }
589
590    /// Acts within an organization the caller has access to.
591    ///
592    /// **Required to reach an organization's connections with an access
593    /// token.** A token can hold grants on several organizations, so the API
594    /// decides which one a request means from this - and a request that omits
595    /// it means the user's personal scope, where an organization-owned
596    /// connection simply is not present. A secret key already carries its
597    /// tenant, so setting this alongside one changes nothing.
598    pub fn organization(mut self, organization_id: impl Into<String>) -> Self {
599        self.tenancy.organization = Some(organization_id.into());
600        self
601    }
602
603    /// Narrows [`Self::organization`] to one of its projects.
604    ///
605    /// A project is always qualified by its organization, so this is only
606    /// meaningful beside one; on its own the request still resolves to the
607    /// personal scope.
608    pub fn project(mut self, project_id: impl Into<String>) -> Self {
609        self.tenancy.project = Some(project_id.into());
610        self
611    }
612
613    /// Authenticates with an OAuth access token instead of a secret key.
614    ///
615    /// The reachable surface is whatever the end user consented to for this
616    /// app, not the whole account. Calling this after [`Self::secret`] (or the
617    /// reverse) replaces the credential rather than adding one: a request
618    /// carries exactly one.
619    pub fn access_token(mut self, token: impl Into<String>) -> Self {
620        self.credential = Some(Credential::access_token(token));
621        self
622    }
623
624    /// Overrides the base URL (e.g. a self-hosted or local instance).
625    pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
626        self.base_url = Some(base_url.into());
627        self
628    }
629
630    /// Sets the default retry schedule, applied to operations that don't
631    /// declare their own.
632    pub fn retry(mut self, schedule: RetrySchedule) -> Self {
633        self.retry = Some(schedule);
634        self
635    }
636
637    /// Sets the default per-request timeout, applied to operations that don't
638    /// declare their own.
639    pub fn timeout(mut self, timeout: Duration) -> Self {
640        self.timeout = Some(timeout);
641        self
642    }
643
644    /// Registers a global hook invoked after every successful call.
645    pub fn on_success<F: Fn(&CallResponse) + Send + Sync + 'static>(mut self, hook: F) -> Self {
646        self.on_success = Some(Arc::new(hook));
647        self
648    }
649
650    /// Registers a global hook invoked after every failed call.
651    pub fn on_error<F: Fn(&Error) + Send + Sync + 'static>(mut self, hook: F) -> Self {
652        self.on_error = Some(Arc::new(hook));
653        self
654    }
655
656    /// Builds the client, applying defaults for any unset field.
657    ///
658    /// Fails fast with [`Error::MissingSecret`] when no credential was
659    /// configured, rather than deferring the misconfiguration to a runtime auth
660    /// failure. **Either credential satisfies it** - a secret key from
661    /// [`Self::secret`] or an OAuth access token from [`Self::access_token`] -
662    /// and a configured-but-empty one counts as absent, since an empty header
663    /// would fail at the API rather than here.
664    pub fn build(self) -> Result<One, Error> {
665        let credential = self
666            .credential
667            .filter(|credential| !credential.is_empty())
668            .ok_or(Error::MissingSecret)?;
669        Self::ensure_crypto_provider();
670        let http = HttpClient::builder()
671            .use_preconfigured_tls(Self::tls_config())
672            .build()
673            .map_err(Error::Transport)?;
674        Ok(One {
675            http,
676            base_url: self
677                .base_url
678                .unwrap_or_else(|| DEFAULT_BASE_URL.to_string())
679                .trim_end_matches('/')
680                .to_string(),
681            credential,
682            tenancy: self.tenancy,
683            retry: self.retry.unwrap_or_default(),
684            timeout: self.timeout,
685            on_success: self.on_success,
686            on_error: self.on_error
687        })
688    }
689
690    /// Installs the process-default rustls crypto provider (`ring`) once. The
691    /// reqwest client uses rustls without a built-in provider, so one must be
692    /// registered before the first TLS handshake; `ring` is chosen over
693    /// `aws-lc-rs` because it cross-compiles cleanly to every published target.
694    fn ensure_crypto_provider() {
695        static ONCE: Once = Once::new();
696        ONCE.call_once(|| {
697            let _ = default_provider().install_default();
698        });
699    }
700
701    /// A rustls config that trusts the bundled Mozilla root certificates, so
702    /// the client establishes TLS without a system certificate store —
703    /// required in minimal container images that ship no CA bundle.
704    fn tls_config() -> ClientConfig {
705        let roots = RootCertStore {
706            roots: TLS_SERVER_ROOTS.to_vec()
707        };
708        ClientConfig::builder()
709            .with_root_certificates(roots)
710            .with_no_client_auth()
711    }
712}
713
714/// A declarative description of an action invocation.
715///
716/// You describe *what* you want — which action (`system_id`), the request
717/// shape, and the retry policy — and the engine ([`ConnectionScope::run`])
718/// resolves *how* to execute it. The action's verb and path are part of the
719/// description; once discovery lands they are filled from the action itself
720/// rather than supplied by hand.
721pub struct Operation<Out = Value> {
722    system_id:  String,
723    method:     Method,
724    path:       String,
725    query:      Value,
726    headers:    BTreeMap<String, String>,
727    body:       Bytes,
728    retry:      Option<RetrySchedule>,
729    retry_on:   Vec<StatusCode>,
730    timeout:    Option<Duration>,
731    on_success: Option<SuccessHook>,
732    on_error:   Option<ErrorHook>,
733    _out:       PhantomData<fn() -> Out>
734}
735
736impl<Out> Clone for Operation<Out> {
737    fn clone(&self) -> Self {
738        Self {
739            system_id:  self.system_id.clone(),
740            method:     self.method.clone(),
741            path:       self.path.clone(),
742            query:      self.query.clone(),
743            headers:    self.headers.clone(),
744            body:       self.body.clone(),
745            retry:      self.retry,
746            retry_on:   self.retry_on.clone(),
747            timeout:    self.timeout,
748            on_success: self.on_success.clone(),
749            on_error:   self.on_error.clone(),
750            _out:       PhantomData
751        }
752    }
753}
754
755impl Operation<Value> {
756    /// Starts a typed action operation from its `system_id`, HTTP method, and
757    /// path template. Envelope parts are attached with the `with_*` setters,
758    /// which take the typed parts directly — the envelope contract is the typed
759    /// fields passed by name, not keys fished out of a serialized blob. Output
760    /// defaults to [`Value`]; generated actions re-tag it via
761    /// [`Operation::returns`].
762    pub fn action(system_id: impl Into<String>, method: Method, path_template: impl Into<String>) -> Self {
763        Self {
764            system_id: system_id.into(),
765            method,
766            path: path_template.into(),
767            query: Value::Null,
768            headers: BTreeMap::new(),
769            body: Bytes::new(),
770            retry: None,
771            retry_on: Vec::new(),
772            timeout: None,
773            on_success: None,
774            on_error: None,
775            _out: PhantomData
776        }
777    }
778}
779
780impl<Out> Operation<Out> {
781    /// Declares the retry policy for this operation, overriding the client
782    /// default. Part of the description — the engine resolves it.
783    pub fn retry(mut self, schedule: RetrySchedule) -> Self {
784        self.retry = Some(schedule);
785        self
786    }
787
788    /// Adds HTTP status codes that should be retried for this call, on top of
789    /// the always-retried transient set (network errors, 5xx, 429). HTTP-only —
790    /// status classification has no meaning outside an API call.
791    pub fn retry_on(mut self, statuses: impl IntoIterator<Item = StatusCode>) -> Self {
792        self.retry_on = statuses.into_iter().collect();
793        self
794    }
795
796    /// Sets a per-request timeout for this call, overriding the client default.
797    pub fn timeout(mut self, timeout: Duration) -> Self {
798        self.timeout = Some(timeout);
799        self
800    }
801
802    /// Registers a per-call success hook, run in addition to the client's
803    /// global `on_success`.
804    pub fn on_success<F: Fn(&CallResponse) + Send + Sync + 'static>(mut self, hook: F) -> Self {
805        self.on_success = Some(Arc::new(hook));
806        self
807    }
808
809    /// Registers a per-call error hook, run in addition to the client's global
810    /// `on_error`.
811    pub fn on_error<F: Fn(&Error) + Send + Sync + 'static>(mut self, hook: F) -> Self {
812        self.on_error = Some(Arc::new(hook));
813        self
814    }
815
816    /// Re-tags the operation's output type. Generated actions attach the
817    /// io_schema's `Output`; callers can override a wrong synced output.
818    pub fn returns<Out2>(self) -> Operation<Out2> {
819        Operation {
820            system_id:  self.system_id,
821            method:     self.method,
822            path:       self.path,
823            query:      self.query,
824            headers:    self.headers,
825            body:       self.body,
826            retry:      self.retry,
827            retry_on:   self.retry_on,
828            timeout:    self.timeout,
829            on_success: self.on_success,
830            on_error:   self.on_error,
831            _out:       PhantomData
832        }
833    }
834
835    /// Fills the path template's `{{name}}` placeholders from the typed path
836    /// part.
837    pub fn with_path<P: Serialize>(mut self, path: &P) -> Result<Self, Error> {
838        let value = to_value(path).map_err(Error::Decode)?;
839        self.path = Self::resolve_path(&self.path, Some(&value))?;
840        Ok(self)
841    }
842
843    /// Attaches the typed query part; serde lowers it to query parameters.
844    pub fn with_query<Q: Serialize>(mut self, query: &Q) -> Result<Self, Error> {
845        self.query = to_value(query).map_err(Error::Decode)?;
846        Ok(self)
847    }
848
849    /// Attaches the typed headers part as request headers.
850    pub fn with_headers<H: Serialize>(mut self, headers: &H) -> Result<Self, Error> {
851        let value = to_value(headers).map_err(Error::Decode)?;
852        self.headers = Self::string_map(Some(&value));
853        Ok(self)
854    }
855
856    /// Serializes the typed body part as the request payload. An omitted
857    /// optional body (`Option<Body>` left unset) serializes to the literal
858    /// `null`; treat that as "no body" and leave the payload empty so the
859    /// engine omits it rather than sending `null` bytes upstream.
860    pub fn with_body<B: Serialize>(mut self, body: &B) -> Result<Self, Error> {
861        let bytes = to_vec(body).map_err(Error::Decode)?;
862        if bytes != b"null" {
863            self.body = Bytes::from(bytes);
864        }
865        Ok(self)
866    }
867
868    /// Distributes a generated action's flat input into its request parts:
869    /// an unkeyed route supplies the whole part, a keyed route then sets one
870    /// entry of its part, and a field the input leaves out is skipped. A
871    /// required part with nothing set is sent as `{}`, and the path template is
872    /// always rendered, so a missing path value fails here instead of going
873    /// upstream.
874    pub fn with_routed<I: Serialize>(self, input: &I, routing: &Routing) -> Result<Self, Error> {
875        let Value::Object(mut fields) = to_value(input).map_err(Error::Decode)? else {
876            return Err(Error::InvalidInput(NON_OBJECT_INPUT.into()));
877        };
878        let mut parts: BTreeMap<Part, Value> = routing
879            .required_parts
880            .iter()
881            .chain([&Part::Path])
882            .map(|part| (*part, Value::Object(Map::new())))
883            .collect();
884        let (whole, keyed): (Vec<&Route>, Vec<&Route>) = routing.routes.iter().partition(|route| route.key.is_none());
885        for route in whole {
886            if let Some(value) = fields.remove(route.field) {
887                parts.insert(route.part, value);
888            }
889        }
890        for route in keyed {
891            let (Some(key), Some(value)) = (route.key, fields.remove(route.field)) else {
892                continue;
893            };
894            match parts.entry(route.part).or_insert_with(|| Value::Object(Map::new())) {
895                Value::Object(entries) => {
896                    entries.insert(key.to_string(), value);
897                }
898                _ => {
899                    let message = format!("`{}` needs `{key}` set on an object", route.field);
900                    return Err(Error::InvalidInput(message.into()));
901                }
902            }
903        }
904        parts.into_iter().try_fold(self, |operation, (part, value)| match part {
905            Part::Path => operation.with_path(&value),
906            Part::Query => operation.with_query(&value),
907            Part::Headers => operation.with_headers(&value),
908            Part::Body => operation.with_body(&value)
909        })
910    }
911
912    /// Sets the request body to raw bytes, for non-JSON payloads. The typed
913    /// `with_body` is preferred for action calls.
914    pub fn raw_body(mut self, body: impl Into<Bytes>) -> Self {
915        self.body = body.into();
916        self
917    }
918
919    /// Merges extra fields into the request body, on top of the typed body —
920    /// the escape hatch for attributes a stale or incomplete io_schema omits.
921    pub fn merge_body(mut self, extra: Value) -> Result<Self, Error> {
922        let mut body: Value = if self.body.is_empty() {
923            Value::Object(Default::default())
924        } else {
925            from_slice(&self.body).map_err(Error::Decode)?
926        };
927        Self::merge(&mut body, extra);
928        self.body = Bytes::from(to_vec(&body).map_err(Error::Decode)?);
929        Ok(self)
930    }
931
932    /// Merges extra parameters on top of the typed query.
933    pub fn merge_query(mut self, extra: Value) -> Self {
934        Self::merge(&mut self.query, extra);
935        self
936    }
937
938    /// Merges extra headers on top of the typed headers.
939    pub fn merge_headers(mut self, extra: Value) -> Self {
940        if let Value::Object(entries) = extra {
941            for (key, value) in entries {
942                let rendered = value.as_str().map(str::to_string).unwrap_or_else(|| value.to_string());
943                self.headers.insert(key, rendered);
944            }
945        }
946        self
947    }
948
949    /// Removes a header — e.g. to drop one injected from a busted `const`.
950    pub fn remove_header(mut self, name: &str) -> Self {
951        self.headers.retain(|key, _| !key.eq_ignore_ascii_case(name));
952        self
953    }
954
955    /// Removes a query parameter.
956    pub fn remove_query(mut self, name: &str) -> Self {
957        if let Some(object) = self.query.as_object_mut() {
958            object.remove(name);
959        }
960        self
961    }
962
963    /// The action's system id (sent as `X-One-Action-Id`).
964    pub fn system_id(&self) -> &str {
965        &self.system_id
966    }
967
968    /// The resolved HTTP method.
969    pub fn method(&self) -> &Method {
970        &self.method
971    }
972
973    /// The resolved upstream path, with placeholders filled in.
974    pub fn path(&self) -> &str {
975        &self.path
976    }
977
978    /// The resolved query parameters.
979    pub fn query(&self) -> &Value {
980        &self.query
981    }
982
983    /// The resolved request headers, including injected `const` headers.
984    pub fn headers(&self) -> &BTreeMap<String, String> {
985        &self.headers
986    }
987
988    /// The serialized request body.
989    pub fn body(&self) -> &Bytes {
990        &self.body
991    }
992
993    /// Shallow-merges the entries of `extra` into `target` when both are
994    /// objects, or replaces `target` if it was null.
995    fn merge(target: &mut Value, extra: Value) {
996        if target.is_null() {
997            *target = extra;
998        } else if let (Some(base), Value::Object(entries)) = (target.as_object_mut(), extra) {
999            for (key, value) in entries {
1000                base.insert(key, value);
1001            }
1002        }
1003    }
1004
1005    /// Fills a path template from a `path` object, rendering it with the same
1006    /// Handlebars engine the platform uses so every template form resolves the
1007    /// way the server expects: `{{name}}` percent-encodes its value into a
1008    /// single path segment, `{{{name}}}` emits it raw (unescaped), and dotted
1009    /// paths (`{{a.b}}`) resolve into the object. Strict mode: a variable the
1010    /// template references but the path object does not supply is an error —
1011    /// the client renders the final route, so a missing value cannot be filled
1012    /// later; fail fast rather than ship `//` or stray braces upstream.
1013    fn resolve_path(template: &str, path: Option<&Value>) -> Result<String, Error> {
1014        let mut renderer = Handlebars::new();
1015        renderer.set_strict_mode(true);
1016        renderer.register_escape_fn(|raw| utf8_percent_encode(raw, PATH_SEGMENT).to_string());
1017        let context = path.cloned().unwrap_or(Value::Null);
1018        renderer
1019            .render_template(template, &context)
1020            .map_err(|error| Error::PathTemplate(error.to_string()))
1021    }
1022
1023    /// Renders a JSON object into a string map for query params / headers.
1024    fn string_map(object: Option<&Value>) -> BTreeMap<String, String> {
1025        let mut map = BTreeMap::new();
1026        if let Some(Value::Object(entries)) = object {
1027            for (key, value) in entries {
1028                let rendered = value.as_str().map(str::to_string).unwrap_or_else(|| value.to_string());
1029                map.insert(key.clone(), rendered);
1030            }
1031        }
1032        map
1033    }
1034}
1035
1036impl<Out> fmt::Debug for Operation<Out> {
1037    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1038        formatter
1039            .debug_struct("Operation")
1040            .field("system_id", &self.system_id)
1041            .field("method", &self.method.as_str())
1042            .field("path", &self.path)
1043            .field("query", &self.query)
1044            .field("headers", &self.headers)
1045            .field("body", &String::from_utf8_lossy(&self.body))
1046            .finish()
1047    }
1048}
1049
1050/// A connection-scoped handle. The engine ([`ConnectionScope::run`]) executes
1051/// declarative [`Operation`]s against this connection.
1052pub struct ConnectionScope<'a> {
1053    one: &'a One,
1054    key: String
1055}
1056
1057impl ConnectionScope<'_> {
1058    /// The engine: resolves and executes a declarative [`Operation`] against
1059    /// this connection. Signs the request with the secret + connection-key +
1060    /// action-id headers, applies the operation's retry/timeout policy (or the
1061    /// client defaults), retries transient HTTP failures (network, 5xx, 429,
1062    /// and any `retry_on` statuses) honoring `Retry-After`, and fires the
1063    /// client + per-call success/error hooks.
1064    pub async fn run<O: IntoOperation>(&self, operation: O) -> Result<CallResponse<O::Output>, Error> {
1065        let Operation {
1066            system_id,
1067            method,
1068            path,
1069            query,
1070            headers,
1071            body,
1072            retry,
1073            retry_on,
1074            timeout,
1075            on_success,
1076            on_error,
1077            ..
1078        } = operation.into_operation().inspect_err(|error| {
1079            if let Some(hook) = &self.one.on_error {
1080                hook(error);
1081            }
1082        })?;
1083        let retry = retry.unwrap_or(self.one.retry);
1084        let timeout = timeout.or(self.one.timeout);
1085        let url = format!("{}/v1/passthrough/{}", self.one.base_url, path.trim_start_matches('/'));
1086
1087        let response = self
1088            .one
1089            .execute(retry, Some((&on_success, &on_error)), &retry_on, || {
1090                let mut request = self
1091                    .one
1092                    .request(method.clone(), &url)
1093                    .header(CONNECTION_KEY_HEADER, &self.key)
1094                    .header(ACTION_ID_HEADER, &system_id);
1095                if let Some(timeout) = timeout {
1096                    request = request.timeout(timeout);
1097                }
1098                if !body.is_empty() {
1099                    request = request.body(body.clone());
1100                }
1101                if query.as_object().is_some_and(|object| !object.is_empty()) {
1102                    request = request.query(&query);
1103                }
1104                for (name, value) in &headers {
1105                    request = request.header(name.as_str(), value.as_str());
1106                }
1107                request
1108            })
1109            .await;
1110
1111        response.map(|response| response.retype())
1112    }
1113
1114    /// Fetches this connection's record from the vault by key, including its
1115    /// metadata. Returns [`Error::NotFound`] if no connection matches.
1116    ///
1117    /// **The lookup happens within the client's tenant scope, not across every
1118    /// tenant.** A secret key carries its tenant server-side, so this is
1119    /// scope-agnostic for one. A bearer is not: the vault resolves the tenant
1120    /// from the request's headers, so a client built without
1121    /// [`OneBuilder::organization`] looks in the user's personal connections
1122    /// and an organization-owned connection reads as absent.
1123    pub async fn get(&self) -> Result<Connection, Error> {
1124        let url = format!("{}{VAULT_CONNECTIONS_PATH}", self.one.base_url);
1125        let response = self
1126            .one
1127            .request(Method::GET, &url)
1128            .query(&[
1129                (CONNECTION_KEY_PARAM, self.key.as_str()),
1130                (PAGE_PARAM, "1"),
1131                (LIMIT_PARAM, "1")
1132            ])
1133            .send()
1134            .await
1135            .map_err(|error| {
1136                if error.is_timeout() {
1137                    Error::Timeout
1138                } else {
1139                    Error::Transport(error)
1140                }
1141            })?;
1142        let status = response.status();
1143        let body = response.bytes().await.map_err(Error::Body)?;
1144        if !status.is_success() {
1145            return Err(Error::Status { status, body });
1146        }
1147        let page: PaginatedVaultConnectionView = from_slice(&body).map_err(Error::Decode)?;
1148        page.rows.into_iter().next().ok_or(Error::NotFound)
1149    }
1150}
1151
1152#[cfg(test)]
1153mod tests {
1154    use std::env::{remove_var, set_var};
1155
1156    use super::{ACCESS_TOKEN_ENV, Credential, One, SECRET_ENV};
1157
1158    /// Reads the credential `from_env` picks for one pair of variable values,
1159    /// leaving the environment as it found it.
1160    ///
1161    /// **One test drives every case, and the restore is not an assertion's
1162    /// job.** The environment is process-global: two tests setting these
1163    /// concurrently decide each other's outcome under a plain `cargo test`, and
1164    /// a cleanup written after the `assert!` never runs on the failing path
1165    /// that most needs it - leaking the variables into every test that follows.
1166    fn credential_from(secret: Option<&str>, access_token: Option<&str>) -> Option<Credential> {
1167        unsafe {
1168            match secret {
1169                Some(value) => set_var(SECRET_ENV, value),
1170                None => remove_var(SECRET_ENV)
1171            }
1172            match access_token {
1173                Some(value) => set_var(ACCESS_TOKEN_ENV, value),
1174                None => remove_var(ACCESS_TOKEN_ENV)
1175            }
1176        }
1177
1178        let credential = One::from_env().ok().map(|one| one.credential);
1179
1180        unsafe {
1181            remove_var(SECRET_ENV);
1182            remove_var(ACCESS_TOKEN_ENV);
1183        }
1184
1185        credential
1186    }
1187
1188    /// `ONE_SECRET=` left behind in a profile or a compose file is how an
1189    /// environment says *not this one*. It used to shadow the access token
1190    /// beside it and then fail as a missing secret, which reads as "you have
1191    /// configured nothing" to someone who has configured the newer variable.
1192    #[test]
1193    fn test_client_from_env_resolves_the_credential_by_precedence() {
1194        assert!(
1195            matches!(credential_from(Some(""), Some("at_from_env")), Some(Credential::AccessToken(_))),
1196            "a blank legacy secret must not shadow the access token beside it"
1197        );
1198        assert!(
1199            matches!(credential_from(Some("   "), Some("at_from_env")), Some(Credential::AccessToken(_))),
1200            "nor must a whitespace-only one"
1201        );
1202        assert!(
1203            matches!(credential_from(Some("sk_from_env"), Some("at_from_env")), Some(Credential::Secret(_))),
1204            "with both set, the longer-standing variable wins"
1205        );
1206        assert!(
1207            matches!(credential_from(Some("sk_from_env"), None), Some(Credential::Secret(_))),
1208            "and it stands alone"
1209        );
1210        assert!(credential_from(None, None).is_none(), "neither configured is a missing secret, not a client");
1211    }
1212}