use crate::{
retry::{RetrySchedule, Retryable},
transport::types::PaginatedVaultConnectionView,
webhooks::Webhooks
};
use bytes::Bytes;
use handlebars::Handlebars;
use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, percent_decode_str, utf8_percent_encode};
use reqwest::{
Client as HttpClient, Error as ReqwestError, RequestBuilder,
header::{AUTHORIZATION, CONTENT_TYPE, HeaderMap, RETRY_AFTER}
};
pub use reqwest::{Method, StatusCode};
use secrecy::{ExposeSecret, SecretBox, SecretString};
use serde::{Serialize, de::DeserializeOwned};
use serde_json::{Error as JsonError, Map, Value, from_slice, to_value, to_vec};
use std::{
collections::BTreeMap,
env::var,
error::Error as StdError,
fmt,
marker::PhantomData,
slice::from_ref,
sync::{Arc, Once},
time::Duration
};
use rustls::{ClientConfig, RootCertStore, crypto::ring::default_provider};
use tokio::time::sleep;
use webpki_roots::TLS_SERVER_ROOTS;
pub use crate::transport::types::PaginatedVaultConnectionViewRowsItem as Connection;
const SECRET_HEADER: &str = "X-One-Secret";
const BEARER_PREFIX: &str = "Bearer ";
const CONNECTION_KEY_HEADER: &str = "X-One-Connection-Key";
const ACTION_ID_HEADER: &str = "X-One-Action-Id";
const ORGANIZATION_ID_HEADER: &str = "X-One-Organization-Id";
const PROJECT_ID_HEADER: &str = "X-One-Project-Id";
const DEFAULT_BASE_URL: &str = "https://api.picaos.com";
const SECRET_ENV: &str = "ONE_SECRET";
const ACCESS_TOKEN_ENV: &str = "ONE_ACCESS_TOKEN";
const BASE_URL_ENV: &str = "ONE_BASE_URL";
const VAULT_CONNECTIONS_PATH: &str = "/v1/vault/connections";
const CONNECTION_KEY_PARAM: &str = "key";
const PAGE_PARAM: &str = "page";
const LIMIT_PARAM: &str = "limit";
const APPLICATION_JSON: &str = "application/json";
const NON_OBJECT_INPUT: &str = "the input must be a JSON object";
pub(crate) const PATH_SEGMENT: &AsciiSet = &NON_ALPHANUMERIC.remove(b'-').remove(b'.').remove(b'_').remove(b'~');
fn configured(key: &str) -> Option<String> {
var(key).ok().filter(|value| !value.trim().is_empty())
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
#[error("transport error: {0}")]
Transport(ReqwestError),
#[error("request timed out")]
Timeout,
#[error("failed to read response body: {0}")]
Body(ReqwestError),
#[error("upstream returned status {status}")]
Status { status: StatusCode, body: Bytes },
#[error("failed to decode response: {0}")]
Decode(JsonError),
#[error("no connection found for the given key")]
NotFound,
#[error(
"a credential is required: a secret key (.secret() or ONE_SECRET) or an OAuth access token (.access_token() \
or ONE_ACCESS_TOKEN)"
)]
MissingSecret,
#[error("path template error: {0}")]
PathTemplate(String),
#[error("invalid action input: {0}")]
InvalidInput(#[source] Box<dyn StdError + Send + Sync>)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Part {
Path,
Query,
Headers,
Body
}
#[derive(Debug, Clone, Copy)]
pub struct Route {
pub field: &'static str,
pub part: Part,
pub key: Option<&'static str>
}
#[derive(Debug, Clone, Copy)]
pub struct Routing {
pub routes: &'static [Route],
pub required_parts: &'static [Part]
}
pub trait IntoOperation {
type Output;
fn into_operation(self) -> Result<Operation<Self::Output>, Error>;
}
impl<Out> IntoOperation for Operation<Out> {
type Output = Out;
fn into_operation(self) -> Result<Self, Error> {
Ok(self)
}
}
impl Retryable for Error {
fn is_transient(&self) -> bool {
match self {
Self::Transport(e) => e.is_timeout() || e.is_connect() || e.is_request(),
Self::Timeout => true,
Self::Status { status, .. } => status.is_server_error() || *status == StatusCode::TOO_MANY_REQUESTS,
Self::Body(_)
| Self::Decode(_)
| Self::NotFound
| Self::MissingSecret
| Self::PathTemplate(_)
| Self::InvalidInput(_) => false
}
}
}
pub struct CallResponse<Out = Value> {
status: StatusCode,
headers: BTreeMap<String, String>,
body: Bytes,
_out: PhantomData<fn() -> Out>
}
impl<Out> Clone for CallResponse<Out> {
fn clone(&self) -> Self {
Self {
status: self.status,
headers: self.headers.clone(),
body: self.body.clone(),
_out: PhantomData
}
}
}
impl<Out> CallResponse<Out> {
pub fn status(&self) -> StatusCode {
self.status
}
pub fn headers(&self) -> &BTreeMap<String, String> {
&self.headers
}
pub fn bytes(&self) -> &Bytes {
&self.body
}
pub fn text(&self) -> String {
String::from_utf8_lossy(&self.body).into_owned()
}
pub fn json<T: DeserializeOwned>(&self) -> Result<T, Error> {
from_slice(&self.body).map_err(Error::Decode)
}
fn retype<U>(self) -> CallResponse<U> {
CallResponse {
status: self.status,
headers: self.headers,
body: self.body,
_out: PhantomData
}
}
}
impl<Out: DeserializeOwned> CallResponse<Out> {
pub fn output(&self) -> Result<Out, Error> {
from_slice(&self.body).map_err(Error::Decode)
}
}
type SuccessHook = Arc<dyn Fn(&CallResponse) + Send + Sync>;
type ErrorHook = Arc<dyn Fn(&Error) + Send + Sync>;
#[derive(Clone)]
pub enum Credential {
Secret(Arc<SecretBox<String>>),
AccessToken(Arc<SecretBox<String>>)
}
impl fmt::Debug for Credential {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Secret(_) => f.write_str("Credential::Secret(<redacted>)"),
Self::AccessToken(_) => f.write_str("Credential::AccessToken(<redacted>)")
}
}
}
impl Credential {
pub fn secret(secret: impl Into<String>) -> Self {
Self::Secret(Arc::new(SecretBox::new(Box::new(secret.into()))))
}
pub fn access_token(token: impl Into<String>) -> Self {
Self::AccessToken(Arc::new(SecretBox::new(Box::new(token.into()))))
}
fn apply(&self, request: RequestBuilder) -> RequestBuilder {
match self {
Self::Secret(secret) => request.header(SECRET_HEADER, secret.expose_secret()),
Self::AccessToken(token) => {
request.header(AUTHORIZATION, format!("{BEARER_PREFIX}{}", token.expose_secret()))
}
}
}
fn is_empty(&self) -> bool {
match self {
Self::Secret(value) | Self::AccessToken(value) => value.expose_secret().trim().is_empty()
}
}
}
#[derive(Clone, Debug, Default)]
pub struct Tenancy {
organization: Option<String>,
project: Option<String>
}
impl Tenancy {
fn apply(&self, request: RequestBuilder) -> RequestBuilder {
let request = match &self.organization {
Some(id) => request.header(ORGANIZATION_ID_HEADER, id),
None => request
};
match &self.project {
Some(id) => request.header(PROJECT_ID_HEADER, id),
None => request
}
}
}
#[derive(Clone)]
pub struct One {
http: HttpClient,
base_url: String,
credential: Credential,
tenancy: Tenancy,
retry: RetrySchedule,
timeout: Option<Duration>,
on_success: Option<SuccessHook>,
on_error: Option<ErrorHook>
}
impl One {
fn request(&self, method: Method, url: &str) -> RequestBuilder {
self.tenancy
.apply(self.credential.apply(self.http.request(method, url)))
}
pub fn new(secret: impl Into<String>) -> Self {
Self::builder()
.secret(secret)
.build()
.expect("One::new requires a non-empty secret")
}
pub fn from_env() -> Result<Self, Error> {
let credential = configured(SECRET_ENV)
.map(Credential::secret)
.or_else(|| configured(ACCESS_TOKEN_ENV).map(Credential::access_token))
.ok_or(Error::MissingSecret)?;
let mut builder = Self::builder().credential(credential);
if let Some(base_url) = configured(BASE_URL_ENV) {
builder = builder.base_url(base_url);
}
builder.build()
}
pub fn builder() -> OneBuilder {
OneBuilder::default()
}
pub fn connection(&self, key: impl Into<String>) -> ConnectionScope<'_> {
ConnectionScope {
one: self,
key: key.into()
}
}
pub fn webhooks(&self, signing_secret: SecretString) -> Webhooks {
Webhooks::new(self.clone(), signing_secret)
}
pub(crate) async fn put_json_response<B: Serialize, Out>(
&self,
path: &str,
body: &B
) -> Result<CallResponse<Out>, Error> {
let url = format!("{}{path}", self.base_url);
let payload = to_vec(body).map_err(Error::Decode)?;
let response = self
.execute(self.retry, None, &[], || {
let mut request = self
.request(Method::PUT, &url)
.header(CONTENT_TYPE, APPLICATION_JSON)
.body(payload.clone());
if let Some(timeout) = self.timeout {
request = request.timeout(timeout);
}
request
})
.await?;
Ok(response.retype())
}
pub(crate) async fn execute<F>(
&self,
retry: RetrySchedule,
on_call: Option<(&Option<SuccessHook>, &Option<ErrorHook>)>,
retry_on: &[StatusCode],
build: F
) -> Result<CallResponse<Value>, Error>
where
F: Fn() -> reqwest::RequestBuilder
{
let send = || {
let request = build();
async move {
let response = match request.send().await {
Ok(response) => response,
Err(error) => {
let mapped = if error.is_timeout() {
Error::Timeout
} else {
Error::Transport(error)
};
return Err((mapped, None));
}
};
let status = response.status();
let headers: BTreeMap<String, String> = response
.headers()
.iter()
.filter_map(|(name, value)| {
value
.to_str()
.ok()
.map(|value| (name.as_str().to_string(), value.to_string()))
})
.collect();
let retry_after = Self::retry_after(response.headers());
let body = match response.bytes().await {
Ok(body) => body,
Err(error) => return Err((Error::Body(error), None))
};
if status.is_success() {
Ok(CallResponse {
status,
headers,
body,
_out: PhantomData
})
} else {
Err((Error::Status { status, body }, retry_after))
}
}
};
let attempts = retry.max_attempts.max(1);
let result: Result<CallResponse<Value>, Error> = 'attempts: {
for attempt in 1..=attempts {
match send().await {
Ok(response) => break 'attempts Ok(response),
Err((error, retry_after)) => {
if attempt == attempts || !Self::is_retryable(&error, retry_on) {
break 'attempts Err(error);
}
sleep(retry_after.unwrap_or_else(|| retry.delay(attempt))).await;
}
}
}
unreachable!("loop runs at least once and breaks on every path")
};
match &result {
Ok(response) => {
if let Some(hook) = &self.on_success {
hook(response);
}
if let Some(hook) = on_call.and_then(|(success, _)| success.as_ref()) {
hook(response);
}
}
Err(error) => self.notify_error(on_call.and_then(|(_, failure)| failure.as_ref()), error)
}
result
}
fn notify_error(&self, per_call: Option<&ErrorHook>, error: &Error) {
for hook in [self.on_error.as_ref(), per_call].into_iter().flatten() {
hook(error);
}
}
fn is_retryable(error: &Error, retry_on: &[StatusCode]) -> bool {
error.is_transient() || matches!(error, Error::Status { status, .. } if retry_on.contains(status))
}
fn retry_after(headers: &HeaderMap) -> Option<Duration> {
headers
.get(RETRY_AFTER)?
.to_str()
.ok()?
.trim()
.parse::<u64>()
.ok()
.map(Duration::from_secs)
}
}
#[derive(Default)]
pub struct OneBuilder {
base_url: Option<String>,
credential: Option<Credential>,
tenancy: Tenancy,
retry: Option<RetrySchedule>,
timeout: Option<Duration>,
on_success: Option<SuccessHook>,
on_error: Option<ErrorHook>
}
impl OneBuilder {
pub fn secret(mut self, secret: impl Into<String>) -> Self {
self.credential = Some(Credential::secret(secret));
self
}
pub fn credential(mut self, credential: Credential) -> Self {
self.credential = Some(credential);
self
}
pub fn organization(mut self, organization_id: impl Into<String>) -> Self {
self.tenancy.organization = Some(organization_id.into());
self
}
pub fn project(mut self, project_id: impl Into<String>) -> Self {
self.tenancy.project = Some(project_id.into());
self
}
pub fn access_token(mut self, token: impl Into<String>) -> Self {
self.credential = Some(Credential::access_token(token));
self
}
pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
self.base_url = Some(base_url.into());
self
}
pub fn retry(mut self, schedule: RetrySchedule) -> Self {
self.retry = Some(schedule);
self
}
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = Some(timeout);
self
}
pub fn on_success<F: Fn(&CallResponse) + Send + Sync + 'static>(mut self, hook: F) -> Self {
self.on_success = Some(Arc::new(hook));
self
}
pub fn on_error<F: Fn(&Error) + Send + Sync + 'static>(mut self, hook: F) -> Self {
self.on_error = Some(Arc::new(hook));
self
}
pub fn build(self) -> Result<One, Error> {
let credential = self
.credential
.filter(|credential| !credential.is_empty())
.ok_or(Error::MissingSecret)?;
Self::ensure_crypto_provider();
let http = HttpClient::builder()
.use_preconfigured_tls(Self::tls_config())
.build()
.map_err(Error::Transport)?;
Ok(One {
http,
base_url: self
.base_url
.unwrap_or_else(|| DEFAULT_BASE_URL.to_string())
.trim_end_matches('/')
.to_string(),
credential,
tenancy: self.tenancy,
retry: self.retry.unwrap_or_default(),
timeout: self.timeout,
on_success: self.on_success,
on_error: self.on_error
})
}
fn ensure_crypto_provider() {
static ONCE: Once = Once::new();
ONCE.call_once(|| {
let _ = default_provider().install_default();
});
}
fn tls_config() -> ClientConfig {
let roots = RootCertStore {
roots: TLS_SERVER_ROOTS.to_vec()
};
ClientConfig::builder()
.with_root_certificates(roots)
.with_no_client_auth()
}
}
pub struct Operation<Out = Value> {
system_id: String,
method: Method,
path: String,
query: Value,
headers: BTreeMap<String, String>,
body: Bytes,
retry: Option<RetrySchedule>,
retry_on: Vec<StatusCode>,
timeout: Option<Duration>,
on_success: Option<SuccessHook>,
on_error: Option<ErrorHook>,
_out: PhantomData<fn() -> Out>
}
impl<Out> Clone for Operation<Out> {
fn clone(&self) -> Self {
Self {
system_id: self.system_id.clone(),
method: self.method.clone(),
path: self.path.clone(),
query: self.query.clone(),
headers: self.headers.clone(),
body: self.body.clone(),
retry: self.retry,
retry_on: self.retry_on.clone(),
timeout: self.timeout,
on_success: self.on_success.clone(),
on_error: self.on_error.clone(),
_out: PhantomData
}
}
}
impl Operation<Value> {
pub fn action(system_id: impl Into<String>, method: Method, path_template: impl Into<String>) -> Self {
Self {
system_id: system_id.into(),
method,
path: path_template.into(),
query: Value::Null,
headers: BTreeMap::new(),
body: Bytes::new(),
retry: None,
retry_on: Vec::new(),
timeout: None,
on_success: None,
on_error: None,
_out: PhantomData
}
}
}
impl<Out> Operation<Out> {
pub fn retry(mut self, schedule: RetrySchedule) -> Self {
self.retry = Some(schedule);
self
}
pub fn retry_on(mut self, statuses: impl IntoIterator<Item = StatusCode>) -> Self {
self.retry_on = statuses.into_iter().collect();
self
}
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = Some(timeout);
self
}
pub fn on_success<F: Fn(&CallResponse) + Send + Sync + 'static>(mut self, hook: F) -> Self {
self.on_success = Some(Arc::new(hook));
self
}
pub fn on_error<F: Fn(&Error) + Send + Sync + 'static>(mut self, hook: F) -> Self {
self.on_error = Some(Arc::new(hook));
self
}
pub fn returns<Out2>(self) -> Operation<Out2> {
Operation {
system_id: self.system_id,
method: self.method,
path: self.path,
query: self.query,
headers: self.headers,
body: self.body,
retry: self.retry,
retry_on: self.retry_on,
timeout: self.timeout,
on_success: self.on_success,
on_error: self.on_error,
_out: PhantomData
}
}
pub fn with_path<P: Serialize>(mut self, path: &P) -> Result<Self, Error> {
let value = to_value(path).map_err(Error::Decode)?;
self.path = Self::resolve_path(&self.path, Some(&value))?;
Ok(self)
}
pub fn with_query<Q: Serialize>(mut self, query: &Q) -> Result<Self, Error> {
self.query = to_value(query).map_err(Error::Decode)?;
Ok(self)
}
pub fn with_headers<H: Serialize>(mut self, headers: &H) -> Result<Self, Error> {
let value = to_value(headers).map_err(Error::Decode)?;
self.headers = header_map(&value);
Ok(self)
}
pub fn with_body<B: Serialize>(mut self, body: &B) -> Result<Self, Error> {
let bytes = to_vec(body).map_err(Error::Decode)?;
if bytes != b"null" {
self.body = Bytes::from(bytes);
}
Ok(self)
}
pub fn with_routed<I: Serialize>(self, input: &I, routing: &Routing) -> Result<Self, Error> {
let Value::Object(mut fields) = to_value(input).map_err(Error::Decode)? else {
return Err(Error::InvalidInput(NON_OBJECT_INPUT.into()));
};
let mut parts: BTreeMap<Part, Value> = routing
.required_parts
.iter()
.chain([&Part::Path])
.map(|part| (*part, Value::Object(Map::new())))
.collect();
let (whole, keyed): (Vec<&Route>, Vec<&Route>) = routing.routes.iter().partition(|route| route.key.is_none());
for route in whole {
if let Some(value) = fields.remove(route.field) {
parts.insert(route.part, value);
}
}
for route in keyed {
let (Some(key), Some(value)) = (route.key, fields.remove(route.field)) else {
continue;
};
match parts.entry(route.part).or_insert_with(|| Value::Object(Map::new())) {
Value::Object(entries) => {
entries.insert(key.to_string(), value);
}
_ => {
let message = format!("`{}` needs `{key}` set on an object", route.field);
return Err(Error::InvalidInput(message.into()));
}
}
}
parts.into_iter().try_fold(self, |operation, (part, value)| match part {
Part::Path => operation.with_path(&value),
Part::Query => operation.with_query(&value),
Part::Headers => operation.with_headers(&value),
Part::Body => operation.with_body(&value)
})
}
pub fn raw_body(mut self, body: impl Into<Bytes>) -> Self {
self.body = body.into();
self
}
pub fn merge_body(mut self, extra: Value) -> Result<Self, Error> {
let mut body: Value = if self.body.is_empty() {
Value::Object(Default::default())
} else {
from_slice(&self.body).map_err(Error::Decode)?
};
Self::merge(&mut body, extra);
self.body = Bytes::from(to_vec(&body).map_err(Error::Decode)?);
Ok(self)
}
pub fn merge_query(mut self, extra: Value) -> Self {
Self::merge(&mut self.query, extra);
self
}
pub fn merge_headers(mut self, extra: Value) -> Self {
if let Value::Object(entries) = extra {
for (key, value) in entries {
self.headers.retain(|name, _| !name.eq_ignore_ascii_case(&key));
if let Some(rendered) = header_value(&value) {
self.headers.insert(key, rendered);
}
}
}
self
}
pub fn remove_header(mut self, name: &str) -> Self {
self.headers.retain(|key, _| !key.eq_ignore_ascii_case(name));
self
}
pub fn remove_query(mut self, name: &str) -> Self {
if let Some(object) = self.query.as_object_mut() {
object.remove(name);
}
self
}
pub fn system_id(&self) -> &str {
&self.system_id
}
pub fn method(&self) -> &Method {
&self.method
}
pub fn path(&self) -> &str {
&self.path
}
pub fn query(&self) -> &Value {
&self.query
}
pub fn headers(&self) -> &BTreeMap<String, String> {
&self.headers
}
pub fn body(&self) -> &Bytes {
&self.body
}
fn merge(target: &mut Value, extra: Value) {
if target.is_null() {
*target = extra;
} else if let (Some(base), Value::Object(entries)) = (target.as_object_mut(), extra) {
for (key, value) in entries {
base.insert(key, value);
}
}
}
fn resolve_path(template: &str, path: Option<&Value>) -> Result<String, Error> {
let mut renderer = Handlebars::new();
renderer.set_strict_mode(true);
renderer.register_escape_fn(|raw| utf8_percent_encode(raw, PATH_SEGMENT).to_string());
let context = path.cloned().unwrap_or(Value::Null);
renderer
.render_template(template, &context)
.map_err(|error| Error::PathTemplate(error.to_string()))
}
}
impl<Out> fmt::Debug for Operation<Out> {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("Operation")
.field("system_id", &self.system_id)
.field("method", &self.method.as_str())
.field("path", &self.path)
.field("query", &self.query)
.field("headers", &self.headers)
.field("body", &String::from_utf8_lossy(&self.body))
.finish()
}
}
pub struct ConnectionScope<'a> {
one: &'a One,
key: String
}
impl ConnectionScope<'_> {
pub async fn run<O: IntoOperation>(&self, operation: O) -> Result<CallResponse<O::Output>, Error> {
let operation = operation
.into_operation()
.inspect_err(|error| self.one.notify_error(None, error))?;
let query = query_pairs(&operation.query)
.inspect_err(|error| self.one.notify_error(operation.on_error.as_ref(), error))?;
let Operation {
system_id,
method,
path,
headers,
body,
retry,
retry_on,
timeout,
on_success,
on_error,
..
} = operation;
let retry = retry.unwrap_or(self.one.retry);
let timeout = timeout.or(self.one.timeout);
let url =
format!("{}/v1/passthrough/{}", self.one.base_url, without_replaced(&path, &query).trim_start_matches('/'));
let response = self
.one
.execute(retry, Some((&on_success, &on_error)), &retry_on, || {
let mut request = self
.one
.request(method.clone(), &url)
.header(CONNECTION_KEY_HEADER, &self.key)
.header(ACTION_ID_HEADER, &system_id);
if let Some(timeout) = timeout {
request = request.timeout(timeout);
}
if !body.is_empty() {
request = request.body(body.clone());
}
if !query.is_empty() {
request = request.query(&query);
}
for (name, value) in &headers {
request = request.header(name.as_str(), value.as_str());
}
request
})
.await;
response.map(|response| response.retype())
}
pub async fn get(&self) -> Result<Connection, Error> {
let url = format!("{}{VAULT_CONNECTIONS_PATH}", self.one.base_url);
let response = self
.one
.request(Method::GET, &url)
.query(&[
(CONNECTION_KEY_PARAM, self.key.as_str()),
(PAGE_PARAM, "1"),
(LIMIT_PARAM, "1")
])
.send()
.await
.map_err(|error| {
if error.is_timeout() {
Error::Timeout
} else {
Error::Transport(error)
}
})?;
let status = response.status();
let body = response.bytes().await.map_err(Error::Body)?;
if !status.is_success() {
return Err(Error::Status { status, body });
}
let page: PaginatedVaultConnectionView = from_slice(&body).map_err(Error::Decode)?;
page.rows.into_iter().next().ok_or(Error::NotFound)
}
}
fn header_map(object: &Value) -> BTreeMap<String, String> {
object
.as_object()
.into_iter()
.flatten()
.filter_map(|(key, value)| header_value(value).map(|rendered| (key.clone(), rendered)))
.collect()
}
fn header_value(value: &Value) -> Option<String> {
match value {
Value::Null => None,
Value::Array(items) => Some(
items
.iter()
.filter(|item| !item.is_null())
.map(rendered)
.collect::<Vec<_>>()
.join(",")
),
single => Some(rendered(single))
}
}
fn query_pairs(query: &Value) -> Result<Vec<(String, String)>, Error> {
query
.as_object()
.into_iter()
.flatten()
.flat_map(|(name, value)| {
let items = match value {
Value::Array(items) => items.as_slice(),
single => from_ref(single)
};
items.iter().filter(|item| !item.is_null()).map(move |item| match item {
Value::Object(_) | Value::Array(_) => Err(Error::InvalidInput(
format!("query parameter `{name}` holds a nested value, which has no query encoding").into()
)),
scalar => Ok((name.clone(), rendered(scalar)))
})
})
.collect()
}
fn without_replaced(path: &str, query: &[(String, String)]) -> String {
let path = path.split('#').next().unwrap_or_default();
let Some((route, own)) = path.split_once('?') else {
return path.to_string();
};
let key = |piece: &str| {
let raw = piece.split('=').next().unwrap_or_default().replace('+', " ");
percent_decode_str(&raw).decode_utf8_lossy().into_owned()
};
let replaced = |piece: &&str| query.iter().any(|(name, _)| *name == key(piece));
let kept = own
.split('&')
.map(|pair| {
pair.split(';')
.filter(|piece| !piece.is_empty() && !replaced(piece))
.collect::<Vec<_>>()
.join(";")
})
.filter(|pair| !pair.is_empty())
.collect::<Vec<_>>()
.join("&");
match kept.is_empty() {
true => route.to_string(),
false => format!("{route}?{kept}")
}
}
fn rendered(value: &Value) -> String {
value.as_str().map(str::to_string).unwrap_or_else(|| value.to_string())
}
#[cfg(test)]
mod tests {
use std::env::{remove_var, set_var};
use super::{ACCESS_TOKEN_ENV, Credential, One, SECRET_ENV, without_replaced};
#[test]
fn test_client_without_replaced_drops_the_templates_pair_a_caller_sets() {
let query = [("attributes".to_string(), "id".to_string())];
assert_eq!(without_replaced("/contacts/1?attributes=all&v=2", &query), "/contacts/1?v=2");
assert_eq!(without_replaced("/contacts/1?attributes=all", &query), "/contacts/1");
assert_eq!(without_replaced("/contacts/1?a%74tributes=all&v", &query), "/contacts/1?v");
assert_eq!(without_replaced("/contacts/1", &query), "/contacts/1");
assert_eq!(without_replaced("/contacts/1?v=2", &[]), "/contacts/1?v=2");
assert_eq!(without_replaced("/contacts/1?x=1;attributes=all", &query), "/contacts/1?x=1");
assert_eq!(without_replaced("/contacts/1?v=2&attributes#stream", &query), "/contacts/1?v=2");
}
fn credential_from(secret: Option<&str>, access_token: Option<&str>) -> Option<Credential> {
unsafe {
match secret {
Some(value) => set_var(SECRET_ENV, value),
None => remove_var(SECRET_ENV)
}
match access_token {
Some(value) => set_var(ACCESS_TOKEN_ENV, value),
None => remove_var(ACCESS_TOKEN_ENV)
}
}
let credential = One::from_env().ok().map(|one| one.credential);
unsafe {
remove_var(SECRET_ENV);
remove_var(ACCESS_TOKEN_ENV);
}
credential
}
#[test]
fn test_client_from_env_resolves_the_credential_by_precedence() {
assert!(
matches!(credential_from(Some(""), Some("at_from_env")), Some(Credential::AccessToken(_))),
"a blank legacy secret must not shadow the access token beside it"
);
assert!(
matches!(credential_from(Some(" "), Some("at_from_env")), Some(Credential::AccessToken(_))),
"nor must a whitespace-only one"
);
assert!(
matches!(credential_from(Some("sk_from_env"), Some("at_from_env")), Some(Credential::Secret(_))),
"with both set, the longer-standing variable wins"
);
assert!(
matches!(credential_from(Some("sk_from_env"), None), Some(Credential::Secret(_))),
"and it stands alone"
);
assert!(credential_from(None, None).is_none(), "neither configured is a missing secret, not a client");
}
}