Skip to content

Commit 7a14d3f

Browse files
authored
feat(auth): try the mail of a code again after it failed (#499)
2 parents 246a7a8 + 884b42d commit 7a14d3f

17 files changed

Lines changed: 819 additions & 18 deletions

File tree

‎docs/client-guide.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ A server can require that a new account confirms its email. Then registration an
1919
1. Show a screen for the code. Keep the code as text, because it can start with 0.
2020
2. Send it to `POST /api/v1/auth/verify-email` with the email and the password, and the `deviceToken` that registration returned. A right code answers like a login, with the tokens, and the person is signed in.
2121
3. A wrong code answers `400` with `VERIFICATION_CODE_INVALID`, and so does an expired code or a code that took 5 wrong tries. The answer is the same for all of them.
22-
4. For a new code, send the email and the password to `POST /api/v1/auth/resend-verification`. Wait `resendAfterSeconds` between two requests. A request before that answers `429` with `VERIFICATION_RESEND_TOO_SOON` and `Retry-After`, which is longer than a minute when the 5 codes of the hour are used up. Count down from the header and do not assume 60 seconds. An account that was sent all the codes that it may have answers `429` with `VERIFICATION_CODE_LIMIT_REACHED` and no `Retry-After`. Tell the person to register again later, because a registration with the same email replaces an account that waited more than a day and never signed in. An account that did sign in, while the verification was off, has no such cap and never gets this answer.
22+
4. For a new code, send the email and the password to `POST /api/v1/auth/resend-verification`. Wait `resendAfterSeconds` between two requests. A request before that answers `429` with `VERIFICATION_RESEND_TOO_SOON` and `Retry-After`, which is longer than a minute when the 5 codes of the hour are used up. Count down from the header and do not assume 60 seconds. An account that was sent all the codes that it may have answers `429` with `VERIFICATION_CODE_LIMIT_REACHED` and no `Retry-After`. Tell the person to register again later, because a registration with the same email replaces an account that waited more than a day and never signed in. An account that did sign in, while the verification was off, has no such cap and never gets this answer. A mail that failed is tried again on its own a few times, so a new code can arrive without a request, and it replaces the earlier one.
2323
5. When `verification.sent` is `false`, the account exists but the mail did not go out. A code that was not mailed gives its wait back, so the resend button works at once. A resend whose mail fails answers `503` with `EMAIL_SEND_FAILED`.
2424

2525
Signing in with the right password before the code is verified answers `403` with `EMAIL_NOT_VERIFIED`. Send the person to the same screen and ask for a new code if the old one is gone. Accounts that were registered before the server turned the check on are verified and sign in as before.

‎docs/data-model.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ PostgreSQL is the only authority for the data of Kibooz. The schema is built by
2525
| `chat_reads` | How far each person of a conversation has read, the id of the last message |
2626
| `notifications` | One entry of the inbox of a teacher or a parent, with a `kind`, a title, a text, an optional reference to the record that caused it (`reference_type` and `reference_id`), the time it was read and the time it was made. A notification is removed 90 days after it was made, and with the account when the account is deleted |
2727
| `refresh_tokens` | A refresh token of a session, stored only as a SHA-256 hash |
28-
| `email_verifications` | The one live code of an account that waits for its email, stored as a keyed hash, with the time it expires, the wrong tries so far, the time of the last send, the sends of the current hour and the number of codes that were sent in all. The row is removed with the account, and when the code is used |
28+
| `email_verifications` | The one live code of an account that waits for its email, stored as a keyed hash, with the time it expires, the wrong tries so far, the time of the last send, the sends of the current hour, the number of codes that were sent in all, and when the mail of the code is tried again after it failed. The row is removed with the account, and when the code is used |
2929
| `leaderboard_seasons` | One row for every semester that has begun |
3030
| `class_seasons` | The label of the semester that the points of a class belong to, so the reset of a new semester can go one class at a time and continue where an instance stopped. A trigger on `classes` adds the row |
3131
| `leaderboard_history` | The final standings of a class for a semester that ended, one row for each class, child and semester (unique key `leaderboard_history_unique`), so a second save of the same semester is skipped and not stored again |

‎docs/operations.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@ With `EMAIL_VERIFICATION_REQUIRED=true` a new account is created without a sessi
7272
- **Switching it off again.** The accounts that wait can sign in at once, without a code, and they stay marked as waiting. Switching it on again locks them out until they verify, and the ones that signed in meanwhile have to ask for a code. An account that signed in meanwhile is never replaced or removed for waiting. One that did not sign in and has waited longer than the limits can be replaced or removed as soon as the setting is on again. The unused codes stay in `email_verifications` until the account is deleted.
7373
- **During a rolling update.** A copy that has not been updated yet lets a waiting account sign in with its password only, and registers new accounts with a session, until the last copy runs the new version. A sign in on such a copy leaves no mark that protects the account from removal, so do not change `EMAIL_VERIFICATION_REQUIRED` during the update. The upgrade marks every account that waits at that moment, and none of them is ever removed for waiting.
7474
- **Accounts that never verify.** They hold their email, NIP and the seat of the child in the class. They do not show as contacts of the chat and cannot be added as teachers. After one day a new registration with their email or NIP replaces them, when nothing else of that registration is taken and the class of a parent takes the child, and after 7 days an hourly job removes them with the same deletion as the one of an account, which is the job `pending_account_purge`. Neither touches an account that ever signed in. Both only work while `EMAIL_VERIFICATION_REQUIRED` is on, because the accounts that wait can sign in when it is off.
75+
- **A mail that fails is tried again.** When Resend does not take the code, the account keeps its row and a job (`verification_mail_retry`, every minute) mails a new code after 1, 5 and 15 minutes and then every hour, 6 times in all, which is about 3 and a half hours. After that the person asks for a new code. A mail that goes out starts the count again. Every try is a new code that replaces the earlier one, and a code that was not taken is not counted for the cap. A mail that Resend does not answer in time counts as not taken although it may arrive, so one account can get up to 7 mails. There is no daily limit on the retries of all accounts together, so they share the quota of the plan with the first mails. When Resend answers 429 and names a quota, the job stops for an hour, and for any other 429 it stops the run it is in. A missing `RESEND_API_KEY` is never retried. The job only runs while `EMAIL_VERIFICATION_REQUIRED` is on. During a rolling update a code that an older copy mails does not end a retry that a newer copy planned, so one more mail may follow.
7576
- **Protect the registration.** Registration mails every new address once, so a flood of new addresses can use the quota of the mail service. Put the same limit in the proxy on `register`, `verify-email` and `resend-verification` as on login, see [Design](design.md).
7677
- **Limits that protect the quota.** A code works 15 minutes and takes 5 wrong tries. One account can have a code sent every 60 seconds and 5 times in an hour. A new code needs the password of the account. `EMAIL_CODES_MAX_PER_ACCOUNT` (20 by default) is the most codes that one account is ever sent, and a code that the mail service did not take is not counted. An account that used them all gets `429 VERIFICATION_CODE_LIMIT_REACHED` for a new code and is replaced or removed later. The cap does not apply to an account that signed in while the verification was off. Such an account is never removed for waiting, so it can always ask for another code, within the other limits.
7778
- **Quota of the mail service.** The Resend plan has a daily and a monthly cap that every key of the account shares. When a send fails, registration still succeeds and its answer says `verification.sent: false`, and the app shows the resend button. Watch `kibooz_verification_emails_total{result="failed"}`.
@@ -110,7 +111,7 @@ The API counts what it does and shows it in the Prometheus text format. The page
110111
| `kibooz_notifications_emitted_total` | `result` | Inserts of in-app notifications after an event, by `stored` or `failed`. A notification is best effort. A failed insert is logged, counted here and sent to the error reports, and the action that caused it still succeeds, so the inbox can miss an entry. A batch of mood logs is one insert |
111112
| `kibooz_verification_emails_total` | `result` | Verification codes that were handed to the mail service, by `sent` or `failed`. A failed send is logged, counted here and sent to the error reports, and the account keeps its code and can ask for a new one. A rise of `failed` is the first sign that the Resend quota or the service is out |
112113
| `kibooz_password_hash_busy_total` | none | Requests that got `429 RATE_LIMITED` because every password hashing slot was taken, which means the server needs more CPU or a higher `PASSWORD_HASH_CONCURRENCY` |
113-
| `kibooz_job_runs_total` | `job`, `result` | Runs of a background job, with `result` `success` or `failure`. The jobs are `semester_check`, `file_cleanup`, `idempotency_purge`, `refresh_token_purge`, `notification_purge`, `pending_account_purge`, `keepalive_database` and `keepalive_redis` |
114+
| `kibooz_job_runs_total` | `job`, `result` | Runs of a background job, with `result` `success` or `failure`. The jobs are `semester_check`, `file_cleanup`, `idempotency_purge`, `refresh_token_purge`, `notification_purge`, `pending_account_purge`, `verification_mail_retry`, `keepalive_database` and `keepalive_redis`. The two jobs about pending accounts and their mail run only while the verification of the email is required |
114115
| `kibooz_job_last_success_timestamp_seconds` | `job` | Unix time of the last successful run, or of the moment the job started when it has not succeeded yet, so an alert can fire when a job has not succeeded for too long. A job that is switched off, such as the file cleanup without a bucket or the keepalive with `KEEPALIVE_SECONDS=0`, has no series |
115116
| `go_sql_*` | `db_name` | The connection pool of the database, such as open, idle and waited-for connections |
116117
| `go_*`, `process_*` | none | The Go runtime and the process, such as memory, goroutines and open files |
Lines changed: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,181 @@
1+
// Package mailretry sends the verification code again to the accounts whose mail failed
2+
package mailretry
3+
4+
import (
5+
"context"
6+
"errors"
7+
"fmt"
8+
"log"
9+
"sync"
10+
"time"
11+
12+
"github.com/google/uuid"
13+
14+
"github.com/SyafaHadyan/kibooz-backend/internal/mailer"
15+
)
16+
17+
const (
18+
// Interval is how often the job looks for a mail that is due, which is short because the first retries come after a minute
19+
Interval = time.Minute
20+
21+
// startDelay is how long after the start the first run happens
22+
startDelay = 20 * time.Second
23+
24+
// batch is how many accounts one run takes. One mail may take the 5 seconds of its timeout, so a run stays well inside the lease.
25+
batch = 10
26+
27+
// lease is how long a claimed account is left alone, so a copy that dies in the middle of a run does not lose the retry and a
28+
// second copy does not mail the same account at the same time
29+
lease = 5 * time.Minute
30+
31+
// retryTimeout bounds one account. It is shorter than the cooldown of a resend, so a retry that stalls cannot mail a code
32+
// after the person got another one
33+
retryTimeout = 30 * time.Second
34+
35+
// quotaPause is how long the job stops after the mail service refused for its quota
36+
quotaPause = time.Hour
37+
)
38+
39+
// Source claims the accounts whose mail is due
40+
type Source interface {
41+
ClaimMailRetries(ctx context.Context, now time.Time, lease time.Duration, limit int) ([]uuid.UUID, error)
42+
}
43+
44+
// Retrier mails a new code to one account
45+
type Retrier func(ctx context.Context, userID uuid.UUID) error
46+
47+
// Job tries the mail of the accounts that wait for a code again, after 1, 5 and 15 minutes and then every hour, a few times in all.
48+
// It must only run while the verification is required.
49+
type Job struct {
50+
source Source
51+
retry Retrier
52+
observe func(error)
53+
now func() time.Time
54+
55+
// startAfter is how long after the start the first run happens, a field for the tests
56+
startAfter time.Duration
57+
58+
mu sync.Mutex
59+
pausedUntil time.Time
60+
}
61+
62+
func NewJob(source Source, retry Retrier) *Job {
63+
return &Job{source: source, retry: retry, now: time.Now, startAfter: startDelay}
64+
}
65+
66+
// Observe sets the function that gets the result of every run, nil for a run that went well, and returns the job
67+
func (j *Job) Observe(observe func(error)) *Job {
68+
j.observe = observe
69+
70+
return j
71+
}
72+
73+
// Run takes the accounts that are due and mails each of them. It returns how many it tried. A quota answer stops the run and the job
74+
// for an hour, and an answer about the rate stops the run. Any other failure of one account does not stop the others, and the run
75+
// returns those errors.
76+
func (j *Job) Run(ctx context.Context) (int, error) {
77+
j.mu.Lock()
78+
paused := j.now().Before(j.pausedUntil)
79+
j.mu.Unlock()
80+
81+
if paused {
82+
return 0, nil
83+
}
84+
85+
ids, err := j.source.ClaimMailRetries(ctx, j.now(), lease, batch)
86+
if err != nil {
87+
return 0, err
88+
}
89+
90+
tried := 0
91+
92+
var failures []error
93+
94+
for _, id := range ids {
95+
if ctx.Err() != nil {
96+
return tried, ctx.Err()
97+
}
98+
99+
tried++
100+
101+
err = j.one(ctx, id)
102+
if errors.Is(err, mailer.ErrRateLimit) {
103+
log.Printf("the mail service refused for its rate, the rest of the verification mail retries wait for their lease")
104+
105+
break
106+
}
107+
108+
if errors.Is(err, mailer.ErrQuota) {
109+
j.mu.Lock()
110+
j.pausedUntil = j.now().Add(quotaPause)
111+
j.mu.Unlock()
112+
113+
log.Printf("the mail service refused for its quota, the verification mail retries stop for %s", quotaPause)
114+
115+
break
116+
}
117+
118+
if err != nil {
119+
failures = append(failures, fmt.Errorf("account %s: %w", id, err))
120+
}
121+
}
122+
123+
return tried, errors.Join(failures...)
124+
}
125+
126+
// one tries one account. A send that is under way is not cut off by a stop of the job, which would count a mail that may have
127+
// been delivered as failed.
128+
func (j *Job) one(ctx context.Context, id uuid.UUID) error {
129+
retryCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), retryTimeout)
130+
defer cancel()
131+
132+
return j.retry(retryCtx, id)
133+
}
134+
135+
// run is one run with its report to the observer and the log
136+
func (j *Job) run(ctx context.Context) {
137+
tried, err := j.Run(ctx)
138+
if j.observe != nil && ctx.Err() == nil {
139+
j.observe(err)
140+
}
141+
142+
if err != nil && !errors.Is(err, context.Canceled) {
143+
log.Printf("verification mail retry run failed %v", err)
144+
}
145+
146+
if tried > 0 {
147+
log.Printf("verification mail retry tried %d accounts", tried)
148+
}
149+
}
150+
151+
// Start runs once per interval until the returned stop function is called, which waits for a run that is under way.
152+
// A zero or negative interval disables it.
153+
func (j *Job) Start(interval time.Duration) (stop func()) {
154+
if interval <= 0 {
155+
return func() {}
156+
}
157+
158+
ctx, cancel := context.WithCancel(context.Background())
159+
160+
var wg sync.WaitGroup
161+
162+
wg.Go(func() {
163+
timer := time.NewTimer(min(interval, j.startAfter))
164+
defer timer.Stop()
165+
166+
for {
167+
select {
168+
case <-ctx.Done():
169+
return
170+
case <-timer.C:
171+
j.run(ctx)
172+
timer.Reset(interval)
173+
}
174+
}
175+
})
176+
177+
return func() {
178+
cancel()
179+
wg.Wait()
180+
}
181+
}
Lines changed: 162 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,162 @@
1+
package mailretry_test
2+
3+
import (
4+
"context"
5+
"errors"
6+
"fmt"
7+
"testing"
8+
"time"
9+
10+
"github.com/google/uuid"
11+
"github.com/stretchr/testify/require"
12+
13+
"github.com/SyafaHadyan/kibooz-backend/internal/app/auth/mailretry"
14+
"github.com/SyafaHadyan/kibooz-backend/internal/mailer"
15+
)
16+
17+
type source struct {
18+
ids []uuid.UUID
19+
err error
20+
calls int
21+
limit int
22+
lease time.Duration
23+
}
24+
25+
func (s *source) ClaimMailRetries(_ context.Context, _ time.Time, lease time.Duration, limit int) ([]uuid.UUID, error) {
26+
s.calls++
27+
s.limit, s.lease = limit, lease
28+
29+
return s.ids, s.err
30+
}
31+
32+
func ids(n int) []uuid.UUID {
33+
list := make([]uuid.UUID, n)
34+
for i := range list {
35+
list[i] = uuid.New()
36+
}
37+
38+
return list
39+
}
40+
41+
func TestRunMailsEveryAccountThatIsDue(t *testing.T) {
42+
src := &source{ids: ids(3)}
43+
44+
var tried []uuid.UUID
45+
46+
job := mailretry.NewJob(src, func(_ context.Context, id uuid.UUID) error {
47+
tried = append(tried, id)
48+
49+
return nil
50+
})
51+
52+
count, err := job.Run(context.Background())
53+
require.NoError(t, err)
54+
require.Equal(t, 3, count)
55+
require.Equal(t, src.ids, tried)
56+
require.Positive(t, src.limit)
57+
require.Greater(t, src.lease, time.Minute, "the lease is longer than the run")
58+
}
59+
60+
func TestAFailureOfOneAccountDoesNotStopTheOthers(t *testing.T) {
61+
src := &source{ids: ids(3)}
62+
calls := 0
63+
64+
job := mailretry.NewJob(src, func(context.Context, uuid.UUID) error {
65+
calls++
66+
if calls == 1 {
67+
return errors.New("database is down")
68+
}
69+
70+
return nil
71+
})
72+
73+
count, err := job.Run(context.Background())
74+
require.ErrorContains(t, err, "database is down")
75+
require.Equal(t, 3, count)
76+
}
77+
78+
func TestAQuotaAnswerStopsTheRunAndThenTheJobForAWhile(t *testing.T) {
79+
src := &source{ids: ids(3)}
80+
calls := 0
81+
82+
job := mailretry.NewJob(src, func(context.Context, uuid.UUID) error {
83+
calls++
84+
85+
return fmt.Errorf("wrapped %w", mailer.ErrQuota)
86+
})
87+
88+
count, err := job.Run(context.Background())
89+
require.NoError(t, err)
90+
require.Equal(t, 1, count)
91+
require.Equal(t, 1, calls, "the accounts after the refused one are left for later")
92+
93+
// the next runs do not even look for accounts
94+
count, err = job.Run(context.Background())
95+
require.NoError(t, err)
96+
require.Zero(t, count)
97+
require.Equal(t, 1, src.calls)
98+
}
99+
100+
func TestARunReportsAFailedClaimAndStopsWithItsContext(t *testing.T) {
101+
_, err := mailretry.NewJob(&source{err: errors.New("database is down")}, nil).Run(context.Background())
102+
require.Error(t, err)
103+
104+
ctx, cancel := context.WithCancel(context.Background())
105+
cancel()
106+
107+
count, err := mailretry.NewJob(&source{ids: ids(2)}, func(context.Context, uuid.UUID) error { return nil }).Run(ctx)
108+
require.ErrorIs(t, err, context.Canceled)
109+
require.Zero(t, count)
110+
}
111+
112+
func TestStartRunsTheJobAndStopWaitsForIt(t *testing.T) {
113+
ran := make(chan struct{}, 1)
114+
observed := make(chan error, 1)
115+
116+
job := mailretry.NewJob(&source{ids: ids(1)}, func(context.Context, uuid.UUID) error {
117+
select {
118+
case ran <- struct{}{}:
119+
default:
120+
}
121+
122+
return nil
123+
}).Observe(func(err error) {
124+
select {
125+
case observed <- err:
126+
default:
127+
}
128+
})
129+
130+
stop := job.Start(10 * time.Millisecond)
131+
132+
select {
133+
case <-ran:
134+
case <-time.After(5 * time.Second):
135+
t.Fatal("the job did not run")
136+
}
137+
138+
require.NoError(t, <-observed)
139+
stop()
140+
141+
mailretry.NewJob(&source{}, nil).Start(0)()
142+
}
143+
144+
func TestAnAnswerAboutTheRateEndsTheRunAndNotTheJob(t *testing.T) {
145+
src := &source{ids: ids(3)}
146+
calls := 0
147+
148+
job := mailretry.NewJob(src, func(context.Context, uuid.UUID) error {
149+
calls++
150+
151+
return fmt.Errorf("wrapped %w", mailer.ErrRateLimit)
152+
})
153+
154+
for range 2 {
155+
count, err := job.Run(context.Background())
156+
require.NoError(t, err)
157+
require.Equal(t, 1, count)
158+
}
159+
160+
require.Equal(t, 2, calls)
161+
require.Equal(t, 2, src.calls, "the next run looks again")
162+
}

0 commit comments

Comments
 (0)