From 8ec6beed3a4ef550ecd86991122b8a8757ef7021 Mon Sep 17 00:00:00 2001 From: hugocasa Date: Fri, 27 Nov 2026 18:23:17 +0100 Subject: [PATCH] feat: require two-factor authentication for password logins (#12704) * feat: add native totp two-factor authentication for password login Co-Authored-By: Claude Opus 5.5 * fix: keep login field spacing when the code field shows Co-Authored-By: Claude Opus 5.5 * fix: keep two-factor across a user overwrite and key the prompt to the submitted email Co-Authored-By: Claude Opus 5.5 * fix: snapshot totp in the overwrite delete and audit wrong two-factor codes Co-Authored-By: Claude Opus 5.5 * feat: move two-factor to ee, add recovery codes, encrypt secrets, db-backed limit Co-Authored-By: Claude Opus 5.5 * fix: refuse a two-factor reset for an account without one Co-Authored-By: Claude Opus 5.5 * fix: serialize two-factor races with key rotation and ce enrollment Co-Authored-By: Claude Opus 5.5 * feat: argon2 recovery codes, otpauth link, totp field name, settings styling Co-Authored-By: Claude Opus 5.5 * fix: serialize totp setup with admins key rotation Co-Authored-By: Claude Opus 5.5 * feat: two-factor setup wizard that asks for the password Co-Authored-By: Claude Opus 5.5 * feat: ask for the two-factor code on its own login screen Co-Authored-By: Claude Opus 5.5 * feat: say two-factor is on with the recovery codes, red turn-off confirm Co-Authored-By: Claude Opus 5.5 * chore: update ee-repo-ref to 5456ade3c09011206acc20ab026dda49f15f9517 This commit updates the EE repository reference after PR #1005 was merged in windmill-ee-private. Previous ee-repo-ref: 84c64720d625ed5a41b6ff0851f9d9b568b31c0b New ee-repo-ref: 5456ade3c09011206acc20ab026dda49f15f9517 Automated by sync-ee-ref workflow. * feat: require two-factor authentication for password logins Co-Authored-By: Claude Opus 5.5 * chore: shorten the require two-factor setting description Co-Authored-By: Claude Opus 5.5 * fix: ignore a login submit while one is in flight Co-Authored-By: Claude Opus 5.5 * docs: note that enrollment at login trusts the password alone Co-Authored-By: Claude Opus 5.5 * chore: point OAuth and SAML users to the identity provider for 2FA Co-Authored-By: Claude Opus 5.5 * fix: finish the root account swap when two-factor is required Co-Authored-By: Claude Opus 5.5 * feat: email the owner when their two-factor settings change Co-Authored-By: Claude Opus 5.5 * feat: recommend two-factor for the root account in instance setup Co-Authored-By: Claude Opus 5.5 * feat: offer two-factor setup on the login card after instance setup Co-Authored-By: Claude Opus 5.5 * feat: stop renewing sessions without two-factor once it is required Co-Authored-By: Claude Opus 5.5 * feat: show a user's two-factor status in the superadmin editor Co-Authored-By: Claude Opus 5.5 * feat: show two-factor in the instance users table Co-Authored-By: Claude Opus 5.5 * perf: load the two-factor setup screens on demand in the login card Co-Authored-By: Claude Opus 5.5 * chore: update ee-repo-ref to 526e8ad937cc09cdbd36f06434e2a0cee9e575bb This commit updates the EE repository reference after PR #1021 was merged in windmill-ee-private. Previous ee-repo-ref: 9c14ad5e266144bd8f21eee9d9514570d5c9fbef New ee-repo-ref: 526e8ad937cc09cdbd36f06434e2a0cee9e575bb Automated by sync-ee-ref workflow. --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: windmill-internal-app[bot] Co-authored-by: Ruben Fiszel --- ...2aa1fa5a76623cf2e7b75774435cdac9720d0.json | 28 ++ ...a4a4eb82c330c9838c8358d1067e6a6dc05dd.json | 20 ++ ...bdc0e1934d67d3f2b14047d434b77d370af21.json | 22 -- backend/ee-repo-ref.txt | 2 +- backend/src/main.rs | 37 ++- backend/src/monitor.rs | 22 +- backend/windmill-api-users/src/totp.rs | 22 +- backend/windmill-api-users/src/totp_oss.rs | 43 ++- backend/windmill-api-users/src/users.rs | 312 ++++++++++++------ backend/windmill-api/openapi.yaml | 112 +++++++ .../windmill-common/src/global_settings.rs | 2 + docs/auth-surface.md | 16 + .../lib/components/InstanceNameEditor.svelte | 43 ++- frontend/src/lib/components/Login.svelte | 164 ++++++++- .../components/SuperadminSettingsInner.svelte | 30 +- .../src/lib/components/instanceSettings.ts | 11 + .../settings/TotpAuthenticator.svelte | 28 ++ .../lib/components/settings/TotpModal.svelte | 50 +-- .../settings/TotpRecoveryCodes.svelte | 37 +++ .../settings/UserInfoSettings.svelte | 17 +- frontend/src/lib/loginError.ts | 3 + .../(user)/instance_settings/+page.svelte | 60 +++- .../(logged)/user/(user)/login/+page.svelte | 2 + frontend/src/routes/(root)/+layout.svelte | 26 +- 24 files changed, 864 insertions(+), 245 deletions(-) create mode 100644 backend/.sqlx/query-235d480efa2a0d8ea0a530454a52aa1fa5a76623cf2e7b75774435cdac9720d0.json create mode 100644 backend/.sqlx/query-31c9a45b4db0ceca15338aa9e95a4a4eb82c330c9838c8358d1067e6a6dc05dd.json delete mode 100644 backend/.sqlx/query-ccc49a2a6e11f874825365de758bdc0e1934d67d3f2b14047d434b77d370af21.json create mode 100644 frontend/src/lib/components/settings/TotpAuthenticator.svelte create mode 100644 frontend/src/lib/components/settings/TotpRecoveryCodes.svelte diff --git a/backend/.sqlx/query-235d480efa2a0d8ea0a530454a52aa1fa5a76623cf2e7b75774435cdac9720d0.json b/backend/.sqlx/query-235d480efa2a0d8ea0a530454a52aa1fa5a76623cf2e7b75774435cdac9720d0.json new file mode 100644 index 0000000000..92fffa33a5 --- /dev/null +++ b/backend/.sqlx/query-235d480efa2a0d8ea0a530454a52aa1fa5a76623cf2e7b75774435cdac9720d0.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT super_admin, login_type = 'password' AND totp_secret IS NULL AS \"lacks_totp!\"\n FROM password WHERE email = $1 AND disabled = false", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "super_admin", + "type_info": "Bool" + }, + { + "ordinal": 1, + "name": "lacks_totp!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + false, + null + ] + }, + "hash": "235d480efa2a0d8ea0a530454a52aa1fa5a76623cf2e7b75774435cdac9720d0" +} diff --git a/backend/.sqlx/query-31c9a45b4db0ceca15338aa9e95a4a4eb82c330c9838c8358d1067e6a6dc05dd.json b/backend/.sqlx/query-31c9a45b4db0ceca15338aa9e95a4a4eb82c330c9838c8358d1067e6a6dc05dd.json new file mode 100644 index 0000000000..16077a65f4 --- /dev/null +++ b/backend/.sqlx/query-31c9a45b4db0ceca15338aa9e95a4a4eb82c330c9838c8358d1067e6a6dc05dd.json @@ -0,0 +1,20 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT email FROM password WHERE totp_secret IS NOT NULL", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "email", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + false + ] + }, + "hash": "31c9a45b4db0ceca15338aa9e95a4a4eb82c330c9838c8358d1067e6a6dc05dd" +} diff --git a/backend/.sqlx/query-ccc49a2a6e11f874825365de758bdc0e1934d67d3f2b14047d434b77d370af21.json b/backend/.sqlx/query-ccc49a2a6e11f874825365de758bdc0e1934d67d3f2b14047d434b77d370af21.json deleted file mode 100644 index a9348dfa8b..0000000000 --- a/backend/.sqlx/query-ccc49a2a6e11f874825365de758bdc0e1934d67d3f2b14047d434b77d370af21.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "SELECT super_admin FROM password WHERE email = $1 AND disabled = false", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "super_admin", - "type_info": "Bool" - } - ], - "parameters": { - "Left": [ - "Text" - ] - }, - "nullable": [ - false - ] - }, - "hash": "ccc49a2a6e11f874825365de758bdc0e1934d67d3f2b14047d434b77d370af21" -} diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index c30483151d..bdc3c2f5be 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -b3c5cbb7edcc42f3db92865896d472cdd8842cf9 +526e8ad937cc09cdbd36f06434e2a0cee9e575bb diff --git a/backend/src/main.rs b/backend/src/main.rs index db5abf21d2..7913249f80 100644 --- a/backend/src/main.rs +++ b/backend/src/main.rs @@ -61,14 +61,15 @@ use windmill_common::{ OAUTH_SETTING, OTEL_SETTING, OTEL_TRACES_RETENTION_SECS_SETTING, OTEL_TRACING_PROXY_SETTING, PIP_INDEX_URL_SETTING, POWERSHELL_REPO_PAT_SETTING, POWERSHELL_REPO_URL_SETTING, PREVIEW_TAGS_OVERRIDE_SETTING, REQUEST_SIZE_LIMIT_SETTING, - REQUIRE_PREEXISTING_USER_FOR_OAUTH_SETTING, RESTART_COORDINATION_SETTING, - RETENTION_PERIOD_SECS_OVERRIDES_SETTING, RETENTION_PERIOD_SECS_SETTING, RUBY_REPOS_SETTING, - SAML_METADATA_SETTING, SANDBOX_IMAGE_CACHE_MAX_MB_SETTING, - SANDBOX_IMAGE_DEFAULT_REGISTRY_SETTING, SANDBOX_IMAGE_MAX_SIZE_MB_SETTING, - SANDBOX_IMAGE_PULL_POLICY_SETTING, SANDBOX_REGISTRY_AUTH_SETTING, SCIM_TOKEN_SETTING, - SERVICE_LOG_RETENTION_SECS_SETTING, SMTP_SETTING, STORE_AUDIT_LOGS_S3_SETTING, - SYNC_HUB_RESOURCE_TYPES_DAILY_SETTING, TEAMS_SETTING, TIMEOUT_WAIT_RESULT_SETTING, - UV_EXCLUDE_NEWER_SETTING, UV_INDEX_STRATEGY_SETTING, UV_PYTHON_INSTALL_MIRROR_SETTING, + REQUIRE_PREEXISTING_USER_FOR_OAUTH_SETTING, REQUIRE_TOTP_SETTING, + RESTART_COORDINATION_SETTING, RETENTION_PERIOD_SECS_OVERRIDES_SETTING, + RETENTION_PERIOD_SECS_SETTING, RUBY_REPOS_SETTING, SAML_METADATA_SETTING, + SANDBOX_IMAGE_CACHE_MAX_MB_SETTING, SANDBOX_IMAGE_DEFAULT_REGISTRY_SETTING, + SANDBOX_IMAGE_MAX_SIZE_MB_SETTING, SANDBOX_IMAGE_PULL_POLICY_SETTING, + SANDBOX_REGISTRY_AUTH_SETTING, SCIM_TOKEN_SETTING, SERVICE_LOG_RETENTION_SECS_SETTING, + SMTP_SETTING, STORE_AUDIT_LOGS_S3_SETTING, SYNC_HUB_RESOURCE_TYPES_DAILY_SETTING, + TEAMS_SETTING, TIMEOUT_WAIT_RESULT_SETTING, UV_EXCLUDE_NEWER_SETTING, + UV_INDEX_STRATEGY_SETTING, UV_PYTHON_INSTALL_MIRROR_SETTING, WORKSPACE_FAIRNESS_DURATION_SECS_SETTING, WORKSPACE_FAIRNESS_ENABLED_SETTING, WORKSPACE_FAIRNESS_MAX_PERCENT_SETTING, WORKSPACE_FAIRNESS_MIN_TOTAL_SETTING, WORKSPACE_MAX_QUEUED_JOBS_SETTING, WORKSPACE_REGISTRIES_SETTING, @@ -136,14 +137,15 @@ use crate::monitor::{ load_dev_workspace_isolation_skip_non_dev_forks, load_dev_workspace_tag_suffix, load_disable_password_login, load_fork_workspace_tag_append_fork_suffix, load_keep_job_dir, load_mcp_disable_token_query_param, load_metrics_debug_enabled, load_preview_tags_override, - load_require_preexisting_user, load_retention_period_overrides, load_tag_per_workspace_enabled, - load_tag_per_workspace_workspaces, load_workspace_fairness_duration_secs, - load_workspace_fairness_enabled, load_workspace_fairness_max_percent, - load_workspace_fairness_min_total, load_workspace_max_queued_jobs, monitor_db, - reload_app_workspaced_route_setting, reload_audit_log_retention_days_setting, - reload_base_url_setting, reload_bun_install_min_release_age_setting, - reload_bunfig_install_scopes_setting, reload_cargo_registries_setting, - reload_critical_alert_mute_ui_setting, reload_critical_alert_mute_zombie_job_restart_setting, + load_require_preexisting_user, load_require_totp, load_retention_period_overrides, + load_tag_per_workspace_enabled, load_tag_per_workspace_workspaces, + load_workspace_fairness_duration_secs, load_workspace_fairness_enabled, + load_workspace_fairness_max_percent, load_workspace_fairness_min_total, + load_workspace_max_queued_jobs, monitor_db, reload_app_workspaced_route_setting, + reload_audit_log_retention_days_setting, reload_base_url_setting, + reload_bun_install_min_release_age_setting, reload_bunfig_install_scopes_setting, + reload_cargo_registries_setting, reload_critical_alert_mute_ui_setting, + reload_critical_alert_mute_zombie_job_restart_setting, reload_critical_alerts_on_token_expiry_setting, reload_critical_error_channels_setting, reload_extra_pip_index_url_setting, reload_http_route_default_allowed_origins_setting, reload_http_route_workspaced_route_setting, reload_hub_api_secret_setting, @@ -2070,6 +2072,9 @@ async fn process_notify_event( DISABLE_PASSWORD_LOGIN_SETTING => { load_disable_password_login(db).await; } + REQUIRE_TOTP_SETTING => { + load_require_totp(db).await; + } windmill_common::global_settings::WORKSPACE_ROLES_SETTING => { windmill_common::roles::invalidate_all_roles_cache(); } diff --git a/backend/src/monitor.rs b/backend/src/monitor.rs index f25182b30a..9e1cb776dd 100644 --- a/backend/src/monitor.rs +++ b/backend/src/monitor.rs @@ -75,8 +75,8 @@ use windmill_common::{ OTEL_SETTING, OTEL_TRACES_RETENTION_SECS_SETTING, OTEL_TRACING_PROXY_SETTING, PIP_INDEX_URL_SETTING, POWERSHELL_REPO_PAT_SETTING, POWERSHELL_REPO_URL_SETTING, PREVIEW_TAGS_OVERRIDE_SETTING, REQUEST_SIZE_LIMIT_SETTING, - REQUIRE_PREEXISTING_USER_FOR_OAUTH_SETTING, RETENTION_PERIOD_SECS_SETTING, - SAML_METADATA_SETTING, SANDBOX_IMAGE_CACHE_MAX_MB_SETTING, + REQUIRE_PREEXISTING_USER_FOR_OAUTH_SETTING, REQUIRE_TOTP, REQUIRE_TOTP_SETTING, + RETENTION_PERIOD_SECS_SETTING, SAML_METADATA_SETTING, SANDBOX_IMAGE_CACHE_MAX_MB_SETTING, SANDBOX_IMAGE_DEFAULT_REGISTRY_SETTING, SANDBOX_IMAGE_MAX_SIZE_MB_SETTING, SANDBOX_IMAGE_PULL_POLICY_SETTING, SANDBOX_REGISTRY_AUTH_SETTING, SCIM_TOKEN_SETTING, SERVICE_LOG_RETENTION_SECS_SETTING, SMTP_SETTING, STORE_AUDIT_LOGS_S3_SETTING, @@ -408,6 +408,9 @@ pub async fn initial_load( pass.setting(DISABLE_PASSWORD_LOGIN_SETTING, false, |v| async move { apply_disable_password_login(v) }); + pass.setting(REQUIRE_TOTP_SETTING, false, |v| async move { + apply_require_totp(v) + }); pass.action(async move { if let Err(e) = reload_critical_alerts_on_db_oversize(db).await { tracing::error!( @@ -1790,6 +1793,21 @@ pub async fn load_disable_password_login(db: &DB) { }; } +pub async fn load_require_totp(db: &DB) { + match load_value_from_global_settings(db, REQUIRE_TOTP_SETTING).await { + Ok(v) => apply_require_totp(v), + Err(e) => tracing::error!("Error loading require_totp setting: {e:#}"), + }; +} + +pub fn apply_require_totp(value: Option) { + match value { + Some(serde_json::Value::Bool(t)) => REQUIRE_TOTP.store(t, Ordering::Relaxed), + None => REQUIRE_TOTP.store(false, Ordering::Relaxed), + _ => (), + }; +} + pub fn apply_disable_password_login(value: Option) { match value { Some(serde_json::Value::Bool(t)) => DISABLE_PASSWORD_LOGIN.store(t, Ordering::Relaxed), diff --git a/backend/windmill-api-users/src/totp.rs b/backend/windmill-api-users/src/totp.rs index 97bcde4eb8..c2926a57ad 100644 --- a/backend/windmill-api-users/src/totp.rs +++ b/backend/windmill-api-users/src/totp.rs @@ -1,9 +1,27 @@ //! Native TOTP second factor for password logins. The implementation is in `totp_ee`. #[cfg(feature = "private")] -pub use crate::totp_ee::{check_login_code, service}; +pub use crate::totp_ee::{ + begin_setup, check_login_code, finish_setup, notify, service, TotpChange, +}; #[cfg(not(feature = "private"))] -pub use crate::totp_oss::{check_login_code, service}; +pub use crate::totp_oss::{ + begin_setup, check_login_code, finish_setup, notify, service, TotpChange, +}; pub const TOTP_REQUIRED: &str = "Two-factor code required"; pub const TOTP_INVALID: &str = "Invalid two-factor code"; +pub const TOTP_SETUP_REQUIRED: &str = "Two-factor setup required"; + +#[derive(serde::Serialize)] +pub struct TotpSetup { + pub secret: String, + pub otpauth_url: String, +} + +/// Whether every password login must have a second factor. Enterprise only: a build without +/// it lets a single account enroll, so it could not satisfy the requirement. +pub fn required() -> bool { + cfg!(all(feature = "enterprise", feature = "private")) + && windmill_common::global_settings::REQUIRE_TOTP.load(std::sync::atomic::Ordering::Relaxed) +} diff --git a/backend/windmill-api-users/src/totp_oss.rs b/backend/windmill-api-users/src/totp_oss.rs index a4945520a4..e7557887f2 100644 --- a/backend/windmill-api-users/src/totp_oss.rs +++ b/backend/windmill-api-users/src/totp_oss.rs @@ -1,3 +1,13 @@ +#[cfg(not(feature = "private"))] +use windmill_common::error::{Error, Result}; + +#[cfg(not(feature = "private"))] +fn unavailable() -> Result { + Err(Error::BadRequest( + "Two-factor authentication requires a build with the private feature".to_string(), + )) +} + #[cfg(not(feature = "private"))] pub fn service() -> axum::Router { axum::Router::new() @@ -9,8 +19,33 @@ pub async fn check_login_code( _db: &windmill_common::DB, _email: &str, _code: &str, -) -> windmill_common::error::Result { - Err(windmill_common::error::Error::BadRequest( - "Two-factor authentication requires a build with the private feature".to_string(), - )) +) -> Result { + unavailable() } + +#[cfg(not(feature = "private"))] +pub async fn begin_setup( + _db: &windmill_common::DB, + _email: &str, +) -> Result { + unavailable() +} + +#[cfg(not(feature = "private"))] +pub async fn finish_setup( + _tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, + _db: &windmill_common::DB, + _email: &str, + _code: &str, + _author: &windmill_common::audit::AuditAuthor, +) -> Result>> { + unavailable() +} + +#[cfg(not(feature = "private"))] +pub enum TotpChange { + Enabled, +} + +#[cfg(not(feature = "private"))] +pub fn notify(_email: &str, _change: TotpChange) {} diff --git a/backend/windmill-api-users/src/users.rs b/backend/windmill-api-users/src/users.rs index 6c78b510ec..883a6d3195 100644 --- a/backend/windmill-api-users/src/users.rs +++ b/backend/windmill-api-users/src/users.rs @@ -189,6 +189,8 @@ pub fn global_service() -> Router { pub fn make_unauthed_service() -> Router { Router::new() .route("/login", post(login)) + .route("/login/totp/setup", post(login_totp_setup)) + .route("/login/totp/enable", post(login_totp_enable)) .route("/logout", post(logout).get(logout)) .route("/is_first_time_setup", get(is_first_time_setup)) .route("/request_password_reset", post(request_password_reset)) @@ -2920,6 +2922,124 @@ async fn set_login_type( )) } +struct PasswordAccount { + email: String, + super_admin: bool, + totp_enabled: bool, +} + +fn login_audit_author(email: &str) -> AuditAuthor { + AuditAuthor { + email: email.to_string(), + username: email.to_string(), + username_override: None, + token_prefix: None, + } +} + +/// The account a password login names, once its password matched, with the transaction the +/// login continues in. A mismatch and an unknown email fail alike, and count against the login +/// rate limit, which is checked before any connection is taken. +async fn verify_password_login<'c>( + db: &DB, + client_ip: Option, + argon2: &Argon2<'_>, + email: &str, + password: &str, +) -> Result<(Transaction<'c, Postgres>, PasswordAccount)> { + if windmill_common::global_settings::DISABLE_PASSWORD_LOGIN + .load(std::sync::atomic::Ordering::Relaxed) + { + return Err(Error::BadRequest( + "Password login is disabled on this instance".to_string(), + )); + } + + windmill_common::login_rate_limit::check_and_increment_login_attempt(client_ip, email)?; + + let mut tx = db.begin().await?; + let row: Option<(String, String, bool, bool)> = sqlx::query_as( + "SELECT email, password_hash, super_admin, totp_secret IS NOT NULL FROM password \ + WHERE email = $1 AND login_type = 'password' AND disabled = false", + ) + .bind(email) + .fetch_optional(&mut *tx) + .await?; + + match row { + Some((email, hash, super_admin, totp_enabled)) + if argon2.verify_password(password.as_bytes(), hash.as_str()).is_ok() => + { + Ok((tx, PasswordAccount { email, super_admin, totp_enabled })) + } + _ => { + audit_log( + &mut *tx, + &login_audit_author(email), + "users.login_failure", + ActionKind::Create, + "global", + None, + None, + ) + .await?; + windmill_common::login_rate_limit::record_login_failure(email); + Err(Error::BadRequest("Invalid login".to_string())) + } + } +} + +/// Audits a wrong two-factor code and commits, unlike a wrong password: the transaction holds +/// the wrong-code count, and a guessed code must leave a trace. +async fn reject_totp_code(mut tx: Transaction<'_, Postgres>, email: &str) -> Error { + let committed = async { + audit_log( + &mut *tx, + &login_audit_author(email), + "users.login_failure", + ActionKind::Create, + "global", + None, + Some([("reason", "invalid_totp_code")].into()), + ) + .await?; + tx.commit().await?; + Ok::<_, Error>(()) + } + .await; + if let Err(e) = committed { + return e; + } + windmill_common::login_rate_limit::record_login_failure(email); + Error::BadRequest(crate::totp::TOTP_INVALID.to_string()) +} + +async fn start_password_session( + mut tx: Transaction<'_, Postgres>, + account: &PasswordAccount, + cookies: Cookies, +) -> Result { + let token = + create_session_token(&account.email, account.super_admin, None, false, &mut tx, cookies) + .await?; + let audit_author = AuditAuthor { + token_prefix: Some(safe_token_prefix(&token)), + ..login_audit_author(&account.email) + }; + audit_log( + &mut *tx, + &audit_author, + "users.login", + ActionKind::Create, + "global", + Some(&truncate_token(&token)), + None, + ) + .await?; + tx.commit().await?; + Ok(token) +} + #[allow(unreachable_code, unused_variables)] async fn login( ClientIp(client_ip): ClientIp, @@ -2936,112 +3056,92 @@ async fn login( } let email = email.to_lowercase(); + let (mut tx, account) = verify_password_login(&db, client_ip, &argon2, &email, &password).await?; - if windmill_common::global_settings::DISABLE_PASSWORD_LOGIN - .load(std::sync::atomic::Ordering::Relaxed) - { + // Asked only once the password matched, so whether an account has a second factor is not + // disclosed to someone who does not know its password. + if account.totp_enabled { + let Some(code) = totp_code.filter(|c| !c.trim().is_empty()) else { + return Err(Error::BadRequest(crate::totp::TOTP_REQUIRED.to_string())); + }; + if !crate::totp::check_login_code(&mut tx, &db, &account.email, &code).await? { + return Err(reject_totp_code(tx, &account.email).await); + } + } else if crate::totp::required() { + return Err(Error::BadRequest(crate::totp::TOTP_SETUP_REQUIRED.to_string())); + } + start_password_session(tx, &account, cookies).await +} + +/// The account a login-time enrollment is for: one without a second factor, on an instance +/// that requires it. Anyone else enrolls from their settings, inside a session. +async fn verify_login_enrollment<'c>( + db: &DB, + client_ip: Option, + argon2: &Argon2<'_>, + email: &str, + password: &str, +) -> Result<(Transaction<'c, Postgres>, PasswordAccount)> { + let (tx, account) = verify_password_login(db, client_ip, argon2, email, password).await?; + if account.totp_enabled || !crate::totp::required() { return Err(Error::BadRequest( - "Password login is disabled on this instance".to_string(), + "Two-factor setup at login is only for accounts that must enroll".to_string(), )); } + Ok((tx, account)) +} - windmill_common::login_rate_limit::check_and_increment_login_attempt(client_ip, &email)?; +#[derive(Deserialize)] +struct LoginTotpSetup { + email: String, + password: String, +} - let mut tx = db.begin().await?; - let audit_author = AuditAuthor { - email: email.clone(), - username: email.clone(), - username_override: None, - token_prefix: None, +async fn login_totp_setup( + ClientIp(client_ip): ClientIp, + Extension(db): Extension, + Extension(argon2): Extension>>, + Json(LoginTotpSetup { email, password }): Json, +) -> JsonResult { + let email = email.to_lowercase(); + let (tx, account) = verify_login_enrollment(&db, client_ip, &argon2, &email, &password).await?; + drop(tx); + Ok(Json(crate::totp::begin_setup(&db, &account.email).await?)) +} + +#[derive(Deserialize)] +struct LoginTotpEnable { + email: String, + password: String, + code: String, +} + +#[derive(Serialize)] +struct LoginRecoveryCodes { + recovery_codes: Vec, +} + +/// Turns the second factor on and starts the session in one step, so the account is never +/// left logged in without it. +async fn login_totp_enable( + ClientIp(client_ip): ClientIp, + cookies: Cookies, + Extension(db): Extension, + Extension(argon2): Extension>>, + Json(LoginTotpEnable { email, password, code }): Json, +) -> JsonResult { + let email = email.to_lowercase(); + let (mut tx, account) = + verify_login_enrollment(&db, client_ip, &argon2, &email, &password).await?; + let author = login_audit_author(&account.email); + let Some(recovery_codes) = + crate::totp::finish_setup(&mut tx, &db, &account.email, &code, &author).await? + else { + return Err(reject_totp_code(tx, &account.email).await); }; - let email_w_h: Option<(String, String, bool, Option)> = sqlx::query_as( - "SELECT email, password_hash, super_admin, totp_secret FROM password WHERE email = $1 \ - AND login_type = 'password' AND disabled = false", - ) - .bind(&email) - .fetch_optional(&mut *tx) - .await?; - - if let Some((email, hash, super_admin, totp_secret)) = email_w_h { - if argon2 - .verify_password(password.as_bytes(), hash.as_str()) - .is_err() - { - audit_log( - &mut *tx, - &audit_author, - "users.login_failure", - ActionKind::Create, - "global", - None, - None, - ) - .await?; - windmill_common::login_rate_limit::record_login_failure(&email); - Err(Error::BadRequest("Invalid login".to_string())) - } else { - // Asked only once the password matched, so whether an account has a second - // factor is not disclosed to someone who does not know its password. - if totp_secret.is_some() { - let Some(code) = totp_code.filter(|c| !c.trim().is_empty()) else { - return Err(Error::BadRequest(crate::totp::TOTP_REQUIRED.to_string())); - }; - if !crate::totp::check_login_code(&mut tx, &db, &email, &code).await? { - // Committed, unlike a wrong password: it holds the wrong-code count, and a - // guessed code must leave a trace. - audit_log( - &mut *tx, - &audit_author, - "users.login_failure", - ActionKind::Create, - "global", - None, - Some([("reason", "invalid_totp_code")].into()), - ) - .await?; - tx.commit().await?; - windmill_common::login_rate_limit::record_login_failure(&email); - return Err(Error::BadRequest(crate::totp::TOTP_INVALID.to_string())); - } - } - let token = - create_session_token(&email, super_admin, None, false, &mut tx, cookies).await?; - - let audit_author = AuditAuthor { - email: email.clone(), - username: email.clone(), - username_override: None, - token_prefix: Some(safe_token_prefix(&token)), - }; - - audit_log( - &mut *tx, - &audit_author, - "users.login", - ActionKind::Create, - "global", - Some(&truncate_token(&token)), - None, - ) - .await?; - - tx.commit().await?; - Ok(token) - } - } else { - audit_log( - &mut *tx, - &audit_author, - "users.login_failure", - ActionKind::Create, - "global", - None, - None, - ) - .await?; - windmill_common::login_rate_limit::record_login_failure(&email); - Err(Error::BadRequest("Invalid login".to_string())) - } + start_password_session(tx, &account, cookies).await?; + crate::totp::notify(&account.email, crate::totp::TotpChange::Enabled); + Ok(Json(LoginRecoveryCodes { recovery_codes })) } #[derive(Deserialize)] @@ -3126,13 +3226,19 @@ async fn refresh_token( let mut tx = db.begin().await?; - let super_admin = sqlx::query_scalar!( - "SELECT super_admin FROM password WHERE email = $1 AND disabled = false", + let account = sqlx::query!( + "SELECT super_admin, login_type = 'password' AND totp_secret IS NULL AS \"lacks_totp!\" + FROM password WHERE email = $1 AND disabled = false", &authed.email ) .fetch_optional(&mut *tx) - .await? - .unwrap_or(false); + .await?; + // A session from before the instance required a second factor is not renewed, so it ends + // within one session lifetime and the next login goes through the setup. + if crate::totp::required() && account.as_ref().is_some_and(|a| a.lacks_totp) { + return Err(Error::BadRequest(crate::totp::TOTP_SETUP_REQUIRED.to_string())); + } + let super_admin = account.is_some_and(|a| a.super_admin); let new_token = create_session_token( &authed.email, diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index 831a5b8775..dcbb421ddf 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -466,6 +466,89 @@ paths: schema: type: string + /auth/login/totp/setup: + post: + security: [] + summary: start the two-factor setup an instance requires, before a session exists + operationId: loginTotpSetup + tags: + - user + requestBody: + description: the credentials of a password account that has no second factor yet + required: true + content: + application/json: + schema: + type: object + properties: + email: + type: string + password: + type: string + required: + - email + - password + responses: + "200": + description: the secret to register in an authenticator app + content: + application/json: + schema: + type: object + properties: + secret: + type: string + otpauth_url: + type: string + required: + - secret + - otpauth_url + + /auth/login/totp/enable: + post: + security: [] + summary: turn on the second factor started by loginTotpSetup and log in + operationId: loginTotpEnable + tags: + - user + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + email: + type: string + password: + type: string + code: + type: string + required: + - email + - password + - code + responses: + "200": + description: > + Two-factor authentication is on and the session cookie is set. Returns + the recovery codes, shown only once. + headers: + Set-Cookie: + schema: + type: string + content: + application/json: + schema: + type: object + properties: + recovery_codes: + type: array + items: + type: string + required: + - recovery_codes + /auth/logout: post: security: [] @@ -710,8 +793,12 @@ paths: properties: enabled: type: boolean + required: + type: boolean + description: whether the instance requires two-factor authentication for password logins required: - enabled + - required /users/totp/setup: post: @@ -858,6 +945,31 @@ paths: schema: type: string + /users/totp/enabled: + get: + summary: list the users who have two-factor authentication (require super admin) + operationId: listTotpEnabledUsers + tags: + - user + responses: + "200": + description: the emails of the users with two-factor authentication on + content: + application/json: + schema: + type: object + properties: + required: + type: boolean + description: whether the instance requires two-factor authentication for password logins + users: + type: array + items: + type: string + required: + - required + - users + /users/set_password_of/{user}: post: summary: set password for a specific user (require super admin) diff --git a/backend/windmill-common/src/global_settings.rs b/backend/windmill-common/src/global_settings.rs index 4792d02e63..b1e8e924ce 100644 --- a/backend/windmill-common/src/global_settings.rs +++ b/backend/windmill-common/src/global_settings.rs @@ -109,6 +109,7 @@ pub const HUB_API_SECRET_SETTING: &str = "hub_api_secret"; pub const AUTOMATE_USERNAME_CREATION_SETTING: &str = "automate_username_creation"; pub const DISABLE_WORKSPACE_INVITE_EMAILS_SETTING: &str = "disable_workspace_invite_emails"; pub const DISABLE_PASSWORD_LOGIN_SETTING: &str = "disable_password_login"; +pub const REQUIRE_TOTP_SETTING: &str = "require_totp"; /// Refuse `?token=` on the MCP endpoints, leaving the `Authorization` header as the only way /// in. A URL-borne credential ends up in browser history, proxy logs and referrers, so an /// instance that cares sends MCP clients through the OAuth flow instead. @@ -584,6 +585,7 @@ use std::sync::atomic::AtomicBool; lazy_static::lazy_static! { pub static ref HTTP_ROUTE_WORKSPACED_ROUTE: AtomicBool = AtomicBool::new(false); pub static ref DISABLE_PASSWORD_LOGIN: AtomicBool = AtomicBool::new(false); + pub static ref REQUIRE_TOTP: AtomicBool = AtomicBool::new(false); pub static ref MCP_DISABLE_TOKEN_QUERY_PARAM: AtomicBool = AtomicBool::new(false); /// `None` when [`MCP_EXTERNAL_IDP_SETTING`] is unset or has no issuer. pub static ref MCP_EXTERNAL_IDP: arc_swap::ArcSwapOption = diff --git a/docs/auth-surface.md b/docs/auth-surface.md index fd1ab6d1be..87a92717d9 100644 --- a/docs/auth-surface.md +++ b/docs/auth-surface.md @@ -43,6 +43,22 @@ Symbols, not line numbers, are cited: they drift less. (`set_encryption_key`); a secret left under an old key locks its user out. The global user export leaves it out, as its files end up in git: an overwrite keeps the second factor of every account it reinstates, and a push to another instance arrives without one. + The `require_totp` instance setting (enterprise only, `totp::required`) makes a password login + without a second factor answer "Two-factor setup required" once the password matched. The + account then enrolls before it has any session, through `POST /auth/login/totp/setup` and + `/auth/login/totp/enable`, which take the password again on each call; `enable` turns the + factor on and mints the session in one transaction, so no session exists without it. While + required, `disable` is refused; a superadmin `reset` is not, and sends the user back through + enrollment. Sessions minted before the setting was turned on stay valid until they expire, + but `refresh_token` no longer renews one for an account without a second factor, so it ends + within `MAX_SESSION_VALIDITY_SECONDS` and the next login goes through the setup. The app + warns in its last 30 minutes, and enrolling from the settings restores renewal. + Until an account enrolls, its password is its only factor: whoever logs in with it first + enrolls their own authenticator, so a password already stolen is not protected, and the owner + needs a superadmin `reset` to recover. Turning the factor on (in settings or at login), off, + regenerating its recovery codes and a superadmin `reset` each email the account's owner when + SMTP is set up (`totp_ee::notify`), after the change has committed, so a change made with a + stolen password or session reaches the owner. - **Sessions** are `token` rows with `label='session'` plus the HttpOnly `token` cookie, minted only by `create_session_token` (`windmill-api-users/src/users.rs`). `GET /api/users/refresh_token` mints one for any non-job token but returns plain text, no redirect. diff --git a/frontend/src/lib/components/InstanceNameEditor.svelte b/frontend/src/lib/components/InstanceNameEditor.svelte index 14d8210e4f..6c7db11bf0 100644 --- a/frontend/src/lib/components/InstanceNameEditor.svelte +++ b/frontend/src/lib/components/InstanceNameEditor.svelte @@ -18,6 +18,9 @@ username?: string | undefined automateUsernameCreation?: boolean login_type: string + /** Whether the user has two-factor authentication; the section shows only then. */ + totpEnabled?: boolean + totpRequired?: boolean } let { @@ -25,7 +28,9 @@ email, username = undefined, automateUsernameCreation = false, - login_type = $bindable() + login_type = $bindable(), + totpEnabled = false, + totpRequired = false }: Props = $props() let password: string = $state('') @@ -44,8 +49,9 @@ sendUserToast(`Password updated for ${email}`) } - async function resetTotp() { + async function removeTotp() { sendUserToast(await UserService.resetTotpOfUser({ user: email })) + dispatch('refresh') } async function saveLoginType() { @@ -177,22 +183,25 @@ Update login type -
-
Two-factor authentication
-
- Removes the user's authenticator, for when they lost access to it. They can set up a new - one from their user settings. + {#if totpEnabled} +
+
Two-factor authentication
+
+ For a user who lost their authenticator and recovery codes. {totpRequired + ? 'They set it up again at their next login.' + : 'They can set it up again from their user settings.'} +
+
- -
+ {/if}
{/snippet} diff --git a/frontend/src/lib/components/Login.svelte b/frontend/src/lib/components/Login.svelte index 068e79fa6b..0f32f4568c 100644 --- a/frontend/src/lib/components/Login.svelte +++ b/frontend/src/lib/components/Login.svelte @@ -46,7 +46,8 @@ loginErrorDetail, loginErrorMessage, TOTP_INVALID_MESSAGE, - TOTP_REQUIRED + TOTP_REQUIRED, + TOTP_SETUP_REQUIRED } from '$lib/loginError' import { parseAccountSettingsHash } from './sidebar/settings' import Badge from './common/badge/Badge.svelte' @@ -84,6 +85,9 @@ * same sign-in without this, which provisions them for real. Password login * ignores it: a guest has no stored credential to check. */ guestApp?: string | undefined + /** Once a password login succeeds, offer to set up two-factor authentication before + * leaving the card, for an account that has none. The user can skip it. */ + offerTotpSetup?: boolean } let { @@ -98,7 +102,8 @@ onLoginError = undefined, preview = undefined, onOptionsLoaded = undefined, - guestApp = undefined + guestApp = undefined, + offerTotpSetup = false }: Props = $props() // The harness never takes effect in a production bundle, whatever a caller passes. @@ -189,16 +194,37 @@ let showPassword = $state(false) let passwordField = $state(undefined) - // The account the server asked an authenticator code for. The code step replaces the form - // and resends the password kept here, so the server needs no half-logged-in state. + // The account the server asked an authenticator code for, or asked to set up two-factor + // authentication when the instance requires it. These steps replace the form and resend the + // password kept here, so the server needs no half-logged-in state. let totpFor = $state(undefined) let totpCode = $state('') let totpField = $state(undefined) let showTotp = $derived(totpFor !== undefined && totpFor === email) + let enrollSetup = $state<{ secret: string; otpauth_url: string } | undefined>(undefined) + // Kept across Back: asking the server again replaces the pending secret, and the QR code the + // user already scanned would stop working. + let issuedSetup: { email: string; setup: { secret: string; otpauth_url: string } } | undefined + let enrollCodes = $state(undefined) + // The setup was offered after a successful login, rather than required before one: a + // session exists, so it goes through the signed-in routes and can be skipped. + let enrollOptional = $state(false) + let enrollSaved = $state(false) + + async function openTotpStep(forEmail: string, setup?: { secret: string; otpauth_url: string }) { + formError = undefined + shake = false + totpFor = forEmail + totpCode = '' + enrollSetup = setup + await tick() + totpField?.focus() + } async function leaveTotp() { totpFor = undefined totpCode = '' + enrollSetup = undefined formError = undefined // The swapped-in markup would otherwise replay a shake left on from a failed attempt. shake = false @@ -267,7 +293,20 @@ displayName: string } + // One submit at a time: a second setup request would replace the pending secret, and the + // page could then show a QR code the server no longer accepts. + let submitting = false async function login(): Promise { + if (submitting) return + submitting = true + try { + await submitLogin() + } finally { + submitting = false + } + } + + async function submitLogin(): Promise { if (!email || !password) { if (!email && !password) failLogin('Enter both your email and password.') else if (!email) failLogin('Enter your email.', 'email') @@ -285,6 +324,11 @@ return } + if (showTotp && enrollSetup) { + await enableTotpAtLogin() + return + } + const requestBody = { email, password, @@ -302,13 +346,24 @@ // previous account must not be served to this one. noteSessionEmail(email) } catch (err) { - if (loginErrorDetail(err) === TOTP_REQUIRED) { - formError = undefined - shake = false - totpFor = requestBody.email - totpCode = '' - await tick() - totpField?.focus() + const detail = loginErrorDetail(err) + if (detail === TOTP_REQUIRED) { + await openTotpStep(requestBody.email) + return + } + if (detail === TOTP_SETUP_REQUIRED) { + try { + const setup = + issuedSetup?.email === requestBody.email + ? issuedSetup.setup + : await UserService.loginTotpSetup({ + requestBody: { email: requestBody.email, password: requestBody.password } + }) + issuedSetup = { email: requestBody.email, setup } + await openTotpStep(requestBody.email, setup) + } catch (setupErr) { + failLogin(loginErrorMessage(setupErr), 'both', requestBody) + } return } const message = loginErrorMessage(err) @@ -316,6 +371,41 @@ return } + if (offerTotpSetup && !requestBody.totp_code) { + // Refused when the account already has a second factor, or by a build or edition + // that cannot give it one: the login then simply goes on. + const setup = await UserService.setupTotp({ + requestBody: { password: requestBody.password } + }).catch(() => undefined) + if (setup) { + enrollOptional = true + await openTotpStep(requestBody.email, setup) + return + } + } + + await finishLogin() + } + + // Turns the second factor on and, when it was required, starts the session in the same + // request; the recovery codes it returns are shown before leaving the page. + async function enableTotpAtLogin(): Promise { + const requestBody = { email: email!, password: password!, code: totpCode } + try { + const { recovery_codes } = enrollOptional + ? await UserService.enableTotp({ requestBody: { code: totpCode } }) + : await UserService.loginTotpEnable({ requestBody }) + noteSessionEmail(requestBody.email) + formError = undefined + enrollSetup = undefined + enrollCodes = recovery_codes + } catch (err) { + const message = loginErrorMessage(err) + failLogin(message, message === TOTP_INVALID_MESSAGE ? 'totp' : 'both', requestBody) + } + } + + async function finishLogin(): Promise { formError = undefined rememberLoginMethod({ kind: 'password' }) @@ -798,17 +888,53 @@

