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
31pub 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
51pub(crate) const PATH_SEGMENT: &AsciiSet = &NON_ALPHANUMERIC.remove(b'-').remove(b'.').remove(b'_').remove(b'~');
56
57fn configured(key: &str) -> Option<String> {
67 var(key).ok().filter(|value| !value.trim().is_empty())
68}
69
70#[derive(Debug, thiserror::Error)]
75#[non_exhaustive]
76pub enum Error {
77 #[error("transport error: {0}")]
79 Transport(ReqwestError),
80 #[error("request timed out")]
82 Timeout,
83 #[error("failed to read response body: {0}")]
85 Body(ReqwestError),
86 #[error("upstream returned status {status}")]
88 Status { status: StatusCode, body: Bytes },
89 #[error("failed to decode response: {0}")]
91 Decode(JsonError),
92 #[error("no connection found for the given key")]
94 NotFound,
95 #[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 #[error("path template error: {0}")]
103 PathTemplate(String),
104 #[error("invalid action input: {0}")]
107 InvalidInput(#[source] Box<dyn StdError + Send + Sync>)
108}
109
110#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
112pub enum Part {
113 Path,
114 Query,
115 Headers,
116 Body
117}
118
119#[derive(Debug, Clone, Copy)]
121pub struct Route {
122 pub field: &'static str,
124 pub part: Part,
126 pub key: Option<&'static str>
128}
129
130#[derive(Debug, Clone, Copy)]
132pub struct Routing {
133 pub routes: &'static [Route],
135 pub required_parts: &'static [Part]
137}
138
139pub trait IntoOperation {
142 type Output;
144
145 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
173pub 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 pub fn status(&self) -> StatusCode {
198 self.status
199 }
200
201 pub fn headers(&self) -> &BTreeMap<String, String> {
204 &self.headers
205 }
206
207 pub fn bytes(&self) -> &Bytes {
209 &self.body
210 }
211
212 pub fn text(&self) -> String {
214 String::from_utf8_lossy(&self.body).into_owned()
215 }
216
217 pub fn json<T: DeserializeOwned>(&self) -> Result<T, Error> {
220 from_slice(&self.body).map_err(Error::Decode)
221 }
222
223 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 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#[derive(Clone)]
255pub enum Credential {
256 Secret(Arc<SecretBox<String>>),
259 AccessToken(Arc<SecretBox<String>>)
263}
264
265impl fmt::Debug for Credential {
266 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 pub fn secret(secret: impl Into<String>) -> Self {
279 Self::Secret(Arc::new(SecretBox::new(Box::new(secret.into()))))
280 }
281
282 pub fn access_token(token: impl Into<String>) -> Self {
284 Self::AccessToken(Arc::new(SecretBox::new(Box::new(token.into()))))
285 }
286
287 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 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#[derive(Clone, Debug, Default)]
323pub struct Tenancy {
324 organization: Option<String>,
325 project: Option<String>
326}
327
328impl Tenancy {
329 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#[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 fn request(&self, method: Method, url: &str) -> RequestBuilder {
366 self.tenancy
367 .apply(self.credential.apply(self.http.request(method, url)))
368 }
369
370 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 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 pub fn builder() -> OneBuilder {
403 OneBuilder::default()
404 }
405
406 pub fn connection(&self, key: impl Into<String>) -> ConnectionScope<'_> {
408 ConnectionScope {
409 one: self,
410 key: key.into()
411 }
412 }
413
414 pub fn webhooks(&self, signing_secret: SecretString) -> Webhooks {
419 Webhooks::new(self.clone(), signing_secret)
420 }
421
422 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 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 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 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#[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 pub fn secret(mut self, secret: impl Into<String>) -> Self {
579 self.credential = Some(Credential::secret(secret));
580 self
581 }
582
583 pub fn credential(mut self, credential: Credential) -> Self {
586 self.credential = Some(credential);
587 self
588 }
589
590 pub fn organization(mut self, organization_id: impl Into<String>) -> Self {
599 self.tenancy.organization = Some(organization_id.into());
600 self
601 }
602
603 pub fn project(mut self, project_id: impl Into<String>) -> Self {
609 self.tenancy.project = Some(project_id.into());
610 self
611 }
612
613 pub fn access_token(mut self, token: impl Into<String>) -> Self {
620 self.credential = Some(Credential::access_token(token));
621 self
622 }
623
624 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 pub fn retry(mut self, schedule: RetrySchedule) -> Self {
633 self.retry = Some(schedule);
634 self
635 }
636
637 pub fn timeout(mut self, timeout: Duration) -> Self {
640 self.timeout = Some(timeout);
641 self
642 }
643
644 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 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 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 fn ensure_crypto_provider() {
695 static ONCE: Once = Once::new();
696 ONCE.call_once(|| {
697 let _ = default_provider().install_default();
698 });
699 }
700
701 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
714pub 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 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 pub fn retry(mut self, schedule: RetrySchedule) -> Self {
784 self.retry = Some(schedule);
785 self
786 }
787
788 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 pub fn timeout(mut self, timeout: Duration) -> Self {
798 self.timeout = Some(timeout);
799 self
800 }
801
802 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 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 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 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 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 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 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 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 pub fn raw_body(mut self, body: impl Into<Bytes>) -> Self {
915 self.body = body.into();
916 self
917 }
918
919 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 pub fn merge_query(mut self, extra: Value) -> Self {
934 Self::merge(&mut self.query, extra);
935 self
936 }
937
938 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 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 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 pub fn system_id(&self) -> &str {
965 &self.system_id
966 }
967
968 pub fn method(&self) -> &Method {
970 &self.method
971 }
972
973 pub fn path(&self) -> &str {
975 &self.path
976 }
977
978 pub fn query(&self) -> &Value {
980 &self.query
981 }
982
983 pub fn headers(&self) -> &BTreeMap<String, String> {
985 &self.headers
986 }
987
988 pub fn body(&self) -> &Bytes {
990 &self.body
991 }
992
993 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 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 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
1050pub struct ConnectionScope<'a> {
1053 one: &'a One,
1054 key: String
1055}
1056
1057impl ConnectionScope<'_> {
1058 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 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 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 #[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}