Compare commits

..

1 Commits

Author SHA1 Message Date
4bcd194e20 Update Rust crate url to v2.5.1
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2024-06-11 00:11:45 +00:00
33 changed files with 1044 additions and 1221 deletions

1757
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,42 +1,42 @@
[package]
name = "basic-oidc"
version = "0.1.5"
edition = "2024"
version = "0.1.4"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
actix = "0.13.5"
actix-identity = "0.8.0"
actix-web = "4.11.0"
actix-session = { version = "0.10.1", features = ["cookie-session"] }
actix = "0.13.3"
actix-identity = "0.7.1"
actix-web = "4.5.1"
actix-session = { version = "0.9.0", features = ["cookie-session"] }
actix-remote-ip = "0.1.0"
clap = { version = "4.5.41", features = ["derive", "env"] }
include_dir = "0.7.4"
log = "0.4.27"
serde_json = "1.0.141"
clap = { version = "4.5.4", features = ["derive", "env"] }
include_dir = "0.7.3"
log = "0.4.21"
serde_json = "1.0.116"
serde_yaml = "0.9.34"
env_logger = "0.11.8"
serde = { version = "1.0.219", features = ["derive"] }
bcrypt = "0.17.0"
uuid = { version = "1.17.0", features = ["v4"] }
mime_guess = "2.0.5"
askama = "0.14.0"
futures-util = "0.3.31"
env_logger = "0.11.3"
serde = { version = "1.0.200", features = ["derive"] }
bcrypt = "0.15.1"
uuid = { version = "1.8.0", features = ["v4"] }
mime_guess = "2.0.4"
askama = "0.12.1"
futures-util = "0.3.30"
urlencoding = "2.1.3"
rand = "0.9.1"
rand = "0.8.5"
base64 = "0.22.1"
jwt-simple = { version = "0.12.12", default-features = false, features = ["pure-rust"] }
jwt-simple = { version = "0.12.9", default-features = false, features = ["pure-rust"] }
digest = "0.10.7"
sha2 = "0.10.9"
lazy-regex = "3.4.1"
totp_rfc6238 = "0.6.1"
base32 = "0.5.1"
qrcode-generator = "5.0.0"
webauthn-rs = { version = "0.5.2", features = ["danger-allow-state-serialisation"] }
url = "2.5.4"
light-openid = { version = "1.0.4", features = ["crypto-wrapper"] }
bincode = "2.0.1"
chrono = "0.4.41"
lazy_static = "1.5.0"
mailchecker = "6.0.17"
sha2 = "0.10.8"
lazy-regex = "3.1.0"
totp_rfc6238 = "0.5.3"
base32 = "0.5.0"
qrcode-generator = "4.1.9"
webauthn-rs = { version = "0.5.0", features = ["danger-allow-state-serialisation"] }
url = "2.5.0"
light-openid = { version = "1.0.2", features = ["crypto-wrapper"] }
bincode = "2.0.0-rc.3"
chrono = "0.4.38"
lazy_static = "1.4.0"
mailchecker = "6.0.4"

View File

@@ -6,4 +6,4 @@ RUN apt-get update \
COPY basic-oidc /usr/local/bin/basic-oidc
ENTRYPOINT ["/usr/local/bin/basic-oidc"]
ENTRYPOINT /usr/local/bin/basic-oidc

View File

@@ -1,3 +1,9 @@
{
"extends": ["local>renovate/presets"]
}
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"packageRules": [
{
"matchUpdateTypes": ["major", "minor", "patch"],
"automerge": true
}
]
}

View File

@@ -1,5 +1,5 @@
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::net::IpAddr;
use actix::{Actor, AsyncContext, Context, Handler, Message};

View File

@@ -8,8 +8,8 @@ use crate::constants::{
OIDC_STATES_CLEANUP_INTERVAL,
};
use actix::{Actor, AsyncContext, Context, Handler, Message};
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::net::IpAddr;
use crate::data::login_redirect::LoginRedirect;

View File