Signing you in…

{/if} - {#if showTotp} + {#if enrollCodes}
-

Two-factor authentication

+

Two-factor authentication is on

- Enter the code from your authenticator app for {email}, or one of your recovery codes. + Logging in with your password now also asks for a code from your authenticator app.

+ + {#await import('./settings/TotpRecoveryCodes.svelte') then { default: TotpRecoveryCodes }} + + {/await} + +
+ {:else if showTotp} +
+
+ {#if enrollSetup && enrollOptional} +

Set up two-factor authentication

+

+ Protect {email} with a code from an authenticator app on top of its password. You can + also do this later from your user settings. +

+ {:else if enrollSetup} +

Set up two-factor authentication

+

+ This instance asks for a code from an authenticator app at each password login. Add + {email} to your app to continue. +

+ {:else} +

Two-factor authentication

+

+ Enter the code from your authenticator app for {email}, or one of your recovery codes. +

+ {/if} +
+ {#if enrollSetup} + {#await import('./settings/TotpAuthenticator.svelte') then { default: TotpAuthenticator }} + + {/await} + {/if}
- + {#if enrollOptional} + + {:else} + + {/if}
diff --git a/frontend/src/lib/components/SuperadminSettingsInner.svelte b/frontend/src/lib/components/SuperadminSettingsInner.svelte index 8924d2af77..5193a20942 100644 --- a/frontend/src/lib/components/SuperadminSettingsInner.svelte +++ b/frontend/src/lib/components/SuperadminSettingsInner.svelte @@ -99,8 +99,17 @@ let editWrappers: Record = $state({}) let activeOnly = $state(false) + // Who has two-factor authentication, fetched beside the list. Undefined on a build without + // two-factor support, which hides the column. + let totp = $state<{ required: boolean; users: Set } | undefined>(undefined) + async function listUsers(activeOnly: boolean): Promise { - users = await UserService.listUsersAsSuperAdmin({ perPage: 100000, activeOnly: activeOnly }) + const [list, enabled] = await Promise.all([ + UserService.listUsersAsSuperAdmin({ perPage: 100000, activeOnly: activeOnly }), + UserService.listTotpEnabledUsers().catch(() => undefined) + ]) + users = list + totp = enabled && { required: enabled.required, users: new Set(enabled.users) } } $effect(() => { @@ -439,6 +448,9 @@ {/if} Name Auth + {#if totp} + 2FA + {/if} {#if activeOnly} Kind {/if} @@ -512,6 +524,17 @@ >{login_type} + {#if totp} + + {#if login_type != 'password'} + – + {:else if totp.users.has(email)} + On + {:else} + Off + {/if} + + {/if} {#if activeOnly} @@ -681,6 +704,8 @@ value={name} {username} {email} + totpEnabled={totp?.users.has(email) ?? false} + totpRequired={totp?.required ?? false} on:refresh={() => { listUsers(activeOnly) }} @@ -770,7 +795,8 @@ +
+ + + They are shown only once. Keep them somewhere other than this device. + + diff --git a/frontend/src/lib/components/settings/UserInfoSettings.svelte b/frontend/src/lib/components/settings/UserInfoSettings.svelte index abb4fe1b20..ae7452d9f8 100644 --- a/frontend/src/lib/components/settings/UserInfoSettings.svelte +++ b/frontend/src/lib/components/settings/UserInfoSettings.svelte @@ -27,11 +27,14 @@ } let totpEnabled = $state(undefined) + let totpRequired = $state(false) let totpAction = $state(undefined) async function loadTotp(): Promise { // Builds without two-factor support do not serve the route: the section stays hidden. - totpEnabled = (await UserService.getTotpStatus().catch(() => undefined))?.enabled + const status = await UserService.getTotpStatus().catch(() => undefined) + totpEnabled = status?.enabled + totpRequired = status?.required ?? false } async function setPassword(): Promise { @@ -94,7 +97,9 @@ Two-factor authentication {totpEnabled - ? 'On. Logging in with your password also asks for a code from your authenticator app.' + ? totpRequired + ? 'On, as this instance requires. Logging in with your password also asks for a code from your authenticator app.' + : 'On. Logging in with your password also asks for a code from your authenticator app.' : 'Ask for a code from an authenticator app each time you log in with your password.'}
@@ -106,9 +111,11 @@ > New recovery codes - + {#if !totpRequired} + + {/if} {:else}
+ {#if totpAvailable && totpRequired} + + This instance requires it. After Set account & finish, you log in with this account + and set it up before getting in. + + {:else if totpAvailable} + + A superadmin account controls the whole instance. Protect it with a code from an + authenticator app on top of its password. + +
+ + {#if setUpTotp} +

+ After Set account & finish, you log in with this account and set it up right + away. You can skip it. +

+ {/if} +
+ {/if} diff --git a/frontend/src/routes/(root)/(logged)/user/(user)/login/+page.svelte b/frontend/src/routes/(root)/(logged)/user/(user)/login/+page.svelte index c88ba13115..c5beb92ef6 100644 --- a/frontend/src/routes/(root)/(logged)/user/(user)/login/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/user/(user)/login/+page.svelte @@ -28,6 +28,7 @@ const email = page.url.searchParams.get('email') ?? '' const password = page.url.searchParams.get('password') ?? '' const error = page.url.searchParams.get('error') ?? undefined + const offerTotpSetup = page.url.searchParams.get('setup_2fa') === '1' const rdFromStorage = localStorage.getItem('rd') || undefined if (rdFromStorage) { localStorage.removeItem('rd') @@ -172,6 +173,7 @@ {error} {password} {email} + {offerTotpSetup} autoRedirect={false} onOptionsLoaded={(options) => (hasThirdParty = options.hasThirdParty)} /> diff --git a/frontend/src/routes/(root)/+layout.svelte b/frontend/src/routes/(root)/+layout.svelte index dddf1671ac..a8589578c2 100644 --- a/frontend/src/routes/(root)/+layout.svelte +++ b/frontend/src/routes/(root)/+layout.svelte @@ -14,6 +14,8 @@ } from '$lib/stores' import { getUserExt } from '$lib/user' import { sendUserToast } from '$lib/toast' + import { loginErrorDetail, TOTP_SETUP_REQUIRED } from '$lib/loginError' + import { USER_SETTINGS_HASH } from '$lib/components/sidebar/settings' import { switchWorkspace } from '$lib/storeUtils' import { forgetForkParent, getRememberedForkParent } from '$lib/forkParentMemory' import { onDestroy, onMount } from 'svelte' @@ -206,6 +208,26 @@ } } + // The instance now requires two-factor authentication and this account has none: the + // session is no longer renewed. Said once per page, with the way to keep it. + let totpSetupWarned = false + async function refreshSession(): Promise { + try { + await UserService.refreshUserToken({ ifExpiringInLessThanS: 30 * 60 }) + } catch (e) { + if (loginErrorDetail(e) !== TOTP_SETUP_REQUIRED) throw e + if (totpSetupWarned) return + totpSetupWarned = true + sendUserToast( + 'This instance now requires two-factor authentication. Set it up to stay logged in: your session ends within 30 minutes otherwise.', + 'warning', + [{ label: 'Set up', callback: () => (location.hash = USER_SETTINGS_HASH) }], + undefined, + 30000 + ) + } + } + let interval: number | undefined = undefined onMount(() => { window.onunhandledrejection = (event: PromiseRejectionEvent) => { @@ -283,7 +305,7 @@ if (page.url.pathname != '/user/login') { setUserWorkspaceStore().catch((e) => console.error('could not load workspace list', e)) loadUser() - UserService.refreshUserToken({ ifExpiringInLessThanS: 30 * 60 }) + refreshSession() } let i = 0 @@ -295,7 +317,7 @@ if (i % 3 == 0) { console.debug('Refreshing user token') // every 15 minutes check if session token is expiring in less than 30min - await UserService.refreshUserToken({ ifExpiringInLessThanS: 30 * 60 }) + await refreshSession() } try {