Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplify client, remove some allocations #528

Merged
merged 3 commits into from
Apr 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions async-stripe/src/client/headers.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::fmt::{Display, Formatter};

use crate::AccountId;
use crate::ApiVersion;
use crate::ApplicationId;
Expand All @@ -9,16 +11,16 @@
pub version: Option<String>,
}

impl ToString for AppInfo {
impl Display for AppInfo {
/// Formats a plugin's 'App Info' into a string that can be added to the end of an User-Agent string.
///
/// This formatting matches that of other libraries, and if changed then it should be changed everywhere.
fn to_string(&self) -> String {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match (&self.version, &self.url) {
(Some(a), Some(b)) => format!("{}/{} ({})", &self.name, a, b),
(Some(a), None) => format!("{}/{}", &self.name, a),
(None, Some(b)) => format!("{} ({})", &self.name, b),
_ => self.name.to_string(),
(Some(a), Some(b)) => write!(f, "{}/{a} ({b})", &self.name),
(Some(a), None) => write!(f, "{}/{a}", &self.name),
(None, Some(b)) => write!(f, "{} ({b})", &self.name),

Check warning on line 22 in async-stripe/src/client/headers.rs

View check run for this annotation

Codecov / codecov/patch

async-stripe/src/client/headers.rs#L21-L22

Added lines #L21 - L22 were not covered by tests
_ => f.write_str(&self.name),
}
}
}
Expand Down
21 changes: 7 additions & 14 deletions async-stripe/src/client/stripe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,7 @@ pub struct Client {
secret_key: String,
headers: Headers,
strategy: RequestStrategy,
app_info: Option<AppInfo>,
api_base: Url,
api_root: String,
}

impl Client {
Expand All @@ -44,9 +42,7 @@ impl Client {
stripe_account: None,
},
strategy: RequestStrategy::Once,
app_info: None,
api_base: Url::parse(url.into()).expect("invalid url"),
api_root: "v1".to_string(),
}
}

Expand Down Expand Up @@ -80,8 +76,7 @@ impl Client {
url: Option<String>,
) -> Self {
let app_info = AppInfo { name, version, url };
self.headers.user_agent = format!("{} {}", USER_AGENT, app_info.to_string());
self.app_info = Some(app_info);
self.headers.user_agent = format!("{USER_AGENT} {app_info}");
self
}

Expand Down Expand Up @@ -156,9 +151,8 @@ impl Client {
return err(StripeError::QueryStringSerialize(qs_ser_err));
}

let body = std::str::from_utf8(params_buffer.as_slice())
.expect("Unable to extract string from params_buffer")
.to_string();
let body =
String::from_utf8(params_buffer).expect("Unable to extract string from params_buffer");

req.set_body(Body::from_string(body));

Expand All @@ -168,7 +162,7 @@ impl Client {

fn url(&self, path: &str) -> Url {
let mut url = self.api_base.clone();
url.set_path(&format!("{}/{}", self.api_root, path.trim_start_matches('/')));
url.set_path(&format!("v1/{}", path.trim_start_matches('/')));
url
}

Expand All @@ -179,17 +173,16 @@ impl Client {
let qs_ser = &mut serde_qs::Serializer::new(&mut params_buffer);
serde_path_to_error::serialize(&params, qs_ser).map_err(StripeError::from)?;

let params = std::str::from_utf8(params_buffer.as_slice())
.expect("Unable to extract string from params_buffer")
.to_string();
let params =
String::from_utf8(params_buffer).expect("Unable to extract string from params_buffer");

url.set_query(Some(&params));
Ok(url)
}

fn create_request(&self, method: Method, url: Url) -> Request {
let mut req = Request::new(method, url);
req.insert_header("authorization", &format!("Bearer {}", self.secret_key));
req.insert_header("authorization", format!("Bearer {}", self.secret_key));

for (key, value) in self.headers.to_array().iter().filter_map(|(k, v)| v.map(|v| (*k, v))) {
req.insert_header(key, value);
Expand Down
4 changes: 1 addition & 3 deletions openapi/src/url_finder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,7 @@ impl UrlFinder {
}

pub fn url_for_object(&self, object: &str) -> Option<String> {
let Some(unprefixed_link) = self.doc_links.get(object) else {
return None;
};
let unprefixed_link = self.doc_links.get(object)?;
Some(format!("https://stripe.com/docs/api{}", unprefixed_link))
}
}
Expand Down
35 changes: 18 additions & 17 deletions stripe_webhook/src/webhook.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use std::collections::HashMap;
use std::str::FromStr;

use chrono::Utc;
Expand Down Expand Up @@ -138,22 +137,24 @@ struct Signature<'r> {

impl<'r> Signature<'r> {
fn parse(raw: &'r str) -> Result<Signature<'r>, WebhookError> {
let headers: HashMap<&str, &str> = raw
.split(',')
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would be a strange attack, but seems good to avoid collecting every pair in the signature since it could be malicious

.map(|header| {
let mut key_and_value = header.split('=');
let key = key_and_value.next();
let value = key_and_value.next();
(key, value)
})
.filter_map(|(key, value)| match (key, value) {
(Some(key), Some(value)) => Some((key, value)),
_ => None,
})
.collect();
let t = headers.get("t").ok_or(WebhookError::BadSignature)?;
let v1 = headers.get("v1").ok_or(WebhookError::BadSignature)?;
Ok(Signature { t: t.parse::<i64>().map_err(WebhookError::BadHeader)?, v1 })
let mut t: Option<i64> = None;
let mut v1: Option<&'r str> = None;
for pair in raw.split(',') {
let (key, val) = pair.split_once('=').ok_or(WebhookError::BadSignature)?;
match key {
"t" => {
t = Some(val.parse().map_err(WebhookError::BadHeader)?);
}
"v1" => {
v1 = Some(val);
}
_ => {}
}
}
Ok(Signature {
t: t.ok_or(WebhookError::BadSignature)?,
v1: v1.ok_or(WebhookError::BadSignature)?,
})
}
}

Expand Down
Loading