Compare commits

...

3 Commits

Author SHA1 Message Date
Timshel 6f7a7f7034
Improve Playwright tests (#7752) 5 days ago
maximilize cdf2035433
Do not fail login when push device registration fails (#7378) 5 days ago
Timshel 010c269e37
Improve and expand kdf_upgrade (#7855) 5 days ago
  1. 2
      playwright/compose/warden/build.sh
  2. 4
      playwright/docker-compose.yml
  3. 2
      playwright/test.env
  4. 35
      src/api/core/accounts.rs
  5. 6
      src/api/core/ciphers.rs
  6. 20
      src/api/core/organizations.rs
  7. 4
      src/api/core/two_factor/authenticator.rs
  8. 4
      src/api/core/two_factor/duo.rs
  9. 4
      src/api/core/two_factor/email.rs
  10. 5
      src/api/core/two_factor/mod.rs
  11. 4
      src/api/core/two_factor/webauthn.rs
  12. 5
      src/api/core/two_factor/yubikey.rs
  13. 11
      src/api/identity.rs
  14. 4
      src/api/mod.rs
  15. 56
      src/config.rs
  16. 33
      src/db/models/user.rs

2
playwright/compose/warden/build.sh

@ -24,7 +24,7 @@ if [[ ! -z "$REPO_URL" ]] && [[ ! -z "$COMMIT_HASH" ]] ; then
fi fi
# Lower the KDF iterations default for faster tests. # Lower the KDF iterations default for faster tests.
sed -i 's/(6e5,2e6,6e5)/(1e5,2e6,1e5)/' /web-vault/app/main.*.js sed -i 's/(6e5,2e6,6e5)/(6e3,2e6,6e3)/' /web-vault/app/main.*.js
# Generate a self signed cert # Generate a self signed cert
mkdir -p /data/ssl; cd /data/ssl mkdir -p /data/ssl; cd /data/ssl

4
playwright/docker-compose.yml

@ -6,6 +6,8 @@ services:
build: build:
context: .. context: ..
dockerfile: Dockerfile dockerfile: Dockerfile
args:
DB: sqlite,mysql,postgresql,unsafe_test_mode
entrypoint: /bin/bash entrypoint: /bin/bash
restart: "no" restart: "no"
@ -23,12 +25,14 @@ services:
env_file: ${DC_ENV_FILE:-.env} env_file: ${DC_ENV_FILE:-.env}
environment: environment:
- ADMIN_TOKEN - ADMIN_TOKEN
- CLIENT_KDF_ITER
- DATABASE_URL - DATABASE_URL
- CLIENT_SUPPRESS_ONBOARDING - CLIENT_SUPPRESS_ONBOARDING
- EMAIL_2FA_AUTO_FALLBACK - EMAIL_2FA_AUTO_FALLBACK
- I_REALLY_WANT_VOLATILE_STORAGE - I_REALLY_WANT_VOLATILE_STORAGE
- LOG_LEVEL - LOG_LEVEL
- LOGIN_RATELIMIT_MAX_BURST - LOGIN_RATELIMIT_MAX_BURST
- PASSWORD_ITERATIONS
- SMTP_HOST - SMTP_HOST
- SMTP_FROM - SMTP_FROM
- SMTP_DEBUG - SMTP_DEBUG

2
playwright/test.env

@ -58,6 +58,8 @@ LOG_LEVEL=info,oidcwarden::sso=debug
LOGIN_RATELIMIT_MAX_BURST=100 LOGIN_RATELIMIT_MAX_BURST=100
ADMIN_TOKEN=admin ADMIN_TOKEN=admin
CLIENT_SUPPRESS_ONBOARDING=true CLIENT_SUPPRESS_ONBOARDING=true
PASSWORD_ITERATIONS=6000
CLIENT_KDF_ITER=6000
SMTP_SECURITY=off SMTP_SECURITY=off
SMTP_PORT=${MAILDEV_SMTP_PORT} SMTP_PORT=${MAILDEV_SMTP_PORT}

35
src/api/core/accounts.rs

@ -1039,8 +1039,8 @@ async fn post_password(data: Json<ChangePassData>, headers: Headers, conn: DbCon
} }
fn set_kdf_data(user: &mut User, data: &KDFData) -> EmptyResult { fn set_kdf_data(user: &mut User, data: &KDFData) -> EmptyResult {
if data.kdf == UserKdfType::Pbkdf2 as i32 && data.kdf_iterations < 100_000 { if data.kdf == UserKdfType::Pbkdf2 as i32 && data.kdf_iterations < CONFIG.client_kdf_iter() {
err!("PBKDF2 KDF iterations must be at least 100000.") err!(format!("PBKDF2 KDF iterations must be at least {}.", CONFIG.client_kdf_iter()))
} }
if data.kdf == UserKdfType::Argon2id as i32 { if data.kdf == UserKdfType::Argon2id as i32 {
@ -1878,7 +1878,7 @@ async fn post_sstamp(data: Json<PasswordOrOtpData>, headers: Headers, conn: DbCo
let data: PasswordOrOtpData = data.into_inner(); let data: PasswordOrOtpData = data.into_inner();
let mut user = headers.user; let mut user = headers.user;
data.validate(&user, true, &conn).await?; data.validate(&mut user, true, &conn).await?;
user.reset_security_stamp(&conn).await?; user.reset_security_stamp(&conn).await?;
let save_result = user.save(&conn).await; let save_result = user.save(&conn).await;
@ -2136,9 +2136,9 @@ async fn post_delete_account(
#[delete("/accounts", data = "<data>")] #[delete("/accounts", data = "<data>")]
async fn delete_account(data: Json<PasswordOrOtpData>, headers: Headers, conn: DbConn, nt: Notify<'_>) -> EmptyResult { async fn delete_account(data: Json<PasswordOrOtpData>, headers: Headers, conn: DbConn, nt: Notify<'_>) -> EmptyResult {
let data: PasswordOrOtpData = data.into_inner(); let data: PasswordOrOtpData = data.into_inner();
let user = headers.user; let mut user = headers.user;
data.validate(&user, true, &conn).await?; data.validate(&mut user, true, &conn).await?;
// The devices are deleted together with the user, so check for push devices beforehand // The devices are deleted together with the user, so check for push devices beforehand
let has_push_device = CONFIG.push_enabled() && Device::check_user_has_push_device(&user.uuid, &conn).await; let has_push_device = CONFIG.push_enabled() && Device::check_user_has_push_device(&user.uuid, &conn).await;
@ -2219,15 +2219,15 @@ fn unknown_email_kdf(email: &str) -> (i32, i32, Option<i32>, Option<i32>) {
const PBKDF2: i32 = UserKdfType::Pbkdf2 as i32; const PBKDF2: i32 = UserKdfType::Pbkdf2 as i32;
const ARGON2ID: i32 = UserKdfType::Argon2id as i32; const ARGON2ID: i32 = UserKdfType::Argon2id as i32;
// Same list as upstream, the default is in it twice to give it more weight // Same list as upstream, the default is in it twice to give it more weight
const KDF_SETTINGS: [(i32, i32, Option<i32>, Option<i32>); 6] = [ let kdf_settings: [(i32, i32, Option<i32>, Option<i32>); 6] = [
(User::CLIENT_KDF_TYPE_DEFAULT, User::CLIENT_KDF_ITER_DEFAULT, None, None), (User::CLIENT_KDF_TYPE_DEFAULT, CONFIG.client_kdf_iter(), None, None),
(User::CLIENT_KDF_TYPE_DEFAULT, User::CLIENT_KDF_ITER_DEFAULT, None, None), (User::CLIENT_KDF_TYPE_DEFAULT, CONFIG.client_kdf_iter(), None, None),
(PBKDF2, 100_000, None, None), (PBKDF2, 100_000, None, None),
(PBKDF2, 5_000, None, None), (PBKDF2, 5_000, None, None),
(ARGON2ID, 3, Some(64), Some(4)), (ARGON2ID, 3, Some(64), Some(4)),
(ARGON2ID, 6, Some(32), Some(4)), (ARGON2ID, 6, Some(32), Some(4)),
]; ];
KDF_SETTINGS[crate::auth::prelogin_kdf_index(email, KDF_SETTINGS.len())] kdf_settings[crate::auth::prelogin_kdf_index(email, kdf_settings.len())]
} }
pub async fn prelogin(data: Json<PreloginData>, ip: ClientIp, conn: DbConn) -> JsonResult { pub async fn prelogin(data: Json<PreloginData>, ip: ClientIp, conn: DbConn) -> JsonResult {
@ -2264,19 +2264,6 @@ struct SecretVerificationRequest {
master_password_hash: String, master_password_hash: String,
} }
// Change the KDF Iterations if necessary
pub async fn kdf_upgrade(user: &mut User, pwd_hash: &str, conn: &DbConn) -> ApiResult<()> {
if user.password_iterations < CONFIG.password_iterations() {
user.password_iterations = CONFIG.password_iterations();
user.set_password(pwd_hash, None, false, None, conn).await?;
if let Err(e) = user.save(conn).await {
error!("Error updating user: {e:#?}");
}
}
Ok(())
}
#[post("/accounts/verify-password", data = "<data>")] #[post("/accounts/verify-password", data = "<data>")]
async fn verify_password(data: Json<SecretVerificationRequest>, headers: Headers, conn: DbConn) -> JsonResult { async fn verify_password(data: Json<SecretVerificationRequest>, headers: Headers, conn: DbConn) -> JsonResult {
let data: SecretVerificationRequest = data.into_inner(); let data: SecretVerificationRequest = data.into_inner();
@ -2286,7 +2273,7 @@ async fn verify_password(data: Json<SecretVerificationRequest>, headers: Headers
err!("Invalid password") err!("Invalid password")
} }
kdf_upgrade(&mut user, &data.master_password_hash, &conn).await?; user.check_persist_kdf_upgrade(&data.master_password_hash, &conn).await?;
Ok(Json(master_password_policy(&user, &conn).await)) Ok(Json(master_password_policy(&user, &conn).await))
} }
@ -2295,7 +2282,7 @@ async fn update_api_key(data: Json<PasswordOrOtpData>, rotate: bool, headers: He
let data: PasswordOrOtpData = data.into_inner(); let data: PasswordOrOtpData = data.into_inner();
let mut user = headers.user; let mut user = headers.user;
data.validate(&user, true, &conn).await?; data.validate(&mut user, true, &conn).await?;
if rotate || user.api_key.is_none() { if rotate || user.api_key.is_none() {
user.api_key = Some(crypto::generate_api_key()); user.api_key = Some(crypto::generate_api_key());

6
src/api/core/ciphers.rs

@ -2302,9 +2302,9 @@ async fn purge_org_vault(
} }
let data: PasswordOrOtpData = data.into_inner(); let data: PasswordOrOtpData = data.into_inner();
let user = headers.user; let mut user = headers.user;
data.validate(&user, true, &conn).await?; data.validate(&mut user, true, &conn).await?;
match Membership::find_confirmed_by_user_and_org(&user.uuid, &organization.org_id, &conn).await { match Membership::find_confirmed_by_user_and_org(&user.uuid, &organization.org_id, &conn).await {
Some(member) if member.atype == MembershipType::Owner => { Some(member) if member.atype == MembershipType::Owner => {
@ -2338,7 +2338,7 @@ async fn purge_personal_vault(
let data: PasswordOrOtpData = data.into_inner(); let data: PasswordOrOtpData = data.into_inner();
let mut user = headers.user; let mut user = headers.user;
data.validate(&user, true, &conn).await?; data.validate(&mut user, true, &conn).await?;
for cipher in Cipher::find_owned_by_user(&user.uuid, &conn).await { for cipher in Cipher::find_owned_by_user(&user.uuid, &conn).await {
cipher.delete(&conn).await?; cipher.delete(&conn).await?;

20
src/api/core/organizations.rs

@ -235,12 +235,14 @@ async fn delete_organization(
headers: OwnerHeaders, headers: OwnerHeaders,
conn: DbConn, conn: DbConn,
) -> EmptyResult { ) -> EmptyResult {
let mut user = headers.user;
if org_id != headers.org_id { if org_id != headers.org_id {
err!("Organization not found", "Organization id's do not match"); err!("Organization not found", "Organization id's do not match");
} }
let data: PasswordOrOtpData = data.into_inner(); let data: PasswordOrOtpData = data.into_inner();
data.validate(&headers.user, true, &conn).await?; data.validate(&mut user, true, &conn).await?;
match Organization::find_by_uuid(&org_id, &conn).await { match Organization::find_by_uuid(&org_id, &conn).await {
None => err!("Organization not found"), None => err!("Organization not found"),
@ -3718,12 +3720,13 @@ async fn put_reset_password_enrollment(
data: Json<OrganizationUserResetPasswordEnrollmentRequest>, data: Json<OrganizationUserResetPasswordEnrollmentRequest>,
conn: DbConn, conn: DbConn,
) -> EmptyResult { ) -> EmptyResult {
if user_id != headers.user.uuid { let mut membership = headers.membership;
let mut user = headers.user;
if user_id != user.uuid {
err!("User to enroll isn't member of required organization", "The user_id and acting user do not match"); err!("User to enroll isn't member of required organization", "The user_id and acting user do not match");
} }
let mut membership = headers.membership;
check_reset_password_applicable(&org_id, &conn).await?; check_reset_password_applicable(&org_id, &conn).await?;
let reset_request = data.into_inner(); let reset_request = data.into_inner();
@ -3738,7 +3741,7 @@ async fn put_reset_password_enrollment(
master_password_hash: reset_request.master_password_hash, master_password_hash: reset_request.master_password_hash,
otp: reset_request.otp, otp: reset_request.otp,
} }
.validate(&headers.user, true, &conn) .validate(&mut user, true, &conn)
.await?; .await?;
} }
@ -3754,8 +3757,7 @@ async fn put_reset_password_enrollment(
EventType::OrganizationUserResetPasswordWithdraw EventType::OrganizationUserResetPasswordWithdraw
}; };
log_event(event_type, &membership.uuid, &org_id, &headers.user.uuid, headers.device.atype, &headers.ip.ip, &conn) log_event(event_type, &membership.uuid, &org_id, &user.uuid, headers.device.atype, &headers.ip.ip, &conn).await;
.await;
Ok(()) Ok(())
} }
@ -3789,10 +3791,10 @@ async fn api_key(
err!("Organization not found", "Organization id's do not match"); err!("Organization not found", "Organization id's do not match");
} }
let data: PasswordOrOtpData = data.into_inner(); let data: PasswordOrOtpData = data.into_inner();
let user = headers.user; let mut user = headers.user;
// Validate the owner users password/otp // Validate the owner users password/otp
data.validate(&user, true, &conn).await?; data.validate(&mut user, true, &conn).await?;
let org_api_key = if let Some(mut org_api_key) = OrganizationApiKey::find_by_org_uuid(org_id, &conn).await { let org_api_key = if let Some(mut org_api_key) = OrganizationApiKey::find_by_org_uuid(org_id, &conn).await {
if rotate { if rotate {

4
src/api/core/two_factor/authenticator.rs

@ -20,9 +20,9 @@ pub fn routes() -> Vec<Route> {
#[post("/two-factor/get-authenticator", data = "<data>")] #[post("/two-factor/get-authenticator", data = "<data>")]
async fn generate_authenticator(data: Json<PasswordOrOtpData>, headers: Headers, conn: DbConn) -> JsonResult { async fn generate_authenticator(data: Json<PasswordOrOtpData>, headers: Headers, conn: DbConn) -> JsonResult {
let user = headers.user; let mut user = headers.user;
data.validate(&user, false, &conn).await?; data.validate(&mut user, false, &conn).await?;
let twofactor = TwoFactor::find_by_user_and_type(&user.uuid, TwoFactorType::Authenticator, &conn).await; let twofactor = TwoFactor::find_by_user_and_type(&user.uuid, TwoFactorType::Authenticator, &conn).await;

4
src/api/core/two_factor/duo.rs

@ -43,9 +43,9 @@ const DISABLED_MESSAGE_DEFAULT: &str = "<To use the global Duo keys, please leav
#[post("/two-factor/get-duo", data = "<data>")] #[post("/two-factor/get-duo", data = "<data>")]
async fn get_duo(data: Json<PasswordOrOtpData>, headers: Headers, conn: DbConn) -> JsonResult { async fn get_duo(data: Json<PasswordOrOtpData>, headers: Headers, conn: DbConn) -> JsonResult {
let data: PasswordOrOtpData = data.into_inner(); let data: PasswordOrOtpData = data.into_inner();
let user = headers.user; let mut user = headers.user;
data.validate(&user, false, &conn).await?; data.validate(&mut user, false, &conn).await?;
let (enabled, duo) = match get_user_duo_data(&user.uuid, &conn).await { let (enabled, duo) = match get_user_duo_data(&user.uuid, &conn).await {
DuoStatus::Global(_) => (true, Some(DuoData::secret())), DuoStatus::Global(_) => (true, Some(DuoData::secret())),

4
src/api/core/two_factor/email.rs

@ -154,9 +154,9 @@ pub async fn send_token(user_id: &UserId, conn: &DbConn) -> EmptyResult {
#[post("/two-factor/get-email", data = "<data>")] #[post("/two-factor/get-email", data = "<data>")]
async fn get_email(data: Json<PasswordOrOtpData>, headers: Headers, conn: DbConn) -> JsonResult { async fn get_email(data: Json<PasswordOrOtpData>, headers: Headers, conn: DbConn) -> JsonResult {
let data: PasswordOrOtpData = data.into_inner(); let data: PasswordOrOtpData = data.into_inner();
let user = headers.user; let mut user = headers.user;
data.validate(&user, false, &conn).await?; data.validate(&mut user, false, &conn).await?;
let (enabled, mfa_email) = let (enabled, mfa_email) =
if let Some(x) = TwoFactor::find_by_user_and_type(&user.uuid, TwoFactorType::Email, &conn).await { if let Some(x) = TwoFactor::find_by_user_and_type(&user.uuid, TwoFactorType::Email, &conn).await {

5
src/api/core/two_factor/mod.rs

@ -104,9 +104,9 @@ async fn get_twofactor(headers: Headers, conn: DbConn) -> Json<Value> {
#[post("/two-factor/get-recover", data = "<data>")] #[post("/two-factor/get-recover", data = "<data>")]
async fn get_recover(data: Json<PasswordOrOtpData>, headers: Headers, conn: DbConn) -> JsonResult { async fn get_recover(data: Json<PasswordOrOtpData>, headers: Headers, conn: DbConn) -> JsonResult {
let data: PasswordOrOtpData = data.into_inner(); let data: PasswordOrOtpData = data.into_inner();
let user = headers.user; let mut user = headers.user;
data.validate(&user, true, &conn).await?; data.validate(&mut user, true, &conn).await?;
Ok(Json(json!({ Ok(Json(json!({
"code": user.totp_recover, "code": user.totp_recover,
@ -129,6 +129,7 @@ pub async fn check_2fa_state(user: &User, device_type: i32, ip: &std::net::IpAdd
if TwoFactor::find_by_user(&user.uuid, conn).await.is_empty() { if TwoFactor::find_by_user(&user.uuid, conn).await.is_empty() {
enforce_2fa_policy(user, &user.uuid, device_type, ip, true, conn).await?; enforce_2fa_policy(user, &user.uuid, device_type, ip, true, conn).await?;
} }
Ok(()) Ok(())
} }

4
src/api/core/two_factor/webauthn.rs

@ -123,9 +123,9 @@ async fn get_webauthn(data: Json<PasswordOrOtpData>, headers: Headers, conn: DbC
} }
let data: PasswordOrOtpData = data.into_inner(); let data: PasswordOrOtpData = data.into_inner();
let user = headers.user; let mut user = headers.user;
data.validate(&user, false, &conn).await?; data.validate(&mut user, false, &conn).await?;
let (enabled, registrations) = get_webauthn_registrations(&user.uuid, &conn).await?; let (enabled, registrations) = get_webauthn_registrations(&user.uuid, &conn).await?;
let keys: Vec<i32> = registrations.iter().map(|r| r.id).collect(); let keys: Vec<i32> = registrations.iter().map(|r| r.id).collect();

5
src/api/core/two_factor/yubikey.rs

@ -122,9 +122,9 @@ async fn generate_yubikey(data: Json<PasswordOrOtpData>, headers: Headers, conn:
get_yubico_credentials()?; get_yubico_credentials()?;
let data: PasswordOrOtpData = data.into_inner(); let data: PasswordOrOtpData = data.into_inner();
let user = headers.user; let mut user = headers.user;
data.validate(&user, false, &conn).await?; data.validate(&mut user, false, &conn).await?;
let user_id = &user.uuid; let user_id = &user.uuid;
@ -148,6 +148,7 @@ async fn generate_yubikey(data: Json<PasswordOrOtpData>, headers: Headers, conn:
#[post("/two-factor/yubikey", data = "<data>")] #[post("/two-factor/yubikey", data = "<data>")]
async fn activate_yubikey(data: Json<EnableYubikeyData>, headers: Headers, conn: DbConn) -> JsonResult { async fn activate_yubikey(data: Json<EnableYubikeyData>, headers: Headers, conn: DbConn) -> JsonResult {
let data: EnableYubikeyData = data.into_inner(); let data: EnableYubikeyData = data.into_inner();
let yubikeys = parse_yubikeys(&data); let yubikeys = parse_yubikeys(&data);
let mut user = headers.user; let mut user = headers.user;

11
src/api/identity.rs

@ -14,7 +14,7 @@ use crate::{
api::{ api::{
ApiResult, EmptyResult, JsonResult, ApiResult, EmptyResult, JsonResult,
core::{ core::{
accounts::{PreloginData, RegisterData, kdf_upgrade, prelogin, register}, accounts::{PreloginData, RegisterData, prelogin, register},
log_user_event, log_user_event,
two_factor::{ two_factor::{
authenticator, duo_oidc, email, enforce_2fa_policy, is_twofactor_provider_usable, webauthn, yubikey, authenticator, duo_oidc, email, enforce_2fa_policy, is_twofactor_provider_usable, webauthn, yubikey,
@ -461,7 +461,7 @@ async fn password_login(
// Change the KDF Iterations (only when not logging in with an auth request) // Change the KDF Iterations (only when not logging in with an auth request)
if data.auth_request.is_none() { if data.auth_request.is_none() {
kdf_upgrade(&mut user, password, conn).await?; user.check_persist_kdf_upgrade(password, conn).await?;
} }
let now = Utc::now().naive_utc(); let now = Utc::now().naive_utc();
@ -606,7 +606,12 @@ async fn authenticated_response(
// register push device // register push device
if !device.is_new() { if !device.is_new() {
register_push_device(device, conn).await?; // Registering the device for push is best-effort: a failure talking to the
// push relay/identity server must not turn a successful authentication into
// an error (see #7371). This mirrors the new-device email handling above.
if let Err(e) = register_push_device(device, conn).await {
error!("An error occurred while registering the device for push notifications: {e}");
}
} }
// Save to update `device.updated_at` to track usage and toggle new status // Save to update `device.updated_at` to track usage and toggle new status

4
src/api/mod.rs

@ -63,7 +63,7 @@ impl PasswordOrOtpData {
/// Tokens used via this struct can be used multiple times during the process /// Tokens used via this struct can be used multiple times during the process
/// First for the validation to continue, after that to enable or validate the following actions /// First for the validation to continue, after that to enable or validate the following actions
/// This is different per caller, so it can be adjusted to delete the token or not /// This is different per caller, so it can be adjusted to delete the token or not
pub async fn validate(&self, user: &User, delete_if_valid: bool, conn: &DbConn) -> EmptyResult { pub async fn validate(&self, user: &mut User, delete_if_valid: bool, conn: &DbConn) -> EmptyResult {
use crate::api::core::two_factor::protected_actions::validate_protected_action_otp; use crate::api::core::two_factor::protected_actions::validate_protected_action_otp;
match (self.master_password_hash.as_deref(), self.otp.as_deref()) { match (self.master_password_hash.as_deref(), self.otp.as_deref()) {
@ -71,6 +71,8 @@ impl PasswordOrOtpData {
if !user.check_valid_password(pw_hash) { if !user.check_valid_password(pw_hash) {
err!("Invalid password"); err!("Invalid password");
} }
user.check_persist_kdf_upgrade(pw_hash, conn).await?;
} }
(None, Some(otp)) => { (None, Some(otp)) => {
validate_protected_action_otp(otp, &user.uuid, delete_if_valid, conn).await?; validate_protected_action_otp(otp, &user.uuid, delete_if_valid, conn).await?;

56
src/config.rs

@ -71,9 +71,16 @@ macro_rules! make_config {
( @type $ty:ty, option) => { Option<$ty> }; ( @type $ty:ty, option) => { Option<$ty> };
( @type $ty:ty, $id:ident) => { $ty }; ( @type $ty:ty, $id:ident) => { $ty };
// Options that only builds with the `unsafe_test_mode` feature read
( @test_only test_def ) => { true };
( @test_only $none_action:ident ) => { false };
// Generate the values depending on none_action // Generate the values depending on none_action
( @build $value:expr, $config:expr, option, ) => { $value }; ( @build $value:expr, $config:expr, option, ) => { $value };
( @build $value:expr, $config:expr, def, $default:expr ) => { $value.unwrap_or($default) }; ( @build $value:expr, $config:expr, def, $default:expr ) => { $value.unwrap_or($default) };
( @build $value:expr, $config:expr, test_def, $default:expr ) => {
if cfg!(feature = "unsafe_test_mode") { $value.unwrap_or($default) } else { $default }
};
( @build $value:expr, $config:expr, auto, $default_fn:expr ) => {{ ( @build $value:expr, $config:expr, auto, $default_fn:expr ) => {{
match $value { match $value {
Some(v) => v, Some(v) => v,
@ -286,6 +293,22 @@ macro_rules! make_config {
)+)+ )+)+
} }
/// Warns about each set `test_def` option in a build without the `unsafe_test_mode` feature, which ignores them.
fn warn_test_only_options(&self) {
if cfg!(feature = "unsafe_test_mode") {
return;
}
$($(
if make_config! { @test_only $none_action } && self.$name.is_some() {
// We can't use warn! here because logging isn't setup yet.
println!(
"[WARNING] {} is only read by builds with the `unsafe_test_mode` feature, ignoring it.",
pastey::paste!(stringify!([<$name:upper>]))
);
}
)+)+
}
/// Merges the values of both builders into a new builder. /// Merges the values of both builders into a new builder.
/// If both have the same element, `other` wins. /// If both have the same element, `other` wins.
fn merge(&self, other: &Self, show_overrides: bool, overrides: &mut Vec<&str>) -> Self { fn merge(&self, other: &Self, show_overrides: bool, overrides: &mut Vec<&str>) -> Self {
@ -352,6 +375,8 @@ macro_rules! make_config {
r#type: &'static str, r#type: &'static str,
doc: ElementDoc, doc: ElementDoc,
overridden: bool, overridden: bool,
#[serde(skip)]
test_only: bool,
} }
#[derive(Serialize)] #[derive(Serialize)]
@ -411,10 +436,20 @@ macro_rules! make_config {
r#type: get_form_type(stringify!($ty)), r#type: get_form_type(stringify!($ty)),
doc: get_doc(concat!($($doc),+)), doc: get_doc(concat!($($doc),+)),
overridden: overridden.contains(&pastey::paste!(stringify!([<$name:upper>]))), overridden: overridden.contains(&pastey::paste!(stringify!([<$name:upper>]))),
test_only: make_config! { @test_only $none_action },
}, },
)+], // End of elements repetition )+], // End of elements repetition
}, },
)+]; // End of groups repetition )+]; // End of groups repetition
// Options only test builds read aren't shown in the others
let data: Vec<GroupData> = data
.into_iter()
.map(|mut group| {
group.elements.retain(|e| !e.test_only || cfg!(feature = "unsafe_test_mode"));
group
})
.collect();
serde_json::to_value(data).unwrap() serde_json::to_value(data).unwrap()
} }
@ -513,6 +548,8 @@ macro_rules! make_config {
// //
// Where action applied when the value wasn't provided and can be: // Where action applied when the value wasn't provided and can be:
// def: Use a default value // def: Use a default value
// test_def: Use a default value, which only builds with the `unsafe_test_mode` feature let you change. Other builds
// warn at startup when it's set, ignore it, and don't show it in the admin panel
// auto: Value is auto generated based on other values // auto: Value is auto generated based on other values
// option: Value is optional // option: Value is optional
// generated: Value is always autogenerated and it's original value ignored // generated: Value is always autogenerated and it's original value ignored
@ -682,6 +719,8 @@ make_config! {
client { client {
/// Control whether clients onboarding interstitials are suppressed |> post-login welcome dialogs, extension install prompts, setup extension redirects, and premium upsell modals /// Control whether clients onboarding interstitials are suppressed |> post-login welcome dialogs, extension install prompts, setup extension redirects, and premium upsell modals
client_suppress_onboarding: bool, true, def, false; client_suppress_onboarding: bool, true, def, false;
/// In most cases this value is set by the client |> Will block clients from setting too low of a value in `accounts::post_kdf`
client_kdf_iter: i32, false, test_def, 600_000;
}, },
/// Advanced settings /// Advanced settings
@ -961,6 +1000,17 @@ make_config! {
}, },
} }
fn check_iterations(iterations: i32, key: &str) -> Result<(), Error> {
if iterations < 100_000 {
#[cfg(feature = "unsafe_test_mode")]
println!("[WARNING] {key} should be at least 100000 or higher. The default is 600000!");
#[cfg(not(feature = "unsafe_test_mode"))]
err!(format!("{key} should be at least 100000 or higher. The default is 600000!"));
}
Ok(())
}
fn validate_config(cfg: &ConfigItems, on_update: bool) -> Result<(), Error> { fn validate_config(cfg: &ConfigItems, on_update: bool) -> Result<(), Error> {
// Validate connection URL is valid and DB feature is enabled // Validate connection URL is valid and DB feature is enabled
#[cfg(sqlite)] #[cfg(sqlite)]
@ -995,9 +1045,8 @@ fn validate_config(cfg: &ConfigItems, on_update: bool) -> Result<(), Error> {
} }
} }
if cfg.password_iterations < 100_000 { check_iterations(cfg.password_iterations, "PASSWORD_ITERATIONS")?;
err!("PASSWORD_ITERATIONS should be at least 100000 or higher. The default is 600000!"); check_iterations(cfg.client_kdf_iter, "CLIENT_KDF_ITER")?;
}
let limit = 256; let limit = 256;
if !(1..=limit).contains(&cfg.database_max_conns) { if !(1..=limit).contains(&cfg.database_max_conns) {
@ -1554,6 +1603,7 @@ impl Config {
// Fill any missing with defaults // Fill any missing with defaults
let config = builder.build(); let config = builder.build();
if !SKIP_CONFIG_VALIDATION.load(Ordering::Relaxed) { if !SKIP_CONFIG_VALIDATION.load(Ordering::Relaxed) {
builder.warn_test_only_options();
validate_config(&config, false)?; validate_config(&config, false)?;
} }

33
src/db/models/user.rs

@ -2,6 +2,7 @@ use chrono::{NaiveDateTime, TimeDelta, Utc};
use derive_more::{AsRef, Deref, Display, From}; use derive_more::{AsRef, Deref, Display, From};
use diesel::prelude::*; use diesel::prelude::*;
use serde_json::Value; use serde_json::Value;
use std::cmp;
use crate::{ use crate::{
CONFIG, CONFIG,
@ -133,7 +134,6 @@ impl UserStampException {
/// Local methods /// Local methods
impl User { impl User {
pub const CLIENT_KDF_TYPE_DEFAULT: i32 = UserKdfType::Pbkdf2 as i32; pub const CLIENT_KDF_TYPE_DEFAULT: i32 = UserKdfType::Pbkdf2 as i32;
pub const CLIENT_KDF_ITER_DEFAULT: i32 = 600_000;
pub fn new(email: &str, name: Option<String>) -> Self { pub fn new(email: &str, name: Option<String>) -> Self {
let now = Utc::now().naive_utc(); let now = Utc::now().naive_utc();
@ -171,7 +171,7 @@ impl User {
excluded_globals: "[]".to_owned(), excluded_globals: "[]".to_owned(),
client_kdf_type: Self::CLIENT_KDF_TYPE_DEFAULT, client_kdf_type: Self::CLIENT_KDF_TYPE_DEFAULT,
client_kdf_iter: Self::CLIENT_KDF_ITER_DEFAULT, client_kdf_iter: CONFIG.client_kdf_iter(),
client_kdf_memory: None, client_kdf_memory: None,
client_kdf_parallelism: None, client_kdf_parallelism: None,
@ -248,6 +248,7 @@ impl User {
allow_next_route: Option<Vec<String>>, allow_next_route: Option<Vec<String>>,
conn: &DbConn, conn: &DbConn,
) -> EmptyResult { ) -> EmptyResult {
self.password_iterations = cmp::max(self.password_iterations, CONFIG.password_iterations());
self.password_hash = self.password_hash =
crypto::hash_password(password.as_bytes(), &self.salt, self.password_iterations.cast_unsigned()); crypto::hash_password(password.as_bytes(), &self.salt, self.password_iterations.cast_unsigned());
@ -477,6 +478,34 @@ impl User {
} }
} }
pub async fn check_persist_kdf_upgrade(&mut self, pwd_hash: &str, conn: &DbConn) -> EmptyResult {
if self.password_iterations < CONFIG.password_iterations() {
let old_iteration = self.password_iterations;
let old_hash = self.password_hash.clone();
self.set_password(pwd_hash, None, false, None, conn).await?;
conn.run(move |conn| {
diesel::update(
users::table
.filter(users::uuid.eq(&self.uuid))
.filter(users::password_iterations.eq(old_iteration))
.filter(users::password_hash.eq(old_hash)),
)
.set((
users::updated_at.eq(Utc::now().naive_utc()),
users::password_iterations.eq(&self.password_iterations),
users::password_hash.eq(&self.password_hash),
))
.execute(conn)
.map_res("Error updating user KDF iterations")
})
.await
} else {
Ok(())
}
}
pub async fn delete(&self, conn: &DbConn) -> EmptyResult { pub async fn delete(&self, conn: &DbConn) -> EmptyResult {
for member in Membership::find_confirmed_by_user(&self.uuid, conn).await { for member in Membership::find_confirmed_by_user(&self.uuid, conn).await {
if member.atype == MembershipType::Owner if member.atype == MembershipType::Owner

Loading…
Cancel
Save