Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions database/migrations/functions/001_load_functions.sql
Original file line number Diff line number Diff line change
Expand Up @@ -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" }}
Expand Down
35 changes: 29 additions & 6 deletions database/migrations/functions/users/approve_session.sql
Original file line number Diff line number Diff line change
@@ -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;
11 changes: 11 additions & 0 deletions database/migrations/functions/users/refund_auth_attempt.sql
Original file line number Diff line number Diff line change
@@ -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;
43 changes: 43 additions & 0 deletions database/migrations/functions/users/register_auth_attempt.sql
Original file line number Diff line number Diff line change
@@ -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;
Original file line number Diff line number Diff line change
@@ -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;
Original file line number Diff line number Diff line change
@@ -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;
12 changes: 9 additions & 3 deletions database/migrations/functions/users/reset_user_password.sql
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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;
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Expand Down
19 changes: 19 additions & 0 deletions database/migrations/schema/067_auth_attempt_limit.sql
Original file line number Diff line number Diff line change
@@ -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;
75 changes: 74 additions & 1 deletion database/tests/functions/users/approve_session.sql
Original file line number Diff line number Diff line change
@@ -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', '');
Expand All @@ -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();
Expand Down
53 changes: 53 additions & 0 deletions database/tests/functions/users/refund_auth_attempt.sql
Original file line number Diff line number Diff line change
@@ -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;
Loading
Loading