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, percent_decode_str, 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 slice::from_ref,
24 sync::{Arc, Once},
25 time::Duration
26};
27
28use rustls::{ClientConfig, RootCertStore, crypto::ring::default_provider};
29use tokio::time::sleep;
30use webpki_roots::TLS_SERVER_ROOTS;
31
32pub use crate::transport::types::PaginatedVaultConnectionViewRowsItem as Connection;
34
35const SECRET_HEADER: &str = "X-One-Secret";
36const BEARER_PREFIX: &str = "Bearer ";
37const CONNECTION_KEY_HEADER: &str = "X-One-Connection-Key";
38const ACTION_ID_HEADER: &str = "X-One-Action-Id";
39const ORGANIZATION_ID_HEADER: &str = "X-One-Organization-Id";
40const PROJECT_ID_HEADER: &str = "X-One-Project-Id";
41const DEFAULT_BASE_URL: &str = "https://api.picaos.com";
42const SECRET_ENV: &str = "ONE_SECRET";
43const ACCESS_TOKEN_ENV: &str = "ONE_ACCESS_TOKEN";
44const BASE_URL_ENV: &str = "ONE_BASE_URL";
45const VAULT_CONNECTIONS_PATH: &str = "/v1/vault/connections";
46const CONNECTION_KEY_PARAM: &str = "key";
47const PAGE_PARAM: &str = "page";
48const LIMIT_PARAM: &str = "limit";
49const APPLICATION_JSON: &str = "application/json";
50const NON_OBJECT_INPUT: &str = "the input must be a JSON object";
51
52pub(crate) const PATH_SEGMENT: &AsciiSet = &NON_ALPHANUMERIC.remove(b'-').remove(b'.').remove(b'_').remove(b'~');
57
58fn configured(key: &str) -> Option<String> {
68 var(key).ok().filter(|value| !value.trim().is_empty())
69}
70
71#[derive(Debug, thiserror::Error)]
76#[non_exhaustive]
77pub enum Error {
78 #[error("transport error: {0}")]
80 Transport(ReqwestError),
81 #[error("request timed out")]
83 Timeout,
84 #[error("failed to read response body: {0}")]
86 Body(ReqwestError),
87 #[error("upstream returned status {status}")]
89 Status { status: StatusCode, body: Bytes },
90 #[error("failed to decode response: {0}")]
92 Decode(JsonError),
93 #[error("no connection found for the given key")]
95 NotFound,
96 #[error(
98 "a credential is required: a secret key (.secret() or ONE_SECRET) or an OAuth access token (.access_token() \
99 or ONE_ACCESS_TOKEN)"
100 )]
101 MissingSecret,
102 #[error("path template error: {0}")]
104 PathTemplate(String),
105 #[error("invalid action input: {0}")]
108 InvalidInput(#[source] Box<dyn StdError + Send + Sync>)
109}
110
111#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
113pub enum Part {
114 Path,
115 Query,
116 Headers,
117 Body
118}
119
120#[derive(Debug, Clone, Copy)]
122pub struct Route {
123 pub field: &'static str,
125 pub part: Part,
127 pub key: Option<&'static str>
129}
130
131#[derive(Debug, Clone, Copy)]
133pub struct Routing {
134 pub routes: &'static [Route],
136 pub required_parts: &'static [Part]
138}
139
140pub trait IntoOperation {
143 type Output;
145
146 fn into_operation(self) -> Result<Operation<Self::Output>, Error>;
148}
149
150impl<Out> IntoOperation for Operation<Out> {
151 type Output = Out;
152
153 fn into_operation(self) -> Result<Self, Error> {
154 Ok(self)
155 }
156}
157
158impl Retryable for Error {
159 fn is_transient(&self) -> bool {
160 match self {
161 Self::Transport(e) => e.is_timeout() || e.is_connect() || e.is_request(),
162 Self::Timeout => true,
163 Self::Status { status, .. } => status.is_server_error() || *status == StatusCode::TOO_MANY_REQUESTS,
164 Self::Body(_)
165 | Self::Decode(_)
166 | Self::NotFound
167 | Self::MissingSecret
168 | Self::PathTemplate(_)
169 | Self::InvalidInput(_) => false
170 }
171 }
172}
173
174pub struct CallResponse<Out = Value> {
179 status: StatusCode,
180 headers: BTreeMap<String, String>,
181 body: Bytes,
182 _out: PhantomData<fn() -> Out>
183}
184
185impl<Out> Clone for CallResponse<Out> {
186 fn clone(&self) -> Self {
187 Self {
188 status: self.status,
189 headers: self.headers.clone(),
190 body: self.body.clone(),
191 _out: PhantomData
192 }
193 }
194}
195
196impl<Out> CallResponse<Out> {
197 pub fn status(&self) -> StatusCode {
199 self.status
200 }
201
202 pub fn headers(&self) -> &BTreeMap<String, String> {
205 &self.headers
206 }
207
208 pub fn bytes(&self) -> &Bytes {
210 &self.body
211 }
212
213 pub fn text(&self) -> String {
215 String::from_utf8_lossy(&self.body).into_owned()
216 }
217
218 pub fn json<T: DeserializeOwned>(&self) -> Result<T, Error> {
221 from_slice(&self.body).map_err(Error::Decode)
222 }
223
224 fn retype<U>(self) -> CallResponse<U> {
227 CallResponse {
228 status: self.status,
229 headers: self.headers,
230 body: self.body,
231 _out: PhantomData
232 }
233 }
234}
235
236impl<Out: DeserializeOwned> CallResponse<Out> {
237 pub fn output(&self) -> Result<Out, Error> {
239 from_slice(&self.body).map_err(Error::Decode)
240 }
241}
242
243type SuccessHook = Arc<dyn Fn(&CallResponse) + Send + Sync>;
244type ErrorHook = Arc<dyn Fn(&Error) + Send + Sync>;
245
246#[derive(Clone)]
256pub enum Credential {
257 Secret(Arc<SecretBox<String>>),
260 AccessToken(Arc<SecretBox<String>>)
264}
265
266impl fmt::Debug for Credential {
267 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
270 match self {
271 Self::Secret(_) => f.write_str("Credential::Secret(<redacted>)"),
272 Self::AccessToken(_) => f.write_str("Credential::AccessToken(<redacted>)")
273 }
274 }
275}
276
277impl Credential {
278 pub fn secret(secret: impl Into<String>) -> Self {
280 Self::Secret(Arc::new(SecretBox::new(Box::new(secret.into()))))
281 }
282
283 pub fn access_token(token: impl Into<String>) -> Self {
285 Self::AccessToken(Arc::new(SecretBox::new(Box::new(token.into()))))
286 }
287
288 fn apply(&self, request: RequestBuilder) -> RequestBuilder {
291 match self {
292 Self::Secret(secret) => request.header(SECRET_HEADER, secret.expose_secret()),
293 Self::AccessToken(token) => {
294 request.header(AUTHORIZATION, format!("{BEARER_PREFIX}{}", token.expose_secret()))
295 }
296 }
297 }
298
299 fn is_empty(&self) -> bool {
307 match self {
308 Self::Secret(value) | Self::AccessToken(value) => value.expose_secret().trim().is_empty()
309 }
310 }
311}
312
313#[derive(Clone, Debug, Default)]
324pub struct Tenancy {
325 organization: Option<String>,
326 project: Option<String>
327}
328
329impl Tenancy {
330 fn apply(&self, request: RequestBuilder) -> RequestBuilder {
332 let request = match &self.organization {
333 Some(id) => request.header(ORGANIZATION_ID_HEADER, id),
334 None => request
335 };
336 match &self.project {
337 Some(id) => request.header(PROJECT_ID_HEADER, id),
338 None => request
339 }
340 }
341}
342
343#[derive(Clone)]
348pub struct One {
349 http: HttpClient,
350 base_url: String,
351 credential: Credential,
352 tenancy: Tenancy,
353 retry: RetrySchedule,
354 timeout: Option<Duration>,
355 on_success: Option<SuccessHook>,
356 on_error: Option<ErrorHook>
357}
358
359impl One {
360 fn request(&self, method: Method, url: &str) -> RequestBuilder {
367 self.tenancy
368 .apply(self.credential.apply(self.http.request(method, url)))
369 }
370
371 pub fn new(secret: impl Into<String>) -> Self {
375 Self::builder()
376 .secret(secret)
377 .build()
378 .expect("One::new requires a non-empty secret")
379 }
380
381 pub fn from_env() -> Result<Self, Error> {
390 let credential = configured(SECRET_ENV)
391 .map(Credential::secret)
392 .or_else(|| configured(ACCESS_TOKEN_ENV).map(Credential::access_token))
393 .ok_or(Error::MissingSecret)?;
394
395 let mut builder = Self::builder().credential(credential);
396 if let Some(base_url) = configured(BASE_URL_ENV) {
397 builder = builder.base_url(base_url);
398 }
399 builder.build()
400 }
401
402 pub fn builder() -> OneBuilder {
404 OneBuilder::default()
405 }
406
407 pub fn connection(&self, key: impl Into<String>) -> ConnectionScope<'_> {
409 ConnectionScope {
410 one: self,
411 key: key.into()
412 }
413 }
414
415 pub fn webhooks(&self, signing_secret: SecretString) -> Webhooks {
420 Webhooks::new(self.clone(), signing_secret)
421 }
422
423 pub(crate) async fn put_json_response<B: Serialize, Out>(
426 &self,
427 path: &str,
428 body: &B
429 ) -> Result<CallResponse<Out>, Error> {
430 let url = format!("{}{path}", self.base_url);
431 let payload = to_vec(body).map_err(Error::Decode)?;
432
433 let response = self
434 .execute(self.retry, None, &[], || {
435 let mut request = self
436 .request(Method::PUT, &url)
437 .header(CONTENT_TYPE, APPLICATION_JSON)
438 .body(payload.clone());
439 if let Some(timeout) = self.timeout {
440 request = request.timeout(timeout);
441 }
442 request
443 })
444 .await?;
445
446 Ok(response.retype())
447 }
448
449 pub(crate) async fn execute<F>(
456 &self,
457 retry: RetrySchedule,
458 on_call: Option<(&Option<SuccessHook>, &Option<ErrorHook>)>,
459 retry_on: &[StatusCode],
460 build: F
461 ) -> Result<CallResponse<Value>, Error>
462 where
463 F: Fn() -> reqwest::RequestBuilder
464 {
465 let send = || {
466 let request = build();
467 async move {
468 let response = match request.send().await {
469 Ok(response) => response,
470 Err(error) => {
471 let mapped = if error.is_timeout() {
472 Error::Timeout
473 } else {
474 Error::Transport(error)
475 };
476 return Err((mapped, None));
477 }
478 };
479 let status = response.status();
480 let headers: BTreeMap<String, String> = response
481 .headers()
482 .iter()
483 .filter_map(|(name, value)| {
484 value
485 .to_str()
486 .ok()
487 .map(|value| (name.as_str().to_string(), value.to_string()))
488 })
489 .collect();
490 let retry_after = Self::retry_after(response.headers());
491 let body = match response.bytes().await {
492 Ok(body) => body,
493 Err(error) => return Err((Error::Body(error), None))
494 };
495 if status.is_success() {
496 Ok(CallResponse {
497 status,
498 headers,
499 body,
500 _out: PhantomData
501 })
502 } else {
503 Err((Error::Status { status, body }, retry_after))
504 }
505 }
506 };
507
508 let attempts = retry.max_attempts.max(1);
509 let result: Result<CallResponse<Value>, Error> = 'attempts: {
510 for attempt in 1..=attempts {
511 match send().await {
512 Ok(response) => break 'attempts Ok(response),
513 Err((error, retry_after)) => {
514 if attempt == attempts || !Self::is_retryable(&error, retry_on) {
515 break 'attempts Err(error);
516 }
517 sleep(retry_after.unwrap_or_else(|| retry.delay(attempt))).await;
518 }
519 }
520 }
521 unreachable!("loop runs at least once and breaks on every path")
522 };
523
524 match &result {
525 Ok(response) => {
526 if let Some(hook) = &self.on_success {
527 hook(response);
528 }
529 if let Some(hook) = on_call.and_then(|(success, _)| success.as_ref()) {
530 hook(response);
531 }
532 }
533 Err(error) => self.notify_error(on_call.and_then(|(_, failure)| failure.as_ref()), error)
534 }
535
536 result
537 }
538
539 fn notify_error(&self, per_call: Option<&ErrorHook>, error: &Error) {
541 for hook in [self.on_error.as_ref(), per_call].into_iter().flatten() {
542 hook(error);
543 }
544 }
545
546 fn is_retryable(error: &Error, retry_on: &[StatusCode]) -> bool {
549 error.is_transient() || matches!(error, Error::Status { status, .. } if retry_on.contains(status))
550 }
551
552 fn retry_after(headers: &HeaderMap) -> Option<Duration> {
554 headers
555 .get(RETRY_AFTER)?
556 .to_str()
557 .ok()?
558 .trim()
559 .parse::<u64>()
560 .ok()
561 .map(Duration::from_secs)
562 }
563}
564
565#[derive(Default)]
567pub struct OneBuilder {
568 base_url: Option<String>,
569 credential: Option<Credential>,
570 tenancy: Tenancy,
571 retry: Option<RetrySchedule>,
572 timeout: Option<Duration>,
573 on_success: Option<SuccessHook>,
574 on_error: Option<ErrorHook>
575}
576
577impl OneBuilder {
578 pub fn secret(mut self, secret: impl Into<String>) -> Self {
580 self.credential = Some(Credential::secret(secret));
581 self
582 }
583
584 pub fn credential(mut self, credential: Credential) -> Self {
587 self.credential = Some(credential);
588 self
589 }
590
591 pub fn organization(mut self, organization_id: impl Into<String>) -> Self {
600 self.tenancy.organization = Some(organization_id.into());
601 self
602 }
603
604 pub fn project(mut self, project_id: impl Into<String>) -> Self {
610 self.tenancy.project = Some(project_id.into());
611 self
612 }
613
614 pub fn access_token(mut self, token: impl Into<String>) -> Self {
621 self.credential = Some(Credential::access_token(token));
622 self
623 }
624
625 pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
627 self.base_url = Some(base_url.into());
628 self
629 }
630
631 pub fn retry(mut self, schedule: RetrySchedule) -> Self {
634 self.retry = Some(schedule);
635 self
636 }
637
638 pub fn timeout(mut self, timeout: Duration) -> Self {
641 self.timeout = Some(timeout);
642 self
643 }
644
645 pub fn on_success<F: Fn(&CallResponse) + Send + Sync + 'static>(mut self, hook: F) -> Self {
647 self.on_success = Some(Arc::new(hook));
648 self
649 }
650
651 pub fn on_error<F: Fn(&Error) + Send + Sync + 'static>(mut self, hook: F) -> Self {
653 self.on_error = Some(Arc::new(hook));
654 self
655 }
656
657 pub fn build(self) -> Result<One, Error> {
666 let credential = self
667 .credential
668 .filter(|credential| !credential.is_empty())
669 .ok_or(Error::MissingSecret)?;
670 Self::ensure_crypto_provider();
671 let http = HttpClient::builder()
672 .use_preconfigured_tls(Self::tls_config())
673 .build()
674 .map_err(Error::Transport)?;
675 Ok(One {
676 http,
677 base_url: self
678 .base_url
679 .unwrap_or_else(|| DEFAULT_BASE_URL.to_string())
680 .trim_end_matches('/')
681 .to_string(),
682 credential,
683 tenancy: self.tenancy,
684 retry: self.retry.unwrap_or_default(),
685 timeout: self.timeout,
686 on_success: self.on_success,
687 on_error: self.on_error
688 })
689 }
690
691 fn ensure_crypto_provider() {
696 static ONCE: Once = Once::new();
697 ONCE.call_once(|| {
698 let _ = default_provider().install_default();
699 });
700 }
701
702 fn tls_config() -> ClientConfig {
706 let roots = RootCertStore {
707 roots: TLS_SERVER_ROOTS.to_vec()
708 };
709 ClientConfig::builder()
710 .with_root_certificates(roots)
711 .with_no_client_auth()
712 }
713}
714
715pub struct Operation<Out = Value> {
723 system_id: String,
724 method: Method,
725 path: String,
726 query: Value,
727 headers: BTreeMap<String, String>,
728 body: Bytes,
729 retry: Option<RetrySchedule>,
730 retry_on: Vec<StatusCode>,
731 timeout: Option<Duration>,
732 on_success: Option<SuccessHook>,
733 on_error: Option<ErrorHook>,
734 _out: PhantomData<fn() -> Out>
735}
736
737impl<Out> Clone for Operation<Out> {
738 fn clone(&self) -> Self {
739 Self {
740 system_id: self.system_id.clone(),
741 method: self.method.clone(),
742 path: self.path.clone(),
743 query: self.query.clone(),
744 headers: self.headers.clone(),
745 body: self.body.clone(),
746 retry: self.retry,
747 retry_on: self.retry_on.clone(),
748 timeout: self.timeout,
749 on_success: self.on_success.clone(),
750 on_error: self.on_error.clone(),
751 _out: PhantomData
752 }
753 }
754}
755
756impl Operation<Value> {
757 pub fn action(system_id: impl Into<String>, method: Method, path_template: impl Into<String>) -> Self {
764 Self {
765 system_id: system_id.into(),
766 method,
767 path: path_template.into(),
768 query: Value::Null,
769 headers: BTreeMap::new(),
770 body: Bytes::new(),
771 retry: None,
772 retry_on: Vec::new(),
773 timeout: None,
774 on_success: None,
775 on_error: None,
776 _out: PhantomData
777 }
778 }
779}
780
781impl<Out> Operation<Out> {
782 pub fn retry(mut self, schedule: RetrySchedule) -> Self {
785 self.retry = Some(schedule);
786 self
787 }
788
789 pub fn retry_on(mut self, statuses: impl IntoIterator<Item = StatusCode>) -> Self {
793 self.retry_on = statuses.into_iter().collect();
794 self
795 }
796
797 pub fn timeout(mut self, timeout: Duration) -> Self {
799 self.timeout = Some(timeout);
800 self
801 }
802
803 pub fn on_success<F: Fn(&CallResponse) + Send + Sync + 'static>(mut self, hook: F) -> Self {
806 self.on_success = Some(Arc::new(hook));
807 self
808 }
809
810 pub fn on_error<F: Fn(&Error) + Send + Sync + 'static>(mut self, hook: F) -> Self {
813 self.on_error = Some(Arc::new(hook));
814 self
815 }
816
817 pub fn returns<Out2>(self) -> Operation<Out2> {
820 Operation {
821 system_id: self.system_id,
822 method: self.method,
823 path: self.path,
824 query: self.query,
825 headers: self.headers,
826 body: self.body,
827 retry: self.retry,
828 retry_on: self.retry_on,
829 timeout: self.timeout,
830 on_success: self.on_success,
831 on_error: self.on_error,
832 _out: PhantomData
833 }
834 }
835
836 pub fn with_path<P: Serialize>(mut self, path: &P) -> Result<Self, Error> {
839 let value = to_value(path).map_err(Error::Decode)?;
840 self.path = Self::resolve_path(&self.path, Some(&value))?;
841 Ok(self)
842 }
843
844 pub fn with_query<Q: Serialize>(mut self, query: &Q) -> Result<Self, Error> {
846 self.query = to_value(query).map_err(Error::Decode)?;
847 Ok(self)
848 }
849
850 pub fn with_headers<H: Serialize>(mut self, headers: &H) -> Result<Self, Error> {
852 let value = to_value(headers).map_err(Error::Decode)?;
853 self.headers = header_map(&value);
854 Ok(self)
855 }
856
857 pub fn with_body<B: Serialize>(mut self, body: &B) -> Result<Self, Error> {
862 let bytes = to_vec(body).map_err(Error::Decode)?;
863 if bytes != b"null" {
864 self.body = Bytes::from(bytes);
865 }
866 Ok(self)
867 }
868
869 pub fn with_routed<I: Serialize>(self, input: &I, routing: &Routing) -> Result<Self, Error> {
876 let Value::Object(mut fields) = to_value(input).map_err(Error::Decode)? else {
877 return Err(Error::InvalidInput(NON_OBJECT_INPUT.into()));
878 };
879 let mut parts: BTreeMap<Part, Value> = routing
880 .required_parts
881 .iter()
882 .chain([&Part::Path])
883 .map(|part| (*part, Value::Object(Map::new())))
884 .collect();
885 let (whole, keyed): (Vec<&Route>, Vec<&Route>) = routing.routes.iter().partition(|route| route.key.is_none());
886 for route in whole {
887 if let Some(value) = fields.remove(route.field) {
888 parts.insert(route.part, value);
889 }
890 }
891 for route in keyed {
892 let (Some(key), Some(value)) = (route.key, fields.remove(route.field)) else {
893 continue;
894 };
895 match parts.entry(route.part).or_insert_with(|| Value::Object(Map::new())) {
896 Value::Object(entries) => {
897 entries.insert(key.to_string(), value);
898 }
899 _ => {
900 let message = format!("`{}` needs `{key}` set on an object", route.field);
901 return Err(Error::InvalidInput(message.into()));
902 }
903 }
904 }
905 parts.into_iter().try_fold(self, |operation, (part, value)| match part {
906 Part::Path => operation.with_path(&value),
907 Part::Query => operation.with_query(&value),
908 Part::Headers => operation.with_headers(&value),
909 Part::Body => operation.with_body(&value)
910 })
911 }
912
913 pub fn raw_body(mut self, body: impl Into<Bytes>) -> Self {
916 self.body = body.into();
917 self
918 }
919
920 pub fn merge_body(mut self, extra: Value) -> Result<Self, Error> {
923 let mut body: Value = if self.body.is_empty() {
924 Value::Object(Default::default())
925 } else {
926 from_slice(&self.body).map_err(Error::Decode)?
927 };
928 Self::merge(&mut body, extra);
929 self.body = Bytes::from(to_vec(&body).map_err(Error::Decode)?);
930 Ok(self)
931 }
932
933 pub fn merge_query(mut self, extra: Value) -> Self {
935 Self::merge(&mut self.query, extra);
936 self
937 }
938
939 pub fn merge_headers(mut self, extra: Value) -> Self {
943 if let Value::Object(entries) = extra {
944 for (key, value) in entries {
945 self.headers.retain(|name, _| !name.eq_ignore_ascii_case(&key));
946 if let Some(rendered) = header_value(&value) {
947 self.headers.insert(key, rendered);
948 }
949 }
950 }
951 self
952 }
953
954 pub fn remove_header(mut self, name: &str) -> Self {
956 self.headers.retain(|key, _| !key.eq_ignore_ascii_case(name));
957 self
958 }
959
960 pub fn remove_query(mut self, name: &str) -> Self {
962 if let Some(object) = self.query.as_object_mut() {
963 object.remove(name);
964 }
965 self
966 }
967
968 pub fn system_id(&self) -> &str {
970 &self.system_id
971 }
972
973 pub fn method(&self) -> &Method {
975 &self.method
976 }
977
978 pub fn path(&self) -> &str {
980 &self.path
981 }
982
983 pub fn query(&self) -> &Value {
985 &self.query
986 }
987
988 pub fn headers(&self) -> &BTreeMap<String, String> {
990 &self.headers
991 }
992
993 pub fn body(&self) -> &Bytes {
995 &self.body
996 }
997
998 fn merge(target: &mut Value, extra: Value) {
1001 if target.is_null() {
1002 *target = extra;
1003 } else if let (Some(base), Value::Object(entries)) = (target.as_object_mut(), extra) {
1004 for (key, value) in entries {
1005 base.insert(key, value);
1006 }
1007 }
1008 }
1009
1010 fn resolve_path(template: &str, path: Option<&Value>) -> Result<String, Error> {
1019 let mut renderer = Handlebars::new();
1020 renderer.set_strict_mode(true);
1021 renderer.register_escape_fn(|raw| utf8_percent_encode(raw, PATH_SEGMENT).to_string());
1022 let context = path.cloned().unwrap_or(Value::Null);
1023 renderer
1024 .render_template(template, &context)
1025 .map_err(|error| Error::PathTemplate(error.to_string()))
1026 }
1027}
1028
1029impl<Out> fmt::Debug for Operation<Out> {
1030 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1031 formatter
1032 .debug_struct("Operation")
1033 .field("system_id", &self.system_id)
1034 .field("method", &self.method.as_str())
1035 .field("path", &self.path)
1036 .field("query", &self.query)
1037 .field("headers", &self.headers)
1038 .field("body", &String::from_utf8_lossy(&self.body))
1039 .finish()
1040 }
1041}
1042
1043pub struct ConnectionScope<'a> {
1046 one: &'a One,
1047 key: String
1048}
1049
1050impl ConnectionScope<'_> {
1051 pub async fn run<O: IntoOperation>(&self, operation: O) -> Result<CallResponse<O::Output>, Error> {
1058 let operation = operation
1059 .into_operation()
1060 .inspect_err(|error| self.one.notify_error(None, error))?;
1061 let query = query_pairs(&operation.query)
1062 .inspect_err(|error| self.one.notify_error(operation.on_error.as_ref(), error))?;
1063 let Operation {
1064 system_id,
1065 method,
1066 path,
1067 headers,
1068 body,
1069 retry,
1070 retry_on,
1071 timeout,
1072 on_success,
1073 on_error,
1074 ..
1075 } = operation;
1076 let retry = retry.unwrap_or(self.one.retry);
1077 let timeout = timeout.or(self.one.timeout);
1078 let url =
1079 format!("{}/v1/passthrough/{}", self.one.base_url, without_replaced(&path, &query).trim_start_matches('/'));
1080
1081 let response = self
1082 .one
1083 .execute(retry, Some((&on_success, &on_error)), &retry_on, || {
1084 let mut request = self
1085 .one
1086 .request(method.clone(), &url)
1087 .header(CONNECTION_KEY_HEADER, &self.key)
1088 .header(ACTION_ID_HEADER, &system_id);
1089 if let Some(timeout) = timeout {
1090 request = request.timeout(timeout);
1091 }
1092 if !body.is_empty() {
1093 request = request.body(body.clone());
1094 }
1095 if !query.is_empty() {
1096 request = request.query(&query);
1097 }
1098 for (name, value) in &headers {
1099 request = request.header(name.as_str(), value.as_str());
1100 }
1101 request
1102 })
1103 .await;
1104
1105 response.map(|response| response.retype())
1106 }
1107
1108 pub async fn get(&self) -> Result<Connection, Error> {
1118 let url = format!("{}{VAULT_CONNECTIONS_PATH}", self.one.base_url);
1119 let response = self
1120 .one
1121 .request(Method::GET, &url)
1122 .query(&[
1123 (CONNECTION_KEY_PARAM, self.key.as_str()),
1124 (PAGE_PARAM, "1"),
1125 (LIMIT_PARAM, "1")
1126 ])
1127 .send()
1128 .await
1129 .map_err(|error| {
1130 if error.is_timeout() {
1131 Error::Timeout
1132 } else {
1133 Error::Transport(error)
1134 }
1135 })?;
1136 let status = response.status();
1137 let body = response.bytes().await.map_err(Error::Body)?;
1138 if !status.is_success() {
1139 return Err(Error::Status { status, body });
1140 }
1141 let page: PaginatedVaultConnectionView = from_slice(&body).map_err(Error::Decode)?;
1142 page.rows.into_iter().next().ok_or(Error::NotFound)
1143 }
1144}
1145
1146fn header_map(object: &Value) -> BTreeMap<String, String> {
1148 object
1149 .as_object()
1150 .into_iter()
1151 .flatten()
1152 .filter_map(|(key, value)| header_value(value).map(|rendered| (key.clone(), rendered)))
1153 .collect()
1154}
1155
1156fn header_value(value: &Value) -> Option<String> {
1160 match value {
1161 Value::Null => None,
1162 Value::Array(items) => Some(
1163 items
1164 .iter()
1165 .filter(|item| !item.is_null())
1166 .map(rendered)
1167 .collect::<Vec<_>>()
1168 .join(",")
1169 ),
1170 single => Some(rendered(single))
1171 }
1172}
1173
1174fn query_pairs(query: &Value) -> Result<Vec<(String, String)>, Error> {
1179 query
1180 .as_object()
1181 .into_iter()
1182 .flatten()
1183 .flat_map(|(name, value)| {
1184 let items = match value {
1185 Value::Array(items) => items.as_slice(),
1186 single => from_ref(single)
1187 };
1188 items.iter().filter(|item| !item.is_null()).map(move |item| match item {
1189 Value::Object(_) | Value::Array(_) => Err(Error::InvalidInput(
1190 format!("query parameter `{name}` holds a nested value, which has no query encoding").into()
1191 )),
1192 scalar => Ok((name.clone(), rendered(scalar)))
1193 })
1194 })
1195 .collect()
1196}
1197
1198fn without_replaced(path: &str, query: &[(String, String)]) -> String {
1203 let path = path.split('#').next().unwrap_or_default();
1204 let Some((route, own)) = path.split_once('?') else {
1205 return path.to_string();
1206 };
1207 let key = |piece: &str| {
1208 let raw = piece.split('=').next().unwrap_or_default().replace('+', " ");
1209 percent_decode_str(&raw).decode_utf8_lossy().into_owned()
1210 };
1211 let replaced = |piece: &&str| query.iter().any(|(name, _)| *name == key(piece));
1212 let kept = own
1213 .split('&')
1214 .map(|pair| {
1215 pair.split(';')
1216 .filter(|piece| !piece.is_empty() && !replaced(piece))
1217 .collect::<Vec<_>>()
1218 .join(";")
1219 })
1220 .filter(|pair| !pair.is_empty())
1221 .collect::<Vec<_>>()
1222 .join("&");
1223 match kept.is_empty() {
1224 true => route.to_string(),
1225 false => format!("{route}?{kept}")
1226 }
1227}
1228
1229fn rendered(value: &Value) -> String {
1231 value.as_str().map(str::to_string).unwrap_or_else(|| value.to_string())
1232}
1233
1234#[cfg(test)]
1235mod tests {
1236 use std::env::{remove_var, set_var};
1237
1238 use super::{ACCESS_TOKEN_ENV, Credential, One, SECRET_ENV, without_replaced};
1239
1240 #[test]
1241 fn test_client_without_replaced_drops_the_templates_pair_a_caller_sets() {
1242 let query = [("attributes".to_string(), "id".to_string())];
1243 assert_eq!(without_replaced("/contacts/1?attributes=all&v=2", &query), "/contacts/1?v=2");
1244 assert_eq!(without_replaced("/contacts/1?attributes=all", &query), "/contacts/1");
1245 assert_eq!(without_replaced("/contacts/1?a%74tributes=all&v", &query), "/contacts/1?v");
1246 assert_eq!(without_replaced("/contacts/1", &query), "/contacts/1");
1247 assert_eq!(without_replaced("/contacts/1?v=2", &[]), "/contacts/1?v=2");
1248 assert_eq!(without_replaced("/contacts/1?x=1;attributes=all", &query), "/contacts/1?x=1");
1249 assert_eq!(without_replaced("/contacts/1?v=2&attributes#stream", &query), "/contacts/1?v=2");
1250 }
1251
1252 fn credential_from(secret: Option<&str>, access_token: Option<&str>) -> Option<Credential> {
1261 unsafe {
1262 match secret {
1263 Some(value) => set_var(SECRET_ENV, value),
1264 None => remove_var(SECRET_ENV)
1265 }
1266 match access_token {
1267 Some(value) => set_var(ACCESS_TOKEN_ENV, value),
1268 None => remove_var(ACCESS_TOKEN_ENV)
1269 }
1270 }
1271
1272 let credential = One::from_env().ok().map(|one| one.credential);
1273
1274 unsafe {
1275 remove_var(SECRET_ENV);
1276 remove_var(ACCESS_TOKEN_ENV);
1277 }
1278
1279 credential
1280 }
1281
1282 #[test]
1287 fn test_client_from_env_resolves_the_credential_by_precedence() {
1288 assert!(
1289 matches!(credential_from(Some(""), Some("at_from_env")), Some(Credential::AccessToken(_))),
1290 "a blank legacy secret must not shadow the access token beside it"
1291 );
1292 assert!(
1293 matches!(credential_from(Some(" "), Some("at_from_env")), Some(Credential::AccessToken(_))),
1294 "nor must a whitespace-only one"
1295 );
1296 assert!(
1297 matches!(credential_from(Some("sk_from_env"), Some("at_from_env")), Some(Credential::Secret(_))),
1298 "with both set, the longer-standing variable wins"
1299 );
1300 assert!(
1301 matches!(credential_from(Some("sk_from_env"), None), Some(Credential::Secret(_))),
1302 "and it stands alone"
1303 );
1304 assert!(credential_from(None, None).is_none(), "neither configured is a missing secret, not a client");
1305 }
1306}