From a415492e5e1b44ad6780f119f62cb3faff91e8f9 Mon Sep 17 00:00:00 2001 From: gibbz00 Date: Sat, 11 May 2024 13:25:05 +0200 Subject: [PATCH 1/3] Define `new_type_*!` constructors with `impl Into<$type>` --- src/macros.rs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/macros.rs b/src/macros.rs index 0f4793ab..2506c393 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -129,8 +129,8 @@ macro_rules! new_type { #[allow(dead_code)] #[doc = $new_doc] - pub fn new(s: $type) -> Self { - $name(s) + pub fn new(s: impl Into<$type>) -> Self { + $name(s.into()) } } impl std::ops::Deref for $name { @@ -238,8 +238,8 @@ macro_rules! new_secret_type { $($item)* #[doc = $new_doc] - pub fn new(s: $type) -> Self { - $name(s) + pub fn new(s: impl Into<$type>) -> Self { + $name(s.into()) } #[doc = $secret_doc] /// @@ -332,7 +332,8 @@ macro_rules! new_url_type { pub struct $name(url::Url, String); impl $name { #[doc = $new_doc] - pub fn new(url: String) -> Result { + pub fn new(url: impl Into) -> Result { + let url = url.into(); Ok($name(url::Url::parse(&url)?, url)) } #[doc = $from_url_doc] From f95b00fe3a5c1e8e9f6d8f723e93dadb052eaf0b Mon Sep 17 00:00:00 2001 From: gibbz00 Date: Sat, 11 May 2024 13:27:55 +0200 Subject: [PATCH 2/3] TEMP: patch oauth2 with its `Into` PR --- Cargo.toml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Cargo.toml b/Cargo.toml index 2cb0a619..1d678a39 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -77,3 +77,7 @@ pretty_assertions = "1.0" reqwest = { version = "0.12", features = ["blocking", "rustls-tls"], default-features = false } retry = "1.0" anyhow = "1.0" + +[patch.crates-io] +# TEMP: https://github.com/ramosbugs/oauth2-rs/pull/275 +oauth2 = { git = "https://github.com/gibbz00/oauth2-rs", branch = "into_string" } From 7635876b703adb50e529a6db9592dc8b08eef4f6 Mon Sep 17 00:00:00 2001 From: gibbz00 Date: Sat, 11 May 2024 13:47:28 +0200 Subject: [PATCH 3/3] Remove redundant `.to_string()` --- examples/gitlab.rs | 8 +- examples/google.rs | 15 ++-- examples/okta_device_grant.rs | 2 +- src/authorization.rs | 87 ++++++++++--------- src/client.rs | 18 ++-- src/core/jwk/tests.rs | 20 ++--- src/discovery/tests.rs | 111 ++++++++++-------------- src/id_token/tests.rs | 149 +++++++++++++-------------------- src/jwt/mod.rs | 2 +- src/jwt/tests.rs | 8 +- src/lib.rs | 84 +++++++++---------- src/logout.rs | 35 ++------ src/macros.rs | 2 +- src/registration/tests.rs | 134 ++++++++++++----------------- src/types/localized.rs | 2 +- src/types/tests.rs | 13 ++- src/verification/mod.rs | 4 +- src/verification/tests.rs | 65 +++++++------- tests/rp_certification_code.rs | 10 +-- tests/rp_common.rs | 10 +-- 20 files changed, 328 insertions(+), 451 deletions(-) diff --git a/examples/gitlab.rs b/examples/gitlab.rs index baaec70a..425a5184 100644 --- a/examples/gitlab.rs +++ b/examples/gitlab.rs @@ -63,7 +63,7 @@ fn main() { env::var("GITLAB_CLIENT_SECRET") .expect("Missing the GITLAB_CLIENT_SECRET environment variable."), ); - let issuer_url = IssuerUrl::new("https://gitlab.com".to_string()).unwrap_or_else(|err| { + let issuer_url = IssuerUrl::new("https://gitlab.com").unwrap_or_else(|err| { handle_error(&err, "Invalid issuer URL"); unreachable!(); }); @@ -93,7 +93,7 @@ fn main() { // This example will be running its own server at localhost:8080. // See below for the server implementation. .set_redirect_uri( - RedirectUrl::new("http://localhost:8080".to_string()).unwrap_or_else(|err| { + RedirectUrl::new("http://localhost:8080").unwrap_or_else(|err| { handle_error(&err, "Invalid redirect URL"); unreachable!(); }), @@ -107,8 +107,8 @@ fn main() { Nonce::new_random, ) // This example is requesting access to the the user's profile including email. - .add_scope(Scope::new("email".to_string())) - .add_scope(Scope::new("profile".to_string())) + .add_scope(Scope::new("email")) + .add_scope(Scope::new("profile")) .url(); println!("Open this URL in your browser:\n{authorize_url}\n"); diff --git a/examples/google.rs b/examples/google.rs index 5a88eb11..ee9f5166 100644 --- a/examples/google.rs +++ b/examples/google.rs @@ -78,11 +78,10 @@ fn main() { env::var("GOOGLE_CLIENT_SECRET") .expect("Missing the GOOGLE_CLIENT_SECRET environment variable."), ); - let issuer_url = - IssuerUrl::new("https://accounts.google.com".to_string()).unwrap_or_else(|err| { - handle_error(&err, "Invalid issuer URL"); - unreachable!(); - }); + let issuer_url = IssuerUrl::new("https://accounts.google.com").unwrap_or_else(|err| { + handle_error(&err, "Invalid issuer URL"); + unreachable!(); + }); let http_client = reqwest::blocking::ClientBuilder::new() // Following redirects opens the client up to SSRF vulnerabilities. @@ -128,7 +127,7 @@ fn main() { // This example will be running its own server at localhost:8080. // See below for the server implementation. .set_redirect_uri( - RedirectUrl::new("http://localhost:8080".to_string()).unwrap_or_else(|err| { + RedirectUrl::new("http://localhost:8080").unwrap_or_else(|err| { handle_error(&err, "Invalid redirect URL"); unreachable!(); }), @@ -149,8 +148,8 @@ fn main() { Nonce::new_random, ) // This example is requesting access to the "calendar" features and the user's profile. - .add_scope(Scope::new("email".to_string())) - .add_scope(Scope::new("profile".to_string())) + .add_scope(Scope::new("email")) + .add_scope(Scope::new("profile")) .url(); println!("Open this URL in your browser:\n{}\n", authorize_url); diff --git a/examples/okta_device_grant.rs b/examples/okta_device_grant.rs index f548e3c9..1176d993 100644 --- a/examples/okta_device_grant.rs +++ b/examples/okta_device_grant.rs @@ -109,7 +109,7 @@ fn main() -> Result<(), anyhow::Error> { let details: CoreDeviceAuthorizationResponse = client .exchange_device_code() - .add_scope(Scope::new("profile".to_string())) + .add_scope(Scope::new("profile")) .request(&http_client) .unwrap_or_else(|err| { handle_error(&err, "Failed to get device code"); diff --git a/src/authorization.rs b/src/authorization.rs index 7f699fec..c8fff63e 100644 --- a/src/authorization.rs +++ b/src/authorization.rs @@ -285,13 +285,13 @@ mod tests { > { color_backtrace::install(); CoreClient::new( - ClientId::new("aaa".to_string()), - IssuerUrl::new("https://example".to_string()).unwrap(), + ClientId::new("aaa"), + IssuerUrl::new("https://example").unwrap(), JsonWebKeySet::default(), ) - .set_client_secret(ClientSecret::new("bbb".to_string())) - .set_auth_uri(AuthUrl::new("https://example/authorize".to_string()).unwrap()) - .set_token_uri(TokenUrl::new("https://example/token".to_string()).unwrap()) + .set_client_secret(ClientSecret::new("bbb")) + .set_auth_uri(AuthUrl::new("https://example/authorize").unwrap()) + .set_token_uri(TokenUrl::new("https://example/token").unwrap()) } #[test] @@ -301,8 +301,8 @@ mod tests { let (authorize_url, _, _) = client .authorize_url( AuthenticationFlow::AuthorizationCode::, - || CsrfToken::new("CSRF123".to_string()), - || Nonce::new("NONCE456".to_string()), + || CsrfToken::new("CSRF123"), + || Nonce::new("NONCE456"), ) .url(); @@ -320,8 +320,8 @@ mod tests { let (authorize_url, _, _) = client .authorize_url( AuthenticationFlow::::Implicit(true), - || CsrfToken::new("CSRF123".to_string()), - || Nonce::new("NONCE456".to_string()), + || CsrfToken::new("CSRF123"), + || Nonce::new("NONCE456"), ) .url(); @@ -342,8 +342,8 @@ mod tests { CoreResponseType::Code, CoreResponseType::Extension("other".to_string()), ]), - || CsrfToken::new("CSRF123".to_string()), - || Nonce::new("NONCE456".to_string()), + || CsrfToken::new("CSRF123"), + || Nonce::new("NONCE456"), ) .url(); @@ -356,30 +356,30 @@ mod tests { #[test] fn test_authorize_url_full() { - let client = new_client() - .set_redirect_uri(RedirectUrl::new("http://localhost:8888/".to_string()).unwrap()); + let client = + new_client().set_redirect_uri(RedirectUrl::new("http://localhost:8888/").unwrap()); let flow = CoreAuthenticationFlow::AuthorizationCode; fn new_csrf() -> CsrfToken { - CsrfToken::new("CSRF123".to_string()) + CsrfToken::new("CSRF123") } fn new_nonce() -> Nonce { - Nonce::new("NONCE456".to_string()) + Nonce::new("NONCE456") } let (authorize_url, _, _) = client .authorize_url(flow.clone(), new_csrf, new_nonce) - .add_scope(Scope::new("email".to_string())) + .add_scope(Scope::new("email")) .set_display(CoreAuthDisplay::Touch) .add_prompt(CoreAuthPrompt::Login) .add_prompt(CoreAuthPrompt::Consent) .set_max_age(Duration::from_secs(1800)) - .add_ui_locale(LanguageTag::new("fr-CA".to_string())) - .add_ui_locale(LanguageTag::new("fr".to_string())) - .add_ui_locale(LanguageTag::new("en".to_string())) + .add_ui_locale(LanguageTag::new("fr-CA")) + .add_ui_locale(LanguageTag::new("fr")) + .add_ui_locale(LanguageTag::new("en")) .add_auth_context_value(AuthenticationContextClass::new( - "urn:mace:incommon:iap:silver".to_string(), + "urn:mace:incommon:iap:silver", )) .url(); assert_eq!( @@ -405,18 +405,18 @@ mod tests { let (authorize_url, _, _) = client .authorize_url(flow.clone(), new_csrf, new_nonce) - .add_scope(Scope::new("email".to_string())) + .add_scope(Scope::new("email")) .set_display(CoreAuthDisplay::Touch) .set_id_token_hint(&id_token) - .set_login_hint(LoginHint::new("foo@bar.com".to_string())) + .set_login_hint(LoginHint::new("foo@bar.com")) .add_prompt(CoreAuthPrompt::Login) .add_prompt(CoreAuthPrompt::Consent) .set_max_age(Duration::from_secs(1800)) - .add_ui_locale(LanguageTag::new("fr-CA".to_string())) - .add_ui_locale(LanguageTag::new("fr".to_string())) - .add_ui_locale(LanguageTag::new("en".to_string())) + .add_ui_locale(LanguageTag::new("fr-CA")) + .add_ui_locale(LanguageTag::new("fr")) + .add_ui_locale(LanguageTag::new("en")) .add_auth_context_value(AuthenticationContextClass::new( - "urn:mace:incommon:iap:silver".to_string(), + "urn:mace:incommon:iap:silver", )) .add_extra_param("foo", "bar") .url(); @@ -434,21 +434,18 @@ mod tests { let (authorize_url, _, _) = client .authorize_url(flow, new_csrf, new_nonce) - .add_scopes(vec![ - Scope::new("email".to_string()), - Scope::new("profile".to_string()), - ]) + .add_scopes(vec![Scope::new("email"), Scope::new("profile")]) .set_display(CoreAuthDisplay::Touch) .set_id_token_hint(&id_token) - .set_login_hint(LoginHint::new("foo@bar.com".to_string())) + .set_login_hint(LoginHint::new("foo@bar.com")) .add_prompt(CoreAuthPrompt::Login) .add_prompt(CoreAuthPrompt::Consent) .set_max_age(Duration::from_secs(1800)) - .add_ui_locale(LanguageTag::new("fr-CA".to_string())) - .add_ui_locale(LanguageTag::new("fr".to_string())) - .add_ui_locale(LanguageTag::new("en".to_string())) + .add_ui_locale(LanguageTag::new("fr-CA")) + .add_ui_locale(LanguageTag::new("fr")) + .add_ui_locale(LanguageTag::new("en")) .add_auth_context_value(AuthenticationContextClass::new( - "urn:mace:incommon:iap:silver".to_string(), + "urn:mace:incommon:iap:silver", )) .add_extra_param("foo", "bar") .url(); @@ -467,33 +464,33 @@ mod tests { #[test] fn test_authorize_url_redirect_url_override() { - let client = new_client() - .set_redirect_uri(RedirectUrl::new("http://localhost:8888/".to_string()).unwrap()); + let client = + new_client().set_redirect_uri(RedirectUrl::new("http://localhost:8888/").unwrap()); let flow = CoreAuthenticationFlow::AuthorizationCode; fn new_csrf() -> CsrfToken { - CsrfToken::new("CSRF123".to_string()) + CsrfToken::new("CSRF123") } fn new_nonce() -> Nonce { - Nonce::new("NONCE456".to_string()) + Nonce::new("NONCE456") } let (authorize_url, _, _) = client .authorize_url(flow, new_csrf, new_nonce) - .add_scope(Scope::new("email".to_string())) + .add_scope(Scope::new("email")) .set_display(CoreAuthDisplay::Touch) .add_prompt(CoreAuthPrompt::Login) .add_prompt(CoreAuthPrompt::Consent) .set_max_age(Duration::from_secs(1800)) - .add_ui_locale(LanguageTag::new("fr-CA".to_string())) - .add_ui_locale(LanguageTag::new("fr".to_string())) - .add_ui_locale(LanguageTag::new("en".to_string())) + .add_ui_locale(LanguageTag::new("fr-CA")) + .add_ui_locale(LanguageTag::new("fr")) + .add_ui_locale(LanguageTag::new("en")) .add_auth_context_value(AuthenticationContextClass::new( - "urn:mace:incommon:iap:silver".to_string(), + "urn:mace:incommon:iap:silver", )) .set_redirect_uri(Cow::Owned( - RedirectUrl::new("http://localhost:8888/alternative".to_string()).unwrap(), + RedirectUrl::new("http://localhost:8888/alternative").unwrap(), )) .url(); assert_eq!( diff --git a/src/client.rs b/src/client.rs index 8617a1be..bfe759fe 100644 --- a/src/client.rs +++ b/src/client.rs @@ -51,14 +51,14 @@ const OPENID_SCOPE: &str = "openid"; /// # /// # let client = /// # CoreClient::new( -/// # ClientId::new("aaa".to_string()), -/// # IssuerUrl::new("https://example".to_string()).unwrap(), +/// # ClientId::new("aaa"), +/// # IssuerUrl::new("https://example").unwrap(), /// # JsonWebKeySet::default(), /// # ) -/// # .set_client_secret(ClientSecret::new("bbb".to_string())) -/// # .set_auth_uri(AuthUrl::new("https://example/authorize".to_string()).unwrap()) -/// # .set_token_uri(TokenUrl::new("https://example/token".to_string()).unwrap()) -/// # .set_revocation_url(RevocationUrl::new("https://revocation/url".to_string()).unwrap()); +/// # .set_client_secret(ClientSecret::new("bbb")) +/// # .set_auth_uri(AuthUrl::new("https://example/authorize").unwrap()) +/// # .set_token_uri(TokenUrl::new("https://example/token").unwrap()) +/// # .set_revocation_url(RevocationUrl::new("https://revocation/url").unwrap()); /// # /// # #[derive(Debug, Error)] /// # enum FakeError { @@ -81,7 +81,7 @@ const OPENID_SCOPE: &str = "openid"; /// # }; /// # /// let res = client -/// .revoke_token(AccessToken::new("some token".to_string()).into()) +/// .revoke_token(AccessToken::new("some token").into()) /// .unwrap() /// .request(&http_client); /// @@ -782,7 +782,7 @@ where ui_locales: Vec::new(), }; if self.use_openid_scope { - request.add_scope(Scope::new(OPENID_SCOPE.to_string())) + request.add_scope(Scope::new(OPENID_SCOPE)) } else { request } @@ -1124,7 +1124,7 @@ where pub fn exchange_device_code(&self) -> DeviceAuthorizationRequest { let request = self.oauth2_client.exchange_device_code(); if self.use_openid_scope { - request.add_scope(Scope::new(OPENID_SCOPE.to_string())) + request.add_scope(Scope::new(OPENID_SCOPE)) } else { request } diff --git a/src/core/jwk/tests.rs b/src/core/jwk/tests.rs index 7350532b..10f55be7 100644 --- a/src/core/jwk/tests.rs +++ b/src/core/jwk/tests.rs @@ -34,7 +34,7 @@ fn test_core_jwk_deserialization_rsa() { let key: CoreJsonWebKey = serde_json::from_str(json).expect("deserialization failed"); assert_eq!(key.kty, CoreJsonWebKeyType::RSA); assert_eq!(key.use_, Some(CoreJsonWebKeyUse::Signature)); - assert_eq!(key.kid, Some(JsonWebKeyId::new("2011-04-29".to_string()))); + assert_eq!(key.kid, Some(JsonWebKeyId::new("2011-04-29"))); assert_eq!( key.n, Some(Base64UrlEncodedBytes::new(vec![ @@ -71,7 +71,7 @@ fn test_core_jwk_deserialization_ec() { let key: CoreJsonWebKey = serde_json::from_str(json).expect("deserialization failed"); assert_eq!(key.kty, CoreJsonWebKeyType::EllipticCurve); assert_eq!(key.use_, Some(CoreJsonWebKeyUse::Signature)); - assert_eq!(key.kid, Some(JsonWebKeyId::new("2011-04-29".to_string()))); + assert_eq!(key.kid, Some(JsonWebKeyId::new("2011-04-29"))); assert_eq!(key.crv, Some(CoreJsonCurveType::P256)); assert_eq!( key.y, @@ -970,17 +970,11 @@ fn test_jwks_unsupported_key() { assert_eq!(jwks.keys()[0].kty, CoreJsonWebKeyType::RSA); assert_eq!(jwks.keys()[0].use_, Some(CoreJsonWebKeyUse::Signature)); - assert_eq!( - jwks.keys()[0].kid, - Some(JsonWebKeyId::new("2011-04-29".to_string())) - ); + assert_eq!(jwks.keys()[0].kid, Some(JsonWebKeyId::new("2011-04-29"))); assert_eq!(jwks.keys()[1].kty, CoreJsonWebKeyType::EllipticCurve); assert_eq!(jwks.keys()[1].use_, Some(CoreJsonWebKeyUse::Signature)); - assert_eq!( - jwks.keys()[1].kid, - Some(JsonWebKeyId::new("2011-05-01".to_string())) - ); + assert_eq!(jwks.keys()[1].kid, Some(JsonWebKeyId::new("2011-05-01"))); assert_eq!(jwks.keys()[1].crv, Some(CoreJsonCurveType::P256)); } @@ -1010,7 +1004,7 @@ fn test_jwks_unsupported_alg() { .expect("deserialization should succeed"); assert_eq!(jwks.keys().len(), 1); let key = &jwks.keys()[0]; - assert_eq!(&key.kid, &Some(JsonWebKeyId::new("2011-05-01".to_string()))); + assert_eq!(&key.kid, &Some(JsonWebKeyId::new("2011-05-01"))); } // Test filtering keys by algorithm @@ -1050,7 +1044,7 @@ fn test_jwks_same_kid_different_alg() { { let keys = jwks.filter_keys( - Some(&JsonWebKeyId::new("2011-04-29".to_string())), + Some(&JsonWebKeyId::new("2011-04-29")), &CoreJwsSigningAlgorithm::RsaSsaPssSha384, ); assert_eq!(keys.len(), 1); @@ -1064,7 +1058,7 @@ fn test_jwks_same_kid_different_alg() { { let keys = jwks.filter_keys( - Some(&JsonWebKeyId::new("2011-04-29".to_string())), + Some(&JsonWebKeyId::new("2011-04-29")), &CoreJwsSigningAlgorithm::RsaSsaPssSha512, ); assert_eq!(keys.len(), 0); diff --git a/src/discovery/tests.rs b/src/discovery/tests.rs index 7b6436b7..cb492bbc 100644 --- a/src/discovery/tests.rs +++ b/src/discovery/tests.rs @@ -242,19 +242,16 @@ fn test_discovery_deserialization() { ]; let new_provider_metadata = CoreProviderMetadata::new( IssuerUrl::new( - "https://rp.certification.openid.net:8080/openidconnect-rs/rp-response_type-code" - .to_string(), + "https://rp.certification.openid.net:8080/openidconnect-rs/rp-response_type-code", ) .unwrap(), AuthUrl::new( "https://rp.certification.openid.net:8080/openidconnect-rs/\ - rp-response_type-code/authorization" - .to_string(), + rp-response_type-code/authorization", ) .unwrap(), JsonWebKeySetUrl::new( - "https://rp.certification.openid.net:8080/static/jwks_3INbZl52IrrPCp2j.json" - .to_string(), + "https://rp.certification.openid.net:8080/static/jwks_3INbZl52IrrPCp2j.json", ) .unwrap(), vec![ResponseTypes::new(vec![CoreResponseType::Code])], @@ -281,13 +278,13 @@ fn test_discovery_deserialization() { CoreJwsSigningAlgorithm::RsaSsaPssSha512, ])) .set_scopes_supported(Some(vec![ - Scope::new("email".to_string()), - Scope::new("phone".to_string()), - Scope::new("profile".to_string()), - Scope::new("openid".to_string()), - Scope::new("address".to_string()), - Scope::new("offline_access".to_string()), - Scope::new("openid".to_string()), + Scope::new("email"), + Scope::new("phone"), + Scope::new("profile"), + Scope::new("openid"), + Scope::new("address"), + Scope::new("offline_access"), + Scope::new("openid"), ])) .set_userinfo_signing_alg_values_supported(Some(all_signing_algs)) .set_id_token_encryption_enc_values_supported(Some(vec![ @@ -313,8 +310,7 @@ fn test_discovery_deserialization() { .set_registration_endpoint(Some( RegistrationUrl::new( "https://rp.certification.openid.net:8080/openidconnect-rs/\ - rp-response_type-code/registration" - .to_string(), + rp-response_type-code/registration", ) .unwrap(), )) @@ -330,8 +326,7 @@ fn test_discovery_deserialization() { .set_userinfo_endpoint(Some( UserInfoUrl::new( "https://rp.certification.openid.net:8080/openidconnect-rs/\ - rp-response_type-code/userinfo" - .to_string(), + rp-response_type-code/userinfo", ) .unwrap(), )) @@ -365,7 +360,7 @@ fn test_discovery_deserialization() { "locale", ] .iter() - .map(|claim| CoreClaimName::new((*claim).to_string())) + .map(|claim| CoreClaimName::new(*claim)) .collect(), )) .set_request_object_encryption_alg_values_supported(Some(all_encryption_algs.clone())) @@ -379,8 +374,7 @@ fn test_discovery_deserialization() { .set_token_endpoint(Some( TokenUrl::new( "https://rp.certification.openid.net:8080/openidconnect-rs/\ - rp-response_type-code/token" - .to_string(), + rp-response_type-code/token", ) .unwrap(), )) @@ -394,9 +388,7 @@ fn test_discovery_deserialization() { CoreJweContentEncryptionAlgorithm::Aes192Gcm, CoreJweContentEncryptionAlgorithm::Aes256Gcm, ])) - .set_acr_values_supported(Some(vec![AuthenticationContextClass::new( - "PASSWORD".to_string(), - )])); + .set_acr_values_supported(Some(vec![AuthenticationContextClass::new("PASSWORD")])); let provider_metadata: CoreProviderMetadata = serde_json::from_str(&json_response).unwrap(); assert_eq!(provider_metadata, new_provider_metadata); @@ -407,7 +399,6 @@ fn test_discovery_deserialization() { assert_eq!( IssuerUrl::new( "https://rp.certification.openid.net:8080/openidconnect-rs/rp-response_type-code" - .to_string() ) .unwrap(), *provider_metadata.issuer() @@ -416,7 +407,6 @@ fn test_discovery_deserialization() { AuthUrl::new( "https://rp.certification.openid.net:8080/openidconnect-rs/rp-response_type-code\ /authorization" - .to_string() ) .unwrap(), *provider_metadata.authorization_endpoint() @@ -426,7 +416,6 @@ fn test_discovery_deserialization() { &TokenUrl::new( "https://rp.certification.openid.net:8080/openidconnect-rs\ /rp-response_type-code/token" - .to_string() ) .unwrap() ), @@ -437,7 +426,6 @@ fn test_discovery_deserialization() { &UserInfoUrl::new( "https://rp.certification.openid.net:8080/openidconnect-rs\ /rp-response_type-code/userinfo" - .to_string() ) .unwrap() ), @@ -446,7 +434,6 @@ fn test_discovery_deserialization() { assert_eq!( &JsonWebKeySetUrl::new( "https://rp.certification.openid.net:8080/static/jwks_3INbZl52IrrPCp2j.json" - .to_string() ) .unwrap(), provider_metadata.jwks_uri() @@ -456,7 +443,6 @@ fn test_discovery_deserialization() { &RegistrationUrl::new( "https://rp.certification.openid.net:8080/openidconnect-rs\ /rp-response_type-code/registration" - .to_string() ) .unwrap() ), @@ -474,7 +460,7 @@ fn test_discovery_deserialization() { "openid", ] .iter() - .map(|s| (*s).to_string()) + .copied() .map(Scope::new) .collect::>() ), @@ -506,9 +492,7 @@ fn test_discovery_deserialization() { provider_metadata.grant_types_supported() ); assert_eq!( - Some(&vec![AuthenticationContextClass::new( - "PASSWORD".to_string(), - )]), + Some(&vec![AuthenticationContextClass::new("PASSWORD",)]), provider_metadata.acr_values_supported() ); assert_eq!( @@ -687,26 +671,26 @@ fn test_discovery_deserialization() { ); assert_eq!( Some(&vec![ - CoreClaimName::new("name".to_string()), - CoreClaimName::new("given_name".to_string()), - CoreClaimName::new("middle_name".to_string()), - CoreClaimName::new("picture".to_string()), - CoreClaimName::new("email_verified".to_string()), - CoreClaimName::new("birthdate".to_string()), - CoreClaimName::new("sub".to_string()), - CoreClaimName::new("address".to_string()), - CoreClaimName::new("zoneinfo".to_string()), - CoreClaimName::new("email".to_string()), - CoreClaimName::new("gender".to_string()), - CoreClaimName::new("preferred_username".to_string()), - CoreClaimName::new("family_name".to_string()), - CoreClaimName::new("website".to_string()), - CoreClaimName::new("profile".to_string()), - CoreClaimName::new("phone_number_verified".to_string()), - CoreClaimName::new("nickname".to_string()), - CoreClaimName::new("updated_at".to_string()), - CoreClaimName::new("phone_number".to_string()), - CoreClaimName::new("locale".to_string()), + CoreClaimName::new("name"), + CoreClaimName::new("given_name"), + CoreClaimName::new("middle_name"), + CoreClaimName::new("picture"), + CoreClaimName::new("email_verified"), + CoreClaimName::new("birthdate"), + CoreClaimName::new("sub"), + CoreClaimName::new("address"), + CoreClaimName::new("zoneinfo"), + CoreClaimName::new("email"), + CoreClaimName::new("gender"), + CoreClaimName::new("preferred_username"), + CoreClaimName::new("family_name"), + CoreClaimName::new("website"), + CoreClaimName::new("profile"), + CoreClaimName::new("phone_number_verified"), + CoreClaimName::new("nickname"), + CoreClaimName::new("updated_at"), + CoreClaimName::new("phone_number"), + CoreClaimName::new("locale"), ]), provider_metadata.claims_supported() ); @@ -791,7 +775,6 @@ fn test_discovery_deserialization_other_fields() { assert_eq!( IssuerUrl::new( "https://rp.certification.openid.net:8080/openidconnect-rs/rp-response_type-code" - .to_string() ) .unwrap(), *provider_metadata.issuer() @@ -800,7 +783,6 @@ fn test_discovery_deserialization_other_fields() { AuthUrl::new( "https://rp.certification.openid.net:8080/openidconnect-rs/rp-response_type-code\ /authorization" - .to_string() ) .unwrap(), *provider_metadata.authorization_endpoint() @@ -810,7 +792,6 @@ fn test_discovery_deserialization_other_fields() { assert_eq!( JsonWebKeySetUrl::new( "https://rp.certification.openid.net:8080/static/jwks_oMXD5waO08Q1GEnv.json" - .to_string() ) .unwrap(), *provider_metadata.jwks_uri() @@ -914,7 +895,6 @@ fn test_discovery_deserialization_other_fields() { &ServiceDocUrl::new( "https://rp.certification.openid.net:8080/openidconnect-rs/rp-response_type-code\ /documentation" - .to_string() ) .unwrap() ), @@ -922,17 +902,17 @@ fn test_discovery_deserialization_other_fields() { ); assert_eq!( Some(&vec![ - LanguageTag::new("de".to_string()), - LanguageTag::new("fr".to_string()), - LanguageTag::new("de-CH-1901".to_string()), + LanguageTag::new("de"), + LanguageTag::new("fr"), + LanguageTag::new("de-CH-1901"), ]), provider_metadata.claims_locales_supported() ); assert_eq!( Some(&vec![ - LanguageTag::new("ja".to_string()), - LanguageTag::new("sr-Latn".to_string()), - LanguageTag::new("yue-HK".to_string()), + LanguageTag::new("ja"), + LanguageTag::new("sr-Latn"), + LanguageTag::new("yue-HK"), ]), provider_metadata.ui_locales_supported() ); @@ -945,7 +925,6 @@ fn test_discovery_deserialization_other_fields() { &OpPolicyUrl::new( "https://rp.certification.openid.net:8080/openidconnect-rs/rp-response_type-code\ /op_policy" - .to_string() ) .unwrap() ), @@ -956,7 +935,6 @@ fn test_discovery_deserialization_other_fields() { &OpTosUrl::new( "https://rp.certification.openid.net:8080/openidconnect-rs/rp-response_type-code\ /op_tos" - .to_string() ) .unwrap() ), @@ -1036,7 +1014,6 @@ fn test_unsupported_enum_values() { assert_eq!( IssuerUrl::new( "https://rp.certification.openid.net:8080/openidconnect-rs/rp-response_type-code" - .to_string() ) .unwrap(), *provider_metadata.issuer() @@ -1045,7 +1022,6 @@ fn test_unsupported_enum_values() { AuthUrl::new( "https://rp.certification.openid.net:8080/openidconnect-rs/rp-response_type-code\ /authorization" - .to_string() ) .unwrap(), *provider_metadata.authorization_endpoint() @@ -1055,7 +1031,6 @@ fn test_unsupported_enum_values() { assert_eq!( JsonWebKeySetUrl::new( "https://rp.certification.openid.net:8080/static/jwks_3INbZl52IrrPCp2j.json" - .to_string() ) .unwrap(), *provider_metadata.jwks_uri() diff --git a/src/id_token/tests.rs b/src/id_token/tests.rs index 304ab8c8..2c83c800 100644 --- a/src/id_token/tests.rs +++ b/src/id_token/tests.rs @@ -40,10 +40,7 @@ fn test_id_token() { *claims.issuer().url(), Url::parse("https://server.example.com").unwrap() ); - assert_eq!( - *claims.audiences(), - vec![Audience::new("s6BhdRkqt3".to_string())] - ); + assert_eq!(*claims.audiences(), vec![Audience::new("s6BhdRkqt3")]); assert_eq!( claims.expiration(), Utc.timestamp_opt(1311281970, 0) @@ -56,10 +53,7 @@ fn test_id_token() { .single() .expect("valid timestamp") ); - assert_eq!( - *claims.subject(), - SubjectIdentifier::new("24400320".to_string()) - ); + assert_eq!(*claims.subject(), SubjectIdentifier::new("24400320")); // test `ToString` implementation assert_eq!(&id_token.to_string(), ID_TOKEN); @@ -91,10 +85,7 @@ fn test_oauth2_response() { *claims.issuer().url(), Url::parse("https://server.example.com").unwrap() ); - assert_eq!( - *claims.audiences(), - vec![Audience::new("s6BhdRkqt3".to_string())] - ); + assert_eq!(*claims.audiences(), vec![Audience::new("s6BhdRkqt3")]); assert_eq!( claims.expiration(), Utc.timestamp_opt(1311281970, 0) @@ -107,10 +98,7 @@ fn test_oauth2_response() { .single() .expect("valid timestamp") ); - assert_eq!( - *claims.subject(), - SubjectIdentifier::new("24400320".to_string()) - ); + assert_eq!(*claims.subject(), SubjectIdentifier::new("24400320")); assert_eq!( serde_json::to_string(&response).expect("failed to serialize"), @@ -121,15 +109,15 @@ fn test_oauth2_response() { #[test] fn test_minimal_claims_serde() { let new_claims = CoreIdTokenClaims::new( - IssuerUrl::new("https://server.example.com".to_string()).unwrap(), - vec![Audience::new("s6BhdRkqt3".to_string())], + IssuerUrl::new("https://server.example.com").unwrap(), + vec![Audience::new("s6BhdRkqt3")], Utc.timestamp_opt(1311281970, 0) .single() .expect("valid timestamp"), Utc.timestamp_opt(1311280970, 0) .single() .expect("valid timestamp"), - StandardClaims::new(SubjectIdentifier::new("24400320".to_string())), + StandardClaims::new(SubjectIdentifier::new("24400320")), EmptyAdditionalClaims {}, ); let expected_serialized_claims = "\ @@ -250,8 +238,8 @@ fn test_complete_claims_serde() { }"; let new_claims = CoreIdTokenClaims::new( - IssuerUrl::new("https://server.example.com".to_string()).unwrap(), - vec![Audience::new("s6BhdRkqt3".to_string())], + IssuerUrl::new("https://server.example.com").unwrap(), + vec![Audience::new("s6BhdRkqt3")], Utc.timestamp_opt(1311281970, 0) .single() .expect("valid timestamp"), @@ -259,13 +247,13 @@ fn test_complete_claims_serde() { .single() .expect("valid timestamp"), StandardClaims { - sub: SubjectIdentifier::new("24400320".to_string()), + sub: SubjectIdentifier::new("24400320"), name: Some( vec![ - (None, EndUserName::new("Homer Simpson".to_string())), + (None, EndUserName::new("Homer Simpson")), ( - Some(LanguageTag::new("es".to_string())), - EndUserName::new("Jomer Simpson".to_string()), + Some(LanguageTag::new("es")), + EndUserName::new("Jomer Simpson"), ), ] .into_iter() @@ -273,21 +261,18 @@ fn test_complete_claims_serde() { ), given_name: Some( vec![ - (None, EndUserGivenName::new("Homer".to_string())), - ( - Some(LanguageTag::new("es".to_string())), - EndUserGivenName::new("Jomer".to_string()), - ), + (None, EndUserGivenName::new("Homer")), + (Some(LanguageTag::new("es")), EndUserGivenName::new("Jomer")), ] .into_iter() .collect(), ), family_name: Some( vec![ - (None, EndUserFamilyName::new("Simpson".to_string())), + (None, EndUserFamilyName::new("Simpson")), ( - Some(LanguageTag::new("es".to_string())), - EndUserFamilyName::new("Simpson".to_string()), + Some(LanguageTag::new("es")), + EndUserFamilyName::new("Simpson"), ), ] .into_iter() @@ -295,38 +280,30 @@ fn test_complete_claims_serde() { ), middle_name: Some( vec![ - (None, EndUserMiddleName::new("Jay".to_string())), - ( - Some(LanguageTag::new("es".to_string())), - EndUserMiddleName::new("Jay".to_string()), - ), + (None, EndUserMiddleName::new("Jay")), + (Some(LanguageTag::new("es")), EndUserMiddleName::new("Jay")), ] .into_iter() .collect(), ), nickname: Some( vec![ - (None, EndUserNickname::new("Homer".to_string())), - ( - Some(LanguageTag::new("es".to_string())), - EndUserNickname::new("Jomer".to_string()), - ), + (None, EndUserNickname::new("Homer")), + (Some(LanguageTag::new("es")), EndUserNickname::new("Jomer")), ] .into_iter() .collect(), ), - preferred_username: Some(EndUserUsername::new("homersimpson".to_string())), + preferred_username: Some(EndUserUsername::new("homersimpson")), profile: Some( vec![ ( None, - EndUserProfileUrl::new("https://example.com/profile?id=12345".to_string()), + EndUserProfileUrl::new("https://example.com/profile?id=12345"), ), ( - Some(LanguageTag::new("es".to_string())), - EndUserProfileUrl::new( - "https://example.com/profile?id=12345&lang=es".to_string(), - ), + Some(LanguageTag::new("es")), + EndUserProfileUrl::new("https://example.com/profile?id=12345&lang=es"), ), ] .into_iter() @@ -336,13 +313,11 @@ fn test_complete_claims_serde() { vec![ ( None, - EndUserPictureUrl::new("https://example.com/avatar?id=12345".to_string()), + EndUserPictureUrl::new("https://example.com/avatar?id=12345"), ), ( - Some(LanguageTag::new("es".to_string())), - EndUserPictureUrl::new( - "https://example.com/avatar?id=12345&lang=es".to_string(), - ), + Some(LanguageTag::new("es")), + EndUserPictureUrl::new("https://example.com/avatar?id=12345&lang=es"), ), ] .into_iter() @@ -350,36 +325,33 @@ fn test_complete_claims_serde() { ), website: Some( vec![ + (None, EndUserWebsiteUrl::new("https://homersimpson.me")), ( - None, - EndUserWebsiteUrl::new("https://homersimpson.me".to_string()), - ), - ( - Some(LanguageTag::new("es".to_string())), - EndUserWebsiteUrl::new("https://homersimpson.me/?lang=es".to_string()), + Some(LanguageTag::new("es")), + EndUserWebsiteUrl::new("https://homersimpson.me/?lang=es"), ), ] .into_iter() .collect(), ), - email: Some(EndUserEmail::new("homer@homersimpson.me".to_string())), + email: Some(EndUserEmail::new("homer@homersimpson.me")), email_verified: Some(true), - gender: Some(CoreGenderClaim::new("male".to_string())), - birthday: Some(EndUserBirthday::new("1956-05-12".to_string())), - birthdate: Some(EndUserBirthday::new("1956-07-12".to_string())), - zoneinfo: Some(EndUserTimezone::new("America/Los_Angeles".to_string())), - locale: Some(LanguageTag::new("en-US".to_string())), - phone_number: Some(EndUserPhoneNumber::new("+1 (555) 555-5555".to_string())), + gender: Some(CoreGenderClaim::new("male")), + birthday: Some(EndUserBirthday::new("1956-05-12")), + birthdate: Some(EndUserBirthday::new("1956-07-12")), + zoneinfo: Some(EndUserTimezone::new("America/Los_Angeles")), + locale: Some(LanguageTag::new("en-US")), + phone_number: Some(EndUserPhoneNumber::new("+1 (555) 555-5555")), phone_number_verified: Some(false), address: Some(AddressClaim { formatted: Some(FormattedAddress::new( - "1234 Hollywood Blvd., Los Angeles, CA 90210".to_string(), + "1234 Hollywood Blvd., Los Angeles, CA 90210", )), - street_address: Some(StreetAddress::new("1234 Hollywood Blvd.".to_string())), - locality: Some(AddressLocality::new("Los Angeles".to_string())), - region: Some(AddressRegion::new("CA".to_string())), - postal_code: Some(AddressPostalCode::new("90210".to_string())), - country: Some(AddressCountry::new("US".to_string())), + street_address: Some(StreetAddress::new("1234 Hollywood Blvd.")), + locality: Some(AddressLocality::new("Los Angeles")), + region: Some(AddressRegion::new("CA")), + postal_code: Some(AddressPostalCode::new("90210")), + country: Some(AddressCountry::new("US")), }), updated_at: Some( Utc.timestamp_opt(1311283970, 0) @@ -394,21 +366,17 @@ fn test_complete_claims_serde() { .single() .expect("valid timestamp"), )) - .set_nonce(Some(Nonce::new("Zm9vYmFy".to_string()))) + .set_nonce(Some(Nonce::new("Zm9vYmFy"))) .set_auth_context_ref(Some(AuthenticationContextClass::new( - "urn:mace:incommon:iap:silver".to_string(), + "urn:mace:incommon:iap:silver", ))) .set_auth_method_refs(Some(vec![ - AuthenticationMethodReference::new("password".to_string()), - AuthenticationMethodReference::new("totp".to_string()), + AuthenticationMethodReference::new("password"), + AuthenticationMethodReference::new("totp"), ])) - .set_authorized_party(Some(ClientId::new("dGhpc19jbGllbnQ".to_string()))) - .set_access_token_hash(Some(AccessTokenHash::new( - "_JPLB-GtkomFJxAOWKHPHQ".to_string(), - ))) - .set_code_hash(Some(AuthorizationCodeHash::new( - "VpTQii5T_8rgwxA-Wtb2Bw".to_string(), - ))); + .set_authorized_party(Some(ClientId::new("dGhpc19jbGllbnQ"))) + .set_access_token_hash(Some(AccessTokenHash::new("_JPLB-GtkomFJxAOWKHPHQ"))) + .set_code_hash(Some(AuthorizationCodeHash::new("VpTQii5T_8rgwxA-Wtb2Bw"))); let claims: CoreIdTokenClaims = serde_json::from_str(claims_json).expect("failed to deserialize"); @@ -533,7 +501,7 @@ fn test_audience() { .expect("failed to deserialize"); assert_eq!( *single_aud_str_claims.audiences(), - vec![Audience::new("s6BhdRkqt3".to_string())], + vec![Audience::new("s6BhdRkqt3")], ); // We always serialize aud as an array, which is valid according to the spec. @@ -560,7 +528,7 @@ fn test_audience() { .expect("failed to deserialize"); assert_eq!( *single_aud_vec_claims.audiences(), - vec![Audience::new("s6BhdRkqt3".to_string())], + vec![Audience::new("s6BhdRkqt3")], ); assert_eq!( serde_json::to_string(&single_aud_vec_claims).expect("failed to serialize"), @@ -585,10 +553,7 @@ fn test_audience() { .expect("failed to deserialize"); assert_eq!( *multi_aud_claims.audiences(), - vec![ - Audience::new("s6BhdRkqt3".to_string()), - Audience::new("aud2".to_string()) - ], + vec![Audience::new("s6BhdRkqt3"), Audience::new("aud2")], ); assert_eq!( serde_json::to_string(&multi_aud_claims).expect("failed to serialize"), @@ -685,7 +650,7 @@ fn test_audiences_claim() { fn verify_audiences(audiences_claim: &A) { assert_eq!( (*audiences_claim).audiences(), - Some(&vec![Audience::new("s6BhdRkqt3".to_string())]), + Some(&vec![Audience::new("s6BhdRkqt3")]), ) } verify_audiences(&claims); @@ -708,7 +673,7 @@ fn test_issuer_claim() { fn verify_issuer(issuer_claim: &I) { assert_eq!( (*issuer_claim).issuer(), - Some(&IssuerUrl::new("https://server.example.com".to_string()).unwrap()), + Some(&IssuerUrl::new("https://server.example.com").unwrap()), ) } verify_issuer(&claims); diff --git a/src/jwt/mod.rs b/src/jwt/mod.rs index a314f25b..714ed4c5 100644 --- a/src/jwt/mod.rs +++ b/src/jwt/mod.rs @@ -367,7 +367,7 @@ where where DE: serde::de::Error, { - let raw_token = v.to_string(); + let raw_token = v; let header: JsonWebTokenHeader; let payload: P; let signature; diff --git a/src/jwt/tests.rs b/src/jwt/tests.rs index 1d622b9e..2d5d3be7 100644 --- a/src/jwt/tests.rs +++ b/src/jwt/tests.rs @@ -191,9 +191,7 @@ fn test_jwt_basic() { assert_eq!(header.cty, None); assert_eq!( header.kid, - Some(JsonWebKeyId::new( - "bilbo.baggins@hobbiton.example".to_string() - )) + Some(JsonWebKeyId::new("bilbo.baggins@hobbiton.example")) ); assert_eq!(header.typ, None); } @@ -234,9 +232,7 @@ fn test_jwt_basic() { fn test_new_jwt() { let signing_key = CoreRsaPrivateSigningKey::from_pem( TEST_RSA_PRIV_KEY, - Some(JsonWebKeyId::new( - "bilbo.baggins@hobbiton.example".to_string(), - )), + Some(JsonWebKeyId::new("bilbo.baggins@hobbiton.example")), ) .unwrap(); let new_jwt = JsonWebToken::< diff --git a/src/lib.rs b/src/lib.rs index 9eb7a7a0..5d61656e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -169,7 +169,7 @@ //! //! // Use OpenID Connect Discovery to fetch the provider metadata. //! let provider_metadata = CoreProviderMetadata::discover( -//! &IssuerUrl::new("https://accounts.example.com".to_string())?, +//! &IssuerUrl::new("https://accounts.example.com")?, //! &http_client, //! )?; //! @@ -178,11 +178,11 @@ //! let client = //! CoreClient::from_provider_metadata( //! provider_metadata, -//! ClientId::new("client_id".to_string()), -//! Some(ClientSecret::new("client_secret".to_string())), +//! ClientId::new("client_id"), +//! Some(ClientSecret::new("client_secret")), //! ) //! // Set the URL the user will be redirected to after the authorization process. -//! .set_redirect_uri(RedirectUrl::new("http://redirect".to_string())?); +//! .set_redirect_uri(RedirectUrl::new("http://redirect")?); //! //! // Generate a PKCE challenge. //! let (pkce_challenge, pkce_verifier) = PkceCodeChallenge::new_random_sha256(); @@ -195,8 +195,8 @@ //! Nonce::new_random, //! ) //! // Set the desired scopes. -//! .add_scope(Scope::new("read".to_string())) -//! .add_scope(Scope::new("write".to_string())) +//! .add_scope(Scope::new("read")) +//! .add_scope(Scope::new("write")) //! // Set the PKCE code challenge. //! .set_pkce_challenge(pkce_challenge) //! .url(); @@ -212,7 +212,7 @@ //! // Now you can exchange it for an access token and ID token. //! let token_response = //! client -//! .exchange_code(AuthorizationCode::new("some authorization code".to_string()))? +//! .exchange_code(AuthorizationCode::new("some authorization code"))? //! // Set the PKCE code verifier. //! .set_pkce_verifier(pkce_verifier) //! .request(&http_client)?; @@ -300,10 +300,10 @@ //! # fn err_wrapper() -> Result { //! let provider_metadata = CoreProviderMetadata::new( //! // Parameters required by the OpenID Connect Discovery spec. -//! IssuerUrl::new("https://accounts.example.com".to_string())?, -//! AuthUrl::new("https://accounts.example.com/authorize".to_string())?, +//! IssuerUrl::new("https://accounts.example.com")?, +//! AuthUrl::new("https://accounts.example.com/authorize")?, //! // Use the JsonWebKeySet struct to serve the JWK Set at this URL. -//! JsonWebKeySetUrl::new("https://accounts.example.com/jwk".to_string())?, +//! JsonWebKeySetUrl::new("https://accounts.example.com/jwk")?, //! // Supported response types (flows). //! vec![ //! // Recommended: support the code flow. @@ -327,32 +327,32 @@ //! EmptyAdditionalProviderMetadata {}, //! ) //! // Specify the token endpoint (required for the code flow). -//! .set_token_endpoint(Some(TokenUrl::new("https://accounts.example.com/token".to_string())?)) +//! .set_token_endpoint(Some(TokenUrl::new("https://accounts.example.com/token")?)) //! // Recommended: support the user info endpoint. //! .set_userinfo_endpoint( -//! Some(UserInfoUrl::new("https://accounts.example.com/userinfo".to_string())?) +//! Some(UserInfoUrl::new("https://accounts.example.com/userinfo")?) //! ) //! // Recommended: specify the supported scopes. //! .set_scopes_supported(Some(vec![ -//! Scope::new("openid".to_string()), -//! Scope::new("email".to_string()), -//! Scope::new("profile".to_string()), +//! Scope::new("openid"), +//! Scope::new("email"), +//! Scope::new("profile"), //! ])) //! // Recommended: specify the supported ID token claims. //! .set_claims_supported(Some(vec![ //! // Providers may also define an enum instead of using CoreClaimName. -//! CoreClaimName::new("sub".to_string()), -//! CoreClaimName::new("aud".to_string()), -//! CoreClaimName::new("email".to_string()), -//! CoreClaimName::new("email_verified".to_string()), -//! CoreClaimName::new("exp".to_string()), -//! CoreClaimName::new("iat".to_string()), -//! CoreClaimName::new("iss".to_string()), -//! CoreClaimName::new("name".to_string()), -//! CoreClaimName::new("given_name".to_string()), -//! CoreClaimName::new("family_name".to_string()), -//! CoreClaimName::new("picture".to_string()), -//! CoreClaimName::new("locale".to_string()), +//! CoreClaimName::new("sub"), +//! CoreClaimName::new("aud"), +//! CoreClaimName::new("email"), +//! CoreClaimName::new("email_verified"), +//! CoreClaimName::new("exp"), +//! CoreClaimName::new("iat"), +//! CoreClaimName::new("iss"), +//! CoreClaimName::new("name"), +//! CoreClaimName::new("given_name"), +//! CoreClaimName::new("family_name"), +//! CoreClaimName::new("picture"), +//! CoreClaimName::new("locale"), //! ])); //! //! serde_json::to_string(&provider_metadata).map_err(From::from) @@ -382,7 +382,7 @@ //! // JsonWebKey trait or submit a PR to add the desired support to this crate. //! CoreRsaPrivateSigningKey::from_pem( //! &rsa_pem, -//! Some(JsonWebKeyId::new("key1".to_string())) +//! Some(JsonWebKeyId::new("key1")) //! ) //! .expect("Invalid RSA private key") //! .as_verification_key() @@ -435,14 +435,14 @@ //! //! # fn err_wrapper() -> Result { //! # let rsa_pem = ""; -//! # let access_token = AccessToken::new("".to_string()); +//! # let access_token = AccessToken::new(""); //! let id_token = CoreIdToken::new( //! CoreIdTokenClaims::new( //! // Specify the issuer URL for the OpenID Connect Provider. -//! IssuerUrl::new("https://accounts.example.com".to_string())?, +//! IssuerUrl::new("https://accounts.example.com")?, //! // The audience is usually a single entry with the client ID of the client for whom //! // the ID token is intended. This is a required claim. -//! vec![Audience::new("client-id-123".to_string())], +//! vec![Audience::new("client-id-123")], //! // The ID token expiration is usually much shorter than that of the access or refresh //! // tokens issued to clients. //! Utc::now() + Duration::seconds(300), @@ -452,11 +452,11 @@ //! StandardClaims::new( //! // Stable subject identifiers are recommended in place of e-mail addresses or other //! // potentially unstable identifiers. This is the only required claim. -//! SubjectIdentifier::new("5f83e0ca-2b8e-4e8c-ba0a-f80fe9bc3632".to_string()) +//! SubjectIdentifier::new("5f83e0ca-2b8e-4e8c-ba0a-f80fe9bc3632") //! ) //! // Optional: specify the user's e-mail address. This should only be provided if the //! // client has been granted the 'profile' or 'email' scopes. -//! .set_email(Some(EndUserEmail::new("bob@example.com".to_string()))) +//! .set_email(Some(EndUserEmail::new("bob@example.com"))) //! // Optional: specify whether the provider has verified the user's e-mail address. //! .set_email_verified(Some(true)), //! // OpenID Connect Providers may supply custom claims by providing a struct that @@ -472,7 +472,7 @@ //! // be used as the HMAC key. //! &CoreRsaPrivateSigningKey::from_pem( //! &rsa_pem, -//! Some(JsonWebKeyId::new("key1".to_string())) +//! Some(JsonWebKeyId::new("key1")) //! ) //! .expect("Invalid RSA private key"), //! // Uses the RS256 signature algorithm. This crate supports any RS*, PS*, or HS* @@ -489,7 +489,7 @@ //! )?; //! //! Ok(CoreTokenResponse::new( -//! AccessToken::new("some_secret".to_string()), +//! AccessToken::new("some_secret"), //! CoreTokenType::Bearer, //! CoreIdTokenFields::new(Some(id_token), EmptyExtraTokenFields {}), //! )) @@ -540,7 +540,7 @@ //! //! // Use OpenID Connect Discovery to fetch the provider metadata. //! let provider_metadata = CoreProviderMetadata::discover_async( -//! IssuerUrl::new("https://accounts.example.com".to_string())?, +//! IssuerUrl::new("https://accounts.example.com")?, //! &http_client, //! ) //! .await?; @@ -550,11 +550,11 @@ //! let client = //! CoreClient::from_provider_metadata( //! provider_metadata, -//! ClientId::new("client_id".to_string()), -//! Some(ClientSecret::new("client_secret".to_string())), +//! ClientId::new("client_id"), +//! Some(ClientSecret::new("client_secret")), //! ) //! // Set the URL the user will be redirected to after the authorization process. -//! .set_redirect_uri(RedirectUrl::new("http://redirect".to_string())?); +//! .set_redirect_uri(RedirectUrl::new("http://redirect")?); //! //! // Generate a PKCE challenge. //! let (pkce_challenge, pkce_verifier) = PkceCodeChallenge::new_random_sha256(); @@ -567,8 +567,8 @@ //! Nonce::new_random, //! ) //! // Set the desired scopes. -//! .add_scope(Scope::new("read".to_string())) -//! .add_scope(Scope::new("write".to_string())) +//! .add_scope(Scope::new("read")) +//! .add_scope(Scope::new("write")) //! // Set the PKCE code challenge. //! .set_pkce_challenge(pkce_challenge) //! .url(); @@ -584,7 +584,7 @@ //! // Now you can exchange it for an access token and ID token. //! let token_response = //! client -//! .exchange_code(AuthorizationCode::new("some authorization code".to_string()))? +//! .exchange_code(AuthorizationCode::new("some authorization code"))? //! // Set the PKCE code verifier. //! .set_pkce_verifier(pkce_verifier) //! .request_async(&http_client) diff --git a/src/logout.rs b/src/logout.rs index 79938a92..978cb6b3 100644 --- a/src/logout.rs +++ b/src/logout.rs @@ -200,29 +200,15 @@ mod tests { \"version\":\"3.0\"}"; let new_provider_metadata = ProviderMetadataWithLogout::new( - IssuerUrl::new( - "https://rp.certification.openid.net:8080/openidconnect-rs/rp-response_type-code" - .to_string(), - ) - .unwrap(), - AuthUrl::new( - "https://rp.certification.openid.net:8080/openidconnect-rs/\ - rp-response_type-code/authorization" - .to_string(), - ) - .unwrap(), - JsonWebKeySetUrl::new( - "https://rp.certification.openid.net:8080/static/jwks_3INbZl52IrrPCp2j.json" - .to_string(), - ) - .unwrap(), + IssuerUrl::new("https://rp.certification.openid.net:8080/openidconnect-rs/rp-response_type-code").unwrap(), + AuthUrl::new("https://rp.certification.openid.net:8080/openidconnect-rs/rp-response_type-code/authorization").unwrap(), + JsonWebKeySetUrl::new("https://rp.certification.openid.net:8080/static/jwks_3INbZl52IrrPCp2j.json").unwrap(), vec![], vec![], vec![], LogoutProviderMetadata { end_session_endpoint: Some(EndSessionUrl::new( "https://rp.certification.openid.net:8080/openidconnect-rs/rp-response_type-code/end_session" - .to_string() ).unwrap()), additional_metadata: Default::default(), }, @@ -235,7 +221,6 @@ mod tests { assert_eq!( Some(EndSessionUrl::new( "https://rp.certification.openid.net:8080/openidconnect-rs/rp-response_type-code/end_session" - .to_string() ).unwrap()), provider_metadata.additional_metadata().end_session_endpoint ); @@ -245,7 +230,6 @@ mod tests { fn test_logout_request_with_no_parameters() { let endpoint = EndSessionUrl::new( "https://rp.certification.openid.net:8080/openidconnect-rs/rp-response_type-code/end_session" - .to_string() ).unwrap(); let logout_url = LogoutRequest::from(endpoint).http_get_url(); @@ -262,7 +246,6 @@ mod tests { fn test_logout_request_with_all_parameters() { let endpoint = EndSessionUrl::new( "https://rp.certification.openid.net:8080/openidconnect-rs/rp-response_type-code/end_session" - .to_string() ).unwrap(); let logout_url = LogoutRequest::from(endpoint) @@ -280,14 +263,14 @@ mod tests { ) .unwrap(), ) - .set_logout_hint(LogoutHint::new("johndoe".to_string())) - .set_client_id(ClientId::new("asdf".to_string())) + .set_logout_hint(LogoutHint::new("johndoe")) + .set_client_id(ClientId::new("asdf")) .set_post_logout_redirect_uri( - PostLogoutRedirectUrl::new("https://localhost:8000/".to_string()).unwrap(), + PostLogoutRedirectUrl::new("https://localhost:8000/").unwrap(), ) - .set_state(CsrfToken::new("asdf".to_string())) - .add_ui_locale(LanguageTag::new("en-US".to_string())) - .add_ui_locale(LanguageTag::new("fr-FR".to_string())) + .set_state(CsrfToken::new("asdf")) + .add_ui_locale(LanguageTag::new("en-US")) + .add_ui_locale(LanguageTag::new("fr-FR")) .http_get_url(); assert_eq!( diff --git a/src/macros.rs b/src/macros.rs index 2506c393..10e1101a 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -390,7 +390,7 @@ macro_rules! new_url_type { where E: ::serde::de::Error, { - $name::new(v.to_string()).map_err(E::custom) + $name::new(v).map_err(E::custom) } } deserializer.deserialize_str(UrlVisitor {}) diff --git a/src/registration/tests.rs b/src/registration/tests.rs index 59d3d26f..3c3f76d0 100644 --- a/src/registration/tests.rs +++ b/src/registration/tests.rs @@ -65,8 +65,8 @@ fn test_metadata_serialization() { assert_eq!( *client_metadata.redirect_uris(), vec![ - RedirectUrl::new("https://example.com/redirect-1".to_string()).unwrap(), - RedirectUrl::new("https://example.com/redirect-2".to_string()).unwrap(), + RedirectUrl::new("https://example.com/redirect-1").unwrap(), + RedirectUrl::new("https://example.com/redirect-2").unwrap(), ] ); assert_eq!( @@ -97,32 +97,26 @@ fn test_metadata_serialization() { assert_eq!( *client_metadata.contacts().unwrap(), vec![ - ClientContactEmail::new("user@example.com".to_string()), - ClientContactEmail::new("admin@openidconnect.local".to_string()), + ClientContactEmail::new("user@example.com"), + ClientContactEmail::new("admin@openidconnect.local"), ] ); assert_eq!( sorted(client_metadata.client_name().unwrap().clone()) .collect::, ClientName)>>(), vec![ - (None, ClientName::new("Example".to_string())), - ( - Some(LanguageTag::new("es".to_string())), - ClientName::new("Ejemplo".to_string()), - ), + (None, ClientName::new("Example")), + (Some(LanguageTag::new("es")), ClientName::new("Ejemplo"),), ] ); assert_eq!( sorted(client_metadata.logo_uri().unwrap().clone()) .collect::, LogoUrl)>>(), vec![ + (None, LogoUrl::new("https://example.com/logo.png").unwrap(),), ( - None, - LogoUrl::new("https://example.com/logo.png".to_string()).unwrap(), - ), - ( - Some(LanguageTag::new("fr".to_string())), - LogoUrl::new("https://example.com/logo-fr.png".to_string()).unwrap(), + Some(LanguageTag::new("fr")), + LogoUrl::new("https://example.com/logo-fr.png").unwrap(), ), ] ); @@ -132,11 +126,11 @@ fn test_metadata_serialization() { vec![ ( None, - ClientUrl::new("https://example.com/client-app".to_string()).unwrap(), + ClientUrl::new("https://example.com/client-app").unwrap(), ), ( - Some(LanguageTag::new("de".to_string())), - ClientUrl::new("https://example.com/client-app-de".to_string()).unwrap(), + Some(LanguageTag::new("de")), + ClientUrl::new("https://example.com/client-app-de").unwrap(), ), ] ); @@ -144,13 +138,10 @@ fn test_metadata_serialization() { sorted(client_metadata.policy_uri().unwrap().clone()) .collect::, PolicyUrl)>>(), vec![ + (None, PolicyUrl::new("https://example.com/policy").unwrap(),), ( - None, - PolicyUrl::new("https://example.com/policy".to_string()).unwrap(), - ), - ( - Some(LanguageTag::new("sr-Latn".to_string())), - PolicyUrl::new("https://example.com/policy-sr-latin".to_string()).unwrap(), + Some(LanguageTag::new("sr-Latn")), + PolicyUrl::new("https://example.com/policy-sr-latin").unwrap(), ), ] ); @@ -158,19 +149,16 @@ fn test_metadata_serialization() { sorted(client_metadata.tos_uri().unwrap().clone()) .collect::, ToSUrl)>>(), vec![ + (None, ToSUrl::new("https://example.com/tos").unwrap(),), ( - None, - ToSUrl::new("https://example.com/tos".to_string()).unwrap(), - ), - ( - Some(LanguageTag::new("sr-Cyrl".to_string())), - ToSUrl::new("https://example.com/tos-sr-cyrl".to_string()).unwrap(), + Some(LanguageTag::new("sr-Cyrl")), + ToSUrl::new("https://example.com/tos-sr-cyrl").unwrap(), ), ] ); assert_eq!( *client_metadata.jwks_uri().unwrap(), - JsonWebKeySetUrl::new("https://example.com/jwks".to_string()).unwrap() + JsonWebKeySetUrl::new("https://example.com/jwks").unwrap() ); assert_eq!( client_metadata.jwks(), @@ -181,7 +169,7 @@ fn test_metadata_serialization() { ); assert_eq!( *client_metadata.sector_identifier_uri().unwrap(), - SectorIdentifierUrl::new("https://example.com/sector".to_string()).unwrap() + SectorIdentifierUrl::new("https://example.com/sector").unwrap() ); assert_eq!( *client_metadata.subject_type().unwrap(), @@ -239,20 +227,20 @@ fn test_metadata_serialization() { assert_eq!( *client_metadata.default_acr_values().unwrap(), vec![ - AuthenticationContextClass::new("0".to_string()), - AuthenticationContextClass::new("urn:mace:incommon:iap:silver".to_string()), - AuthenticationContextClass::new("urn:mace:incommon:iap:bronze".to_string()), + AuthenticationContextClass::new("0"), + AuthenticationContextClass::new("urn:mace:incommon:iap:silver"), + AuthenticationContextClass::new("urn:mace:incommon:iap:bronze"), ] ); assert_eq!( *client_metadata.sector_identifier_uri().unwrap(), - SectorIdentifierUrl::new("https://example.com/sector".to_string()).unwrap() + SectorIdentifierUrl::new("https://example.com/sector").unwrap() ); assert_eq!( *client_metadata.request_uris().unwrap(), vec![ - RequestUrl::new("https://example.com/request-1".to_string()).unwrap(), - RequestUrl::new("https://example.com/request-2".to_string()).unwrap(), + RequestUrl::new("https://example.com/request-1").unwrap(), + RequestUrl::new("https://example.com/request-2").unwrap(), ] ); let serialized_json = serde_json::to_string(&client_metadata).unwrap(); @@ -271,7 +259,7 @@ fn test_metadata_serialization_minimal() { assert_eq!( *client_metadata.redirect_uris(), - vec![RedirectUrl::new("https://example.com/redirect-1".to_string()).unwrap(),] + vec![RedirectUrl::new("https://example.com/redirect-1").unwrap(),] ); assert_eq!(client_metadata.response_types(), None); assert_eq!(client_metadata.grant_types(), None); @@ -364,7 +352,7 @@ fn test_response_serialization() { assert_eq!( *registration_response.client_id(), - ClientId::new("abcdefgh".to_string()) + ClientId::new("abcdefgh") ); assert_eq!( *registration_response.client_secret().unwrap().secret(), @@ -379,7 +367,7 @@ fn test_response_serialization() { ); assert_eq!( *registration_response.registration_client_uri().unwrap(), - ClientConfigUrl::new("https://example-provider.com/registration".to_string()).unwrap() + ClientConfigUrl::new("https://example-provider.com/registration").unwrap() ); assert_eq!( registration_response.client_id_issued_at().unwrap(), @@ -396,8 +384,8 @@ fn test_response_serialization() { assert_eq!( *registration_response.redirect_uris(), vec![ - RedirectUrl::new("https://example.com/redirect-1".to_string()).unwrap(), - RedirectUrl::new("https://example.com/redirect-2".to_string()).unwrap(), + RedirectUrl::new("https://example.com/redirect-1").unwrap(), + RedirectUrl::new("https://example.com/redirect-2").unwrap(), ] ); assert_eq!( @@ -428,32 +416,26 @@ fn test_response_serialization() { assert_eq!( *registration_response.contacts().unwrap(), vec![ - ClientContactEmail::new("user@example.com".to_string()), - ClientContactEmail::new("admin@openidconnect.local".to_string()), + ClientContactEmail::new("user@example.com"), + ClientContactEmail::new("admin@openidconnect.local"), ] ); assert_eq!( sorted(registration_response.client_name().unwrap().clone()) .collect::, ClientName)>>(), vec![ - (None, ClientName::new("Example".to_string())), - ( - Some(LanguageTag::new("es".to_string())), - ClientName::new("Ejemplo".to_string()), - ), + (None, ClientName::new("Example")), + (Some(LanguageTag::new("es")), ClientName::new("Ejemplo"),), ] ); assert_eq!( sorted(registration_response.logo_uri().unwrap().clone()) .collect::, LogoUrl)>>(), vec![ + (None, LogoUrl::new("https://example.com/logo.png").unwrap(),), ( - None, - LogoUrl::new("https://example.com/logo.png".to_string()).unwrap(), - ), - ( - Some(LanguageTag::new("fr".to_string())), - LogoUrl::new("https://example.com/logo-fr.png".to_string()).unwrap(), + Some(LanguageTag::new("fr")), + LogoUrl::new("https://example.com/logo-fr.png").unwrap(), ), ] ); @@ -463,11 +445,11 @@ fn test_response_serialization() { vec![ ( None, - ClientUrl::new("https://example.com/client-app".to_string()).unwrap(), + ClientUrl::new("https://example.com/client-app").unwrap(), ), ( - Some(LanguageTag::new("de".to_string())), - ClientUrl::new("https://example.com/client-app-de".to_string()).unwrap(), + Some(LanguageTag::new("de")), + ClientUrl::new("https://example.com/client-app-de").unwrap(), ), ] ); @@ -475,13 +457,10 @@ fn test_response_serialization() { sorted(registration_response.policy_uri().unwrap().clone()) .collect::, PolicyUrl)>>(), vec![ + (None, PolicyUrl::new("https://example.com/policy").unwrap(),), ( - None, - PolicyUrl::new("https://example.com/policy".to_string()).unwrap(), - ), - ( - Some(LanguageTag::new("sr-Latn".to_string())), - PolicyUrl::new("https://example.com/policy-sr-latin".to_string()).unwrap(), + Some(LanguageTag::new("sr-Latn")), + PolicyUrl::new("https://example.com/policy-sr-latin").unwrap(), ), ] ); @@ -489,19 +468,16 @@ fn test_response_serialization() { sorted(registration_response.tos_uri().unwrap().clone()) .collect::, ToSUrl)>>(), vec![ + (None, ToSUrl::new("https://example.com/tos").unwrap(),), ( - None, - ToSUrl::new("https://example.com/tos".to_string()).unwrap(), - ), - ( - Some(LanguageTag::new("sr-Cyrl".to_string())), - ToSUrl::new("https://example.com/tos-sr-cyrl".to_string()).unwrap(), + Some(LanguageTag::new("sr-Cyrl")), + ToSUrl::new("https://example.com/tos-sr-cyrl").unwrap(), ), ] ); assert_eq!( *registration_response.jwks_uri().unwrap(), - JsonWebKeySetUrl::new("https://example.com/jwks".to_string()).unwrap() + JsonWebKeySetUrl::new("https://example.com/jwks").unwrap() ); assert_eq!( registration_response.jwks(), @@ -512,7 +488,7 @@ fn test_response_serialization() { ); assert_eq!( *registration_response.sector_identifier_uri().unwrap(), - SectorIdentifierUrl::new("https://example.com/sector".to_string()).unwrap() + SectorIdentifierUrl::new("https://example.com/sector").unwrap() ); assert_eq!( *registration_response.subject_type().unwrap(), @@ -588,20 +564,20 @@ fn test_response_serialization() { assert_eq!( *registration_response.default_acr_values().unwrap(), vec![ - AuthenticationContextClass::new("0".to_string()), - AuthenticationContextClass::new("urn:mace:incommon:iap:silver".to_string()), - AuthenticationContextClass::new("urn:mace:incommon:iap:bronze".to_string()), + AuthenticationContextClass::new("0"), + AuthenticationContextClass::new("urn:mace:incommon:iap:silver"), + AuthenticationContextClass::new("urn:mace:incommon:iap:bronze"), ] ); assert_eq!( *registration_response.sector_identifier_uri().unwrap(), - SectorIdentifierUrl::new("https://example.com/sector".to_string()).unwrap() + SectorIdentifierUrl::new("https://example.com/sector").unwrap() ); assert_eq!( *registration_response.request_uris().unwrap(), vec![ - RequestUrl::new("https://example.com/request-1".to_string()).unwrap(), - RequestUrl::new("https://example.com/request-2".to_string()).unwrap(), + RequestUrl::new("https://example.com/request-1").unwrap(), + RequestUrl::new("https://example.com/request-2").unwrap(), ] ); let serialized_json = serde_json::to_string(®istration_response).unwrap(); diff --git a/src/types/localized.rs b/src/types/localized.rs index ae51daa5..a3c824e0 100644 --- a/src/types/localized.rs +++ b/src/types/localized.rs @@ -22,7 +22,7 @@ pub(crate) fn split_language_tag_key(key: &str) -> (&str, Option) { let language_tag = lang_tag_sep .next() .filter(|language_tag| !language_tag.is_empty()) - .map(|language_tag| LanguageTag::new(language_tag.to_string())); + .map(LanguageTag::new); (field_name, language_tag) } diff --git a/src/types/tests.rs b/src/types/tests.rs index 6e93b638..71c878e1 100644 --- a/src/types/tests.rs +++ b/src/types/tests.rs @@ -4,7 +4,7 @@ use crate::IssuerUrl; fn test_issuer_url_append() { assert_eq!( "http://example.com/.well-known/openid-configuration", - IssuerUrl::new("http://example.com".to_string()) + IssuerUrl::new("http://example.com") .unwrap() .join(".well-known/openid-configuration") .unwrap() @@ -12,7 +12,7 @@ fn test_issuer_url_append() { ); assert_eq!( "http://example.com/.well-known/openid-configuration", - IssuerUrl::new("http://example.com/".to_string()) + IssuerUrl::new("http://example.com/") .unwrap() .join(".well-known/openid-configuration") .unwrap() @@ -20,7 +20,7 @@ fn test_issuer_url_append() { ); assert_eq!( "http://example.com/x/.well-known/openid-configuration", - IssuerUrl::new("http://example.com/x".to_string()) + IssuerUrl::new("http://example.com/x") .unwrap() .join(".well-known/openid-configuration") .unwrap() @@ -28,7 +28,7 @@ fn test_issuer_url_append() { ); assert_eq!( "http://example.com/x/.well-known/openid-configuration", - IssuerUrl::new("http://example.com/x/".to_string()) + IssuerUrl::new("http://example.com/x/") .unwrap() .join(".well-known/openid-configuration") .unwrap() @@ -38,8 +38,7 @@ fn test_issuer_url_append() { #[test] fn test_url_serialize() { - let issuer_url = - IssuerUrl::new("http://example.com/.well-known/openid-configuration".to_string()).unwrap(); + let issuer_url = IssuerUrl::new("http://example.com/.well-known/openid-configuration").unwrap(); let serialized_url = serde_json::to_string(&issuer_url).unwrap(); assert_eq!( @@ -51,7 +50,7 @@ fn test_url_serialize() { assert_eq!(issuer_url, deserialized_url); assert_eq!( - serde_json::to_string(&IssuerUrl::new("http://example.com".to_string()).unwrap()).unwrap(), + serde_json::to_string(&IssuerUrl::new("http://example.com").unwrap()).unwrap(), "\"http://example.com\"", ); } diff --git a/src/verification/mod.rs b/src/verification/mod.rs index d8b2a888..d9aa9eaa 100644 --- a/src/verification/mod.rs +++ b/src/verification/mod.rs @@ -525,8 +525,8 @@ where /// Initializes a no-op verifier that performs no signature, audience, or issuer verification. /// The token's expiration time is still checked, and the token is otherwise required to conform to the expected format. pub fn new_insecure_without_verification() -> Self { - let empty_issuer = IssuerUrl::new("https://0.0.0.0".to_owned()) - .expect("Creating empty issuer url mustn't fail"); + let empty_issuer = + IssuerUrl::new("https://0.0.0.0").expect("Creating empty issuer url mustn't fail"); Self::new_public_client( ClientId::new(String::new()), empty_issuer, diff --git a/src/verification/tests.rs b/src/verification/tests.rs index bd73663e..6904b86e 100644 --- a/src/verification/tests.rs +++ b/src/verification/tests.rs @@ -109,8 +109,8 @@ fn test_jwt_verified_claims() { let rsa_key = serde_json::from_str::(TEST_RSA_PUB_KEY).expect("deserialization failed"); - let client_id = ClientId::new("my_client".to_string()); - let issuer = IssuerUrl::new("https://example.com".to_string()).unwrap(); + let client_id = ClientId::new("my_client"); + let issuer = IssuerUrl::new("https://example.com").unwrap(); let verifier = CoreJwtClaimsVerifier::new( client_id.clone(), issuer.clone(), @@ -329,7 +329,7 @@ fn test_jwt_verified_claims() { issuer.clone(), CoreJsonWebKeySet::new(vec![]), ) - .set_client_secret(ClientSecret::new("my_secret".to_string())); + .set_client_secret(ClientSecret::new("my_secret")); let valid_hs256_jwt = serde_json::from_value::(serde_json::Value::String( "eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOlsibXlfY2xpZW50Il0sImlzcyI6Imh0dHBzOi8vZXhhbXBsZ\ @@ -428,7 +428,7 @@ fn test_jwt_verified_claims() { other => panic!("unexpected result: {:?}", other), } - let kid = JsonWebKeyId::new("bilbo.baggins@hobbiton.example".to_string()); + let kid = JsonWebKeyId::new("bilbo.baggins@hobbiton.example"); let n = Base64UrlEncodedBytes::new(vec![ 159, 129, 15, 180, 3, 130, 115, 208, 37, 145, 228, 7, 63, 49, 210, 182, 0, 27, 130, 206, 219, 77, 146, 240, 80, 22, 93, 71, 207, 202, 184, 163, 196, 28, 183, 120, 172, 117, 83, @@ -521,7 +521,7 @@ fn test_jwt_verified_claims() { // Client secret + public key verifier .clone() - .set_client_secret(ClientSecret::new("my_secret".to_string())) + .set_client_secret(ClientSecret::new("my_secret")) .verified_claims(valid_rs256_jwt.clone()) .expect("verification should succeed"); @@ -597,8 +597,8 @@ fn test_id_token_verified_claims() { let rsa_key = serde_json::from_str::(TEST_RSA_PUB_KEY).expect("deserialization failed"); - let client_id = ClientId::new("my_client".to_string()); - let issuer = IssuerUrl::new("https://example.com".to_string()).unwrap(); + let client_id = ClientId::new("my_client"); + let issuer = IssuerUrl::new("https://example.com").unwrap(); let mock_current_time = AtomicUsize::new(1544932149); let mock_is_valid_issue_time = AtomicBool::new(true); // Extra scope needed to ensure closures are destroyed before the values they borrow. @@ -684,7 +684,7 @@ fn test_id_token_verified_claims() { } mock_is_valid_issue_time.store(true, Ordering::Relaxed); - let valid_nonce = Nonce::new("the_nonce".to_string()); + let valid_nonce = Nonce::new("the_nonce"); // Successful verification w/o checking nonce public_client_verifier @@ -727,10 +727,9 @@ fn test_id_token_verified_claims() { .expect("failed to deserialize"); // Invalid nonce - match public_client_verifier.verified_claims( - &test_jwt_with_nonce, - &Nonce::new("different_nonce".to_string()), - ) { + match public_client_verifier + .verified_claims(&test_jwt_with_nonce, &Nonce::new("different_nonce")) + { Err(ClaimsVerificationError::InvalidNonce(_)) => {} other => panic!("unexpected result: {:?}", other), } @@ -844,7 +843,7 @@ fn test_id_token_verified_claims() { .expect("failed to deserialize"); let private_client_verifier = CoreIdTokenVerifier::new_confidential_client( client_id.clone(), - ClientSecret::new("my_secret".to_string()), + ClientSecret::new("my_secret"), issuer.clone(), CoreJsonWebKeySet::new(vec![rsa_key.clone()]), ) @@ -881,7 +880,7 @@ fn test_id_token_verified_claims() { let private_client_verifier_with_other_secret = CoreIdTokenVerifier::new_confidential_client( client_id, - ClientSecret::new("other_secret".to_string()), + ClientSecret::new("other_secret"), issuer, CoreJsonWebKeySet::new(vec![rsa_key]), ) @@ -910,9 +909,9 @@ fn test_id_token_verified_claims() { #[test] fn test_new_id_token() { - let client_id = ClientId::new("my_client".to_string()); - let issuer = IssuerUrl::new("https://example.com".to_string()).unwrap(); - let nonce = Nonce::new("the_nonce".to_string()); + let client_id = ClientId::new("my_client"); + let issuer = IssuerUrl::new("https://example.com").unwrap(); + let nonce = Nonce::new("the_nonce"); let rsa_priv_key = CoreRsaPrivateSigningKey::from_pem(TEST_RSA_PRIV_KEY, None).unwrap(); let id_token = CoreIdToken::new( @@ -925,11 +924,11 @@ fn test_new_id_token() { Utc.timestamp_opt(1544928549, 0) .single() .expect("valid timestamp"), - StandardClaims::new(SubjectIdentifier::new("subject".to_string())), + StandardClaims::new(SubjectIdentifier::new("subject")), Default::default(), ) .set_nonce(Some(nonce.clone())) - .set_auth_context_ref(Some(AuthenticationContextClass::new("the_acr".to_string()))) + .set_auth_context_ref(Some(AuthenticationContextClass::new("the_acr"))) .set_auth_time(Some( Utc.timestamp_opt(1544928548, 0) .single() @@ -937,10 +936,8 @@ fn test_new_id_token() { )), &rsa_priv_key, CoreJwsSigningAlgorithm::RsaSsaPkcs1V15Sha256, - Some(&AccessToken::new("the_access_token".to_string())), - Some(&AuthorizationCode::new( - "the_authorization_code".to_string(), - )), + Some(&AccessToken::new("the_access_token")), + Some(&AuthorizationCode::new("the_authorization_code")), ) .unwrap(); @@ -987,9 +984,9 @@ fn test_user_info_verified_claims() { let rsa_key = serde_json::from_str::(TEST_RSA_PUB_KEY).expect("deserialization failed"); - let client_id = ClientId::new("my_client".to_string()); - let issuer = IssuerUrl::new("https://example.com".to_string()).unwrap(); - let sub = SubjectIdentifier::new("the_subject".to_string()); + let client_id = ClientId::new("my_client"); + let issuer = IssuerUrl::new("https://example.com").unwrap(); + let sub = SubjectIdentifier::new("the_subject"); let verifier = CoreUserInfoVerifier::new( client_id.clone(), @@ -1011,13 +1008,13 @@ fn test_user_info_verified_claims() { .unwrap() .iter() .collect::>(), - vec![(None, &EndUserName::new("Jane Doe".to_string()))], + vec![(None, &EndUserName::new("Jane Doe"))], ); // Invalid subject match CoreUserInfoClaims::from_json::( json_claims.as_bytes(), - Some(&SubjectIdentifier::new("wrong_subject".to_string())), + Some(&SubjectIdentifier::new("wrong_subject")), ) { Err(UserInfoError::ClaimsVerification(ClaimsVerificationError::InvalidSubject(_))) => {} other => panic!("unexpected result: {:?}", other), @@ -1064,7 +1061,7 @@ fn test_user_info_verified_claims() { // JWT response with invalid issuer claim (error) match jwt_claims.clone().claims(&CoreUserInfoVerifier::new( client_id.clone(), - IssuerUrl::new("https://attacker.com".to_string()).unwrap(), + IssuerUrl::new("https://attacker.com").unwrap(), CoreJsonWebKeySet::new(vec![rsa_key.clone()]), Some(sub.clone()), )) { @@ -1078,7 +1075,7 @@ fn test_user_info_verified_claims() { .claims( &CoreUserInfoVerifier::new( client_id, - IssuerUrl::new("https://attacker.com".to_string()).unwrap(), + IssuerUrl::new("https://attacker.com").unwrap(), CoreJsonWebKeySet::new(vec![rsa_key.clone()]), Some(sub.clone()), ) @@ -1088,7 +1085,7 @@ fn test_user_info_verified_claims() { // JWT response with invalid audience claim (error) match jwt_claims.clone().claims(&CoreUserInfoVerifier::new( - ClientId::new("wrong_client".to_string()), + ClientId::new("wrong_client"), issuer.clone(), CoreJsonWebKeySet::new(vec![rsa_key.clone()]), Some(sub.clone()), @@ -1101,7 +1098,7 @@ fn test_user_info_verified_claims() { jwt_claims .claims( &CoreUserInfoVerifier::new( - ClientId::new("wrong_client".to_string()), + ClientId::new("wrong_client"), issuer, CoreJsonWebKeySet::new(vec![rsa_key]), Some(sub), @@ -1115,8 +1112,8 @@ fn test_user_info_verified_claims() { fn test_new_user_info_claims() { let claims = CoreUserInfoClaims::new( StandardClaims { - sub: SubjectIdentifier::new("the_subject".to_string()), - name: Some(EndUserName::new("John Doe".to_string()).into()), + sub: SubjectIdentifier::new("the_subject"), + name: Some(EndUserName::new("John Doe").into()), given_name: None, family_name: None, middle_name: None, diff --git a/tests/rp_certification_code.rs b/tests/rp_certification_code.rs index 39440f77..39dff562 100644 --- a/tests/rp_certification_code.rs +++ b/tests/rp_certification_code.rs @@ -133,7 +133,7 @@ impl TestState { log_info!("Successfully received authentication response from Authorization Server"); let authorization_code = - AuthorizationCode::new(query_params.get("code").unwrap().to_string()); + AuthorizationCode::new(query_params.get("code").unwrap().as_ref()); log_debug!( "Authorization Server returned authorization code: {}", authorization_code.secret() @@ -264,7 +264,7 @@ fn rp_response_type_code() { fn rp_scope_userinfo_claims() { let user_info_scopes = ["profile", "email", "address", "phone"] .iter() - .map(|scope| Scope::new((*scope).to_string())) + .map(|scope| Scope::new(*scope)) .collect::>(); let test_state = TestState::init("rp-scope-userinfo-claims", |reg| reg) .authorize(&user_info_scopes) @@ -555,7 +555,7 @@ fn rp_id_token_issuer_mismatch() { #[ignore] fn rp_userinfo_bad_sub_claim() { let test_state = TestState::init("rp-userinfo-bad-sub-claim", |reg| reg) - .authorize(&[Scope::new("profile".to_string())]) + .authorize(&[Scope::new("profile")]) .exchange_code(); let id_token_claims = test_state.id_token_claims(); log_debug!("ID token: {:?}", id_token_claims); @@ -573,7 +573,7 @@ fn rp_userinfo_bad_sub_claim() { #[ignore] fn rp_userinfo_bearer_header() { let test_state = TestState::init("rp-userinfo-bearer-header", |reg| reg) - .authorize(&[Scope::new("profile".to_string())]) + .authorize(&[Scope::new("profile")]) .exchange_code(); let id_token_claims = test_state.id_token_claims(); log_debug!("ID token: {:?}", id_token_claims); @@ -589,7 +589,7 @@ fn rp_userinfo_sig() { let test_state = TestState::init("rp-userinfo-sig", |reg| { reg.set_userinfo_signed_response_alg(Some(CoreJwsSigningAlgorithm::RsaSsaPkcs1V15Sha256)) }) - .authorize(&[Scope::new("profile".to_string())]) + .authorize(&[Scope::new("profile")]) .exchange_code(); let id_token_claims = test_state.id_token_claims(); log_debug!("ID token: {:?}", id_token_claims); diff --git a/tests/rp_common.rs b/tests/rp_common.rs index 08a853fc..faf31c01 100644 --- a/tests/rp_common.rs +++ b/tests/rp_common.rs @@ -165,18 +165,14 @@ where F: FnOnce(CoreClientRegistrationRequest) -> CoreClientRegistrationRequest, { let registration_request_pre = CoreClientRegistrationRequest::new( - vec![RedirectUrl::new(RP_REDIRECT_URI.to_string()).unwrap()], + vec![RedirectUrl::new(RP_REDIRECT_URI).unwrap()], Default::default(), ) .set_application_type(Some(CoreApplicationType::Native)) .set_client_name(Some( - vec![(None, ClientName::new(RP_NAME.to_string()))] - .into_iter() - .collect(), + vec![(None, ClientName::new(RP_NAME))].into_iter().collect(), )) - .set_contacts(Some(vec![ClientContactEmail::new( - RP_CONTACT_EMAIL.to_string(), - )])); + .set_contacts(Some(vec![ClientContactEmail::new(RP_CONTACT_EMAIL)])); let registration_request_post = request_fn(registration_request_pre);