@@ -151,7 +151,7 @@ impl Handler<LocalLoginRequest> for UsersActor {
fn handle(&mut self, msg: LocalLoginRequest, _ctx: &mut Self::Context) -> Self::Result {
match self.manager.find_by_username_or_email(&msg.login) {
Err(e) => {
log::error!("Failed to find user! {e}");
log::error!("Failed to find user! {}", e);
MessageResult(LoginResult::Error)
}
Ok(None) => MessageResult(LoginResult::AccountNotFound),
@@ -184,7 +184,7 @@ impl Handler<ProviderLoginRequest> for UsersActor {
fn handle(&mut self, msg: ProviderLoginRequest, _ctx: &mut Self::Context) -> Self::Result {
match self.manager.find_by_email(&msg.email) {
Err(e) => {
log::error!("Failed to find user! {e}");
log::error!("Failed to find user! {}", e);
MessageResult(LoginResult::Error)
}
Ok(None) => MessageResult(LoginResult::AccountNotFound),
@@ -210,7 +210,7 @@ impl Handler<CreateAccount> for UsersActor {
match self.manager.create_user_account(msg.0) {
Ok(id) => Some(id),
Err(e) => {
log::error!("Failed to create user account! {e}");
log::error!("Failed to create user account! {}", e);
None
}
}
@@ -227,7 +227,7 @@ impl Handler<ChangePasswordRequest> for UsersActor {
{
Ok(_) => true,
Err(e) => {
log::error!("Failed to change user password! {e:?}");
log::error!("Failed to change user password! {:?}", e);
false
}
}
@@ -241,7 +241,7 @@ impl Handler<Add2FAFactor> for UsersActor {
match self.manager.add_2fa_factor(&msg.0, msg.1) {
Ok(_) => true,
Err(e) => {
log::error!("Failed to add 2FA factor! {e}");
log::error!("Failed to add 2FA factor! {}", e);
false
}
}
@@ -255,7 +255,7 @@ impl Handler<Remove2FAFactor> for UsersActor {
match self.manager.remove_2fa_factor(&msg.0, msg.1) {
Ok(_) => true,
Err(e) => {
log::error!("Failed to remove 2FA factor! {e}");
log::error!("Failed to remove 2FA factor! {}", e);
false
}
}
@@ -272,7 +272,7 @@ impl Handler<AddSuccessful2FALogin> for UsersActor {
{
Ok(_) => true,
Err(e) => {
log::error!("Failed to save successful 2FA authentication! {e}");
log::error!("Failed to save successful 2FA authentication! {}", e);
false
}
}
@@ -309,7 +309,10 @@ impl Handler<SetAuthorizedAuthenticationSources> for UsersActor {
{
Ok(_) => true,
Err(e) => {
log::error!("Failed to set authorized authentication sources for user! {e}");
log::error!(
"Failed to set authorized authentication sources for user! {}",
e
);
false
}
}
@@ -322,7 +325,7 @@ impl Handler<SetGrantedClients> for UsersActor {
match self.manager.set_granted_2fa_clients(&msg.0, msg.1) {
Ok(_) => true,
Err(e) => {
log::error!("Failed to set granted 2FA clients! {e}");
log::error!("Failed to set granted 2FA clients! {}", e);
false
}
}
@@ -336,7 +339,7 @@ impl Handler<GetUserRequest> for UsersActor {
MessageResult(GetUserResult(match self.manager.find_by_user_id(&msg.0) {
Ok(r) => r,
Err(e) => {
log::error!("Failed to find user by id! {e}");
log::error!("Failed to find user by id! {}", e);
None
}
}))
@@ -350,7 +353,7 @@ impl Handler<VerifyUserPasswordRequest> for UsersActor {
self.manager
.verify_user_password(&msg.0, &msg.1)
.unwrap_or_else(|e| {
log::error!("Failed to verify user password! {e}");
log::error!("Failed to verify user password! {}", e);
false
})
}
@@ -364,7 +367,7 @@ impl Handler<FindUserByUsername> for UsersActor {
self.manager
.find_by_username_or_email(&msg.0)
.unwrap_or_else(|e| {
log::error!("Failed to find user by username or email! {e}");
log::error!("Failed to find user by username or email! {}", e);
None
}),
))
@@ -378,7 +381,7 @@ impl Handler<GetAllUsers> for UsersActor {
match self.manager.get_entire_users_list() {
Ok(r) => r,
Err(e) => {
log::error!("Failed to get entire users list! {e}");
log::error!("Failed to get entire users list! {}", e);
vec![]
}
}
@@ -392,7 +395,7 @@ impl Handler<UpdateUserSettings> for UsersActor {
match self.manager.set_general_user_settings(msg.0) {
Ok(_) => true,
Err(e) => {
log::error!("Failed to update general user information! {e:?}");
log::error!("Failed to update general user information! {:?}", e);
false
}
}
@@ -406,7 +409,7 @@ impl Handler<DeleteUserRequest> for UsersActor {
match self.manager.delete_account(&msg.0) {
Ok(_) => true,
Err(e) => {
log::error!("Failed to delete user account! {e}");
log::error!("Failed to delete user account! {}", e);
false
}
}

View File

@@ -1,6 +1,6 @@
use crate::actors::users_actor;
use actix::Addr;
use actix_web::{HttpResponse, Responder, web};
use actix_web::{web, HttpResponse, Responder};
use crate::actors::users_actor::{DeleteUserRequest, FindUserByUsername, UsersActor};
use crate::data::action_logger::{Action, ActionLogger};

View File

@@ -2,7 +2,7 @@ use std::ops::Deref;
use std::sync::Arc;
use actix::Addr;
use actix_web::{HttpResponse, Responder, web};
use actix_web::{web, HttpResponse, Responder};
use askama::Template;
use crate::actors::users_actor;

View File

@@ -1,7 +1,7 @@
use std::path::Path;
use actix_web::{HttpResponse, web};
use include_dir::{Dir, include_dir};
use actix_web::{web, HttpResponse};
use include_dir::{include_dir, Dir};
/// Assets directory
static ASSETS_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/assets");

View File

@@ -4,7 +4,7 @@ use crate::data::action_logger::{Action, ActionLogger};
use actix::Addr;
use actix_identity::Identity;
use actix_remote_ip::RemoteIP;
use actix_web::{HttpRequest, HttpResponse, Responder, web};
use actix_web::{web, HttpRequest, HttpResponse, Responder};
use webauthn_rs::prelude::PublicKeyCredential;
use crate::data::session_identity::{SessionIdentity, SessionStatus};
@@ -47,7 +47,7 @@ pub async fn auth_webauthn(
HttpResponse::Ok().body("You are authenticated!")
}
Err(e) => {
log::error!("Failed to authenticate user using webauthn! {e:?}");
log::error!("Failed to authenticate user using webauthn! {:?}", e);
logger.log(Action::LoginWebauthnAttempt {
success: false,
user_id,

View File

@@ -1,7 +1,7 @@
use actix::Addr;
use actix_identity::Identity;
use actix_remote_ip::RemoteIP;
use actix_web::{HttpRequest, HttpResponse, Responder, web};
use actix_web::{web, HttpRequest, HttpResponse, Responder};
use askama::Template;
use std::sync::Arc;
@@ -14,7 +14,7 @@ use crate::controllers::base_controller::{
};
use crate::data::action_logger::{Action, ActionLogger};
use crate::data::force_2fa_auth::Force2FAAuth;
use crate::data::login_redirect::{LoginRedirect, get_2fa_url};
use crate::data::login_redirect::{get_2fa_url, LoginRedirect};
use crate::data::provider::{Provider, ProvidersManager};
use crate::data::session_identity::{SessionIdentity, SessionStatus};
use crate::data::user::User;
@@ -177,10 +177,7 @@ pub async fn login_route(
}
LoginResult::LocalAuthForbidden => {
log::warn!(
"Failed login for username {} : attempted to use local auth, but it is forbidden",
&login
);
log::warn!("Failed login for username {} : attempted to use local auth, but it is forbidden", &login);
logger.log(Action::TryLocalLoginFromUnauthorizedAccount(&login));
danger = Some("You cannot login from local auth with your account!".to_string());
}
@@ -190,7 +187,12 @@ pub async fn login_route(
}
c => {
log::warn!("Failed login for ip {remote_ip:?} / username {login}: {c:?}");
log::warn!(
"Failed login for ip {:?} / username {}: {:?}",
remote_ip,
login,
c
);
logger.log(Action::FailedLoginWithBadCredentials(&login));
danger = Some("Login failed.".to_string());
@@ -469,7 +471,7 @@ pub async fn login_with_webauthn(
let challenge = match manager.start_authentication(&user.uid, &pub_keys) {
Ok(c) => c,
Err(e) => {
log::error!("Failed to generate webauthn challenge! {e:?}");
log::error!("Failed to generate webauthn challenge! {:?}", e);
return HttpResponse::InternalServerError().body(build_fatal_error_page(
"Failed to generate webauthn challenge",
));
@@ -479,7 +481,7 @@ pub async fn login_with_webauthn(
let challenge_json = match serde_json::to_string(&challenge.login_challenge) {
Ok(r) => r,
Err(e) => {
log::error!("Failed to serialize challenge! {e:?}");
log::error!("Failed to serialize challenge! {:?}", e);
return HttpResponse::InternalServerError().body("Failed to serialize challenge!");
}
};

View File

@@ -4,9 +4,9 @@ use std::sync::Arc;
use actix::Addr;
use actix_identity::Identity;
use actix_web::error::ErrorUnauthorized;
use actix_web::{HttpRequest, HttpResponse, Responder, web};
use base64::Engine as _;
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};
@@ -16,12 +16,12 @@ use crate::constants::*;
use crate::controllers::base_controller::{build_fatal_error_page, redirect_user};
use crate::data::action_logger::{Action, ActionLogger};
use crate::data::app_config::AppConfig;
use crate::data::client::{AdditionalClaims, ClientID, ClientManager};
use crate::data::client::{AdditionalClaims, AuthenticationFlow, ClientID, ClientManager};
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::login_redirect::{LoginRedirect, get_2fa_url};
use crate::data::login_redirect::{get_2fa_url, LoginRedirect};
use crate::data::session_identity::SessionIdentity;
use crate::data::user::User;
@@ -32,7 +32,6 @@ pub async fn get_configuration(req: HttpRequest) -> impl Responder {
let is_secure_request = req
.headers()
.get("HTTP_X_FORWARDED_PROTO")
.or_else(|| req.headers().get("X-Forwarded-Proto"))
.map(|v| v.to_str().unwrap_or_default().to_lowercase().eq("https"))
.unwrap_or(false);
@@ -50,39 +49,37 @@ pub async fn get_configuration(req: HttpRequest) -> impl Responder {
host
);
HttpResponse::Ok()
.insert_header(("access-control-allow-origin", "*"))
.json(OpenIDConfig {
issuer: AppConfig::get().website_origin.clone(),
authorization_endpoint: AppConfig::get().full_url(AUTHORIZE_URI),
token_endpoint: curr_origin.clone() + TOKEN_URI,
userinfo_endpoint: Some(curr_origin.clone() + USERINFO_URI),
jwks_uri: curr_origin + CERT_URI,
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()]),
})
HttpResponse::Ok().json(OpenIDConfig {
issuer: AppConfig::get().website_origin.clone(),
authorization_endpoint: AppConfig::get().full_url(AUTHORIZE_URI),
token_endpoint: curr_origin.clone() + TOKEN_URI,
userinfo_endpoint: Some(curr_origin.clone() + USERINFO_URI),
jwks_uri: curr_origin + CERT_URI,
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()]),
})
}
#[derive(serde::Deserialize, Debug)]
@@ -111,7 +108,12 @@ pub struct AuthorizeQuery {
}
fn error_redirect(query: &AuthorizeQuery, error: &str, description: &str) -> HttpResponse {
log::warn!("Failed to process sign in request ({error} => {description}): {query:?}");
log::warn!(
"Failed to process sign in request ({} => {}): {:?}",
error,
description,
query
);
HttpResponse::Found()
.append_header((
"Location",
@@ -215,8 +217,8 @@ pub async fn authorize(
));
}
match (client.has_secret(), query.response_type.as_str()) {
(_, "code") => {
match (client.auth_flow(), query.response_type.as_str()) {
(AuthenticationFlow::AuthorizationCode, "code") => {
// Save all authentication information in memory
let session = Session {
session_id: SessionID(rand_str(OPEN_ID_SESSION_LEN)),
@@ -238,7 +240,7 @@ pub async fn authorize(
.await
.unwrap();
log::trace!("New OpenID session: {session:#?}");
log::trace!("New OpenID session: {:#?}", session);
logger.log(Action::NewOpenIDSession { client: &client });
Ok(HttpResponse::Found()
@@ -258,8 +260,7 @@ pub async fn authorize(
.finish())
}
// id_token is available only if user has no secret configured
(false, "id_token") => {
(AuthenticationFlow::Implicit, "id_token") => {
let id_token = IdToken {
issuer: AppConfig::get().website_origin.to_string(),
subject_identifier: user.uid.0.clone(),
@@ -291,11 +292,11 @@ pub async fn authorize(
.finish())
}
(secret, code) => {
(flow, code) => {
log::warn!(
"For client {:?}, configured with secret {:?}, made request with code {}",
"For client {:?}, configured with flow {:?}, made request with code {}",
client.id,
secret,
flow,
code
);
Ok(error_redirect(
@@ -314,7 +315,12 @@ struct ErrorResponse {
}
pub fn error_response<D: Debug>(query: &D, error: &str, description: &str) -> HttpResponse {
log::warn!("request failed: {error} - {description} => '{query:#?}'");
log::warn!(
"request failed: {} - {} => '{:#?}'",
error,
description,
query
);
HttpResponse::BadRequest().json(ErrorResponse {
error: error.to_string(),
error_description: description.to_string(),
@@ -359,7 +365,9 @@ pub async fn token(
let (client_id, client_secret) =
match (&query.client_id, &query.client_secret, authorization_header) {
// post authentication
(Some(client_id), client_secret, None) => (client_id.clone(), client_secret.clone()),
(Some(client_id), Some(client_secret), None) => {
(client_id.clone(), client_secret.to_string())
}
// Basic authentication
(_, None, Some(v)) => {
@@ -379,7 +387,7 @@ pub async fn token(
let decode = String::from_utf8_lossy(&match BASE64_STANDARD.decode(token) {
Ok(d) => d,
Err(e) => {
log::error!("Failed to decode authorization header: {e:?}");
log::error!("Failed to decode authorization header: {:?}", e);
return Ok(error_response(
&query,
"invalid_request",
@@ -390,8 +398,8 @@ pub async fn token(
.to_string();
match decode.split_once(':') {
None => (ClientID(decode), None),
Some((id, secret)) => (ClientID(id.to_string()), Some(secret.to_string())),
None => (ClientID(decode), "".to_string()),
Some((id, secret)) => (ClientID(id.to_string()), secret.to_string()),
}
}
@@ -409,7 +417,7 @@ pub async fn token(
.ok_or_else(|| ErrorUnauthorized("Client not found"))?;
// Retrieving token requires the client to have a defined secret
if client.secret != client_secret {
if client.secret != Some(client_secret) {
return Ok(error_response(
&query,
"invalid_request",
@@ -599,9 +607,8 @@ pub async fn token(
};
Ok(HttpResponse::Ok()
.insert_header(("Cache-Control", "no-store"))
.insert_header(("Pragma", "no-cache"))
.insert_header(("access-control-allow-origin", "*"))
.append_header(("Cache-Control", "no-store"))
.append_header(("Pragam", "no-cache"))
.json(token_response))
}

View File

@@ -3,7 +3,7 @@ use std::sync::Arc;
use actix::Addr;
use actix_identity::Identity;
use actix_remote_ip::RemoteIP;
use actix_web::{HttpRequest, HttpResponse, Responder, web};
use actix_web::{web, HttpRequest, HttpResponse, Responder};
use askama::Template;
use crate::actors::bruteforce_actor::BruteForceActor;
@@ -96,14 +96,14 @@ pub async fn start_login(
let config = match ProviderConfigurationHelper::get_configuration(&provider).await {
Ok(c) => c,
Err(e) => {
log::error!("Failed to load provider configuration! {e}");
log::error!("Failed to load provider configuration! {}", e);
return HttpResponse::InternalServerError().body(build_fatal_error_page(
"Failed to load provider configuration!",
));
}
};
log::debug!("Provider configuration: {config:?}");
log::debug!("Provider configuration: {:?}", config);
let url = config.auth_url(&provider, &state);
log::debug!("Redirect user on {url} for authentication",);
@@ -210,7 +210,7 @@ pub async fn finish_login(
let provider_config = match ProviderConfigurationHelper::get_configuration(&provider).await {
Ok(c) => c,
Err(e) => {
log::error!("Failed to load provider configuration! {e}");
log::error!("Failed to load provider configuration! {}", e);
return HttpResponse::InternalServerError().body(build_fatal_error_page(
"Failed to load provider configuration!",
));
@@ -222,7 +222,7 @@ pub async fn finish_login(
let token = match token {
Ok(t) => t,
Err(e) => {
log::error!("Failed to retrieve login token! {e:?}");
log::error!("Failed to retrieve login token! {:?}", e);
bruteforce
.send(bruteforce_actor::RecordFailedAttempt {
@@ -247,7 +247,7 @@ pub async fn finish_login(
let user_info = match provider_config.get_userinfo(&token).await {
Ok(info) => info,
Err(e) => {
log::error!("Failed to retrieve user information! {e:?}");
log::error!("Failed to retrieve user information! {:?}", e);
logger.log(Action::ProviderFailedGetUserInfo {
provider: &provider,

View File

@@ -1,6 +1,6 @@
use actix::Addr;
use actix_remote_ip::RemoteIP;
use actix_web::{HttpResponse, Responder, web};
use actix_web::{web, HttpResponse, Responder};
use askama::Template;
use crate::actors::bruteforce_actor::BruteForceActor;

View File

@@ -1,5 +1,5 @@
use actix::Addr;
use actix_web::{HttpResponse, Responder, web};
use actix_web::{web, HttpResponse, Responder};
use uuid::Uuid;
use webauthn_rs::prelude::RegisterPublicKeyCredential;
@@ -94,7 +94,7 @@ pub async fn save_webauthn_factor(
let key = match manager.finish_registration(&user, &form.0.opaque_state, form.0.credential) {
Ok(k) => k,
Err(e) => {
log::error!("Failed to register security key! {e:?}");
log::error!("Failed to register security key! {:?}", e);
return HttpResponse::InternalServerError().body("Failed to register key!");
}
};

View File

@@ -2,8 +2,8 @@ use std::ops::Deref;
use actix_web::{HttpResponse, Responder};
use askama::Template;
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use base64::Engine as _;
use qrcode_generator::QrCodeEcc;
use crate::constants::MAX_SECOND_FACTOR_NAME_LEN;
@@ -68,7 +68,7 @@ pub async fn add_totp_factor_route(_critical: CriticalRoute, user: CurrentUser)
let qr_code = match qr_code {
Ok(q) => q,
Err(e) => {
log::error!("Failed to generate QrCode! {e:?}");
log::error!("Failed to generate QrCode! {:?}", e);
return HttpResponse::InternalServerError().body("Failed to generate QrCode!");
}
};
@@ -95,7 +95,7 @@ pub async fn add_webauthn_factor_route(
let registration_request = match manager.start_register(&user) {
Ok(r) => r,
Err(e) => {
log::error!("Failed to request new key! {e:?}");
log::error!("Failed to request new key! {:?}", e);
return HttpResponse::InternalServerError()
.body("Failed to generate request for registration!");
}
@@ -104,7 +104,7 @@ pub async fn add_webauthn_factor_route(
let challenge_json = match serde_json::to_string(&registration_request.creation_challenge) {
Ok(r) => r,
Err(e) => {
log::error!("Failed to serialize challenge! {e:?}");
log::error!("Failed to serialize challenge! {:?}", e);
return HttpResponse::InternalServerError().body("Failed to serialize challenge!");
}
};

View File

@@ -6,7 +6,7 @@ use actix::Addr;
use actix_identity::Identity;
use actix_remote_ip::RemoteIP;
use actix_web::dev::Payload;
use actix_web::{Error, FromRequest, HttpRequest, web};
use actix_web::{web, Error, FromRequest, HttpRequest};
use crate::actors::providers_states_actor::ProviderLoginState;
use crate::actors::users_actor;
@@ -101,7 +101,7 @@ pub enum Action<'a> {
},
}
impl Action<'_> {
impl<'a> Action<'a> {
pub fn as_string(&self) -> String {
match self {
Action::AdminDeleteUser(user) => {
@@ -142,55 +142,27 @@ impl Action<'_> {
false => format!("performed FAILED webauthn attempt for user {user_id:?}"),
},
Action::StartLoginAttemptWithOpenIDProvider { provider_id, state } => format!(
"started new authentication attempt through an OpenID provider (prov={} / state={state})",
provider_id.0
),
Action::ProviderError { message } => {
format!("failed provider authentication with message '{message}'")
}
Action::ProviderCBInvalidState { state } => {
format!("provided invalid callback state after provider authentication: '{state}'")
}
Action::ProviderRateLimited => {
"could not complete OpenID login because it has reached failed attempts rate limit!"
.to_string()
}
Action::ProviderFailedGetToken { state, code } => format!(
"could not complete login from provider because the id_token could not be retrieved! (state={state:?} code = {code})"
),
Action::ProviderFailedGetUserInfo { provider } => format!(
"could not get user information from userinfo endpoint of provider {}!",
provider.id.0
),
Action::ProviderEmailNotValidated { provider } => format!(
"could not login using provider {} because its email was marked as not validated!",
provider.id.0
),
Action::ProviderMissingEmailInResponse { provider } => format!(
"could not login using provider {} because the email was not provided by userinfo endpoint!",
provider.id.0
),
Action::ProviderAccountNotFound { provider, email } => format!(
"could not login using provider {} because the email {email} could not be associated to any account!",
&provider.id.0
),
Action::ProviderAccountDisabled { provider, email } => format!(
"could not login using provider {} because the account associated to the email {email} is disabled!",
&provider.id.0
),
Action::ProviderAccountNotAllowedToLoginWithProvider { provider, email } => format!(
"could not login using provider {} because the account associated to the email {email} is not allowed to authenticate using this provider!",
&provider.id.0
),
Action::ProviderLoginFailed { provider, email } => format!(
"could not login using provider {} with the email {email} for an unknown reason!",
&provider.id.0
),
Action::ProviderLoginSuccessful { provider, user } => format!(
"successfully authenticated using provider {} as {}",
provider.id.0,
user.quick_identity()
"started new authentication attempt through an OpenID provider (prov={} / state={state})", provider_id.0
),
Action::ProviderError { message } =>
format!("failed provider authentication with message '{message}'"),
Action::ProviderCBInvalidState { state } =>
format!("provided invalid callback state after provider authentication: '{state}'"),
Action::ProviderRateLimited => "could not complete OpenID login because it has reached failed attempts rate limit!".to_string(),
Action::ProviderFailedGetToken {state, code} => format!("could not complete login from provider because the id_token could not be retrieved! (state={:?} code = {code})",state),
Action::ProviderFailedGetUserInfo {provider} => format!("could not get user information from userinfo endpoint of provider {}!", provider.id.0),
Action::ProviderEmailNotValidated {provider}=>format!("could not login using provider {} because its email was marked as not validated!", provider.id.0),
Action::ProviderMissingEmailInResponse {provider}=>format!("could not login using provider {} because the email was not provided by userinfo endpoint!", provider.id.0),
Action::ProviderAccountNotFound { provider, email } =>
format!("could not login using provider {} because the email {email} could not be associated to any account!", &provider.id.0),
Action::ProviderAccountDisabled { provider, email } =>
format!("could not login using provider {} because the account associated to the email {email} is disabled!", &provider.id.0),
Action::ProviderAccountNotAllowedToLoginWithProvider { provider, email } =>
format!("could not login using provider {} because the account associated to the email {email} is not allowed to authenticate using this provider!", &provider.id.0),
Action::ProviderLoginFailed { provider, email } =>
format!("could not login using provider {} with the email {email} for an unknown reason!", &provider.id.0),
Action::ProviderLoginSuccessful {provider, user} =>
format!("successfully authenticated using provider {} as {}", provider.id.0, user.quick_identity()),
Action::Signout => "signed out".to_string(),
Action::UserNeed2FAOnLogin(user) => {
format!(
@@ -209,9 +181,7 @@ impl Action<'_> {
format!("successfully authenticated as {login}, but this is a DISABLED ACCOUNT")
}
Action::TryLocalLoginFromUnauthorizedAccount(login) => {
format!(
"successfully locally authenticated as {login}, but this is a FORBIDDEN for this account!"
)
format!("successfully locally authenticated as {login}, but this is a FORBIDDEN for this account!")
}
Action::FailedLoginWithBadCredentials(login) => {
format!("attempted to authenticate as {login} but with a WRONG PASSWORD")
@@ -232,10 +202,7 @@ impl Action<'_> {
Action::NewOpenIDSession { client } => {
format!("opened a new OpenID session with {:?}", client.id)
}
Action::NewOpenIDSuccessfulImplicitAuth { client } => format!(
"finished an implicit flow connection for client {:?}",
client.id
),
Action::NewOpenIDSuccessfulImplicitAuth { client } => format!("finished an implicit flow connection for client {:?}", client.id),
Action::ChangedHisPassword => "changed his password".to_string(),
Action::ClearedHisLoginHistory => "cleared his login history".to_string(),
Action::AddNewFactor(factor) => format!(
@@ -260,7 +227,7 @@ impl ActionLogger {
None => "Anonymous user".to_string(),
Some(u) => u.quick_identity(),
},
self.ip,
self.ip.to_string(),
action.as_string()
)
}

View File

@@ -7,6 +7,12 @@ use std::collections::HashMap;
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Eq, PartialEq)]
pub struct ClientID(pub String);
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum AuthenticationFlow {
AuthorizationCode,
Implicit,
}
pub type AdditionalClaims = HashMap<String, Value>;
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
@@ -55,9 +61,12 @@ impl PartialEq for Client {
impl Eq for Client {}
impl Client {
/// Check if the client has a secret defined
pub fn has_secret(&self) -> bool {
self.secret.is_some()
/// Get the client authentication flow
pub fn auth_flow(&self) -> AuthenticationFlow {
match self.secret {
None => AuthenticationFlow::Implicit,
Some(_) => AuthenticationFlow::AuthorizationCode,
}
}
/// Process a single claim value

View File

@@ -1,5 +1,5 @@
use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD as BASE64_URL_SAFE_NO_PAD;
use base64::Engine as _;
use crate::utils::crypt_utils::sha256;
@@ -22,7 +22,7 @@ impl CodeChallenge {
encoded.eq(&self.code_challenge)
}
s => {
log::error!("Unknown code challenge method: {s}");
log::error!("Unknown code challenge method: {}", s);
false
}
}
@@ -40,8 +40,8 @@ mod test {
code_challenge: "text1".to_string(),
};
assert!(chal.verify_code("text1"));
assert!(!chal.verify_code("text2"));
assert_eq!(true, chal.verify_code("text1"));
assert_eq!(false, chal.verify_code("text2"));
}
#[test]
@@ -51,8 +51,8 @@ mod test {
code_challenge: "uSOvC48D8TMh6RgW-36XppMlMgys-6KAE_wEIev9W2g".to_string(),
};
assert!(chal.verify_code("HIwht3lCHfnsruA+7Sq8NP2mPj5cBZe0Ewf23eK9UQhK4TdCIt3SK7Fr/giCdnfjxYQILOPG2D562emggAa2lA=="));
assert!(!chal.verify_code("text1"));
assert_eq!(true, chal.verify_code("HIwht3lCHfnsruA+7Sq8NP2mPj5cBZe0Ewf23eK9UQhK4TdCIt3SK7Fr/giCdnfjxYQILOPG2D562emggAa2lA=="));
assert_eq!(false, chal.verify_code("text1"));
}
#[test]
@@ -62,7 +62,10 @@ mod test {
code_challenge: "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM".to_string(),
};
assert!(chal.verify_code("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"));
assert!(!chal.verify_code("text1"));
assert_eq!(
true,
chal.verify_code("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk")
);
assert_eq!(false, chal.verify_code("text1"));
}
}

View File

@@ -1,6 +1,6 @@
use crate::data::current_user::CurrentUser;
use crate::data::from_request_redirect::FromRequestRedirect;
use crate::data::login_redirect::{LoginRedirect, get_2fa_url};
use crate::data::login_redirect::{get_2fa_url, LoginRedirect};
use actix_web::dev::Payload;
use actix_web::{FromRequest, HttpRequest};
use std::future::Future;

View File

@@ -6,7 +6,7 @@ use actix::Addr;
use actix_identity::Identity;
use actix_web::dev::Payload;
use actix_web::error::ErrorInternalServerError;
use actix_web::{Error, FromRequest, HttpRequest, web};
use actix_web::{web, Error, FromRequest, HttpRequest};
use crate::actors::users_actor;
use crate::actors::users_actor::UsersActor;

View File

@@ -20,10 +20,7 @@ where
/// Open entity
pub fn open_or_create<A: AsRef<Path>>(path: A) -> Res<Self> {
if !path.as_ref().is_file() {
log::warn!(
"Entities at {:?} does not point to a file, creating a new empty entity container...",
path.as_ref()
);
log::warn!("Entities at {:?} does not point to a file, creating a new empty entity container...", path.as_ref());
return Ok(Self {
file_path: path.as_ref().to_path_buf(),
list: vec![],

View File

@@ -2,7 +2,7 @@ use crate::data::current_user::CurrentUser;
use crate::data::session_identity::SessionIdentity;
use actix_identity::Identity;
use actix_web::dev::Payload;
use actix_web::{Error, FromRequest, HttpRequest, web};
use actix_web::{web, Error, FromRequest, HttpRequest};
use std::future::Future;
use std::pin::Pin;

View File

@@ -1,12 +1,12 @@
use jwt_simple::algorithms::RSAKeyPairLike;
use jwt_simple::claims::JWTClaims;
use jwt_simple::prelude::RS256KeyPair;
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde::Serialize;
use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE as BASE64_URL_URL_SAFE;
use base64::engine::general_purpose::URL_SAFE_NO_PAD as BASE64_URL_SAFE_NO_PAD;
use base64::Engine as _;
use crate::utils::err::Res;
use crate::utils::string_utils::rand_str;

View File

@@ -26,9 +26,7 @@ impl ProviderConfiguration {
let state = urlencoding::encode(&state.state_id).to_string();
let callback_url = AppConfig::get().oidc_provider_redirect_url();
format!(
"{authorization_url}?response_type=code&scope=openid%20profile%20email&client_id={client_id}&state={state}&redirect_uri={callback_url}"
)
format!("{authorization_url}?response_type=code&scope=openid%20profile%20email&client_id={client_id}&state={state}&redirect_uri={callback_url}")
}
/// Retrieve the authorization token after a successful authentication, using an authorization code

View File

@@ -30,7 +30,7 @@ pub struct SessionIdentityData {
pub struct SessionIdentity<'a>(pub Option<&'a Identity>);
impl SessionIdentity<'_> {
impl<'a> SessionIdentity<'a> {
fn get_session_data(&self) -> Option<SessionIdentityData> {
if let Some(id) = self.0 {
Self::deserialize_session_data(id.id().ok())
@@ -46,7 +46,7 @@ impl SessionIdentity<'_> {
.map(|f| match f {
Ok(d) => Some(d),
Err(e) => {
log::warn!("Failed to deserialize session data! {e:?}");
log::warn!("Failed to deserialize session data! {:?}", e);
None
}
})
@@ -65,7 +65,7 @@ impl SessionIdentity<'_> {
log::debug!("Will set user session data.");
if let Err(e) = Identity::login(&req.extensions(), s) {
log::error!("Failed to set session data! {e}");
log::error!("Failed to set session data! {}", e);
}
log::debug!("Did set user session data.");
}

View File

@@ -1,3 +1,5 @@
use std::io::ErrorKind;
use base32::Alphabet;
use rand::Rng;
use totp_rfc6238::{HashAlgorithm, TotpGenerator};
@@ -19,7 +21,7 @@ pub struct TotpKey {
impl TotpKey {
/// Generate a new TOTP key
pub fn new_random() -> Self {
let random_bytes = rand::rng().random::<[u8; 20]>();
let random_bytes = rand::thread_rng().gen::<[u8; 20]>();
Self {
encoded: base32::encode(BASE32_ALPHABET, &random_bytes),
}
@@ -78,7 +80,7 @@ impl TotpKey {
/// Get the code at a specific time
fn get_code_at<F: Fn() -> u64>(&self, get_time: F) -> Res<String> {
let generator = TotpGenerator::new()
let gen = TotpGenerator::new()
.set_digit(NUM_DIGITS)
.unwrap()
.set_step(PERIOD)
@@ -88,14 +90,15 @@ impl TotpKey {
let key = match base32::decode(BASE32_ALPHABET, &self.encoded) {
None => {
return Err(Box::new(std::io::Error::other(
return Err(Box::new(std::io::Error::new(
ErrorKind::Other,
"Failed to decode base32 secret!",
)));
}
Some(k) => k,
};
Ok(generator.get_code_with(&key, get_time))
Ok(gen.get_code_with(&key, get_time))
}
/// Check a code's validity

View File

@@ -3,7 +3,7 @@ use std::net::IpAddr;
use crate::actors::users_actor::{AuthorizedAuthenticationSources, UsersSyncBackend};
use crate::data::entity_manager::EntityManager;
use crate::data::user::{FactorID, GeneralSettings, GrantedClients, TwoFactor, User, UserID};
use crate::utils::err::{Res, new_error};
use crate::utils::err::{new_error, Res};
use crate::utils::time::time;
impl EntityManager<User> {
@@ -18,7 +18,7 @@ impl EntityManager<User> {
};
if let Err(e) = self.replace_entries(|u| u.uid.eq(id), &update(user)) {
log::error!("Failed to update user information! {e:?}");
log::error!("Failed to update user information! {:?}", e);
return Err(e);
}
@@ -34,7 +34,7 @@ fn verify_password<P: AsRef<[u8]>>(pwd: P, hash: &str) -> bool {
match bcrypt::verify(pwd, hash) {
Ok(r) => r,
Err(e) => {
log::warn!("Failed to verify password! {e:?}");
log::warn!("Failed to verify password! {:?}", e);
false
}
}

View File

@@ -1,3 +1,4 @@
use std::io::ErrorKind;
use std::sync::Arc;
use actix_web::web;
@@ -108,11 +109,17 @@ impl WebAuthManager {
) -> Res<WebauthnPubKey> {
let state: RegisterKeyOpaqueData = self.crypto_wrapper.decrypt(opaque_state)?;
if state.user_id != user.uid {
return Err(Box::new(std::io::Error::other("Invalid user for pubkey!")));
return Err(Box::new(std::io::Error::new(
ErrorKind::Other,
"Invalid user for pubkey!",
)));
}
if state.expire < time() {
return Err(Box::new(std::io::Error::other("Challenge has expired!")));
return Err(Box::new(std::io::Error::new(
ErrorKind::Other,
"Challenge has expired!",
)));
}
let res = self.core.finish_passkey_registration(
@@ -150,11 +157,17 @@ impl WebAuthManager {
) -> Res {
let state: AuthStateOpaqueData = self.crypto_wrapper.decrypt(opaque_state)?;
if &state.user_id != user_id {
return Err(Box::new(std::io::Error::other("Invalid user for pubkey!")));
return Err(Box::new(std::io::Error::new(
ErrorKind::Other,
"Invalid user for pubkey!",
)));
}
if state.expire < time() {
return Err(Box::new(std::io::Error::other("Challenge has expired!")));
return Err(Box::new(std::io::Error::new(
ErrorKind::Other,
"Challenge has expired!",
)));
}
self.core.finish_passkey_authentication(

View File

@@ -2,14 +2,14 @@ use core::time::Duration;
use std::sync::Arc;
use actix::Actor;
use actix_identity::IdentityMiddleware;
use actix_identity::config::LogoutBehaviour;
use actix_identity::IdentityMiddleware;
use actix_remote_ip::RemoteIPConfig;
use actix_session::SessionMiddleware;
use actix_session::storage::CookieSessionStore;
use actix_session::SessionMiddleware;
use actix_web::cookie::{Key, SameSite};
use actix_web::middleware::Logger;
use actix_web::{App, HttpResponse, HttpServer, get, middleware, web};
use actix_web::{get, middleware, web, App, HttpResponse, HttpServer};
use basic_oidc::actors::bruteforce_actor::BruteForceActor;
use basic_oidc::actors::openid_sessions_actor::OpenIDSessionsActor;
@@ -51,7 +51,7 @@ async fn main() -> std::io::Result<()> {
// Create initial user if required
if users.is_empty() {
log::info!("Create default {DEFAULT_ADMIN_USERNAME} user");
log::info!("Create default {} user", DEFAULT_ADMIN_USERNAME);
let default_admin = User {
username: DEFAULT_ADMIN_USERNAME.to_string(),
authorized_clients: None,

View File

@@ -1,15 +1,15 @@
//! # Authentication middleware
use std::future::{Future, Ready, ready};
use std::future::{ready, Future, Ready};
use std::pin::Pin;
use std::rc::Rc;
use actix_identity::IdentityExt;
use actix_web::body::EitherBody;
use actix_web::http::{Method, header};
use actix_web::http::{header, Method};
use actix_web::{
dev::{forward_ready, Service, ServiceRequest, ServiceResponse, Transform},
Error, HttpResponse,
dev::{Service, ServiceRequest, ServiceResponse, Transform, forward_ready},
};
use crate::constants::{
@@ -97,7 +97,10 @@ where
.unwrap_or("bad")
.eq(&AppConfig::get().website_origin)
{
log::warn!("Blocked POST request from invalid origin! Origin given {o:?}");
log::warn!(
"Blocked POST request from invalid origin! Origin given {:?}",
o
);
return Ok(req.into_response(
HttpResponse::Unauthorized()
.body("POST request from invalid origin!")
@@ -130,8 +133,8 @@ where
_ => ConnStatus::SignedOut,
};
log::trace!("Connection data: {session_data:#?}");
log::debug!("Connection status: {session:?}");
log::trace!("Connection data: {:#?}", session_data);
log::debug!("Connection status: {:?}", session);
// Redirect user to login page
if !session.is_auth()

View File

@@ -1,9 +1,14 @@
use lazy_regex::regex_find;
use rand::distr::{Alphanumeric, SampleString};
use rand::distributions::Alphanumeric;
use rand::Rng;
/// Generate a random string of a given size
pub fn rand_str(len: usize) -> String {
Alphanumeric.sample_string(&mut rand::rng(), len)
rand::thread_rng()
.sample_iter(&Alphanumeric)
.map(char::from)
.take(len)
.collect()
}
/// Parse environment variables
@@ -44,10 +49,8 @@ mod test {
const VAR_ONE: &str = "VAR_ONE";
#[test]
fn test_apply_env_var() {
unsafe {
env::set_var(VAR_ONE, "good");
}
let src = format!("This is ${{{VAR_ONE}}}");
env::set_var(VAR_ONE, "good");
let src = format!("This is ${{{}}}", VAR_ONE);
assert_eq!("This is good", apply_env_vars(&src));
}
@@ -55,7 +58,7 @@ mod test {
#[test]
fn test_invalid_var_syntax() {
let src = format!("This is ${{{VAR_INVALID}}}");
let src = format!("This is ${{{}}}", VAR_INVALID);
assert_eq!(src, apply_env_vars(&src));
}