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 <noreply@anthropic.com>

* fix: keep login field spacing when the code field shows

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: keep two-factor across a user overwrite and key the prompt to the submitted email

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: snapshot totp in the overwrite delete and audit wrong two-factor codes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: move two-factor to ee, add recovery codes, encrypt secrets, db-backed limit

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: refuse a two-factor reset for an account without one

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: serialize two-factor races with key rotation and ce enrollment

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: argon2 recovery codes, otpauth link, totp field name, settings styling

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: serialize totp setup with admins key rotation

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: two-factor setup wizard that asks for the password

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: ask for the two-factor code on its own login screen

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: say two-factor is on with the recovery codes, red turn-off confirm

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* 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 <noreply@anthropic.com>

* chore: shorten the require two-factor setting description

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: ignore a login submit while one is in flight

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: note that enrollment at login trusts the password alone

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore: point OAuth and SAML users to the identity provider for 2FA

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: finish the root account swap when two-factor is required

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: email the owner when their two-factor settings change

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: recommend two-factor for the root account in instance setup

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: offer two-factor setup on the login card after instance setup

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: stop renewing sessions without two-factor once it is required

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: show a user's two-factor status in the superadmin editor

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: show two-factor in the instance users table

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* perf: load the two-factor setup screens on demand in the login card

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* 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 <noreply@anthropic.com>
Co-authored-by: windmill-internal-app[bot] <windmill-internal-app[bot]@users.noreply.github.com>
Co-authored-by: Ruben Fiszel <ruben@windmill.dev>
This commit is contained in:
hugocasa
2026-11-27 18:23:17 +01:00
committed by GitHub
co-authored by Claude Opus 5.5 windmill-internal-app[bot] Ruben Fiszel
parent a32ae571ca
commit 8ec6beed3a
24 changed files with 864 additions and 245 deletions
@@ -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"
}
@@ -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"
}
@@ -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"
}
+1 -1
View File
@@ -1 +1 @@
b3c5cbb7edcc42f3db92865896d472cdd8842cf9
526e8ad937cc09cdbd36f06434e2a0cee9e575bb
+21 -16
View File
@@ -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();
}
+20 -2
View File
@@ -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<serde_json::Value>) {
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<serde_json::Value>) {
match value {
Some(serde_json::Value::Bool(t)) => DISABLE_PASSWORD_LOGIN.store(t, Ordering::Relaxed),
+20 -2
View File
@@ -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)
}
+39 -4
View File
@@ -1,3 +1,13 @@
#[cfg(not(feature = "private"))]
use windmill_common::error::{Error, Result};
#[cfg(not(feature = "private"))]
fn unavailable<T>() -> Result<T> {
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<bool> {
Err(windmill_common::error::Error::BadRequest(
"Two-factor authentication requires a build with the private feature".to_string(),
))
) -> Result<bool> {
unavailable()
}
#[cfg(not(feature = "private"))]
pub async fn begin_setup(
_db: &windmill_common::DB,
_email: &str,
) -> Result<crate::totp::TotpSetup> {
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<Option<Vec<String>>> {
unavailable()
}
#[cfg(not(feature = "private"))]
pub enum TotpChange {
Enabled,
}
#[cfg(not(feature = "private"))]
pub fn notify(_email: &str, _change: TotpChange) {}
+209 -103
View File
@@ -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<std::net::IpAddr>,
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<String> {
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<std::net::IpAddr>,
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<DB>,
Extension(argon2): Extension<Arc<Argon2<'_>>>,
Json(LoginTotpSetup { email, password }): Json<LoginTotpSetup>,
) -> JsonResult<crate::totp::TotpSetup> {
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<String>,
}
/// 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<DB>,
Extension(argon2): Extension<Arc<Argon2<'_>>>,
Json(LoginTotpEnable { email, password, code }): Json<LoginTotpEnable>,
) -> JsonResult<LoginRecoveryCodes> {
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<String>)> = 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,
+112
View File
@@ -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)
@@ -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<McpExternalIdp> =
+16
View File
@@ -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.
@@ -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
</Button>
</label>
<div class="block text-primary">
<div class="pb-1 text-xs font-semibold text-emphasis">Two-factor authentication</div>
<div class="text-2xs text-secondary mb-1">
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}
<div class="block text-primary">
<div class="pb-1 text-xs font-semibold text-emphasis">Two-factor authentication</div>
<div class="text-2xs text-secondary mb-1">
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.'}
</div>
<Button
unifiedSize="md"
variant="default"
buttonType="button"
btnClasses="mt-2"
onclick={removeTotp}
>
Remove two-factor
</Button>
</div>
<Button
unifiedSize="md"
variant="default"
buttonType="button"
btnClasses="mt-2"
onclick={resetTotp}
>
Reset two-factor
</Button>
</div>
{/if}
</div>
{/snippet}
</Popover>
+147 -17
View File
@@ -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<Password | undefined>(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<string | undefined>(undefined)
let totpCode = $state('')
let totpField = $state<TextInput | undefined>(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<string[] | undefined>(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<void> {
if (submitting) return
submitting = true
try {
await submitLogin()
} finally {
submitting = false
}
}
async function submitLogin(): Promise<void> {
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<void> {
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<void> {
formError = undefined
rememberLoginMethod({ kind: 'password' })
@@ -798,17 +888,53 @@
<p class="text-sm text-center text-secondary py-4">Signing you in…</p>
{/if}
{#if showTotp}
{#if enrollCodes}
<div class="space-y-4">
<div class="space-y-1">
<h2 class="text-sm font-semibold text-emphasis">Two-factor authentication</h2>
<h2 class="text-sm font-semibold text-emphasis">Two-factor authentication is on</h2>
<p class="text-xs text-secondary">
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.
</p>
</div>
<!-- Loaded on demand: the login page every visitor gets stays free of the QR encoder
and the code highlighter, which only these screens use. -->
{#await import('./settings/TotpRecoveryCodes.svelte') then { default: TotpRecoveryCodes }}
<TotpRecoveryCodes codes={enrollCodes} bind:saved={enrollSaved} />
{/await}
<Button onClick={finishLogin} variant="accent" unifiedSize="lg" disabled={!enrollSaved}>
Continue
</Button>
</div>
{:else if showTotp}
<div class="space-y-4">
<div class="space-y-1">
{#if enrollSetup && enrollOptional}
<h2 class="text-sm font-semibold text-emphasis">Set up two-factor authentication</h2>
<p class="text-xs text-secondary">
Protect {email} with a code from an authenticator app on top of its password. You can
also do this later from your user settings.
</p>
{:else if enrollSetup}
<h2 class="text-sm font-semibold text-emphasis">Set up two-factor authentication</h2>
<p class="text-xs text-secondary">
This instance asks for a code from an authenticator app at each password login. Add
{email} to your app to continue.
</p>
{:else}
<h2 class="text-sm font-semibold text-emphasis">Two-factor authentication</h2>
<p class="text-xs text-secondary">
Enter the code from your authenticator app for {email}, or one of your recovery codes.
</p>
{/if}
</div>
{#if enrollSetup}
{#await import('./settings/TotpAuthenticator.svelte') then { default: TotpAuthenticator }}
<TotpAuthenticator setup={enrollSetup} />
{/await}
{/if}
<div bind:this={fieldsEl} class="space-y-1 {shake ? 'motion-safe:animate-shake' : ''}">
<label for={totpId} class="block text-xs font-semibold text-emphasis">
Authentication code
{enrollSetup ? 'The 6-digit code your app shows' : 'Authentication code'}
</label>
<TextInput
bind:this={totpField}
@@ -828,10 +954,14 @@
</div>
<div class="space-y-2">
<Button onClick={login} variant="accent" unifiedSize="lg" disabled={!totpCode.trim()}>
Verify
{enrollOptional ? 'Turn on' : enrollSetup ? 'Turn on and log in' : 'Verify'}
</Button>
<div class="center-center">
<Button unifiedSize="sm" variant="subtle" onClick={leaveTotp}>Back</Button>
{#if enrollOptional}
<Button unifiedSize="sm" variant="subtle" onClick={finishLogin}>Skip for now</Button>
{:else}
<Button unifiedSize="sm" variant="subtle" onClick={leaveTotp}>Back</Button>
{/if}
</div>
</div>
</div>
@@ -99,8 +99,17 @@
let editWrappers: Record<string, HTMLDivElement> = $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<string> } | undefined>(undefined)
async function listUsers(activeOnly: boolean): Promise<void> {
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}
<Cell head>Name</Cell>
<Cell head>Auth</Cell>
{#if totp}
<Cell head>2FA</Cell>
{/if}
{#if activeOnly}
<Cell head>Kind</Cell>
{/if}
@@ -512,6 +524,17 @@
><span title={login_type} class="truncate block">{login_type}</span
></Cell
>
{#if totp}
<Cell>
{#if login_type != 'password'}
<span class="text-secondary">–</span>
{:else if totp.users.has(email)}
On
{:else}
<span class="text-secondary">Off</span>
{/if}
</Cell>
{/if}
{#if activeOnly}
<Cell>
<span>
@@ -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 @@
<Cell
colspan={5 +
(automateUsernameCreation ? 1 : 0) +
(activeOnly ? 1 : 0)}
(activeOnly ? 1 : 0) +
(totp ? 1 : 0)}
>
<Button
variant="subtle"
@@ -871,6 +871,17 @@ export const settings: Record<string, Setting[]> = {
fieldType: 'boolean',
storage: 'setting'
},
{
label: 'Require two-factor authentication',
description:
'Password logins ask for a code from an authenticator app. Users without two-factor authentication set it up at their next login.',
tooltip:
'Users cannot turn it off while this is on. OAuth and SAML logins are not affected: enforce two-factor authentication at the identity provider. Sessions that already exist are no longer renewed for users without it, so they end within 3 days by default.',
key: 'require_totp',
fieldType: 'boolean',
storage: 'setting',
ee_only: ''
},
{
label: 'Auto-login SSO provider',
description: 'Send the login page straight to this provider.',
@@ -0,0 +1,28 @@
<script lang="ts">
import { CopyButton } from '$lib/components/common'
import { renderSVG } from 'uqr'
interface Props {
setup: { secret: string; otpauth_url: string }
}
let { setup }: Props = $props()
</script>
<div class="flex flex-col gap-1">
<span class="text-xs text-secondary font-normal">
Scan this QR code with an authenticator app, or open it on this device.
</span>
<a
href={setup.otpauth_url}
aria-label="Add to an authenticator app"
class="w-40 h-40 bg-white p-1 rounded-md"
>
{@html renderSVG(setup.otpauth_url)}
</a>
<div class="flex flex-row flex-wrap gap-1 items-center text-2xs text-secondary font-normal">
Or enter this key manually:
<span class="font-mono text-emphasis break-all">{setup.secret}</span>
<CopyButton value={setup.secret} />
</div>
</div>
@@ -4,16 +4,13 @@
<script lang="ts">
import { UserService } from '$lib/gen'
import { Alert, Button, CopyButton } from '$lib/components/common'
import { Alert, Button } from '$lib/components/common'
import Modal from '../common/modal/Modal.svelte'
import Stepper from '../common/stepper/Stepper.svelte'
import Checkbox from '../common/checkbox/Checkbox.svelte'
import TextInput from '../text_input/TextInput.svelte'
import CopyableCodeBlock from '../details/CopyableCodeBlock.svelte'
import { plaintext } from 'svelte-highlight/languages'
import { sendUserToast } from '$lib/toast'
import { download } from '$lib/utils'
import { renderSVG } from 'uqr'
import TotpAuthenticator from './TotpAuthenticator.svelte'
import TotpRecoveryCodes from './TotpRecoveryCodes.svelte'
interface Props {
action: TotpAction | undefined
@@ -128,28 +125,7 @@
Logging in with your password now also asks for a code from your authenticator app.
</Alert>
{/if}
<div class="flex flex-col gap-1">
<span class="text-xs text-secondary font-normal">
Each code logs you in once if you lose your authenticator.
</span>
<CopyableCodeBlock code={recoveryCodes.join('\n')} language={plaintext} />
<div class="flex">
<Button
unifiedSize="sm"
variant="default"
onClick={() => download('windmill-recovery-codes.txt', recoveryCodes!.join('\n'))}
>
Download
</Button>
</div>
</div>
<Alert type="warning" title="Save these codes now" size="xs">
They are shown only once. Keep them somewhere other than this device.
</Alert>
<label class="flex flex-row gap-2 items-center text-xs text-primary font-normal">
<Checkbox checked={saved} onChange={() => (saved = !saved)} />
I saved my recovery codes
</label>
<TotpRecoveryCodes codes={recoveryCodes} bind:saved />
<div class="flex justify-end">
{@render primary()}
</div>
@@ -166,23 +142,7 @@
</label>
{:else}
{#if setup}
<div class="flex flex-col gap-1">
<span class="text-xs text-secondary font-normal">
Scan this QR code with an authenticator app, or open it on this device.
</span>
<a
href={setup.otpauth_url}
aria-label="Add to an authenticator app"
class="w-40 h-40 bg-white p-1 rounded-md"
>
{@html renderSVG(setup.otpauth_url)}
</a>
<div class="flex flex-row gap-1 items-center text-2xs text-secondary font-normal">
Or enter this key manually:
<span class="font-mono text-emphasis">{setup.secret}</span>
<CopyButton value={setup.secret} />
</div>
</div>
<TotpAuthenticator {setup} />
{/if}
<label class="flex flex-col gap-1">
<span class="text-xs text-emphasis font-semibold">Code</span>
@@ -0,0 +1,37 @@
<script lang="ts">
import { Alert, Button } from '$lib/components/common'
import Checkbox from '../common/checkbox/Checkbox.svelte'
import CopyableCodeBlock from '../details/CopyableCodeBlock.svelte'
import { plaintext } from 'svelte-highlight/languages'
import { download } from '$lib/utils'
interface Props {
codes: string[]
saved: boolean
}
let { codes, saved = $bindable() }: Props = $props()
</script>
<div class="flex flex-col gap-1">
<span class="text-xs text-secondary font-normal">
Each code logs you in once if you lose your authenticator.
</span>
<CopyableCodeBlock code={codes.join('\n')} language={plaintext} />
<div class="flex">
<Button
unifiedSize="sm"
variant="default"
onClick={() => download('windmill-recovery-codes.txt', codes.join('\n'))}
>
Download
</Button>
</div>
</div>
<Alert type="warning" title="Save these codes now" size="xs">
They are shown only once. Keep them somewhere other than this device.
</Alert>
<label class="flex flex-row gap-2 items-center text-xs text-primary font-normal">
<Checkbox checked={saved} onChange={() => (saved = !saved)} />
I saved my recovery codes
</label>
@@ -27,11 +27,14 @@
}
let totpEnabled = $state<boolean | undefined>(undefined)
let totpRequired = $state(false)
let totpAction = $state<TotpAction | undefined>(undefined)
async function loadTotp(): Promise<void> {
// 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<void> {
@@ -94,7 +97,9 @@
<span class="text-xs text-emphasis font-semibold">Two-factor authentication</span>
<span class="text-xs text-secondary font-normal">
{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.'}
</span>
<div class="flex flex-row gap-1">
@@ -106,9 +111,11 @@
>
New recovery codes
</Button>
<Button unifiedSize="sm" variant="default" onClick={() => (totpAction = 'disable')}>
Turn off
</Button>
{#if !totpRequired}
<Button unifiedSize="sm" variant="default" onClick={() => (totpAction = 'disable')}>
Turn off
</Button>
{/if}
{:else}
<Button unifiedSize="sm" variant="default" onClick={() => (totpAction = 'setup')}>
Set up two-factor authentication
+3
View File
@@ -6,6 +6,9 @@ const KNOWN_LOGIN_ERRORS = ['Password login is disabled on this instance']
/** The password matched and the account asks for its authenticator code: a prompt, not a failure. */
export const TOTP_REQUIRED = 'Two-factor code required'
/** The password matched, the instance requires a second factor and the account has none yet. */
export const TOTP_SETUP_REQUIRED = 'Two-factor setup required'
export const TOTP_INVALID_MESSAGE = 'Invalid authentication code.'
const GENERIC_LOGIN_ERROR = 'Could not sign you in. Please try again.'
@@ -22,6 +22,7 @@
import { onDestroy, tick } from 'svelte'
import { SettingService, UserService } from '$lib/gen'
import { sendUserToast } from '$lib/toast'
import { loginErrorDetail, TOTP_SETUP_REQUIRED } from '$lib/loginError'
import TextInput from '$lib/components/text_input/TextInput.svelte'
import Toggle from '$lib/components/Toggle.svelte'
import SettingsPageHeader from '$lib/components/settings/SettingsPageHeader.svelte'
@@ -94,6 +95,17 @@
let accountSubmitting = $state(false)
let accountError = $state('')
let showOssAccountDialog = $state(false)
// Offered only when this build serves two-factor authentication. When the instance
// requires it, the new account sets it up at the login page anyway.
let totpAvailable = $state(false)
let totpRequired = $state(false)
let setUpTotp = $state(true)
UserService.getTotpStatus()
.then((status) => {
totpAvailable = true
totpRequired = status.required
})
.catch(() => {})
let ossAccountError = $state('')
// --- Resource type sync (triggered on entering account step) ---
@@ -294,13 +306,22 @@
}
})
const token = await UserService.login({
requestBody: { email: newEmail, password: newPassword }
})
let token: string | undefined
try {
token = await UserService.login({
requestBody: { email: newEmail, password: newPassword }
})
} catch (e) {
// The instance requires two-factor authentication: the password matched, and the new
// account sets it up at the login page. The current session removes the old account.
if (loginErrorDetail(e) !== TOTP_SETUP_REQUIRED) throw e
}
// Update the client token for subsequent requests
const { OpenAPI } = await import('$lib/gen')
OpenAPI.TOKEN = token
if (token) {
// Update the client token for subsequent requests
const { OpenAPI } = await import('$lib/gen')
OpenAPI.TOKEN = token
}
try {
await UserService.globalUserDelete({ email: oldEmail })
@@ -315,7 +336,8 @@
'/user/login?email=' +
encodeURIComponent(newEmail) +
'&password=' +
encodeURIComponent(newPassword)
encodeURIComponent(newPassword) +
(totpAvailable && !totpRequired && setUpTotp ? '&setup_2fa=1' : '')
)
)
} catch (e: any) {
@@ -367,6 +389,30 @@
size="md"
/>
</div>
{#if totpAvailable && totpRequired}
<Alert type="info" title="Two-factor authentication is required" size="xs">
This instance requires it. After Set account &amp; finish, you log in with this account
and set it up before getting in.
</Alert>
{:else if totpAvailable}
<Alert type="info" title="Recommended: two-factor authentication" size="xs">
A superadmin account controls the whole instance. Protect it with a code from an
authenticator app on top of its password.
</Alert>
<div class="flex flex-col gap-1">
<Toggle
bind:checked={setUpTotp}
options={{ right: 'Set up two-factor authentication next' }}
size="xs"
/>
{#if setUpTotp}
<p class="text-tertiary text-2xs">
After Set account &amp; finish, you log in with this account and set it up right
away. You can skip it.
</p>
{/if}
</div>
{/if}
</div>
</SettingCard>
@@ -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)}
/>
+24 -2
View File
@@ -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<void> {
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 {