From dc49d78075b4d9c76d71d7e254eb656647847862 Mon Sep 17 00:00:00 2001 From: Pierre Hubert Date: Sat, 29 Apr 2023 12:33:23 +0200 Subject: [PATCH] Use OpenID primites & client from light-openid crate --- Cargo.lock | 1 - Cargo.toml | 3 +- src/controllers/openid_controller.rs | 40 +++++++--- src/data/mod.rs | 1 - src/data/openid_primitive.rs | 107 --------------------------- src/data/provider_configuration.rs | 80 +++++--------------- 6 files changed, 48 insertions(+), 184 deletions(-) delete mode 100644 src/data/openid_primitive.rs diff --git a/Cargo.lock b/Cargo.lock index 0c70d82..0e48c7e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -580,7 +580,6 @@ dependencies = [ "mime_guess", "qrcode-generator", "rand", - "reqwest", "serde", "serde_json", "serde_yaml", diff --git a/Cargo.toml b/Cargo.toml index ceff572..d65c767 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -38,5 +38,4 @@ url = "2.3.1" light-openid = { version = "1.0.1", features=["crypto-wrapper"] } bincode = "2.0.0-rc.3" chrono = "0.4.24" -lazy_static = "1.4.0" -reqwest = { version = "0.11.16", features = ["json"] } \ No newline at end of file +lazy_static = "1.4.0" \ No newline at end of file diff --git a/src/controllers/openid_controller.rs b/src/controllers/openid_controller.rs index 4140c4e..f014243 100644 --- a/src/controllers/openid_controller.rs +++ b/src/controllers/openid_controller.rs @@ -7,6 +7,7 @@ use actix_web::error::ErrorUnauthorized; use actix_web::{web, HttpRequest, HttpResponse, Responder}; use base64::engine::general_purpose::STANDARD as BASE64_STANDARD; use base64::Engine as _; +use light_openid::primitives::{OpenIDConfig, OpenIDTokenResponse, OpenIDUserInfo}; use crate::actors::openid_sessions_actor::{OpenIDSessionsActor, Session, SessionID}; use crate::actors::users_actor::UsersActor; @@ -20,7 +21,7 @@ use crate::data::code_challenge::CodeChallenge; use crate::data::current_user::CurrentUser; use crate::data::id_token::IdToken; use crate::data::jwt_signer::{JWTSigner, JsonWebKey}; -use crate::data::openid_primitive::{OpenIDConfig, OpenIDUserInfo, TokenResponse}; + use crate::data::session_identity::SessionIdentity; use crate::data::user::User; use crate::utils::string_utils::rand_str; @@ -51,15 +52,32 @@ pub async fn get_configuration(req: HttpRequest) -> impl Responder { issuer: AppConfig::get().website_origin.clone(), authorization_endpoint: AppConfig::get().full_url(AUTHORIZE_URI), token_endpoint: curr_origin.clone() + TOKEN_URI, - userinfo_endpoint: curr_origin.clone() + USERINFO_URI, + userinfo_endpoint: Some(curr_origin.clone() + USERINFO_URI), jwks_uri: curr_origin + CERT_URI, - scopes_supported: vec!["openid", "profile", "email"], - response_types_supported: vec!["code", "id_token", "token id_token"], - subject_types_supported: vec!["public"], - id_token_signing_alg_values_supported: vec!["RS256"], - token_endpoint_auth_methods_supported: vec!["client_secret_post", "client_secret_basic"], - claims_supported: vec!["sub", "name", "given_name", "family_name", "email"], - code_challenge_methods_supported: vec!["plain", "S256"], + scopes_supported: Some(vec![ + "openid".to_string(), + "profile".to_string(), + "email".to_string(), + ]), + response_types_supported: vec![ + "code".to_string(), + "id_token".to_string(), + "token id_token".to_string(), + ], + subject_types_supported: vec!["public".to_string()], + id_token_signing_alg_values_supported: vec!["RS256".to_string()], + token_endpoint_auth_methods_supported: Some(vec![ + "client_secret_post".to_string(), + "client_secret_basic".to_string(), + ]), + claims_supported: Some(vec![ + "sub".to_string(), + "name".to_string(), + "given_name".to_string(), + "family_name".to_string(), + "email".to_string(), + ]), + code_challenge_methods_supported: Some(vec!["plain".to_string(), "S256".to_string()]), }) } @@ -438,7 +456,7 @@ pub async fn token( email: user.email, }; - TokenResponse { + OpenIDTokenResponse { access_token: session.access_token.expect("Missing access token!"), token_type: "Bearer".to_string(), refresh_token: Some(session.refresh_token), @@ -488,7 +506,7 @@ pub async fn token( .await .unwrap(); - TokenResponse { + OpenIDTokenResponse { access_token: session.access_token.expect("Missing access token!"), token_type: "Bearer".to_string(), refresh_token: Some(session.refresh_token), diff --git a/src/data/mod.rs b/src/data/mod.rs index 497f568..6e2cacd 100644 --- a/src/data/mod.rs +++ b/src/data/mod.rs @@ -8,7 +8,6 @@ pub mod entity_manager; pub mod id_token; pub mod jwt_signer; pub mod login_redirect; -pub mod openid_primitive; pub mod provider; pub mod provider_configuration; pub mod session_identity; diff --git a/src/data/openid_primitive.rs b/src/data/openid_primitive.rs deleted file mode 100644 index 86e63e1..0000000 --- a/src/data/openid_primitive.rs +++ /dev/null @@ -1,107 +0,0 @@ -//! # OpenID primitives - -/// OpenID discovery information -#[derive(Debug, Clone, serde::Serialize)] -pub struct OpenIDConfig { - /// URL using the https scheme with no query or fragment component that the OP asserts as its Issuer Identifier. If Issuer discovery is supported (see Section 2), this value MUST be identical to the issuer value returned by WebFinger. This also MUST be identical to the iss Claim value in ID Tokens issued from this Issuer - pub issuer: String, - - /// REQUIRED. URL of the OP's OAuth 2.0 Authorization Endpoint `OpenID.Core` - pub authorization_endpoint: String, - - /// URL of the OP's OAuth 2.0 Token Endpoint `OpenID.Core`. This is REQUIRED unless only the Implicit Flow is used. - pub token_endpoint: String, - - /// RECOMMENDED. URL of the OP's UserInfo Endpoint `[`OpenID.Core`]`. This URL MUST use the https scheme and MAY contain port, path, and query parameter components - pub userinfo_endpoint: String, - - /// REQUIRED. URL of the OP's JSON Web Key Set `[`JWK`]` document. This contains the signing key(s) the RP uses to validate signatures from the OP. The JWK Set MAY also contain the Server's encryption key(s), which are used by RPs to encrypt requests to the Server. When both signing and encryption keys are made available, a use (Key Use) parameter value is REQUIRED for all keys in the referenced JWK Set to indicate each key's intended usage. Although some algorithms allow the same key to be used for both signatures and encryption, doing so is NOT RECOMMENDED, as it is less secure. The JWK x5c parameter MAY be used to provide X.509 representations of keys provided. When used, the bare key values MUST still be present and MUST match those in the certificate. - pub jwks_uri: String, - - /// RECOMMENDED. JSON array containing a list of the OAuth 2.0 `[`RFC6749`]` scope values that this server supports. The server MUST support the openid scope value. Servers MAY choose not to advertise some supported scope values even when this parameter is used, although those defined in `[`OpenID.Core`]` SHOULD be listed, if supported. - pub scopes_supported: Vec<&'static str>, - - /// REQUIRED. JSON array containing a list of the OAuth 2.0 response_type values that this OP supports. Dynamic OpenID Providers MUST support the code, id_token, and the token id_token Response Type values. - pub response_types_supported: Vec<&'static str>, - - /// REQUIRED. JSON array containing a list of the Subject Identifier types that this OP supports. Valid types include pairwise and public. - pub subject_types_supported: Vec<&'static str>, - - /// REQUIRED. JSON array containing a list of the JWS signing algorithms (alg values) supported by the OP for the ID Token to encode the Claims in a JWT `[`JWT`. The algorithm RS256 MUST be included. The value none MAY be supported, but MUST NOT be used unless the Response Type used returns no ID Token from the Authorization Endpoint (such as when using the Authorization Code Flow). - pub id_token_signing_alg_values_supported: Vec<&'static str>, - - /// OPTIONAL. JSON array containing a list of Client Authentication methods supported by this Token Endpoint. The options are client_secret_post, client_secret_basic, client_secret_jwt, and private_key_jwt - pub token_endpoint_auth_methods_supported: Vec<&'static str>, - - /// RECOMMENDED. JSON array containing a list of the Claim Names of the Claims that the OpenID Provider MAY be able to supply values for. Note that for privacy or other reasons, this might not be an exhaustive list. - pub claims_supported: Vec<&'static str>, - - pub code_challenge_methods_supported: Vec<&'static str>, -} - -/// OpenID token response -/// -/// The content of this field is specified in -/// * OAuth specifications: https://datatracker.ietf.org/doc/html/rfc6749#section-5.1 -/// * OpenID Core specifications: https://openid.net/specs/openid-connect-core-1_0.html#TokenResponse -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -pub struct TokenResponse { - /// REQUIRED. The access token issued by the authorization server. - pub access_token: String, - - /// REQUIRED. The type of the token issued. It MUST be "Bearer" - pub token_type: String, - - /// OPTIONAL. The refresh token, which can be used to obtain new - /// access tokens using the same authorization grant - #[serde(skip_serializing_if = "Option::is_none")] - pub refresh_token: Option, - - /// RECOMMENDED. The lifetime in seconds of the access token. For - /// example, the value "3600" denotes that the access token will - /// expire in one hour from the time the response was generated. - /// If omitted, the authorization server SHOULD provide the - /// expiration time via other means or document the default value. - #[serde(skip_serializing_if = "Option::is_none")] - pub expires_in: Option, - - /// REQUIRED. ID Token value associated with the authenticated session. - /// - /// Note: this field is marked as optionnal because it is excluded in case - /// of request of refresh token. - #[serde(skip_serializing_if = "Option::is_none")] - pub id_token: Option, -} - -/// Refer to for more information -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -pub struct OpenIDUserInfo { - /// Subject - Identifier for the End-User at the Issuer - /// - /// This is the only mandatory field - pub sub: String, - - /// End-User's full name in displayable form including all name parts, possibly including titles and suffixes, ordered according to the End-User's locale and preferences. - #[serde(skip_serializing_if = "Option::is_none")] - pub name: Option, - - /// Given name(s) or first name(s) of the End-User. Note that in some cultures, people can have multiple given names; all can be present, with the names being separated by space characters. - #[serde(skip_serializing_if = "Option::is_none")] - pub given_name: Option, - - /// Surname(s) or last name(s) of the End-User. Note that in some cultures, people can have multiple family names or no family name; all can be present, with the names being separated by space characters. - #[serde(skip_serializing_if = "Option::is_none")] - pub family_name: Option, - - /// Shorthand name by which the End-User wishes to be referred to at the RP, such as janedoe or j.doe. This value MAY be any valid JSON string including special characters such as @, /, or whitespace. The RP MUST NOT rely upon this value being unique, as discussed in - #[serde(skip_serializing_if = "Option::is_none")] - pub preferred_username: Option, - - /// End-User's preferred e-mail address. Its value MUST conform to the RFC 5322 RFC5322 addr-spec syntax. The RP MUST NOT rely upon this value being unique, as discussed in Section 5.7. - #[serde(skip_serializing_if = "Option::is_none")] - pub email: Option, - - /// True if the End-User's e-mail address has been verified; otherwise false. When this Claim Value is true, this means that the OP took affirmative steps to ensure that this e-mail address was controlled by the End-User at the time the verification was performed. The means by which an e-mail address is verified is context-specific, and dependent upon the trust framework or contractual agreements within which the parties are operating. - #[serde(skip_serializing_if = "Option::is_none")] - pub email_verified: Option, -} diff --git a/src/data/provider_configuration.rs b/src/data/provider_configuration.rs index eaf079e..36b17b4 100644 --- a/src/data/provider_configuration.rs +++ b/src/data/provider_configuration.rs @@ -1,38 +1,20 @@ use std::cell::RefCell; use std::collections::HashMap; -use base64::engine::general_purpose::STANDARD as BASE64_STANDARD; -use base64::Engine as _; +use light_openid::primitives::{OpenIDConfig, OpenIDTokenResponse, OpenIDUserInfo}; use crate::actors::providers_states_actor::ProviderLoginState; use crate::constants::OIDC_PROVIDERS_LIFETIME; use crate::data::app_config::AppConfig; -use crate::data::jwt_signer::JsonWebKey; -use crate::data::openid_primitive::{OpenIDUserInfo, TokenResponse}; + use crate::data::provider::Provider; use crate::utils::err::Res; use crate::utils::time::time; -#[derive(Debug, Clone, serde::Deserialize)] -pub struct ProviderDiscovery { - pub issuer: String, - pub authorization_endpoint: String, - pub token_endpoint: String, - pub userinfo_endpoint: Option, - pub jwks_uri: String, - pub claims_supported: Option>, -} - -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -pub struct ProviderJWKs { - pub keys: Vec, -} - /// Provider configuration #[derive(Debug, Clone)] pub struct ProviderConfiguration { - pub discovery: ProviderDiscovery, - //pub keys: ProviderJWKs, + pub discovery: OpenIDConfig, pub expire: u64, } @@ -52,41 +34,23 @@ impl ProviderConfiguration { &self, provider: &Provider, authorization_code: &str, - ) -> Res { - let authorization = - BASE64_STANDARD.encode(format!("{}:{}", provider.client_id, provider.client_secret)); + ) -> Res { + let (token, _) = self + .discovery + .request_token( + &provider.client_id, + &provider.client_secret, + authorization_code, + &AppConfig::get().oidc_provider_redirect_url(), + ) + .await?; - let redirect_url = AppConfig::get().oidc_provider_redirect_url(); - - let mut params = HashMap::new(); - params.insert("grant_type", "authorization_code"); - params.insert("code", authorization_code); - params.insert("redirect_uri", redirect_url.as_str()); - - Ok(reqwest::Client::new() - .post(&self.discovery.token_endpoint) - .header("Authorization", format!("Basic {authorization}")) - .form(¶ms) - .send() - .await? - .json() - .await?) + Ok(token) } - /// Retrieve information about the user, using given [TokenResponse] - pub async fn get_userinfo(&self, token: &TokenResponse) -> Res { - Ok(reqwest::Client::new() - .get( - self.discovery - .userinfo_endpoint - .as_ref() - .expect("Userinfo endpoint is required by this implementation!"), - ) - .header("Authorization", format!("Bearer {}", token.access_token)) - .send() - .await? - .json() - .await?) + /// Retrieve information about the user, using a given [OpenIDTokenResponse] + pub async fn get_userinfo(&self, token: &OpenIDTokenResponse) -> Res { + Ok(self.discovery.request_user_info(token).await?.0) } } @@ -119,16 +83,8 @@ impl ProviderConfigurationHelper { /// Get fresh configuration from provider async fn fetch_configuration(provider: &Provider) -> Res { - let discovery: ProviderDiscovery = reqwest::get(&provider.configuration_url) - .await? - .json() - .await?; - - // let keys: ProviderJWKs = reqwest::get(&discovery.jwks_uri).await?.json().await?; - Ok(ProviderConfiguration { - discovery, - // keys, + discovery: OpenIDConfig::load_from_url(&provider.configuration_url).await?, expire: time() + OIDC_PROVIDERS_LIFETIME, }) }