Compare commits

6 Commits

Author SHA1 Message Date
6d341069a0 Fix appearance issue in clients list screen with long client ids
All checks were successful
continuous-integration/drone/push Build is passing
2025-10-29 12:34:47 +01:00
d4de81f1fb Can disable local login
All checks were successful
continuous-integration/drone/push Build is passing
2025-10-29 12:20:05 +01:00
9a599fdde2 Can create accounts automatically for a given upstream provider
All checks were successful
continuous-integration/drone/push Build is passing
2025-10-29 11:30:45 +01:00
764ad3d5a1 Add sample upstream provider 2025-10-29 09:34:10 +01:00
ffd93c5435 Can customize login background image
All checks were successful
continuous-integration/drone/push Build is passing
2025-10-28 18:05:35 +01:00
2a729d4153 Can log actions in JSON format
All checks were successful
continuous-integration/drone/push Build is passing
2025-10-28 11:43:23 +01:00
28 changed files with 578 additions and 171 deletions

2
.gitignore vendored
View File

@@ -1,3 +1,3 @@
/target
.idea
storage
/storage

View File

@@ -67,10 +67,11 @@ You can add as much upstream provider as you want, using the following syntax in
```yaml
- id: gitlab
name: GitLab
logo: gitlab # Can be either gitea, gitlab, github, microsoft, google or a full URL
logo: gitlab # Can be either openid, gitea, gitlab, github, microsoft, google or a full URL
client_id: CLIENT_ID_GIVEN_BY_PROVIDER
client_secret: CLIENT_SECRET_GIVEN_BY_PROVIDER
configuration_url: https://gitlab.com/.well-known/openid-configuration
allow_auto_account_creation: true
```
@@ -108,5 +109,20 @@ Corresponding client configuration:
OAuth proxy can then be access on this URL: http://192.168.2.103:4180/
## Testing with upstream identity provider
The folder [sample_upstream_provider](sample_upstream_provider) contains a working scenario of authentication with an upstream provider.
Run the following command to run the scenario:
```bash
cd sample_upstream_provider
docker compose up
```
- Upstream provider (not to be directly used): http://localhost:9001
- BasicOIDC: http://localhost:8000
- Client 2: http://localhost:8012
- Client 1: http://localhost:8011
## Contributing
If you wish to contribute to this software, feel free to send an email to contact@communiquons.org to get an account on my system, managed by BasicOIDC :)

View File

