Skip to content

Commit 3fcdcfc

Browse files
committed
Fix clippy lints
1 parent c36062e commit 3fcdcfc

File tree

6 files changed

+62
-47
lines changed

6 files changed

+62
-47
lines changed

src/auth.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -250,7 +250,7 @@ impl SigV4Authenticator {
250250

251251
// Remove the access key from the credential to get the credential scope. This requires that prevalidate() has
252252
// been called.
253-
let cscope = self.credential.splitn(2, '/').nth(1).expect("prevalidate should have been called first");
253+
let cscope = self.credential.split_once('/').map(|x| x.1).expect("prevalidate should have been called first");
254254

255255
result.extend(AWS4_HMAC_SHA256.as_bytes());
256256
result.push(b'\n');
@@ -295,7 +295,7 @@ impl SigV4Authenticator {
295295
impl Debug for SigV4Authenticator {
296296
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
297297
f.debug_struct("SigV4Authenticator")
298-
.field("canonical_request_sha256", &hex::encode(&self.canonical_request_sha256))
298+
.field("canonical_request_sha256", &hex::encode(self.canonical_request_sha256))
299299
.field("session_token", &self.session_token)
300300
.field("signature", &self.signature)
301301
.field("request_timestamp", &self.request_timestamp)
@@ -385,7 +385,7 @@ mod tests {
385385
ring::digest::SHA256_OUTPUT_LEN,
386386
scratchstack_aws_principal::{Principal, User},
387387
scratchstack_errors::ServiceError,
388-
std::{error::Error, fs::File},
388+
std::{error::Error, fs::File, str::FromStr},
389389
tower::BoxError,
390390
};
391391

@@ -470,7 +470,7 @@ mod tests {
470470
match request.access_key() {
471471
"AKIDEXAMPLE" => {
472472
let principal = Principal::from(vec![User::new("aws", "123456789012", "/", "test").unwrap().into()]);
473-
let k_secret = KSecretKey::from_str("wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY");
473+
let k_secret = KSecretKey::from_str("wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY").unwrap();
474474
let k_signing = k_secret.to_ksigning(request.request_date(), request.region(), request.service());
475475

476476
let response =

src/aws4.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ use {
1919
fs::File,
2020
io::{BufRead, BufReader, Read, Seek},
2121
path::PathBuf,
22-
str::from_utf8,
22+
str::{from_utf8, FromStr},
2323
},
2424
tower::BoxError,
2525
};
@@ -289,7 +289,7 @@ async fn run(basename: &str) {
289289

290290
async fn get_signing_key(request: GetSigningKeyRequest) -> Result<GetSigningKeyResponse, BoxError> {
291291
let principal = Principal::from(User::new("aws", "123456789012", "/", "test").unwrap());
292-
let k_secret = KSecretKey::from_str("wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY");
292+
let k_secret = KSecretKey::from_str("wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY").unwrap();
293293
let k_signing = k_secret.to_ksigning(request.request_date(), request.region(), request.service());
294294

295295
let response = GetSigningKeyResponse::builder().principal(principal).signing_key(k_signing).build().unwrap();

src/canonical.rs

Lines changed: 23 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -174,9 +174,9 @@ impl CanonicalRequest {
174174
mut body: Bytes,
175175
options: SignatureOptions,
176176
) -> Result<(Self, Parts, Bytes), SignatureError> {
177-
let canonical_path = canonicalize_uri_path(&parts.uri.path(), options.s3)?;
177+
let canonical_path = canonicalize_uri_path(parts.uri.path(), options.s3)?;
178178
let content_type = get_content_type_and_charset(&parts.headers);
179-
let mut query_parameters = query_string_to_normalized_map(&parts.uri.query().unwrap_or(""))?;
179+
let mut query_parameters = query_string_to_normalized_map(parts.uri.query().unwrap_or(""))?;
180180

181181
if options.url_encode_form {
182182
// Treat requests with application/x-www-form-urlencoded bodies as if they were passed into the query string.
@@ -210,7 +210,7 @@ impl CanonicalRequest {
210210
}
211211
};
212212

213-
query_parameters.extend(query_string_to_normalized_map(body_query.as_str())?.into_iter());
213+
query_parameters.extend(query_string_to_normalized_map(body_query.as_str())?);
214214
// Rebuild the parts URI with the new query string.
215215
let qs = canonicalize_query_to_string(&query_parameters);
216216
trace!("Rebuilding URI with new query string: {}", qs);
@@ -320,12 +320,12 @@ impl CanonicalRequest {
320320

321321
/// Get the SHA-256 hash of the [canonical request](https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html).
322322
pub fn canonical_request_sha256(&self, signed_headers: &Vec<String>) -> [u8; SHA256_OUTPUT_LEN] {
323-
let canonical_request = self.canonical_request(&signed_headers);
323+
let canonical_request = self.canonical_request(signed_headers);
324324
let result_digest = digest(&SHA256, canonical_request.as_ref());
325325
let result_slice = result_digest.as_ref();
326326
assert!(result_slice.len() == SHA256_OUTPUT_LEN);
327327
let mut result: [u8; SHA256_OUTPUT_LEN] = [0; SHA256_OUTPUT_LEN];
328-
result.as_mut_slice().clone_from_slice(&result_slice);
328+
result.as_mut_slice().clone_from_slice(result_slice);
329329
result
330330
}
331331

@@ -497,7 +497,7 @@ impl CanonicalRequest {
497497
}
498498

499499
let mut signed_headers = if let Some(signed_headers) = parameter_map.get(SIGNED_HEADERS) {
500-
signed_headers.split(|c| *c == b';').map(|s| latin1_to_string(s)).collect()
500+
signed_headers.split(|c| *c == b';').map(latin1_to_string).collect()
501501
} else {
502502
missing_messages.push(MSG_AUTH_HEADER_REQ_SIGNED_HEADERS);
503503
Vec::new()
@@ -824,7 +824,7 @@ pub fn get_content_type_and_charset(headers: &HeaderMap<HeaderValue>) -> Option<
824824
None => return None,
825825
};
826826

827-
let mut parts = content_type_opts.split(|c| *c == b';').map(|s| trim_ascii(s));
827+
let mut parts = content_type_opts.split(|c| *c == b';').map(trim_ascii);
828828
let content_type = latin1_to_string(parts.next().expect("split always returns at least one element"));
829829

830830
for option in parts {
@@ -870,7 +870,7 @@ pub fn normalize_headers(headers: &HeaderMap<HeaderValue>) -> HashMap<String, Ve
870870
for (key, value) in headers.iter() {
871871
let key = key.as_str().to_lowercase();
872872
let value = normalize_header_value(value.as_bytes());
873-
result.entry(key).or_insert_with(Vec::new).push(value);
873+
result.entry(key).or_default().push(value);
874874
}
875875

876876
result
@@ -886,7 +886,7 @@ fn normalize_header_value(value: &[u8]) -> Vec<u8> {
886886
for c in value {
887887
if *c == b' ' {
888888
if !last_was_space {
889-
result.push(' ' as u8);
889+
result.push(b' ');
890890
last_was_space = true;
891891
}
892892
} else {
@@ -897,7 +897,7 @@ fn normalize_header_value(value: &[u8]) -> Vec<u8> {
897897

898898
if last_was_space {
899899
// Remove trailing spaces.
900-
while result.last() == Some(&(' ' as u8)) {
900+
while result.last() == Some(&b' ') {
901901
result.pop();
902902
}
903903
}
@@ -1100,8 +1100,8 @@ fn unescape_uri_encoding(s: &str) -> String {
11001100
while let Some(c) = chars.next() {
11011101
if c == b'%' {
11021102
let mut hex_digits = [0u8; 2];
1103-
hex_digits[0] = chars.next().expect(MSG_INCOMPLETE_TRAILING_ESCAPE) as u8;
1104-
hex_digits[1] = chars.next().expect(MSG_INCOMPLETE_TRAILING_ESCAPE) as u8;
1103+
hex_digits[0] = chars.next().expect(MSG_INCOMPLETE_TRAILING_ESCAPE);
1104+
hex_digits[1] = chars.next().expect(MSG_INCOMPLETE_TRAILING_ESCAPE);
11051105
match u8::from_str_radix(from_utf8(&hex_digits).unwrap(), 16) {
11061106
Ok(c) => result.push(c as char),
11071107
Err(_) => panic!("{}{}{}", MSG_ILLEGAL_HEX_CHAR, hex_digits[0] as char, hex_digits[1] as char),
@@ -1132,7 +1132,7 @@ mod tests {
11321132
uri::{PathAndQuery, Uri},
11331133
},
11341134
scratchstack_errors::ServiceError,
1135-
std::{collections::HashMap, mem::transmute},
1135+
std::collections::HashMap,
11361136
};
11371137

11381138
macro_rules! expect_err {
@@ -1252,7 +1252,7 @@ mod tests {
12521252
assert_eq!(foo.len(), 1);
12531253
assert_eq!(foo[0], "bar");
12541254

1255-
assert!(v.get("").is_none());
1255+
assert!(!v.contains_key(""));
12561256
}
12571257

12581258
#[test_log::test]
@@ -1273,22 +1273,23 @@ mod tests {
12731273
#[test_log::test]
12741274
fn normalize_invalid_hex_path_cr() {
12751275
// The HTTP crate does its own validation; we need to hack into it to force invalid URI elements in there.
1276-
for (path, error_message) in vec![
1276+
for (path, error_message) in [
12771277
("/abcd%yy", "Illegal hex character in escape % pattern: %yy"),
12781278
("/abcd%0", "Incomplete trailing escape % sequence"),
12791279
("/abcd%", "Incomplete trailing escape % sequence"),
12801280
] {
12811281
let mut fake_path = "/".to_string();
12821282
while fake_path.len() < path.len() {
1283-
fake_path.push_str("a");
1283+
fake_path.push('a');
12841284
}
12851285

12861286
let mut pq = PathAndQuery::from_maybe_shared(fake_path.clone()).unwrap();
12871287
let pq_path = Bytes::from_static(path.as_bytes());
12881288

12891289
unsafe {
1290-
// Rewrite the path to be invalid.
1291-
let pq_ptr: *mut PathAndQuerySimulate = transmute(&mut pq);
1290+
// Rewrite the path to be invalid. This can't be done with the normal PathAndQuery
1291+
// API.
1292+
let pq_ptr: *mut PathAndQuerySimulate = &mut pq as *mut PathAndQuery as *mut PathAndQuerySimulate;
12921293
(*pq_ptr).data = pq_path;
12931294
}
12941295

@@ -1313,22 +1314,22 @@ mod tests {
13131314
#[test_log::test]
13141315
fn normalize_invalid_hex_query_cr() {
13151316
// The HTTP crate does its own validation; we need to hack into it to force invalid URI elements in there.
1316-
for (path, error_message) in vec![
1317+
for (path, error_message) in [
13171318
("/?x=abcd%yy", "Illegal hex character in escape % pattern: %yy"),
13181319
("/?x=abcd%0", "Incomplete trailing escape % sequence"),
13191320
("/?x=abcd%", "Incomplete trailing escape % sequence"),
13201321
] {
13211322
let mut fake_path = "/?x=".to_string();
13221323
while fake_path.len() < path.len() {
1323-
fake_path.push_str("a");
1324+
fake_path.push('a');
13241325
}
13251326

13261327
let mut pq = PathAndQuery::from_maybe_shared(fake_path.clone()).unwrap();
13271328
let pq_path = Bytes::from_static(path.as_bytes());
13281329

13291330
unsafe {
13301331
// Rewrite the path to be invalid.
1331-
let pq_ptr: *mut PathAndQuerySimulate = transmute(&mut pq);
1332+
let pq_ptr: *mut PathAndQuerySimulate = &mut pq as *mut PathAndQuery as *mut PathAndQuerySimulate;
13321333
(*pq_ptr).data = pq_path;
13331334
}
13341335

@@ -1487,7 +1488,7 @@ mod tests {
14871488
let (parts, body) = request.into_parts();
14881489

14891490
let (cr, _, _) = CanonicalRequest::from_request_parts(parts, body, SignatureOptions::default()).unwrap();
1490-
assert!(cr.query_parameters.get("foo").is_none());
1491+
assert!(!cr.query_parameters.contains_key("foo"));
14911492
}
14921493

14931494
#[test_log::test]

src/lib.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
//! GetSigningKeyRequest, GetSigningKeyResponse, KSecretKey, SignatureOptions,
3737
//! SignedHeaderRequirements, service_for_signing_key_fn, sigv4_validate_request,
3838
//! };
39+
//! use std::str::FromStr;
3940
//! use tower::{BoxError, Service};
4041
//!
4142
//! const ACCESS_KEY: &str = "AKIAIOSFODNN7EXAMPLE";
@@ -67,7 +68,7 @@
6768
//! assert_eq!(request.region(), REGION);
6869
//! assert_eq!(request.service(), SERVICE);
6970
//! let user = User::new(PARTITION, ACCOUNT_ID, PATH, USER_NAME)?;
70-
//! let secret_key = KSecretKey::from_str(SECRET_KEY);
71+
//! let secret_key = KSecretKey::from_str(SECRET_KEY).unwrap();
7172
//! let signing_key = secret_key.to_ksigning(request.request_date(), REGION, SERVICE);
7273
//! Ok(GetSigningKeyResponse::builder()
7374
//! .principal(user)

src/signature.rs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,7 @@ mod tests {
171171
lazy_static::lazy_static,
172172
scratchstack_aws_principal::{Principal, User},
173173
scratchstack_errors::ServiceError,
174-
std::mem::transmute,
174+
std::str::FromStr,
175175
tower::BoxError,
176176
};
177177

@@ -216,7 +216,7 @@ mod tests {
216216
Signature=c9d5ea9f3f72853aea855b47ea873832890dbdd183b4468f858259531a5138ea";
217217

218218
async fn get_signing_key(req: GetSigningKeyRequest) -> Result<GetSigningKeyResponse, BoxError> {
219-
let k_secret = KSecretKey::from_str("wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY");
219+
let k_secret = KSecretKey::from_str("wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY").unwrap();
220220
let k_signing = k_secret.to_ksigning(req.request_date(), req.region(), req.service());
221221

222222
let principal = Principal::from(vec![User::new("aws", "123456789012", "/", "test").unwrap().into()]);
@@ -332,8 +332,8 @@ mod tests {
332332

333333
if i == 0 {
334334
unsafe {
335-
// Rewrite the path to be invalid.
336-
let pq_ptr: *mut PathAndQuerySimulate = transmute(&mut pq);
335+
// Rewrite the path to be invalid. This can't be done with the normal PathAndQuery API.
336+
let pq_ptr: *mut PathAndQuerySimulate = &mut pq as *mut PathAndQuery as *mut PathAndQuerySimulate;
337337
(*pq_ptr).data = pq_path;
338338
}
339339
}
@@ -499,8 +499,8 @@ mod tests {
499499

500500
if i == 0 {
501501
unsafe {
502-
// Rewrite the path to be invalid.
503-
let pq_ptr: *mut PathAndQuerySimulate = transmute(&mut pq);
502+
// Rewrite the path to be invalid. This cannot be done with the normal PathAndQuery API.
503+
let pq_ptr: *mut PathAndQuerySimulate = &mut pq as *mut PathAndQuery as *mut PathAndQuerySimulate;
504504
(*pq_ptr).data = pq_path;
505505
}
506506
}
@@ -706,7 +706,7 @@ mod tests {
706706
s3: true,
707707
..Default::default()
708708
};
709-
let opt3 = opt1.clone();
709+
let opt3 = opt1;
710710
let opt4 = opt1;
711711
assert_eq!(opt1.s3, opt2.s3);
712712
assert_eq!(opt1.s3, opt3.s3);

src/signing_key.rs

Lines changed: 24 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,10 @@ use {
55
ring::digest::SHA256_OUTPUT_LEN,
66
scratchstack_aws_principal::{Principal, SessionData},
77
std::{
8+
convert::Infallible,
89
fmt::{Debug, Display, Formatter, Result as FmtResult},
910
future::Future,
11+
str::FromStr,
1012
},
1113
tower::{service_fn, util::ServiceFn, BoxError},
1214
};
@@ -140,17 +142,21 @@ impl Display for KSigningKey {
140142
}
141143
}
142144

143-
impl KSecretKey {
145+
impl FromStr for KSecretKey {
146+
type Err = Infallible;
147+
144148
/// Create a new `KSecretKey` from a raw AWS secret key.
145-
pub fn from_str(raw: &str) -> Self {
149+
fn from_str(raw: &str) -> Result<Self, Infallible> {
146150
let mut prefixed_key = Vec::with_capacity(4 + raw.len());
147151
prefixed_key.extend_from_slice(b"AWS4");
148152
prefixed_key.extend_from_slice(raw.as_bytes());
149-
Self {
153+
Ok(Self {
150154
prefixed_key,
151-
}
155+
})
152156
}
157+
}
153158

159+
impl KSecretKey {
154160
/// Create a new `KDateKey` from this `KSecretKey` and a date.
155161
pub fn to_kdate(&self, date: NaiveDate) -> KDateKey {
156162
let date = date.format("%Y%m%d").to_string();
@@ -377,15 +383,16 @@ mod tests {
377383
crate::{GetSigningKeyRequest, GetSigningKeyResponse, KSecretKey},
378384
chrono::NaiveDate,
379385
scratchstack_aws_principal::{AssumedRole, Principal},
386+
std::str::FromStr,
380387
};
381388

382389
#[test_log::test]
383390
fn test_signing_key_derived() {
384391
let date = NaiveDate::from_ymd_opt(2015, 8, 30).unwrap();
385392

386-
let ksecret1a = KSecretKey::from_str("wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY");
387-
let ksecret1b = KSecretKey::from_str("wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY");
388-
let ksecret2 = KSecretKey::from_str("wJalrXUtnFEMI/K7MDENG+bPxRfiCZEXAMPLEKEY");
393+
let ksecret1a = KSecretKey::from_str("wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY").unwrap();
394+
let ksecret1b = KSecretKey::from_str("wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY").unwrap();
395+
let ksecret2 = KSecretKey::from_str("wJalrXUtnFEMI/K7MDENG+bPxRfiCZEXAMPLEKEY").unwrap();
389396

390397
assert_eq!(ksecret1a, ksecret1b);
391398
assert_eq!(ksecret1a, ksecret1a.clone());
@@ -495,8 +502,11 @@ mod tests {
495502
assert_eq!(gsk_req1a.region, gsk_req1b.region);
496503
assert_eq!(gsk_req1a.service, gsk_req1b.service);
497504

498-
let signing_key =
499-
KSecretKey::from_str("wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY").to_ksigning(date, "us-east-1", "example");
505+
let signing_key = KSecretKey::from_str("wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY").unwrap().to_ksigning(
506+
date,
507+
"us-east-1",
508+
"example",
509+
);
500510
let principal = Principal::from(AssumedRole::new("aws", "123456789012", "role", "session").unwrap());
501511

502512
let gsk_resp1a =
@@ -520,8 +530,11 @@ mod tests {
520530
#[test_log::test]
521531
fn test_response_builder() {
522532
let date = NaiveDate::from_ymd_opt(2015, 8, 30).unwrap();
523-
let signing_key =
524-
KSecretKey::from_str("wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY").to_ksigning(date, "us-east-1", "example");
533+
let signing_key = KSecretKey::from_str("wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY").unwrap().to_ksigning(
534+
date,
535+
"us-east-1",
536+
"example",
537+
);
525538
let response = GetSigningKeyResponse::builder().signing_key(signing_key).build().unwrap();
526539
assert!(response.principal().is_empty());
527540
assert!(response.session_data().is_empty());

0 commit comments

Comments
 (0)