diff --git a/database/migrations/functions/001_load_functions.sql b/database/migrations/functions/001_load_functions.sql index 50a780b288..d2fdf4e3d1 100644 --- a/database/migrations/functions/001_load_functions.sql +++ b/database/migrations/functions/001_load_functions.sql @@ -91,9 +91,12 @@ {{ template "users/delete_user.sql" }} {{ template "users/get_user_profile.sql" }} {{ template "users/get_user_tfa_config.sql" }} +{{ template "users/refund_auth_attempt.sql" }} +{{ template "users/register_auth_attempt.sql" }} {{ template "users/register_delete_user_code.sql" }} {{ template "users/register_password_reset_code.sql" }} {{ template "users/register_session.sql" }} +{{ template "users/register_session_with_password.sql" }} {{ template "users/register_user.sql" }} {{ template "users/reset_user_password.sql" }} {{ template "users/update_user_password.sql" }} diff --git a/database/migrations/functions/users/approve_session.sql b/database/migrations/functions/users/approve_session.sql index d70223bd0f..5f6f44abe5 100644 --- a/database/migrations/functions/users/approve_session.sql +++ b/database/migrations/functions/users/approve_session.sql @@ -1,13 +1,36 @@ --- approvee_session approves the provided session in the database. +-- approve_session approves the provided session in the database, which must +-- be pending approval. When a recovery code is provided, it is removed from +-- the session owner's codes so that it can't be used again. The code must +-- still be one of the owner's codes, so concurrent approvals cannot use the +-- same code twice. create or replace function approve_session(p_session_id text, p_recovery_code text) returns void as $$ begin - -- Mark session as approved - update session set approved = true where session_id = p_session_id; - - -- If a recovery code was used, remove it so that it can't be used again + -- If a recovery code was used, remove it from the session owner's codes + -- (the user row is locked before the session row, as in reset_user_password). + -- A concurrent approval using the same code waits for the user row and + -- then finds the code gone if p_recovery_code <> '' then - update "user" set tfa_recovery_codes = array_remove(tfa_recovery_codes, p_recovery_code); + update "user" set tfa_recovery_codes = array_remove(tfa_recovery_codes, p_recovery_code) + where user_id = ( + select user_id from session where session_id = p_session_id and approved = false + ) + and p_recovery_code = any(tfa_recovery_codes); + if not found then + perform from session where session_id = p_session_id and approved = false; + if not found then + raise 'session not pending'; + end if; + raise 'invalid recovery code'; + end if; + end if; + + -- Mark session as approved. The session may have been approved or deleted + -- (password reset or update) since the caller looked it up; raising undoes + -- the removal of the recovery code + update session set approved = true where session_id = p_session_id and approved = false; + if not found then + raise 'session not pending'; end if; end $$ language plpgsql; diff --git a/database/migrations/functions/users/refund_auth_attempt.sql b/database/migrations/functions/users/refund_auth_attempt.sql new file mode 100644 index 0000000000..205f41b6bb --- /dev/null +++ b/database/migrations/functions/users/refund_auth_attempt.sql @@ -0,0 +1,11 @@ +-- refund_auth_attempt gives back to the user provided the attempt of the given +-- kind it has just reserved, once that attempt has succeeded. It never gives +-- back more than one interval and never builds up credit beyond an unused +-- allowance. +create or replace function refund_auth_attempt(p_user_id uuid, p_kind text, p_interval int) +returns void as $$ + update auth_attempt_limit + set tat = greatest(tat - make_interval(secs => p_interval), current_timestamp) + where user_id = p_user_id + and kind = p_kind; +$$ language sql; diff --git a/database/migrations/functions/users/register_auth_attempt.sql b/database/migrations/functions/users/register_auth_attempt.sql new file mode 100644 index 0000000000..3cb5936c7d --- /dev/null +++ b/database/migrations/functions/users/register_auth_attempt.sql @@ -0,0 +1,43 @@ +-- register_auth_attempt reserves an attempt of the given kind for the user +-- provided. It returns 0 when the attempt is allowed, or the number of seconds +-- to wait otherwise. The allowance follows GCRA: up to p_burst attempts at +-- once, then one every p_interval seconds. +create or replace function register_auth_attempt( + p_user_id uuid, + p_kind text, + p_burst int, + p_interval int +) +returns int as $$ +declare + v_interval interval := make_interval(secs => p_interval); + v_limit timestamptz := current_timestamp + (p_burst - 1) * v_interval; + v_tat timestamptz; +begin + -- Fast path: allowance exhausted, answer without locking or writing + select tat into v_tat + from auth_attempt_limit + where user_id = p_user_id and kind = p_kind; + if v_tat > v_limit then + return ceil(extract(epoch from v_tat - v_limit))::int; + end if; + + -- Reserve: allowed iff max(tat, now) <= now + (burst - 1) * interval. + -- Concurrent callers queue on the row lock and re-check the condition on + -- the newest tat + insert into auth_attempt_limit as l (user_id, kind, tat) + values (p_user_id, p_kind, current_timestamp + v_interval) + on conflict (user_id, kind) do update + set tat = greatest(l.tat, current_timestamp) + v_interval + where greatest(l.tat, current_timestamp) <= v_limit; + if found then + return 0; + end if; + + -- Rejected: the statement above holds the row lock, so tat is stable + select tat into v_tat + from auth_attempt_limit + where user_id = p_user_id and kind = p_kind; + return greatest(1, ceil(extract(epoch from v_tat - v_limit)))::int; +end +$$ language plpgsql; diff --git a/database/migrations/functions/users/register_password_reset_code.sql b/database/migrations/functions/users/register_password_reset_code.sql index 46607983a1..8cf2eafaf7 100644 --- a/database/migrations/functions/users/register_password_reset_code.sql +++ b/database/migrations/functions/users/register_password_reset_code.sql @@ -1,15 +1,31 @@ -- register_password_reset_code registers a password reset code for the user --- identified by the email provided. +-- identified by the email provided. A user has at most one code, and it is only +-- replaced when it is older than 3 hours; until then the request is refused, +-- so the link already sent keeps working. The 3 hours must stay at least 1 hour +-- below the 4 hours lifetime in verify_password_reset_code, so that a refused +-- request always leaves a link with at least 1 hour left. create or replace function register_password_reset_code(p_email text, p_code text) returns void as $$ +declare + v_user_id uuid; begin - insert into password_reset_code (password_reset_code_id, user_id) - select p_code, user_id from "user" where email = p_email - on conflict (user_id) do update set - password_reset_code_id = p_code, - created_at = current_timestamp; + -- Get the user the email belongs to + select user_id into v_user_id from "user" where email = p_email; if not found then raise 'invalid email'; end if; + + -- Register the code, unless the user has one that is 3 hours old or less. + -- Concurrent requests queue on the existing row (or on the unique index) + -- and re-check the condition against the latest committed code + insert into password_reset_code as prc (password_reset_code_id, user_id) + values (p_code, v_user_id) + on conflict (user_id) do update set + password_reset_code_id = excluded.password_reset_code_id, + created_at = current_timestamp + where prc.created_at < current_timestamp - '3 hours'::interval; + if not found then + raise 'password reset code already registered'; + end if; end $$ language plpgsql; diff --git a/database/migrations/functions/users/register_session_with_password.sql b/database/migrations/functions/users/register_session_with_password.sql new file mode 100644 index 0000000000..1d7f86d6b0 --- /dev/null +++ b/database/migrations/functions/users/register_session_with_password.sql @@ -0,0 +1,18 @@ +-- register_session_with_password registers the provided session, provided the +-- password hash the caller checked (login) or has just set (password reset) is +-- still the user's current one. It waits for any in-flight password change, so +-- a session can never outlive the reset or update that replaced the password. +create or replace function register_session_with_password(p_session jsonb, p_password text) +returns boolean as $$ +begin + perform from "user" + where user_id = (p_session->>'user_id')::uuid + and password = p_password + for share; + if not found then + raise 'password changed'; + end if; + + return register_session(p_session); +end +$$ language plpgsql; diff --git a/database/migrations/functions/users/reset_user_password.sql b/database/migrations/functions/users/reset_user_password.sql index 1f1d2ae08c..d769742e40 100644 --- a/database/migrations/functions/users/reset_user_password.sql +++ b/database/migrations/functions/users/reset_user_password.sql @@ -1,5 +1,6 @@ -- reset_user_password resets the password of the user associated to the code --- provided if it is still valid, returning the email of the user. +-- provided if it is still valid, returning the email of the user. The code is +-- consumed, so it can be used only once, even by concurrent requests. create or replace function reset_user_password(p_code text, p_new_password text) returns text as $$ declare @@ -21,8 +22,13 @@ begin email_verified = true where user_id = v_user_id; - -- Delete password reset code - delete from password_reset_code where user_id = v_user_id; + -- Consume the password reset code. The user row is locked above, so a + -- concurrent reset with the same code, or one whose code has just been + -- replaced, finds no code here and fails, undoing its password update + delete from password_reset_code where password_reset_code_id = p_code; + if not found then + raise 'invalid password reset code'; + end if; -- Invalidate current user sessions delete from session where user_id = v_user_id; diff --git a/database/migrations/functions/users/verify_password_reset_code.sql b/database/migrations/functions/users/verify_password_reset_code.sql index ff4ab807b9..d8071ab5c2 100644 --- a/database/migrations/functions/users/verify_password_reset_code.sql +++ b/database/migrations/functions/users/verify_password_reset_code.sql @@ -1,11 +1,12 @@ -- verify_password_reset_code verifies is the password reset code provided is --- valid. The code must exist and not have expired. +-- valid. The code must exist and not have expired. Codes are valid for 4 hours +-- (register_password_reset_code relies on this lifetime). create or replace function verify_password_reset_code(p_code text) returns void as $$ begin perform from password_reset_code where password_reset_code_id = p_code - and created_at + '15 minute'::interval > current_timestamp; + and created_at + '4 hours'::interval > current_timestamp; if not found then raise 'invalid password reset code'; end if; diff --git a/database/migrations/schema/067_auth_attempt_limit.sql b/database/migrations/schema/067_auth_attempt_limit.sql new file mode 100644 index 0000000000..84e3a89035 --- /dev/null +++ b/database/migrations/schema/067_auth_attempt_limit.sql @@ -0,0 +1,19 @@ +create table if not exists auth_attempt_limit ( + user_id uuid not null references "user" on delete cascade, + kind text not null check (kind in ( + 'login_password', + 'login_tfa', + 'password_update', + 'tfa_disable' + )), + tat timestamptz not null, + primary key (user_id, kind) +); + +-- Password reset codes issued under the previous 15 minutes lifetime must not +-- become valid again under the new 4 hours one +delete from password_reset_code where created_at <= current_timestamp - '15 minutes'::interval; + +---- create above / drop below ---- + +drop table if exists auth_attempt_limit; diff --git a/database/tests/functions/users/approve_session.sql b/database/tests/functions/users/approve_session.sql index d457c09cd3..6f00f74234 100644 --- a/database/tests/functions/users/approve_session.sql +++ b/database/tests/functions/users/approve_session.sql @@ -1,17 +1,22 @@ -- Start transaction and plan tests begin; -select plan(3); +select plan(13); -- Declare some variables \set user1ID '00000000-0000-0000-0000-000000000001' +\set user2ID '00000000-0000-0000-0000-000000000002' \set session1ID '00001' \set session2ID '00002' +\set session3ID '00003' -- Seed some data insert into "user" (user_id, alias, email, tfa_recovery_codes) values (:'user1ID', 'user1', 'user1@email.com', '{code1, code2}'); +insert into "user" (user_id, alias, email, tfa_recovery_codes) +values (:'user2ID', 'user2', 'user2@email.com', '{code1, code3}'); insert into session (session_id, user_id, approved) values (:'session1ID', :'user1ID', false); insert into session (session_id, user_id, approved) values (:'session2ID', :'user1ID', false); +insert into session (session_id, user_id, approved) values (:'session3ID', :'user1ID', false); -- Run some tests select approve_session(:'session1ID', ''); @@ -34,6 +39,74 @@ select is( 'code1 should have been removed from 2fa recovery codes list' ) from "user" where user_id = (select user_id from session where session_id = :'session2ID'); +select is( + '{code1, code3}', + tfa_recovery_codes, + 'Other users 2fa recovery codes should not have been modified' +) +from "user" where user_id = :'user2ID'; + +-- Try using a recovery code that has already been used +select throws_ok( + $$ select approve_session('00003', 'code1') $$, + 'P0001', + 'invalid recovery code', + 'A recovery code already used should not approve another session' +); + +-- Try using a recovery code of another user +select throws_ok( + $$ select approve_session('00003', 'code3') $$, + 'P0001', + 'invalid recovery code', + 'A recovery code of another user should not approve the session' +); +select is( + false, + approved, + 'session3 should still be pending' +) +from session where session_id = :'session3ID'; +select is( + '{code1, code3}', + tfa_recovery_codes, + 'The other user recovery codes should not have been modified' +) +from "user" where user_id = :'user2ID'; + +-- Try approving a session that has already been approved +select throws_ok( + $$ select approve_session('00001', '') $$, + 'P0001', + 'session not pending', + 'A session already approved should not be approved again' +); +select throws_ok( + $$ select approve_session('00001', 'code2') $$, + 'P0001', + 'session not pending', + 'A session already approved should not be approved again with a recovery code' +); + +-- Try approving a session that does not exist +select throws_ok( + $$ select approve_session('unknown', '') $$, + 'P0001', + 'session not pending', + 'A session that does not exist should not be approved' +); +select throws_ok( + $$ select approve_session('unknown', 'code2') $$, + 'P0001', + 'session not pending', + 'A session that does not exist should not be approved with a recovery code' +); +select is( + '{code2}', + tfa_recovery_codes, + 'The recovery code provided in failed approvals should not have been removed' +) +from "user" where user_id = :'user1ID'; -- Finish tests and rollback transaction select * from finish(); diff --git a/database/tests/functions/users/refund_auth_attempt.sql b/database/tests/functions/users/refund_auth_attempt.sql new file mode 100644 index 0000000000..3e40e02c2b --- /dev/null +++ b/database/tests/functions/users/refund_auth_attempt.sql @@ -0,0 +1,53 @@ +-- Start transaction and plan tests +begin; +select plan(4); + +-- Declare some variables +\set user1ID '00000000-0000-0000-0000-000000000001' + +-- Seed some data +insert into "user" (user_id, alias, email) values (:'user1ID', 'user1', 'user1@email.com'); +insert into auth_attempt_limit (user_id, kind, tat) +values (:'user1ID', 'login_password', current_timestamp + '10 hours'::interval); +insert into auth_attempt_limit (user_id, kind, tat) +values (:'user1ID', 'login_tfa', current_timestamp + '30 minutes'::interval); + +-- Refund should give back one interval +select refund_auth_attempt(:'user1ID', 'login_password', 3600); +select is( + tat, + current_timestamp + '9 hours'::interval, + 'Refund should give back one interval' +) +from auth_attempt_limit where user_id = :'user1ID' and kind = 'login_password'; + +-- Next attempt should be allowed +select is( + register_auth_attempt(:'user1ID', 'login_password', 10, 3600), + 0, + 'Attempt after a refund should be allowed' +); + +-- Refund should never set tat before now +select refund_auth_attempt(:'user1ID', 'login_tfa', 3600); +select is( + tat, + current_timestamp, + 'Refund should never set tat before now' +) +from auth_attempt_limit where user_id = :'user1ID' and kind = 'login_tfa'; + +-- Refund without attempts should create nothing +select refund_auth_attempt(:'user1ID', 'tfa_disable', 86400); +select is_empty( + $$ + select * from auth_attempt_limit + where user_id = '00000000-0000-0000-0000-000000000001' + and kind = 'tfa_disable' + $$, + 'Refund without attempts should create nothing' +); + +-- Finish tests and rollback transaction +select * from finish(); +rollback; diff --git a/database/tests/functions/users/register_auth_attempt.sql b/database/tests/functions/users/register_auth_attempt.sql new file mode 100644 index 0000000000..bff21ff15e --- /dev/null +++ b/database/tests/functions/users/register_auth_attempt.sql @@ -0,0 +1,96 @@ +-- Start transaction and plan tests +begin; +select plan(11); + +-- Declare some variables +\set user1ID '00000000-0000-0000-0000-000000000001' +\set user2ID '00000000-0000-0000-0000-000000000002' + +-- Seed some data +insert into "user" (user_id, alias, email) values (:'user1ID', 'user1', 'user1@email.com'); +insert into "user" (user_id, alias, email) values (:'user2ID', 'user2', 'user2@email.com'); + +-- First attempt should be allowed +select is( + register_auth_attempt(:'user1ID', 'login_password', 10, 3600), + 0, + 'First attempt should be allowed' +); +select is( + tat, + current_timestamp + '1 hour'::interval, + 'First attempt should set tat to now + 1 hour' +) +from auth_attempt_limit where user_id = :'user1ID' and kind = 'login_password'; + +-- Attempts up to the burst should be allowed +select is( + array( + select register_auth_attempt(:'user1ID', 'login_password', 10, 3600) + from generate_series(2, 10) + ), + array_fill(0, array[9]), + 'Attempts 2 to 10 should be allowed' +); + +-- Attempt above the burst should be rejected +select is( + register_auth_attempt(:'user1ID', 'login_password', 10, 3600), + 3600, + 'Attempt 11 should be rejected with 3600 seconds to wait' +); +select is( + tat, + current_timestamp + '10 hours'::interval, + 'Rejected attempt should not change tat' +) +from auth_attempt_limit where user_id = :'user1ID' and kind = 'login_password'; + +-- Kinds and users should be independent +select is( + register_auth_attempt(:'user1ID', 'login_tfa', 10, 10800), + 0, + 'Attempt of another kind should be allowed' +); +select is( + register_auth_attempt(:'user2ID', 'login_password', 10, 3600), + 0, + 'Attempt of another user should be allowed' +); + +-- Attempt with a tat in the past should be allowed +update auth_attempt_limit set tat = current_timestamp - '1 day'::interval +where user_id = :'user1ID' and kind = 'login_password'; +select is( + register_auth_attempt(:'user1ID', 'login_password', 10, 3600), + 0, + 'Attempt with a tat in the past should be allowed' +); +select is( + tat, + current_timestamp + '1 hour'::interval, + 'Attempt with a tat in the past should set tat to now + 1 hour' +) +from auth_attempt_limit where user_id = :'user1ID' and kind = 'login_password'; + +-- Attempt of an unknown kind should fail +select throws_ok( + $$ select register_auth_attempt('00000000-0000-0000-0000-000000000001', 'unknown', 10, 3600) $$, + 23514, + 'new row for relation "auth_attempt_limit" violates check constraint "auth_attempt_limit_kind_check"', + 'Attempt of an unknown kind should fail' +); + +-- Deleting the user should delete its attempts +delete from "user" where user_id = :'user2ID'; +select is_empty( + $$ + select * from auth_attempt_limit + where user_id = '00000000-0000-0000-0000-000000000002' + $$, + 'User2 attempts should have been deleted with the user' +); + +-- Finish tests and rollback transaction +select * from finish(); +rollback; diff --git a/database/tests/functions/users/register_password_reset_code.sql b/database/tests/functions/users/register_password_reset_code.sql index b055093a3f..9fc55d9a6f 100644 --- a/database/tests/functions/users/register_password_reset_code.sql +++ b/database/tests/functions/users/register_password_reset_code.sql @@ -1,39 +1,85 @@ -- Start transaction and plan tests begin; -select plan(3); +select plan(8); --- Seed user +-- Seed users insert into "user" (user_id, alias, email) values ('00000000-0000-0000-0000-000000000001', 'user1', 'user1@email.com'); +insert into "user" (user_id, alias, email) +values ('00000000-0000-0000-0000-000000000002', 'user2', 'user2@email.com'); -- Register password reset code select register_password_reset_code('user1@email.com', 'code1'); +select results_eq( + $$ + select password_reset_code_id, created_at + from password_reset_code + where user_id = '00000000-0000-0000-0000-000000000001' + $$, + $$ values ('code1', current_timestamp) $$, + 'Password reset code for user1 should be registered' +); + +-- Try registering another password reset code for the same user +select throws_ok( + $$ select register_password_reset_code('user1@email.com', 'code2') $$, + 'P0001', + 'password reset code already registered', + 'Password reset code for user1 should not be replaced while it is recent' +); +update password_reset_code set created_at = current_timestamp - '3 hours'::interval +where password_reset_code_id = 'code1'; +select throws_ok( + $$ select register_password_reset_code('user1@email.com', 'code2') $$, + 'P0001', + 'password reset code already registered', + 'Password reset code for user1 should not be replaced when it is exactly 3 hours old' +); select is( password_reset_code_id, 'code1', - 'Password reset code for user1 should be registered' + 'Password reset code for user1 should have been kept' ) from password_reset_code join "user" using (user_id) where alias = 'user1'; --- Register another password reset code for the same user -select register_password_reset_code('user1@email.com', 'code2'); -select is( - password_reset_code_id, - 'code2', +-- Register another password reset code for the same user once the code is old +update password_reset_code set created_at = current_timestamp - '3 hours 1 second'::interval +where password_reset_code_id = 'code1'; +select lives_ok( + $$ select register_password_reset_code('user1@email.com', 'code2') $$, + 'Password reset code for user1 should be replaced when it is older than 3 hours' +); +select results_eq( + $$ + select password_reset_code_id, created_at + from password_reset_code + where user_id = '00000000-0000-0000-0000-000000000001' + $$, + $$ values ('code2', current_timestamp) $$, 'Password reset code for user1 should have been updated' -) -from password_reset_code -join "user" using (user_id) -where alias = 'user1'; +); + +-- Register password reset code for another user +select register_password_reset_code('user2@email.com', 'code3'); +select results_eq( + $$ + select alias, password_reset_code_id + from password_reset_code + join "user" using (user_id) + order by password_reset_code_id collate "C" + $$, + $$ values ('user1', 'code2'), ('user2', 'code3') $$, + 'Each user should have their own password reset code' +); -- Try registering password reset code using unregistered email select throws_ok( - $$ select register_password_reset_code('user2@email.com', 'code') $$, + $$ select register_password_reset_code('user3@email.com', 'code') $$, 'P0001', 'invalid email', - 'No password reset code should be registered for unregistered email user2@email.com' + 'No password reset code should be registered for unregistered email user3@email.com' ); -- Finish tests and rollback transaction diff --git a/database/tests/functions/users/register_session_with_password.sql b/database/tests/functions/users/register_session_with_password.sql new file mode 100644 index 0000000000..9a09d690b3 --- /dev/null +++ b/database/tests/functions/users/register_session_with_password.sql @@ -0,0 +1,77 @@ +-- Start transaction and plan tests +begin; +select plan(5); + +-- Seed user +insert into "user" (user_id, alias, email, password) +values ('00000000-0000-0000-0000-000000000001', 'user1', 'user1@email.com', 'hash1'); +insert into "user" (user_id, alias, email, password, tfa_enabled) +values ('00000000-0000-0000-0000-000000000002', 'user2', 'user2@email.com', 'hash2', true); + +-- Register session for user with 2fa disabled +select is( + register_session_with_password(' + { + "session_id": "hashed-session-id-user1", + "user_id": "00000000-0000-0000-0000-000000000001" + } + ', 'hash1'), + true, + 'Session for user1 should be approved' +); + +-- Register session for user with 2fa enabled +select is( + register_session_with_password(' + { + "session_id": "hashed-session-id-user2", + "user_id": "00000000-0000-0000-0000-000000000002" + } + ', 'hash2'), + false, + 'Session for user2 should not be approved' +); + +-- Check if sessions registration succeeded +select results_eq( + $$ + select + session_id, + user_id, + approved + from session + order by session_id collate "C" + $$, + $$ + values + ('hashed-session-id-user1', '00000000-0000-0000-0000-000000000001'::uuid, true), + ('hashed-session-id-user2', '00000000-0000-0000-0000-000000000002'::uuid, false) + $$, + 'Sessions for user1 and user2 should exist' +); + +-- Try registering session with a password that is no longer the current one +select throws_ok( + $$ + select register_session_with_password(' + { + "session_id": "hashed-session-id-user1-2", + "user_id": "00000000-0000-0000-0000-000000000001" + } + ', 'hash0') + $$, + 'P0001', + 'password changed', + 'Session should not be registered when the password has changed' +); +select is_empty( + $$ + select * from session + where session_id = 'hashed-session-id-user1-2' + $$, + 'No session should have been registered when the password has changed' +); + +-- Finish tests and rollback transaction +select * from finish(); +rollback; diff --git a/database/tests/functions/users/reset_user_password.sql b/database/tests/functions/users/reset_user_password.sql index 210856e614..8195d38b27 100644 --- a/database/tests/functions/users/reset_user_password.sql +++ b/database/tests/functions/users/reset_user_password.sql @@ -1,6 +1,6 @@ -- Start transaction and plan tests begin; -select plan(6); +select plan(8); -- Declare some variables \set user1ID '00000000-0000-0000-0000-000000000001' @@ -16,7 +16,7 @@ values (:'user2ID', 'user2', 'user2@email.com'); insert into password_reset_code (password_reset_code_id, user_id, created_at) values (:'code1ID', :'user1ID', current_timestamp); insert into password_reset_code (password_reset_code_id, user_id, created_at) -values (:'code2ID', :'user2ID', current_timestamp - '30 minute'::interval); +values (:'code2ID', :'user2ID', current_timestamp - '4 hours'::interval); insert into session (session_id, user_id) values (gen_random_bytes(32), :'user1ID'); -- Password reset should fail in the following cases @@ -60,6 +60,20 @@ select is( 'User1 email should be returned' ); +-- Password reset code should not be usable again +select throws_ok( + $$ select reset_user_password('00000000-0000-0000-0000-000000000001', 'pass2') $$, + 'P0001', + 'invalid password reset code', + 'Password reset failed because code had already been used' +); + +-- A new password reset code can be registered right after the reset +select lives_ok( + $$ select register_password_reset_code('user1@email.com', 'code3') $$, + 'New password reset code should be registered after the previous one was used' +); + -- Finish tests and rollback transaction select * from finish(); rollback; diff --git a/database/tests/functions/users/verify_password_reset_code.sql b/database/tests/functions/users/verify_password_reset_code.sql index 0ccc62ffdd..23378e56f9 100644 --- a/database/tests/functions/users/verify_password_reset_code.sql +++ b/database/tests/functions/users/verify_password_reset_code.sql @@ -1,32 +1,42 @@ -- Start transaction and plan tests begin; -select plan(3); +select plan(4); -- Declare some variables \set user1ID '00000000-0000-0000-0000-000000000001' \set code1ID '00000000-0000-0000-0000-000000000001' \set user2ID '00000000-0000-0000-0000-000000000002' \set code2ID '00000000-0000-0000-0000-000000000002' +\set user3ID '00000000-0000-0000-0000-000000000003' +\set code3ID '00000000-0000-0000-0000-000000000003' -- Seed some data insert into "user" (user_id, alias, email) values (:'user1ID', 'user1', 'user1@email.com'); insert into "user" (user_id, alias, email) values (:'user2ID', 'user2', 'user2@email.com'); +insert into "user" (user_id, alias, email) +values (:'user3ID', 'user3', 'user3@email.com'); insert into password_reset_code (password_reset_code_id, user_id, created_at) values (:'code1ID', :'user1ID', current_timestamp - '5 minute'::interval); insert into password_reset_code (password_reset_code_id, user_id, created_at) -values (:'code2ID', :'user2ID', current_timestamp - '30 minute'::interval); +values (:'code2ID', :'user2ID', current_timestamp - '4 hours'::interval); +insert into password_reset_code (password_reset_code_id, user_id, created_at) +values (:'code3ID', :'user3ID', current_timestamp - '4 hours'::interval + '1 second'::interval); -- Password reset should succeed select lives_ok( $$ select verify_password_reset_code('00000000-0000-0000-0000-000000000001') $$, 'Verify password reset code succeeded' ); +select lives_ok( + $$ select verify_password_reset_code('00000000-0000-0000-0000-000000000003') $$, + 'Verify password reset code succeeded one second before it expires' +); -- Password reset should fail in the following cases select throws_ok( - $$ select verify_password_reset_code('00000000-0000-0000-0000-000000000003') $$, + $$ select verify_password_reset_code('00000000-0000-0000-0000-000000000004') $$, 'P0001', 'invalid password reset code', 'Verify password reset code failed because code did not exist' diff --git a/database/tests/schema/schema.sql b/database/tests/schema/schema.sql index 8f38375c8c..ed78d1fd4f 100644 --- a/database/tests/schema/schema.sql +++ b/database/tests/schema/schema.sql @@ -1,6 +1,6 @@ -- Start transaction and plan tests begin; -select plan(196); +select plan(202); -- Check default_text_search_config is correct select results_eq( @@ -17,6 +17,7 @@ select has_extension('pg_partman'); -- Check expected tables exist select has_table('api_key'); +select has_table('auth_attempt_limit'); select has_table('delete_user_code'); select has_table('email_verification_code'); select has_table('event'); @@ -55,6 +56,11 @@ select columns_are('api_key', array[ 'user_id', 'created_at' ]); +select columns_are('auth_attempt_limit', array[ + 'user_id', + 'kind', + 'tat' +]); select columns_are('delete_user_code', array[ 'delete_user_code_id', 'user_id', @@ -305,6 +311,9 @@ select columns_are('webhook__package', array[ select indexes_are('api_key', array[ 'api_key_pkey' ]); +select indexes_are('auth_attempt_limit', array[ + 'auth_attempt_limit_pkey' +]); select indexes_are('delete_user_code', array[ 'delete_user_code_pkey', 'delete_user_code_user_id_key' @@ -512,9 +521,12 @@ select has_function('approve_session'); select has_function('delete_user'); select has_function('get_user_profile'); select has_function('get_user_tfa_config'); +select has_function('refund_auth_attempt'); +select has_function('register_auth_attempt'); select has_function('register_delete_user_code'); select has_function('register_password_reset_code'); select has_function('register_session'); +select has_function('register_session_with_password'); select has_function('register_user'); select has_function('reset_user_password'); select has_function('update_user_password'); diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yaml index b1462236f5..e2f2ea92e6 100644 --- a/docs/api/openapi.yaml +++ b/docs/api/openapi.yaml @@ -198,7 +198,11 @@ paths: tags: - Users summary: Register a code to reset the password - description: Register a code to reset the password + description: >- + Register a code to reset the password and email a link to the user. If + the user already has a code issued in the last 3 hours, no new code is + registered and no email is sent. The response is 201 whether or not a + code was registered. operationId: resetPasswordCode requestBody: content: @@ -240,6 +244,16 @@ paths: responses: "200": description: "The request has succeeded" + content: + application/json: + schema: + type: object + required: + - email + properties: + email: + type: string + description: Email of the user the code belongs to "400": $ref: "#/components/responses/BadRequest" "410": @@ -271,7 +285,25 @@ paths: type: string responses: "204": - $ref: "#/components/responses/NoContent" + description: "The request has succeeded, no content returned" + headers: + Set-Cookie: + schema: + type: string + description: >- + Session cookie, set only when a session has been created for + this browser + X-SESSION-APPROVED: + schema: + type: string + enum: + - "true" + - "false" + description: >- + Set only when a session has been created for this browser: + `true` when it is signed in, `false` when the two-factor + authentication passcode is still needed. When absent, the + browser has not been signed in "400": $ref: "#/components/responses/BadRequest" "429": @@ -3927,6 +3959,9 @@ components: type: apiKey in: header name: X-API-KEY-ID + description: >- + API keys cannot be used to create API keys or to manage two-factor + authentication. ApiKeySecret: type: apiKey in: header @@ -6040,6 +6075,11 @@ components: $ref: "#/components/schemas/Error" TooManyRequests: description: The user has sent too many requests in a given amount of time + headers: + Retry-After: + schema: + type: integer + description: Number of seconds to wait before trying again UnauthorizedError: description: Valid authentication credentials not provided content: diff --git a/docs/faq.md b/docs/faq.md index 92a2e68321..5fe9428e97 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -27,6 +27,7 @@ - [Can I add my entire OCI registry to Artifact Hub?](#can-i-add-my-entire-oci-registry-to-artifact-hub) - [How do I add the repository metadata file for OCI repositories?](#how-do-i-add-the-repository-metadata-file-for-oci-repositories) - [Authentication](#authentication) + - [Why am I asked to wait before trying to sign in again?](#why-am-i-asked-to-wait-before-trying-to-sign-in-again) - [How do I reset my 2FA?](#how-do-i-reset-my-2fa) - [Can I change my email address?](#can-i-change-my-email-address) - [Self-hosted Deployments](#self-hosted-deployments) @@ -160,9 +161,23 @@ The metadata file needs to be pushed to the OCI registry as well, using a specia ## Authentication +### Why am I asked to wait before trying to sign in again? + +To protect accounts from password and code guessing, the number of attempts is limited per account. You can try to sign in 10 times, and after that once per hour. Similarly, you can enter 10 authentication codes from your 2FA device/app, and after that one every 3 hours. Changing your password and turning off 2FA from the control panel have their own limits. Correct attempts do not count towards any of these limits, and recovery codes are never limited. When a limit is reached, the UI tells you how long you need to wait. + +If you don't want to wait, you can reset your password using the `Forgot password?` link. Resetting your password signs you in on that browser (if you have 2FA enabled, you'll still need to enter a code) and signs out every other session. While someone keeps triggering the limit, you can only be signed in on one browser at a time. Reset links work for 4 hours and only once, and a new one is only sent when the last one is more than 3 hours old. The reset form shows the email of the account the link belongs to: please check that it is yours before setting a new password. + +If you are repeatedly told that there were too many incorrect codes and you didn't make those attempts, someone may know your password. Reset it to a new password, which signs out every other session and stops them. Then finish signing in with a recovery code, or with a code from your app once the wait is over. API keys cannot be used to create API keys or to manage 2FA, so after a reset you can remove every API key from the control panel. + +In self-hosted instances without email configured, password reset links cannot be sent. In that case, an operator can clear the limits of an account by running the following statement in the database: + +```sql +delete from auth_attempt_limit where user_id = (select user_id from "user" where email = ''); +``` + ### How do I reset my 2FA? -Do you have the recovery codes provided during the 2FA setup process? If yes, when you are prompted for a code from your 2FA device/app, you can use one of those recovery codes to log in. Please note that those recovery codes can only be used once each. +Do you have the recovery codes provided during the 2FA setup process? If yes, when you are prompted for a code from your 2FA device/app, you can use one of those recovery codes to log in, even when the number of code attempts has been limited. Please note that those recovery codes can only be used once each. ### Can I change my email address? diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.go index eb6f501949..6df7c54d87 100644 --- a/internal/handlers/handlers.go +++ b/internal/handlers/handlers.go @@ -199,6 +199,7 @@ func (h *Handlers) setupRouter() { r.Delete("/", h.Users.DeleteUser) r.Post("/delete-user-code", h.Users.RegisterDeleteUserCode) r.Route("/tfa", func(r chi.Router) { + r.Use(h.Users.RejectAPIKey) r.Put("/disable", h.Users.DisableTFA) r.Put("/enable", h.Users.EnableTFA) r.Post("/", h.Users.SetupTFA) @@ -338,7 +339,7 @@ func (h *Handlers) setupRouter() { r.Route("/api-keys", func(r chi.Router) { r.Use(h.Users.RequireLogin) r.Get("/", h.APIKeys.GetOwnedByUser) - r.Post("/", h.APIKeys.Add) + r.With(h.Users.RejectAPIKey).Post("/", h.APIKeys.Add) r.Route("/{apiKeyID}", func(r chi.Router) { r.Get("/", h.APIKeys.Get) r.Put("/", h.APIKeys.Update) diff --git a/internal/handlers/helpers/helpers.go b/internal/handlers/helpers/helpers.go index 91c999140a..a4cb7f1d68 100644 --- a/internal/handlers/helpers/helpers.go +++ b/internal/handlers/helpers/helpers.go @@ -85,7 +85,12 @@ func RenderJSON(w http.ResponseWriter, dataJSON []byte, cacheMaxAge time.Duratio func RenderErrorJSON(w http.ResponseWriter, err error) { w.Header().Set("Content-Type", "application/json") var errMsg string + var tooManyErr *hub.TooManyAttemptsError switch { + case errors.As(err, &tooManyErr): + w.Header().Set("Retry-After", strconv.Itoa(tooManyErr.RetryAfter)) + w.WriteHeader(http.StatusTooManyRequests) + errMsg = hub.ErrTooManyAttempts.Error() case errors.Is(err, hub.ErrInvalidInput): w.WriteHeader(http.StatusBadRequest) if err != nil { diff --git a/internal/handlers/helpers/helpers_test.go b/internal/handlers/helpers/helpers_test.go index 18fb3b82b8..9dc15cf09a 100644 --- a/internal/handlers/helpers/helpers_test.go +++ b/internal/handlers/helpers/helpers_test.go @@ -173,31 +173,43 @@ func TestRenderErrorJSON(t *testing.T) { err error expectedStatusCode int expectedErrorMsg string + expectedRetryAfter string }{ { hub.ErrInvalidInput, http.StatusBadRequest, "invalid input", + "", }, { fmt.Errorf("%w: test error", hub.ErrInvalidInput), http.StatusBadRequest, "invalid input: test error", + "", }, { hub.ErrInsufficientPrivilege, http.StatusForbidden, "", + "", }, { hub.ErrNotFound, http.StatusNotFound, "", + "", + }, + { + &hub.TooManyAttemptsError{RetryAfter: 30}, + http.StatusTooManyRequests, + "too many attempts, please try again later", + "30", }, { tests.ErrFakeDB, http.StatusInternalServerError, "", + "", }, } for i, tc := range testCases { @@ -212,6 +224,7 @@ func TestRenderErrorJSON(t *testing.T) { assert.Equal(t, tc.expectedStatusCode, resp.StatusCode) assert.Equal(t, "application/json", h.Get("Content-Type")) + assert.Equal(t, tc.expectedRetryAfter, h.Get("Retry-After")) var expectedBody bytes.Buffer writeErrorJSON(&expectedBody, tc.expectedErrorMsg) assert.Equal(t, expectedBody.Bytes(), data) diff --git a/internal/handlers/user/handlers.go b/internal/handlers/user/handlers.go index 8bec765941..52c421843b 100644 --- a/internal/handlers/user/handlers.go +++ b/internal/handlers/user/handlers.go @@ -57,6 +57,10 @@ const ( ) var ( + // errAPIKeyNotAllowed error indicates that API keys cannot be used for the + // operation requested. + errAPIKeyNotAllowed = errors.New("api keys cannot be used for this operation") + // errInvalidAPIKey error indicates that the API key provided is not valid. errInvalidAPIKey = errors.New("invalid api key") @@ -168,7 +172,11 @@ func (h *Handlers) ApproveSession(w http.ResponseWriter, r *http.Request) { // Approve session using the passcode provided if err := h.userManager.ApproveSession(r.Context(), sessionID, passcode); err != nil { h.logger.Error().Err(err).Str("method", "ApproveSession").Send() - helpers.RenderErrorJSON(w, err) + if errors.Is(err, user.ErrSessionNotPending) { + helpers.RenderErrorWithCodeJSON(w, errInvalidSession, http.StatusUnauthorized) + } else { + helpers.RenderErrorJSON(w, err) + } return } @@ -376,38 +384,18 @@ func (h *Handlers) Login(w http.ResponseWriter, r *http.Request) { return } - // Register user session - ip, _, _ := net.SplitHostPort(r.RemoteAddr) - session, err := h.userManager.RegisterSession(r.Context(), &hub.Session{ - UserID: checkCredentialsOutput.UserID, - IP: ip, - UserAgent: r.UserAgent(), - }) + // Register user session and set session cookie. If the password has been + // changed since it was checked, the credentials are no longer valid + session, err := h.newSession(w, r, checkCredentialsOutput.UserID, checkCredentialsOutput.PasswordHash) if err != nil { h.logger.Error().Err(err).Str("method", "Login").Msg("registerSession failed") - helpers.RenderErrorJSON(w, err) - return - } - - // Generate and set session cookie - encodedSessionID, err := h.sc.Encode(sessionCookieName, session.SessionID) - if err != nil { - h.logger.Error().Err(err).Str("method", "Login").Msg("sessionID encoding failed") - helpers.RenderErrorJSON(w, err) + if errors.Is(err, user.ErrPasswordChanged) { + helpers.RenderErrorWithCodeJSON(w, nil, http.StatusUnauthorized) + } else { + helpers.RenderErrorJSON(w, err) + } return } - cookie := &http.Cookie{ - Name: sessionCookieName, - Value: encodedSessionID, - Path: "/", - Expires: time.Now().Add(sessionDuration), - HttpOnly: true, - SameSite: http.SameSiteLaxMode, - } - if h.cfg.GetBool("server.cookie.secure") { - cookie.Secure = true - } - http.SetCookie(w, cookie) w.Header().Set(SessionApprovedHeader, strconv.FormatBool(session.Approved)) w.WriteHeader(http.StatusNoContent) } @@ -579,7 +567,9 @@ func (h *Handlers) RegisterPasswordResetCode(w http.ResponseWriter, r *http.Requ helpers.RenderErrorJSON(w, hub.ErrInvalidInput) return } - _ = h.userManager.RegisterPasswordResetCode(r.Context(), input["email"]) + if err := h.userManager.RegisterPasswordResetCode(r.Context(), input["email"]); err != nil { + h.logger.Error().Err(err).Str("method", "RegisterPasswordResetCode").Send() + } w.WriteHeader(http.StatusCreated) } @@ -803,6 +793,60 @@ func (h *Handlers) newUserFromOIDProfile( }, nil } +// newSession registers a new session for the user provided and sets the +// session cookie in the response. When a password hash is provided, the +// session is only registered if it is still the user's current one. +func (h *Handlers) newSession( + w http.ResponseWriter, + r *http.Request, + userID string, + passwordHash string, +) (*hub.Session, error) { + // Register user session + ip, _, _ := net.SplitHostPort(r.RemoteAddr) + session, err := h.userManager.RegisterSession(r.Context(), &hub.Session{ + UserID: userID, + IP: ip, + UserAgent: r.UserAgent(), + PasswordHash: passwordHash, + }) + if err != nil { + return nil, err + } + + // Generate and set session cookie + encodedSessionID, err := h.sc.Encode(sessionCookieName, session.SessionID) + if err != nil { + return nil, fmt.Errorf("sessionID encoding failed: %w", err) + } + cookie := &http.Cookie{ + Name: sessionCookieName, + Value: encodedSessionID, + Path: "/", + Expires: time.Now().Add(sessionDuration), + HttpOnly: true, + SameSite: http.SameSiteLaxMode, + } + if h.cfg.GetBool("server.cookie.secure") { + cookie.Secure = true + } + http.SetCookie(w, cookie) + + return session, nil +} + +// RejectAPIKey is a middleware that refuses requests authenticated with an +// API key, for operations that require an interactive session. +func (h *Handlers) RejectAPIKey(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get(APIKeyIDHeader) != "" && r.Header.Get(APIKeySecretHeader) != "" { + helpers.RenderErrorWithCodeJSON(w, errAPIKeyNotAllowed, http.StatusForbidden) + return + } + next.ServeHTTP(w, r) + }) +} + // RequireLogin is a middleware that verifies if a user is logged in. func (h *Handlers) RequireLogin(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -867,17 +911,25 @@ func (h *Handlers) RequireLogin(next http.Handler) http.Handler { }) } -// ResetPassword is an http handler used to reset the user's password. +// ResetPassword is an http handler used to reset the user's password. Once the +// password has been reset, the browser is signed in to the account, unless it +// is signed in to another one. func (h *Handlers) ResetPassword(w http.ResponseWriter, r *http.Request) { + logger := h.logger.With().Str("method", "ResetPassword").Logger() var input map[string]string if err := json.NewDecoder(r.Body).Decode(&input); err != nil { - h.logger.Error().Err(err).Str("method", "ResetPassword").Msg(hub.ErrInvalidInput.Error()) + logger.Error().Err(err).Msg(hub.ErrInvalidInput.Error()) helpers.RenderErrorJSON(w, hub.ErrInvalidInput) return } - err := h.userManager.ResetPassword(r.Context(), input["code"], input["password"]) + + // Note which account, if any, this browser is signed in to (before the + // reset, which deletes a session of the same account) + signedInUserID, sessionErr := h.approvedSessionUserID(r) + + out, err := h.userManager.ResetPassword(r.Context(), input["code"], input["password"]) if err != nil { - h.logger.Error().Err(err).Str("method", "ResetPassword").Send() + logger.Error().Err(err).Send() if errors.Is(err, user.ErrInvalidPasswordResetCode) { helpers.RenderErrorWithCodeJSON(w, err, http.StatusBadRequest) } else { @@ -885,9 +937,54 @@ func (h *Handlers) ResetPassword(w http.ResponseWriter, r *http.Request) { } return } + + // Sign this browser in, unless it is signed in to another account + switch { + case sessionErr != nil: + logger.Error().Err(sessionErr).Str("user_id", out.UserID).Msg("password reset without sign-in: session check failed") + case out.UserID == "": + // Already logged by the manager + case signedInUserID != "" && signedInUserID != out.UserID: + logger.Info().Str("user_id", out.UserID).Msg("password reset without sign-in: browser signed in to another account") + default: + session, err := h.newSession(w, r, out.UserID, out.PasswordHash) + switch { + case errors.Is(err, user.ErrPasswordChanged): + logger.Info().Str("user_id", out.UserID).Msg("password reset without sign-in: password changed again") + case err != nil: + logger.Error().Err(err).Str("user_id", out.UserID).Msg("password reset without sign-in: registering session failed") + default: + w.Header().Set(SessionApprovedHeader, strconv.FormatBool(session.Approved)) + } + } w.WriteHeader(http.StatusNoContent) } +// approvedSessionUserID returns the id of the user whose approved session the +// request's session cookie identifies. An empty string is returned when the +// request has no usable session cookie or the session is not valid. +func (h *Handlers) approvedSessionUserID(r *http.Request) (string, error) { + // Extract session id from cookie + cookie, err := r.Cookie(sessionCookieName) + if err != nil { + return "", nil + } + var sessionID string + if err := h.sc.Decode(sessionCookieName, cookie.Value, &sessionID); err != nil { + return "", nil + } + + // Check the session is approved and has not expired + checkSessionOutput, err := h.userManager.CheckSession(r.Context(), sessionID, sessionDuration) + if err != nil { + return "", err + } + if !checkSessionOutput.Valid { + return "", nil + } + return checkSessionOutput.UserID, nil +} + // SetupTFA is an http handler used to setup two-factor authentication. func (h *Handlers) SetupTFA(w http.ResponseWriter, r *http.Request) { dataJSON, err := h.userManager.SetupTFA(r.Context()) @@ -969,7 +1066,7 @@ func (h *Handlers) VerifyPasswordResetCode(w http.ResponseWriter, r *http.Reques helpers.RenderErrorJSON(w, hub.ErrInvalidInput) return } - err := h.userManager.VerifyPasswordResetCode(r.Context(), input["code"]) + userEmail, err := h.userManager.VerifyPasswordResetCode(r.Context(), input["code"]) if err != nil { h.logger.Error().Err(err).Str("method", "VerifyPasswordResetCode").Send() if errors.Is(err, user.ErrInvalidPasswordResetCode) { @@ -979,7 +1076,8 @@ func (h *Handlers) VerifyPasswordResetCode(w http.ResponseWriter, r *http.Reques } return } - w.WriteHeader(http.StatusOK) + dataJSON, _ := json.Marshal(map[string]string{"email": userEmail}) + helpers.RenderJSON(w, dataJSON, 0, http.StatusOK) } // OauthState represents the state of an oauth authorization session, used to diff --git a/internal/handlers/user/handlers_test.go b/internal/handlers/user/handlers_test.go index 5b8b77392a..8d4c2a063c 100644 --- a/internal/handlers/user/handlers_test.go +++ b/internal/handlers/user/handlers_test.go @@ -112,6 +112,51 @@ func TestApproveSession(t *testing.T) { assert.Equal(t, http.StatusInternalServerError, resp.StatusCode) }) + t.Run("session not pending", func(t *testing.T) { + t.Parallel() + w := httptest.NewRecorder() + body := strings.NewReader(`{"passcode": "123456"}`) + r, _ := http.NewRequest("PUT", "/", body) + + hw := newHandlersWrapper() + hw.um.On("ApproveSession", r.Context(), sessionID, "123456").Return(user.ErrSessionNotPending) + encodedSessionID, _ := hw.h.sc.Encode(sessionCookieName, sessionID) + r.AddCookie(newTestCookie(sessionCookieName, encodedSessionID)) + hw.h.ApproveSession(w, r) + resp := w.Result() + defer resp.Body.Close() + h := resp.Header + data, _ := io.ReadAll(resp.Body) + + assert.Equal(t, http.StatusUnauthorized, resp.StatusCode) + assert.Equal(t, "application/json", h.Get("Content-Type")) + assert.Equal(t, buildError(errInvalidSession.Error()), data) + hw.um.AssertExpectations(t) + }) + + t.Run("too many attempts", func(t *testing.T) { + t.Parallel() + w := httptest.NewRecorder() + body := strings.NewReader(`{"passcode": "123456"}`) + r, _ := http.NewRequest("PUT", "/", body) + + hw := newHandlersWrapper() + hw.um.On("ApproveSession", r.Context(), sessionID, "123456"). + Return(&hub.TooManyAttemptsError{RetryAfter: 30}) + encodedSessionID, _ := hw.h.sc.Encode(sessionCookieName, sessionID) + r.AddCookie(newTestCookie(sessionCookieName, encodedSessionID)) + hw.h.ApproveSession(w, r) + resp := w.Result() + defer resp.Body.Close() + h := resp.Header + data, _ := io.ReadAll(resp.Body) + + assert.Equal(t, http.StatusTooManyRequests, resp.StatusCode) + assert.Equal(t, "30", h.Get("Retry-After")) + assert.Equal(t, buildError(hub.ErrTooManyAttempts.Error()), data) + hw.um.AssertExpectations(t) + }) + t.Run("session approval succeeded", func(t *testing.T) { t.Parallel() w := httptest.NewRecorder() @@ -434,6 +479,26 @@ func TestDisableTFA(t *testing.T) { hw.um.AssertExpectations(t) }) + t.Run("too many attempts", func(t *testing.T) { + t.Parallel() + w := httptest.NewRecorder() + body := strings.NewReader(`{"passcode": "123456"}`) + r, _ := http.NewRequest("PUT", "/", body) + + hw := newHandlersWrapper() + hw.um.On("DisableTFA", r.Context(), "123456").Return(&hub.TooManyAttemptsError{RetryAfter: 30}) + hw.h.DisableTFA(w, r) + resp := w.Result() + defer resp.Body.Close() + h := resp.Header + data, _ := io.ReadAll(resp.Body) + + assert.Equal(t, http.StatusTooManyRequests, resp.StatusCode) + assert.Equal(t, "30", h.Get("Retry-After")) + assert.Equal(t, buildError(hub.ErrTooManyAttempts.Error()), data) + hw.um.AssertExpectations(t) + }) + t.Run("disable 2fa succeeded", func(t *testing.T) { t.Parallel() w := httptest.NewRecorder() @@ -698,6 +763,28 @@ func TestLogin(t *testing.T) { hw.um.AssertExpectations(t) }) + t.Run("too many attempts", func(t *testing.T) { + t.Parallel() + w := httptest.NewRecorder() + body := strings.NewReader(`{"email": "email", "password": "pass"}`) + r, _ := http.NewRequest("POST", "/", body) + + hw := newHandlersWrapper() + hw.um.On("CheckCredentials", r.Context(), "email", "pass"). + Return(nil, &hub.TooManyAttemptsError{RetryAfter: 120}) + hw.h.Login(w, r) + resp := w.Result() + defer resp.Body.Close() + h := resp.Header + data, _ := io.ReadAll(resp.Body) + + assert.Equal(t, http.StatusTooManyRequests, resp.StatusCode) + assert.Equal(t, "120", h.Get("Retry-After")) + assert.Equal(t, buildError(hub.ErrTooManyAttempts.Error()), data) + assert.Empty(t, resp.Cookies()) + hw.um.AssertExpectations(t) + }) + t.Run("invalid credentials provided", func(t *testing.T) { t.Parallel() w := httptest.NewRecorder() @@ -723,14 +810,40 @@ func TestLogin(t *testing.T) { hw := newHandlersWrapper() hw.um.On("CheckCredentials", r.Context(), "email", "pass"). - Return(&hub.CheckCredentialsOutput{Valid: true, UserID: "userID"}, nil) - hw.um.On("RegisterSession", r.Context(), &hub.Session{UserID: "userID"}). + Return(&hub.CheckCredentialsOutput{Valid: true, UserID: "userID", PasswordHash: "hash"}, nil) + hw.um.On("RegisterSession", r.Context(), &hub.Session{UserID: "userID", PasswordHash: "hash"}). Return(nil, tests.ErrFakeDB) hw.h.Login(w, r) resp := w.Result() defer resp.Body.Close() assert.Equal(t, http.StatusInternalServerError, resp.StatusCode) + assert.Empty(t, resp.Cookies()) + hw.um.AssertExpectations(t) + }) + + t.Run("password changed since it was checked", func(t *testing.T) { + t.Parallel() + w := httptest.NewRecorder() + body := strings.NewReader(`{"email": "email", "password": "pass"}`) + r, _ := http.NewRequest("POST", "/", body) + + hw := newHandlersWrapper() + hw.um.On("CheckCredentials", r.Context(), "email", "pass"). + Return(&hub.CheckCredentialsOutput{Valid: true, UserID: "userID", PasswordHash: "hash"}, nil) + hw.um.On("RegisterSession", r.Context(), &hub.Session{UserID: "userID", PasswordHash: "hash"}). + Return(nil, user.ErrPasswordChanged) + hw.h.Login(w, r) + resp := w.Result() + defer resp.Body.Close() + h := resp.Header + data, _ := io.ReadAll(resp.Body) + + assert.Equal(t, http.StatusUnauthorized, resp.StatusCode) + assert.Equal(t, "application/json", h.Get("Content-Type")) + assert.Equal(t, buildError(""), data) + assert.Empty(t, resp.Cookies()) + assert.Empty(t, h.Get(SessionApprovedHeader)) hw.um.AssertExpectations(t) }) @@ -742,8 +855,8 @@ func TestLogin(t *testing.T) { hw := newHandlersWrapper() hw.um.On("CheckCredentials", r.Context(), "email", "pass"). - Return(&hub.CheckCredentialsOutput{Valid: true, UserID: "userID"}, nil) - hw.um.On("RegisterSession", r.Context(), &hub.Session{UserID: "userID"}). + Return(&hub.CheckCredentialsOutput{Valid: true, UserID: "userID", PasswordHash: "hash"}, nil) + hw.um.On("RegisterSession", r.Context(), &hub.Session{UserID: "userID", PasswordHash: "hash"}). Return(&hub.Session{ SessionID: sessionID, Approved: true, @@ -776,8 +889,8 @@ func TestLogin(t *testing.T) { hw := newHandlersWrapper() hw.um.On("CheckCredentials", r.Context(), "email", "pass"). - Return(&hub.CheckCredentialsOutput{Valid: true, UserID: "userID"}, nil) - hw.um.On("RegisterSession", r.Context(), &hub.Session{UserID: "userID"}). + Return(&hub.CheckCredentialsOutput{Valid: true, UserID: "userID", PasswordHash: "hash"}, nil) + hw.um.On("RegisterSession", r.Context(), &hub.Session{UserID: "userID", PasswordHash: "hash"}). Return(&hub.Session{ SessionID: sessionID, Approved: false, @@ -1282,6 +1395,71 @@ func TestRegisterUser(t *testing.T) { }) } +func TestRejectAPIKey(t *testing.T) { + testCases := []struct { + desc string + apiKeyID string + apiKeySecret string + expectedNextCalled bool + }{ + { + "api key id and secret provided", + "keyID", + "secret", + false, + }, + { + "only api key id provided", + "keyID", + "", + true, + }, + { + "only api key secret provided", + "", + "secret", + true, + }, + { + "no api key provided", + "", + "", + true, + }, + } + for _, tc := range testCases { + t.Run(tc.desc, func(t *testing.T) { + t.Parallel() + w := httptest.NewRecorder() + r, _ := http.NewRequest("POST", "/", nil) + r.Header.Add(APIKeyIDHeader, tc.apiKeyID) + r.Header.Add(APIKeySecretHeader, tc.apiKeySecret) + + hw := newHandlersWrapper() + var nextCalled bool + next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + nextCalled = true + }) + hw.h.RejectAPIKey(next).ServeHTTP(w, r) + resp := w.Result() + defer resp.Body.Close() + h := resp.Header + data, _ := io.ReadAll(resp.Body) + + assert.Equal(t, tc.expectedNextCalled, nextCalled) + if tc.expectedNextCalled { + assert.Equal(t, http.StatusOK, resp.StatusCode) + } else { + assert.Equal(t, http.StatusForbidden, resp.StatusCode) + assert.Equal(t, "application/json", h.Get("Content-Type")) + assert.Equal(t, buildError(errAPIKeyNotAllowed.Error()), data) + } + hw.um.AssertExpectations(t) + hw.am.AssertExpectations(t) + }) + } +} + func TestRequireLogin(t *testing.T) { sessionID := "sessionID" @@ -1488,6 +1666,8 @@ func TestRequireLogin(t *testing.T) { } func TestResetPassword(t *testing.T) { + sessionID := "sessionID" + t.Run("invalid input", func(t *testing.T) { t.Parallel() w := httptest.NewRecorder() @@ -1500,57 +1680,189 @@ func TestResetPassword(t *testing.T) { defer resp.Body.Close() assert.Equal(t, http.StatusBadRequest, resp.StatusCode) + assert.Empty(t, resp.Cookies()) + assert.Empty(t, resp.Header.Get(SessionApprovedHeader)) hw.um.AssertExpectations(t) }) - t.Run("password reset failed (invalid code)", func(t *testing.T) { - t.Parallel() - w := httptest.NewRecorder() - body := strings.NewReader(`{"code": "code", "password": "password"}`) - r, _ := http.NewRequest("PUT", "/", body) - - hw := newHandlersWrapper() - hw.um.On("ResetPassword", r.Context(), "code", "password"). - Return(user.ErrInvalidPasswordResetCode) - hw.h.ResetPassword(w, r) - resp := w.Result() - defer resp.Body.Close() - - assert.Equal(t, http.StatusBadRequest, resp.StatusCode) - hw.um.AssertExpectations(t) - }) - - t.Run("password reset failed (db error)", func(t *testing.T) { - t.Parallel() - w := httptest.NewRecorder() - body := strings.NewReader(`{"code": "code", "password": "password"}`) - r, _ := http.NewRequest("PUT", "/", body) + t.Run("password reset failed", func(t *testing.T) { + testCases := []struct { + description string + err error + expectedStatusCode int + }{ + { + "invalid code", + user.ErrInvalidPasswordResetCode, + http.StatusBadRequest, + }, + { + "database error", + tests.ErrFakeDB, + http.StatusInternalServerError, + }, + } + for _, tc := range testCases { + t.Run(tc.description, func(t *testing.T) { + t.Parallel() + w := httptest.NewRecorder() + body := strings.NewReader(`{"code": "code", "password": "password"}`) + r, _ := http.NewRequest("PUT", "/", body) - hw := newHandlersWrapper() - hw.um.On("ResetPassword", r.Context(), "code", "password").Return(tests.ErrFakeDB) - hw.h.ResetPassword(w, r) - resp := w.Result() - defer resp.Body.Close() + hw := newHandlersWrapper() + hw.um.On("ResetPassword", r.Context(), "code", "password").Return(nil, tc.err) + hw.h.ResetPassword(w, r) + resp := w.Result() + defer resp.Body.Close() - assert.Equal(t, http.StatusInternalServerError, resp.StatusCode) - hw.um.AssertExpectations(t) + assert.Equal(t, tc.expectedStatusCode, resp.StatusCode) + assert.Empty(t, resp.Cookies()) + assert.Empty(t, resp.Header.Get(SessionApprovedHeader)) + hw.um.AssertNotCalled(t, "RegisterSession", mock.Anything, mock.Anything) + hw.um.AssertExpectations(t) + }) + } }) t.Run("password reset succeeded", func(t *testing.T) { - t.Parallel() - w := httptest.NewRecorder() - body := strings.NewReader(`{"code": "code", "password": "password"}`) - r, _ := http.NewRequest("PUT", "/", body) - r = r.WithContext(context.WithValue(r.Context(), hub.UserIDKey, "userID")) + testCases := []struct { + description string + sessionCookie string // "", "valid" or "undecodable" + checkSessionOutput *hub.CheckSessionOutput + checkSessionErr error + resetPasswordOutput *hub.ResetPasswordOutput + registerSession bool + registeredSession *hub.Session + registerSessionErr error + expectedSignIn bool + expectedApprovedHeader string + }{ + { + description: "no session cookie, session approved", + resetPasswordOutput: &hub.ResetPasswordOutput{UserID: "userID", PasswordHash: "hash"}, + registerSession: true, + registeredSession: &hub.Session{SessionID: sessionID, Approved: true}, + expectedSignIn: true, + expectedApprovedHeader: "true", + }, + { + description: "no session cookie, session pending approval", + resetPasswordOutput: &hub.ResetPasswordOutput{UserID: "userID", PasswordHash: "hash"}, + registerSession: true, + registeredSession: &hub.Session{SessionID: sessionID, Approved: false}, + expectedSignIn: true, + expectedApprovedHeader: "false", + }, + { + description: "approved session of the same user", + sessionCookie: "valid", + checkSessionOutput: &hub.CheckSessionOutput{Valid: true, UserID: "userID"}, + resetPasswordOutput: &hub.ResetPasswordOutput{UserID: "userID", PasswordHash: "hash"}, + registerSession: true, + registeredSession: &hub.Session{SessionID: sessionID, Approved: true}, + expectedSignIn: true, + expectedApprovedHeader: "true", + }, + { + description: "approved session of another user", + sessionCookie: "valid", + checkSessionOutput: &hub.CheckSessionOutput{Valid: true, UserID: "otherUserID"}, + resetPasswordOutput: &hub.ResetPasswordOutput{UserID: "userID", PasswordHash: "hash"}, + }, + { + description: "session not valid", + sessionCookie: "valid", + checkSessionOutput: &hub.CheckSessionOutput{Valid: false}, + resetPasswordOutput: &hub.ResetPasswordOutput{UserID: "userID", PasswordHash: "hash"}, + registerSession: true, + registeredSession: &hub.Session{SessionID: sessionID, Approved: true}, + expectedSignIn: true, + expectedApprovedHeader: "true", + }, + { + description: "undecodable session cookie", + sessionCookie: "undecodable", + resetPasswordOutput: &hub.ResetPasswordOutput{UserID: "userID", PasswordHash: "hash"}, + registerSession: true, + registeredSession: &hub.Session{SessionID: sessionID, Approved: true}, + expectedSignIn: true, + expectedApprovedHeader: "true", + }, + { + description: "error checking session", + sessionCookie: "valid", + checkSessionErr: tests.ErrFakeDB, + resetPasswordOutput: &hub.ResetPasswordOutput{UserID: "userID", PasswordHash: "hash"}, + }, + { + description: "password changed again", + resetPasswordOutput: &hub.ResetPasswordOutput{UserID: "userID", PasswordHash: "hash"}, + registerSession: true, + registerSessionErr: user.ErrPasswordChanged, + }, + { + description: "error registering session", + resetPasswordOutput: &hub.ResetPasswordOutput{UserID: "userID", PasswordHash: "hash"}, + registerSession: true, + registerSessionErr: tests.ErrFakeDB, + }, + { + description: "user id not available", + resetPasswordOutput: &hub.ResetPasswordOutput{UserID: "", PasswordHash: "hash"}, + }, + } + for _, tc := range testCases { + t.Run(tc.description, func(t *testing.T) { + t.Parallel() + w := httptest.NewRecorder() + body := strings.NewReader(`{"code": "code", "password": "password"}`) + r, _ := http.NewRequest("PUT", "/", body) - hw := newHandlersWrapper() - hw.um.On("ResetPassword", r.Context(), "code", "password").Return(nil) - hw.h.ResetPassword(w, r) - resp := w.Result() - defer resp.Body.Close() + hw := newHandlersWrapper() + switch tc.sessionCookie { + case "valid": + encodedSessionID, _ := hw.h.sc.Encode(sessionCookieName, "currentSessionID") + r.AddCookie(newTestCookie(sessionCookieName, encodedSessionID)) + hw.um.On("CheckSession", r.Context(), "currentSessionID", sessionDuration). + Return(tc.checkSessionOutput, tc.checkSessionErr) + case "undecodable": + r.AddCookie(newTestCookie(sessionCookieName, "invalidValue")) + } + hw.um.On("ResetPassword", r.Context(), "code", "password").Return(tc.resetPasswordOutput, nil) + if tc.registerSession { + hw.um.On("RegisterSession", r.Context(), &hub.Session{UserID: "userID", PasswordHash: "hash"}). + Return(tc.registeredSession, tc.registerSessionErr) + } + hw.h.ResetPassword(w, r) + resp := w.Result() + defer resp.Body.Close() + h := resp.Header - assert.Equal(t, http.StatusNoContent, resp.StatusCode) - hw.um.AssertExpectations(t) + assert.Equal(t, http.StatusNoContent, resp.StatusCode) + assert.Equal(t, tc.expectedApprovedHeader, h.Get(SessionApprovedHeader)) + if tc.expectedSignIn { + require.Len(t, resp.Cookies(), 1) + cookie := resp.Cookies()[0] + assert.Equal(t, sessionCookieName, cookie.Name) + assert.Equal(t, "/", cookie.Path) + assert.True(t, cookie.HttpOnly) + assert.False(t, cookie.Secure) + var cookieSessionID string + err := hw.h.sc.Decode(sessionCookieName, cookie.Value, &cookieSessionID) + require.NoError(t, err) + assert.Equal(t, sessionID, cookieSessionID) + } else { + assert.Empty(t, resp.Cookies()) + } + if !tc.registerSession { + hw.um.AssertNotCalled(t, "RegisterSession", mock.Anything, mock.Anything) + } + if tc.sessionCookie != "valid" { + hw.um.AssertNotCalled(t, "CheckSession", mock.Anything, mock.Anything, mock.Anything) + } + hw.um.AssertExpectations(t) + }) + } }) } @@ -1659,6 +1971,28 @@ func TestUpdatePassword(t *testing.T) { hw.um.AssertExpectations(t) }) + t.Run("too many attempts", func(t *testing.T) { + t.Parallel() + w := httptest.NewRecorder() + body := strings.NewReader(`{"old": "old", "new": "new"}`) + r, _ := http.NewRequest("PUT", "/", body) + r = r.WithContext(context.WithValue(r.Context(), hub.UserIDKey, "userID")) + + hw := newHandlersWrapper() + hw.um.On("UpdatePassword", r.Context(), "old", "new"). + Return(&hub.TooManyAttemptsError{RetryAfter: 30}) + hw.h.UpdatePassword(w, r) + resp := w.Result() + defer resp.Body.Close() + h := resp.Header + data, _ := io.ReadAll(resp.Body) + + assert.Equal(t, http.StatusTooManyRequests, resp.StatusCode) + assert.Equal(t, "30", h.Get("Retry-After")) + assert.Equal(t, buildError(hub.ErrTooManyAttempts.Error()), data) + hw.um.AssertExpectations(t) + }) + t.Run("password updated successfully", func(t *testing.T) { t.Parallel() w := httptest.NewRecorder() @@ -1821,21 +2155,25 @@ func TestVerifyPasswordResetCode(t *testing.T) { t.Run("valid input", func(t *testing.T) { testCases := []struct { description string + email string err error expectedStatusCode int }{ { "valid code", + "user@email.com", nil, http.StatusOK, }, { "invalid code", + "", user.ErrInvalidPasswordResetCode, http.StatusGone, }, { "database error", + "", tests.ErrFakeDB, http.StatusInternalServerError, }, @@ -1847,12 +2185,18 @@ func TestVerifyPasswordResetCode(t *testing.T) { r, _ := http.NewRequest("POST", "/", strings.NewReader(`{"code": "code"}`)) hw := newHandlersWrapper() - hw.um.On("VerifyPasswordResetCode", r.Context(), "code").Return(tc.err) + hw.um.On("VerifyPasswordResetCode", r.Context(), "code").Return(tc.email, tc.err) hw.h.VerifyPasswordResetCode(w, r) resp := w.Result() defer resp.Body.Close() + h := resp.Header + data, _ := io.ReadAll(resp.Body) assert.Equal(t, tc.expectedStatusCode, resp.StatusCode) + if tc.err == nil { + assert.Equal(t, "application/json", h.Get("Content-Type")) + assert.Equal(t, []byte(`{"email":"user@email.com"}`), data) + } hw.um.AssertExpectations(t) }) } diff --git a/internal/hub/errors.go b/internal/hub/errors.go index e9732a9f07..bf312e226a 100644 --- a/internal/hub/errors.go +++ b/internal/hub/errors.go @@ -12,8 +12,26 @@ var ( // ErrNotFound indicates that the requested item was not found. ErrNotFound = errors.New("not found") + + // ErrTooManyAttempts indicates that too many attempts of an operation have + // been made and it must be retried later. The web application relies on + // this message to tell this error apart from a 429 sent by a CDN or proxy + // (TOO_MANY_ATTEMPTS_MESSAGE in web/src/api/index.ts). + ErrTooManyAttempts = errors.New("too many attempts, please try again later") ) +// TooManyAttemptsError provides some details about an ErrTooManyAttempts error. +type TooManyAttemptsError struct { + RetryAfter int // Seconds until the next attempt is allowed +} + +// Error implements the error interface. +func (e *TooManyAttemptsError) Error() string { return ErrTooManyAttempts.Error() } + +// Unwrap returns the ErrTooManyAttempts error this error provides details +// about. +func (e *TooManyAttemptsError) Unwrap() error { return ErrTooManyAttempts } + // ErrorsCollector interface defines the methods that an errors collector // implementation should provide. type ErrorsCollector interface { diff --git a/internal/hub/user.go b/internal/hub/user.go index 6b55b2fd6e..e2a1070cd1 100644 --- a/internal/hub/user.go +++ b/internal/hub/user.go @@ -8,8 +8,9 @@ import ( // CheckCredentialsOutput represents the output returned by the // CheckCredentials method. type CheckCredentialsOutput struct { - Valid bool `json:"valid"` - UserID string `json:"user_id"` + Valid bool `json:"valid"` + UserID string `json:"user_id"` + PasswordHash string `json:"-"` } // CheckSessionOutput represents the output returned by the CheckSession method. @@ -18,13 +19,20 @@ type CheckSessionOutput struct { UserID string `json:"user_id"` } +// ResetPasswordOutput represents the output returned by the ResetPassword method. +type ResetPasswordOutput struct { + UserID string `json:"user_id"` // Empty if it could not be looked up after the reset + PasswordHash string `json:"-"` +} + // Session represents some information about a user session. type Session struct { - SessionID string `json:"session_id"` - UserID string `json:"user_id"` - IP string `json:"ip"` - UserAgent string `json:"user_agent"` - Approved bool `json:"approved"` + SessionID string `json:"session_id"` + UserID string `json:"user_id"` + IP string `json:"ip"` + UserAgent string `json:"user_agent"` + Approved bool `json:"approved"` + PasswordHash string `json:"-"` } // SetupTFAOutput represents the output returned by the SetupTFA method. @@ -77,10 +85,10 @@ type UserManager interface { RegisterPasswordResetCode(ctx context.Context, userEmail string) error RegisterSession(ctx context.Context, session *Session) (*Session, error) RegisterUser(ctx context.Context, user *User) error - ResetPassword(ctx context.Context, code, newPassword string) error + ResetPassword(ctx context.Context, code, newPassword string) (*ResetPasswordOutput, error) SetupTFA(ctx context.Context) ([]byte, error) UpdatePassword(ctx context.Context, old, new string) error UpdateProfile(ctx context.Context, user *User) error VerifyEmail(ctx context.Context, code string) (bool, error) - VerifyPasswordResetCode(ctx context.Context, code string) error + VerifyPasswordResetCode(ctx context.Context, code string) (string, error) } diff --git a/internal/user/manager.go b/internal/user/manager.go index dbdd1ddd1a..be1b036ed5 100644 --- a/internal/user/manager.go +++ b/internal/user/manager.go @@ -11,6 +11,7 @@ import ( "fmt" "html/template" "image/png" + "strings" "time" _ "embed" // Used by templates @@ -21,6 +22,7 @@ import ( "github.com/jackc/pgx/v4" "github.com/pquerna/otp" "github.com/pquerna/otp/totp" + "github.com/rs/zerolog/log" "github.com/satori/uuid" "github.com/spf13/viper" pwvalidator "github.com/wagslane/go-password-validator" @@ -29,30 +31,35 @@ import ( const ( // Database queries - approveSessionDBQ = `select approve_session($1::text, $2::text)` - checkUserAliasAvailDBQ = `select user_id from "user" where alias = $1::text` - checkUserCredsDBQ = `select user_id, password from "user" where email = $1 and password is not null and email_verified = true` //#nosec - deleteSessionDBQ = `delete from session where session_id = $1` - deleteUserDBQ = `select delete_user($1::uuid, $2::text)` - disableTFADBQ = `update "user" set tfa_enabled = false, tfa_url = null, tfa_recovery_codes = null where user_id = $1 and tfa_enabled = true` - enableTFADBQ = `update "user" set tfa_enabled = true where user_id = $1` - getSessionDBQ = `select user_id, floor(extract(epoch from created_at)), approved from session where session_id = $1` - getTFAConfigDBQ = `select get_user_tfa_config($1::uuid)` - getUserEmailDBQ = `select email from "user" where user_id = $1` - getUserIDFromEmailDBQ = `select user_id from "user" where email = $1` - getUserIDFromSessionIDDBQ = `select user_id from session where session_id = $1` - getUserPasswordDBQ = `select password from "user" where user_id = $1 and password is not null` - getUserProfileDBQ = `select get_user_profile($1::uuid)` - registerPasswordResetCodeDBQ = `select register_password_reset_code($1::text, $2::text)` - registerSessionDBQ = `select register_session($1::jsonb)` - registerUserDBQ = `select register_user($1::jsonb)` - registerDeleteUserCodeDBQ = `select register_delete_user_code($1::uuid, $2::text)` - resetUserPasswordDBQ = `select reset_user_password($1::text, $2::text)` - updateTFAInfoDBQ = `update "user" set tfa_url = $2, tfa_recovery_codes = $3 where user_id = $1` - updateUserPasswordDBQ = `select update_user_password($1::uuid, $2::text, $3::text)` - updateUserProfileDBQ = `select update_user_profile($1::uuid, $2::jsonb)` - verifyEmailDBQ = `select verify_email($1::uuid)` - verifyPasswordResetCodeDBQ = `select verify_password_reset_code($1::text)` + approveSessionDBQ = `select approve_session($1::text, $2::text)` + checkUserAliasAvailDBQ = `select user_id from "user" where alias = $1::text` + checkUserCredsDBQ = `select user_id, password from "user" where email = $1 and password is not null and email_verified = true` //#nosec + deletePasswordResetCodeDBQ = `delete from password_reset_code where password_reset_code_id = $1` + deleteSessionDBQ = `delete from session where session_id = $1` + deleteUserDBQ = `select delete_user($1::uuid, $2::text)` + disableTFADBQ = `update "user" set tfa_enabled = false, tfa_url = null, tfa_recovery_codes = null where user_id = $1 and tfa_enabled = true` + enableTFADBQ = `update "user" set tfa_enabled = true where user_id = $1 and tfa_url = $2 and tfa_enabled is not true returning user_id` + getPasswordResetCodeEmailDBQ = `select u.email from "user" u join password_reset_code prc using (user_id) where prc.password_reset_code_id = $1` // #nosec G101 -- query, not a credential + getSessionDBQ = `select user_id, floor(extract(epoch from created_at)), approved from session where session_id = $1` + getTFAConfigDBQ = `select get_user_tfa_config($1::uuid)` + getUserEmailDBQ = `select email from "user" where user_id = $1` + getUserIDFromEmailDBQ = `select user_id from "user" where email = $1` + getUserIDFromSessionIDDBQ = `select user_id from session where session_id = $1 and approved = false` + getUserPasswordDBQ = `select password from "user" where user_id = $1 and password is not null` + getUserProfileDBQ = `select get_user_profile($1::uuid)` + refundAuthAttemptDBQ = `select refund_auth_attempt($1::uuid, $2::text, $3::int)` + registerAuthAttemptDBQ = `select register_auth_attempt($1::uuid, $2::text, $3::int, $4::int)` + registerPasswordResetCodeDBQ = `select register_password_reset_code($1::text, $2::text)` + registerSessionDBQ = `select register_session($1::jsonb)` + registerSessionWithPasswordDBQ = `select register_session_with_password($1::jsonb, $2::text)` + registerUserDBQ = `select register_user($1::jsonb)` + registerDeleteUserCodeDBQ = `select register_delete_user_code($1::uuid, $2::text)` + resetUserPasswordDBQ = `select reset_user_password($1::text, $2::text)` + updateTFAInfoDBQ = `update "user" set tfa_url = $2, tfa_recovery_codes = $3 where user_id = $1 and tfa_enabled is not true returning user_id` + updateUserPasswordDBQ = `select update_user_password($1::uuid, $2::text, $3::text)` + updateUserProfileDBQ = `select update_user_profile($1::uuid, $2::jsonb)` + verifyEmailDBQ = `select verify_email($1::uuid)` + verifyPasswordResetCodeDBQ = `select verify_password_reset_code($1::text)` numRecoveryCodes = 10 ) @@ -63,6 +70,21 @@ const ( PasswordMinEntropyBits = 50 ) +// attemptLimit represents the allowance of attempts of a given kind each user +// has (see register_auth_attempt). +type attemptLimit struct { + kind string + burst int + interval int // Seconds +} + +var ( + loginPasswordLimit = attemptLimit{"login_password", 10, 3600} + loginTFALimit = attemptLimit{"login_tfa", 10, 3 * 3600} + passwordUpdateLimit = attemptLimit{"password_update", 10, 3600} + tfaDisableLimit = attemptLimit{"tfa_disable", 5, 24 * 3600} +) + type templateID int const ( @@ -118,12 +140,54 @@ var ( // database when the password reset code is not valid. errInvalidPasswordResetCodeDB = errors.New("ERROR: invalid password reset code (SQLSTATE P0001)") + // errPasswordChangedDB represents the error returned from the database + // when the password hash provided is no longer the user's current one. + errPasswordChangedDB = errors.New("ERROR: password changed (SQLSTATE P0001)") + + // errInvalidEmailDB represents the error returned from the database when + // the email provided does not belong to any user. + errInvalidEmailDB = errors.New("ERROR: invalid email (SQLSTATE P0001)") + + // errPasswordResetCodeAlreadyRegisteredDB represents the error returned + // from the database when the user already has a password reset code not + // older than 3 hours. + errPasswordResetCodeAlreadyRegisteredDB = errors.New("ERROR: password reset code already registered (SQLSTATE P0001)") + + // errInvalidRecoveryCodeDB represents the error returned from the database + // when the recovery code provided is not one of the user's codes anymore. + errInvalidRecoveryCodeDB = errors.New("ERROR: invalid recovery code (SQLSTATE P0001)") + + // errSessionNotPendingDB represents the error returned from the database + // when the session to approve does not exist or has already been approved. + errSessionNotPendingDB = errors.New("ERROR: session not pending (SQLSTATE P0001)") + // errInvalidTFAPasscode indicates that the TFA passcode provided is not // valid. errInvalidTFAPasscode = fmt.Errorf("%w: %s", hub.ErrInvalidInput, "invalid passcode") + // errTFAAlreadyEnabled indicates that two-factor authentication is + // already enabled for the user. + errTFAAlreadyEnabled = fmt.Errorf("%w: %s", hub.ErrInvalidInput, "two-factor authentication already enabled") + + // errTFASetupChanged indicates that two-factor authentication has not + // been set up, or that the setup has changed since the passcode was + // validated. + errTFASetupChanged = fmt.Errorf( + "%w: %s", + hub.ErrInvalidInput, + "two-factor authentication has not been set up or has changed, please start again", + ) + // ErrNotFound indicates that the user does not exist. ErrNotFound = errors.New("user not found") + + // ErrPasswordChanged indicates that the user's password is no longer the + // one the operation was based on. + ErrPasswordChanged = errors.New("password changed") + + // ErrSessionNotPending indicates that the session provided does not exist + // or has already been approved. + ErrSessionNotPending = errors.New("session not found or already approved") ) // Manager provides an API to manage users. @@ -158,14 +222,18 @@ func (m *Manager) ApproveSession(ctx context.Context, sessionID, passcode string if len(sessionID) == 0 { return fmt.Errorf("%w: %s", hub.ErrInvalidInput, "sessionID not provided") } + passcode = strings.TrimSpace(passcode) if passcode == "" { return fmt.Errorf("%w: %s", hub.ErrInvalidInput, "passcode not provided") } - // Get id of the user the session belongs to + // Get id of the user the session belongs to (only pending sessions) var userID string err := m.db.QueryRow(ctx, getUserIDFromSessionIDDBQ, hash(sessionID)).Scan(&userID) if err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return ErrSessionNotPending + } return err } @@ -175,23 +243,41 @@ func (m *Manager) ApproveSession(ctx context.Context, sessionID, passcode string return err } - // Validate passcode provided by user - key, err := otp.NewKeyFromURL(c.URL) - if err != nil { - return err - } - validRecoveryCodeProvided := isValidRecoveryCode(c.RecoveryCodes, passcode) - if !totp.Validate(passcode, key.Secret()) && !validRecoveryCodeProvided { - return errInvalidTFAPasscode - } - - // Approve session + // Validate passcode provided by user. TOTP codes are subject to an + // attempts limit, recovery codes are not. var recoveryCode string - if validRecoveryCodeProvided { + if isTOTPCode(passcode) { + if err := m.reserveAttempt(ctx, userID, loginTFALimit); err != nil { + return err + } + key, err := otp.NewKeyFromURL(c.URL) + if err != nil { + return err + } + if !totp.Validate(passcode, key.Secret()) { + return errInvalidTFAPasscode + } + m.refundAttempt(ctx, userID, loginTFALimit) + } else { + if !isValidRecoveryCode(c.RecoveryCodes, passcode) { + return errInvalidTFAPasscode + } recoveryCode = passcode } - _, err = m.db.Exec(ctx, approveSessionDBQ, hash(sessionID), recoveryCode) - return err + + // Approve session. The database checks again that the session is still + // pending and the recovery code still available, as a concurrent request + // may have changed that since they were read above + if _, err := m.db.Exec(ctx, approveSessionDBQ, hash(sessionID), recoveryCode); err != nil { + switch err.Error() { + case errInvalidRecoveryCodeDB.Error(): + return errInvalidTFAPasscode + case errSessionNotPendingDB.Error(): + return ErrSessionNotPending + } + return err + } + return nil } // CheckAvailability checks the availability of a given value for the provided @@ -253,16 +339,23 @@ func (m *Manager) CheckCredentials( return nil, err } + // Reserve an attempt before checking the password + if err := m.reserveAttempt(ctx, userID, loginPasswordLimit); err != nil { + return nil, err + } + // Check if the password provided is valid err = bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password)) if err != nil { return &hub.CheckCredentialsOutput{Valid: false}, nil } + m.refundAttempt(ctx, userID, loginPasswordLimit) return &hub.CheckCredentialsOutput{ - Valid: true, - UserID: userID, - }, err + Valid: true, + UserID: userID, + PasswordHash: hashedPassword, + }, nil } // CheckSession checks if the user session provided is valid. @@ -358,6 +451,7 @@ func (m *Manager) DisableTFA(ctx context.Context, passcode string) error { userID := ctx.Value(hub.UserIDKey).(string) // Validate input + passcode = strings.TrimSpace(passcode) if passcode == "" { return fmt.Errorf("%w: %s", hub.ErrInvalidInput, "passcode not provided") } @@ -368,12 +462,21 @@ func (m *Manager) DisableTFA(ctx context.Context, passcode string) error { return err } - // Validate passcode provided by user - key, err := otp.NewKeyFromURL(c.URL) - if err != nil { - return err - } - if !totp.Validate(passcode, key.Secret()) && !isValidRecoveryCode(c.RecoveryCodes, passcode) { + // Validate passcode provided by user. TOTP codes are subject to an + // attempts limit, recovery codes are not. + if isTOTPCode(passcode) { + if err := m.reserveAttempt(ctx, userID, tfaDisableLimit); err != nil { + return err + } + key, err := otp.NewKeyFromURL(c.URL) + if err != nil { + return err + } + if !totp.Validate(passcode, key.Secret()) { + return errInvalidTFAPasscode + } + m.refundAttempt(ctx, userID, tfaDisableLimit) + } else if !isValidRecoveryCode(c.RecoveryCodes, passcode) { return errInvalidTFAPasscode } @@ -421,6 +524,10 @@ func (m *Manager) EnableTFA(ctx context.Context, passcode string) error { return err } + if c.Enabled { + return errTFAAlreadyEnabled + } + // Validate passcode provided by user key, err := otp.NewKeyFromURL(c.URL) if err != nil { @@ -430,8 +537,13 @@ func (m *Manager) EnableTFA(ctx context.Context, passcode string) error { return errInvalidTFAPasscode } - // Set TFA as enabled in the database - if _, err := m.db.Exec(ctx, enableTFADBQ, userID); err != nil { + // Set TFA as enabled in the database, provided the setup validated above + // is still the current one + var id string + if err := m.db.QueryRow(ctx, enableTFADBQ, userID, c.URL).Scan(&id); err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return errTFASetupChanged + } return err } @@ -542,43 +654,46 @@ func (m *Manager) RegisterDeleteUserCode(ctx context.Context) error { } // RegisterPasswordResetCode registers a code that allows the user identified -// by the email provided to reset the password. A link containing the code will -// be emailed to the user to initiate the password reset process. +// by the email provided to reset the password, and emails the user a link +// containing it. Nothing is registered or sent when the email is unknown or +// when the user already has a code not older than 3 hours (the link sent with +// it is still valid); both cases return nil. func (m *Manager) RegisterPasswordResetCode(ctx context.Context, userEmail string) error { // Validate input if userEmail == "" { return fmt.Errorf("%w: %s", hub.ErrInvalidInput, "email not provided") } + // Run to completion even if the client goes away, so that a stored code + // is either emailed or removed + ctx = context.WithoutCancel(ctx) + // Register password reset code in database randomBytes := make([]byte, 32) if _, err := rand.Read(randomBytes); err != nil { return err } code := base64.URLEncoding.EncodeToString(randomBytes) - _, err := m.db.Exec(ctx, registerPasswordResetCodeDBQ, userEmail, hash(code)) - if err != nil { + codeHashed := hash(code) + if _, err := m.db.Exec(ctx, registerPasswordResetCodeDBQ, userEmail, codeHashed); err != nil { + switch err.Error() { + case errInvalidEmailDB.Error(), errPasswordResetCodeAlreadyRegisteredDB.Error(): + return nil + } return err } + if m.es == nil { + return nil + } - // Send password reset email - if m.es != nil { - templateData := baseTemplateData(m.cfg) - templateData["Link"] = fmt.Sprintf("%s/reset-password?code=%s", templateData["BaseURL"], code) - var emailBody bytes.Buffer - if err := m.tmpl[passwordResetEmail].Execute(&emailBody, templateData); err != nil { - return err - } - emailData := &email.Data{ - To: userEmail, - Subject: "Password reset", - Body: emailBody.Bytes(), - } - if err := m.es.SendEmail(emailData); err != nil { - return err + // Send password reset email. If it cannot be sent, remove the code so + // that the next request can send a new link + if err := m.sendPasswordResetEmail(userEmail, code); err != nil { + if _, errDel := m.db.Exec(ctx, deletePasswordResetCodeDBQ, codeHashed); errDel != nil { + return errors.Join(err, errDel) } + return err } - return nil } @@ -604,7 +719,15 @@ func (m *Manager) RegisterSession(ctx context.Context, session *hub.Session) (*h session.SessionID = sessionIDHashed sessionJSON, _ := json.Marshal(session) var approved bool - err := m.db.QueryRow(ctx, registerSessionDBQ, sessionJSON).Scan(&approved) + var err error + if session.PasswordHash != "" { + err = m.db.QueryRow(ctx, registerSessionWithPasswordDBQ, sessionJSON, session.PasswordHash).Scan(&approved) + if err != nil && err.Error() == errPasswordChangedDB.Error() { + return nil, ErrPasswordChanged + } + } else { + err = m.db.QueryRow(ctx, registerSessionDBQ, sessionJSON).Scan(&approved) // OAuth + } if err != nil { return nil, err } @@ -679,22 +802,22 @@ func (m *Manager) RegisterUser(ctx context.Context, user *hub.User) error { } // ResetPassword resets the user password in the database. -func (m *Manager) ResetPassword(ctx context.Context, code, newPassword string) error { +func (m *Manager) ResetPassword(ctx context.Context, code, newPassword string) (*hub.ResetPasswordOutput, error) { // Validate input if code == "" { - return fmt.Errorf("%w: %s", hub.ErrInvalidInput, "code not provided") + return nil, fmt.Errorf("%w: %s", hub.ErrInvalidInput, "code not provided") } if newPassword == "" { - return fmt.Errorf("%w: %s", hub.ErrInvalidInput, "new password not provided") + return nil, fmt.Errorf("%w: %s", hub.ErrInvalidInput, "new password not provided") } if err := pwvalidator.Validate(newPassword, PasswordMinEntropyBits); err != nil { - return fmt.Errorf("%w: %w", hub.ErrInvalidInput, err) + return nil, fmt.Errorf("%w: %w", hub.ErrInvalidInput, err) } // Hash new password newHashed, err := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.DefaultCost) if err != nil { - return err + return nil, err } // Reset user password in database @@ -702,29 +825,41 @@ func (m *Manager) ResetPassword(ctx context.Context, code, newPassword string) e err = m.db.QueryRow(ctx, resetUserPasswordDBQ, hash(code), string(newHashed)).Scan(&userEmail) if err != nil { if err.Error() == errInvalidPasswordResetCodeDB.Error() { - return ErrInvalidPasswordResetCode + return nil, ErrInvalidPasswordResetCode } - return err + return nil, err + } + + // The password has been reset: from here on errors are logged, not + // returned, so that the caller still reports the reset as done + out := &hub.ResetPasswordOutput{PasswordHash: string(newHashed)} + if err := m.db.QueryRow(ctx, getUserIDFromEmailDBQ, userEmail).Scan(&out.UserID); err != nil { + log.Error().Err(err).Str("method", "ResetPassword").Msg("error getting user id after password reset") } // Send password reset success email if m.es != nil { templateData := baseTemplateData(m.cfg) var emailBody bytes.Buffer - if err := m.tmpl[passwordResetSuccessEmail].Execute(&emailBody, templateData); err != nil { - return err - } - emailData := &email.Data{ - To: userEmail, - Subject: "Your password has been reset", - Body: emailBody.Bytes(), + err := m.tmpl[passwordResetSuccessEmail].Execute(&emailBody, templateData) + if err == nil { + emailData := &email.Data{ + To: userEmail, + Subject: "Your password has been reset", + Body: emailBody.Bytes(), + } + err = m.es.SendEmail(emailData) } - if err := m.es.SendEmail(emailData); err != nil { - return err + if err != nil { + log.Error(). + Err(err). + Str("method", "ResetPassword"). + Str("user_id", out.UserID). + Msg("error sending password reset success email") } } - return nil + return out, nil } // SetupTFA sets up two-factor authentication for the requesting user. This @@ -757,9 +892,13 @@ func (m *Manager) SetupTFA(ctx context.Context) ([]byte, error) { recoveryCodes = append(recoveryCodes, code) } - // Store TOTP key and recovery codes in database - _, err = m.db.Exec(ctx, updateTFAInfoDBQ, userID, key.URL(), recoveryCodes) - if err != nil { + // Store TOTP key and recovery codes in database, unless TFA is already + // enabled + var id string + if err := m.db.QueryRow(ctx, updateTFAInfoDBQ, userID, key.URL(), recoveryCodes).Scan(&id); err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return nil, errTFAAlreadyEnabled + } return nil, err } @@ -802,10 +941,14 @@ func (m *Manager) UpdatePassword(ctx context.Context, old, new string) error { if err != nil { return err } + if err := m.reserveAttempt(ctx, userID, passwordUpdateLimit); err != nil { + return err + } err = bcrypt.CompareHashAndPassword([]byte(oldHashed), []byte(old)) if err != nil { return ErrInvalidPassword } + m.refundAttempt(ctx, userID, passwordUpdateLimit) // Hash new password newHashed, err := bcrypt.GenerateFromPassword([]byte(new), bcrypt.DefaultCost) @@ -858,19 +1001,70 @@ func (m *Manager) VerifyEmail(ctx context.Context, code string) (bool, error) { return verified, err } -// VerifyPasswordResetCode verifies if the provided code is valid. -func (m *Manager) VerifyPasswordResetCode(ctx context.Context, code string) error { +// VerifyPasswordResetCode verifies if the provided code is valid, returning +// the email of the user it belongs to. +func (m *Manager) VerifyPasswordResetCode(ctx context.Context, code string) (string, error) { // Validate input if code == "" { - return fmt.Errorf("%w: %s", hub.ErrInvalidInput, "code not provided") + return "", fmt.Errorf("%w: %s", hub.ErrInvalidInput, "code not provided") } // Verify password reset code in database - _, err := m.db.Exec(ctx, verifyPasswordResetCodeDBQ, hash(code)) - if err != nil && err.Error() == errInvalidPasswordResetCodeDB.Error() { - return ErrInvalidPasswordResetCode + codeHashed := hash(code) + if _, err := m.db.Exec(ctx, verifyPasswordResetCodeDBQ, codeHashed); err != nil { + if err.Error() == errInvalidPasswordResetCodeDB.Error() { + return "", ErrInvalidPasswordResetCode + } + return "", err } - return err + + // Get the email of the user the code belongs to + var userEmail string + if err := m.db.QueryRow(ctx, getPasswordResetCodeEmailDBQ, codeHashed).Scan(&userEmail); err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return "", ErrInvalidPasswordResetCode + } + return "", err + } + return userEmail, nil +} + +// reserveAttempt reserves an attempt of the kind provided for the user. It +// returns a *hub.TooManyAttemptsError when the allowance is used up. +func (m *Manager) reserveAttempt(ctx context.Context, userID string, l attemptLimit) error { + var wait int + if err := m.db.QueryRow(ctx, registerAuthAttemptDBQ, userID, l.kind, l.burst, l.interval).Scan(&wait); err != nil { + return err + } + if wait > 0 { + return &hub.TooManyAttemptsError{RetryAfter: wait} + } + return nil +} + +// refundAttempt gives back the attempt reserved for a check that succeeded. +// Errors are logged, not returned, so that a correct credential always works. +func (m *Manager) refundAttempt(ctx context.Context, userID string, l attemptLimit) { + if _, err := m.db.Exec(context.WithoutCancel(ctx), refundAuthAttemptDBQ, userID, l.kind, l.interval); err != nil { + log.Warn().Err(err).Str("user_id", userID).Str("kind", l.kind).Msg("error refunding auth attempt") + } +} + +// sendPasswordResetEmail sends the user an email with a link containing the +// password reset code provided. +func (m *Manager) sendPasswordResetEmail(userEmail, code string) error { + templateData := baseTemplateData(m.cfg) + templateData["Link"] = fmt.Sprintf("%s/reset-password?code=%s", templateData["BaseURL"], code) + var emailBody bytes.Buffer + if err := m.tmpl[passwordResetEmail].Execute(&emailBody, templateData); err != nil { + return err + } + emailData := &email.Data{ + To: userEmail, + Subject: "Password reset", + Body: emailBody.Bytes(), + } + return m.es.SendEmail(emailData) } // hash is a helper function that creates a sha512 hash of the text provided. @@ -878,6 +1072,20 @@ func hash(text string) string { return fmt.Sprintf("%x", sha512.Sum512([]byte(text))) } +// isTOTPCode checks if the passcode provided looks like a TOTP code: exactly +// 6 ASCII digits. Only such input can ever validate as a TOTP code. +func isTOTPCode(passcode string) bool { + if len(passcode) != 6 { + return false + } + for i := 0; i < len(passcode); i++ { + if passcode[i] < '0' || passcode[i] > '9' { + return false + } + } + return true +} + // isValidRecoveryCode checks if the code provided is a valid recovery code. func isValidRecoveryCode(recoveryCodes []string, code string) bool { for _, recoveryCode := range recoveryCodes { diff --git a/internal/user/manager_test.go b/internal/user/manager_test.go index c4d918c540..33bba4d32b 100644 --- a/internal/user/manager_test.go +++ b/internal/user/manager_test.go @@ -1,10 +1,13 @@ package user import ( + "bytes" "context" "encoding/json" "errors" "fmt" + "html/template" + "regexp" "testing" "time" @@ -23,6 +26,15 @@ import ( var cfg *viper.Viper +// unusableHash is a well-formed bcrypt hash of the maximum cost: checking a +// password against it takes far longer than the tests timeout, so a test that +// uses it only passes if the password is never checked. +const unusableHash = "$2a$31$abcdefghijklmnopqrstuuabcdefghijklmnopqrstuvwxyzABCDE" // #nosec G101 + +// invalidURLTFAConfigJSON is a 2fa config, enabled, whose key url cannot be +// parsed: a test that uses it only passes if no passcode is validated. +var invalidURLTFAConfigJSON = []byte(`{"enabled": true, "url": "%zz"}`) + func init() { cfg = viper.New() cfg.Set("theme.siteName", "Artifact Hub") @@ -44,6 +56,7 @@ func TestApproveSession(t *testing.T) { RecoveryCodes: []string{code1}, } tfaConfigJSON, _ := json.Marshal(tfaConfig) + l := loginTFALimit t.Run("invalid input", func(t *testing.T) { testCases := []struct { @@ -61,6 +74,11 @@ func TestApproveSession(t *testing.T) { "sessionID", "", }, + { + "passcode not provided", + "sessionID", + " ", + }, } for _, tc := range testCases { t.Run(tc.errMsg, func(t *testing.T) { @@ -74,9 +92,52 @@ func TestApproveSession(t *testing.T) { }) t.Run("error getting user id from session", func(t *testing.T) { + testCases := []struct { + passcode string + }{ + {"123456"}, + {code1}, + } + for _, tc := range testCases { + t.Run(tc.passcode, func(t *testing.T) { + t.Parallel() + db := &tests.DBMock{} + db.On("QueryRow", ctx, getUserIDFromSessionIDDBQ, hashedSessionID).Return("", tests.ErrFakeDB) + m := NewManager(cfg, db, nil) + + err := m.ApproveSession(ctx, sessionID, tc.passcode) + assert.Equal(t, tests.ErrFakeDB, err) + db.AssertExpectations(t) + }) + } + }) + + t.Run("session not pending (already approved or gone)", func(t *testing.T) { + testCases := []struct { + passcode string + }{ + {"123456"}, + {code1}, + } + for _, tc := range testCases { + t.Run(tc.passcode, func(t *testing.T) { + t.Parallel() + db := &tests.DBMock{} + db.On("QueryRow", ctx, getUserIDFromSessionIDDBQ, hashedSessionID).Return("", pgx.ErrNoRows) + m := NewManager(cfg, db, nil) + + err := m.ApproveSession(ctx, sessionID, tc.passcode) + assert.Equal(t, ErrSessionNotPending, err) + db.AssertExpectations(t) + }) + } + }) + + t.Run("error getting 2fa config from database", func(t *testing.T) { t.Parallel() db := &tests.DBMock{} - db.On("QueryRow", ctx, getUserIDFromSessionIDDBQ, hashedSessionID).Return("", tests.ErrFakeDB) + db.On("QueryRow", ctx, getUserIDFromSessionIDDBQ, hash(sessionID)).Return("userID", nil) + db.On("QueryRow", ctx, getTFAConfigDBQ, "userID").Return(nil, tests.ErrFakeDB) m := NewManager(cfg, db, nil) err := m.ApproveSession(ctx, sessionID, "123456") @@ -84,11 +145,12 @@ func TestApproveSession(t *testing.T) { db.AssertExpectations(t) }) - t.Run("error getting 2fa config from database", func(t *testing.T) { + t.Run("error reserving attempt", func(t *testing.T) { t.Parallel() db := &tests.DBMock{} db.On("QueryRow", ctx, getUserIDFromSessionIDDBQ, hash(sessionID)).Return("userID", nil) - db.On("QueryRow", ctx, getTFAConfigDBQ, "userID").Return(nil, tests.ErrFakeDB) + db.On("QueryRow", ctx, getTFAConfigDBQ, "userID").Return(tfaConfigJSON, nil) + db.On("QueryRow", ctx, registerAuthAttemptDBQ, "userID", l.kind, l.burst, l.interval).Return(0, tests.ErrFakeDB) m := NewManager(cfg, db, nil) err := m.ApproveSession(ctx, sessionID, "123456") @@ -96,23 +158,88 @@ func TestApproveSession(t *testing.T) { db.AssertExpectations(t) }) - t.Run("invalid passcode provided", func(t *testing.T) { + t.Run("too many attempts", func(t *testing.T) { t.Parallel() db := &tests.DBMock{} + // The key url cannot be parsed: validating the passcode before the + // attempt is reserved would return a different error db.On("QueryRow", ctx, getUserIDFromSessionIDDBQ, hash(sessionID)).Return("userID", nil) - db.On("QueryRow", ctx, getTFAConfigDBQ, "userID").Return(tfaConfigJSON, nil) + db.On("QueryRow", ctx, getTFAConfigDBQ, "userID").Return(invalidURLTFAConfigJSON, nil) + db.On("QueryRow", ctx, registerAuthAttemptDBQ, "userID", l.kind, l.burst, l.interval).Return(120, nil) m := NewManager(cfg, db, nil) err := m.ApproveSession(ctx, sessionID, "123456") - assert.Equal(t, errInvalidTFAPasscode, err) + var tooManyErr *hub.TooManyAttemptsError + require.True(t, errors.As(err, &tooManyErr)) + assert.Equal(t, 120, tooManyErr.RetryAfter) + assert.True(t, errors.Is(err, hub.ErrTooManyAttempts)) db.AssertExpectations(t) }) + t.Run("invalid passcode provided", func(t *testing.T) { + testCases := []struct { + description string + passcode string + counted bool + }{ + { + "invalid totp code", + "123456", + true, + }, + { + "invalid recovery code", + "unknown", + false, + }, + { + "5 digits", + "12345", + false, + }, + } + for _, tc := range testCases { + t.Run(tc.description, func(t *testing.T) { + t.Parallel() + db := &tests.DBMock{} + db.On("QueryRow", ctx, getUserIDFromSessionIDDBQ, hash(sessionID)).Return("userID", nil) + db.On("QueryRow", ctx, getTFAConfigDBQ, "userID").Return(tfaConfigJSON, nil) + if tc.counted { + db.On("QueryRow", ctx, registerAuthAttemptDBQ, "userID", l.kind, l.burst, l.interval).Return(0, nil) + } + m := NewManager(cfg, db, nil) + + err := m.ApproveSession(ctx, sessionID, tc.passcode) + assert.Equal(t, errInvalidTFAPasscode, err) + db.AssertExpectations(t) + }) + } + }) + t.Run("session approved successfully", func(t *testing.T) { t.Parallel() db := &tests.DBMock{} db.On("QueryRow", ctx, getUserIDFromSessionIDDBQ, hash(sessionID)).Return("userID", nil) db.On("QueryRow", ctx, getTFAConfigDBQ, "userID").Return(tfaConfigJSON, nil) + db.On("QueryRow", ctx, registerAuthAttemptDBQ, "userID", l.kind, l.burst, l.interval).Return(0, nil) + db.On("Exec", context.WithoutCancel(ctx), refundAuthAttemptDBQ, "userID", l.kind, l.interval).Return(nil) + db.On("Exec", ctx, approveSessionDBQ, hashedSessionID, "").Return(nil) + m := NewManager(cfg, db, nil) + + passcode, _ := totp.GenerateCode(key.Secret(), time.Now()) + err := m.ApproveSession(ctx, sessionID, " "+passcode+" ") + assert.Nil(t, err) + db.AssertExpectations(t) + }) + + t.Run("session approved successfully (refund failed)", func(t *testing.T) { + t.Parallel() + db := &tests.DBMock{} + db.On("QueryRow", ctx, getUserIDFromSessionIDDBQ, hash(sessionID)).Return("userID", nil) + db.On("QueryRow", ctx, getTFAConfigDBQ, "userID").Return(tfaConfigJSON, nil) + db.On("QueryRow", ctx, registerAuthAttemptDBQ, "userID", l.kind, l.burst, l.interval).Return(0, nil) + db.On("Exec", context.WithoutCancel(ctx), refundAuthAttemptDBQ, "userID", l.kind, l.interval). + Return(tests.ErrFakeDB) db.On("Exec", ctx, approveSessionDBQ, hashedSessionID, "").Return(nil) m := NewManager(cfg, db, nil) @@ -130,10 +257,48 @@ func TestApproveSession(t *testing.T) { db.On("Exec", ctx, approveSessionDBQ, hashedSessionID, code1).Return(nil) m := NewManager(cfg, db, nil) - err := m.ApproveSession(ctx, sessionID, code1) + err := m.ApproveSession(ctx, sessionID, " "+code1+" ") assert.Nil(t, err) db.AssertExpectations(t) }) + + t.Run("error approving session", func(t *testing.T) { + testCases := []struct { + description string + dbErr error + expectedErr error + }{ + { + "recovery code used by a concurrent request", + errInvalidRecoveryCodeDB, + errInvalidTFAPasscode, + }, + { + "session approved or deleted by a concurrent request", + errSessionNotPendingDB, + ErrSessionNotPending, + }, + { + "database error", + tests.ErrFakeDB, + tests.ErrFakeDB, + }, + } + for _, tc := range testCases { + t.Run(tc.description, func(t *testing.T) { + t.Parallel() + db := &tests.DBMock{} + db.On("QueryRow", ctx, getUserIDFromSessionIDDBQ, hash(sessionID)).Return("userID", nil) + db.On("QueryRow", ctx, getTFAConfigDBQ, "userID").Return(tfaConfigJSON, nil) + db.On("Exec", ctx, approveSessionDBQ, hashedSessionID, code1).Return(tc.dbErr) + m := NewManager(cfg, db, nil) + + err := m.ApproveSession(ctx, sessionID, code1) + assert.Equal(t, tc.expectedErr, err) + db.AssertExpectations(t) + }) + } + }) } func TestCheckAvailability(t *testing.T) { @@ -211,6 +376,8 @@ func TestCheckAvailability(t *testing.T) { func TestCheckCredentials(t *testing.T) { ctx := context.Background() + pw, _ := bcrypt.GenerateFromPassword([]byte("pass"), bcrypt.DefaultCost) + l := loginPasswordLimit t.Run("invalid input", func(t *testing.T) { testCases := []struct { @@ -265,33 +432,84 @@ func TestCheckCredentials(t *testing.T) { db.AssertExpectations(t) }) - t.Run("invalid credentials provided", func(t *testing.T) { + t.Run("error reserving attempt", func(t *testing.T) { t.Parallel() - pw, _ := bcrypt.GenerateFromPassword([]byte("pass"), bcrypt.DefaultCost) db := &tests.DBMock{} db.On("QueryRow", ctx, checkUserCredsDBQ, "email").Return([]interface{}{"userID", string(pw)}, nil) + db.On("QueryRow", ctx, registerAuthAttemptDBQ, "userID", l.kind, l.burst, l.interval).Return(0, tests.ErrFakeDB) m := NewManager(cfg, db, nil) - output, err := m.CheckCredentials(ctx, "email", "pass2") - assert.NoError(t, err) - assert.False(t, output.Valid) - assert.Empty(t, output.UserID) + output, err := m.CheckCredentials(ctx, "email", "pass") + assert.Equal(t, tests.ErrFakeDB, err) + assert.Nil(t, output) db.AssertExpectations(t) }) - t.Run("valid credentials provided", func(t *testing.T) { + t.Run("too many attempts", func(t *testing.T) { t.Parallel() - pw, _ := bcrypt.GenerateFromPassword([]byte("pass"), bcrypt.DefaultCost) db := &tests.DBMock{} - db.On("QueryRow", ctx, checkUserCredsDBQ, "email").Return([]interface{}{"userID", string(pw)}, nil) + // Checking a password against the stored hash would not finish in + // time, so a result shows the password is not checked + db.On("QueryRow", ctx, checkUserCredsDBQ, "email").Return([]interface{}{"userID", unusableHash}, nil) + db.On("QueryRow", ctx, registerAuthAttemptDBQ, "userID", l.kind, l.burst, l.interval).Return(120, nil) m := NewManager(cfg, db, nil) output, err := m.CheckCredentials(ctx, "email", "pass") + var tooManyErr *hub.TooManyAttemptsError + require.True(t, errors.As(err, &tooManyErr)) + assert.Equal(t, 120, tooManyErr.RetryAfter) + assert.Nil(t, output) + db.AssertExpectations(t) + }) + + t.Run("invalid credentials provided", func(t *testing.T) { + t.Parallel() + db := &tests.DBMock{} + db.On("QueryRow", ctx, checkUserCredsDBQ, "email").Return([]interface{}{"userID", string(pw)}, nil) + db.On("QueryRow", ctx, registerAuthAttemptDBQ, "userID", l.kind, l.burst, l.interval).Return(0, nil) + m := NewManager(cfg, db, nil) + + output, err := m.CheckCredentials(ctx, "email", "pass2") assert.NoError(t, err) - assert.True(t, output.Valid) - assert.Equal(t, "userID", output.UserID) + assert.False(t, output.Valid) + assert.Empty(t, output.UserID) + assert.Empty(t, output.PasswordHash) db.AssertExpectations(t) }) + + t.Run("valid credentials provided", func(t *testing.T) { + testCases := []struct { + description string + refundErr error + }{ + { + "attempt refunded", + nil, + }, + { + "error refunding attempt", + tests.ErrFakeDB, + }, + } + for _, tc := range testCases { + t.Run(tc.description, func(t *testing.T) { + t.Parallel() + db := &tests.DBMock{} + db.On("QueryRow", ctx, checkUserCredsDBQ, "email").Return([]interface{}{"userID", string(pw)}, nil) + db.On("QueryRow", ctx, registerAuthAttemptDBQ, "userID", l.kind, l.burst, l.interval).Return(0, nil) + db.On("Exec", context.WithoutCancel(ctx), refundAuthAttemptDBQ, "userID", l.kind, l.interval). + Return(tc.refundErr) + m := NewManager(cfg, db, nil) + + output, err := m.CheckCredentials(ctx, "email", "pass") + assert.NoError(t, err) + assert.True(t, output.Valid) + assert.Equal(t, "userID", output.UserID) + assert.Equal(t, string(pw), output.PasswordHash) + db.AssertExpectations(t) + }) + } + }) } func TestCheckSession(t *testing.T) { @@ -526,6 +744,7 @@ func TestDisableTFA(t *testing.T) { RecoveryCodes: []string{code1}, } tfaConfigJSON, _ := json.Marshal(tfaConfig) + l := tfaDisableLimit t.Run("user id not found in ctx", func(t *testing.T) { t.Parallel() @@ -536,11 +755,28 @@ func TestDisableTFA(t *testing.T) { }) t.Run("invalid input", func(t *testing.T) { - t.Parallel() - m := NewManager(cfg, nil, nil) - err := m.DisableTFA(ctx, "") - - assert.True(t, errors.Is(err, hub.ErrInvalidInput)) + testCases := []struct { + description string + passcode string + }{ + { + "empty passcode", + "", + }, + { + "whitespace passcode", + " ", + }, + } + for _, tc := range testCases { + t.Run(tc.description, func(t *testing.T) { + t.Parallel() + m := NewManager(cfg, nil, nil) + err := m.DisableTFA(ctx, tc.passcode) + assert.True(t, errors.Is(err, hub.ErrInvalidInput)) + assert.Contains(t, err.Error(), "passcode not provided") + }) + } }) t.Run("error getting 2fa config from database", func(t *testing.T) { @@ -554,21 +790,74 @@ func TestDisableTFA(t *testing.T) { db.AssertExpectations(t) }) - t.Run("invalid passcode provided", func(t *testing.T) { + t.Run("error reserving attempt", func(t *testing.T) { t.Parallel() db := &tests.DBMock{} db.On("QueryRow", ctx, getTFAConfigDBQ, "userID").Return(tfaConfigJSON, nil) + db.On("QueryRow", ctx, registerAuthAttemptDBQ, "userID", l.kind, l.burst, l.interval).Return(0, tests.ErrFakeDB) m := NewManager(cfg, db, nil) err := m.DisableTFA(ctx, "123456") - assert.Equal(t, errInvalidTFAPasscode, err) + assert.Equal(t, tests.ErrFakeDB, err) + db.AssertExpectations(t) + }) + + t.Run("too many attempts", func(t *testing.T) { + t.Parallel() + db := &tests.DBMock{} + // The key url cannot be parsed: validating the passcode before the + // attempt is reserved would return a different error + db.On("QueryRow", ctx, getTFAConfigDBQ, "userID").Return(invalidURLTFAConfigJSON, nil) + db.On("QueryRow", ctx, registerAuthAttemptDBQ, "userID", l.kind, l.burst, l.interval).Return(3600, nil) + m := NewManager(cfg, db, nil) + + err := m.DisableTFA(ctx, "123456") + var tooManyErr *hub.TooManyAttemptsError + require.True(t, errors.As(err, &tooManyErr)) + assert.Equal(t, 3600, tooManyErr.RetryAfter) db.AssertExpectations(t) }) + t.Run("invalid passcode provided", func(t *testing.T) { + testCases := []struct { + description string + passcode string + counted bool + }{ + { + "invalid totp code", + "123456", + true, + }, + { + "invalid recovery code", + "unknown", + false, + }, + } + for _, tc := range testCases { + t.Run(tc.description, func(t *testing.T) { + t.Parallel() + db := &tests.DBMock{} + db.On("QueryRow", ctx, getTFAConfigDBQ, "userID").Return(tfaConfigJSON, nil) + if tc.counted { + db.On("QueryRow", ctx, registerAuthAttemptDBQ, "userID", l.kind, l.burst, l.interval).Return(0, nil) + } + m := NewManager(cfg, db, nil) + + err := m.DisableTFA(ctx, tc.passcode) + assert.Equal(t, errInvalidTFAPasscode, err) + db.AssertExpectations(t) + }) + } + }) + t.Run("error setting 2fa as disabled in the database", func(t *testing.T) { t.Parallel() db := &tests.DBMock{} db.On("QueryRow", ctx, getTFAConfigDBQ, "userID").Return(tfaConfigJSON, nil) + db.On("QueryRow", ctx, registerAuthAttemptDBQ, "userID", l.kind, l.burst, l.interval).Return(0, nil) + db.On("Exec", context.WithoutCancel(ctx), refundAuthAttemptDBQ, "userID", l.kind, l.interval).Return(nil) db.On("Exec", ctx, disableTFADBQ, "userID").Return(tests.ErrFakeDB) m := NewManager(cfg, db, nil) @@ -582,6 +871,8 @@ func TestDisableTFA(t *testing.T) { t.Parallel() db := &tests.DBMock{} db.On("QueryRow", ctx, getTFAConfigDBQ, "userID").Return(tfaConfigJSON, nil) + db.On("QueryRow", ctx, registerAuthAttemptDBQ, "userID", l.kind, l.burst, l.interval).Return(0, nil) + db.On("Exec", context.WithoutCancel(ctx), refundAuthAttemptDBQ, "userID", l.kind, l.interval).Return(nil) db.On("Exec", ctx, disableTFADBQ, "userID").Return(nil) db.On("QueryRow", ctx, getUserEmailDBQ, "userID").Return("email", nil) es := &email.SenderMock{} @@ -598,6 +889,8 @@ func TestDisableTFA(t *testing.T) { t.Parallel() db := &tests.DBMock{} db.On("QueryRow", ctx, getTFAConfigDBQ, "userID").Return(tfaConfigJSON, nil) + db.On("QueryRow", ctx, registerAuthAttemptDBQ, "userID", l.kind, l.burst, l.interval).Return(0, nil) + db.On("Exec", context.WithoutCancel(ctx), refundAuthAttemptDBQ, "userID", l.kind, l.interval).Return(nil) db.On("Exec", ctx, disableTFADBQ, "userID").Return(nil) db.On("QueryRow", ctx, getUserEmailDBQ, "userID").Return("email", nil) es := &email.SenderMock{} @@ -605,7 +898,7 @@ func TestDisableTFA(t *testing.T) { m := NewManager(cfg, db, es) passcode, _ := totp.GenerateCode(key.Secret(), time.Now()) - err := m.DisableTFA(ctx, passcode) + err := m.DisableTFA(ctx, " "+passcode+" ") assert.Nil(t, err) db.AssertExpectations(t) }) @@ -631,7 +924,7 @@ func TestEnableTFA(t *testing.T) { } key, _ := totp.Generate(opts) tfaConfig := &hub.TFAConfig{ - Enabled: true, + Enabled: false, URL: key.URL(), } tfaConfigJSON, _ := json.Marshal(tfaConfig) @@ -663,35 +956,66 @@ func TestEnableTFA(t *testing.T) { db.AssertExpectations(t) }) - t.Run("invalid passcode provided", func(t *testing.T) { + t.Run("2fa already enabled", func(t *testing.T) { t.Parallel() + // The key url cannot be parsed: validating the passcode before + // checking if 2fa is enabled would return a different error db := &tests.DBMock{} - db.On("QueryRow", ctx, getTFAConfigDBQ, "userID").Return(tfaConfigJSON, nil) + db.On("QueryRow", ctx, getTFAConfigDBQ, "userID").Return(invalidURLTFAConfigJSON, nil) m := NewManager(cfg, db, nil) err := m.EnableTFA(ctx, "123456") - assert.Equal(t, errInvalidTFAPasscode, err) + assert.Equal(t, errTFAAlreadyEnabled, err) + assert.True(t, errors.Is(err, hub.ErrInvalidInput)) db.AssertExpectations(t) }) - t.Run("error setting 2fa as enabled in the database", func(t *testing.T) { + t.Run("invalid passcode provided", func(t *testing.T) { t.Parallel() db := &tests.DBMock{} db.On("QueryRow", ctx, getTFAConfigDBQ, "userID").Return(tfaConfigJSON, nil) - db.On("Exec", ctx, enableTFADBQ, "userID").Return(tests.ErrFakeDB) m := NewManager(cfg, db, nil) - passcode, _ := totp.GenerateCode(key.Secret(), time.Now()) - err := m.EnableTFA(ctx, passcode) - assert.Equal(t, tests.ErrFakeDB, err) + err := m.EnableTFA(ctx, "123456") + assert.Equal(t, errInvalidTFAPasscode, err) db.AssertExpectations(t) }) + t.Run("error setting 2fa as enabled in the database", func(t *testing.T) { + testCases := []struct { + dbErr error + expectedErr error + }{ + { + tests.ErrFakeDB, + tests.ErrFakeDB, + }, + { + pgx.ErrNoRows, + errTFASetupChanged, + }, + } + for _, tc := range testCases { + t.Run(tc.dbErr.Error(), func(t *testing.T) { + t.Parallel() + db := &tests.DBMock{} + db.On("QueryRow", ctx, getTFAConfigDBQ, "userID").Return(tfaConfigJSON, nil) + db.On("QueryRow", ctx, enableTFADBQ, "userID", key.URL()).Return("", tc.dbErr) + m := NewManager(cfg, db, nil) + + passcode, _ := totp.GenerateCode(key.Secret(), time.Now()) + err := m.EnableTFA(ctx, passcode) + assert.Equal(t, tc.expectedErr, err) + db.AssertExpectations(t) + }) + } + }) + t.Run("error sending 2fa enabled email notification", func(t *testing.T) { t.Parallel() db := &tests.DBMock{} db.On("QueryRow", ctx, getTFAConfigDBQ, "userID").Return(tfaConfigJSON, nil) - db.On("Exec", ctx, enableTFADBQ, "userID").Return(nil) + db.On("QueryRow", ctx, enableTFADBQ, "userID", key.URL()).Return("userID", nil) db.On("QueryRow", ctx, getUserEmailDBQ, "userID").Return("email", nil) es := &email.SenderMock{} es.On("SendEmail", mock.Anything).Return(email.ErrFakeSenderFailure) @@ -707,7 +1031,7 @@ func TestEnableTFA(t *testing.T) { t.Parallel() db := &tests.DBMock{} db.On("QueryRow", ctx, getTFAConfigDBQ, "userID").Return(tfaConfigJSON, nil) - db.On("Exec", ctx, enableTFADBQ, "userID").Return(nil) + db.On("QueryRow", ctx, enableTFADBQ, "userID", key.URL()).Return("userID", nil) db.On("QueryRow", ctx, getUserEmailDBQ, "userID").Return("email", nil) es := &email.SenderMock{} es.On("SendEmail", mock.Anything).Return(nil) @@ -901,6 +1225,9 @@ func TestRegisterDeleteUserCode(t *testing.T) { func TestRegisterPasswordResetCode(t *testing.T) { ctx := context.Background() + dbCtx := context.WithoutCancel(ctx) + userEmail := "email@email.com" + linkRE := regexp.MustCompile(`/reset-password\?code=([A-Za-z0-9_=-]+)`) t.Run("invalid input", func(t *testing.T) { testCases := []struct { @@ -925,45 +1252,115 @@ func TestRegisterPasswordResetCode(t *testing.T) { } }) - t.Run("successful password reset code registration in database", func(t *testing.T) { + t.Run("password reset code not registered in database", func(t *testing.T) { testCases := []struct { - description string - emailSenderResponse error + dbErr error + expectedErr error }{ { - "password reset code sent successfully", + errInvalidEmailDB, nil, }, { - "error sending password reset code", - email.ErrFakeSenderFailure, + errPasswordResetCodeAlreadyRegisteredDB, + nil, + }, + { + tests.ErrFakeDB, + tests.ErrFakeDB, + }, + } + for _, tc := range testCases { + t.Run(tc.dbErr.Error(), func(t *testing.T) { + t.Parallel() + db := &tests.DBMock{} + db.On("Exec", dbCtx, registerPasswordResetCodeDBQ, userEmail, mock.Anything).Return(tc.dbErr) + es := &email.SenderMock{} + m := NewManager(cfg, db, es) + + err := m.RegisterPasswordResetCode(ctx, userEmail) + assert.Equal(t, tc.expectedErr, err) + db.AssertExpectations(t) + es.AssertNotCalled(t, "SendEmail", mock.Anything) + }) + } + }) + + t.Run("password reset code sent successfully", func(t *testing.T) { + t.Parallel() + var codeHashed string + db := &tests.DBMock{} + db.On("Exec", dbCtx, registerPasswordResetCodeDBQ, userEmail, mock.AnythingOfType("string")). + Run(func(args mock.Arguments) { codeHashed = args.String(3) }). + Return(nil) + es := &email.SenderMock{} + es.On("SendEmail", mock.MatchedBy(func(data *email.Data) bool { + matches := linkRE.FindSubmatch(data.Body) + return data.To == userEmail && + data.Subject == "Password reset" && + bytes.Contains(data.Body, []byte("4 hours")) && + matches != nil && + hash(string(matches[1])) == codeHashed + })).Return(nil) + m := NewManager(cfg, db, es) + + err := m.RegisterPasswordResetCode(ctx, userEmail) + assert.NoError(t, err) + assert.NotEmpty(t, codeHashed) + db.AssertExpectations(t) + es.AssertExpectations(t) + }) + + t.Run("error sending password reset code", func(t *testing.T) { + testCases := []struct { + description string + deleteErr error + }{ + { + "password reset code deleted", + nil, + }, + { + "error deleting password reset code", + tests.ErrFakeDB, }, } for _, tc := range testCases { t.Run(tc.description, func(t *testing.T) { t.Parallel() + var codeHashed string db := &tests.DBMock{} - db.On("Exec", ctx, registerPasswordResetCodeDBQ, "email@email.com", mock.Anything).Return(nil) + db.On("Exec", dbCtx, registerPasswordResetCodeDBQ, userEmail, mock.AnythingOfType("string")). + Run(func(args mock.Arguments) { codeHashed = args.String(3) }). + Return(nil) + db.On("Exec", dbCtx, deletePasswordResetCodeDBQ, mock.MatchedBy(func(h string) bool { + return h == codeHashed + })).Return(tc.deleteErr) es := &email.SenderMock{} - es.On("SendEmail", mock.Anything).Return(tc.emailSenderResponse) + es.On("SendEmail", mock.Anything).Return(email.ErrFakeSenderFailure) m := NewManager(cfg, db, es) - err := m.RegisterPasswordResetCode(ctx, "email@email.com") - assert.Equal(t, tc.emailSenderResponse, err) + err := m.RegisterPasswordResetCode(ctx, userEmail) + if tc.deleteErr == nil { + assert.Equal(t, email.ErrFakeSenderFailure, err) + } else { + assert.True(t, errors.Is(err, email.ErrFakeSenderFailure)) + assert.True(t, errors.Is(err, tc.deleteErr)) + } db.AssertExpectations(t) es.AssertExpectations(t) }) } }) - t.Run("database error registering password reset code", func(t *testing.T) { + t.Run("password reset code registered without email sender", func(t *testing.T) { t.Parallel() db := &tests.DBMock{} - db.On("Exec", ctx, registerPasswordResetCodeDBQ, "email@email.com", mock.Anything).Return(tests.ErrFakeDB) + db.On("Exec", dbCtx, registerPasswordResetCodeDBQ, userEmail, mock.Anything).Return(nil) m := NewManager(cfg, db, nil) - err := m.RegisterPasswordResetCode(ctx, "email@email.com") - assert.Equal(t, tests.ErrFakeDB, err) + err := m.RegisterPasswordResetCode(ctx, userEmail) + assert.NoError(t, err) db.AssertExpectations(t) }) } @@ -971,6 +1368,19 @@ func TestRegisterPasswordResetCode(t *testing.T) { func TestRegisterSession(t *testing.T) { ctx := context.Background() userID := "00000000-0000-0000-0000-000000000001" + passwordHash := "passwordHash" + + // sessionJSONMatcher checks that the session JSON belongs to the user and + // does not include the password hash + sessionJSONMatcher := mock.MatchedBy(func(sessionJSON []byte) bool { + var s map[string]interface{} + if err := json.Unmarshal(sessionJSON, &s); err != nil { + return false + } + return s["user_id"] == userID && + s["session_id"] != "" && + !bytes.Contains(sessionJSON, []byte(passwordHash)) + }) t.Run("invalid input", func(t *testing.T) { testCases := []struct { @@ -1011,10 +1421,41 @@ func TestRegisterSession(t *testing.T) { db.AssertExpectations(t) }) + t.Run("database error (with password hash)", func(t *testing.T) { + testCases := []struct { + dbErr error + expectedErr error + }{ + { + tests.ErrFakeDB, + tests.ErrFakeDB, + }, + { + errPasswordChangedDB, + ErrPasswordChanged, + }, + } + for _, tc := range testCases { + t.Run(tc.dbErr.Error(), func(t *testing.T) { + t.Parallel() + db := &tests.DBMock{} + db.On("QueryRow", ctx, registerSessionWithPasswordDBQ, sessionJSONMatcher, passwordHash). + Return(nil, tc.dbErr) + m := NewManager(cfg, db, nil) + + sIN := &hub.Session{UserID: userID, PasswordHash: passwordHash} + sOUT, err := m.RegisterSession(ctx, sIN) + assert.Equal(t, tc.expectedErr, err) + assert.Nil(t, sOUT) + db.AssertExpectations(t) + }) + } + }) + t.Run("successful session registration", func(t *testing.T) { t.Parallel() db := &tests.DBMock{} - db.On("QueryRow", ctx, registerSessionDBQ, mock.Anything).Return(true, nil) + db.On("QueryRow", ctx, registerSessionDBQ, sessionJSONMatcher).Return(true, nil) m := NewManager(cfg, db, nil) sIN := &hub.Session{ @@ -1029,6 +1470,38 @@ func TestRegisterSession(t *testing.T) { assert.True(t, sOUT.Approved) db.AssertExpectations(t) }) + + t.Run("successful session registration (with password hash)", func(t *testing.T) { + testCases := []struct { + approved bool + }{ + {true}, + {false}, + } + for _, tc := range testCases { + t.Run(fmt.Sprintf("approved: %t", tc.approved), func(t *testing.T) { + t.Parallel() + db := &tests.DBMock{} + db.On("QueryRow", ctx, registerSessionWithPasswordDBQ, sessionJSONMatcher, passwordHash). + Return(tc.approved, nil) + m := NewManager(cfg, db, nil) + + sIN := &hub.Session{ + UserID: userID, + IP: "192.168.1.100", + UserAgent: "Safari 13.0.5", + PasswordHash: passwordHash, + } + sOUT, err := m.RegisterSession(ctx, sIN) + assert.NoError(t, err) + assert.NotEmpty(t, sOUT.SessionID) + assert.Equal(t, userID, sOUT.UserID) + assert.Equal(t, tc.approved, sOUT.Approved) + assert.Empty(t, sOUT.PasswordHash) + db.AssertExpectations(t) + }) + } + }) } func TestRegisterUser(t *testing.T) { @@ -1161,9 +1634,10 @@ func TestResetPassword(t *testing.T) { t.Parallel() es := &email.SenderMock{} m := NewManager(cfg, nil, es) - err := m.ResetPassword(ctx, tc.code, tc.newPassword) + out, err := m.ResetPassword(ctx, tc.code, tc.newPassword) assert.True(t, errors.Is(err, hub.ErrInvalidInput)) assert.Contains(t, err.Error(), tc.errMsg) + assert.Nil(t, out) }) } }) @@ -1189,8 +1663,9 @@ func TestResetPassword(t *testing.T) { db.On("QueryRow", ctx, resetUserPasswordDBQ, codeHashed, mock.Anything).Return("", tc.dbErr) m := NewManager(cfg, db, nil) - err := m.ResetPassword(ctx, code, newPassword) + out, err := m.ResetPassword(ctx, code, newPassword) assert.Equal(t, tc.expectedErr, err) + assert.Nil(t, out) db.AssertExpectations(t) }) } @@ -1215,17 +1690,72 @@ func TestResetPassword(t *testing.T) { t.Parallel() db := &tests.DBMock{} db.On("QueryRow", ctx, resetUserPasswordDBQ, codeHashed, mock.Anything).Return("email", nil) + db.On("QueryRow", ctx, getUserIDFromEmailDBQ, "email").Return("userID", nil) es := &email.SenderMock{} - es.On("SendEmail", mock.Anything).Return(tc.emailSenderResponse) + es.On("SendEmail", mock.MatchedBy(func(data *email.Data) bool { + return data.To == "email" && data.Subject == "Your password has been reset" + })).Return(tc.emailSenderResponse) m := NewManager(cfg, db, es) - err := m.ResetPassword(ctx, code, newPassword) - assert.Equal(t, tc.emailSenderResponse, err) + out, err := m.ResetPassword(ctx, code, newPassword) + assert.NoError(t, err) + require.NotNil(t, out) + assert.Equal(t, "userID", out.UserID) + assert.NoError(t, bcrypt.CompareHashAndPassword([]byte(out.PasswordHash), []byte(newPassword))) db.AssertExpectations(t) es.AssertExpectations(t) }) } }) + + t.Run("password reset, error getting user id", func(t *testing.T) { + t.Parallel() + db := &tests.DBMock{} + db.On("QueryRow", ctx, resetUserPasswordDBQ, codeHashed, mock.Anything).Return("email", nil) + db.On("QueryRow", ctx, getUserIDFromEmailDBQ, "email").Return("", tests.ErrFakeDB) + es := &email.SenderMock{} + es.On("SendEmail", mock.Anything).Return(nil) + m := NewManager(cfg, db, es) + + out, err := m.ResetPassword(ctx, code, newPassword) + assert.NoError(t, err) + require.NotNil(t, out) + assert.Empty(t, out.UserID) + assert.NoError(t, bcrypt.CompareHashAndPassword([]byte(out.PasswordHash), []byte(newPassword))) + db.AssertExpectations(t) + es.AssertExpectations(t) + }) + + t.Run("password reset, error rendering success email", func(t *testing.T) { + t.Parallel() + db := &tests.DBMock{} + db.On("QueryRow", ctx, resetUserPasswordDBQ, codeHashed, mock.Anything).Return("email", nil) + db.On("QueryRow", ctx, getUserIDFromEmailDBQ, "email").Return("userID", nil) + es := &email.SenderMock{} + m := NewManager(cfg, db, es) + m.tmpl[passwordResetSuccessEmail] = template.Must(template.New("").Parse(`{{ template "missing" }}`)) + + out, err := m.ResetPassword(ctx, code, newPassword) + assert.NoError(t, err) + require.NotNil(t, out) + assert.Equal(t, "userID", out.UserID) + db.AssertExpectations(t) + es.AssertNotCalled(t, "SendEmail", mock.Anything) + }) + + t.Run("password reset without email sender", func(t *testing.T) { + t.Parallel() + db := &tests.DBMock{} + db.On("QueryRow", ctx, resetUserPasswordDBQ, codeHashed, mock.Anything).Return("email", nil) + db.On("QueryRow", ctx, getUserIDFromEmailDBQ, "email").Return("userID", nil) + m := NewManager(cfg, db, nil) + + out, err := m.ResetPassword(ctx, code, newPassword) + assert.NoError(t, err) + require.NotNil(t, out) + assert.Equal(t, "userID", out.UserID) + db.AssertExpectations(t) + }) } func TestSetupTFA(t *testing.T) { @@ -1252,23 +1782,40 @@ func TestSetupTFA(t *testing.T) { }) t.Run("error storing 2fa info in database", func(t *testing.T) { - t.Parallel() - db := &tests.DBMock{} - db.On("QueryRow", ctx, getUserEmailDBQ, "userID").Return("email", nil) - db.On("Exec", ctx, updateTFAInfoDBQ, "userID", mock.Anything, mock.Anything).Return(tests.ErrFake) - m := NewManager(cfg, db, nil) + testCases := []struct { + dbErr error + expectedErr error + }{ + { + tests.ErrFake, + tests.ErrFake, + }, + { + pgx.ErrNoRows, + errTFAAlreadyEnabled, + }, + } + for _, tc := range testCases { + t.Run(tc.dbErr.Error(), func(t *testing.T) { + t.Parallel() + db := &tests.DBMock{} + db.On("QueryRow", ctx, getUserEmailDBQ, "userID").Return("email", nil) + db.On("QueryRow", ctx, updateTFAInfoDBQ, "userID", mock.Anything, mock.Anything).Return("", tc.dbErr) + m := NewManager(cfg, db, nil) - dataJSON, err := m.SetupTFA(ctx) - assert.Nil(t, dataJSON) - assert.Equal(t, tests.ErrFake, err) - db.AssertExpectations(t) + dataJSON, err := m.SetupTFA(ctx) + assert.Nil(t, dataJSON) + assert.Equal(t, tc.expectedErr, err) + db.AssertExpectations(t) + }) + } }) t.Run("setup 2fa succeeded", func(t *testing.T) { t.Parallel() db := &tests.DBMock{} db.On("QueryRow", ctx, getUserEmailDBQ, "userID").Return("email", nil) - db.On("Exec", ctx, updateTFAInfoDBQ, "userID", mock.Anything, mock.Anything).Return(nil) + db.On("QueryRow", ctx, updateTFAInfoDBQ, "userID", mock.Anything, mock.Anything).Return("userID", nil) m := NewManager(cfg, db, nil) dataJSON, err := m.SetupTFA(ctx) @@ -1291,6 +1838,7 @@ func TestUpdatePassword(t *testing.T) { ctx := context.WithValue(context.Background(), hub.UserIDKey, "userID") oldHashed, _ := bcrypt.GenerateFromPassword([]byte("old"), bcrypt.DefaultCost) new := "a66bV.Xp2" + l := passwordUpdateLimit t.Run("user id not found in ctx", func(t *testing.T) { t.Parallel() @@ -1334,9 +1882,31 @@ func TestUpdatePassword(t *testing.T) { }) t.Run("database error getting user password", func(t *testing.T) { + testCases := []struct { + dbErr error + }{ + {tests.ErrFakeDB}, + {pgx.ErrNoRows}, + } + for _, tc := range testCases { + t.Run(tc.dbErr.Error(), func(t *testing.T) { + t.Parallel() + db := &tests.DBMock{} + db.On("QueryRow", ctx, getUserPasswordDBQ, "userID").Return("", tc.dbErr) + m := NewManager(cfg, db, nil) + + err := m.UpdatePassword(ctx, "old", new) + assert.Equal(t, tc.dbErr, err) + db.AssertExpectations(t) + }) + } + }) + + t.Run("error reserving attempt", func(t *testing.T) { t.Parallel() db := &tests.DBMock{} - db.On("QueryRow", ctx, getUserPasswordDBQ, "userID").Return("", tests.ErrFakeDB) + db.On("QueryRow", ctx, getUserPasswordDBQ, "userID").Return(string(oldHashed), nil) + db.On("QueryRow", ctx, registerAuthAttemptDBQ, "userID", l.kind, l.burst, l.interval).Return(0, tests.ErrFakeDB) m := NewManager(cfg, db, nil) err := m.UpdatePassword(ctx, "old", new) @@ -1344,14 +1914,31 @@ func TestUpdatePassword(t *testing.T) { db.AssertExpectations(t) }) + t.Run("too many attempts", func(t *testing.T) { + t.Parallel() + db := &tests.DBMock{} + // Checking a password against the stored hash would not finish in + // time, so a result shows the password is not checked + db.On("QueryRow", ctx, getUserPasswordDBQ, "userID").Return(unusableHash, nil) + db.On("QueryRow", ctx, registerAuthAttemptDBQ, "userID", l.kind, l.burst, l.interval).Return(60, nil) + m := NewManager(cfg, db, nil) + + err := m.UpdatePassword(ctx, "old", new) + var tooManyErr *hub.TooManyAttemptsError + require.True(t, errors.As(err, &tooManyErr)) + assert.Equal(t, 60, tooManyErr.RetryAfter) + db.AssertExpectations(t) + }) + t.Run("invalid user password provided", func(t *testing.T) { t.Parallel() db := &tests.DBMock{} db.On("QueryRow", ctx, getUserPasswordDBQ, "userID").Return(string(oldHashed), nil) + db.On("QueryRow", ctx, registerAuthAttemptDBQ, "userID", l.kind, l.burst, l.interval).Return(0, nil) m := NewManager(cfg, db, nil) err := m.UpdatePassword(ctx, "old2", new) - assert.Error(t, err) + assert.Equal(t, ErrInvalidPassword, err) db.AssertExpectations(t) }) @@ -1359,6 +1946,8 @@ func TestUpdatePassword(t *testing.T) { t.Parallel() db := &tests.DBMock{} db.On("QueryRow", ctx, getUserPasswordDBQ, "userID").Return(string(oldHashed), nil) + db.On("QueryRow", ctx, registerAuthAttemptDBQ, "userID", l.kind, l.burst, l.interval).Return(0, nil) + db.On("Exec", context.WithoutCancel(ctx), refundAuthAttemptDBQ, "userID", l.kind, l.interval).Return(nil) db.On("Exec", ctx, updateUserPasswordDBQ, "userID", mock.Anything, mock.Anything). Return(tests.ErrFakeDB) m := NewManager(cfg, db, nil) @@ -1372,7 +1961,9 @@ func TestUpdatePassword(t *testing.T) { t.Parallel() db := &tests.DBMock{} db.On("QueryRow", ctx, getUserPasswordDBQ, "userID").Return(string(oldHashed), nil) - db.On("Exec", ctx, updateUserPasswordDBQ, "userID", mock.Anything, mock.Anything).Return(nil) + db.On("QueryRow", ctx, registerAuthAttemptDBQ, "userID", l.kind, l.burst, l.interval).Return(0, nil) + db.On("Exec", context.WithoutCancel(ctx), refundAuthAttemptDBQ, "userID", l.kind, l.interval).Return(nil) + db.On("Exec", ctx, updateUserPasswordDBQ, "userID", string(oldHashed), mock.Anything).Return(nil) m := NewManager(cfg, db, nil) err := m.UpdatePassword(ctx, "old", new) @@ -1494,9 +2085,10 @@ func TestVerifyPasswordResetCode(t *testing.T) { t.Run(tc.errMsg, func(t *testing.T) { t.Parallel() m := NewManager(cfg, nil, nil) - err := m.VerifyPasswordResetCode(ctx, tc.code) + userEmail, err := m.VerifyPasswordResetCode(ctx, tc.code) assert.True(t, errors.Is(err, hub.ErrInvalidInput)) assert.Contains(t, err.Error(), tc.errMsg) + assert.Empty(t, userEmail) }) } }) @@ -1522,8 +2114,39 @@ func TestVerifyPasswordResetCode(t *testing.T) { db.On("Exec", ctx, verifyPasswordResetCodeDBQ, codeHashed).Return(tc.dbErr) m := NewManager(cfg, db, nil) - err := m.VerifyPasswordResetCode(ctx, code) + userEmail, err := m.VerifyPasswordResetCode(ctx, code) + assert.Equal(t, tc.expectedErr, err) + assert.Empty(t, userEmail) + db.AssertExpectations(t) + }) + } + }) + + t.Run("database error getting password reset code email", func(t *testing.T) { + testCases := []struct { + dbErr error + expectedErr error + }{ + { + tests.ErrFakeDB, + tests.ErrFakeDB, + }, + { + pgx.ErrNoRows, + ErrInvalidPasswordResetCode, + }, + } + for _, tc := range testCases { + t.Run(tc.dbErr.Error(), func(t *testing.T) { + t.Parallel() + db := &tests.DBMock{} + db.On("Exec", ctx, verifyPasswordResetCodeDBQ, codeHashed).Return(nil) + db.On("QueryRow", ctx, getPasswordResetCodeEmailDBQ, codeHashed).Return("", tc.dbErr) + m := NewManager(cfg, db, nil) + + userEmail, err := m.VerifyPasswordResetCode(ctx, code) assert.Equal(t, tc.expectedErr, err) + assert.Empty(t, userEmail) db.AssertExpectations(t) }) } @@ -1533,10 +2156,12 @@ func TestVerifyPasswordResetCode(t *testing.T) { t.Parallel() db := &tests.DBMock{} db.On("Exec", ctx, verifyPasswordResetCodeDBQ, codeHashed).Return(nil) + db.On("QueryRow", ctx, getPasswordResetCodeEmailDBQ, codeHashed).Return("email@email.com", nil) m := NewManager(cfg, db, nil) - err := m.VerifyPasswordResetCode(ctx, code) + userEmail, err := m.VerifyPasswordResetCode(ctx, code) assert.Equal(t, nil, err) + assert.Equal(t, "email@email.com", userEmail) db.AssertExpectations(t) }) } diff --git a/internal/user/mock.go b/internal/user/mock.go index a52313347f..0bfdd52e6a 100644 --- a/internal/user/mock.go +++ b/internal/user/mock.go @@ -117,9 +117,13 @@ func (m *ManagerMock) RegisterUser(ctx context.Context, user *hub.User) error { } // ResetPassword implements the UserManager interface. -func (m *ManagerMock) ResetPassword(ctx context.Context, code, newPassword string) error { +func (m *ManagerMock) ResetPassword( + ctx context.Context, + code, newPassword string, +) (*hub.ResetPasswordOutput, error) { args := m.Called(ctx, code, newPassword) - return args.Error(0) + data, _ := args.Get(0).(*hub.ResetPasswordOutput) + return data, args.Error(1) } // SetupTFA implements the UserManager interface. @@ -148,7 +152,7 @@ func (m *ManagerMock) VerifyEmail(ctx context.Context, code string) (bool, error } // VerifyPasswordResetCode implements the UserManager interface. -func (m *ManagerMock) VerifyPasswordResetCode(ctx context.Context, code string) error { +func (m *ManagerMock) VerifyPasswordResetCode(ctx context.Context, code string) (string, error) { args := m.Called(ctx, code) - return args.Error(0) + return args.String(0), args.Error(1) } diff --git a/internal/user/template/password_reset_email.tmpl b/internal/user/template/password_reset_email.tmpl index b381094ac8..93aea529cf 100644 --- a/internal/user/template/password_reset_email.tmpl +++ b/internal/user/template/password_reset_email.tmpl @@ -13,8 +13,8 @@

Hi!

We got a request to reset your {{ .Theme.SiteName }} password.

-

If you did not perform this request, you can safely ignore this email. Otherwise, click the link below to complete the process.

-

Please note that the password reset link will only be valid for 15 minutes. If you haven't completed the process by then, you'll need to get a new password reset link.

+

If you did not perform this request, you can ignore this email, but keep it for 3 hours: no new link will be sent before then. Otherwise, click the link below to complete the process.

+

Please note that the password reset link will be valid for 4 hours. If a new link is requested in the next 3 hours, no new email will be sent and this link remains the one to use. If you haven't completed the process in 4 hours, you'll need to get a new password reset link.

diff --git a/internal/user/template/password_reset_success_email.tmpl b/internal/user/template/password_reset_success_email.tmpl index 5454590d85..b0bb190140 100644 --- a/internal/user/template/password_reset_success_email.tmpl +++ b/internal/user/template/password_reset_success_email.tmpl @@ -11,8 +11,8 @@

Hi!

-

Your {{ .Theme.SiteName }} password has been reset. You can now use your new password to log in to your account.

-

If this wasn't you, please reset your password to secure your account.

+

Your {{ .Theme.SiteName }} password has been reset, and every session that existed before the reset has been signed out.

+

If this wasn't you, please reset your password to secure your account, and review your API keys: a reset does not remove them.

diff --git a/web/src/api/index.test.tsx b/web/src/api/index.test.tsx index 7d472228c4..d73d362652 100644 --- a/web/src/api/index.test.tsx +++ b/web/src/api/index.test.tsx @@ -142,6 +142,103 @@ describe('API', () => { }); expect(fetchMock).toHaveBeenCalledTimes(1); }); + + it('TooManyAttempts with retry after seconds', async () => { + fetchMock.mockResponse(JSON.stringify({ message: 'too many attempts, please try again later' }), { + headers: { + 'content-type': 'application/json', + 'retry-after': '120', + }, + status: 429, + }); + + await expect(API.getOrganization('org1')).rejects.toStrictEqual({ + kind: ErrorKind.TooManyAttempts, + message: 'too many attempts, please try again later', + retryAfter: 120, + }); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it('TooManyAttempts with retry after date', async () => { + fetchMock.mockResponse(JSON.stringify({ message: 'too many attempts, please try again later' }), { + headers: { + 'content-type': 'application/json', + 'retry-after': 'Wed, 21 Oct 2015 07:28:00 GMT', + }, + status: 429, + }); + + await expect(API.getOrganization('org1')).rejects.toStrictEqual({ + kind: ErrorKind.TooManyAttempts, + message: 'too many attempts, please try again later', + retryAfter: undefined, + }); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it('TooManyAttempts without retry after', async () => { + fetchMock.mockResponse(JSON.stringify({ message: 'too many attempts, please try again later' }), { + headers: { + 'content-type': 'application/json', + }, + status: 429, + }); + + await expect(API.getOrganization('org1')).rejects.toStrictEqual({ + kind: ErrorKind.TooManyAttempts, + message: 'too many attempts, please try again later', + retryAfter: undefined, + }); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it('TooManyRequests with another message (not sent by the hub)', async () => { + fetchMock.mockResponse(JSON.stringify({ message: 'Rate exceeded' }), { + headers: { + 'content-type': 'application/json', + 'retry-after': '30', + }, + status: 429, + }); + + await expect(API.getOrganization('org1')).rejects.toStrictEqual({ + kind: ErrorKind.TooManyRequests, + message: 'Rate exceeded', + retryAfter: 30, + }); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it('TooManyRequests with a non-JSON body', async () => { + fetchMock.mockResponse('Too Many Requests', { + headers: { + 'content-type': 'text/html', + }, + status: 429, + }); + + await expect(API.getOrganization('org1')).rejects.toStrictEqual({ + kind: ErrorKind.TooManyRequests, + retryAfter: undefined, + }); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it('TooManyRequests with empty body', async () => { + fetchMock.mockResponse('', { + headers: { + 'retry-after': '30', + }, + status: 429, + }); + + await expect(API.getOrganization('org1')).rejects.toStrictEqual({ + kind: ErrorKind.TooManyRequests, + retryAfter: 30, + }); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); }); describe('getPackage', () => { @@ -1815,6 +1912,23 @@ describe('API', () => { describe('verifyPasswordResetCode', () => { it('success', async () => { + fetchMock.mockResponse(JSON.stringify({ email: 'test@email.com' }), { + headers: { + 'content-type': 'application/json', + }, + status: 200, + }); + + const response = await API.verifyPasswordResetCode('code'); + + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(fetchMock.mock.calls[0][0]).toEqual('/api/v1/users/verify-password-reset-code'); + expect(fetchMock.mock.calls[0][1]!.method).toBe('POST'); + expect(fetchMock.mock.calls[0][1]!.body).toBe(JSON.stringify({ code: 'code' })); + expect(response).toBe('test@email.com'); + }); + + it('success without email', async () => { fetchMock.mockResponse('', { headers: { 'content-type': 'text/plain; charset=utf-8', @@ -1826,19 +1940,50 @@ describe('API', () => { expect(fetchMock).toHaveBeenCalledTimes(1); expect(fetchMock.mock.calls[0][0]).toEqual('/api/v1/users/verify-password-reset-code'); - expect(response).toEqual(''); + expect(response).toBeUndefined(); }); }); describe('resetPassword', () => { - it('success', async () => { - mockNoContentResponse(); + const mockResetPasswordResponse = (sessionApproved?: string) => { + fetchMock.mockResponse( + new Response(null, { + headers: sessionApproved ? { 'X-Session-Approved': sessionApproved } : {}, + status: 204, + }) + ); + }; + + it('success when signed in', async () => { + mockResetPasswordResponse('true'); const response = await API.resetPassword('code', 'pass'); expect(fetchMock).toHaveBeenCalledTimes(1); expect(fetchMock.mock.calls[0][0]).toEqual('/api/v1/users/reset-password'); - expect(response).toEqual(''); + expect(fetchMock.mock.calls[0][1]!.method).toBe('PUT'); + expect(fetchMock.mock.calls[0][1]!.body).toBe(JSON.stringify({ code: 'code', password: 'pass' })); + expect(response).toBe(true); + }); + + it('rejects when the session is not approved', async () => { + mockResetPasswordResponse('false'); + + await expect(API.resetPassword('code', 'pass')).rejects.toEqual({ + kind: ErrorKind.NotApprovedSession, + }); + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(fetchMock.mock.calls[0][0]).toEqual('/api/v1/users/reset-password'); + }); + + it('success when not signed in', async () => { + mockResetPasswordResponse(); + + const response = await API.resetPassword('code', 'pass'); + + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(fetchMock.mock.calls[0][0]).toEqual('/api/v1/users/reset-password'); + expect(response).toBe(false); }); }); diff --git a/web/src/api/index.ts b/web/src/api/index.ts index 1f70a065fa..0e1996cc72 100644 --- a/web/src/api/index.ts +++ b/web/src/api/index.ts @@ -2,6 +2,7 @@ import camelCase from 'lodash/camelCase'; import isArray from 'lodash/isArray'; import isNull from 'lodash/isNull'; import isObject from 'lodash/isObject'; +import isString from 'lodash/isString'; import isUndefined from 'lodash/isUndefined'; import { JSONSchema } from '../jsonschema'; @@ -80,6 +81,10 @@ interface APIFetchProps { headers?: string[]; } +// Message the hub sends with a 429 when the attempts allowed for an account +// have been used up (hub.ErrTooManyAttempts) +const TOO_MANY_ATTEMPTS_MESSAGE = 'too many attempts, please try again later'; + type SecurityReportRaw = { [key: string]: { Results: SecurityReportResult[] } | SecurityReportResult[]; }; @@ -169,6 +174,28 @@ class API_CLASS { kind: ErrorKind.Gone, }; break; + case 429: { + // Retry-After is only used when it is a number of seconds (it may + // also be a date, for example when set by a CDN) + const retryAfter = res.headers.get('Retry-After'); + error = { + kind: ErrorKind.TooManyRequests, + retryAfter: !isNull(retryAfter) && /^\d+$/.test(retryAfter) ? parseInt(retryAfter, 10) : undefined, + }; + try { + tmpError = await res.json(); + error.message = tmpError.message !== '' ? tmpError.message : undefined; + } catch { + // Empty or non-JSON body + } + // Only the hub's own response means that the attempts allowed for + // the account have been used up. Any other 429 (a CDN or a proxy + // limiting requests) says nothing about the account + if (error.message === TOO_MANY_ATTEMPTS_MESSAGE) { + error.kind = ErrorKind.TooManyAttempts; + } + break; + } default: try { tmpError = await res.json(); @@ -984,8 +1011,8 @@ class API_CLASS { }); } - public verifyPasswordResetCode(code: string): Promise { - return this.apiFetch({ + public async verifyPasswordResetCode(code: string): Promise { + const res = await this.apiFetch({ url: `${this.API_BASE_URL}/users/verify-password-reset-code`, opts: { method: 'POST', @@ -997,10 +1024,14 @@ class API_CLASS { }), }, }); + // A server that does not return the email returns no JSON body + return isString(res?.email) ? res.email : undefined; } - public resetPassword(code: string, password: string): Promise { - return this.apiFetch({ + // Returns true when the browser has been signed in, false when it has not, + // and throws a NotApprovedSession error when the session needs a passcode + public async resetPassword(code: string, password: string): Promise { + const res = await this.apiFetch({ url: `${this.API_BASE_URL}/users/reset-password`, opts: { method: 'PUT', @@ -1012,7 +1043,9 @@ class API_CLASS { password: password, }), }, + checkApprovedSession: true, }); + return res?.headers?.get(this.HEADERS.sessionApproved) === 'true'; } public getAHStats(): Promise { diff --git a/web/src/layout/common/Alert.module.css b/web/src/layout/common/Alert.module.css index 585ad0c679..9cfe34f696 100644 --- a/web/src/layout/common/Alert.module.css +++ b/web/src/layout/common/Alert.module.css @@ -4,7 +4,7 @@ } .isAlertActive { - max-height: 300px; + max-height: 1000px; } @media (prefers-reduced-motion: reduce) { diff --git a/web/src/layout/common/Alert.test.tsx b/web/src/layout/common/Alert.test.tsx index 94e3e18969..aceadb7839 100644 --- a/web/src/layout/common/Alert.test.tsx +++ b/web/src/layout/common/Alert.test.tsx @@ -1,4 +1,4 @@ -import { render, screen } from '@testing-library/react'; +import { fireEvent, render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { hasClassContaining } from '../../utils/testUtils'; @@ -60,4 +60,63 @@ describe('Alert', () => { expect(onCloseMock).toHaveBeenCalledTimes(1); }); + + it('displays again the same message when it is set right after closing the alert', async () => { + const { rerender } = render(); + expect(await screen.findByRole('alert')).toBeInTheDocument(); + + rerender(); + expect(screen.queryByRole('alert')).toBeNull(); + + rerender(); + + expect(await screen.findByRole('alert')).toBeInTheDocument(); + expect(screen.getByText('errorMessage')).toBeInTheDocument(); + expect(hasClassContaining(screen.getByTestId('alertWrapper'), 'isAlertActive')).toBe(true); + }); + + describe('when the size of the alert can be observed', () => { + let onResize: () => void; + const observeMock = jest.fn(); + const disconnectMock = jest.fn(); + + beforeEach(() => { + window.ResizeObserver = class { + constructor(callback: () => void) { + onResize = callback; + } + observe = observeMock; + unobserve = jest.fn(); + disconnect = disconnectMock; + } as unknown as typeof ResizeObserver; + }); + + afterEach(() => { + delete (window as { ResizeObserver?: typeof ResizeObserver }).ResizeObserver; + }); + + it('keeps the alert in view while it opens', async () => { + render(); + + const alertWrapper = screen.getByTestId('alertWrapper'); + expect(await screen.findByRole('alert')).toBeInTheDocument(); + expect(observeMock).toHaveBeenCalledWith(alertWrapper); + expect(scrollIntoViewMock).toHaveBeenCalledTimes(1); + + onResize(); + + expect(scrollIntoViewMock).toHaveBeenCalledTimes(2); + expect(scrollIntoViewMock).toHaveBeenLastCalledWith({ block: 'nearest', inline: 'nearest' }); + + fireEvent.transitionEnd(alertWrapper); + + expect(disconnectMock).toHaveBeenCalled(); + }); + + it('does not observe the alert when there is no message', () => { + render(); + + expect(observeMock).not.toHaveBeenCalled(); + }); + }); }); diff --git a/web/src/layout/common/Alert.tsx b/web/src/layout/common/Alert.tsx index 631691a028..aca35b419e 100644 --- a/web/src/layout/common/Alert.tsx +++ b/web/src/layout/common/Alert.tsx @@ -28,7 +28,8 @@ const Alert: ElementType = (props: Props) => { }, 1000); } } else { - if (props.message !== errorMessage) { + // The alert may have just been closed while still holding this message + if (props.message !== errorMessage || !isVisible) { setErrorMessage(props.message); setIsVisible(true); errorWrapper.current!.scrollIntoView({ block: 'start', inline: 'nearest', behavior: 'smooth' }); @@ -42,6 +43,29 @@ const Alert: ElementType = (props: Props) => { }; }, [props.message]); + // When the message is set the alert has no height yet, so the call above + // cannot bring all of it into view: follow it while it opens + useEffect(() => { + const wrapper = errorWrapper.current; + if (!isVisible || isNull(wrapper) || typeof ResizeObserver === 'undefined') return; + + const observer = new ResizeObserver(() => { + wrapper.scrollIntoView({ block: 'nearest', inline: 'nearest' }); + }); + observer.observe(wrapper); + const stopObserving = (e: TransitionEvent) => { + if (e.target === wrapper) { + observer.disconnect(); + } + }; + wrapper.addEventListener('transitionend', stopObserving); + + return () => { + wrapper.removeEventListener('transitionend', stopObserving); + observer.disconnect(); + }; + }, [isVisible, errorMessage]); + return (
{ }); }); + it('TooManyAttemptsError', async () => { + vi.mocked(API).updatePassword.mockRejectedValue({ + kind: ErrorKind.TooManyAttempts, + retryAfter: 1800, + }); + + render(); + + await userEvent.type(screen.getByTestId('oldPasswordInput'), 'oldpass'); + await userEvent.type(screen.getByTestId('passwordInput'), 'newpass'); + await userEvent.type(screen.getByTestId('confirmPasswordInput'), 'newpass'); + + const btn = screen.getByRole('button', { name: 'Update password' }); + expect(btn).toBeInTheDocument(); + await userEvent.click(btn); + + await waitFor(() => { + expect(API.updatePassword).toHaveBeenCalledTimes(1); + }); + + await waitFor(() => { + expect(alertDispatcher.postAlert).toHaveBeenCalledTimes(1); + expect(alertDispatcher.postAlert).toHaveBeenCalledWith({ + type: 'danger', + message: 'Too many attempts to change your password. Please try again in 30 minutes.', + }); + }); + }); + + it('TooManyAttemptsError without retry after', async () => { + vi.mocked(API).updatePassword.mockRejectedValue({ + kind: ErrorKind.TooManyAttempts, + }); + + render(); + + await userEvent.type(screen.getByTestId('oldPasswordInput'), 'oldpass'); + await userEvent.type(screen.getByTestId('passwordInput'), 'newpass'); + await userEvent.type(screen.getByTestId('confirmPasswordInput'), 'newpass'); + + const btn = screen.getByRole('button', { name: 'Update password' }); + expect(btn).toBeInTheDocument(); + await userEvent.click(btn); + + await waitFor(() => { + expect(API.updatePassword).toHaveBeenCalledTimes(1); + }); + + await waitFor(() => { + expect(alertDispatcher.postAlert).toHaveBeenCalledTimes(1); + expect(alertDispatcher.postAlert).toHaveBeenCalledWith({ + type: 'danger', + message: 'Too many attempts to change your password. Please try again in a little while.', + }); + }); + expect(mockUseNavigate).not.toHaveBeenCalled(); + }); + + it('TooManyRequestsError (not the attempts limit)', async () => { + vi.mocked(API).updatePassword.mockRejectedValue({ + kind: ErrorKind.TooManyRequests, + retryAfter: 30, + }); + + render(); + + await userEvent.type(screen.getByTestId('oldPasswordInput'), 'oldpass'); + await userEvent.type(screen.getByTestId('passwordInput'), 'newpass'); + await userEvent.type(screen.getByTestId('confirmPasswordInput'), 'newpass'); + await userEvent.click(screen.getByRole('button', { name: 'Update password' })); + + await waitFor(() => { + expect(API.updatePassword).toHaveBeenCalledTimes(1); + }); + + await waitFor(() => { + expect(alertDispatcher.postAlert).toHaveBeenCalledTimes(1); + expect(alertDispatcher.postAlert).toHaveBeenCalledWith({ + type: 'danger', + message: 'Too many requests. Please try again in a minute.', + }); + }); + expect(mockUseNavigate).not.toHaveBeenCalled(); + }); + it('default error message', async () => { vi.mocked(API).updatePassword.mockRejectedValue({ kind: ErrorKind.Other, diff --git a/web/src/layout/controlPanel/settings/userSettings/profile/UpdatePassword.tsx b/web/src/layout/controlPanel/settings/userSettings/profile/UpdatePassword.tsx index c8225b87a9..8c35ab9825 100644 --- a/web/src/layout/controlPanel/settings/userSettings/profile/UpdatePassword.tsx +++ b/web/src/layout/controlPanel/settings/userSettings/profile/UpdatePassword.tsx @@ -9,6 +9,7 @@ import { AppCtx, signOut } from '../../../../../context/AppCtx'; import { ErrorKind, RefInputField } from '../../../../../types'; import alertDispatcher from '../../../../../utils/alertDispatcher'; import compoundErrorMessage from '../../../../../utils/compoundErrorMessage'; +import getRetryAfterText from '../../../../../utils/getRetryAfterText'; import InputField from '../../../../common/InputField'; interface Password { @@ -57,7 +58,17 @@ const UpdatePassword = () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any } catch (err: any) { setIsSending(false); - if (err.kind !== ErrorKind.Unauthorized) { + if (err.kind === ErrorKind.TooManyAttempts) { + alertDispatcher.postAlert({ + type: 'danger', + message: `Too many attempts to change your password. Please try again in ${getRetryAfterText(err.retryAfter)}.`, + }); + } else if (err.kind === ErrorKind.TooManyRequests) { + alertDispatcher.postAlert({ + type: 'danger', + message: `Too many requests. Please try again in ${getRetryAfterText(err.retryAfter)}.`, + }); + } else if (err.kind !== ErrorKind.Unauthorized) { const error = compoundErrorMessage(err, 'An error occurred updating your password'); alertDispatcher.postAlert({ type: 'danger', diff --git a/web/src/layout/controlPanel/settings/userSettings/profile/twoFactorAuth/DisableModal.test.tsx b/web/src/layout/controlPanel/settings/userSettings/profile/twoFactorAuth/DisableModal.test.tsx index 47793d9fc7..c601b748e8 100644 --- a/web/src/layout/controlPanel/settings/userSettings/profile/twoFactorAuth/DisableModal.test.tsx +++ b/web/src/layout/controlPanel/settings/userSettings/profile/twoFactorAuth/DisableModal.test.tsx @@ -117,6 +117,101 @@ describe('DisableModal', () => { ).toBeInTheDocument(); }); + it('incorrect code', async () => { + vi.mocked(API).disableTFA.mockRejectedValue({ + kind: ErrorKind.Other, + message: 'invalid input: invalid passcode', + }); + + render(); + + const btn = screen.getByRole('button', { name: 'Open disable two-factor authentication modal' }); + await userEvent.click(btn); + + const passcodeInput = screen.getByRole('textbox'); + await userEvent.type(passcodeInput, '123456'); + await userEvent.click(screen.getByRole('button', { name: 'Disable two-factor authentication' })); + + await waitFor(() => { + expect(API.disableTFA).toHaveBeenCalledTimes(1); + }); + + expect(await screen.findByText('Incorrect code. Please check it and try again.')).toBeInTheDocument(); + expect(onAuthErrorMock).not.toHaveBeenCalled(); + expect(onChangeMock).not.toHaveBeenCalled(); + }); + + it('too many attempts', async () => { + vi.mocked(API).disableTFA.mockRejectedValue({ kind: ErrorKind.TooManyAttempts, retryAfter: 86400 }); + + render(); + + const btn = screen.getByRole('button', { name: 'Open disable two-factor authentication modal' }); + await userEvent.click(btn); + + const passcodeInput = screen.getByRole('textbox'); + await userEvent.type(passcodeInput, '123456'); + await userEvent.click(screen.getByRole('button', { name: 'Disable two-factor authentication' })); + + await waitFor(() => { + expect(API.disableTFA).toHaveBeenCalledTimes(1); + }); + + expect( + await screen.findByText( + 'Too many incorrect codes. Please try again in 24 hours, or use one of your recovery codes.' + ) + ).toBeInTheDocument(); + expect(onAuthErrorMock).not.toHaveBeenCalled(); + expect(onChangeMock).not.toHaveBeenCalled(); + }); + + it('too many attempts without retry after', async () => { + vi.mocked(API).disableTFA.mockRejectedValue({ kind: ErrorKind.TooManyAttempts }); + + render(); + + const btn = screen.getByRole('button', { name: 'Open disable two-factor authentication modal' }); + await userEvent.click(btn); + + const passcodeInput = screen.getByRole('textbox'); + await userEvent.type(passcodeInput, '123456'); + await userEvent.click(screen.getByRole('button', { name: 'Disable two-factor authentication' })); + + await waitFor(() => { + expect(API.disableTFA).toHaveBeenCalledTimes(1); + }); + + expect( + await screen.findByText( + 'Too many incorrect codes. Please try again in a little while, or use one of your recovery codes.' + ) + ).toBeInTheDocument(); + expect(onAuthErrorMock).not.toHaveBeenCalled(); + }); + + it('too many requests (not the attempts limit)', async () => { + vi.mocked(API).disableTFA.mockRejectedValue({ kind: ErrorKind.TooManyRequests }); + + render(); + + const btn = screen.getByRole('button', { name: 'Open disable two-factor authentication modal' }); + await userEvent.click(btn); + + const passcodeInput = screen.getByRole('textbox'); + await userEvent.type(passcodeInput, '123456'); + await userEvent.click(screen.getByRole('button', { name: 'Disable two-factor authentication' })); + + await waitFor(() => { + expect(API.disableTFA).toHaveBeenCalledTimes(1); + }); + + expect(await screen.findByText('Too many requests. Please try again in a little while.')).toBeInTheDocument(); + expect(screen.queryByText(/Too many incorrect codes/)).toBeNull(); + expect(onAuthErrorMock).not.toHaveBeenCalled(); + expect(onChangeMock).not.toHaveBeenCalled(); + }); + it('unauthorized', async () => { vi.mocked(API).disableTFA.mockRejectedValue({ kind: ErrorKind.Unauthorized }); diff --git a/web/src/layout/controlPanel/settings/userSettings/profile/twoFactorAuth/DisableModal.tsx b/web/src/layout/controlPanel/settings/userSettings/profile/twoFactorAuth/DisableModal.tsx index 3f9c537287..8aa92307e1 100644 --- a/web/src/layout/controlPanel/settings/userSettings/profile/twoFactorAuth/DisableModal.tsx +++ b/web/src/layout/controlPanel/settings/userSettings/profile/twoFactorAuth/DisableModal.tsx @@ -5,6 +5,8 @@ import { IoMdCloseCircle } from 'react-icons/io'; import API from '../../../../../../api'; import { ErrorKind } from '../../../../../../types'; +import getRetryAfterText from '../../../../../../utils/getRetryAfterText'; +import isInvalidPasscodeError from '../../../../../../utils/isInvalidPasscodeError'; import InputField from '../../../../../common/InputField'; import Modal from '../../../../../common/Modal'; import styles from './DisableModal.module.css'; @@ -37,7 +39,15 @@ const DisableTwoFactorAuthenticationModal = (props: Props) => { // eslint-disable-next-line @typescript-eslint/no-explicit-any } catch (err: any) { setIsProcessing(false); - if (err.kind !== ErrorKind.Unauthorized) { + if (err.kind === ErrorKind.TooManyAttempts) { + setApiError( + `Too many incorrect codes. Please try again in ${getRetryAfterText(err.retryAfter)}, or use one of your recovery codes.` + ); + } else if (err.kind === ErrorKind.TooManyRequests) { + setApiError(`Too many requests. Please try again in ${getRetryAfterText(err.retryAfter)}.`); + } else if (isInvalidPasscodeError(err)) { + setApiError('Incorrect code. Please check it and try again.'); + } else if (err.kind !== ErrorKind.Unauthorized) { setApiError('An error occurred turning off two-factor authentication, please try again later.'); } else { props.onAuthError(); diff --git a/web/src/layout/home/ResetPasswordModal.module.css b/web/src/layout/home/ResetPasswordModal.module.css index 781b943d7d..c5f62f384b 100644 --- a/web/src/layout/home/ResetPasswordModal.module.css +++ b/web/src/layout/home/ResetPasswordModal.module.css @@ -5,7 +5,8 @@ .modal { max-width: 90%; width: 620px !important; - height: 500px; + min-height: 500px; + height: auto; } @media only screen and (max-width: 767.98px) { diff --git a/web/src/layout/home/ResetPasswordModal.test.tsx b/web/src/layout/home/ResetPasswordModal.test.tsx index 28d49f8a89..90d8a16875 100644 --- a/web/src/layout/home/ResetPasswordModal.test.tsx +++ b/web/src/layout/home/ResetPasswordModal.test.tsx @@ -4,20 +4,80 @@ import { BrowserRouter as Router } from 'react-router-dom'; import { vi } from 'vitest'; import API from '../../api'; -import { ErrorKind } from '../../types'; +import { AppCtx } from '../../context/AppCtx'; +import { ErrorKind, Profile } from '../../types'; import ResetPasswordModal from './ResetPasswordModal'; vi.mock('../../api'); const scrollIntoViewMock = jest.fn(); window.HTMLElement.prototype.scrollIntoView = scrollIntoViewMock; +const mockCtx = { + user: null, + prefs: { + controlPanel: {}, + search: { limit: 60 }, + theme: { + configured: 'light', + effective: 'light', + }, + notifications: { + lastDisplayedTime: null, + enabled: true, + displayed: [], + }, + }, +}; + +const mockDispatch = jest.fn(); + +const renderResetPasswordModal = (user: Profile | null = null) => + render( + + + + + + ); + +const submitResetForm = async () => { + await waitFor(() => { + expect(API.verifyPasswordResetCode).toHaveBeenCalledTimes(1); + }); + + const passwordInput = await screen.findByTestId('passwordInput'); + const confirmPasswordInput = screen.getByTestId('confirmPasswordInput'); + + await userEvent.type(passwordInput, '123abc'); + await userEvent.type(confirmPasswordInput, '123abc'); + + const btn = screen.getByRole('button', { name: 'Reset password' }); + await userEvent.click(btn); + + await waitFor(() => { + expect(API.resetPassword).toHaveBeenCalledTimes(1); + expect(API.resetPassword).toHaveBeenCalledWith('123', '123abc'); + }); +}; + +const submitPasscode = async (passcode: string) => { + const passcodeInput = screen.getByRole('textbox', { name: 'Authentication code' }); + await userEvent.type(passcodeInput, passcode); + await userEvent.click(screen.getByRole('button', { name: 'Verify passcode' })); + + await waitFor(() => { + expect(API.approveSession).toHaveBeenCalledTimes(1); + expect(API.approveSession).toHaveBeenCalledWith(passcode); + }); +}; + describe('ResetPasswordModal', () => { afterEach(() => { jest.resetAllMocks(); }); it('creates snapshot', async () => { - vi.mocked(API).verifyPasswordResetCode.mockResolvedValue(null); + vi.mocked(API).verifyPasswordResetCode.mockResolvedValue('jsmith@email.com'); const { asFragment } = render( @@ -35,7 +95,7 @@ describe('ResetPasswordModal', () => { describe('Render', () => { it('renders component', async () => { - vi.mocked(API).verifyPasswordResetCode.mockResolvedValue(null); + vi.mocked(API).verifyPasswordResetCode.mockResolvedValue(undefined); render( @@ -57,6 +117,27 @@ describe('ResetPasswordModal', () => { expect(screen.getByText('Password')).toBeInTheDocument(); expect(screen.getByText('Confirm password')).toBeInTheDocument(); + expect(screen.queryByTestId('emailInput')).not.toBeInTheDocument(); + }); + + it('renders read-only email field', async () => { + vi.mocked(API).verifyPasswordResetCode.mockResolvedValue('jsmith@email.com'); + + render( + + + + ); + + await waitFor(() => { + expect(API.verifyPasswordResetCode).toHaveBeenCalledTimes(1); + }); + + const emailInput = await screen.findByRole('textbox', { name: 'Email' }); + expect(emailInput).toHaveValue('jsmith@email.com'); + expect(emailInput).toHaveAttribute('type', 'email'); + expect(emailInput).toHaveAttribute('readonly'); + expect(emailInput).toHaveAttribute('autocomplete', 'username'); }); describe('when verifyPasswordResetCode fails', () => { @@ -76,7 +157,9 @@ describe('ResetPasswordModal', () => { }); expect( - await screen.findByText('This password reset link is no longer valid, please get a new one.') + await screen.findByText( + 'This password reset link is no longer valid. Links work for 4 hours and only once. If you requested more than one, use the most recent email; otherwise request a new link below.' + ) ).toBeInTheDocument(); expect(screen.getByTestId('resetPasswordForm')).toBeInTheDocument(); @@ -124,44 +207,150 @@ describe('ResetPasswordModal', () => { }); }); - it('resets password', async () => { - vi.mocked(API).verifyPasswordResetCode.mockResolvedValue(null); - vi.mocked(API).resetPassword.mockResolvedValue(null); + it('resets password and signs in', async () => { + vi.mocked(API).verifyPasswordResetCode.mockResolvedValue('jsmith@email.com'); + vi.mocked(API).resetPassword.mockResolvedValue(true); + vi.mocked(API).getUserProfile.mockResolvedValue({ + alias: 'jsmith', + email: 'jsmith@email.com', + passwordSet: true, + }); - render( - - - - ); + renderResetPasswordModal(); + await submitResetForm(); + expect(await screen.findByText("Your password has been reset and you're now signed in.")).toBeInTheDocument(); await waitFor(() => { - expect(API.verifyPasswordResetCode).toHaveBeenCalledTimes(1); + expect(API.getUserProfile).toHaveBeenCalledTimes(1); }); + expect(screen.queryByRole('button', { name: 'Reset password' })).not.toBeInTheDocument(); + }); - const passwordInput = await screen.findByTestId('passwordInput'); - const confirmPasswordInput = screen.getByTestId('confirmPasswordInput'); + it('resets password without signing in', async () => { + vi.mocked(API).verifyPasswordResetCode.mockResolvedValue('jsmith@email.com'); + vi.mocked(API).resetPassword.mockResolvedValue(false); - await userEvent.type(passwordInput, '123abc'); - await userEvent.type(confirmPasswordInput, '123abc'); + renderResetPasswordModal(); + await submitResetForm(); - const btn = screen.getByRole('button', { name: 'Reset password' }); - await userEvent.click(btn); + expect(await screen.findByText('Your password has been reset. You can now sign in.')).toBeInTheDocument(); + expect(API.getUserProfile).not.toHaveBeenCalled(); + expect(screen.queryByRole('button', { name: 'Reset password' })).not.toBeInTheDocument(); + }); - await waitFor(() => { - expect(API.resetPassword).toHaveBeenCalledTimes(1); - expect(API.resetPassword).toHaveBeenCalledWith('123', '123abc'); - }); + it('resets password without signing in when the browser is signed in to another account', async () => { + vi.mocked(API).verifyPasswordResetCode.mockResolvedValue('jsmith@email.com'); + vi.mocked(API).resetPassword.mockResolvedValue(false); + + renderResetPasswordModal({ alias: 'other', email: 'other@email.com', passwordSet: true }); + await submitResetForm(); expect( await screen.findByText( - 'Your password has been reset successfully. You can now log in using the new credentials.' + 'Your password has been reset. This browser is still signed in to another account (other).' ) ).toBeInTheDocument(); + expect(screen.queryByText('Your password has been reset. You can now sign in.')).toBeNull(); + expect(API.getUserProfile).not.toHaveBeenCalled(); + }); + + it('resets password without signing in when the account is the one the browser was signed in to', async () => { + vi.mocked(API).verifyPasswordResetCode.mockResolvedValue('jsmith@email.com'); + vi.mocked(API).resetPassword.mockResolvedValue(false); + + renderResetPasswordModal({ alias: 'jsmith', email: 'jsmith@email.com', passwordSet: true }); + await submitResetForm(); + + expect(await screen.findByText('Your password has been reset. You can now sign in.')).toBeInTheDocument(); + }); + + describe('when the passcode is required', () => { + const passcodeText = + 'Your password has been reset. To finish signing in, enter the code from your authenticator app or one of your recovery codes.'; + + beforeEach(() => { + vi.mocked(API).verifyPasswordResetCode.mockResolvedValue('jsmith@email.com'); + vi.mocked(API).resetPassword.mockRejectedValue({ + kind: ErrorKind.NotApprovedSession, + }); + }); + + it('renders passcode form', async () => { + renderResetPasswordModal(); + await submitResetForm(); + + expect(await screen.findByText(passcodeText)).toBeInTheDocument(); + expect(screen.getByRole('textbox', { name: 'Authentication code' })).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Verify passcode' })).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'Reset password' })).not.toBeInTheDocument(); + expect(mockDispatch).toHaveBeenCalledWith({ type: 'signOut' }); + }); + + it('signs in when the passcode is approved', async () => { + vi.mocked(API).approveSession.mockResolvedValue(null); + vi.mocked(API).getUserProfile.mockResolvedValue({ + alias: 'jsmith', + email: 'jsmith@email.com', + passwordSet: true, + }); + + renderResetPasswordModal(); + await submitResetForm(); + expect(await screen.findByText(passcodeText)).toBeInTheDocument(); + + await submitPasscode('123456'); + + expect(await screen.findByText("Your password has been reset and you're now signed in.")).toBeInTheDocument(); + await waitFor(() => { + expect(API.getUserProfile).toHaveBeenCalledTimes(1); + }); + expect(screen.queryByRole('textbox', { name: 'Authentication code' })).not.toBeInTheDocument(); + }); + + it('when there are too many incorrect codes', async () => { + vi.mocked(API).approveSession.mockRejectedValue({ + kind: ErrorKind.TooManyAttempts, + message: 'too many attempts, please try again later', + retryAfter: 120, + }); + + renderResetPasswordModal(); + await submitResetForm(); + expect(await screen.findByText(passcodeText)).toBeInTheDocument(); + + await submitPasscode('123456'); + + expect( + await screen.findByText( + 'Too many incorrect codes for this account. Please try again in 2 minutes, or enter one of your recovery codes.' + ) + ).toBeInTheDocument(); + expect(screen.getByRole('textbox', { name: 'Authentication code' })).toBeInTheDocument(); + expect(API.getUserProfile).not.toHaveBeenCalled(); + }); + + it('when the sign-in has expired', async () => { + vi.mocked(API).approveSession.mockRejectedValue({ + kind: ErrorKind.Unauthorized, + message: 'invalid session', + }); + + renderResetPasswordModal(); + await submitResetForm(); + expect(await screen.findByText(passcodeText)).toBeInTheDocument(); + + await submitPasscode('123456'); + + expect( + await screen.findByText('This sign-in has expired. Close this window and sign in again.') + ).toBeInTheDocument(); + expect(API.getUserProfile).not.toHaveBeenCalled(); + }); }); describe('when resetPassword fails', () => { it('custom error', async () => { - vi.mocked(API).verifyPasswordResetCode.mockResolvedValue(null); + vi.mocked(API).verifyPasswordResetCode.mockResolvedValue(undefined); vi.mocked(API).resetPassword.mockRejectedValue({ kind: ErrorKind.Other, message: 'custom error', @@ -194,7 +383,7 @@ describe('ResetPasswordModal', () => { }); it('default error', async () => { - vi.mocked(API).verifyPasswordResetCode.mockResolvedValue(null); + vi.mocked(API).verifyPasswordResetCode.mockResolvedValue(undefined); vi.mocked(API).resetPassword.mockRejectedValue({ kind: ErrorKind.Other, }); diff --git a/web/src/layout/home/ResetPasswordModal.tsx b/web/src/layout/home/ResetPasswordModal.tsx index 1ccdf5b3be..e4700f8230 100644 --- a/web/src/layout/home/ResetPasswordModal.tsx +++ b/web/src/layout/home/ResetPasswordModal.tsx @@ -2,17 +2,19 @@ import classnames from 'classnames'; import every from 'lodash/every'; import isNull from 'lodash/isNull'; import isUndefined from 'lodash/isUndefined'; -import { ChangeEvent, useEffect, useRef, useState } from 'react'; +import { ChangeEvent, useContext, useEffect, useRef, useState } from 'react'; import { CgLastpass } from 'react-icons/cg'; import { MdClose, MdDone } from 'react-icons/md'; import { useNavigate } from 'react-router-dom'; import API from '../../api'; +import { AppCtx, refreshUserProfile, signOut } from '../../context/AppCtx'; import { ErrorKind, RefInputField } from '../../types'; import compoundErrorMessage from '../../utils/compoundErrorMessage'; import InputField from '../common/InputField'; import Loading from '../common/Loading'; import Modal from '../common/Modal'; +import ApproveSessionForm from '../navigation/ApproveSessionForm'; import ResetPassword from '../navigation/ResetPassword'; import styles from './ResetPasswordModal.module.css'; @@ -30,7 +32,10 @@ interface Props { code?: string | null; } +type Outcome = 'form' | 'signedIn' | 'passcode' | 'notSignedIn'; + const ResetPasswordModal = (props: Props) => { + const { ctx, dispatch } = useContext(AppCtx); const [code, setCode] = useState(props.code); const [verifying, setVerifying] = useState(null); const [validCode, setValidCode] = useState(null); @@ -44,7 +49,15 @@ const ResetPasswordModal = (props: Props) => { const [isValidated, setIsValidated] = useState(false); const [apiError, setApiError] = useState(null); const [apiPwdError, setApiPwdError] = useState(null); - const [isSuccess, setIsSuccess] = useState(false); + const [outcome, setOutcome] = useState('form'); + const [email, setEmail] = useState(); + + // Alias of the account this browser is signed in to, when it is not the one + // the password reset link belongs to (the reset does not sign it in then) + const otherAccountAlias = + !isNull(ctx.user) && !isUndefined(ctx.user) && !isUndefined(email) && ctx.user.email !== email + ? ctx.user.alias + : undefined; const onPasswordChange = (e: ChangeEvent) => { setPassword({ value: e.target.value, isValid: e.currentTarget.checkValidity() }); @@ -59,13 +72,24 @@ const ResetPasswordModal = (props: Props) => { async function resetPassword(password: string) { try { - await API.resetPassword(code!, password); - setIsSuccess(true); + const signedIn = await API.resetPassword(code!, password); + if (signedIn) { + refreshUserProfile(dispatch); + setOutcome('signedIn'); + } else { + setOutcome('notSignedIn'); + } setIsSending(false); // eslint-disable-next-line @typescript-eslint/no-explicit-any } catch (err: any) { - const error = compoundErrorMessage(err, 'An error occurred resetting the password'); - setApiError(error); + if (err.kind === ErrorKind.NotApprovedSession) { + // A session of the same account in this browser was just deleted + dispatch(signOut()); + setOutcome('passcode'); + } else { + const error = compoundErrorMessage(err, 'An error occurred resetting the password'); + setApiError(error); + } setIsSending(false); } } @@ -110,12 +134,14 @@ const ResetPasswordModal = (props: Props) => { async function verifyPasswordResetCode() { setVerifying(true); try { - await API.verifyPasswordResetCode(code!); + setEmail(await API.verifyPasswordResetCode(code!)); setValidCode(true); // eslint-disable-next-line @typescript-eslint/no-explicit-any } catch (err: any) { if (err.kind === ErrorKind.Gone) { - setApiError('This password reset link is no longer valid, please get a new one.'); + setApiError( + 'This password reset link is no longer valid. Links work for 4 hours and only once. If you requested more than one, use the most recent email; otherwise request a new link below.' + ); setDisplayResetPwd(true); } else { let error = 'An error occurred with your password reset code.'; @@ -178,12 +204,12 @@ const ResetPasswordModal = (props: Props) => { disabledClose={verifying} modalClassName={styles.modal} open - closeButton={validCode && !isSuccess ? closeButton : undefined} + closeButton={validCode && outcome === 'form' ? closeButton : undefined} error={apiError} cleanError={cleanApiError} >
{verifying ? ( <> @@ -194,13 +220,39 @@ const ResetPasswordModal = (props: Props) => {
{validCode ? ( <> - {isSuccess ? ( -
-
- + {outcome !== 'form' ? ( + <> +
+
+ +
+ {outcome === 'signedIn' && <>Your password has been reset and you're now signed in.} + {outcome === 'passcode' && ( + <> + Your password has been reset. To finish signing in, enter the code from your authenticator app + or one of your recovery codes. + + )} + {outcome === 'notSignedIn' && ( + <> + {isUndefined(otherAccountAlias) + ? 'Your password has been reset. You can now sign in.' + : `Your password has been reset. This browser is still signed in to another account (${otherAccountAlias}).`} + + )}
- Your password has been reset successfully. You can now log in using the new credentials. -
+ {outcome === 'passcode' && ( + { + setApiError(null); + refreshUserProfile(dispatch); + setOutcome('signedIn'); + }} + onError={setApiError} + expiredHint="Close this window and sign in again." + /> + )} + ) : (
{ autoComplete="off" noValidate > + {email && ( + + )} + creates snapshot 1`] = ` class="modal-body p-4 h-100 d-flex flex-column" >
creates snapshot 1`] = ` data-testid="resetPwdForm" novalidate="" > +
+ + +
+
diff --git a/web/src/layout/navigation/ApproveSessionForm.test.tsx b/web/src/layout/navigation/ApproveSessionForm.test.tsx new file mode 100644 index 0000000000..3bd7194487 --- /dev/null +++ b/web/src/layout/navigation/ApproveSessionForm.test.tsx @@ -0,0 +1,246 @@ +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { vi } from 'vitest'; + +import API from '../../api'; +import { ErrorKind } from '../../types'; +import ApproveSessionForm from './ApproveSessionForm'; +vi.mock('../../api'); + +const onSuccessMock = jest.fn(); +const onErrorMock = jest.fn(); + +const defaultProps = { + onSuccess: onSuccessMock, + onError: onErrorMock, + expiredHint: 'Go back and sign in again.', +}; + +const tooManyText = + 'Too many incorrect codes for this account. Please try again in 2 minutes, or enter one of your recovery codes.'; + +describe('ApproveSessionForm', () => { + afterEach(() => { + jest.resetAllMocks(); + }); + + const submitPasscode = async (passcode: string) => { + const input = screen.getByRole('textbox', { name: 'Authentication code' }); + await userEvent.type(input, passcode); + + const btn = screen.getByRole('button', { name: 'Verify passcode' }); + expect(btn).toBeEnabled(); + await userEvent.click(btn); + + await waitFor(() => { + expect(API.approveSession).toHaveBeenCalledTimes(1); + expect(API.approveSession).toHaveBeenCalledWith(passcode); + }); + }; + + describe('Render', () => { + it('renders component', () => { + render(); + + expect(screen.getByText('Authentication code')).toBeInTheDocument(); + expect(screen.getByTestId('passcodeInput')).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Verify passcode' })).toBeDisabled(); + expect(screen.getByRole('button', { name: 'Verify passcode' })).toHaveTextContent('Verify'); + }); + + it('focuses the passcode field', () => { + render(); + + expect(screen.getByRole('textbox', { name: 'Authentication code' })).toHaveFocus(); + }); + + it('calls onSuccess when the session is approved', async () => { + vi.mocked(API).approveSession.mockResolvedValue(null); + + render(); + + await submitPasscode('123456'); + + await waitFor(() => { + expect(onSuccessMock).toHaveBeenCalledTimes(1); + }); + expect(onErrorMock).not.toHaveBeenCalled(); + expect(screen.queryByText('Verifying...')).toBeNull(); + }); + + it('calls onError with the incorrect code text when the passcode is invalid', async () => { + vi.mocked(API).approveSession.mockRejectedValue({ + kind: ErrorKind.Other, + message: 'invalid input: invalid passcode', + }); + + render(); + + await submitPasscode('123456'); + + await waitFor(() => { + expect(onErrorMock).toHaveBeenCalledTimes(1); + expect(onErrorMock).toHaveBeenCalledWith('Incorrect code. Please check it and try again.'); + }); + expect(onSuccessMock).not.toHaveBeenCalled(); + expect(screen.getByRole('button', { name: 'Verify passcode' })).toBeEnabled(); + }); + + it('calls onError with the error message when the request fails for another reason', async () => { + vi.mocked(API).approveSession.mockRejectedValue({ + kind: ErrorKind.Other, + message: 'custom error', + }); + + render(); + + await submitPasscode('123456'); + + await waitFor(() => { + expect(onErrorMock).toHaveBeenCalledTimes(1); + expect(onErrorMock).toHaveBeenCalledWith('An error occurred signing in: custom error'); + }); + expect(onSuccessMock).not.toHaveBeenCalled(); + }); + + it('calls onError with the expired text when the sign-in has expired', async () => { + vi.mocked(API).approveSession.mockRejectedValue({ + kind: ErrorKind.Unauthorized, + message: 'invalid session', + }); + + render(); + + await submitPasscode('123456'); + + await waitFor(() => { + expect(onErrorMock).toHaveBeenCalledTimes(1); + expect(onErrorMock).toHaveBeenCalledWith('This sign-in has expired. Go back and sign in again.'); + }); + expect(onSuccessMock).not.toHaveBeenCalled(); + }); + + it('calls onError with a neutral text, without the hint, when requests are limited upstream', async () => { + vi.mocked(API).approveSession.mockRejectedValue({ + kind: ErrorKind.TooManyRequests, + retryAfter: 30, + }); + + render(); + + await submitPasscode('123456'); + + await waitFor(() => { + expect(onErrorMock).toHaveBeenCalledTimes(1); + expect(onErrorMock).toHaveBeenCalledWith('Too many requests. Please try again in a minute.'); + }); + expect(onSuccessMock).not.toHaveBeenCalled(); + expect(screen.getByRole('button', { name: 'Verify passcode' })).toBeEnabled(); + expect(screen.queryByText('Custom hint.')).toBeNull(); + }); + + it('calls onError with the too many attempts text', async () => { + vi.mocked(API).approveSession.mockRejectedValue({ + kind: ErrorKind.TooManyAttempts, + message: 'too many attempts, please try again later', + retryAfter: 90, + }); + + render(); + + await submitPasscode('123456'); + + await waitFor(() => { + expect(onErrorMock).toHaveBeenCalledTimes(1); + expect(onErrorMock).toHaveBeenCalledWith(tooManyText); + }); + expect(onSuccessMock).not.toHaveBeenCalled(); + }); + + it('displays the hint provided below the form, not in the error, after too many attempts', async () => { + vi.mocked(API) + .approveSession.mockRejectedValueOnce({ + kind: ErrorKind.TooManyAttempts, + message: 'too many attempts, please try again later', + retryAfter: 90, + }) + .mockRejectedValueOnce({ + kind: ErrorKind.Other, + message: 'invalid input: invalid passcode', + }); + + render(); + + expect(screen.queryByText('Custom hint.')).toBeNull(); + + await submitPasscode('123456'); + + await waitFor(() => { + expect(onErrorMock).toHaveBeenCalledTimes(1); + expect(onErrorMock).toHaveBeenCalledWith(tooManyText); + }); + expect(await screen.findByText('Custom hint.')).toBeInTheDocument(); + expect(onSuccessMock).not.toHaveBeenCalled(); + + // The hint stays when a later attempt fails for another reason + await userEvent.click(screen.getByRole('button', { name: 'Verify passcode' })); + + await waitFor(() => { + expect(onErrorMock).toHaveBeenCalledTimes(2); + expect(onErrorMock).toHaveBeenLastCalledWith('Incorrect code. Please check it and try again.'); + }); + expect(screen.getByText('Custom hint.')).toBeInTheDocument(); + }); + }); + + describe('Enter key', () => { + it('does not send a request when the passcode is empty', () => { + render(); + + fireEvent.keyDown(screen.getByRole('textbox', { name: 'Authentication code' }), { key: 'Enter' }); + + expect(API.approveSession).not.toHaveBeenCalled(); + }); + + it('sends only one request while the first one is pending', async () => { + vi.mocked(API).approveSession.mockReturnValue(new Promise(() => {})); + + render(); + + const input = screen.getByRole('textbox', { name: 'Authentication code' }); + await userEvent.type(input, '123456'); + + // First press, auto-repeat events while the key is held and a second press + fireEvent.keyDown(input, { key: 'Enter' }); + fireEvent.keyDown(input, { key: 'Enter', repeat: true }); + fireEvent.keyDown(input, { key: 'Enter' }); + + expect(await screen.findByText('Verifying...')).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Verify passcode' })).toBeDisabled(); + expect(API.approveSession).toHaveBeenCalledTimes(1); + expect(API.approveSession).toHaveBeenCalledWith('123456'); + }); + }); + + describe('when the form is removed while the request is pending', () => { + it('does not call onError', async () => { + let rejectRequest: (err: unknown) => void = () => {}; + vi.mocked(API).approveSession.mockReturnValue( + new Promise((_, reject) => { + rejectRequest = reject; + }) + ); + + const { unmount } = render(); + + await submitPasscode('123456'); + unmount(); + rejectRequest({ kind: ErrorKind.Other, message: 'invalid input: invalid passcode' }); + await Promise.resolve(); + await Promise.resolve(); + + expect(onErrorMock).not.toHaveBeenCalled(); + expect(onSuccessMock).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/web/src/layout/navigation/ApproveSessionForm.tsx b/web/src/layout/navigation/ApproveSessionForm.tsx new file mode 100644 index 0000000000..52e1d2196f --- /dev/null +++ b/web/src/layout/navigation/ApproveSessionForm.tsx @@ -0,0 +1,120 @@ +import { ChangeEvent, KeyboardEvent, useEffect, useRef, useState } from 'react'; + +import API from '../../api'; +import { ErrorKind } from '../../types'; +import compoundErrorMessage from '../../utils/compoundErrorMessage'; +import getRetryAfterText from '../../utils/getRetryAfterText'; +import isInvalidPasscodeError from '../../utils/isInvalidPasscodeError'; +import InputField from '../common/InputField'; + +interface Props { + onSuccess: () => void; + onError: (message: string) => void; + expiredHint: string; + // Shown below the form once too many incorrect codes have been entered + tooManyHint?: string; +} + +const ApproveSessionForm = (props: Props) => { + const [passcode, setPasscode] = useState(''); + const [isApprovingSession, setIsApprovingSession] = useState(false); + const [tooManyAttempts, setTooManyAttempts] = useState(false); + const isMounted = useRef(true); + + useEffect(() => { + isMounted.current = true; + return () => { + isMounted.current = false; + }; + }, []); + + const onPasscodeChange = (e: ChangeEvent) => { + setPasscode(e.target.value); + }; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const getErrorMessage = (err: any): string => { + switch (err.kind) { + case ErrorKind.TooManyAttempts: + return `Too many incorrect codes for this account. Please try again in ${getRetryAfterText( + err.retryAfter + )}, or enter one of your recovery codes.`; + case ErrorKind.TooManyRequests: + return `Too many requests. Please try again in ${getRetryAfterText(err.retryAfter)}.`; + case ErrorKind.Unauthorized: + return `This sign-in has expired. ${props.expiredHint}`; + default: + if (isInvalidPasscodeError(err)) { + return 'Incorrect code. Please check it and try again.'; + } + return compoundErrorMessage(err, 'An error occurred signing in'); + } + }; + + async function approveSession() { + if (passcode === '' || isApprovingSession) return; + try { + setIsApprovingSession(true); + await API.approveSession(passcode); + setIsApprovingSession(false); + props.onSuccess(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } catch (err: any) { + // The error is not reported once the form is gone (the user went back) + if (!isMounted.current) return; + setIsApprovingSession(false); + if (err.kind === ErrorKind.TooManyAttempts) { + setTooManyAttempts(true); + } + props.onError(getErrorMessage(err)); + } + } + + const handleOnReturnKeyDown = (event: KeyboardEvent): void => { + if (event.key === 'Enter' && !event.repeat) { + approveSession(); + } + }; + + return ( +
+
+ + + + + {tooManyAttempts && props.tooManyHint && {props.tooManyHint}} +
+
+ ); +}; + +export default ApproveSessionForm; diff --git a/web/src/layout/navigation/LogIn.test.tsx b/web/src/layout/navigation/LogIn.test.tsx index 8d74c7e6fd..13a2a52d85 100644 --- a/web/src/layout/navigation/LogIn.test.tsx +++ b/web/src/layout/navigation/LogIn.test.tsx @@ -1,4 +1,4 @@ -import { render, screen, waitFor } from '@testing-library/react'; +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { BrowserRouter as Router } from 'react-router-dom'; import { vi } from 'vitest'; @@ -207,6 +207,337 @@ describe('LogIn', () => { }); }); + describe('Too many sign-in attempts', () => { + afterEach(() => { + document.head.querySelectorAll("meta[name^='artifacthub:']").forEach((el) => el.remove()); + }); + + it('displays error with retry time and keeps Forgot password and OAuth enabled', async () => { + const meta = document.createElement('meta'); + meta.name = 'artifacthub:githubAuth'; + meta.content = 'true'; + document.head.appendChild(meta); + vi.mocked(API).login.mockRejectedValue({ + kind: ErrorKind.TooManyAttempts, + message: 'too many attempts, please try again later', + retryAfter: 120, + }); + + render( + + + + ); + + await userEvent.type(screen.getByLabelText('Password'), 'pass123'); + await userEvent.type(screen.getByRole('textbox', { name: 'Email' }), 'jsmith@email.com'); + await userEvent.click(screen.getByRole('button', { name: 'Sign in' })); + + await waitFor(() => { + expect(API.login).toHaveBeenCalledTimes(1); + }); + + expect( + await screen.findByText( + 'Too many sign-in attempts for this account. Please try again in 2 minutes, or use "Forgot password?" to reset your password and sign in.' + ) + ).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Open reset password' })).toBeEnabled(); + expect(screen.getByRole('button', { name: 'Sign in with GitHub' })).toBeEnabled(); + expect(screen.getByRole('button', { name: 'Sign in' })).toBeEnabled(); + }); + + describe('once the error is displayed', () => { + const tooManyRegex = /Too many sign-in attempts for this account/; + + const displayError = async () => { + vi.mocked(API).login.mockRejectedValue({ + kind: ErrorKind.TooManyAttempts, + message: 'too many attempts, please try again later', + retryAfter: 3600, + }); + + render( + + + + ); + + await userEvent.type(screen.getByLabelText('Password'), 'pass123'); + await userEvent.type(screen.getByRole('textbox', { name: 'Email' }), 'jsmith@email.com'); + await userEvent.click(screen.getByRole('button', { name: 'Sign in' })); + + expect(await screen.findByText(tooManyRegex)).toBeInTheDocument(); + }; + + it('keeps it when a button of the form is focused', async () => { + await displayError(); + + fireEvent.focusIn(screen.getByRole('button', { name: 'Open reset password' })); + fireEvent.focusIn(screen.getByRole('button', { name: 'Sign in' })); + + expect(screen.getByText(tooManyRegex)).toBeInTheDocument(); + }); + + it('removes it when a field of the form is focused', async () => { + await displayError(); + + fireEvent.focusIn(screen.getByLabelText('Password')); + + await waitFor(() => { + expect(screen.queryByText(tooManyRegex)).toBeNull(); + }); + }); + + // Some browsers do not focus buttons when they are clicked + it('removes it when Forgot password is clicked, even if the button is not focused', async () => { + await displayError(); + + fireEvent.click(screen.getByRole('button', { name: 'Open reset password' })); + + expect(await screen.findByText('Forgot Password?')).toBeInTheDocument(); + await waitFor(() => { + expect(screen.queryByText(tooManyRegex)).toBeNull(); + }); + }); + }); + + it('displays a neutral error when requests are limited upstream', async () => { + vi.mocked(API).login.mockRejectedValue({ + kind: ErrorKind.TooManyRequests, + }); + + render( + + + + ); + + await userEvent.type(screen.getByLabelText('Password'), 'pass123'); + await userEvent.type(screen.getByRole('textbox', { name: 'Email' }), 'jsmith@email.com'); + await userEvent.click(screen.getByRole('button', { name: 'Sign in' })); + + await waitFor(() => { + expect(API.login).toHaveBeenCalledTimes(1); + }); + + expect(await screen.findByText('Too many requests. Please try again in a little while.')).toBeInTheDocument(); + expect(screen.queryByText(/Too many sign-in attempts for this account/)).toBeNull(); + expect(screen.getByRole('button', { name: 'Sign in' })).toBeEnabled(); + }); + }); + + describe('Enter key on the password field', () => { + it('sends only one request while the first one is pending', async () => { + vi.mocked(API).login.mockReturnValue(new Promise(() => {})); + + render( + + + + ); + + await userEvent.type(screen.getByRole('textbox', { name: 'Email' }), 'jsmith@email.com'); + const passwordInput = screen.getByLabelText('Password'); + await userEvent.type(passwordInput, 'pass123'); + + // First press, auto-repeat events while the key is held and a second press + fireEvent.keyDown(passwordInput, { key: 'Enter' }); + fireEvent.keyDown(passwordInput, { key: 'Enter', repeat: true }); + fireEvent.keyDown(passwordInput, { key: 'Enter', repeat: true }); + fireEvent.keyDown(passwordInput, { key: 'Enter' }); + + await waitFor(() => { + expect(API.login).toHaveBeenCalledTimes(1); + }); + expect(await screen.findByText('Signing in...')).toBeInTheDocument(); + + fireEvent.keyDown(passwordInput, { key: 'Enter', repeat: true }); + fireEvent.keyDown(passwordInput, { key: 'Enter' }); + + // Give any extra request the time to be sent before checking + await new Promise((resolve) => setTimeout(resolve, 50)); + expect(API.login).toHaveBeenCalledTimes(1); + }); + + it('ignores auto-repeat events of a held key', async () => { + render( + + + + ); + + await userEvent.type(screen.getByRole('textbox', { name: 'Email' }), 'jsmith@email.com'); + const passwordInput = screen.getByLabelText('Password'); + await userEvent.type(passwordInput, 'pass123'); + + fireEvent.keyDown(passwordInput, { key: 'Enter', repeat: true }); + + await new Promise((resolve) => setTimeout(resolve, 50)); + expect(API.login).not.toHaveBeenCalled(); + }); + + it('can submit again once the request has failed', async () => { + vi.mocked(API).login.mockRejectedValue({ kind: ErrorKind.Unauthorized }); + + render( + + + + ); + + await userEvent.type(screen.getByRole('textbox', { name: 'Email' }), 'jsmith@email.com'); + const passwordInput = screen.getByLabelText('Password'); + await userEvent.type(passwordInput, 'pass123'); + + fireEvent.keyDown(passwordInput, { key: 'Enter' }); + expect(await screen.findByText('Authentication failed. Please check your credentials.')).toBeInTheDocument(); + expect(API.login).toHaveBeenCalledTimes(1); + + fireEvent.keyDown(passwordInput, { key: 'Enter' }); + await waitFor(() => { + expect(API.login).toHaveBeenCalledTimes(2); + }); + }); + }); + + describe('Passcode step', () => { + const goToPasscodeStep = async () => { + vi.mocked(API).login.mockRejectedValue({ + kind: ErrorKind.NotApprovedSession, + }); + + await userEvent.type(screen.getByLabelText('Password'), 'pass123'); + await userEvent.type(screen.getByRole('textbox', { name: 'Email' }), 'jsmith@email.com'); + await userEvent.click(screen.getByRole('button', { name: 'Sign in' })); + + await waitFor(() => { + expect(API.login).toHaveBeenCalledTimes(1); + }); + + expect(await screen.findByRole('textbox', { name: 'Authentication code' })).toBeInTheDocument(); + }; + + const submitPasscode = async (passcode: string) => { + await userEvent.type(screen.getByRole('textbox', { name: 'Authentication code' }), passcode); + await userEvent.click(screen.getByRole('button', { name: 'Verify passcode' })); + + await waitFor(() => { + expect(API.approveSession).toHaveBeenCalledTimes(1); + expect(API.approveSession).toHaveBeenCalledWith(passcode); + }); + }; + + it('renders passcode form', async () => { + render( + + + + ); + + await goToPasscodeStep(); + + expect(screen.getByTestId('passcodeInput')).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Verify passcode' })).toBeDisabled(); + expect(screen.getByRole('button', { name: 'Back to Sign in' })).toBeInTheDocument(); + expect(screen.queryByTestId('loginForm')).toBeNull(); + }); + + it('approves session', async () => { + vi.mocked(API).approveSession.mockResolvedValue(null); + + render( + + + + ); + + await goToPasscodeStep(); + await submitPasscode('123456'); + + await waitFor(() => { + expect(defaultProps.setOpenLogIn).toHaveBeenCalledTimes(1); + expect(defaultProps.setOpenLogIn).toHaveBeenCalledWith(false); + }); + }); + + it('keeps passcode form when code is wrong', async () => { + vi.mocked(API).approveSession.mockRejectedValue({ + kind: ErrorKind.Other, + message: 'invalid input: invalid passcode', + }); + + render( + + + + ); + + await goToPasscodeStep(); + await submitPasscode('123456'); + + expect(await screen.findByText('Incorrect code. Please check it and try again.')).toBeInTheDocument(); + expect(screen.getByRole('textbox', { name: 'Authentication code' })).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Verify passcode' })).toBeEnabled(); + expect(screen.queryByTestId('loginForm')).toBeNull(); + expect(defaultProps.setOpenLogIn).not.toHaveBeenCalled(); + }); + + it('displays expired error and goes back to enabled sign in form', async () => { + vi.mocked(API).approveSession.mockRejectedValue({ + kind: ErrorKind.Unauthorized, + message: 'invalid session', + }); + + render( + + + + ); + + await goToPasscodeStep(); + await submitPasscode('123456'); + + expect(await screen.findByText('This sign-in has expired. Go back and sign in again.')).toBeInTheDocument(); + + await userEvent.click(screen.getByRole('button', { name: 'Back to Sign in' })); + + const btn = await screen.findByRole('button', { name: 'Sign in' }); + expect(btn).toBeEnabled(); + expect(btn).toHaveTextContent('Sign in'); + expect(screen.queryByText('Signing in...')).toBeNull(); + }); + + it('displays too many codes error, with the Forgot password hint below the form', async () => { + vi.mocked(API).approveSession.mockRejectedValue({ + kind: ErrorKind.TooManyAttempts, + message: 'too many attempts, please try again later', + retryAfter: 7200, + }); + + render( + + + + ); + + await goToPasscodeStep(); + await submitPasscode('123456'); + + expect( + await screen.findByText( + 'Too many incorrect codes for this account. Please try again in 2 hours, or enter one of your recovery codes.' + ) + ).toBeInTheDocument(); + expect( + screen.getByText( + 'If you didn\'t make these attempts, someone may know your password: go back and use "Forgot password?" to reset it to a new password. That signs out every other session and stops them; then finish signing in with a recovery code, or with a code from your app once the wait is over.' + ) + ).toBeInTheDocument(); + expect(screen.getByRole('textbox', { name: 'Authentication code' })).toBeInTheDocument(); + }); + }); + describe('Reset password', () => { it('displays form', async () => { render( diff --git a/web/src/layout/navigation/LogIn.tsx b/web/src/layout/navigation/LogIn.tsx index d0c9d1b692..3ea414d188 100644 --- a/web/src/layout/navigation/LogIn.tsx +++ b/web/src/layout/navigation/LogIn.tsx @@ -2,7 +2,7 @@ import classnames from 'classnames'; import every from 'lodash/every'; import isNull from 'lodash/isNull'; import isUndefined from 'lodash/isUndefined'; -import { ChangeEvent, Dispatch, KeyboardEvent, SetStateAction, useContext, useRef, useState } from 'react'; +import { ChangeEvent, Dispatch, FocusEvent, KeyboardEvent, SetStateAction, useContext, useRef, useState } from 'react'; import { FaSignInAlt } from 'react-icons/fa'; import { IoIosArrowBack } from 'react-icons/io'; import { useLocation, useNavigate } from 'react-router-dom'; @@ -12,12 +12,18 @@ import { AppCtx, refreshUserProfile, signOut } from '../../context/AppCtx'; import { ErrorKind, RefInputField, UserLogin } from '../../types'; import cleanLoginUrlParams from '../../utils/cleanLoginUrlParams'; import compoundErrorMessage from '../../utils/compoundErrorMessage'; +import getRetryAfterText from '../../utils/getRetryAfterText'; import InputField from '../common/InputField'; import Modal from '../common/Modal'; +import ApproveSessionForm from './ApproveSessionForm'; import styles from './LogIn.module.css'; import OAuth from './OAuth'; import ResetPassword from './ResetPassword'; +// Shown in the passcode step once too many incorrect codes have been entered +const TOO_MANY_CODES_HINT = + 'If you didn\'t make these attempts, someone may know your password: go back and use "Forgot password?" to reset it to a new password. That signs out every other session and stops them; then finish signing in with a recovery code, or with a code from your app once the wait is over.'; + interface FormValidation { isValid: boolean; user: null | UserLogin; @@ -48,20 +54,27 @@ const LogIn = (props: Props) => { const [apiError, setApiError] = useState(null); const [email, setEmail] = useState(''); const [visibleResetPassword, setVisibleResetPassword] = useState(false); - const [passcode, setPasscode] = useState(''); - const [isApprovingSession, setIsApprovingSession] = useState(false); - - const onPasscodeChange = (e: ChangeEvent) => { - setPasscode(e.target.value); - }; - // Clean API error when form is focused after validation const cleanApiError = () => { if (!isNull(apiError)) { setApiError(null); } }; + // Clean API error when one of the form's fields is focused. Focusing a + // button must not clean it: removing the alert moves the form, and the click + // that focused the button could be lost + const onFormFocus = (e: FocusEvent) => { + if (e.target instanceof HTMLInputElement) { + cleanApiError(); + } + }; + + const openResetPassword = () => { + cleanApiError(); + setVisibleResetPassword(true); + }; + const onEmailChange = (e: ChangeEvent) => { setEmail(e.target.value); }; @@ -87,15 +100,19 @@ const LogIn = (props: Props) => { let error = compoundErrorMessage(err, 'An error occurred signing in'); if (err.kind === ErrorKind.Unauthorized) { error = 'Authentication failed. Please check your credentials.'; + } else if (err.kind === ErrorKind.TooManyAttempts) { + error = `Too many sign-in attempts for this account. Please try again in ${getRetryAfterText( + err.retryAfter + )}, or use "Forgot password?" to reset your password and sign in.`; + } else if (err.kind === ErrorKind.TooManyRequests) { + error = `Too many requests. Please try again in ${getRetryAfterText(err.retryAfter)}.`; } setApiError(error); setIsLoading({ status: false }); - setIsApprovingSession(false); dispatch(signOut()); }; const onLoginSuccess = () => { - setIsApprovingSession(false); setIsLoading({ status: false }); dispatch(refreshUserProfile(dispatch, props.redirect)); props.setOpenLogIn(false); @@ -108,6 +125,7 @@ const LogIn = (props: Props) => { // eslint-disable-next-line @typescript-eslint/no-explicit-any } catch (err: any) { if (err.kind === ErrorKind.NotApprovedSession) { + setIsLoading({ status: false }); setVisible2FACode(true); } else { onLoginError(err); @@ -115,18 +133,10 @@ const LogIn = (props: Props) => { } } - async function approveSession() { - try { - setIsApprovingSession(true); - await API.approveSession(passcode); - onLoginSuccess(); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - } catch (err: any) { - onLoginError(err); - } - } - const submitForm = () => { + // Each request uses one of the sign-in attempts allowed for the account, + // so only one is sent at a time + if (isLoading.status) return; cleanApiError(); setIsLoading({ type: 'log', status: true }); if (loginForm.current) { @@ -165,7 +175,7 @@ const LogIn = (props: Props) => { }; const handleOnReturnKeyDown = (event: KeyboardEvent): void => { - if (event.key === 'Enter' && !isNull(loginForm)) { + if (event.key === 'Enter' && !event.repeat && !isNull(loginForm)) { submitForm(); } }; @@ -217,39 +227,12 @@ const LogIn = (props: Props) => {
-
-
- - - -
-
+
) : (
@@ -257,7 +240,7 @@ const LogIn = (props: Props) => { ref={loginForm} data-testid="loginForm" className={classnames('w-100', { 'needs-validation': !isValidated }, { 'was-validated': isValidated })} - onFocus={cleanApiError} + onFocus={onFormFocus} autoComplete="on" noValidate > @@ -297,7 +280,7 @@ const LogIn = (props: Props) => {
) : ( { + for (let i = 0; i < tests.length; i++) { + it('returns correct text', () => { + const actual = getRetryAfterText(tests[i].input); + expect(actual).toEqual(tests[i].output); + }); + } +}); diff --git a/web/src/utils/getRetryAfterText.ts b/web/src/utils/getRetryAfterText.ts new file mode 100644 index 0000000000..0c54a97947 --- /dev/null +++ b/web/src/utils/getRetryAfterText.ts @@ -0,0 +1,16 @@ +import isUndefined from 'lodash/isUndefined'; + +// Returns how long to wait before retrying, given the seconds provided in the +// Retry-After header of a 429 response (undefined when it was not available) +const getRetryAfterText = (seconds?: number): string => { + if (isUndefined(seconds)) return 'a little while'; + if (seconds <= 5) return 'a moment'; + if (seconds <= 60) return 'a minute'; + if (seconds < 5400) { + const minutes = Math.ceil(seconds / 60); + return minutes === 60 ? 'an hour' : `${minutes} minutes`; + } + return `${Math.ceil(seconds / 3600)} hours`; +}; + +export default getRetryAfterText; diff --git a/web/src/utils/isInvalidPasscodeError.test.ts b/web/src/utils/isInvalidPasscodeError.test.ts new file mode 100644 index 0000000000..ae56feb3cc --- /dev/null +++ b/web/src/utils/isInvalidPasscodeError.test.ts @@ -0,0 +1,24 @@ +import { Error, ErrorKind } from '../types'; +import isInvalidPasscodeError from './isInvalidPasscodeError'; + +interface Test { + input: Error; + output: boolean; +} + +const tests: Test[] = [ + { input: { kind: ErrorKind.Other, message: 'invalid input: invalid passcode' }, output: true }, + { input: { kind: ErrorKind.Other, message: 'invalid input: passcode not provided' }, output: false }, + { input: { kind: ErrorKind.Other }, output: false }, + { input: { kind: ErrorKind.Unauthorized, message: 'invalid input: invalid passcode' }, output: false }, + { input: { kind: ErrorKind.TooManyAttempts, message: 'too many attempts, please try again later' }, output: false }, +]; + +describe('isInvalidPasscodeError', () => { + for (let i = 0; i < tests.length; i++) { + it('returns correct value', () => { + const actual = isInvalidPasscodeError(tests[i].input); + expect(actual).toEqual(tests[i].output); + }); + } +}); diff --git a/web/src/utils/isInvalidPasscodeError.ts b/web/src/utils/isInvalidPasscodeError.ts new file mode 100644 index 0000000000..d12c38a4a8 --- /dev/null +++ b/web/src/utils/isInvalidPasscodeError.ts @@ -0,0 +1,12 @@ +import { Error, ErrorKind } from '../types'; + +// Message the hub sends when the two-factor authentication code provided is +// not valid (errInvalidTFAPasscode in internal/user/manager.go) +const INVALID_PASSCODE_MESSAGE = 'invalid input: invalid passcode'; + +// Checks if the error provided means that the two-factor authentication code +// sent (from an authenticator app or a recovery code) was not valid +const isInvalidPasscodeError = (err: Error): boolean => + err.kind === ErrorKind.Other && err.message === INVALID_PASSCODE_MESSAGE; + +export default isInvalidPasscodeError;