From 6cc9f4c54cdf73e5100df309cb7ccbd8c4fba495 Mon Sep 17 00:00:00 2001 From: Pierre Hubert Date: Sat, 29 Apr 2023 11:11:24 +0000 Subject: [PATCH] Refactor dependencies to reduce code base size (#111) Use crates to reduce code base size : * `actix-remote-ip` to safely determine user IP location * `light-openid` for the OpenID primitives & as client to handle federation Reviewed-on: https://gitea.communiquons.org/pierre/BasicOIDC/pulls/111 --- Cargo.lock | 70 ++++++---- Cargo.toml | 6 +- src/controllers/login_api.rs | 2 +- src/controllers/login_controller.rs | 2 +- src/controllers/openid_controller.rs | 40 ++++-- src/controllers/providers_controller.rs | 2 +- src/controllers/settings_controller.rs | 7 +- src/data/action_logger.rs | 3 +- src/data/crypto_wrapper.rs | 98 ------------- src/data/mod.rs | 3 - src/data/openid_primitive.rs | 107 -------------- src/data/provider_configuration.rs | 80 +++-------- src/data/remote_ip.rs | 30 ---- src/data/webauthn_manager.rs | 2 +- src/main.rs | 4 + src/utils/mod.rs | 1 - src/utils/network_utils.rs | 178 ------------------------ templates/settings/account_details.html | 2 + 18 files changed, 112 insertions(+), 525 deletions(-) delete mode 100644 src/data/crypto_wrapper.rs delete mode 100644 src/data/openid_primitive.rs delete mode 100644 src/data/remote_ip.rs delete mode 100644 src/utils/network_utils.rs diff --git a/Cargo.lock b/Cargo.lock index 67b0af1..0e48c7e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -108,6 +108,17 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "actix-remote-ip" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7629b357d4705cf3f1e31f989f48ecd56027112f7d52dcf06dd96ee197065f8e" +dependencies = [ + "actix-web", + "futures-util", + "log", +] + [[package]] name = "actix-router" version = "0.5.1" @@ -547,9 +558,9 @@ version = "0.1.4" dependencies = [ "actix", "actix-identity", + "actix-remote-ip", "actix-session", "actix-web", - "aes-gcm", "askama", "base32", "base64 0.21.0", @@ -564,11 +575,11 @@ dependencies = [ "jwt-simple", "lazy-regex", "lazy_static", + "light-openid", "log", "mime_guess", "qrcode-generator", "rand", - "reqwest", "serde", "serde_json", "serde_yaml", @@ -1188,12 +1199,12 @@ dependencies = [ [[package]] name = "flate2" -version = "1.0.25" +version = "1.0.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8a2db397cb1c8772f31494cb8917e48cd1e64f0fa7efac59fbd741a0a8ce841" +checksum = "3b9429470923de8e8cbd4d2dc513535400b4b3fef0319fb5c4e1f520a7bef743" dependencies = [ "crc32fast", - "miniz_oxide 0.6.2", + "miniz_oxide", ] [[package]] @@ -1753,6 +1764,23 @@ version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "348108ab3fba42ec82ff6e9564fc4ca0247bdccdc68dd8af9764bbc79c3c8ffb" +[[package]] +name = "light-openid" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "608aa1b7148a6eeab631c6267deca33407ff851ab50eea115e52c13a9bb184ee" +dependencies = [ + "aes-gcm", + "base64 0.21.0", + "bincode", + "log", + "rand", + "reqwest", + "serde", + "serde_json", + "urlencoding", +] + [[package]] name = "link-cplusplus" version = "1.0.8" @@ -1764,9 +1792,9 @@ dependencies = [ [[package]] name = "linux-raw-sys" -version = "0.3.5" +version = "0.3.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e8776872cdc2f073ccaab02e336fa321328c1e02646ebcb9d2108d0baab480d" +checksum = "b64f40e5e03e0d54f03845c8197d0291253cdbedfb1cb46b13c2c117554a9f4c" [[package]] name = "local-channel" @@ -1833,15 +1861,6 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" -[[package]] -name = "miniz_oxide" -version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b275950c28b37e794e8c55d88aeb5e139d0ce23fdbbeda68f8d7174abdf9e8fa" -dependencies = [ - "adler", -] - [[package]] name = "miniz_oxide" version = "0.7.1" @@ -2155,7 +2174,7 @@ dependencies = [ "crc32fast", "fdeflate", "flate2", - "miniz_oxide 0.7.1", + "miniz_oxide", ] [[package]] @@ -2287,9 +2306,9 @@ checksum = "a5996294f19bd3aae0453a862ad728f60e6600695733dd5df01da90c54363a3c" [[package]] name = "reqwest" -version = "0.11.16" +version = "0.11.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27b71749df584b7f4cac2c426c127a7c785a5106cc98f7a8feb044115f0fa254" +checksum = "13293b639a097af28fc8a90f22add145a9c954e49d77da06263d58cf44d5fb91" dependencies = [ "base64 0.21.0", "bytes", @@ -2389,9 +2408,9 @@ dependencies = [ [[package]] name = "rustix" -version = "0.37.15" +version = "0.37.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0661814f891c57c930a610266415528da53c4933e6dea5fb350cbfe048a9ece" +checksum = "bc809f704c03a812ac71f22456c857be34185cac691a4316f27ab0f633bb9009" dependencies = [ "bitflags", "errno", @@ -2834,10 +2853,11 @@ checksum = "b6bc1c9ce2b5135ac7f93c72918fc37feb872bdc6a5533a8b85eb4b86bfdae52" [[package]] name = "tracing" -version = "0.1.38" +version = "0.1.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf9cf6a813d3f40c88b0b6b6f29a5c95c6cdbf97c1f9cc53fb820200f5ad814d" +checksum = "8ce8c33a8d48bd45d624a6e523445fd21ec13d3653cd51f681abf67418f54eb8" dependencies = [ + "cfg-if", "log", "pin-project-lite", "tracing-attributes", @@ -2972,9 +2992,9 @@ checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a" [[package]] name = "uuid" -version = "1.3.1" +version = "1.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b55a3fef2a1e3b3a00ce878640918820d3c51081576ac657d23af9fc7928fdb" +checksum = "4dad5567ad0cf5b760e5665964bec1b47dfd077ba8a2544b513f3556d3d239a2" dependencies = [ "getrandom", "serde", diff --git a/Cargo.toml b/Cargo.toml index 3e423c1..d65c767 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,6 +10,7 @@ actix = "0.13.0" actix-identity = "0.5.2" actix-web = "4" actix-session = { version = "0.7.2", features = ["cookie-session"] } +actix-remote-ip = "0.1.0" clap = { version = "4.2.1", features = ["derive", "env"] } include_dir = "0.7.3" log = "0.4.17" @@ -34,8 +35,7 @@ base32 = "0.4.0" qrcode-generator = "4.1.8" webauthn-rs = { version = "0.4.8", features = ["danger-allow-state-serialisation"] } url = "2.3.1" -aes-gcm = { version = "0.10.1", features = ["aes"] } +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/login_api.rs b/src/controllers/login_api.rs index 19043a0..532fdc1 100644 --- a/src/controllers/login_api.rs +++ b/src/controllers/login_api.rs @@ -1,9 +1,9 @@ use crate::actors::users_actor; use crate::actors::users_actor::UsersActor; use crate::data::action_logger::{Action, ActionLogger}; -use crate::data::remote_ip::RemoteIP; use actix::Addr; use actix_identity::Identity; +use actix_remote_ip::RemoteIP; use actix_web::{web, HttpRequest, HttpResponse, Responder}; use webauthn_rs::prelude::PublicKeyCredential; diff --git a/src/controllers/login_controller.rs b/src/controllers/login_controller.rs index 5bcf1f3..770beeb 100644 --- a/src/controllers/login_controller.rs +++ b/src/controllers/login_controller.rs @@ -1,5 +1,6 @@ use actix::Addr; use actix_identity::Identity; +use actix_remote_ip::RemoteIP; use actix_web::{web, HttpRequest, HttpResponse, Responder}; use askama::Template; use std::sync::Arc; @@ -14,7 +15,6 @@ use crate::controllers::base_controller::{ use crate::data::action_logger::{Action, ActionLogger}; use crate::data::login_redirect::LoginRedirect; use crate::data::provider::{Provider, ProvidersManager}; -use crate::data::remote_ip::RemoteIP; use crate::data::session_identity::{SessionIdentity, SessionStatus}; use crate::data::user::User; use crate::data::webauthn_manager::WebAuthManagerReq; 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/controllers/providers_controller.rs b/src/controllers/providers_controller.rs index f067ad7..3b77f95 100644 --- a/src/controllers/providers_controller.rs +++ b/src/controllers/providers_controller.rs @@ -2,6 +2,7 @@ use std::sync::Arc; use actix::Addr; use actix_identity::Identity; +use actix_remote_ip::RemoteIP; use actix_web::{web, HttpRequest, HttpResponse, Responder}; use askama::Template; @@ -16,7 +17,6 @@ use crate::data::action_logger::{Action, ActionLogger}; use crate::data::login_redirect::LoginRedirect; use crate::data::provider::{ProviderID, ProvidersManager}; use crate::data::provider_configuration::ProviderConfigurationHelper; -use crate::data::remote_ip::RemoteIP; use crate::data::session_identity::{SessionIdentity, SessionStatus}; #[derive(askama::Template)] diff --git a/src/controllers/settings_controller.rs b/src/controllers/settings_controller.rs index db713e2..30c69b4 100644 --- a/src/controllers/settings_controller.rs +++ b/src/controllers/settings_controller.rs @@ -1,4 +1,5 @@ use actix::Addr; +use actix_remote_ip::RemoteIP; use actix_web::{web, HttpResponse, Responder}; use askama::Template; @@ -9,7 +10,7 @@ use crate::constants::{APP_NAME, MAX_FAILED_LOGIN_ATTEMPTS, MIN_PASS_LEN}; use crate::data::action_logger::{Action, ActionLogger}; use crate::data::app_config::AppConfig; use crate::data::current_user::CurrentUser; -use crate::data::remote_ip::RemoteIP; + use crate::data::user::User; pub(crate) struct BaseSettingsPage<'a> { @@ -45,6 +46,7 @@ impl<'a> BaseSettingsPage<'a> { #[template(path = "settings/account_details.html")] struct AccountDetailsPage<'a> { _p: BaseSettingsPage<'a>, + remote_ip: String, } #[derive(Template)] @@ -55,11 +57,12 @@ struct ChangePasswordPage<'a> { } /// Account details page -pub async fn account_settings_details_route(user: CurrentUser) -> impl Responder { +pub async fn account_settings_details_route(user: CurrentUser, ip: RemoteIP) -> impl Responder { let user = user.into(); HttpResponse::Ok().body( AccountDetailsPage { _p: BaseSettingsPage::get("Account details", &user, None, None), + remote_ip: ip.0.to_string(), } .render() .unwrap(), diff --git a/src/data/action_logger.rs b/src/data/action_logger.rs index 694d074..46e9278 100644 --- a/src/data/action_logger.rs +++ b/src/data/action_logger.rs @@ -4,6 +4,7 @@ use std::pin::Pin; use actix::Addr; use actix_identity::Identity; +use actix_remote_ip::RemoteIP; use actix_web::dev::Payload; use actix_web::{web, Error, FromRequest, HttpRequest}; @@ -12,7 +13,7 @@ use crate::actors::users_actor; use crate::actors::users_actor::{AuthorizedAuthenticationSources, UsersActor}; use crate::data::client::Client; use crate::data::provider::{Provider, ProviderID}; -use crate::data::remote_ip::RemoteIP; + use crate::data::session_identity::SessionIdentity; use crate::data::user::{FactorID, GrantedClients, TwoFactor, User, UserID}; diff --git a/src/data/crypto_wrapper.rs b/src/data/crypto_wrapper.rs deleted file mode 100644 index eb2d34b..0000000 --- a/src/data/crypto_wrapper.rs +++ /dev/null @@ -1,98 +0,0 @@ -use std::io::ErrorKind; - -use aes_gcm::aead::{Aead, OsRng}; -use aes_gcm::{Aes256Gcm, Key, KeyInit, Nonce}; -use base64::engine::general_purpose::STANDARD as BASE64_STANDARD; -use base64::Engine as _; -use bincode::{Decode, Encode}; -use rand::Rng; - -use crate::utils::err::Res; - -const NONCE_LEN: usize = 12; - -pub struct CryptoWrapper { - key: Key, -} - -impl CryptoWrapper { - /// Generate a new memory wrapper - pub fn new_random() -> Self { - Self { - key: Aes256Gcm::generate_key(&mut OsRng), - } - } - - /// Encrypt some data - pub fn encrypt(&self, data: &T) -> Res { - let aes_key = Aes256Gcm::new(&self.key); - let nonce_bytes = rand::thread_rng().gen::<[u8; NONCE_LEN]>(); - - let serialized_data = bincode::encode_to_vec(data, bincode::config::standard())?; - - let mut enc = aes_key - .encrypt(Nonce::from_slice(&nonce_bytes), serialized_data.as_slice()) - .unwrap(); - enc.extend_from_slice(&nonce_bytes); - - Ok(BASE64_STANDARD.encode(enc)) - } - - /// Decrypt some data previously encrypted using the [`CryptoWrapper::encrypt`] method - pub fn decrypt(&self, input: &str) -> Res { - let bytes = BASE64_STANDARD.decode(input)?; - - if bytes.len() < NONCE_LEN { - return Err(Box::new(std::io::Error::new( - ErrorKind::Other, - "Input string is smaller than nonce!", - ))); - } - - let (enc, nonce) = bytes.split_at(bytes.len() - NONCE_LEN); - assert_eq!(nonce.len(), NONCE_LEN); - - let aes_key = Aes256Gcm::new(&self.key); - - let dec = match aes_key.decrypt(Nonce::from_slice(nonce), enc) { - Ok(d) => d, - Err(e) => { - log::error!("Failed to decrypt wrapped data! {:#?}", e); - return Err(Box::new(std::io::Error::new( - ErrorKind::Other, - "Failed to decrypt wrapped data!", - ))); - } - }; - - Ok(bincode::decode_from_slice(&dec, bincode::config::standard())?.0) - } -} - -#[cfg(test)] -mod test { - use crate::data::crypto_wrapper::CryptoWrapper; - use bincode::{Decode, Encode}; - - #[derive(Encode, Decode, Eq, PartialEq, Debug)] - struct Message(String); - - #[test] - fn encrypt_and_decrypt() { - let wrapper = CryptoWrapper::new_random(); - let msg = Message("Pierre was here".to_string()); - let enc = wrapper.encrypt(&msg).unwrap(); - let dec: Message = wrapper.decrypt(&enc).unwrap(); - - assert_eq!(dec, msg) - } - - #[test] - fn encrypt_and_decrypt_invalid() { - let wrapper_1 = CryptoWrapper::new_random(); - let wrapper_2 = CryptoWrapper::new_random(); - let msg = Message("Pierre was here".to_string()); - let enc = wrapper_1.encrypt(&msg).unwrap(); - wrapper_2.decrypt::(&enc).unwrap_err(); - } -} diff --git a/src/data/mod.rs b/src/data/mod.rs index 8bcf253..6e2cacd 100644 --- a/src/data/mod.rs +++ b/src/data/mod.rs @@ -3,16 +3,13 @@ pub mod action_logger; pub mod app_config; pub mod client; pub mod code_challenge; -pub mod crypto_wrapper; pub mod current_user; 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 remote_ip; pub mod session_identity; pub mod totp_key; pub mod user; 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, }) } diff --git a/src/data/remote_ip.rs b/src/data/remote_ip.rs deleted file mode 100644 index 98b7531..0000000 --- a/src/data/remote_ip.rs +++ /dev/null @@ -1,30 +0,0 @@ -use std::net::IpAddr; - -use actix_web::dev::Payload; -use actix_web::{Error, FromRequest, HttpRequest}; -use futures_util::future::{ready, Ready}; - -use crate::data::app_config::AppConfig; -use crate::utils::network_utils::get_remote_ip; - -#[derive(Copy, Clone, Debug, Eq, PartialEq)] -pub struct RemoteIP(pub IpAddr); - -impl From for IpAddr { - fn from(i: RemoteIP) -> Self { - i.0 - } -} - -impl FromRequest for RemoteIP { - type Error = Error; - type Future = Ready>; - - #[inline] - fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future { - ready(Ok(RemoteIP(get_remote_ip( - req, - AppConfig::get().proxy_ip.as_deref(), - )))) - } -} diff --git a/src/data/webauthn_manager.rs b/src/data/webauthn_manager.rs index 0575ed8..cb3e3be 100644 --- a/src/data/webauthn_manager.rs +++ b/src/data/webauthn_manager.rs @@ -3,6 +3,7 @@ use std::sync::Arc; use actix_web::web; use bincode::{Decode, Encode}; +use light_openid::crypto_wrapper::CryptoWrapper; use uuid::Uuid; use webauthn_rs::prelude::{ CreationChallengeResponse, Passkey, PublicKeyCredential, RegisterPublicKeyCredential, @@ -14,7 +15,6 @@ use crate::constants::{ APP_NAME, WEBAUTHN_LOGIN_CHALLENGE_EXPIRE, WEBAUTHN_REGISTER_CHALLENGE_EXPIRE, }; use crate::data::app_config::AppConfig; -use crate::data::crypto_wrapper::CryptoWrapper; use crate::data::user::{User, UserID}; use crate::utils::err::Res; use crate::utils::time::time; diff --git a/src/main.rs b/src/main.rs index 1093f87..5c34e79 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,6 +4,7 @@ use std::sync::Arc; use actix::Actor; use actix_identity::config::LogoutBehaviour; use actix_identity::IdentityMiddleware; +use actix_remote_ip::RemoteIPConfig; use actix_session::storage::CookieSessionStore; use actix_session::SessionMiddleware; use actix_web::cookie::{Key, SameSite}; @@ -113,6 +114,9 @@ async fn main() -> std::io::Result<()> { .app_data(web::Data::new(providers.clone())) .app_data(web::Data::new(jwt_signer.clone())) .app_data(web::Data::new(webauthn_manager.clone())) + .app_data(web::Data::new(RemoteIPConfig { + proxy: AppConfig::get().proxy_ip.clone(), + })) .wrap( middleware::DefaultHeaders::new().add(("Permissions-Policy", "interest-cohort=()")), ) diff --git a/src/utils/mod.rs b/src/utils/mod.rs index a93d33b..86d67dc 100644 --- a/src/utils/mod.rs +++ b/src/utils/mod.rs @@ -1,5 +1,4 @@ pub mod crypt_utils; pub mod err; -pub mod network_utils; pub mod string_utils; pub mod time; diff --git a/src/utils/network_utils.rs b/src/utils/network_utils.rs deleted file mode 100644 index 874a5e4..0000000 --- a/src/utils/network_utils.rs +++ /dev/null @@ -1,178 +0,0 @@ -use std::net::{IpAddr, Ipv6Addr}; -use std::str::FromStr; - -use actix_web::HttpRequest; - -/// Check if two ips matches -pub fn match_ip(pattern: &str, ip: &str) -> bool { - if pattern.eq(ip) { - return true; - } - - if pattern.ends_with('*') && ip.starts_with(&pattern.replace('*', "")) { - return true; - } - - false -} - -/// Get the remote IP address -pub fn get_remote_ip(req: &HttpRequest, proxy_ip: Option<&str>) -> IpAddr { - let mut ip = req.peer_addr().unwrap().ip(); - - // We check if the request comes from a trusted reverse proxy - if let Some(proxy) = proxy_ip.as_ref() { - if match_ip(proxy, &ip.to_string()) { - if let Some(header) = req.headers().get("X-Forwarded-For") { - let header = header.to_str().unwrap(); - - let remote_ip = if let Some((upstream_ip, _)) = header.split_once(',') { - upstream_ip - } else { - header - }; - - if let Some(upstream_ip) = parse_ip(remote_ip) { - ip = upstream_ip; - } - } - } - } - - ip -} - -/// Parse an IP address -pub fn parse_ip(ip: &str) -> Option { - let mut ip = match IpAddr::from_str(ip) { - Ok(ip) => ip, - Err(e) => { - log::warn!("Failed to parse an IP address: {}", e); - return None; - } - }; - - if let IpAddr::V6(ipv6) = &mut ip { - let mut octets = ipv6.octets(); - for o in octets.iter_mut().skip(8) { - *o = 0; - } - ip = IpAddr::V6(Ipv6Addr::from(octets)); - } - - Some(ip) -} - -#[cfg(test)] -mod test { - use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; - use std::str::FromStr; - - use actix_web::test::TestRequest; - - use crate::utils::network_utils::{get_remote_ip, parse_ip}; - - #[test] - fn test_get_remote_ip() { - let req = TestRequest::default() - .peer_addr(SocketAddr::from_str("192.168.1.1:1000").unwrap()) - .to_http_request(); - assert_eq!( - get_remote_ip(&req, None), - "192.168.1.1".parse::().unwrap() - ); - } - - #[test] - fn test_get_remote_ip_from_proxy() { - let req = TestRequest::default() - .peer_addr(SocketAddr::from_str("192.168.1.1:1000").unwrap()) - .insert_header(("X-Forwarded-For", "1.1.1.1")) - .to_http_request(); - assert_eq!( - get_remote_ip(&req, Some("192.168.1.1")), - "1.1.1.1".parse::().unwrap() - ); - } - - #[test] - fn test_get_remote_ip_from_proxy_2() { - let req = TestRequest::default() - .peer_addr(SocketAddr::from_str("192.168.1.1:1000").unwrap()) - .insert_header(("X-Forwarded-For", "1.1.1.1, 1.2.2.2")) - .to_http_request(); - assert_eq!( - get_remote_ip(&req, Some("192.168.1.1")), - "1.1.1.1".parse::().unwrap() - ); - } - - #[test] - fn test_get_remote_ip_from_proxy_ipv6() { - let req = TestRequest::default() - .peer_addr(SocketAddr::from_str("192.168.1.1:1000").unwrap()) - .insert_header(("X-Forwarded-For", "10::1, 1.2.2.2")) - .to_http_request(); - assert_eq!( - get_remote_ip(&req, Some("192.168.1.1")), - "10::".parse::().unwrap() - ); - } - - #[test] - fn test_get_remote_ip_from_no_proxy() { - let req = TestRequest::default() - .peer_addr(SocketAddr::from_str("192.168.1.1:1000").unwrap()) - .insert_header(("X-Forwarded-For", "1.1.1.1, 1.2.2.2")) - .to_http_request(); - assert_eq!( - get_remote_ip(&req, None), - "192.168.1.1".parse::().unwrap() - ); - } - - #[test] - fn test_get_remote_ip_from_other_proxy() { - let req = TestRequest::default() - .peer_addr(SocketAddr::from_str("192.168.1.1:1000").unwrap()) - .insert_header(("X-Forwarded-For", "1.1.1.1, 1.2.2.2")) - .to_http_request(); - assert_eq!( - get_remote_ip(&req, Some("192.168.1.2")), - "192.168.1.1".parse::().unwrap() - ); - } - - #[test] - fn parse_bad_ip() { - let ip = parse_ip("badbad"); - assert_eq!(None, ip); - } - - #[test] - fn parse_ip_v4_address() { - let ip = parse_ip("192.168.1.1").unwrap(); - assert_eq!(ip, IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1))); - } - - #[test] - fn parse_ip_v6_address() { - let ip = parse_ip("2a00:1450:4007:813::200e").unwrap(); - assert_eq!( - ip, - IpAddr::V6(Ipv6Addr::new(0x2a00, 0x1450, 0x4007, 0x813, 0, 0, 0, 0)) - ); - } - - #[test] - fn parse_ip_v6_address_2() { - let ip = parse_ip("::1").unwrap(); - assert_eq!(ip, IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0))); - } - - #[test] - fn parse_ip_v6_address_3() { - let ip = parse_ip("a::1").unwrap(); - assert_eq!(ip, IpAddr::V6(Ipv6Addr::new(0xa, 0, 0, 0, 0, 0, 0, 0))); - } -} diff --git a/templates/settings/account_details.html b/templates/settings/account_details.html index ace56be..4d918de 100644 --- a/templates/settings/account_details.html +++ b/templates/settings/account_details.html @@ -30,4 +30,6 @@ +

Your IP address: {{ remote_ip }}

+ {% endblock content %}