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
51 changed files with 1249 additions and 1885 deletions

View File

@@ -4,57 +4,10 @@ type: docker
name: default name: default
steps: steps:
# Code quality - name: cargo_check
- name: code_quality
image: rust image: rust
volumes:
- name: rust_registry
path: /usr/local/cargo/registry
commands: commands:
- rustup component add clippy - rustup component add clippy
- cargo clippy -- -D warnings - cargo clippy -- -D warnings
- cargo test - cargo test
# Build source code
- name: compile
image: rust
depends_on:
- code_quality
when:
event:
- tag
volumes:
- name: rust_registry
path: /usr/local/cargo/registry
- name: releases
path: /tmp/releases
commands:
- cargo build --release
- ls -lah target/release/basic-oidc
- cp target/release/basic-oidc /tmp/releases
# Auto-release to Gitea
- name: gitea_release
image: plugins/gitea-release
depends_on:
- compile
when:
event:
- tag
volumes:
- name: releases
path: /tmp/releases
environment:
PLUGIN_API_KEY:
from_secret: GITEA_API_KEY # needs permission write:repository
settings:
base_url: https://gitea.communiquons.org
files:
- /tmp/releases/basic-oidc
checksum: sha512
volumes:
- name: rust_registry
temp: { }
- name: releases
temp: {}

2
.gitignore vendored
View File

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

1777
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

