diff --git a/backend/.sqlx/query-05d2b07dd15d14a9c36bdb3dac87d1deb52b91ac98fdadc0c355955a1d90d26a.json b/backend/.sqlx/query-05d2b07dd15d14a9c36bdb3dac87d1deb52b91ac98fdadc0c355955a1d90d26a.json new file mode 100644 index 0000000000..e896c247ba --- /dev/null +++ b/backend/.sqlx/query-05d2b07dd15d14a9c36bdb3dac87d1deb52b91ac98fdadc0c355955a1d90d26a.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE password SET totp_recovery_codes = $2 WHERE email = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "TextArray" + ] + }, + "nullable": [] + }, + "hash": "05d2b07dd15d14a9c36bdb3dac87d1deb52b91ac98fdadc0c355955a1d90d26a" +} diff --git a/backend/.sqlx/query-08cc5c57fb76a392fc32c9122e32d8c33945f8e20daf9242e1de8f4f4ef5546e.json b/backend/.sqlx/query-08cc5c57fb76a392fc32c9122e32d8c33945f8e20daf9242e1de8f4f4ef5546e.json new file mode 100644 index 0000000000..1ac535026a --- /dev/null +++ b/backend/.sqlx/query-08cc5c57fb76a392fc32c9122e32d8c33945f8e20daf9242e1de8f4f4ef5546e.json @@ -0,0 +1,47 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT totp_secret, totp_pending_secret, totp_last_step, totp_recovery_codes,\n (totp_failed_attempts >= $2 AND totp_failed_since > now() - interval '1 minute')\n AS \"locked!\"\n FROM password WHERE email = $1 FOR UPDATE", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "totp_secret", + "type_info": "Text" + }, + { + "ordinal": 1, + "name": "totp_pending_secret", + "type_info": "Text" + }, + { + "ordinal": 2, + "name": "totp_last_step", + "type_info": "Int8" + }, + { + "ordinal": 3, + "name": "totp_recovery_codes", + "type_info": "TextArray" + }, + { + "ordinal": 4, + "name": "locked!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text", + "Int4" + ] + }, + "nullable": [ + true, + true, + true, + true, + null + ] + }, + "hash": "08cc5c57fb76a392fc32c9122e32d8c33945f8e20daf9242e1de8f4f4ef5546e" +} diff --git a/backend/.sqlx/query-0cdcf2f56b35f2c4929071933c2c7f3e4e2dda9f0663fb8b814ce78c3c99a63d.json b/backend/.sqlx/query-0cdcf2f56b35f2c4929071933c2c7f3e4e2dda9f0663fb8b814ce78c3c99a63d.json new file mode 100644 index 0000000000..a1119618b7 --- /dev/null +++ b/backend/.sqlx/query-0cdcf2f56b35f2c4929071933c2c7f3e4e2dda9f0663fb8b814ce78c3c99a63d.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE password SET totp_secret = totp_pending_secret, totp_pending_secret = NULL,\n totp_recovery_codes = $2\n WHERE email = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "TextArray" + ] + }, + "nullable": [] + }, + "hash": "0cdcf2f56b35f2c4929071933c2c7f3e4e2dda9f0663fb8b814ce78c3c99a63d" +} diff --git a/backend/.sqlx/query-134c3b21135ff0558fd234490b7ef56ccb86c2ba94d318c5fb341aa9114b8268.json b/backend/.sqlx/query-134c3b21135ff0558fd234490b7ef56ccb86c2ba94d318c5fb341aa9114b8268.json new file mode 100644 index 0000000000..28987c7d5f --- /dev/null +++ b/backend/.sqlx/query-134c3b21135ff0558fd234490b7ef56ccb86c2ba94d318c5fb341aa9114b8268.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE password SET totp_pending_secret = $2\n WHERE email = $1 AND login_type = 'password' AND totp_secret IS NULL", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [] + }, + "hash": "134c3b21135ff0558fd234490b7ef56ccb86c2ba94d318c5fb341aa9114b8268" +} diff --git a/backend/.sqlx/query-4b8fe0471867cbf4bbb571eae4fc097b36b70a46748fa0c2eedae610173bde86.json b/backend/.sqlx/query-4b8fe0471867cbf4bbb571eae4fc097b36b70a46748fa0c2eedae610173bde86.json new file mode 100644 index 0000000000..c5797b6bfb --- /dev/null +++ b/backend/.sqlx/query-4b8fe0471867cbf4bbb571eae4fc097b36b70a46748fa0c2eedae610173bde86.json @@ -0,0 +1,20 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT 1 AS \"one!\" FROM workspace_key\n WHERE workspace_id = 'admins' AND kind = 'cloud' FOR UPDATE", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "one!", + "type_info": "Int4" + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + null + ] + }, + "hash": "4b8fe0471867cbf4bbb571eae4fc097b36b70a46748fa0c2eedae610173bde86" +} diff --git a/backend/.sqlx/query-4c100853478519e794d05fe6070acfe8ddb246ceaed99e9e25f6bd34b105c6de.json b/backend/.sqlx/query-4c100853478519e794d05fe6070acfe8ddb246ceaed99e9e25f6bd34b105c6de.json new file mode 100644 index 0000000000..121eadc9b0 --- /dev/null +++ b/backend/.sqlx/query-4c100853478519e794d05fe6070acfe8ddb246ceaed99e9e25f6bd34b105c6de.json @@ -0,0 +1,38 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM password RETURNING email, totp_secret, totp_last_step, totp_recovery_codes", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "email", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "totp_secret", + "type_info": "Text" + }, + { + "ordinal": 2, + "name": "totp_last_step", + "type_info": "Int8" + }, + { + "ordinal": 3, + "name": "totp_recovery_codes", + "type_info": "TextArray" + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + false, + true, + true, + true + ] + }, + "hash": "4c100853478519e794d05fe6070acfe8ddb246ceaed99e9e25f6bd34b105c6de" +} diff --git a/backend/.sqlx/query-4d6646a2bccd6599cdd0d603a2e64f621449524162ef02ff52825af519f576e9.json b/backend/.sqlx/query-4d6646a2bccd6599cdd0d603a2e64f621449524162ef02ff52825af519f576e9.json new file mode 100644 index 0000000000..8bf052ee38 --- /dev/null +++ b/backend/.sqlx/query-4d6646a2bccd6599cdd0d603a2e64f621449524162ef02ff52825af519f576e9.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT password_hash FROM password WHERE email = $1 AND login_type = 'password'", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "password_hash", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + true + ] + }, + "hash": "4d6646a2bccd6599cdd0d603a2e64f621449524162ef02ff52825af519f576e9" +} diff --git a/backend/.sqlx/query-4e57eb6c62eb8a04088e91cae5cf955af22d885b24908c3beb949be24378797f.json b/backend/.sqlx/query-4e57eb6c62eb8a04088e91cae5cf955af22d885b24908c3beb949be24378797f.json new file mode 100644 index 0000000000..560d5b017f --- /dev/null +++ b/backend/.sqlx/query-4e57eb6c62eb8a04088e91cae5cf955af22d885b24908c3beb949be24378797f.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE password SET\n totp_failed_attempts = CASE WHEN totp_failed_since > now() - interval '1 minute'\n THEN totp_failed_attempts + 1 ELSE 1 END,\n totp_failed_since = CASE WHEN totp_failed_since > now() - interval '1 minute'\n THEN totp_failed_since ELSE now() END\n WHERE email = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [] + }, + "hash": "4e57eb6c62eb8a04088e91cae5cf955af22d885b24908c3beb949be24378797f" +} diff --git a/backend/.sqlx/query-536bda805dc3d1a5e66185787749b02dbefe608a83564cf165157230a4887639.json b/backend/.sqlx/query-536bda805dc3d1a5e66185787749b02dbefe608a83564cf165157230a4887639.json new file mode 100644 index 0000000000..8abcf226be --- /dev/null +++ b/backend/.sqlx/query-536bda805dc3d1a5e66185787749b02dbefe608a83564cf165157230a4887639.json @@ -0,0 +1,32 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT email, totp_secret, totp_pending_secret FROM password\n WHERE totp_secret IS NOT NULL OR totp_pending_secret IS NOT NULL FOR UPDATE", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "email", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "totp_secret", + "type_info": "Text" + }, + { + "ordinal": 2, + "name": "totp_pending_secret", + "type_info": "Text" + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + false, + true, + true + ] + }, + "hash": "536bda805dc3d1a5e66185787749b02dbefe608a83564cf165157230a4887639" +} diff --git a/backend/.sqlx/query-547f245179c2f91275a0b8e00e5dc327f3a6fe55fb9020c922603e4e7946b49c.json b/backend/.sqlx/query-547f245179c2f91275a0b8e00e5dc327f3a6fe55fb9020c922603e4e7946b49c.json new file mode 100644 index 0000000000..adebd908b1 --- /dev/null +++ b/backend/.sqlx/query-547f245179c2f91275a0b8e00e5dc327f3a6fe55fb9020c922603e4e7946b49c.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE password SET totp_secret = NULL, totp_pending_secret = NULL, totp_last_step = NULL,\n totp_recovery_codes = NULL, totp_failed_attempts = 0, totp_failed_since = NULL\n WHERE email = $1 AND (totp_secret IS NOT NULL OR totp_pending_secret IS NOT NULL)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [] + }, + "hash": "547f245179c2f91275a0b8e00e5dc327f3a6fe55fb9020c922603e4e7946b49c" +} diff --git a/backend/.sqlx/query-80a33efd3fd3e9bb447568f7e51aecdedadcbf2aaf65820b91793accbd695032.json b/backend/.sqlx/query-80a33efd3fd3e9bb447568f7e51aecdedadcbf2aaf65820b91793accbd695032.json new file mode 100644 index 0000000000..f05f18da31 --- /dev/null +++ b/backend/.sqlx/query-80a33efd3fd3e9bb447568f7e51aecdedadcbf2aaf65820b91793accbd695032.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE password SET totp_failed_attempts = 0, totp_failed_since = NULL WHERE email = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [] + }, + "hash": "80a33efd3fd3e9bb447568f7e51aecdedadcbf2aaf65820b91793accbd695032" +} diff --git a/backend/.sqlx/query-8449b974fcedf52f9746ae6fd6a052977a44f8b068285949cef8b6ac3ecd6dce.json b/backend/.sqlx/query-8449b974fcedf52f9746ae6fd6a052977a44f8b068285949cef8b6ac3ecd6dce.json new file mode 100644 index 0000000000..b317570b13 --- /dev/null +++ b/backend/.sqlx/query-8449b974fcedf52f9746ae6fd6a052977a44f8b068285949cef8b6ac3ecd6dce.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT totp_secret IS NOT NULL AS \"enrolled!\" FROM password\n WHERE email = $1 AND login_type = 'password'", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "enrolled!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "8449b974fcedf52f9746ae6fd6a052977a44f8b068285949cef8b6ac3ecd6dce" +} diff --git a/backend/.sqlx/query-8728e856ad6ba82495890e466f5226b401927d6ada71f91e0a035f9945dbf036.json b/backend/.sqlx/query-8728e856ad6ba82495890e466f5226b401927d6ada71f91e0a035f9945dbf036.json new file mode 100644 index 0000000000..873a16c236 --- /dev/null +++ b/backend/.sqlx/query-8728e856ad6ba82495890e466f5226b401927d6ada71f91e0a035f9945dbf036.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT key FROM workspace_key WHERE workspace_id = $1 AND kind = 'cloud' FOR SHARE", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "key", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + false + ] + }, + "hash": "8728e856ad6ba82495890e466f5226b401927d6ada71f91e0a035f9945dbf036" +} diff --git a/backend/.sqlx/query-be65c6653f4e116517ff14abb7e3f075a82e41f758daae9aeab4d558d781f817.json b/backend/.sqlx/query-be65c6653f4e116517ff14abb7e3f075a82e41f758daae9aeab4d558d781f817.json new file mode 100644 index 0000000000..18cf2c0f80 --- /dev/null +++ b/backend/.sqlx/query-be65c6653f4e116517ff14abb7e3f075a82e41f758daae9aeab4d558d781f817.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT EXISTS(SELECT 1 FROM password WHERE totp_secret IS NOT NULL AND email <> $1)\n AS \"exists!\"", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "exists!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "be65c6653f4e116517ff14abb7e3f075a82e41f758daae9aeab4d558d781f817" +} diff --git a/backend/.sqlx/query-c42f409f1c238ed5d6e9b57dd0b2a621e23dfbfefe99e848484b764fa57d837f.json b/backend/.sqlx/query-c42f409f1c238ed5d6e9b57dd0b2a621e23dfbfefe99e848484b764fa57d837f.json new file mode 100644 index 0000000000..7754fb84c2 --- /dev/null +++ b/backend/.sqlx/query-c42f409f1c238ed5d6e9b57dd0b2a621e23dfbfefe99e848484b764fa57d837f.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE password SET totp_recovery_codes = array_remove(totp_recovery_codes, $2)\n WHERE email = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [] + }, + "hash": "c42f409f1c238ed5d6e9b57dd0b2a621e23dfbfefe99e848484b764fa57d837f" +} diff --git a/backend/.sqlx/query-d5f86d08766c4dfee235b2a3c001b912ca690f498c1c3e2113d7b5bc9823c87d.json b/backend/.sqlx/query-d5f86d08766c4dfee235b2a3c001b912ca690f498c1c3e2113d7b5bc9823c87d.json new file mode 100644 index 0000000000..ee455947b1 --- /dev/null +++ b/backend/.sqlx/query-d5f86d08766c4dfee235b2a3c001b912ca690f498c1c3e2113d7b5bc9823c87d.json @@ -0,0 +1,17 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE password SET totp_secret = $2, totp_last_step = $3, totp_recovery_codes = $4\n WHERE email = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Text", + "Int8", + "TextArray" + ] + }, + "nullable": [] + }, + "hash": "d5f86d08766c4dfee235b2a3c001b912ca690f498c1c3e2113d7b5bc9823c87d" +} diff --git a/backend/.sqlx/query-eaac18f48398babf27a273da98eb9420b2c7fd5363525240b43b5c47928217f2.json b/backend/.sqlx/query-eaac18f48398babf27a273da98eb9420b2c7fd5363525240b43b5c47928217f2.json new file mode 100644 index 0000000000..4f805aa8fa --- /dev/null +++ b/backend/.sqlx/query-eaac18f48398babf27a273da98eb9420b2c7fd5363525240b43b5c47928217f2.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT totp_secret IS NOT NULL AS \"enabled!\" FROM password WHERE email = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "enabled!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "eaac18f48398babf27a273da98eb9420b2c7fd5363525240b43b5c47928217f2" +} diff --git a/backend/.sqlx/query-ed4c95dbac85508ab9836f380a550ba3dd46e63cec97c789bd0c06b81fc92a59.json b/backend/.sqlx/query-ed4c95dbac85508ab9836f380a550ba3dd46e63cec97c789bd0c06b81fc92a59.json new file mode 100644 index 0000000000..92361f1f50 --- /dev/null +++ b/backend/.sqlx/query-ed4c95dbac85508ab9836f380a550ba3dd46e63cec97c789bd0c06b81fc92a59.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE password SET totp_last_step = $2 WHERE email = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Int8" + ] + }, + "nullable": [] + }, + "hash": "ed4c95dbac85508ab9836f380a550ba3dd46e63cec97c789bd0c06b81fc92a59" +} diff --git a/backend/.sqlx/query-fffeda2be11d5c6d5969d49569d726046f138262c097e6f05a70bdea35e2038a.json b/backend/.sqlx/query-fffeda2be11d5c6d5969d49569d726046f138262c097e6f05a70bdea35e2038a.json new file mode 100644 index 0000000000..83e6269d09 --- /dev/null +++ b/backend/.sqlx/query-fffeda2be11d5c6d5969d49569d726046f138262c097e6f05a70bdea35e2038a.json @@ -0,0 +1,16 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE password SET totp_secret = $2, totp_pending_secret = $3 WHERE email = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Text", + "Text" + ] + }, + "nullable": [] + }, + "hash": "fffeda2be11d5c6d5969d49569d726046f138262c097e6f05a70bdea35e2038a" +} diff --git a/backend/Cargo.lock b/backend/Cargo.lock index a7fc3a92c9..9d3110af0b 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -16368,12 +16368,16 @@ version = "1.886.0" dependencies = [ "argon2", "axum", + "base32", "chrono", + "hmac 0.12.1", "http 1.5.0", "hyper 1.13.0", "lazy_static", + "rand 0.9.5", "serde", "serde_json", + "sha1", "sqlx", "time", "tokio", diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index 74d6ecc82f..f564d218cc 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -c05fadda9d6bd772e56cec00d5b9c721afab4aed +5456ade3c09011206acc20ab026dda49f15f9517 diff --git a/backend/migrations/20261124085334_totp_two_factor.down.sql b/backend/migrations/20261124085334_totp_two_factor.down.sql new file mode 100644 index 0000000000..631dced01e --- /dev/null +++ b/backend/migrations/20261124085334_totp_two_factor.down.sql @@ -0,0 +1,7 @@ +ALTER TABLE password + DROP COLUMN IF EXISTS totp_secret, + DROP COLUMN IF EXISTS totp_pending_secret, + DROP COLUMN IF EXISTS totp_last_step, + DROP COLUMN IF EXISTS totp_recovery_codes, + DROP COLUMN IF EXISTS totp_failed_attempts, + DROP COLUMN IF EXISTS totp_failed_since; diff --git a/backend/migrations/20261124085334_totp_two_factor.up.sql b/backend/migrations/20261124085334_totp_two_factor.up.sql new file mode 100644 index 0000000000..0383516d08 --- /dev/null +++ b/backend/migrations/20261124085334_totp_two_factor.up.sql @@ -0,0 +1,7 @@ +ALTER TABLE password + ADD COLUMN IF NOT EXISTS totp_secret TEXT, + ADD COLUMN IF NOT EXISTS totp_pending_secret TEXT, + ADD COLUMN IF NOT EXISTS totp_last_step BIGINT, + ADD COLUMN IF NOT EXISTS totp_recovery_codes TEXT[], + ADD COLUMN IF NOT EXISTS totp_failed_attempts INTEGER NOT NULL DEFAULT 0, + ADD COLUMN IF NOT EXISTS totp_failed_since TIMESTAMPTZ; diff --git a/backend/windmill-api-users/Cargo.toml b/backend/windmill-api-users/Cargo.toml index cfd683434c..a0af0994a7 100644 --- a/backend/windmill-api-users/Cargo.toml +++ b/backend/windmill-api-users/Cargo.toml @@ -24,6 +24,10 @@ windmill-audit.workspace = true windmill-git-sync.workspace = true argon2.workspace = true +base32.workspace = true +hmac.workspace = true +rand.workspace = true +sha1.workspace = true axum.workspace = true chrono.workspace = true http.workspace = true diff --git a/backend/windmill-api-users/src/lib.rs b/backend/windmill-api-users/src/lib.rs index ee5369e616..fd294db72d 100644 --- a/backend/windmill-api-users/src/lib.rs +++ b/backend/windmill-api-users/src/lib.rs @@ -1,3 +1,7 @@ +pub mod totp; +#[cfg(feature = "private")] +pub mod totp_ee; +mod totp_oss; pub mod users; #[cfg(feature = "private")] pub mod users_ee; diff --git a/backend/windmill-api-users/src/totp.rs b/backend/windmill-api-users/src/totp.rs new file mode 100644 index 0000000000..97bcde4eb8 --- /dev/null +++ b/backend/windmill-api-users/src/totp.rs @@ -0,0 +1,9 @@ +//! 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}; +#[cfg(not(feature = "private"))] +pub use crate::totp_oss::{check_login_code, service}; + +pub const TOTP_REQUIRED: &str = "Two-factor code required"; +pub const TOTP_INVALID: &str = "Invalid two-factor code"; diff --git a/backend/windmill-api-users/src/totp_oss.rs b/backend/windmill-api-users/src/totp_oss.rs new file mode 100644 index 0000000000..a4945520a4 --- /dev/null +++ b/backend/windmill-api-users/src/totp_oss.rs @@ -0,0 +1,16 @@ +#[cfg(not(feature = "private"))] +pub fn service() -> axum::Router { + axum::Router::new() +} + +#[cfg(not(feature = "private"))] +pub async fn check_login_code( + _tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, + _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(), + )) +} diff --git a/backend/windmill-api-users/src/users.rs b/backend/windmill-api-users/src/users.rs index 4acaff2433..7f9e5a9600 100644 --- a/backend/windmill-api-users/src/users.rs +++ b/backend/windmill-api-users/src/users.rs @@ -125,6 +125,7 @@ pub fn global_service() -> Router { .route("/exists/{email}", get(exists_email)) .route("/email", get(get_email)) .route("/whoami", get(global_whoami)) + .nest("/totp", crate::totp::service()) .route("/list_invites", get(list_invites)) .route("/decline_invite", post(decline_invite)) .route("/accept_invite", post(accept_invite)) @@ -345,6 +346,8 @@ pub struct TruncatedToken { pub struct Login { pub email: String, pub password: String, + #[serde(default)] + pub totp_code: Option, } lazy_static::lazy_static! { @@ -2905,7 +2908,7 @@ async fn login( cookies: Cookies, Extension(db): Extension, Extension(argon2): Extension>>, - Json(Login { email, password }): Json, + Json(Login { email, password, totp_code }): Json, ) -> Result { // In `--no-auth` mode there is no real login; the frontend never needs a // session cookie because every request already resolves as the admin @@ -2933,15 +2936,15 @@ async fn login( username_override: None, token_prefix: None, }; - let email_w_h: Option<(String, String, bool)> = sqlx::query_as( - "SELECT email, password_hash, super_admin FROM password WHERE email = $1 AND login_type = \ - 'password' AND disabled = false", + 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)) = email_w_h { + if let Some((email, hash, super_admin, totp_secret)) = email_w_h { if argon2 .verify_password(password.as_bytes(), hash.as_str()) .is_err() @@ -2959,6 +2962,30 @@ async fn login( 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?; @@ -4711,9 +4738,22 @@ async fn overwrite_global_users( // Replaces the account table, so β€” unlike the paths that remove one account β€” it deliberately // does not call `delete_drafts_of_email`: the addresses are about to be reinstated, and // dropping every draft on the instance to restore accounts would be pure collateral. - sqlx::query!("DELETE FROM password") - .execute(&mut *tx) - .await?; + // The export leaves TOTP secrets out, since its files end up in git. A second factor is + // kept for every account the overwrite reinstates, rather than silently switched off. + // Read by the DELETE itself: a separate snapshot would miss an enrollment committing + // between the two and then delete it. The secrets are under the `admins` key: its row lock + // keeps a rotation from re-encrypting while the restored rows are not visible to it. + sqlx::query!( + "SELECT 1 AS \"one!\" FROM workspace_key + WHERE workspace_id = 'admins' AND kind = 'cloud' FOR UPDATE" + ) + .fetch_optional(&mut *tx) + .await?; + let totp = sqlx::query!( + "DELETE FROM password RETURNING email, totp_secret, totp_last_step, totp_recovery_codes" + ) + .fetch_all(&mut *tx) + .await?; for user in users { sqlx::query!( "INSERT INTO password(email, password_hash, login_type, super_admin, verified, name, company, first_time_user, username) @@ -4731,6 +4771,18 @@ async fn overwrite_global_users( .execute(&mut *tx) .await?; } + for t in totp.into_iter().filter(|t| t.totp_secret.is_some()) { + sqlx::query!( + "UPDATE password SET totp_secret = $2, totp_last_step = $3, totp_recovery_codes = $4 + WHERE email = $1", + t.email, + t.totp_secret, + t.totp_last_step, + t.totp_recovery_codes.as_deref() + ) + .execute(&mut *tx) + .await?; + } audit_log( &mut *tx, &authed, diff --git a/backend/windmill-api-workspaces/src/workspaces.rs b/backend/windmill-api-workspaces/src/workspaces.rs index 2580ce84f4..de4dd44168 100644 --- a/backend/windmill-api-workspaces/src/workspaces.rs +++ b/backend/windmill-api-workspaces/src/workspaces.rs @@ -6908,6 +6908,9 @@ async fn set_encryption_key( &new_encryption_key, ) .await?; + if w_id == "admins" { + reencrypt_totp_secrets(&mut tx, &previous_encryption_key, &new_encryption_key).await?; + } tx.commit().await?; @@ -6946,6 +6949,45 @@ async fn set_encryption_key( return Ok(()); } +/// Two-factor secrets of password logins are kept under the `admins` workspace key. Never +/// synced, so they move to the new key even when the caller skips re-encryption: one left under +/// the old key would lock its user out. +async fn reencrypt_totp_secrets( + conn: &mut sqlx::PgConnection, + old: &windmill_common::variables::WorkspaceCrypt, + new: &windmill_common::variables::WorkspaceCrypt, +) -> Result<()> { + let rows = sqlx::query!( + "SELECT email, totp_secret, totp_pending_secret FROM password + WHERE totp_secret IS NOT NULL OR totp_pending_secret IS NOT NULL FOR UPDATE" + ) + .fetch_all(&mut *conn) + .await?; + // Left as is when it does not decrypt: dropping it would switch the second factor off. + let reencrypt = |email: &str, value: Option| { + value.map(|v| match decrypt(old, v.clone()) { + Ok(plain) => encrypt(new, &plain), + Err(e) => { + tracing::warn!("the two-factor secret of {email} does not decrypt under the current key, leaving it as is: {e}"); + v + } + }) + }; + for row in rows { + let secret = reencrypt(&row.email, row.totp_secret); + let pending = reencrypt(&row.email, row.totp_pending_secret); + sqlx::query!( + "UPDATE password SET totp_secret = $2, totp_pending_secret = $3 WHERE email = $1", + row.email, + secret, + pending + ) + .execute(&mut *conn) + .await?; + } + Ok(()) +} + /// Move the git-sync secrets the server keeps under the workspace key (stored /// repository tokens, webhook secrets) to the new key. They are never synced, so /// unlike variables they are still under the old key when the caller skips diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index d1e67be29a..59fd845f3d 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -694,6 +694,170 @@ paths: schema: type: string + /users/totp: + get: + summary: get whether two-factor authentication is enabled for the current user + operationId: getTotpStatus + tags: + - user + responses: + "200": + description: two-factor status + content: + application/json: + schema: + type: object + properties: + enabled: + type: boolean + required: + - enabled + + /users/totp/setup: + post: + summary: start two-factor setup by generating a new authenticator secret + operationId: setupTotp + tags: + - user + requestBody: + description: the account's current password + required: true + content: + application/json: + schema: + type: object + properties: + password: + type: string + required: + - 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 + + /users/totp/enable: + post: + summary: enable two-factor authentication with a code from the secret generated by setup + operationId: enableTotp + tags: + - user + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + code: + type: string + required: + - code + responses: + "200": + description: two-factor authentication enabled, with its recovery codes + content: + application/json: + schema: + type: object + properties: + recovery_codes: + type: array + description: single-use codes accepted in place of an authenticator code, shown only once + items: + type: string + required: + - recovery_codes + + /users/totp/recovery_codes: + post: + summary: replace the recovery codes, with a current code or a recovery code + operationId: regenerateTotpRecoveryCodes + tags: + - user + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + code: + type: string + required: + - code + responses: + "200": + description: the new recovery codes + content: + application/json: + schema: + type: object + properties: + recovery_codes: + type: array + description: single-use codes accepted in place of an authenticator code, shown only once + items: + type: string + required: + - recovery_codes + + /users/totp/disable: + post: + summary: disable two-factor authentication with a current code or a recovery code + operationId: disableTotp + tags: + - user + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + code: + type: string + required: + - code + responses: + "200": + description: two-factor authentication disabled + content: + text/plain: + schema: + type: string + + /users/totp/reset/{user}: + post: + summary: remove the two-factor authentication of a user (require super admin) + operationId: resetTotpOfUser + tags: + - user + parameters: + - name: user + in: path + required: true + schema: + type: string + responses: + "200": + description: two-factor authentication removed + content: + text/plain: + schema: + type: string + /users/set_password_of/{user}: post: summary: set password for a specific user (require super admin) @@ -33922,6 +34086,12 @@ components: type: string password: type: string + totp_code: + type: string + description: > + Current code of the account's authenticator app, or one of its recovery codes. Required once the account has + two-factor authentication enabled; the login answers "Two-factor code required" + when it is missing and the password is correct. required: - email - password diff --git a/docs/auth-surface.md b/docs/auth-surface.md index b21e8eca67..9299f6bd3a 100644 --- a/docs/auth-surface.md +++ b/docs/auth-surface.md @@ -25,6 +25,24 @@ Symbols, not line numbers, are cited: they drift less. access-token row, then its grant, the order the trigger also follows. A new path that writes a user's tokens and may revoke must lock that row first too. `leave_workspace` deletes no tokens and revokes nothing; `leave_instance` deletes every token of the account, as `delete_user` does. +- **Two-factor (TOTP) guards `POST /auth/login` only** (`windmill-api-users/src/totp_ee.rs`, + with a stub in `totp_oss.rs`; a build without `enterprise` allows it for one user). The + password is checked first, so "Two-factor code required" tells only someone who knows the + password that a code is needed. Every other way into a session skips it on purpose: OAuth and + SAML (the provider owns the second factor), login links (minted by a superadmin, who can reset + the second factor anyway, and never for a superadmin or devops account), and `GET /users/refresh_token` (a session already exists). + Authenticator codes are single-use (`totp_last_step`), and so are the ten recovery codes, stored + as salted argon2 hashes (a code carries about 52 bits, too few for a plain digest) and are + accepted wherever a code is. Wrong codes are capped per account at 5 a minute on the + `password` row, so the cap holds across servers; the caller commits the count even when it + refuses the code. Without that cap, a known password leaves a 6-digit code as the only barrier. + Enrolling (`setup`) asks for the password again, so a stolen session cannot add its own + authenticator and lock the owner out of password login. A superadmin removes a lost second + factor with `POST /users/totp/reset/{user}`. The secret is + encrypted under the `admins` workspace key, and rotating that key re-encrypts it + (`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. - **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/package-lock.json b/frontend/package-lock.json index 85fc4bda2a..ee9d4d601b 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -96,6 +96,7 @@ "tailwind-merge": "^1.13.2", "unified": "^11.0.5", "unist-util-visit": "^5.0.0", + "uqr": "^0.1.3", "vscode": "npm:@codingame/monaco-vscode-extension-api@=25.0.0", "vscode-languageclient": "~9.0.1", "vscode-uri": "~3.1.0", @@ -13446,6 +13447,12 @@ "browserslist": ">= 4.21.0" } }, + "node_modules/uqr": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/uqr/-/uqr-0.1.3.tgz", + "integrity": "sha512-0rjE8iEJe4YmT9TOhwsZtqCMRLc5DXZUI2UEYUUg63ikBkqqE5EYWaI0etFe/5KUcmcYwLih2RND1kq+hrUJXA==", + "license": "MIT" + }, "node_modules/uri-js": { "version": "4.4.1", "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", diff --git a/frontend/package.json b/frontend/package.json index c0ff933f1c..e926002b63 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -161,6 +161,7 @@ "tailwind-merge": "^1.13.2", "unified": "^11.0.5", "unist-util-visit": "^5.0.0", + "uqr": "^0.1.3", "vscode": "npm:@codingame/monaco-vscode-extension-api@=25.0.0", "vscode-languageclient": "~9.0.1", "vscode-uri": "~3.1.0", diff --git a/frontend/src/lib/components/InstanceNameEditor.svelte b/frontend/src/lib/components/InstanceNameEditor.svelte index 9d21da963c..14d8210e4f 100644 --- a/frontend/src/lib/components/InstanceNameEditor.svelte +++ b/frontend/src/lib/components/InstanceNameEditor.svelte @@ -44,6 +44,10 @@ sendUserToast(`Password updated for ${email}`) } + async function resetTotp() { + sendUserToast(await UserService.resetTotpOfUser({ user: email })) + } + async function saveLoginType() { await UserService.setLoginTypeForUser({ user: email, requestBody: { login_type } }) sendUserToast(`Login type updated for ${email}`) @@ -173,6 +177,22 @@ 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. +
+ +
{/snippet} diff --git a/frontend/src/lib/components/Login.svelte b/frontend/src/lib/components/Login.svelte index cdd5c290fa..068e79fa6b 100644 --- a/frontend/src/lib/components/Login.svelte +++ b/frontend/src/lib/components/Login.svelte @@ -42,7 +42,12 @@ import { sameTopDomainOrigin } from '$lib/cookies' import { isValidLogoutRedirect, toSameOriginRelativePath } from '$lib/logoutRedirect' import InputError from './InputError.svelte' - import { loginErrorMessage } from '$lib/loginError' + import { + loginErrorDetail, + loginErrorMessage, + TOTP_INVALID_MESSAGE, + TOTP_REQUIRED + } from '$lib/loginError' import { parseAccountSettingsHash } from './sidebar/settings' import Badge from './common/badge/Badge.svelte' import { @@ -109,6 +114,7 @@ const emailId = `${uid}-email` const passwordId = `${uid}-password` const errorId = `${uid}-error` + const totpId = `${uid}-totp` const emailErrorId = `${uid}-email-error` const providers = [ @@ -183,6 +189,22 @@ 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. + let totpFor = $state(undefined) + let totpCode = $state('') + let totpField = $state(undefined) + let showTotp = $derived(totpFor !== undefined && totpFor === email) + + async function leaveTotp() { + totpFor = undefined + totpCode = '' + formError = undefined + // The swapped-in markup would otherwise replay a shake left on from a failed attempt. + shake = false + await tick() + passwordField?.focus() + } // Type argument rather than annotation: annotating narrows the declaration to the // initializer's `undefined`, so a top-level read sees `never` instead of the array. let logins = $state(undefined) @@ -200,7 +222,7 @@ let formError = $state< | { message: string - fields: 'both' | 'email' | 'password' + fields: 'both' | 'email' | 'password' | 'totp' email: string | undefined password: string | undefined } @@ -221,7 +243,7 @@ async function failLogin( message: string, - fields: 'both' | 'email' | 'password' = 'both', + fields: 'both' | 'email' | 'password' | 'totp' = 'both', // The pair the message is about. Defaults to what is in the fields right now, but a // rejected request passes what it actually submitted: the user may have typed on since. attempted: { email: string | undefined; password: string | undefined } = { email, password } @@ -258,9 +280,15 @@ return } + if (showTotp && !totpCode.trim()) { + failLogin('Enter the code from your authenticator app.', 'totp') + return + } + const requestBody = { email, - password + password, + totp_code: showTotp ? totpCode : undefined } // Await the DOM update: the field must be back to type="password" before the @@ -274,7 +302,17 @@ // previous account must not be served to this one. noteSessionEmail(email) } catch (err) { - failLogin(loginErrorMessage(err), 'both', requestBody) + if (loginErrorDetail(err) === TOTP_REQUIRED) { + formError = undefined + shake = false + totpFor = requestBody.email + totpCode = '' + await tick() + totpField?.focus() + return + } + const message = loginErrorMessage(err) + failLogin(message, message === TOTP_INVALID_MESSAGE ? 'totp' : 'both', requestBody) return } @@ -760,130 +798,179 @@

Signing you in…

{/if} - {#if !passwordFirst} - {@render providerButtons()} - {#if !autoRedirecting && !disablePasswordLogin && (saml || (logins && logins.length > 0))} - {@render orDivider()} - - {#if !showPassword} -
- -
- {/if} - {/if} - {/if} - - {#if !autoRedirecting && showPassword && !disablePasswordLogin} -
- {#if firstTime} -

- Welcome! Default credentials admin@windmill.dev / changeme have been prefilled. + {#if showTotp} +

+
+

Two-factor authentication

+

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

- {/if} -
- {#if cloudHosted} -

- To get credentials without the OAuth providers above, send an email at - contact@windmill.dev -

- {/if} -
-
- -
- { - // Only move on once the field holds something: while the browser's - // credential dropdown is open, Enter belongs to the dropdown - if (e.key === 'Enter' && !e.isComposing && !e.repeat && e.currentTarget.value) { - e.preventDefault() - passwordField?.focus() - } - } - }} - /> -
- -
- -
- -
- -
- {@render errorMessage()} -
-
- -
- - {#if smtpConfigured} - - {/if} +
+
+ + + {@render errorMessage()} +
+
+ +
+
- - {#if cloudHosted} -

- By logging in, you agree to our - - Terms of service - - and - - Privacy policy - -

- {/if}
- {/if} + {:else} + {#if !passwordFirst} + {@render providerButtons()} + {#if !autoRedirecting && !disablePasswordLogin && (saml || (logins && logins.length > 0))} + {@render orDivider()} + + {#if !showPassword} +
+ +
+ {/if} + {/if} + {/if} - {#if passwordFirst && (saml || (logins && logins.length > 0))} - {@render orDivider()} - {@render providerButtons()} + {#if !autoRedirecting && showPassword && !disablePasswordLogin} +
+ {#if firstTime} +

+ Welcome! Default credentials admin@windmill.dev / changeme have been prefilled. +

+ {/if} +
+ {#if cloudHosted} +

+ To get credentials without the OAuth providers above, send an email at + contact@windmill.dev +

+ {/if} +
+
+ +
+ { + // Only move on once the field holds something: while the browser's + // credential dropdown is open, Enter belongs to the dropdown + if ( + e.key === 'Enter' && + !e.isComposing && + !e.repeat && + e.currentTarget.value + ) { + e.preventDefault() + passwordField?.focus() + } + } + }} + /> +
+ +
+ +
+ +
+ +
+ {@render errorMessage()} +
+
+ +
+ + {#if smtpConfigured} + + {/if} +
+
+ + {#if cloudHosted} +

+ By logging in, you agree to our + + Terms of service + + and + + Privacy policy + +

+ {/if} +
+ {/if} + + {#if passwordFirst && (saml || (logins && logins.length > 0))} + {@render orDivider()} + {@render providerButtons()} + {/if} {/if}
diff --git a/frontend/src/lib/components/settings/TotpModal.svelte b/frontend/src/lib/components/settings/TotpModal.svelte new file mode 100644 index 0000000000..7b03c9a56d --- /dev/null +++ b/frontend/src/lib/components/settings/TotpModal.svelte @@ -0,0 +1,202 @@ + + + + +{#snippet primary()} + +{/snippet} + + action != undefined, (v) => !v && action != undefined && close()} + on:confirmed={next} + kind={recoveryCodes ? 'X' : 'button'} +> +
+ {#if action == 'setup'} + + {/if} + + {#if recoveryCodes} + {#if action == 'setup'} + + Logging in with your password now also asks for a code from your authenticator app. + + {/if} +
+ + Each code logs you in once if you lose your authenticator. + + +
+ +
+
+ + They are shown only once. Keep them somewhere other than this device. + + +
+ {@render primary()} +
+ {:else if action == 'setup' && step == 0} + + {:else} + {#if setup} +
+ + Scan this QR code with an authenticator app, or open it on this device. + + + {@html renderSVG(setup.otpauth_url)} + +
+ Or enter this key manually: + {setup.secret} + +
+
+ {/if} + + {/if} +
+ + {#snippet actions()} + {@render primary()} + {/snippet} +
diff --git a/frontend/src/lib/components/settings/UserInfoSettings.svelte b/frontend/src/lib/components/settings/UserInfoSettings.svelte index 611b7cc683..abb4fe1b20 100644 --- a/frontend/src/lib/components/settings/UserInfoSettings.svelte +++ b/frontend/src/lib/components/settings/UserInfoSettings.svelte @@ -5,6 +5,7 @@ import { Button } from '$lib/components/common' import { sendUserToast } from '$lib/toast' import TextInput from '../text_input/TextInput.svelte' + import TotpModal, { type TotpAction } from './TotpModal.svelte' let newPassword = $state(undefined) let passwordError = $state(undefined) @@ -19,11 +20,20 @@ async function loadLoginType(): Promise { login_type = (await UserService.globalWhoami()).login_type + if (login_type == 'password') await loadTotp() if (login_type == 'pending_oauth') { passwordAllowed = !(await UserService.isPasswordLoginDisabled().catch(() => false)) } } + let totpEnabled = $state(undefined) + 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 + } + async function setPassword(): Promise { if (newPassword) { await UserService.setPassword({ @@ -78,4 +88,34 @@
{/if} + + {#if login_type == 'password' && totpEnabled != undefined} +
+ Two-factor authentication + + {totpEnabled + ? '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.'} + +
+ {#if totpEnabled} + + + {:else} + + {/if} +
+
+ {/if} + diff --git a/frontend/src/lib/loginError.test.ts b/frontend/src/lib/loginError.test.ts index cf76dca5ec..56d053a1c7 100644 --- a/frontend/src/lib/loginError.test.ts +++ b/frontend/src/lib/loginError.test.ts @@ -1,5 +1,10 @@ import { describe, it, expect } from 'vitest' -import { loginErrorMessage } from './loginError' +import { + loginErrorDetail, + loginErrorMessage, + TOTP_INVALID_MESSAGE, + TOTP_REQUIRED +} from './loginError' describe('loginErrorMessage', () => { it('maps the backend rejection to one message for a wrong email and a wrong password', () => { @@ -21,6 +26,15 @@ describe('loginErrorMessage', () => { ) }) + it('recognises the two-factor responses of the login endpoint', () => { + expect(loginErrorDetail({ status: 400, body: 'Bad request: Two-factor code required' })).toBe( + TOTP_REQUIRED + ) + expect(loginErrorMessage({ status: 400, body: 'Bad request: Invalid two-factor code' })).toBe( + TOTP_INVALID_MESSAGE + ) + }) + it('never surfaces server text it does not recognise, to an unauthenticated visitor', () => { const sqlError = { status: 400, diff --git a/frontend/src/lib/loginError.ts b/frontend/src/lib/loginError.ts index d26f44abd6..72f56d6b7b 100644 --- a/frontend/src/lib/loginError.ts +++ b/frontend/src/lib/loginError.ts @@ -3,17 +3,29 @@ // error page β€” would otherwise be printed verbatim to an unauthenticated visitor. 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' + +export const TOTP_INVALID_MESSAGE = 'Invalid authentication code.' + const GENERIC_LOGIN_ERROR = 'Could not sign you in. Please try again.' -export function loginErrorMessage(err: any): string { - // The API returns errors as plain text, prefixed by their class (e.g. "Bad request: Invalid - // login"); ApiError.message is only the HTTP status text. +// The API returns errors as plain text, prefixed by their class (e.g. "Bad request: Invalid +// login"); ApiError.message is only the HTTP status text. +export function loginErrorDetail(err: any): string { const raw = typeof err?.body === 'string' ? err.body : err?.body?.error?.message const body = typeof raw === 'string' ? raw : '' - const detail = body.replace(/^(Bad request|Internal|Error): /, '').trim() + return body.replace(/^(Bad request|Internal|Error): /, '').trim() +} + +export function loginErrorMessage(err: any): string { + const detail = loginErrorDetail(err) if (detail === 'Invalid login') { return 'Invalid email or password.' } + if (detail === 'Invalid two-factor code') { + return TOTP_INVALID_MESSAGE + } if (err?.status === 429) { return 'Too many login attempts. Please try again later.' }