@@ -14,7 +14,6 @@ body {
/* background */
@media screen and (min-width: 767px) {
.bg-login {
background-image: url(/assets/img/forest.jpg);
width: 100%;
height: 100%;
position: fixed;

View File

@@ -20,4 +20,8 @@ body {
.form-control::placeholder {
color: #555;
}
.table-break-works td {
word-break: break-all;
}

View File

@@ -0,0 +1 @@
<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>OpenID</title><path d="M14.54.889l-3.63 1.773v18.17c-4.15-.52-7.27-2.78-7.27-5.5 0-2.58 2.8-4.75 6.63-5.41v-2.31C4.42 8.322 0 11.502 0 15.332c0 3.96 4.74 7.24 10.91 7.78l3.63-1.71V.888m.64 6.724v2.31c1.43.25 2.71.7 3.76 1.31l-1.97 1.11 7.03 1.53-.5-5.21-1.87 1.06c-1.74-1.06-3.96-1.81-6.45-2.11z"/></svg>

After

Width:  |  Height:  |  Size: 382 B

View File

@@ -0,0 +1,26 @@
issuer: http://127.0.0.1:9001/dex
storage:
type: memory
web:
http: 0.0.0.0:9001
oauth2:
# Automate some clicking
# Note: this might actually make some tests pass that otherwise wouldn't.
skipApprovalScreen: false
connectors:
# Note: this might actually make some tests pass that otherwise wouldn't.
- type: mockCallback
id: mock
name: Example
# Basic OP test suite requires two clients.
staticClients:
- id: foo
secret: bar
redirectURIs:
- http://localhost:8000/prov_cb
name: Auth

View File

@@ -0,0 +1,47 @@
services:
upstream:
image: dexidp/dex
user: "1000"
network_mode: host
volumes:
- ./dex-provider:/conf:ro
command: [ "dex", "serve", "/conf/dex.config.yaml" ]
client1:
image: pierre42100/oidc_test_client
user: "1000"
network_mode: host
environment:
- LISTEN_ADDR=0.0.0.0:8011
- PUBLIC_URL=http://127.0.0.1:8011
- CONFIGURATION_URL=http://localhost:8000/.well-known/openid-configuration
- CLIENT_ID=testclient1
- CLIENT_SECRET=secretone
client2:
image: pierre42100/oidc_test_client
user: "1000"
network_mode: host
environment:
- LISTEN_ADDR=0.0.0.0:8012
- PUBLIC_URL=http://127.0.0.1:8012
- CONFIGURATION_URL=http://localhost:8000/.well-known/openid-configuration
- CLIENT_ID=testclient2
- CLIENT_SECRET=secrettwo
basicoidc:
image: rust
user: "1000"
network_mode: host
environment:
- STORAGE_PATH=/storage
- DISABLE_LOCAL_LOGIN=true
#- RUST_LOG=debug
volumes:
- ../:/app
- ./storage:/storage
- ~/.cargo/registry:/usr/local/cargo/registry
command:
- bash
- -c
- cd /app && cargo run

View File

@@ -0,0 +1 @@
users.json

View File

@@ -0,0 +1,11 @@
- id: testclient1
name: Client 1
description: client1
secret: secretone
redirect_uri: http://127.0.0.1:8011/
granted_to_all_users: true
- id: testclient2
name: Client 2
description: client2
secret: secrettwo
redirect_uri: http://127.0.0.1:8012/

View File

@@ -0,0 +1,7 @@
- id: upstream
name: Upstream
logo: openid
client_id: foo
client_secret: bar
configuration_url: http://127.0.0.1:9001/dex/.well-known/openid-configuration
allow_auto_account_creation: true

View File

@@ -17,7 +17,7 @@ use crate::data::provider::ProviderID;
use crate::utils::string_utils::rand_str;
use crate::utils::time::time;
#[derive(Debug, Clone)]
#[derive(Debug, Clone, serde::Serialize)]
pub struct ProviderLoginState {
pub provider_id: ProviderID,
pub state_id: String,

View File

@@ -1,10 +1,11 @@
use std::net::IpAddr;
use crate::data::provider::{Provider, ProviderID};
use actix::{Actor, Context, Handler, Message, MessageResult};
use crate::data::user::{FactorID, GeneralSettings, GrantedClients, TwoFactor, User, UserID};
use crate::utils::err::Res;
use crate::utils::string_utils::is_acceptable_login;
use actix::{Actor, Context, Handler, Message, MessageResult};
use light_openid::primitives::OpenIDUserInfo;
/// User storage interface
pub trait UsersSyncBackend {
@@ -38,6 +39,8 @@ pub enum LoginResult {
LocalAuthForbidden,
AuthFromProviderForbidden,
Success(Box<User>),
AccountAutoCreated(Box<User>),
CannotAutoCreateAccount(String),
}
#[derive(Message)]
@@ -51,6 +54,7 @@ pub struct LocalLoginRequest {
#[rtype(LoginResult)]
pub struct ProviderLoginRequest {
pub email: String,
pub user_info: OpenIDUserInfo,
pub provider: Provider,
}
@@ -104,7 +108,7 @@ pub struct AddSuccessful2FALogin(pub UserID, pub IpAddr);
#[rtype(result = "bool")]
pub struct Clear2FALoginHistory(pub UserID);
#[derive(Eq, PartialEq, Debug, Clone)]
#[derive(Eq, PartialEq, Debug, Clone, serde::Serialize)]
pub struct AuthorizedAuthenticationSources {
pub local: bool,
pub upstream: Vec<ProviderID>,
@@ -187,7 +191,86 @@ impl Handler<ProviderLoginRequest> for UsersActor {
log::error!("Failed to find user! {e}");
MessageResult(LoginResult::Error)
}
Ok(None) => MessageResult(LoginResult::AccountNotFound),
Ok(None) => {
// Check if automatic account creation is enabled for this provider
if !msg.provider.allow_auto_account_creation {
return MessageResult(LoginResult::AccountNotFound);
}
// Extract username for account creation
let mut username = msg
.user_info
.preferred_username
.unwrap_or(msg.email.to_string());
// Determine username from email, if necessary
if !is_acceptable_login(&username)
|| matches!(
self.manager.find_by_username_or_email(&username),
Ok(Some(_))
)
{
username = msg.email.clone();
}
// Check if username is already taken
if matches!(
self.manager.find_by_username_or_email(&username),
Ok(Some(_))
) {
return MessageResult(LoginResult::CannotAutoCreateAccount(format!(
"username {username} is already taken!"
)));
}
if !is_acceptable_login(&username) {
return MessageResult(LoginResult::CannotAutoCreateAccount(
"could not determine acceptable login for user!".to_string(),
));
}
// Automatic account creation
let user_id = match self.manager.create_user_account(GeneralSettings {
uid: UserID::random(),
username,
first_name: msg.user_info.given_name.unwrap_or_default(),
last_name: msg.user_info.family_name.unwrap_or_default(),
email: msg.email.to_string(),
enabled: true,
two_factor_exemption_after_successful_login: false,
is_admin: false,
}) {
Ok(u) => u,
Err(e) => {
log::error!("Failed to create user account! {e}");
return MessageResult(LoginResult::CannotAutoCreateAccount(
"missing some user information".to_string(),
));
}
};
// Mark the provider as the only authorized source
if let Err(e) = self.manager.set_authorized_authentication_sources(
&user_id,
AuthorizedAuthenticationSources {
local: false,
upstream: vec![msg.provider.id],
},
) {
log::error!(
"Failed to set authorized authentication sources for newly created account! {e}"
);
}
// Extract user information to return them
let Ok(Some(user)) = self.manager.find_by_user_id(&user_id) else {
return MessageResult(LoginResult::CannotAutoCreateAccount(
"failed to get created user information".to_string(),
));
};
MessageResult(LoginResult::AccountAutoCreated(Box::new(user)))
}
Ok(Some(user)) => {
if !user.can_login_from_provider(&msg.provider) {
return MessageResult(LoginResult::AuthFromProviderForbidden);

View File

@@ -65,7 +65,9 @@ pub async fn delete_user(
let res = users.send(DeleteUserRequest(req.0.user_id)).await.unwrap();
if res {
action_logger.log(Action::AdminDeleteUser(&user));
action_logger.log(Action::AdminDeleteUser {
user: user.loggable(),
});
HttpResponse::Ok().finish()
} else {
HttpResponse::InternalServerError().finish()

View File

@@ -165,7 +165,10 @@ pub async fn users_route(
let factors_to_keep = update.0.two_factor.split(';').collect::<Vec<_>>();
for factor in &edited_user.two_factor {
if !factors_to_keep.contains(&factor.id.0.as_str()) {
logger.log(Action::AdminRemoveUserFactor(&edited_user, factor));
logger.log(Action::AdminRemoveUserFactor {
user: edited_user.loggable(),
factor: factor.loggable(),
});
users
.send(users_actor::Remove2FAFactor(
edited_user.uid.clone(),
@@ -186,10 +189,10 @@ pub async fn users_route(
};
if edited_user.authorized_authentication_sources() != auth_sources {
logger.log(Action::AdminSetAuthorizedAuthenticationSources(
&edited_user,
&auth_sources,
));
logger.log(Action::AdminSetAuthorizedAuthenticationSources {
user: edited_user.loggable(),
sources: &auth_sources,
});
users
.send(users_actor::SetAuthorizedAuthenticationSources(
edited_user.uid.clone(),
@@ -216,10 +219,10 @@ pub async fn users_route(
};
if edited_user.granted_clients() != granted_clients {
logger.log(Action::AdminSetNewGrantedClientsList(
&edited_user,
&granted_clients,
));
logger.log(Action::AdminSetNewGrantedClientsList {
user: edited_user.loggable(),
clients: &granted_clients,
});
users
.send(users_actor::SetGrantedClients(
edited_user.uid.clone(),
@@ -231,7 +234,9 @@ pub async fn users_route(
// Clear user 2FA history if requested
if update.0.clear_2fa_history.is_some() {
logger.log(Action::AdminClear2FAHistory(&edited_user));
logger.log(Action::AdminClear2FAHistory {
user: edited_user.loggable(),
});
users
.send(users_actor::Clear2FALoginHistory(edited_user.uid.clone()))
.await
@@ -242,7 +247,9 @@ pub async fn users_route(
let new_password = match update.0.gen_new_password.is_some() {
false => None,
true => {
logger.log(Action::AdminResetUserPassword(&edited_user));
logger.log(Action::AdminResetUserPassword {
user: edited_user.loggable(),
});
let temp_pass = rand_str(TEMPORARY_PASSWORDS_LEN);
users
@@ -269,11 +276,15 @@ pub async fn users_route(
} else {
success = Some(match is_creating {
true => {
logger.log(Action::AdminCreateUser(&edited_user));
logger.log(Action::AdminCreateUser {
user: edited_user.loggable(),
});
format!("User {} was successfully created!", edited_user.full_name())
}
false => {
logger.log(Action::AdminUpdateUser(&edited_user));
logger.log(Action::AdminUpdateUser {
user: edited_user.loggable(),
});
format!("User {} was successfully updated!", edited_user.full_name())
}
});

View File

@@ -13,6 +13,7 @@ use crate::controllers::base_controller::{
build_fatal_error_page, redirect_user, redirect_user_for_login,
};
use crate::data::action_logger::{Action, ActionLogger};
use crate::data::app_config::AppConfig;
use crate::data::force_2fa_auth::Force2FAAuth;
use crate::data::login_redirect::{LoginRedirect, get_2fa_url};
use crate::data::provider::{Provider, ProvidersManager};
@@ -21,46 +22,61 @@ use crate::data::user::User;
use crate::data::webauthn_manager::WebAuthManagerReq;
use crate::utils::string_utils;
pub struct BaseLoginPage<'a> {
pub struct BaseLoginPage {
pub danger: Option<String>,
pub success: Option<String>,
pub background_image: &'static str,
pub page_title: &'static str,
pub app_name: &'static str,
pub redirect_uri: &'a LoginRedirect,
pub redirect_uri: LoginRedirect,
}
impl Default for BaseLoginPage {
fn default() -> Self {
Self {
page_title: "Login",
danger: None,
success: None,
background_image: &AppConfig::get().login_background_image,
app_name: APP_NAME,
redirect_uri: LoginRedirect::default(),
}
}
}
#[derive(Template)]
#[template(path = "login/login.html")]
struct LoginTemplate<'a> {
p: BaseLoginPage<'a>,
struct LoginTemplate {
p: BaseLoginPage,
login: String,
show_local_login: bool,
providers: Vec<Provider>,
}
#[derive(Template)]
#[template(path = "login/password_reset.html")]
struct PasswordResetTemplate<'a> {
p: BaseLoginPage<'a>,
struct PasswordResetTemplate {
p: BaseLoginPage,
min_pass_len: usize,
}
#[derive(Template)]
#[template(path = "login/choose_second_factor.html")]
struct ChooseSecondFactorTemplate<'a> {
p: BaseLoginPage<'a>,
p: BaseLoginPage,
user: &'a User,
}
#[derive(Template)]
#[template(path = "login/otp_input.html")]
struct LoginWithOTPTemplate<'a> {
p: BaseLoginPage<'a>,
struct LoginWithOTPTemplate {
p: BaseLoginPage,
}
#[derive(Template)]
#[template(path = "login/webauthn_input.html")]
struct LoginWithWebauthnTemplate<'a> {
p: BaseLoginPage<'a>,
struct LoginWithWebauthnTemplate {
p: BaseLoginPage,
opaque_state: String,
challenge_json: String,
}
@@ -111,7 +127,7 @@ pub async fn login_route(
// Check if user session must be closed
if let Some(true) = query.logout {
if let Some(id) = id {
logger.log(Action::Signout);
logger.log(Action::SignOut);
id.logout();
}
success = Some("Goodbye!".to_string());
@@ -141,8 +157,10 @@ pub async fn login_route(
"Given login could not be processed, because it has an invalid format!".to_string(),
);
}
// Try to authenticate user
else if let Some(req) = &req {
// Try to authenticate user (local login)
else if let Some(req) = &req
&& !AppConfig::get().disable_local_login
{
login.clone_from(&req.login);
let response: LoginResult = users
.send(users_actor::LocalLoginRequest {
@@ -155,14 +173,20 @@ pub async fn login_route(
match response {
LoginResult::Success(user) => {
let status = if user.need_reset_password {
logger.log(Action::UserNeedNewPasswordOnLogin(&user));
logger.log(Action::UserNeedNewPasswordOnLogin {
user: user.loggable(),
});
SessionStatus::NeedNewPassword
} else if user.has_two_factor() && !user.can_bypass_two_factors_for_ip(remote_ip.0)
{
logger.log(Action::UserNeed2FAOnLogin(&user));
logger.log(Action::UserNeed2FAOnLogin {
user: user.loggable(),
});
SessionStatus::Need2FA
} else {
logger.log(Action::UserSuccessfullyAuthenticated(&user));
logger.log(Action::UserSuccessfullyAuthenticated {
user: user.loggable(),
});
SessionStatus::SignedIn
};
@@ -172,7 +196,7 @@ pub async fn login_route(
LoginResult::AccountDisabled => {
log::warn!("Failed login for username {} : account is disabled", &login);
logger.log(Action::TryLoginWithDisabledAccount(&login));
logger.log(Action::TryLoginWithDisabledAccount { login: &login });
danger = Some("Your account is disabled!".to_string());
}
@@ -181,7 +205,7 @@ pub async fn login_route(
"Failed login for username {} : attempted to use local auth, but it is forbidden",
&login
);
logger.log(Action::TryLocalLoginFromUnauthorizedAccount(&login));
logger.log(Action::TryLocalLoginFromUnauthorizedAccount { login: &login });
danger = Some("You cannot login from local auth with your account!".to_string());
}
@@ -191,7 +215,7 @@ pub async fn login_route(
c => {
log::warn!("Failed login for ip {remote_ip:?} / username {login}: {c:?}");
logger.log(Action::FailedLoginWithBadCredentials(&login));
logger.log(Action::FailedLoginWithBadCredentials { login: &login });
danger = Some("Login failed.".to_string());
bruteforce
@@ -203,6 +227,10 @@ pub async fn login_route(
}
}
}
// If there is only a single provider, trigger auto-login
else if AppConfig::get().disable_local_login && providers.len() == 1 {
return redirect_user(&providers.cloned()[0].login_url(&query.redirect));
}
HttpResponse::Ok().content_type("text/html").body(
LoginTemplate {
@@ -210,10 +238,11 @@ pub async fn login_route(
page_title: "Login",
danger,
success,
app_name: APP_NAME,
redirect_uri: &query.redirect,
redirect_uri: query.0.redirect,
..Default::default()
},
login,
show_local_login: !AppConfig::get().disable_local_login,
providers: providers.cloned(),
}
.render()
@@ -272,7 +301,7 @@ pub async fn reset_password_route(
danger = Some("Failed to change password!".to_string());
} else {
SessionIdentity(id.as_ref()).set_status(&http_req, SessionStatus::SignedIn);
logger.log(Action::UserChangedPasswordOnLogin(&user_id));
logger.log(Action::UserChangedPasswordOnLogin { user_id: &user_id });
return redirect_user(query.redirect.get());
}
}
@@ -283,9 +312,8 @@ pub async fn reset_password_route(
p: BaseLoginPage {
page_title: "Password reset",
danger,
success: None,
app_name: APP_NAME,
redirect_uri: &query.redirect,
redirect_uri: query.0.redirect,
..Default::default()
},
min_pass_len: MIN_PASS_LEN,
}
@@ -333,10 +361,8 @@ pub async fn choose_2fa_method(
ChooseSecondFactorTemplate {
p: BaseLoginPage {
page_title: "Two factor authentication",
danger: None,
success: None,
app_name: APP_NAME,
redirect_uri: &query.redirect,
redirect_uri: query.0.redirect,
..Default::default()
},
user: &user,
}
@@ -395,7 +421,7 @@ pub async fn login_with_otp(
{
logger.log(Action::OTPLoginAttempt {
success: false,
user: &user,
user: user.loggable(),
});
danger = Some("Specified code is invalid!".to_string());
} else {
@@ -412,7 +438,7 @@ pub async fn login_with_otp(
session.set_status(&http_req, SessionStatus::SignedIn);
logger.log(Action::OTPLoginAttempt {
success: true,
user: &user,
user: user.loggable(),
});
return redirect_user(query.redirect.get());
}
@@ -424,8 +450,8 @@ pub async fn login_with_otp(
danger,
success: None,
page_title: "Two-Factor Auth",
app_name: APP_NAME,
redirect_uri: &query.redirect,
redirect_uri: query.0.redirect,
..Default::default()
},
}
.render()
@@ -487,11 +513,9 @@ pub async fn login_with_webauthn(
HttpResponse::Ok().body(
LoginWithWebauthnTemplate {
p: BaseLoginPage {
danger: None,
success: None,
page_title: "Two-Factor Auth",
app_name: APP_NAME,
redirect_uri: &query.redirect,
redirect_uri: query.0.redirect,
..Default::default()
},
opaque_state: challenge.opaque_state,
challenge_json: urlencoding::encode(&challenge_json).to_string(),

View File

@@ -239,7 +239,7 @@ pub async fn authorize(
.unwrap();
log::trace!("New OpenID session: {session:#?}");
logger.log(Action::NewOpenIDSession { client: &client });
logger.log(Action::NewOpenIDSession { client: &client.id });
Ok(HttpResponse::Found()
.append_header((
@@ -273,7 +273,7 @@ pub async fn authorize(
};
log::trace!("New OpenID id token: {:#?}", &id_token);
logger.log(Action::NewOpenIDSuccessfulImplicitAuth { client: &client });
logger.log(Action::NewOpenIDSuccessfulImplicitAuth { client: &client.id });
Ok(HttpResponse::Found()
.append_header((

View File

@@ -1,16 +1,10 @@
use std::sync::Arc;
use actix::Addr;
use actix_identity::Identity;
use actix_remote_ip::RemoteIP;
use actix_web::{HttpRequest, HttpResponse, Responder, web};
use askama::Template;
use crate::actors::bruteforce_actor::BruteForceActor;
use crate::actors::providers_states_actor::{ProviderLoginState, ProvidersStatesActor};
use crate::actors::users_actor::{LoginResult, UsersActor};
use crate::actors::{bruteforce_actor, providers_states_actor, users_actor};
use crate::constants::{APP_NAME, MAX_FAILED_LOGIN_ATTEMPTS};
use crate::constants::MAX_FAILED_LOGIN_ATTEMPTS;
use crate::controllers::base_controller::{build_fatal_error_page, redirect_user};
use crate::controllers::login_controller::BaseLoginPage;
use crate::data::action_logger::{Action, ActionLogger};
@@ -18,11 +12,16 @@ use crate::data::login_redirect::LoginRedirect;
use crate::data::provider::{ProviderID, ProvidersManager};
use crate::data::provider_configuration::ProviderConfigurationHelper;
use crate::data::session_identity::{SessionIdentity, SessionStatus};
use actix::Addr;
use actix_identity::Identity;
use actix_remote_ip::RemoteIP;
use actix_web::{HttpRequest, HttpResponse, Responder, web};
use askama::Template;
#[derive(askama::Template)]
#[template(path = "login/prov_login_error.html")]
struct ProviderLoginError<'a> {
p: BaseLoginPage<'a>,
p: BaseLoginPage,
message: &'a str,
}
@@ -30,11 +29,9 @@ impl<'a> ProviderLoginError<'a> {
pub fn get(message: &'a str, redirect_uri: &'a LoginRedirect) -> HttpResponse {
let body = Self {
p: BaseLoginPage {
danger: None,
success: None,
page_title: "Upstream login",
app_name: APP_NAME,
redirect_uri,
redirect_uri: redirect_uri.clone(),
..Default::default()
},
message,
}
@@ -275,7 +272,7 @@ pub async fn finish_login(
}
// Check if email was provided by the userinfo endpoint
let email = match user_info.email {
let email = match &user_info.email {
Some(e) => e,
None => {
logger.log(Action::ProviderMissingEmailInResponse {
@@ -295,6 +292,7 @@ pub async fn finish_login(
let result: LoginResult = users
.send(users_actor::ProviderLoginRequest {
email: email.clone(),
user_info: user_info.clone(),
provider: provider.clone(),
})
.await
@@ -302,6 +300,13 @@ pub async fn finish_login(
let user = match result {
LoginResult::Success(u) => u,
LoginResult::AccountAutoCreated(u) => {
logger.log(Action::ProviderAccountAutoCreated {
provider: &provider,
user: u.loggable(),
});
u
}
LoginResult::AccountNotFound => {
logger.log(Action::ProviderAccountNotFound {
provider: &provider,
@@ -357,14 +362,18 @@ pub async fn finish_login(
logger.log(Action::ProviderLoginSuccessful {
provider: &provider,
user: &user,
user: user.loggable(),
});
let status = if user.has_two_factor() && !user.can_bypass_two_factors_for_ip(remote_ip.0) {
logger.log(Action::UserNeed2FAOnLogin(&user));
logger.log(Action::UserNeed2FAOnLogin {
user: user.loggable(),
});
SessionStatus::Need2FA
} else {
logger.log(Action::UserSuccessfullyAuthenticated(&user));
logger.log(Action::UserSuccessfullyAuthenticated {
user: user.loggable(),
});
SessionStatus::SignedIn
};

View File

@@ -18,6 +18,7 @@ pub(crate) struct BaseSettingsPage<'a> {
pub success_message: Option<String>,
pub page_title: &'static str,
pub app_name: &'static str,
pub local_login_enabled: bool,
pub user: &'a User,
pub version: &'static str,
pub ip_location_api: Option<&'static str>,
@@ -37,6 +38,7 @@ impl<'a> BaseSettingsPage<'a> {
app_name: APP_NAME,
user,
version: env!("CARGO_PKG_VERSION"),
local_login_enabled: !AppConfig::get().disable_local_login,
ip_location_api: AppConfig::get().ip_location_service.as_deref(),
}
}

View File

@@ -1,6 +1,5 @@
use actix::Addr;
use actix_web::{HttpResponse, Responder, web};
use uuid::Uuid;
use webauthn_rs::prelude::RegisterPublicKeyCredential;
use crate::actors::users_actor;
@@ -53,11 +52,13 @@ pub async fn save_totp_factor(
}
let factor = TwoFactor {
id: FactorID(Uuid::new_v4().to_string()),
id: FactorID::random(),
name: factor_name,
kind: TwoFactorType::TOTP(key),
};
logger.log(Action::AddNewFactor(&factor));
logger.log(Action::AddNewFactor {
factor: factor.loggable(),
});
let res = users
.send(users_actor::Add2FAFactor(user.uid.clone(), factor))
@@ -100,11 +101,13 @@ pub async fn save_webauthn_factor(
};
let factor = TwoFactor {
id: FactorID(Uuid::new_v4().to_string()),
id: FactorID::random(),
name: factor_name,
kind: TwoFactorType::WEBAUTHN(Box::new(key)),
};
logger.log(Action::AddNewFactor(&factor));
logger.log(Action::AddNewFactor {
factor: factor.loggable(),
});
let res = users
.send(users_actor::Add2FAFactor(user.uid.clone(), factor))

View File

@@ -11,21 +11,113 @@ use actix_web::{Error, FromRequest, HttpRequest, web};
use crate::actors::providers_states_actor::ProviderLoginState;
use crate::actors::users_actor;
use crate::actors::users_actor::{AuthorizedAuthenticationSources, UsersActor};
use crate::data::client::Client;
use crate::data::app_config::{ActionLoggerFormat, AppConfig};
use crate::data::client::ClientID;
use crate::data::provider::{Provider, ProviderID};
use crate::data::session_identity::SessionIdentity;
use crate::data::user::{FactorID, GrantedClients, TwoFactor, User, UserID};
use crate::data::user::{FactorID, GrantedClients, TwoFactor, TwoFactorType, User, UserID};
use crate::utils::time::time;
#[derive(serde::Serialize)]
pub struct LoggableUser {
pub uid: UserID,
pub username: String,
pub email: String,
pub admin: bool,
}
impl LoggableUser {
pub fn quick_identity(&self) -> String {
format!(
"{} {} {} ({:?})",
match self.admin {
true => "admin",
false => "user",
},
self.username,
self.email,
self.uid
)
}
}
impl User {
pub fn loggable(&self) -> LoggableUser {
LoggableUser {
uid: self.uid.clone(),
username: self.username.clone(),
email: self.email.clone(),
admin: self.admin,
}
}
}
#[derive(Debug, serde::Serialize)]
pub enum LoggableFactorType {
TOTP,
WEBAUTHN,
}
#[derive(serde::Serialize)]
pub struct LoggableFactor {
pub id: FactorID,
pub name: String,
pub kind: LoggableFactorType,
}
impl LoggableFactor {
pub fn quick_description(&self) -> String {
format!(
"#{} of type {:?} and name '{}'",
self.id.0, self.kind, self.name
)
}
}
impl TwoFactor {
pub fn loggable(&self) -> LoggableFactor {
LoggableFactor {
id: self.id.clone(),
name: self.name.to_string(),
kind: match self.kind {
TwoFactorType::TOTP(_) => LoggableFactorType::TOTP,
TwoFactorType::WEBAUTHN(_) => LoggableFactorType::WEBAUTHN,
},
}
}
}
#[derive(serde::Serialize)]
#[serde(tag = "type")]
pub enum Action<'a> {
AdminCreateUser(&'a User),
AdminUpdateUser(&'a User),
AdminDeleteUser(&'a User),
AdminResetUserPassword(&'a User),
AdminRemoveUserFactor(&'a User, &'a TwoFactor),
AdminSetAuthorizedAuthenticationSources(&'a User, &'a AuthorizedAuthenticationSources),
AdminSetNewGrantedClientsList(&'a User, &'a GrantedClients),
AdminClear2FAHistory(&'a User),
AdminCreateUser {
user: LoggableUser,
},
AdminUpdateUser {
user: LoggableUser,
},
AdminDeleteUser {
user: LoggableUser,
},
AdminResetUserPassword {
user: LoggableUser,
},
AdminRemoveUserFactor {
user: LoggableUser,
factor: LoggableFactor,
},
AdminSetAuthorizedAuthenticationSources {
user: LoggableUser,
sources: &'a AuthorizedAuthenticationSources,
},
AdminSetNewGrantedClientsList {
user: LoggableUser,
clients: &'a GrantedClients,
},
AdminClear2FAHistory {
user: LoggableUser,
},
LoginWebauthnAttempt {
success: bool,
user_id: UserID,
@@ -58,6 +150,10 @@ pub enum Action<'a> {
provider: &'a Provider,
email: &'a str,
},
ProviderAccountAutoCreated {
provider: &'a Provider,
user: LoggableUser,
},
ProviderAccountDisabled {
provider: &'a Provider,
email: &'a str,
@@ -73,29 +169,45 @@ pub enum Action<'a> {
},
ProviderLoginSuccessful {
provider: &'a Provider,
user: &'a User,
user: LoggableUser,
},
SignOut,
UserNeed2FAOnLogin {
user: LoggableUser,
},
UserSuccessfullyAuthenticated {
user: LoggableUser,
},
UserNeedNewPasswordOnLogin {
user: LoggableUser,
},
TryLoginWithDisabledAccount {
login: &'a str,
},
TryLocalLoginFromUnauthorizedAccount {
login: &'a str,
},
FailedLoginWithBadCredentials {
login: &'a str,
},
UserChangedPasswordOnLogin {
user_id: &'a UserID,
},
Signout,
UserNeed2FAOnLogin(&'a User),
UserSuccessfullyAuthenticated(&'a User),
UserNeedNewPasswordOnLogin(&'a User),
TryLoginWithDisabledAccount(&'a str),
TryLocalLoginFromUnauthorizedAccount(&'a str),
FailedLoginWithBadCredentials(&'a str),
UserChangedPasswordOnLogin(&'a UserID),
OTPLoginAttempt {
user: &'a User,
user: LoggableUser,
success: bool,
},
NewOpenIDSession {
client: &'a Client,
client: &'a ClientID,
},
NewOpenIDSuccessfulImplicitAuth {
client: &'a Client,
client: &'a ClientID,
},
ChangedHisPassword,
ClearedHisLoginHistory,
AddNewFactor(&'a TwoFactor),
AddNewFactor {
factor: LoggableFactor,
},
Removed2FAFactor {
factor_id: &'a FactorID,
},
@@ -104,35 +216,35 @@ pub enum Action<'a> {
impl Action<'_> {
pub fn as_string(&self) -> String {
match self {
Action::AdminDeleteUser(user) => {
Action::AdminDeleteUser { user } => {
format!("deleted account of {}", user.quick_identity())
}
Action::AdminCreateUser(user) => {
Action::AdminCreateUser { user } => {
format!("created account of {}", user.quick_identity())
}
Action::AdminUpdateUser(user) => {
Action::AdminUpdateUser { user } => {
format!("updated account of {}", user.quick_identity())
}
Action::AdminResetUserPassword(user) => {
Action::AdminResetUserPassword { user } => {
format!(
"set a temporary password for the account of {}",
user.quick_identity()
)
}
Action::AdminRemoveUserFactor(user, factor) => format!(
Action::AdminRemoveUserFactor { user, factor } => format!(
"removed 2 factor ({}) of user ({})",
factor.quick_description(),
user.quick_identity()
),
Action::AdminClear2FAHistory(user) => {
Action::AdminClear2FAHistory { user } => {
format!("cleared 2FA history of {}", user.quick_identity())
}
Action::AdminSetAuthorizedAuthenticationSources(user, sources) => format!(
Action::AdminSetAuthorizedAuthenticationSources { user, sources } => format!(
"update authorized authentication sources ({:?}) for user ({})",
sources,
user.quick_identity()
),
Action::AdminSetNewGrantedClientsList(user, clients) => format!(
Action::AdminSetNewGrantedClientsList { user, clients } => format!(
"set new granted clients list ({:?}) for user ({})",
clients,
user.quick_identity()
@@ -174,6 +286,11 @@ impl Action<'_> {
"could not login using provider {} because the email {email} could not be associated to any account!",
&provider.id.0
),
Action::ProviderAccountAutoCreated { provider, user } => format!(
"triggered automatic account creation for {} from provider {} because it was not found in local accounts list!",
user.quick_identity(),
&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
@@ -191,32 +308,32 @@ impl Action<'_> {
provider.id.0,
user.quick_identity()
),
Action::Signout => "signed out".to_string(),
Action::UserNeed2FAOnLogin(user) => {
Action::SignOut => "signed out".to_string(),
Action::UserNeed2FAOnLogin { user } => {
format!(
"successfully authenticated as user {:?} but need to do 2FA authentication",
user.quick_identity()
)
}
Action::UserSuccessfullyAuthenticated(user) => {
Action::UserSuccessfullyAuthenticated { user } => {
format!("successfully authenticated as {}", user.quick_identity())
}
Action::UserNeedNewPasswordOnLogin(user) => format!(
Action::UserNeedNewPasswordOnLogin { user } => format!(
"successfully authenticated as {}, but need to set a new password",
user.quick_identity()
),
Action::TryLoginWithDisabledAccount(login) => {
Action::TryLoginWithDisabledAccount { login } => {
format!("successfully authenticated as {login}, but this is a DISABLED ACCOUNT")
}
Action::TryLocalLoginFromUnauthorizedAccount(login) => {
Action::TryLocalLoginFromUnauthorizedAccount { login } => {
format!(
"successfully locally authenticated as {login}, but this is a FORBIDDEN for this account!"
)
}
Action::FailedLoginWithBadCredentials(login) => {
Action::FailedLoginWithBadCredentials { login } => {
format!("attempted to authenticate as {login} but with a WRONG PASSWORD")
}
Action::UserChangedPasswordOnLogin(user_id) => {
Action::UserChangedPasswordOnLogin { user_id } => {
format!("set a new password at login as user {user_id:?}")
}
Action::OTPLoginAttempt { user, success } => match success {
@@ -230,15 +347,15 @@ impl Action<'_> {
),
},
Action::NewOpenIDSession { client } => {
format!("opened a new OpenID session with {:?}", client.id)
format!("opened a new OpenID session with {:?}", client)
}
Action::NewOpenIDSuccessfulImplicitAuth { client } => format!(
"finished an implicit flow connection for client {:?}",
client.id
client
),
Action::ChangedHisPassword => "changed his password".to_string(),
Action::ClearedHisLoginHistory => "cleared his login history".to_string(),
Action::AddNewFactor(factor) => format!(
Action::AddNewFactor { factor } => format!(
"added a new factor to his account : {}",
factor.quick_description(),
),
@@ -247,6 +364,15 @@ impl Action<'_> {
}
}
#[derive(serde::Serialize)]
struct JsonActionData<'a> {
time: u64,
ip: IpAddr,
user: Option<LoggableUser>,
#[serde(flatten)]
action: Action<'a>,
}
pub struct ActionLogger {
ip: IpAddr,
user: Option<User>,
@@ -254,15 +380,27 @@ pub struct ActionLogger {
impl ActionLogger {
pub fn log(&self, action: Action) {
log::info!(
"{} from {} has {}",
match &self.user {
None => "Anonymous user".to_string(),
Some(u) => u.quick_identity(),
match AppConfig::get().action_logger_format {
ActionLoggerFormat::Text => log::info!(
"{} from {} has {}",
match &self.user {
None => "Anonymous user".to_string(),
Some(u) => u.loggable().quick_identity(),
},
self.ip,
action.as_string()
),
ActionLoggerFormat::Json => match serde_json::to_string(&JsonActionData {
time: time(),
ip: self.ip,
user: self.user.as_ref().map(User::loggable),
action,
}) {
Ok(j) => println!("{j}"),
Err(e) => log::error!("Failed to serialize event to JSON! {e}"),
},
self.ip,
action.as_string()
)
ActionLoggerFormat::None => {}
}
}
}

View File

@@ -6,6 +6,15 @@ use crate::constants::{
APP_NAME, CLIENTS_LIST_FILE, OIDC_PROVIDER_CB_URI, PROVIDERS_LIST_FILE, USERS_LIST_FILE,
};
/// Action logger format
#[derive(Copy, Clone, Eq, PartialEq, Debug, clap::ValueEnum, Default)]
pub enum ActionLoggerFormat {
#[default]
Text,
Json,
None,
}
/// Basic OIDC provider
#[derive(Parser, Debug, Clone)]
#[clap(author, version, about, long_about = None)]
@@ -45,6 +54,19 @@ pub struct AppConfig {
/// Example: "https://api.geoip.rs"
#[arg(long, short, env)]
pub ip_location_service: Option<String>,
/// Action logger output format
#[arg(long, env, default_value_t, value_enum)]
pub action_logger_format: ActionLoggerFormat,
/// Login background image
#[arg(long, env, default_value = "/assets/img/forest.jpg")]
pub login_background_image: String,
/// Disable local login. If this option is set without any upstream providers set, it will be impossible
/// to authenticate
#[arg(long, env)]
pub disable_local_login: bool,
}
lazy_static::lazy_static! {

View File

@@ -26,6 +26,10 @@ pub struct Provider {
///
/// (.well-known/openid-configuration endpoint)
pub configuration_url: String,
/// Set to true if accounts on BasicOIDC should be automatically created from this provider
#[serde(default)]
pub allow_auto_account_creation: bool,
}
impl Provider {
@@ -42,6 +46,7 @@ impl Provider {
"github" => "/assets/img/brands/github.svg",
"microsoft" => "/assets/img/brands/microsoft.svg",
"google" => "/assets/img/brands/google.svg",
"openid" => "/assets/img/brands/openid.svg",
s => s,
}
}

View File

@@ -14,6 +14,12 @@ use crate::utils::time::{fmt_time, time};
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, Encode, Decode)]
pub struct UserID(pub String);
impl UserID {
pub fn random() -> Self {
Self(uuid::Uuid::new_v4().to_string())
}
}
#[derive(Debug, Clone)]
pub struct GeneralSettings {
pub uid: UserID,
@@ -26,7 +32,7 @@ pub struct GeneralSettings {
pub is_admin: bool,
}
#[derive(Eq, PartialEq, Clone, Debug)]
#[derive(Eq, PartialEq, Clone, Debug, serde::Serialize)]
pub enum GrantedClients {
AllClients,
SomeClients(Vec<ClientID>),
@@ -46,6 +52,12 @@ impl GrantedClients {
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct FactorID(pub String);
impl FactorID {
pub fn random() -> Self {
Self(uuid::Uuid::new_v4().to_string())
}
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum TwoFactorType {
TOTP(TotpKey),
@@ -60,15 +72,6 @@ pub struct TwoFactor {
}
impl TwoFactor {
pub fn quick_description(&self) -> String {
format!(
"#{} of type {} and name '{}'",
self.id.0,
self.type_str(),
self.name
)
}
pub fn type_str(&self) -> &'static str {
match self.kind {
TwoFactorType::TOTP(_) => "Authenticator app",
@@ -170,19 +173,6 @@ impl User {
format!("{} {}", self.first_name, self.last_name)
}
pub fn quick_identity(&self) -> String {
format!(
"{} {} {} ({:?})",
match self.admin {
true => "admin",
false => "user",
},
self.username,
self.email,
self.uid
)
}
/// Get the list of sources from which a user can authenticate from
pub fn authorized_authentication_sources(&self) -> AuthorizedAuthenticationSources {
AuthorizedAuthenticationSources {
@@ -317,7 +307,7 @@ impl Eq for User {}
impl Default for User {
fn default() -> Self {
Self {
uid: UserID(uuid::Uuid::new_v4().to_string()),
uid: UserID::random(),
first_name: "".to_string(),
last_name: "".to_string(),
username: "".to_string(),

View File

@@ -31,28 +31,25 @@ fn hash_password<P: AsRef<[u8]>>(pwd: P) -> Res<String> {
}
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:?}");
false
}
}
bcrypt::verify(pwd, hash).unwrap_or_else(|e| {
log::warn!("Failed to verify password! {e:?}");
false
})
}
impl UsersSyncBackend for EntityManager<User> {
fn find_by_email(&self, u: &str) -> Res<Option<User>> {
fn find_by_username_or_email(&self, u: &str) -> Res<Option<User>> {
for entry in self.iter() {
if entry.email.eq(u) {
if entry.username.eq(u) || entry.email.eq(u) {
return Ok(Some(entry.clone()));
}
}
Ok(None)
}
fn find_by_username_or_email(&self, u: &str) -> Res<Option<User>> {
fn find_by_email(&self, u: &str) -> Res<Option<User>> {
for entry in self.iter() {
if entry.username.eq(u) || entry.email.eq(u) {
if entry.email.eq(u) {
return Ok(Some(entry.clone()));
}
}
@@ -74,7 +71,7 @@ impl UsersSyncBackend for EntityManager<User> {
fn create_user_account(&mut self, settings: GeneralSettings) -> Res<UserID> {
let mut user = User {
uid: UserID(uuid::Uuid::new_v4().to_string()),
uid: UserID::random(),
..Default::default()
};
user.update_general_settings(settings);

View File

@@ -30,6 +30,12 @@
font-size: 3.5rem;
}
}
@media screen and (min-width: 767px) {
.bg-login {
background-image: url({{ p.background_image }});
}
}
</style>

View File

@@ -18,6 +18,8 @@
</style>
<!-- Local login -->
{% if show_local_login %}
<form action="/login?redirect={{ p.redirect_uri.get_encoded() }}" method="post">
<div>
<div class="form-floating">
@@ -36,6 +38,7 @@
<button class="w-100 btn btn-lg btn-primary" type="submit">Sign in</button>
</form>
{% endif %}
<!-- Upstream providers -->
{% if !providers.is_empty() %}

View File

@@ -24,7 +24,7 @@
Account details
</a>
</li>
{% if p.user.allow_local_login %}
{% if p.user.allow_local_login && p.local_login_enabled %}
<li>
<a href="/settings/change_password" class="nav-link link-dark">
Change password

View File

@@ -1,7 +1,7 @@
{% extends "base_settings_page.html" %}
{% block content %}
<table class="table table-hover" style="max-width: 800px;" aria-describedby="Clients list">
<table class="table table-hover table-break-works" style="max-width: 800px;" aria-describedby="Clients list">
<thead>
<tr>
<th scope="col">ID</th>