@@ -67,11 +67,10 @@ You can add as much upstream provider as you want, using the following syntax in
```yaml ```yaml
- id: gitlab - id: gitlab
name: GitLab name: GitLab
logo: gitlab # Can be either openid, gitea, gitlab, github, microsoft, google or a full URL logo: gitlab # Can be either gitea, gitlab, github, microsoft, google or a full URL
client_id: CLIENT_ID_GIVEN_BY_PROVIDER client_id: CLIENT_ID_GIVEN_BY_PROVIDER
client_secret: CLIENT_SECRET_GIVEN_BY_PROVIDER client_secret: CLIENT_SECRET_GIVEN_BY_PROVIDER
configuration_url: https://gitlab.com/.well-known/openid-configuration configuration_url: https://gitlab.com/.well-known/openid-configuration
allow_auto_account_creation: true
``` ```
@@ -109,20 +108,5 @@ Corresponding client configuration:
OAuth proxy can then be access on this URL: http://192.168.2.103:4180/ 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 ## 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 :) 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,6 +14,7 @@ body {
/* background */ /* background */
@media screen and (min-width: 767px) { @media screen and (min-width: 767px) {
.bg-login { .bg-login {
background-image: url(/assets/img/forest.jpg);
width: 100%; width: 100%;
height: 100%; height: 100%;
position: fixed; position: fixed;

View File

@@ -21,7 +21,3 @@ body {
.form-control::placeholder { .form-control::placeholder {
color: #555; color: #555;
} }
.table-break-works td {
word-break: break-all;
}

View File

@@ -1 +0,0 @@
<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>

Before

Width:  |  Height:  |  Size: 382 B

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,26 +0,0 @@
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

@@ -1,47 +0,0 @@
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

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

View File

@@ -1,11 +0,0 @@
- 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

@@ -1,7 +0,0 @@
- 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

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

View File

@@ -8,8 +8,8 @@ use crate::constants::{
OIDC_STATES_CLEANUP_INTERVAL, OIDC_STATES_CLEANUP_INTERVAL,
}; };
use actix::{Actor, AsyncContext, Context, Handler, Message}; use actix::{Actor, AsyncContext, Context, Handler, Message};
use std::collections::HashMap;
use std::collections::hash_map::Entry; use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::net::IpAddr; use std::net::IpAddr;
use crate::data::login_redirect::LoginRedirect; use crate::data::login_redirect::LoginRedirect;
@@ -17,7 +17,7 @@ use crate::data::provider::ProviderID;
use crate::utils::string_utils::rand_str; use crate::utils::string_utils::rand_str;
use crate::utils::time::time; use crate::utils::time::time;
#[derive(Debug, Clone, serde::Serialize)] #[derive(Debug, Clone)]
pub struct ProviderLoginState { pub struct ProviderLoginState {
pub provider_id: ProviderID, pub provider_id: ProviderID,
pub state_id: String, pub state_id: String,

View File

@@ -1,11 +1,10 @@
use std::net::IpAddr; use std::net::IpAddr;
use crate::data::provider::{Provider, ProviderID}; 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::data::user::{FactorID, GeneralSettings, GrantedClients, TwoFactor, User, UserID};
use crate::utils::err::Res; 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 /// User storage interface
pub trait UsersSyncBackend { pub trait UsersSyncBackend {
@@ -39,8 +38,6 @@ pub enum LoginResult {
LocalAuthForbidden, LocalAuthForbidden,
AuthFromProviderForbidden, AuthFromProviderForbidden,
Success(Box<User>), Success(Box<User>),
AccountAutoCreated(Box<User>),
CannotAutoCreateAccount(String),
} }
#[derive(Message)] #[derive(Message)]
@@ -54,7 +51,6 @@ pub struct LocalLoginRequest {
#[rtype(LoginResult)] #[rtype(LoginResult)]
pub struct ProviderLoginRequest { pub struct ProviderLoginRequest {
pub email: String, pub email: String,
pub user_info: OpenIDUserInfo,
pub provider: Provider, pub provider: Provider,
} }
@@ -108,7 +104,7 @@ pub struct AddSuccessful2FALogin(pub UserID, pub IpAddr);
#[rtype(result = "bool")] #[rtype(result = "bool")]
pub struct Clear2FALoginHistory(pub UserID); pub struct Clear2FALoginHistory(pub UserID);
#[derive(Eq, PartialEq, Debug, Clone, serde::Serialize)] #[derive(Eq, PartialEq, Debug, Clone)]
pub struct AuthorizedAuthenticationSources { pub struct AuthorizedAuthenticationSources {
pub local: bool, pub local: bool,
pub upstream: Vec<ProviderID>, pub upstream: Vec<ProviderID>,
@@ -155,7 +151,7 @@ impl Handler<LocalLoginRequest> for UsersActor {
fn handle(&mut self, msg: LocalLoginRequest, _ctx: &mut Self::Context) -> Self::Result { fn handle(&mut self, msg: LocalLoginRequest, _ctx: &mut Self::Context) -> Self::Result {
match self.manager.find_by_username_or_email(&msg.login) { match self.manager.find_by_username_or_email(&msg.login) {
Err(e) => { Err(e) => {
log::error!("Failed to find user! {e}"); log::error!("Failed to find user! {}", e);
MessageResult(LoginResult::Error) MessageResult(LoginResult::Error)
} }
Ok(None) => MessageResult(LoginResult::AccountNotFound), Ok(None) => MessageResult(LoginResult::AccountNotFound),
@@ -188,89 +184,10 @@ impl Handler<ProviderLoginRequest> for UsersActor {
fn handle(&mut self, msg: ProviderLoginRequest, _ctx: &mut Self::Context) -> Self::Result { fn handle(&mut self, msg: ProviderLoginRequest, _ctx: &mut Self::Context) -> Self::Result {
match self.manager.find_by_email(&msg.email) { match self.manager.find_by_email(&msg.email) {
Err(e) => { Err(e) => {
log::error!("Failed to find user! {e}"); log::error!("Failed to find user! {}", e);
MessageResult(LoginResult::Error) MessageResult(LoginResult::Error)
} }
Ok(None) => { Ok(None) => MessageResult(LoginResult::AccountNotFound),
// 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)) => { Ok(Some(user)) => {
if !user.can_login_from_provider(&msg.provider) { if !user.can_login_from_provider(&msg.provider) {
return MessageResult(LoginResult::AuthFromProviderForbidden); return MessageResult(LoginResult::AuthFromProviderForbidden);
@@ -293,7 +210,7 @@ impl Handler<CreateAccount> for UsersActor {
match self.manager.create_user_account(msg.0) { match self.manager.create_user_account(msg.0) {
Ok(id) => Some(id), Ok(id) => Some(id),
Err(e) => { Err(e) => {
log::error!("Failed to create user account! {e}"); log::error!("Failed to create user account! {}", e);
None None
} }
} }
@@ -310,7 +227,7 @@ impl Handler<ChangePasswordRequest> for UsersActor {
{ {
Ok(_) => true, Ok(_) => true,
Err(e) => { Err(e) => {
log::error!("Failed to change user password! {e:?}"); log::error!("Failed to change user password! {:?}", e);
false false
} }
} }
@@ -324,7 +241,7 @@ impl Handler<Add2FAFactor> for UsersActor {
match self.manager.add_2fa_factor(&msg.0, msg.1) { match self.manager.add_2fa_factor(&msg.0, msg.1) {
Ok(_) => true, Ok(_) => true,
Err(e) => { Err(e) => {
log::error!("Failed to add 2FA factor! {e}"); log::error!("Failed to add 2FA factor! {}", e);
false false
} }
} }
@@ -338,7 +255,7 @@ impl Handler<Remove2FAFactor> for UsersActor {
match self.manager.remove_2fa_factor(&msg.0, msg.1) { match self.manager.remove_2fa_factor(&msg.0, msg.1) {
Ok(_) => true, Ok(_) => true,
Err(e) => { Err(e) => {
log::error!("Failed to remove 2FA factor! {e}"); log::error!("Failed to remove 2FA factor! {}", e);
false false
} }
} }
@@ -355,7 +272,7 @@ impl Handler<AddSuccessful2FALogin> for UsersActor {
{ {
Ok(_) => true, Ok(_) => true,
Err(e) => { Err(e) => {
log::error!("Failed to save successful 2FA authentication! {e}"); log::error!("Failed to save successful 2FA authentication! {}", e);
false false
} }
} }
@@ -392,7 +309,10 @@ impl Handler<SetAuthorizedAuthenticationSources> for UsersActor {
{ {
Ok(_) => true, Ok(_) => true,
Err(e) => { 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 false
} }
} }
@@ -405,7 +325,7 @@ impl Handler<SetGrantedClients> for UsersActor {
match self.manager.set_granted_2fa_clients(&msg.0, msg.1) { match self.manager.set_granted_2fa_clients(&msg.0, msg.1) {
Ok(_) => true, Ok(_) => true,
Err(e) => { Err(e) => {
log::error!("Failed to set granted 2FA clients! {e}"); log::error!("Failed to set granted 2FA clients! {}", e);
false false
} }
} }
@@ -419,7 +339,7 @@ impl Handler<GetUserRequest> for UsersActor {
MessageResult(GetUserResult(match self.manager.find_by_user_id(&msg.0) { MessageResult(GetUserResult(match self.manager.find_by_user_id(&msg.0) {
Ok(r) => r, Ok(r) => r,
Err(e) => { Err(e) => {
log::error!("Failed to find user by id! {e}"); log::error!("Failed to find user by id! {}", e);
None None
} }
})) }))
@@ -433,7 +353,7 @@ impl Handler<VerifyUserPasswordRequest> for UsersActor {
self.manager self.manager
.verify_user_password(&msg.0, &msg.1) .verify_user_password(&msg.0, &msg.1)
.unwrap_or_else(|e| { .unwrap_or_else(|e| {
log::error!("Failed to verify user password! {e}"); log::error!("Failed to verify user password! {}", e);
false false
}) })
} }
@@ -447,7 +367,7 @@ impl Handler<FindUserByUsername> for UsersActor {
self.manager self.manager
.find_by_username_or_email(&msg.0) .find_by_username_or_email(&msg.0)
.unwrap_or_else(|e| { .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 None
}), }),
)) ))
@@ -461,7 +381,7 @@ impl Handler<GetAllUsers> for UsersActor {
match self.manager.get_entire_users_list() { match self.manager.get_entire_users_list() {
Ok(r) => r, Ok(r) => r,
Err(e) => { Err(e) => {
log::error!("Failed to get entire users list! {e}"); log::error!("Failed to get entire users list! {}", e);
vec![] vec![]
} }
} }
@@ -475,7 +395,7 @@ impl Handler<UpdateUserSettings> for UsersActor {
match self.manager.set_general_user_settings(msg.0) { match self.manager.set_general_user_settings(msg.0) {
Ok(_) => true, Ok(_) => true,
Err(e) => { Err(e) => {
log::error!("Failed to update general user information! {e:?}"); log::error!("Failed to update general user information! {:?}", e);
false false
} }
} }
@@ -489,7 +409,7 @@ impl Handler<DeleteUserRequest> for UsersActor {
match self.manager.delete_account(&msg.0) { match self.manager.delete_account(&msg.0) {
Ok(_) => true, Ok(_) => true,
Err(e) => { Err(e) => {
log::error!("Failed to delete user account! {e}"); log::error!("Failed to delete user account! {}", e);
false false
} }
} }

View File

@@ -1,6 +1,6 @@
use crate::actors::users_actor; use crate::actors::users_actor;
use actix::Addr; 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::actors::users_actor::{DeleteUserRequest, FindUserByUsername, UsersActor};
use crate::data::action_logger::{Action, ActionLogger}; use crate::data::action_logger::{Action, ActionLogger};
@@ -65,9 +65,7 @@ pub async fn delete_user(
let res = users.send(DeleteUserRequest(req.0.user_id)).await.unwrap(); let res = users.send(DeleteUserRequest(req.0.user_id)).await.unwrap();
if res { if res {
action_logger.log(Action::AdminDeleteUser { action_logger.log(Action::AdminDeleteUser(&user));
user: user.loggable(),
});
HttpResponse::Ok().finish() HttpResponse::Ok().finish()
} else { } else {
HttpResponse::InternalServerError().finish() HttpResponse::InternalServerError().finish()

View File

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

View File

@@ -1,7 +1,7 @@
use std::path::Path; use std::path::Path;
use actix_web::{HttpResponse, web}; use actix_web::{web, HttpResponse};
use include_dir::{Dir, include_dir}; use include_dir::{include_dir, Dir};
/// Assets directory /// Assets directory
static ASSETS_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/assets"); 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::Addr;
use actix_identity::Identity; use actix_identity::Identity;
use actix_remote_ip::RemoteIP; 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 webauthn_rs::prelude::PublicKeyCredential;
use crate::data::session_identity::{SessionIdentity, SessionStatus}; use crate::data::session_identity::{SessionIdentity, SessionStatus};
@@ -47,7 +47,7 @@ pub async fn auth_webauthn(
HttpResponse::Ok().body("You are authenticated!") HttpResponse::Ok().body("You are authenticated!")
} }
Err(e) => { Err(e) => {
log::error!("Failed to authenticate user using webauthn! {e:?}"); log::error!("Failed to authenticate user using webauthn! {:?}", e);
logger.log(Action::LoginWebauthnAttempt { logger.log(Action::LoginWebauthnAttempt {
success: false, success: false,
user_id, user_id,

View File

@@ -1,7 +1,7 @@
use actix::Addr; use actix::Addr;
use actix_identity::Identity; use actix_identity::Identity;
use actix_remote_ip::RemoteIP; use actix_remote_ip::RemoteIP;
use actix_web::{HttpRequest, HttpResponse, Responder, web}; use actix_web::{web, HttpRequest, HttpResponse, Responder};
use askama::Template; use askama::Template;
use std::sync::Arc; use std::sync::Arc;
@@ -13,70 +13,54 @@ use crate::controllers::base_controller::{
build_fatal_error_page, redirect_user, redirect_user_for_login, build_fatal_error_page, redirect_user, redirect_user_for_login,
}; };
use crate::data::action_logger::{Action, ActionLogger}; use crate::data::action_logger::{Action, ActionLogger};
use crate::data::app_config::AppConfig;
use crate::data::force_2fa_auth::Force2FAAuth; 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::provider::{Provider, ProvidersManager};
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;
use crate::utils::string_utils; use crate::utils::string_utils;
pub struct BaseLoginPage { pub struct BaseLoginPage<'a> {
pub danger: Option<String>, pub danger: Option<String>,
pub success: Option<String>, pub success: Option<String>,
pub background_image: &'static str,
pub page_title: &'static str, pub page_title: &'static str,
pub app_name: &'static str, pub app_name: &'static str,
pub redirect_uri: LoginRedirect, pub redirect_uri: &'a 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)] #[derive(Template)]
#[template(path = "login/login.html")] #[template(path = "login/login.html")]
struct LoginTemplate { struct LoginTemplate<'a> {
p: BaseLoginPage, p: BaseLoginPage<'a>,
login: String, login: String,
show_local_login: bool,
providers: Vec<Provider>, providers: Vec<Provider>,
} }
#[derive(Template)] #[derive(Template)]
#[template(path = "login/password_reset.html")] #[template(path = "login/password_reset.html")]
struct PasswordResetTemplate { struct PasswordResetTemplate<'a> {
p: BaseLoginPage, p: BaseLoginPage<'a>,
min_pass_len: usize, min_pass_len: usize,
} }
#[derive(Template)] #[derive(Template)]
#[template(path = "login/choose_second_factor.html")] #[template(path = "login/choose_second_factor.html")]
struct ChooseSecondFactorTemplate<'a> { struct ChooseSecondFactorTemplate<'a> {
p: BaseLoginPage, p: BaseLoginPage<'a>,
user: &'a User, user: &'a User,
} }
#[derive(Template)] #[derive(Template)]
#[template(path = "login/otp_input.html")] #[template(path = "login/otp_input.html")]
struct LoginWithOTPTemplate { struct LoginWithOTPTemplate<'a> {
p: BaseLoginPage, p: BaseLoginPage<'a>,
} }
#[derive(Template)] #[derive(Template)]
#[template(path = "login/webauthn_input.html")] #[template(path = "login/webauthn_input.html")]
struct LoginWithWebauthnTemplate { struct LoginWithWebauthnTemplate<'a> {
p: BaseLoginPage, p: BaseLoginPage<'a>,
opaque_state: String, opaque_state: String,
challenge_json: String, challenge_json: String,
} }
@@ -127,7 +111,7 @@ pub async fn login_route(
// Check if user session must be closed // Check if user session must be closed
if let Some(true) = query.logout { if let Some(true) = query.logout {
if let Some(id) = id { if let Some(id) = id {
logger.log(Action::SignOut); logger.log(Action::Signout);
id.logout(); id.logout();
} }
success = Some("Goodbye!".to_string()); success = Some("Goodbye!".to_string());
@@ -157,10 +141,8 @@ pub async fn login_route(
"Given login could not be processed, because it has an invalid format!".to_string(), "Given login could not be processed, because it has an invalid format!".to_string(),
); );
} }
// Try to authenticate user (local login) // Try to authenticate user
else if let Some(req) = &req else if let Some(req) = &req {
&& !AppConfig::get().disable_local_login
{
login.clone_from(&req.login); login.clone_from(&req.login);
let response: LoginResult = users let response: LoginResult = users
.send(users_actor::LocalLoginRequest { .send(users_actor::LocalLoginRequest {
@@ -173,20 +155,14 @@ pub async fn login_route(
match response { match response {
LoginResult::Success(user) => { LoginResult::Success(user) => {
let status = if user.need_reset_password { let status = if user.need_reset_password {
logger.log(Action::UserNeedNewPasswordOnLogin { logger.log(Action::UserNeedNewPasswordOnLogin(&user));
user: user.loggable(),
});
SessionStatus::NeedNewPassword SessionStatus::NeedNewPassword
} else if user.has_two_factor() && !user.can_bypass_two_factors_for_ip(remote_ip.0) } else if user.has_two_factor() && !user.can_bypass_two_factors_for_ip(remote_ip.0)
{ {
logger.log(Action::UserNeed2FAOnLogin { logger.log(Action::UserNeed2FAOnLogin(&user));
user: user.loggable(),
});
SessionStatus::Need2FA SessionStatus::Need2FA
} else { } else {
logger.log(Action::UserSuccessfullyAuthenticated { logger.log(Action::UserSuccessfullyAuthenticated(&user));
user: user.loggable(),
});
SessionStatus::SignedIn SessionStatus::SignedIn
}; };
@@ -196,16 +172,13 @@ pub async fn login_route(
LoginResult::AccountDisabled => { LoginResult::AccountDisabled => {
log::warn!("Failed login for username {} : account is disabled", &login); log::warn!("Failed login for username {} : account is disabled", &login);
logger.log(Action::TryLoginWithDisabledAccount { login: &login }); logger.log(Action::TryLoginWithDisabledAccount(&login));
danger = Some("Your account is disabled!".to_string()); danger = Some("Your account is disabled!".to_string());
} }
LoginResult::LocalAuthForbidden => { LoginResult::LocalAuthForbidden => {
log::warn!( log::warn!("Failed login for username {} : attempted to use local auth, but it is forbidden", &login);
"Failed login for username {} : attempted to use local auth, but it is forbidden", logger.log(Action::TryLocalLoginFromUnauthorizedAccount(&login));
&login
);
logger.log(Action::TryLocalLoginFromUnauthorizedAccount { login: &login });
danger = Some("You cannot login from local auth with your account!".to_string()); danger = Some("You cannot login from local auth with your account!".to_string());
} }
@@ -214,8 +187,13 @@ pub async fn login_route(
} }
c => { c => {
log::warn!("Failed login for ip {remote_ip:?} / username {login}: {c:?}"); log::warn!(
logger.log(Action::FailedLoginWithBadCredentials { login: &login }); "Failed login for ip {:?} / username {}: {:?}",
remote_ip,
login,
c
);
logger.log(Action::FailedLoginWithBadCredentials(&login));
danger = Some("Login failed.".to_string()); danger = Some("Login failed.".to_string());
bruteforce bruteforce
@@ -227,10 +205,6 @@ 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( HttpResponse::Ok().content_type("text/html").body(
LoginTemplate { LoginTemplate {
@@ -238,11 +212,10 @@ pub async fn login_route(
page_title: "Login", page_title: "Login",
danger, danger,
success, success,
redirect_uri: query.0.redirect, app_name: APP_NAME,
..Default::default() redirect_uri: &query.redirect,
}, },
login, login,
show_local_login: !AppConfig::get().disable_local_login,
providers: providers.cloned(), providers: providers.cloned(),
} }
.render() .render()
@@ -301,7 +274,7 @@ pub async fn reset_password_route(
danger = Some("Failed to change password!".to_string()); danger = Some("Failed to change password!".to_string());
} else { } else {
SessionIdentity(id.as_ref()).set_status(&http_req, SessionStatus::SignedIn); SessionIdentity(id.as_ref()).set_status(&http_req, SessionStatus::SignedIn);
logger.log(Action::UserChangedPasswordOnLogin { user_id: &user_id }); logger.log(Action::UserChangedPasswordOnLogin(&user_id));
return redirect_user(query.redirect.get()); return redirect_user(query.redirect.get());
} }
} }
@@ -312,8 +285,9 @@ pub async fn reset_password_route(
p: BaseLoginPage { p: BaseLoginPage {
page_title: "Password reset", page_title: "Password reset",
danger, danger,
redirect_uri: query.0.redirect, success: None,
..Default::default() app_name: APP_NAME,
redirect_uri: &query.redirect,
}, },
min_pass_len: MIN_PASS_LEN, min_pass_len: MIN_PASS_LEN,
} }
@@ -361,8 +335,10 @@ pub async fn choose_2fa_method(
ChooseSecondFactorTemplate { ChooseSecondFactorTemplate {
p: BaseLoginPage { p: BaseLoginPage {
page_title: "Two factor authentication", page_title: "Two factor authentication",
redirect_uri: query.0.redirect, danger: None,
..Default::default() success: None,
app_name: APP_NAME,
redirect_uri: &query.redirect,
}, },
user: &user, user: &user,
} }
@@ -421,7 +397,7 @@ pub async fn login_with_otp(
{ {
logger.log(Action::OTPLoginAttempt { logger.log(Action::OTPLoginAttempt {
success: false, success: false,
user: user.loggable(), user: &user,
}); });
danger = Some("Specified code is invalid!".to_string()); danger = Some("Specified code is invalid!".to_string());
} else { } else {
@@ -438,7 +414,7 @@ pub async fn login_with_otp(
session.set_status(&http_req, SessionStatus::SignedIn); session.set_status(&http_req, SessionStatus::SignedIn);
logger.log(Action::OTPLoginAttempt { logger.log(Action::OTPLoginAttempt {
success: true, success: true,
user: user.loggable(), user: &user,
}); });
return redirect_user(query.redirect.get()); return redirect_user(query.redirect.get());
} }
@@ -450,8 +426,8 @@ pub async fn login_with_otp(
danger, danger,
success: None, success: None,
page_title: "Two-Factor Auth", page_title: "Two-Factor Auth",
redirect_uri: query.0.redirect, app_name: APP_NAME,
..Default::default() redirect_uri: &query.redirect,
}, },
} }
.render() .render()
@@ -495,7 +471,7 @@ pub async fn login_with_webauthn(
let challenge = match manager.start_authentication(&user.uid, &pub_keys) { let challenge = match manager.start_authentication(&user.uid, &pub_keys) {
Ok(c) => c, Ok(c) => c,
Err(e) => { 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( return HttpResponse::InternalServerError().body(build_fatal_error_page(
"Failed to generate webauthn challenge", "Failed to generate webauthn challenge",
)); ));
@@ -505,7 +481,7 @@ pub async fn login_with_webauthn(
let challenge_json = match serde_json::to_string(&challenge.login_challenge) { let challenge_json = match serde_json::to_string(&challenge.login_challenge) {
Ok(r) => r, Ok(r) => r,
Err(e) => { Err(e) => {
log::error!("Failed to serialize challenge! {e:?}"); log::error!("Failed to serialize challenge! {:?}", e);
return HttpResponse::InternalServerError().body("Failed to serialize challenge!"); return HttpResponse::InternalServerError().body("Failed to serialize challenge!");
} }
}; };
@@ -513,9 +489,11 @@ pub async fn login_with_webauthn(
HttpResponse::Ok().body( HttpResponse::Ok().body(
LoginWithWebauthnTemplate { LoginWithWebauthnTemplate {
p: BaseLoginPage { p: BaseLoginPage {
danger: None,
success: None,
page_title: "Two-Factor Auth", page_title: "Two-Factor Auth",
redirect_uri: query.0.redirect, app_name: APP_NAME,
..Default::default() redirect_uri: &query.redirect,
}, },
opaque_state: challenge.opaque_state, opaque_state: challenge.opaque_state,
challenge_json: urlencoding::encode(&challenge_json).to_string(), challenge_json: urlencoding::encode(&challenge_json).to_string(),

View File

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

View File

@@ -1,10 +1,16 @@
use std::sync::Arc; use std::sync::Arc;
use actix::Addr;
use actix_identity::Identity;
use actix_remote_ip::RemoteIP;
use actix_web::{web, HttpRequest, HttpResponse, Responder};
use askama::Template;
use crate::actors::bruteforce_actor::BruteForceActor; use crate::actors::bruteforce_actor::BruteForceActor;
use crate::actors::providers_states_actor::{ProviderLoginState, ProvidersStatesActor}; use crate::actors::providers_states_actor::{ProviderLoginState, ProvidersStatesActor};
use crate::actors::users_actor::{LoginResult, UsersActor}; use crate::actors::users_actor::{LoginResult, UsersActor};
use crate::actors::{bruteforce_actor, providers_states_actor, users_actor}; use crate::actors::{bruteforce_actor, providers_states_actor, users_actor};
use crate::constants::MAX_FAILED_LOGIN_ATTEMPTS; use crate::constants::{APP_NAME, MAX_FAILED_LOGIN_ATTEMPTS};
use crate::controllers::base_controller::{build_fatal_error_page, redirect_user}; use crate::controllers::base_controller::{build_fatal_error_page, redirect_user};
use crate::controllers::login_controller::BaseLoginPage; use crate::controllers::login_controller::BaseLoginPage;
use crate::data::action_logger::{Action, ActionLogger}; use crate::data::action_logger::{Action, ActionLogger};
@@ -12,16 +18,11 @@ 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::session_identity::{SessionIdentity, SessionStatus}; 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)] #[derive(askama::Template)]
#[template(path = "login/prov_login_error.html")] #[template(path = "login/prov_login_error.html")]
struct ProviderLoginError<'a> { struct ProviderLoginError<'a> {
p: BaseLoginPage, p: BaseLoginPage<'a>,
message: &'a str, message: &'a str,
} }
@@ -29,9 +30,11 @@ impl<'a> ProviderLoginError<'a> {
pub fn get(message: &'a str, redirect_uri: &'a LoginRedirect) -> HttpResponse { pub fn get(message: &'a str, redirect_uri: &'a LoginRedirect) -> HttpResponse {
let body = Self { let body = Self {
p: BaseLoginPage { p: BaseLoginPage {
danger: None,
success: None,
page_title: "Upstream login", page_title: "Upstream login",
redirect_uri: redirect_uri.clone(), app_name: APP_NAME,
..Default::default() redirect_uri,
}, },
message, message,
} }
@@ -93,14 +96,14 @@ pub async fn start_login(
let config = match ProviderConfigurationHelper::get_configuration(&provider).await { let config = match ProviderConfigurationHelper::get_configuration(&provider).await {
Ok(c) => c, Ok(c) => c,
Err(e) => { 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( return HttpResponse::InternalServerError().body(build_fatal_error_page(
"Failed to load provider configuration!", "Failed to load provider configuration!",
)); ));
} }
}; };
log::debug!("Provider configuration: {config:?}"); log::debug!("Provider configuration: {:?}", config);
let url = config.auth_url(&provider, &state); let url = config.auth_url(&provider, &state);
log::debug!("Redirect user on {url} for authentication",); log::debug!("Redirect user on {url} for authentication",);
@@ -207,7 +210,7 @@ pub async fn finish_login(
let provider_config = match ProviderConfigurationHelper::get_configuration(&provider).await { let provider_config = match ProviderConfigurationHelper::get_configuration(&provider).await {
Ok(c) => c, Ok(c) => c,
Err(e) => { 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( return HttpResponse::InternalServerError().body(build_fatal_error_page(
"Failed to load provider configuration!", "Failed to load provider configuration!",
)); ));
@@ -219,7 +222,7 @@ pub async fn finish_login(
let token = match token { let token = match token {
Ok(t) => t, Ok(t) => t,
Err(e) => { Err(e) => {
log::error!("Failed to retrieve login token! {e:?}"); log::error!("Failed to retrieve login token! {:?}", e);
bruteforce bruteforce
.send(bruteforce_actor::RecordFailedAttempt { .send(bruteforce_actor::RecordFailedAttempt {
@@ -244,7 +247,7 @@ pub async fn finish_login(
let user_info = match provider_config.get_userinfo(&token).await { let user_info = match provider_config.get_userinfo(&token).await {
Ok(info) => info, Ok(info) => info,
Err(e) => { Err(e) => {
log::error!("Failed to retrieve user information! {e:?}"); log::error!("Failed to retrieve user information! {:?}", e);
logger.log(Action::ProviderFailedGetUserInfo { logger.log(Action::ProviderFailedGetUserInfo {
provider: &provider, provider: &provider,
@@ -272,7 +275,7 @@ pub async fn finish_login(
} }
// Check if email was provided by the userinfo endpoint // Check if email was provided by the userinfo endpoint
let email = match &user_info.email { let email = match user_info.email {
Some(e) => e, Some(e) => e,
None => { None => {
logger.log(Action::ProviderMissingEmailInResponse { logger.log(Action::ProviderMissingEmailInResponse {
@@ -292,7 +295,6 @@ pub async fn finish_login(
let result: LoginResult = users let result: LoginResult = users
.send(users_actor::ProviderLoginRequest { .send(users_actor::ProviderLoginRequest {
email: email.clone(), email: email.clone(),
user_info: user_info.clone(),
provider: provider.clone(), provider: provider.clone(),
}) })
.await .await
@@ -300,13 +302,6 @@ pub async fn finish_login(
let user = match result { let user = match result {
LoginResult::Success(u) => u, LoginResult::Success(u) => u,
LoginResult::AccountAutoCreated(u) => {
logger.log(Action::ProviderAccountAutoCreated {
provider: &provider,
user: u.loggable(),
});
u
}
LoginResult::AccountNotFound => { LoginResult::AccountNotFound => {
logger.log(Action::ProviderAccountNotFound { logger.log(Action::ProviderAccountNotFound {
provider: &provider, provider: &provider,
@@ -362,18 +357,14 @@ pub async fn finish_login(
logger.log(Action::ProviderLoginSuccessful { logger.log(Action::ProviderLoginSuccessful {
provider: &provider, provider: &provider,
user: user.loggable(), user: &user,
}); });
let status = if user.has_two_factor() && !user.can_bypass_two_factors_for_ip(remote_ip.0) { let status = if user.has_two_factor() && !user.can_bypass_two_factors_for_ip(remote_ip.0) {
logger.log(Action::UserNeed2FAOnLogin { logger.log(Action::UserNeed2FAOnLogin(&user));
user: user.loggable(),
});
SessionStatus::Need2FA SessionStatus::Need2FA
} else { } else {
logger.log(Action::UserSuccessfullyAuthenticated { logger.log(Action::UserSuccessfullyAuthenticated(&user));
user: user.loggable(),
});
SessionStatus::SignedIn SessionStatus::SignedIn
}; };

View File

@@ -1,6 +1,6 @@
use actix::Addr; use actix::Addr;
use actix_remote_ip::RemoteIP; use actix_remote_ip::RemoteIP;
use actix_web::{HttpResponse, Responder, web}; use actix_web::{web, HttpResponse, Responder};
use askama::Template; use askama::Template;
use crate::actors::bruteforce_actor::BruteForceActor; use crate::actors::bruteforce_actor::BruteForceActor;
@@ -18,7 +18,6 @@ pub(crate) struct BaseSettingsPage<'a> {
pub success_message: Option<String>, pub success_message: Option<String>,
pub page_title: &'static str, pub page_title: &'static str,
pub app_name: &'static str, pub app_name: &'static str,
pub local_login_enabled: bool,
pub user: &'a User, pub user: &'a User,
pub version: &'static str, pub version: &'static str,
pub ip_location_api: Option<&'static str>, pub ip_location_api: Option<&'static str>,
@@ -38,7 +37,6 @@ impl<'a> BaseSettingsPage<'a> {
app_name: APP_NAME, app_name: APP_NAME,
user, user,
version: env!("CARGO_PKG_VERSION"), version: env!("CARGO_PKG_VERSION"),
local_login_enabled: !AppConfig::get().disable_local_login,
ip_location_api: AppConfig::get().ip_location_service.as_deref(), ip_location_api: AppConfig::get().ip_location_service.as_deref(),
} }
} }

View File

@@ -1,5 +1,6 @@
use actix::Addr; use actix::Addr;
use actix_web::{HttpResponse, Responder, web}; use actix_web::{web, HttpResponse, Responder};
use uuid::Uuid;
use webauthn_rs::prelude::RegisterPublicKeyCredential; use webauthn_rs::prelude::RegisterPublicKeyCredential;
use crate::actors::users_actor; use crate::actors::users_actor;
@@ -52,13 +53,11 @@ pub async fn save_totp_factor(
} }
let factor = TwoFactor { let factor = TwoFactor {
id: FactorID::random(), id: FactorID(Uuid::new_v4().to_string()),
name: factor_name, name: factor_name,
kind: TwoFactorType::TOTP(key), kind: TwoFactorType::TOTP(key),
}; };
logger.log(Action::AddNewFactor { logger.log(Action::AddNewFactor(&factor));
factor: factor.loggable(),
});
let res = users let res = users
.send(users_actor::Add2FAFactor(user.uid.clone(), factor)) .send(users_actor::Add2FAFactor(user.uid.clone(), factor))
@@ -95,19 +94,17 @@ pub async fn save_webauthn_factor(
let key = match manager.finish_registration(&user, &form.0.opaque_state, form.0.credential) { let key = match manager.finish_registration(&user, &form.0.opaque_state, form.0.credential) {
Ok(k) => k, Ok(k) => k,
Err(e) => { 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!"); return HttpResponse::InternalServerError().body("Failed to register key!");
} }
}; };
let factor = TwoFactor { let factor = TwoFactor {
id: FactorID::random(), id: FactorID(Uuid::new_v4().to_string()),
name: factor_name, name: factor_name,
kind: TwoFactorType::WEBAUTHN(Box::new(key)), kind: TwoFactorType::WEBAUTHN(Box::new(key)),
}; };
logger.log(Action::AddNewFactor { logger.log(Action::AddNewFactor(&factor));
factor: factor.loggable(),
});
let res = users let res = users
.send(users_actor::Add2FAFactor(user.uid.clone(), factor)) .send(users_actor::Add2FAFactor(user.uid.clone(), factor))

View File

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

View File

@@ -6,118 +6,26 @@ use actix::Addr;
use actix_identity::Identity; use actix_identity::Identity;
use actix_remote_ip::RemoteIP; use actix_remote_ip::RemoteIP;
use actix_web::dev::Payload; 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::providers_states_actor::ProviderLoginState;
use crate::actors::users_actor; use crate::actors::users_actor;
use crate::actors::users_actor::{AuthorizedAuthenticationSources, UsersActor}; use crate::actors::users_actor::{AuthorizedAuthenticationSources, UsersActor};
use crate::data::app_config::{ActionLoggerFormat, AppConfig}; use crate::data::client::Client;
use crate::data::client::ClientID;
use crate::data::provider::{Provider, ProviderID}; use crate::data::provider::{Provider, ProviderID};
use crate::data::session_identity::SessionIdentity; use crate::data::session_identity::SessionIdentity;
use crate::data::user::{FactorID, GrantedClients, TwoFactor, TwoFactorType, User, UserID}; use crate::data::user::{FactorID, GrantedClients, TwoFactor, 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> { pub enum Action<'a> {
AdminCreateUser { AdminCreateUser(&'a User),
user: LoggableUser, AdminUpdateUser(&'a User),
}, AdminDeleteUser(&'a User),
AdminUpdateUser { AdminResetUserPassword(&'a User),
user: LoggableUser, AdminRemoveUserFactor(&'a User, &'a TwoFactor),
}, AdminSetAuthorizedAuthenticationSources(&'a User, &'a AuthorizedAuthenticationSources),
AdminDeleteUser { AdminSetNewGrantedClientsList(&'a User, &'a GrantedClients),
user: LoggableUser, AdminClear2FAHistory(&'a User),
},
AdminResetUserPassword {
user: LoggableUser,
},
AdminRemoveUserFactor {
user: LoggableUser,
factor: LoggableFactor,
},
AdminSetAuthorizedAuthenticationSources {
user: LoggableUser,
sources: &'a AuthorizedAuthenticationSources,
},
AdminSetNewGrantedClientsList {
user: LoggableUser,
clients: &'a GrantedClients,
},
AdminClear2FAHistory {
user: LoggableUser,
},
LoginWebauthnAttempt { LoginWebauthnAttempt {
success: bool, success: bool,
user_id: UserID, user_id: UserID,
@@ -150,10 +58,6 @@ pub enum Action<'a> {
provider: &'a Provider, provider: &'a Provider,
email: &'a str, email: &'a str,
}, },
ProviderAccountAutoCreated {
provider: &'a Provider,
user: LoggableUser,
},
ProviderAccountDisabled { ProviderAccountDisabled {
provider: &'a Provider, provider: &'a Provider,
email: &'a str, email: &'a str,
@@ -169,82 +73,66 @@ pub enum Action<'a> {
}, },
ProviderLoginSuccessful { ProviderLoginSuccessful {
provider: &'a Provider, provider: &'a Provider,
user: LoggableUser, user: &'a User,
},
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 { OTPLoginAttempt {
user: LoggableUser, user: &'a User,
success: bool, success: bool,
}, },
NewOpenIDSession { NewOpenIDSession {
client: &'a ClientID, client: &'a Client,
}, },
NewOpenIDSuccessfulImplicitAuth { NewOpenIDSuccessfulImplicitAuth {
client: &'a ClientID, client: &'a Client,
}, },
ChangedHisPassword, ChangedHisPassword,
ClearedHisLoginHistory, ClearedHisLoginHistory,
AddNewFactor { AddNewFactor(&'a TwoFactor),
factor: LoggableFactor,
},
Removed2FAFactor { Removed2FAFactor {
factor_id: &'a FactorID, factor_id: &'a FactorID,
}, },
} }
impl Action<'_> { impl<'a> Action<'a> {
pub fn as_string(&self) -> String { pub fn as_string(&self) -> String {
match self { match self {
Action::AdminDeleteUser { user } => { Action::AdminDeleteUser(user) => {
format!("deleted account of {}", user.quick_identity()) format!("deleted account of {}", user.quick_identity())
} }
Action::AdminCreateUser { user } => { Action::AdminCreateUser(user) => {
format!("created account of {}", user.quick_identity()) format!("created account of {}", user.quick_identity())
} }
Action::AdminUpdateUser { user } => { Action::AdminUpdateUser(user) => {
format!("updated account of {}", user.quick_identity()) format!("updated account of {}", user.quick_identity())
} }
Action::AdminResetUserPassword { user } => { Action::AdminResetUserPassword(user) => {
format!( format!(
"set a temporary password for the account of {}", "set a temporary password for the account of {}",
user.quick_identity() user.quick_identity()
) )
} }
Action::AdminRemoveUserFactor { user, factor } => format!( Action::AdminRemoveUserFactor(user, factor) => format!(
"removed 2 factor ({}) of user ({})", "removed 2 factor ({}) of user ({})",
factor.quick_description(), factor.quick_description(),
user.quick_identity() user.quick_identity()
), ),
Action::AdminClear2FAHistory { user } => { Action::AdminClear2FAHistory(user) => {
format!("cleared 2FA history of {}", user.quick_identity()) format!("cleared 2FA history of {}", user.quick_identity())
} }
Action::AdminSetAuthorizedAuthenticationSources { user, sources } => format!( Action::AdminSetAuthorizedAuthenticationSources(user, sources) => format!(
"update authorized authentication sources ({:?}) for user ({})", "update authorized authentication sources ({:?}) for user ({})",
sources, sources,
user.quick_identity() user.quick_identity()
), ),
Action::AdminSetNewGrantedClientsList { user, clients } => format!( Action::AdminSetNewGrantedClientsList(user, clients) => format!(
"set new granted clients list ({:?}) for user ({})", "set new granted clients list ({:?}) for user ({})",
clients, clients,
user.quick_identity() user.quick_identity()
@@ -254,86 +142,51 @@ impl Action<'_> {
false => format!("performed FAILED webauthn attempt for user {user_id:?}"), false => format!("performed FAILED webauthn attempt for user {user_id:?}"),
}, },
Action::StartLoginAttemptWithOpenIDProvider { provider_id, state } => format!( Action::StartLoginAttemptWithOpenIDProvider { provider_id, state } => format!(
"started new authentication attempt through an OpenID provider (prov={} / state={state})", "started new authentication attempt through an OpenID provider (prov={} / state={state})", provider_id.0
provider_id.0
), ),
Action::ProviderError { message } => { Action::ProviderError { message } =>
format!("failed provider authentication with message '{message}'") format!("failed provider authentication with message '{message}'"),
} Action::ProviderCBInvalidState { state } =>
Action::ProviderCBInvalidState { state } => { format!("provided invalid callback state after provider authentication: '{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::ProviderRateLimited => { Action::ProviderFailedGetUserInfo {provider} => format!("could not get user information from userinfo endpoint of provider {}!", provider.id.0),
"could not complete OpenID login because it has reached failed attempts rate limit!" Action::ProviderEmailNotValidated {provider}=>format!("could not login using provider {} because its email was marked as not validated!", provider.id.0),
.to_string() 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 } =>
Action::ProviderFailedGetToken { state, code } => format!( format!("could not login using provider {} because the email {email} could not be associated to any account!", &provider.id.0),
"could not complete login from provider because the id_token could not be retrieved! (state={state:?} code = {code})" Action::ProviderAccountDisabled { provider, email } =>
), format!("could not login using provider {} because the account associated to the email {email} is disabled!", &provider.id.0),
Action::ProviderFailedGetUserInfo { provider } => format!( Action::ProviderAccountNotAllowedToLoginWithProvider { provider, email } =>
"could not get user information from userinfo endpoint of provider {}!", 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),
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::ProviderEmailNotValidated { provider } => format!( Action::ProviderLoginSuccessful {provider, user} =>
"could not login using provider {} because its email was marked as not validated!", format!("successfully authenticated using provider {} as {}", provider.id.0, user.quick_identity()),
provider.id.0 Action::Signout => "signed out".to_string(),
), Action::UserNeed2FAOnLogin(user) => {
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::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
),
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!( format!(
"successfully authenticated as user {:?} but need to do 2FA authentication", "successfully authenticated as user {:?} but need to do 2FA authentication",
user.quick_identity() user.quick_identity()
) )
} }
Action::UserSuccessfullyAuthenticated { user } => { Action::UserSuccessfullyAuthenticated(user) => {
format!("successfully authenticated as {}", user.quick_identity()) 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", "successfully authenticated as {}, but need to set a new password",
user.quick_identity() user.quick_identity()
), ),
Action::TryLoginWithDisabledAccount { login } => { Action::TryLoginWithDisabledAccount(login) => {
format!("successfully authenticated as {login}, but this is a DISABLED ACCOUNT") format!("successfully authenticated as {login}, but this is a DISABLED ACCOUNT")
} }
Action::TryLocalLoginFromUnauthorizedAccount { login } => { Action::TryLocalLoginFromUnauthorizedAccount(login) => {
format!( format!("successfully locally authenticated as {login}, but this is a FORBIDDEN for this account!")
"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") 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:?}") format!("set a new password at login as user {user_id:?}")
} }
Action::OTPLoginAttempt { user, success } => match success { Action::OTPLoginAttempt { user, success } => match success {
@@ -347,15 +200,12 @@ impl Action<'_> {
), ),
}, },
Action::NewOpenIDSession { client } => { Action::NewOpenIDSession { client } => {
format!("opened a new OpenID session with {:?}", client) format!("opened a new OpenID session with {:?}", client.id)
} }
Action::NewOpenIDSuccessfulImplicitAuth { client } => format!( Action::NewOpenIDSuccessfulImplicitAuth { client } => format!("finished an implicit flow connection for client {:?}", client.id),
"finished an implicit flow connection for client {:?}",
client
),
Action::ChangedHisPassword => "changed his password".to_string(), Action::ChangedHisPassword => "changed his password".to_string(),
Action::ClearedHisLoginHistory => "cleared his login history".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 : {}", "added a new factor to his account : {}",
factor.quick_description(), factor.quick_description(),
), ),
@@ -364,15 +214,6 @@ impl Action<'_> {
} }
} }
#[derive(serde::Serialize)]
struct JsonActionData<'a> {
time: u64,
ip: IpAddr,
user: Option<LoggableUser>,
#[serde(flatten)]
action: Action<'a>,
}
pub struct ActionLogger { pub struct ActionLogger {
ip: IpAddr, ip: IpAddr,
user: Option<User>, user: Option<User>,
@@ -380,27 +221,15 @@ pub struct ActionLogger {
impl ActionLogger { impl ActionLogger {
pub fn log(&self, action: Action) { pub fn log(&self, action: Action) {
match AppConfig::get().action_logger_format { log::info!(
ActionLoggerFormat::Text => log::info!( "{} from {} has {}",
"{} from {} has {}", match &self.user {
match &self.user { None => "Anonymous user".to_string(),
None => "Anonymous user".to_string(), Some(u) => u.quick_identity(),
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}"),
}, },
ActionLoggerFormat::None => {} self.ip.to_string(),
} action.as_string()
)
} }
} }

View File

@@ -6,15 +6,6 @@ use crate::constants::{
APP_NAME, CLIENTS_LIST_FILE, OIDC_PROVIDER_CB_URI, PROVIDERS_LIST_FILE, USERS_LIST_FILE, 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 /// Basic OIDC provider
#[derive(Parser, Debug, Clone)] #[derive(Parser, Debug, Clone)]
#[clap(author, version, about, long_about = None)] #[clap(author, version, about, long_about = None)]
@@ -27,14 +18,6 @@ pub struct AppConfig {
#[clap(short, long, env)] #[clap(short, long, env)]
pub storage_path: String, pub storage_path: String,
/// Overwrite clients list file path, if the file is not to be found in storage path
#[clap(long, env)]
pub clients_list_file_path: Option<String>,
/// Overwrite providers list file path, if the file is not to be found in storage path
#[clap(long, env)]
pub providers_list_file_path: Option<String>,
/// App token token /// App token token
#[clap(short, long, env, default_value = "")] #[clap(short, long, env, default_value = "")]
pub token_key: String, pub token_key: String,
@@ -49,24 +32,11 @@ pub struct AppConfig {
/// IP location service API /// IP location service API
/// ///
/// Operating instance of IP location service : https://gitlab.com/pierre42100/iplocationserver /// Up instance of IP location service : https://gitlab.com/pierre42100/iplocationserver
/// ///
/// Example: "https://api.geoip.rs" /// Example: "https://api.geoip.rs"
#[arg(long, short, env)] #[arg(long, short, env)]
pub ip_location_service: Option<String>, 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! { lazy_static::lazy_static! {
@@ -101,17 +71,11 @@ impl AppConfig {
} }
pub fn clients_file(&self) -> PathBuf { pub fn clients_file(&self) -> PathBuf {
match &self.clients_list_file_path { self.storage_path().join(CLIENTS_LIST_FILE)
None => self.storage_path().join(CLIENTS_LIST_FILE),
Some(p) => Path::new(p).to_path_buf(),
}
} }
pub fn providers_file(&self) -> PathBuf { pub fn providers_file(&self) -> PathBuf {
match &self.providers_list_file_path { self.storage_path().join(PROVIDERS_LIST_FILE)
None => self.storage_path().join(PROVIDERS_LIST_FILE),
Some(p) => Path::new(p).to_path_buf(),
}
} }
pub fn full_url(&self, uri: &str) -> String { pub fn full_url(&self, uri: &str) -> String {

View File

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

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::general_purpose::URL_SAFE_NO_PAD as BASE64_URL_SAFE_NO_PAD;
use base64::Engine as _;
use crate::utils::crypt_utils::sha256; use crate::utils::crypt_utils::sha256;
@@ -22,7 +22,7 @@ impl CodeChallenge {
encoded.eq(&self.code_challenge) encoded.eq(&self.code_challenge)
} }
s => { s => {
log::error!("Unknown code challenge method: {s}"); log::error!("Unknown code challenge method: {}", s);
false false
} }
} }
@@ -40,8 +40,8 @@ mod test {
code_challenge: "text1".to_string(), code_challenge: "text1".to_string(),
}; };
assert!(chal.verify_code("text1")); assert_eq!(true, chal.verify_code("text1"));
assert!(!chal.verify_code("text2")); assert_eq!(false, chal.verify_code("text2"));
} }
#[test] #[test]
@@ -51,8 +51,8 @@ mod test {
code_challenge: "uSOvC48D8TMh6RgW-36XppMlMgys-6KAE_wEIev9W2g".to_string(), code_challenge: "uSOvC48D8TMh6RgW-36XppMlMgys-6KAE_wEIev9W2g".to_string(),
}; };
assert!(chal.verify_code("HIwht3lCHfnsruA+7Sq8NP2mPj5cBZe0Ewf23eK9UQhK4TdCIt3SK7Fr/giCdnfjxYQILOPG2D562emggAa2lA==")); assert_eq!(true, chal.verify_code("HIwht3lCHfnsruA+7Sq8NP2mPj5cBZe0Ewf23eK9UQhK4TdCIt3SK7Fr/giCdnfjxYQILOPG2D562emggAa2lA=="));
assert!(!chal.verify_code("text1")); assert_eq!(false, chal.verify_code("text1"));
} }
#[test] #[test]
@@ -62,7 +62,10 @@ mod test {
code_challenge: "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM".to_string(), code_challenge: "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM".to_string(),
}; };
assert!(chal.verify_code("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk")); assert_eq!(
assert!(!chal.verify_code("text1")); 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::current_user::CurrentUser;
use crate::data::from_request_redirect::FromRequestRedirect; 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::dev::Payload;
use actix_web::{FromRequest, HttpRequest}; use actix_web::{FromRequest, HttpRequest};
use std::future::Future; use std::future::Future;

View File

@@ -6,7 +6,7 @@ use actix::Addr;
use actix_identity::Identity; use actix_identity::Identity;
use actix_web::dev::Payload; use actix_web::dev::Payload;
use actix_web::error::ErrorInternalServerError; 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;
use crate::actors::users_actor::UsersActor; use crate::actors::users_actor::UsersActor;

View File

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

View File

@@ -2,7 +2,7 @@ use crate::data::current_user::CurrentUser;
use crate::data::session_identity::SessionIdentity; use crate::data::session_identity::SessionIdentity;
use actix_identity::Identity; use actix_identity::Identity;
use actix_web::dev::Payload; 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::future::Future;
use std::pin::Pin; use std::pin::Pin;

View File

@@ -1,12 +1,12 @@
use jwt_simple::algorithms::RSAKeyPairLike; use jwt_simple::algorithms::RSAKeyPairLike;
use jwt_simple::claims::JWTClaims; use jwt_simple::claims::JWTClaims;
use jwt_simple::prelude::RS256KeyPair; use jwt_simple::prelude::RS256KeyPair;
use serde::Serialize;
use serde::de::DeserializeOwned; 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 as BASE64_URL_URL_SAFE;
use base64::engine::general_purpose::URL_SAFE_NO_PAD as BASE64_URL_SAFE_NO_PAD; 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::err::Res;
use crate::utils::string_utils::rand_str; use crate::utils::string_utils::rand_str;

View File

@@ -26,10 +26,6 @@ pub struct Provider {
/// ///
/// (.well-known/openid-configuration endpoint) /// (.well-known/openid-configuration endpoint)
pub configuration_url: String, 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 { impl Provider {
@@ -46,7 +42,6 @@ impl Provider {
"github" => "/assets/img/brands/github.svg", "github" => "/assets/img/brands/github.svg",
"microsoft" => "/assets/img/brands/microsoft.svg", "microsoft" => "/assets/img/brands/microsoft.svg",
"google" => "/assets/img/brands/google.svg", "google" => "/assets/img/brands/google.svg",
"openid" => "/assets/img/brands/openid.svg",
s => s, s => s,
} }
} }

View File

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

View File

@@ -5,15 +5,20 @@ use serde::{Deserialize, Serialize};
use crate::data::user::{User, UserID}; use crate::data::user::{User, UserID};
use crate::utils::time::time; use crate::utils::time::time;
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Default)] #[derive(Debug, Serialize, Deserialize, Eq, PartialEq)]
pub enum SessionStatus { pub enum SessionStatus {
#[default]
Invalid, Invalid,
SignedIn, SignedIn,
NeedNewPassword, NeedNewPassword,
Need2FA, Need2FA,
} }
impl Default for SessionStatus {
fn default() -> Self {
Self::Invalid
}
}
#[derive(Debug, Serialize, Deserialize, Default)] #[derive(Debug, Serialize, Deserialize, Default)]
pub struct SessionIdentityData { pub struct SessionIdentityData {
pub id: Option<UserID>, pub id: Option<UserID>,
@@ -25,7 +30,7 @@ pub struct SessionIdentityData {
pub struct SessionIdentity<'a>(pub Option<&'a Identity>); pub struct SessionIdentity<'a>(pub Option<&'a Identity>);
impl SessionIdentity<'_> { impl<'a> SessionIdentity<'a> {
fn get_session_data(&self) -> Option<SessionIdentityData> { fn get_session_data(&self) -> Option<SessionIdentityData> {
if let Some(id) = self.0 { if let Some(id) = self.0 {
Self::deserialize_session_data(id.id().ok()) Self::deserialize_session_data(id.id().ok())
@@ -41,7 +46,7 @@ impl SessionIdentity<'_> {
.map(|f| match f { .map(|f| match f {
Ok(d) => Some(d), Ok(d) => Some(d),
Err(e) => { Err(e) => {
log::warn!("Failed to deserialize session data! {e:?}"); log::warn!("Failed to deserialize session data! {:?}", e);
None None
} }
}) })
@@ -60,7 +65,7 @@ impl SessionIdentity<'_> {
log::debug!("Will set user session data."); log::debug!("Will set user session data.");
if let Err(e) = Identity::login(&req.extensions(), s) { 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."); log::debug!("Did set user session data.");
} }

View File

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

View File

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

View File

@@ -3,7 +3,7 @@ use std::net::IpAddr;
use crate::actors::users_actor::{AuthorizedAuthenticationSources, UsersSyncBackend}; use crate::actors::users_actor::{AuthorizedAuthenticationSources, UsersSyncBackend};
use crate::data::entity_manager::EntityManager; use crate::data::entity_manager::EntityManager;
use crate::data::user::{FactorID, GeneralSettings, GrantedClients, TwoFactor, User, UserID}; 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; use crate::utils::time::time;
impl EntityManager<User> { impl EntityManager<User> {
@@ -18,7 +18,7 @@ impl EntityManager<User> {
}; };
if let Err(e) = self.replace_entries(|u| u.uid.eq(id), &update(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); return Err(e);
} }
@@ -31,25 +31,28 @@ fn hash_password<P: AsRef<[u8]>>(pwd: P) -> Res<String> {
} }
fn verify_password<P: AsRef<[u8]>>(pwd: P, hash: &str) -> bool { fn verify_password<P: AsRef<[u8]>>(pwd: P, hash: &str) -> bool {
bcrypt::verify(pwd, hash).unwrap_or_else(|e| { match bcrypt::verify(pwd, hash) {
log::warn!("Failed to verify password! {e:?}"); Ok(r) => r,
false Err(e) => {
}) log::warn!("Failed to verify password! {:?}", e);
false
}
}
} }
impl UsersSyncBackend for EntityManager<User> { impl UsersSyncBackend for EntityManager<User> {
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() { for entry in self.iter() {
if entry.username.eq(u) || entry.email.eq(u) { if entry.email.eq(u) {
return Ok(Some(entry.clone())); return Ok(Some(entry.clone()));
} }
} }
Ok(None) Ok(None)
} }
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() { for entry in self.iter() {
if entry.email.eq(u) { if entry.username.eq(u) || entry.email.eq(u) {
return Ok(Some(entry.clone())); return Ok(Some(entry.clone()));
} }
} }
@@ -71,7 +74,7 @@ impl UsersSyncBackend for EntityManager<User> {
fn create_user_account(&mut self, settings: GeneralSettings) -> Res<UserID> { fn create_user_account(&mut self, settings: GeneralSettings) -> Res<UserID> {
let mut user = User { let mut user = User {
uid: UserID::random(), uid: UserID(uuid::Uuid::new_v4().to_string()),
..Default::default() ..Default::default()
}; };
user.update_general_settings(settings); user.update_general_settings(settings);

View File

@@ -1,3 +1,4 @@
use std::io::ErrorKind;
use std::sync::Arc; use std::sync::Arc;
use actix_web::web; use actix_web::web;
@@ -108,11 +109,17 @@ impl WebAuthManager {
) -> Res<WebauthnPubKey> { ) -> Res<WebauthnPubKey> {
let state: RegisterKeyOpaqueData = self.crypto_wrapper.decrypt(opaque_state)?; let state: RegisterKeyOpaqueData = self.crypto_wrapper.decrypt(opaque_state)?;
if state.user_id != user.uid { 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() { 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( let res = self.core.finish_passkey_registration(
@@ -150,11 +157,17 @@ impl WebAuthManager {
) -> Res { ) -> Res {
let state: AuthStateOpaqueData = self.crypto_wrapper.decrypt(opaque_state)?; let state: AuthStateOpaqueData = self.crypto_wrapper.decrypt(opaque_state)?;
if &state.user_id != user_id { 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() { 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( self.core.finish_passkey_authentication(

View File

@@ -2,14 +2,14 @@ use core::time::Duration;
use std::sync::Arc; use std::sync::Arc;
use actix::Actor; use actix::Actor;
use actix_identity::config::LogoutBehaviour;
use actix_identity::IdentityMiddleware; use actix_identity::IdentityMiddleware;
use actix_identity::config::LogoutBehavior;
use actix_remote_ip::RemoteIPConfig; use actix_remote_ip::RemoteIPConfig;
use actix_session::SessionMiddleware;
use actix_session::storage::CookieSessionStore; use actix_session::storage::CookieSessionStore;
use actix_session::SessionMiddleware;
use actix_web::cookie::{Key, SameSite}; use actix_web::cookie::{Key, SameSite};
use actix_web::middleware::Logger; 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::bruteforce_actor::BruteForceActor;
use basic_oidc::actors::openid_sessions_actor::OpenIDSessionsActor; use basic_oidc::actors::openid_sessions_actor::OpenIDSessionsActor;
@@ -51,7 +51,7 @@ async fn main() -> std::io::Result<()> {
// Create initial user if required // Create initial user if required
if users.is_empty() { if users.is_empty() {
log::info!("Create default {DEFAULT_ADMIN_USERNAME} user"); log::info!("Create default {} user", DEFAULT_ADMIN_USERNAME);
let default_admin = User { let default_admin = User {
username: DEFAULT_ADMIN_USERNAME.to_string(), username: DEFAULT_ADMIN_USERNAME.to_string(),
authorized_clients: None, authorized_clients: None,
@@ -100,7 +100,7 @@ async fn main() -> std::io::Result<()> {
.build(); .build();
let identity_middleware = IdentityMiddleware::builder() let identity_middleware = IdentityMiddleware::builder()
.logout_behavior(LogoutBehavior::PurgeSession) .logout_behaviour(LogoutBehaviour::PurgeSession)
.visit_deadline(Some(Duration::from_secs(MAX_INACTIVITY_DURATION))) .visit_deadline(Some(Duration::from_secs(MAX_INACTIVITY_DURATION)))
.login_deadline(Some(Duration::from_secs(MAX_SESSION_DURATION))) .login_deadline(Some(Duration::from_secs(MAX_SESSION_DURATION)))
.build(); .build();

View File

@@ -1,15 +1,15 @@
//! # Authentication middleware //! # Authentication middleware
use std::future::{Future, Ready, ready}; use std::future::{ready, Future, Ready};
use std::pin::Pin; use std::pin::Pin;
use std::rc::Rc; use std::rc::Rc;
use actix_identity::IdentityExt; use actix_identity::IdentityExt;
use actix_web::body::EitherBody; use actix_web::body::EitherBody;
use actix_web::http::{Method, header}; use actix_web::http::{header, Method};
use actix_web::{ use actix_web::{
dev::{forward_ready, Service, ServiceRequest, ServiceResponse, Transform},
Error, HttpResponse, Error, HttpResponse,
dev::{Service, ServiceRequest, ServiceResponse, Transform, forward_ready},
}; };
use crate::constants::{ use crate::constants::{
@@ -89,21 +89,25 @@ where
Box::pin(async move { Box::pin(async move {
// Check if POST request comes from another website (block invalid origins) // Check if POST request comes from another website (block invalid origins)
let origin = req.headers().get(header::ORIGIN); let origin = req.headers().get(header::ORIGIN);
if req.method() == Method::POST if req.method() == Method::POST && req.path() != TOKEN_URI && req.path() != USERINFO_URI
&& req.path() != TOKEN_URI
&& req.path() != USERINFO_URI
&& let Some(o) = origin
&& !o
.to_str()
.unwrap_or("bad")
.eq(&AppConfig::get().website_origin)
{ {
log::warn!("Blocked POST request from invalid origin! Origin given {o:?}"); if let Some(o) = origin {
return Ok(req.into_response( if !o
HttpResponse::Unauthorized() .to_str()
.body("POST request from invalid origin!") .unwrap_or("bad")
.map_into_right_body(), .eq(&AppConfig::get().website_origin)
)); {
log::warn!(
"Blocked POST request from invalid origin! Origin given {:?}",
o
);
return Ok(req.into_response(
HttpResponse::Unauthorized()
.body("POST request from invalid origin!")
.map_into_right_body(),
));
}
}
} }
if req.path().starts_with("/.git") { if req.path().starts_with("/.git") {
@@ -129,8 +133,8 @@ where
_ => ConnStatus::SignedOut, _ => ConnStatus::SignedOut,
}; };
log::trace!("Connection data: {session_data:#?}"); log::trace!("Connection data: {:#?}", session_data);
log::debug!("Connection status: {session:?}"); log::debug!("Connection status: {:?}", session);
// Redirect user to login page // Redirect user to login page
if !session.is_auth() if !session.is_auth()

View File

@@ -1,9 +1,14 @@
use lazy_regex::regex_find; 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 /// Generate a random string of a given size
pub fn rand_str(len: usize) -> String { 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 /// Parse environment variables
@@ -44,10 +49,8 @@ mod test {
const VAR_ONE: &str = "VAR_ONE"; const VAR_ONE: &str = "VAR_ONE";
#[test] #[test]
fn test_apply_env_var() { fn test_apply_env_var() {
unsafe { env::set_var(VAR_ONE, "good");
env::set_var(VAR_ONE, "good"); let src = format!("This is ${{{}}}", VAR_ONE);
}
let src = format!("This is ${{{VAR_ONE}}}");
assert_eq!("This is good", apply_env_vars(&src)); assert_eq!("This is good", apply_env_vars(&src));
} }
@@ -55,7 +58,7 @@ mod test {
#[test] #[test]
fn test_invalid_var_syntax() { 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)); assert_eq!(src, apply_env_vars(&src));
} }

View File

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

View File

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

View File

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

View File

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