Refactor dependencies to reduce code base size #111

Merged
pierre merged 4 commits from dep-refactoring into master 2023-04-29 11:11:25 +00:00
18 changed files with 112 additions and 525 deletions

70
Cargo.lock generated
View File

@ -108,6 +108,17 @@ dependencies = [
"syn 1.0.109", "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]] [[package]]
name = "actix-router" name = "actix-router"
version = "0.5.1" version = "0.5.1"
@ -547,9 +558,9 @@ version = "0.1.4"
dependencies = [ dependencies = [
"actix", "actix",
"actix-identity", "actix-identity",
"actix-remote-ip",
"actix-session", "actix-session",
"actix-web", "actix-web",
"aes-gcm",
"askama", "askama",
"base32", "base32",
"base64 0.21.0", "base64 0.21.0",
@ -564,11 +575,11 @@ dependencies = [
"jwt-simple", "jwt-simple",
"lazy-regex", "lazy-regex",
"lazy_static", "lazy_static",
"light-openid",
"log", "log",
"mime_guess", "mime_guess",
"qrcode-generator", "qrcode-generator",
"rand", "rand",
"reqwest",
"serde", "serde",
"serde_json", "serde_json",
"serde_yaml", "serde_yaml",
@ -1188,12 +1199,12 @@ dependencies = [
[[package]] [[package]]
name = "flate2" name = "flate2"
version = "1.0.25" version = "1.0.26"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a8a2db397cb1c8772f31494cb8917e48cd1e64f0fa7efac59fbd741a0a8ce841" checksum = "3b9429470923de8e8cbd4d2dc513535400b4b3fef0319fb5c4e1f520a7bef743"
dependencies = [ dependencies = [
"crc32fast", "crc32fast",
"miniz_oxide 0.6.2", "miniz_oxide",
] ]
[[package]] [[package]]
@ -1753,6 +1764,23 @@ version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "348108ab3fba42ec82ff6e9564fc4ca0247bdccdc68dd8af9764bbc79c3c8ffb" 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]] [[package]]
name = "link-cplusplus" name = "link-cplusplus"
version = "1.0.8" version = "1.0.8"
@ -1764,9 +1792,9 @@ dependencies = [
[[package]] [[package]]
name = "linux-raw-sys" name = "linux-raw-sys"
version = "0.3.5" version = "0.3.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e8776872cdc2f073ccaab02e336fa321328c1e02646ebcb9d2108d0baab480d" checksum = "b64f40e5e03e0d54f03845c8197d0291253cdbedfb1cb46b13c2c117554a9f4c"
[[package]] [[package]]
name = "local-channel" name = "local-channel"
@ -1833,15 +1861,6 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" 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]] [[package]]
name = "miniz_oxide" name = "miniz_oxide"
version = "0.7.1" version = "0.7.1"
@ -2155,7 +2174,7 @@ dependencies = [
"crc32fast", "crc32fast",
"fdeflate", "fdeflate",
"flate2", "flate2",
"miniz_oxide 0.7.1", "miniz_oxide",
] ]
[[package]] [[package]]
@ -2287,9 +2306,9 @@ checksum = "a5996294f19bd3aae0453a862ad728f60e6600695733dd5df01da90c54363a3c"
[[package]] [[package]]
name = "reqwest" name = "reqwest"
version = "0.11.16" version = "0.11.17"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27b71749df584b7f4cac2c426c127a7c785a5106cc98f7a8feb044115f0fa254" checksum = "13293b639a097af28fc8a90f22add145a9c954e49d77da06263d58cf44d5fb91"
dependencies = [ dependencies = [
"base64 0.21.0", "base64 0.21.0",
"bytes", "bytes",
@ -2389,9 +2408,9 @@ dependencies = [
[[package]] [[package]]
name = "rustix" name = "rustix"
version = "0.37.15" version = "0.37.17"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a0661814f891c57c930a610266415528da53c4933e6dea5fb350cbfe048a9ece" checksum = "bc809f704c03a812ac71f22456c857be34185cac691a4316f27ab0f633bb9009"
dependencies = [ dependencies = [
"bitflags", "bitflags",
"errno", "errno",
@ -2834,10 +2853,11 @@ checksum = "b6bc1c9ce2b5135ac7f93c72918fc37feb872bdc6a5533a8b85eb4b86bfdae52"
[[package]] [[package]]
name = "tracing" name = "tracing"
version = "0.1.38" version = "0.1.37"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf9cf6a813d3f40c88b0b6b6f29a5c95c6cdbf97c1f9cc53fb820200f5ad814d" checksum = "8ce8c33a8d48bd45d624a6e523445fd21ec13d3653cd51f681abf67418f54eb8"
dependencies = [ dependencies = [
"cfg-if",
"log", "log",
"pin-project-lite", "pin-project-lite",
"tracing-attributes", "tracing-attributes",
@ -2972,9 +2992,9 @@ checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a"
[[package]] [[package]]
name = "uuid" name = "uuid"
version = "1.3.1" version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b55a3fef2a1e3b3a00ce878640918820d3c51081576ac657d23af9fc7928fdb" checksum = "4dad5567ad0cf5b760e5665964bec1b47dfd077ba8a2544b513f3556d3d239a2"
dependencies = [ dependencies = [
"getrandom", "getrandom",
"serde", "serde",

View File

@ -10,6 +10,7 @@ actix = "0.13.0"
actix-identity = "0.5.2" actix-identity = "0.5.2"
actix-web = "4" actix-web = "4"
actix-session = { version = "0.7.2", features = ["cookie-session"] } actix-session = { version = "0.7.2", features = ["cookie-session"] }
actix-remote-ip = "0.1.0"
clap = { version = "4.2.1", features = ["derive", "env"] } clap = { version = "4.2.1", features = ["derive", "env"] }
include_dir = "0.7.3" include_dir = "0.7.3"
log = "0.4.17" log = "0.4.17"
@ -34,8 +35,7 @@ base32 = "0.4.0"
qrcode-generator = "4.1.8" qrcode-generator = "4.1.8"
webauthn-rs = { version = "0.4.8", features = ["danger-allow-state-serialisation"] } webauthn-rs = { version = "0.4.8", features = ["danger-allow-state-serialisation"] }
url = "2.3.1" 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" bincode = "2.0.0-rc.3"
chrono = "0.4.24" chrono = "0.4.24"
lazy_static = "1.4.0" lazy_static = "1.4.0"
reqwest = { version = "0.11.16", features = ["json"] }

View File

@ -1,9 +1,9 @@
use crate::actors::users_actor; use crate::actors::users_actor;
use crate::actors::users_actor::UsersActor; use crate::actors::users_actor::UsersActor;
use crate::data::action_logger::{Action, ActionLogger}; use crate::data::action_logger::{Action, ActionLogger};
use crate::data::remote_ip::RemoteIP;
use actix::Addr; use actix::Addr;
use actix_identity::Identity; use actix_identity::Identity;
use actix_remote_ip::RemoteIP;
use actix_web::{web, HttpRequest, HttpResponse, Responder}; use actix_web::{web, HttpRequest, HttpResponse, Responder};
use webauthn_rs::prelude::PublicKeyCredential; use webauthn_rs::prelude::PublicKeyCredential;

View File

@ -1,5 +1,6 @@
use actix::Addr; use actix::Addr;
use actix_identity::Identity; use actix_identity::Identity;
use actix_remote_ip::RemoteIP;
use actix_web::{web, HttpRequest, HttpResponse, Responder}; use actix_web::{web, HttpRequest, HttpResponse, Responder};
use askama::Template; use askama::Template;
use std::sync::Arc; use std::sync::Arc;
@ -14,7 +15,6 @@ use crate::controllers::base_controller::{
use crate::data::action_logger::{Action, ActionLogger}; use crate::data::action_logger::{Action, ActionLogger};
use crate::data::login_redirect::LoginRedirect; use crate::data::login_redirect::LoginRedirect;
use crate::data::provider::{Provider, ProvidersManager}; use crate::data::provider::{Provider, ProvidersManager};
use crate::data::remote_ip::RemoteIP;
use crate::data::session_identity::{SessionIdentity, SessionStatus}; use crate::data::session_identity::{SessionIdentity, SessionStatus};
use crate::data::user::User; use crate::data::user::User;
use crate::data::webauthn_manager::WebAuthManagerReq; use crate::data::webauthn_manager::WebAuthManagerReq;

View File

@ -7,6 +7,7 @@ use actix_web::error::ErrorUnauthorized;
use actix_web::{web, HttpRequest, HttpResponse, Responder}; use actix_web::{web, HttpRequest, HttpResponse, Responder};
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD; use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use base64::Engine as _; use base64::Engine as _;
use light_openid::primitives::{OpenIDConfig, OpenIDTokenResponse, OpenIDUserInfo};
use crate::actors::openid_sessions_actor::{OpenIDSessionsActor, Session, SessionID}; use crate::actors::openid_sessions_actor::{OpenIDSessionsActor, Session, SessionID};
use crate::actors::users_actor::UsersActor; 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::current_user::CurrentUser;
use crate::data::id_token::IdToken; use crate::data::id_token::IdToken;
use crate::data::jwt_signer::{JWTSigner, JsonWebKey}; use crate::data::jwt_signer::{JWTSigner, JsonWebKey};
use crate::data::openid_primitive::{OpenIDConfig, OpenIDUserInfo, TokenResponse};
use crate::data::session_identity::SessionIdentity; use crate::data::session_identity::SessionIdentity;
use crate::data::user::User; use crate::data::user::User;
use crate::utils::string_utils::rand_str; 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(), issuer: AppConfig::get().website_origin.clone(),
authorization_endpoint: AppConfig::get().full_url(AUTHORIZE_URI), authorization_endpoint: AppConfig::get().full_url(AUTHORIZE_URI),
token_endpoint: curr_origin.clone() + TOKEN_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, jwks_uri: curr_origin + CERT_URI,
scopes_supported: vec!["openid", "profile", "email"], scopes_supported: Some(vec![
response_types_supported: vec!["code", "id_token", "token id_token"], "openid".to_string(),
subject_types_supported: vec!["public"], "profile".to_string(),
id_token_signing_alg_values_supported: vec!["RS256"], "email".to_string(),
token_endpoint_auth_methods_supported: vec!["client_secret_post", "client_secret_basic"], ]),
claims_supported: vec!["sub", "name", "given_name", "family_name", "email"], response_types_supported: vec![
code_challenge_methods_supported: vec!["plain", "S256"], "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, email: user.email,
}; };
TokenResponse { OpenIDTokenResponse {
access_token: session.access_token.expect("Missing access token!"), access_token: session.access_token.expect("Missing access token!"),
token_type: "Bearer".to_string(), token_type: "Bearer".to_string(),
refresh_token: Some(session.refresh_token), refresh_token: Some(session.refresh_token),
@ -488,7 +506,7 @@ pub async fn token(
.await .await
.unwrap(); .unwrap();
TokenResponse { OpenIDTokenResponse {
access_token: session.access_token.expect("Missing access token!"), access_token: session.access_token.expect("Missing access token!"),
token_type: "Bearer".to_string(), token_type: "Bearer".to_string(),
refresh_token: Some(session.refresh_token), refresh_token: Some(session.refresh_token),

View File

@ -2,6 +2,7 @@ use std::sync::Arc;
use actix::Addr; use actix::Addr;
use actix_identity::Identity; use actix_identity::Identity;
use actix_remote_ip::RemoteIP;
use actix_web::{web, HttpRequest, HttpResponse, Responder}; use actix_web::{web, HttpRequest, HttpResponse, Responder};
use askama::Template; use askama::Template;
@ -16,7 +17,6 @@ use crate::data::action_logger::{Action, ActionLogger};
use crate::data::login_redirect::LoginRedirect; use crate::data::login_redirect::LoginRedirect;
use crate::data::provider::{ProviderID, ProvidersManager}; use crate::data::provider::{ProviderID, ProvidersManager};
use crate::data::provider_configuration::ProviderConfigurationHelper; use crate::data::provider_configuration::ProviderConfigurationHelper;
use crate::data::remote_ip::RemoteIP;
use crate::data::session_identity::{SessionIdentity, SessionStatus}; use crate::data::session_identity::{SessionIdentity, SessionStatus};
#[derive(askama::Template)] #[derive(askama::Template)]

View File

@ -1,4 +1,5 @@
use actix::Addr; use actix::Addr;
use actix_remote_ip::RemoteIP;
use actix_web::{web, HttpResponse, Responder}; use actix_web::{web, HttpResponse, Responder};
use askama::Template; 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::action_logger::{Action, ActionLogger};
use crate::data::app_config::AppConfig; use crate::data::app_config::AppConfig;
use crate::data::current_user::CurrentUser; use crate::data::current_user::CurrentUser;
use crate::data::remote_ip::RemoteIP;
use crate::data::user::User; use crate::data::user::User;
pub(crate) struct BaseSettingsPage<'a> { pub(crate) struct BaseSettingsPage<'a> {
@ -45,6 +46,7 @@ impl<'a> BaseSettingsPage<'a> {
#[template(path = "settings/account_details.html")] #[template(path = "settings/account_details.html")]
struct AccountDetailsPage<'a> { struct AccountDetailsPage<'a> {
_p: BaseSettingsPage<'a>, _p: BaseSettingsPage<'a>,
remote_ip: String,
} }
#[derive(Template)] #[derive(Template)]
@ -55,11 +57,12 @@ struct ChangePasswordPage<'a> {
} }
/// Account details page /// 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(); let user = user.into();
HttpResponse::Ok().body( HttpResponse::Ok().body(
AccountDetailsPage { AccountDetailsPage {
_p: BaseSettingsPage::get("Account details", &user, None, None), _p: BaseSettingsPage::get("Account details", &user, None, None),
remote_ip: ip.0.to_string(),
} }
.render() .render()
.unwrap(), .unwrap(),

View File

@ -4,6 +4,7 @@ use std::pin::Pin;
use actix::Addr; use actix::Addr;
use actix_identity::Identity; use actix_identity::Identity;
use actix_remote_ip::RemoteIP;
use actix_web::dev::Payload; use actix_web::dev::Payload;
use actix_web::{web, Error, FromRequest, HttpRequest}; 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::actors::users_actor::{AuthorizedAuthenticationSources, UsersActor};
use crate::data::client::Client; use crate::data::client::Client;
use crate::data::provider::{Provider, ProviderID}; use crate::data::provider::{Provider, ProviderID};
use crate::data::remote_ip::RemoteIP;
use crate::data::session_identity::SessionIdentity; use crate::data::session_identity::SessionIdentity;
use crate::data::user::{FactorID, GrantedClients, TwoFactor, User, UserID}; use crate::data::user::{FactorID, GrantedClients, TwoFactor, User, UserID};

View File

@ -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<Aes256Gcm>,
}
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<T: Encode + Decode>(&self, data: &T) -> Res<String> {
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<T: Decode>(&self, input: &str) -> Res<T> {
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::<Message>(&enc).unwrap_err();
}
}

View File

@ -3,16 +3,13 @@ pub mod action_logger;
pub mod app_config; pub mod app_config;
pub mod client; pub mod client;
pub mod code_challenge; pub mod code_challenge;
pub mod crypto_wrapper;
pub mod current_user; pub mod current_user;
pub mod entity_manager; pub mod entity_manager;
pub mod id_token; pub mod id_token;
pub mod jwt_signer; pub mod jwt_signer;
pub mod login_redirect; pub mod login_redirect;
pub mod openid_primitive;
pub mod provider; pub mod provider;
pub mod provider_configuration; pub mod provider_configuration;
pub mod remote_ip;
pub mod session_identity; pub mod session_identity;
pub mod totp_key; pub mod totp_key;
pub mod user; pub mod user;

View File

@ -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<String>,
/// 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<u64>,
/// 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<String>,
}
/// Refer to <https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims> 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<String>,
/// 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<String>,
/// 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<String>,
/// 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<String>,
/// 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<String>,
/// 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<bool>,
}

View File

@ -1,38 +1,20 @@
use std::cell::RefCell; use std::cell::RefCell;
use std::collections::HashMap; use std::collections::HashMap;
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD; use light_openid::primitives::{OpenIDConfig, OpenIDTokenResponse, OpenIDUserInfo};
use base64::Engine as _;
use crate::actors::providers_states_actor::ProviderLoginState; use crate::actors::providers_states_actor::ProviderLoginState;
use crate::constants::OIDC_PROVIDERS_LIFETIME; use crate::constants::OIDC_PROVIDERS_LIFETIME;
use crate::data::app_config::AppConfig; 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::data::provider::Provider;
use crate::utils::err::Res; use crate::utils::err::Res;
use crate::utils::time::time; 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<String>,
pub jwks_uri: String,
pub claims_supported: Option<Vec<String>>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ProviderJWKs {
pub keys: Vec<JsonWebKey>,
}
/// Provider configuration /// Provider configuration
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct ProviderConfiguration { pub struct ProviderConfiguration {
pub discovery: ProviderDiscovery, pub discovery: OpenIDConfig,
//pub keys: ProviderJWKs,
pub expire: u64, pub expire: u64,
} }
@ -52,41 +34,23 @@ impl ProviderConfiguration {
&self, &self,
provider: &Provider, provider: &Provider,
authorization_code: &str, authorization_code: &str,
) -> Res<TokenResponse> { ) -> Res<OpenIDTokenResponse> {
let authorization = let (token, _) = self
BASE64_STANDARD.encode(format!("{}:{}", provider.client_id, provider.client_secret)); .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(); Ok(token)
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(&params)
.send()
.await?
.json()
.await?)
} }
/// Retrieve information about the user, using given [TokenResponse] /// Retrieve information about the user, using a given [OpenIDTokenResponse]
pub async fn get_userinfo(&self, token: &TokenResponse) -> Res<OpenIDUserInfo> { pub async fn get_userinfo(&self, token: &OpenIDTokenResponse) -> Res<OpenIDUserInfo> {
Ok(reqwest::Client::new() Ok(self.discovery.request_user_info(token).await?.0)
.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?)
} }
} }
@ -119,16 +83,8 @@ impl ProviderConfigurationHelper {
/// Get fresh configuration from provider /// Get fresh configuration from provider
async fn fetch_configuration(provider: &Provider) -> Res<ProviderConfiguration> { async fn fetch_configuration(provider: &Provider) -> Res<ProviderConfiguration> {
let discovery: ProviderDiscovery = reqwest::get(&provider.configuration_url)
.await?
.json()
.await?;
// let keys: ProviderJWKs = reqwest::get(&discovery.jwks_uri).await?.json().await?;
Ok(ProviderConfiguration { Ok(ProviderConfiguration {
discovery, discovery: OpenIDConfig::load_from_url(&provider.configuration_url).await?,
// keys,
expire: time() + OIDC_PROVIDERS_LIFETIME, expire: time() + OIDC_PROVIDERS_LIFETIME,
}) })
} }

View File

@ -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<RemoteIP> for IpAddr {
fn from(i: RemoteIP) -> Self {
i.0
}
}
impl FromRequest for RemoteIP {
type Error = Error;
type Future = Ready<Result<Self, Error>>;
#[inline]
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
ready(Ok(RemoteIP(get_remote_ip(
req,
AppConfig::get().proxy_ip.as_deref(),
))))
}
}

View File

@ -3,6 +3,7 @@ use std::sync::Arc;
use actix_web::web; use actix_web::web;
use bincode::{Decode, Encode}; use bincode::{Decode, Encode};
use light_openid::crypto_wrapper::CryptoWrapper;
use uuid::Uuid; use uuid::Uuid;
use webauthn_rs::prelude::{ use webauthn_rs::prelude::{
CreationChallengeResponse, Passkey, PublicKeyCredential, RegisterPublicKeyCredential, CreationChallengeResponse, Passkey, PublicKeyCredential, RegisterPublicKeyCredential,
@ -14,7 +15,6 @@ use crate::constants::{
APP_NAME, WEBAUTHN_LOGIN_CHALLENGE_EXPIRE, WEBAUTHN_REGISTER_CHALLENGE_EXPIRE, APP_NAME, WEBAUTHN_LOGIN_CHALLENGE_EXPIRE, WEBAUTHN_REGISTER_CHALLENGE_EXPIRE,
}; };
use crate::data::app_config::AppConfig; use crate::data::app_config::AppConfig;
use crate::data::crypto_wrapper::CryptoWrapper;
use crate::data::user::{User, UserID}; use crate::data::user::{User, UserID};
use crate::utils::err::Res; use crate::utils::err::Res;
use crate::utils::time::time; use crate::utils::time::time;

View File

@ -4,6 +4,7 @@ use std::sync::Arc;
use actix::Actor; use actix::Actor;
use actix_identity::config::LogoutBehaviour; use actix_identity::config::LogoutBehaviour;
use actix_identity::IdentityMiddleware; use actix_identity::IdentityMiddleware;
use actix_remote_ip::RemoteIPConfig;
use actix_session::storage::CookieSessionStore; use actix_session::storage::CookieSessionStore;
use actix_session::SessionMiddleware; use actix_session::SessionMiddleware;
use actix_web::cookie::{Key, SameSite}; 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(providers.clone()))
.app_data(web::Data::new(jwt_signer.clone())) .app_data(web::Data::new(jwt_signer.clone()))
.app_data(web::Data::new(webauthn_manager.clone())) .app_data(web::Data::new(webauthn_manager.clone()))
.app_data(web::Data::new(RemoteIPConfig {
proxy: AppConfig::get().proxy_ip.clone(),
}))
.wrap( .wrap(
middleware::DefaultHeaders::new().add(("Permissions-Policy", "interest-cohort=()")), middleware::DefaultHeaders::new().add(("Permissions-Policy", "interest-cohort=()")),
) )

View File

@ -1,5 +1,4 @@
pub mod crypt_utils; pub mod crypt_utils;
pub mod err; pub mod err;
pub mod network_utils;
pub mod string_utils; pub mod string_utils;
pub mod time; pub mod time;

View File

@ -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<IpAddr> {
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::<IpAddr>().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::<IpAddr>().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::<IpAddr>().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::<IpAddr>().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::<IpAddr>().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::<IpAddr>().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)));
}
}

View File

@ -30,4 +30,6 @@
</tbody> </tbody>
</table> </table>
<p>Your IP address: {{ remote_ip }}</p>
{% endblock content %} {% endblock content %}