Add password reset by emailed single-use link #215

Merged
rob merged 5 commits from password-reset into main 2026-11-21 15:02:59 +00:00
Collaborator

Lets a local-password user who forgot their password get a reset link by email. Vikunja task 584. ADR-0174 supersedes ADR-0094 and lifts the v1 email exclusion for password recovery only.

Behaviour:

  • POST /api/auth/password-reset/request answers 202 for every address. Only an account with a local password gets a mail. OIDC-only accounts get the same 202 and nothing.
  • The link carries a 256-bit token. Only its SHA-256 is stored, with a 30-minute expiry.
  • POST /api/auth/password-reset/confirm redeems the token once, sets the password, voids the account's other reset tokens and revokes its refresh tokens, in one transaction. Bad, used and expired tokens all give the same 400.
  • Both routes sit under the existing auth rate limiter.
  • New pages /forgot-password and /reset-password. The sign-in page links to the first instead of the ADR-0094 sentence.

Config and rollout:

  • New keys Smtp:Host, Smtp:Port, Smtp:Username, Smtp:Password, Smtp:FromAddress, WebUi:BaseUrl (README). With Smtp:Host set, the from address and base URL are required. With none, nothing is sent: Development logs the mail, elsewhere only a warning with no token.
  • Migration 0006-password-reset-tokens.sql. SchemaVersionHealthCheck.RequiredScript now names it, so run the schema upgrade before deploying or readiness reports unhealthy.
  • MailKit added to Infrastructure. It pulls a vulnerable System.Security.Cryptography.Pkcs 10.0.0, so that is pinned to 10.0.13 with a comment.

Tests are in Api.Tests (flow over HTTP with a capturing mail sender), Infrastructure.Tests (SQL, log sender, schema) and WebUI.Tests (pages).

Lets a local-password user who forgot their password get a reset link by email. Vikunja task 584. ADR-0174 supersedes ADR-0094 and lifts the v1 email exclusion for password recovery only. Behaviour: - `POST /api/auth/password-reset/request` answers 202 for every address. Only an account with a local password gets a mail. OIDC-only accounts get the same 202 and nothing. - The link carries a 256-bit token. Only its SHA-256 is stored, with a 30-minute expiry. - `POST /api/auth/password-reset/confirm` redeems the token once, sets the password, voids the account's other reset tokens and revokes its refresh tokens, in one transaction. Bad, used and expired tokens all give the same 400. - Both routes sit under the existing auth rate limiter. - New pages `/forgot-password` and `/reset-password`. The sign-in page links to the first instead of the ADR-0094 sentence. Config and rollout: - New keys `Smtp:Host`, `Smtp:Port`, `Smtp:Username`, `Smtp:Password`, `Smtp:FromAddress`, `WebUi:BaseUrl` (README). With `Smtp:Host` set, the from address and base URL are required. With none, nothing is sent: Development logs the mail, elsewhere only a warning with no token. - Migration `0006-password-reset-tokens.sql`. `SchemaVersionHealthCheck.RequiredScript` now names it, so run the schema upgrade before deploying or readiness reports unhealthy. - MailKit added to Infrastructure. It pulls a vulnerable `System.Security.Cryptography.Pkcs` 10.0.0, so that is pinned to 10.0.13 with a comment. Tests are in Api.Tests (flow over HTTP with a capturing mail sender), Infrastructure.Tests (SQL, log sender, schema) and WebUI.Tests (pages).
Add password reset by emailed single-use link
Some checks failed
CI / build (pull_request) Failing after 3m50s
CI / e2e (pull_request) Has been skipped
CI / container-images (pull_request) Has been skipped
dc925aeebb
Claude left a comment

Verdict: changes needed

Two tests cannot fail on the behaviour they guard (see inline). One low-risk hardening item is also worth deciding on. Design, SQL and transaction look sound.

  1. PostRequest_TheRelayFails_StillAnswers202 passes with the catch in SendResetMailAsync deleted: the faulted task is discarded, so the response is still 202. Assert the warning is logged (or that the task's fault is observed), otherwise it guards nothing.
  2. Nothing tests that AddPlaceMarkPasswordReset passes environment.IsDevelopment() to LogEmailSender. Flip it to true and every test stays green while production logs the reset link. Add a test that builds the provider with a non-Development environment and no Smtp:Host, sends, and asserts the token is absent from the log. The same file's startup throw (Smtp:Host set without FromAddress or WebUi:BaseUrl) is also untested.
  3. Request is limited per IP only. Each call for a known address inserts a row and sends a mail, so one address can be mail-bombed from a few IPs. Consider skipping the insert and send when that user already has an unused token created in the last minute. The 202 stays the same.
  4. Low: changing the password or email (ADR-0056 paths) does not void outstanding reset tokens, so a link mailed before the change stays valid for up to 30 minutes. Decide whether that is accepted; the ADR is silent.
  5. Minor: SmtpEmailSender does options.Password!, so a Username with no Password throws a NullReferenceException on every send, swallowed as a warning. Validate at startup alongside the FromAddress check.
  6. Minor: "30 minutes" is hard-coded in the mail body and in ForgotPassword.razor while PasswordResetTokenRepository.Lifetime exists. They can drift.
Verdict: changes needed Two tests cannot fail on the behaviour they guard (see inline). One low-risk hardening item is also worth deciding on. Design, SQL and transaction look sound. 1. `PostRequest_TheRelayFails_StillAnswers202` passes with the `catch` in `SendResetMailAsync` deleted: the faulted task is discarded, so the response is still 202. Assert the warning is logged (or that the task's fault is observed), otherwise it guards nothing. 2. Nothing tests that `AddPlaceMarkPasswordReset` passes `environment.IsDevelopment()` to `LogEmailSender`. Flip it to `true` and every test stays green while production logs the reset link. Add a test that builds the provider with a non-Development environment and no `Smtp:Host`, sends, and asserts the token is absent from the log. The same file's startup throw (Smtp:Host set without FromAddress or WebUi:BaseUrl) is also untested. 3. Request is limited per IP only. Each call for a known address inserts a row and sends a mail, so one address can be mail-bombed from a few IPs. Consider skipping the insert and send when that user already has an unused token created in the last minute. The 202 stays the same. 4. Low: changing the password or email (ADR-0056 paths) does not void outstanding reset tokens, so a link mailed before the change stays valid for up to 30 minutes. Decide whether that is accepted; the ADR is silent. 5. Minor: `SmtpEmailSender` does `options.Password!`, so a Username with no Password throws a NullReferenceException on every send, swallowed as a warning. Validate at startup alongside the FromAddress check. 6. Minor: "30 minutes" is hard-coded in the mail body and in ForgotPassword.razor while `PasswordResetTokenRepository.Lifetime` exists. They can drift.
@ -0,0 +38,4 @@
}
var (token, tokenHash) = RefreshTokenGenerator.Generate();
await resetTokens.CreateAsync(user.Id, tokenHash, timeProvider.GetUtcNow().UtcDateTime, cancellationToken);
Author
Collaborator

No per-account throttle: each request for a known address inserts a row and sends a mail. Skip both if an unused token under a minute old exists; same 202.

No per-account throttle: each request for a known address inserts a row and sends a mail. Skip both if an unused token under a minute old exists; same 202.
@ -0,0 +22,4 @@
if (string.IsNullOrWhiteSpace(smtp?.Host))
{
return services.AddSingleton<IEmailSender>(provider =>
new LogEmailSender(provider.GetRequiredService<ILogger<LogEmailSender>>(), environment.IsDevelopment()));
Author
Collaborator

Untested: set this to true and the whole suite stays green while Production logs the token. Needs a wiring test with a non-Development environment.

Untested: set this to true and the whole suite stays green while Production logs the token. Needs a wiring test with a non-Development environment.
@ -0,0 +112,4 @@
}
[Fact]
public async Task PostRequest_TheRelayFails_StillAnswers202()
Author
Collaborator

Passes with the catch in SendResetMailAsync removed (exception lands in the discarded task). Assert the LogResetMailFailed warning instead.

Passes with the catch in SendResetMailAsync removed (exception lands in the discarded task). Assert the LogResetMailFailed warning instead.
Throttle reset mail, test its wiring and relay failure
Some checks failed
CI / build (pull_request) Failing after 5m0s
CI / e2e (pull_request) Has been skipped
CI / container-images (pull_request) Has been skipped
c009016784
Claude left a comment

Verdict: mergeable

All six round-one findings are addressed. Nothing new to act on.

Verdict: mergeable All six round-one findings are addressed. Nothing new to act on.
Merge remote-tracking branch 'origin/main' into password-reset
Some checks failed
CI / build (pull_request) Failing after 7m55s
CI / e2e (pull_request) Has been skipped
CI / container-images (pull_request) Has been skipped
86f9f1b6e5
Claude left a comment

Verdict: mergeable

The merge of main added only #216's changes, so the diff against main is what review 877 approved. Nothing to act on.

Verdict: mergeable The merge of `main` added only #216's changes, so the diff against `main` is what review 877 approved. Nothing to act on.
Test SmtpEmailSender against a real Mailpit relay
Some checks failed
CI / build (pull_request) Has been cancelled
CI / e2e (pull_request) Has been cancelled
CI / container-images (pull_request) Has been cancelled
dc03836e15
Claude left a comment

Verdict: changes needed

One finding. The authenticated: true case cannot fail if authentication is broken.

MP_SMTP_AUTH_ACCEPT_ANY=1 makes auth optional, so Mailpit accepts the message whether or not AuthenticateAsync runs, and with any credentials. Delete the if (!string.IsNullOrEmpty(options.Username)) block in SmtpEmailSender and both theory rows stay green. That case only covers the lines.

Fix: start Mailpit with MP_SMTP_AUTH=relay-user:relay-password instead of ACCEPT_ANY. Keep MP_SMTP_AUTH_ALLOW_INSECURE=1. Mailpit then rejects unauthenticated and wrong-credential sends. The false row would fail against the same fixture, so give it its own assertion (ShouldThrow on the send) or a second Mailpit without auth. Then mutate the auth block and confirm the true row goes red.

Port mapping, readiness and recipient uniqueness look fine.

Verdict: changes needed One finding. The `authenticated: true` case cannot fail if authentication is broken. `MP_SMTP_AUTH_ACCEPT_ANY=1` makes auth optional, so Mailpit accepts the message whether or not `AuthenticateAsync` runs, and with any credentials. Delete the `if (!string.IsNullOrEmpty(options.Username))` block in `SmtpEmailSender` and both theory rows stay green. That case only covers the lines. Fix: start Mailpit with `MP_SMTP_AUTH=relay-user:relay-password` instead of `ACCEPT_ANY`. Keep `MP_SMTP_AUTH_ALLOW_INSECURE=1`. Mailpit then rejects unauthenticated and wrong-credential sends. The `false` row would fail against the same fixture, so give it its own assertion (`ShouldThrow` on the send) or a second Mailpit without auth. Then mutate the auth block and confirm the `true` row goes red. Port mapping, readiness and recipient uniqueness look fine.
Make the Mailpit relay require credentials in the SMTP test
All checks were successful
CI / build (pull_request) Successful in 8m24s
CI / container-images (pull_request) Successful in 2s
CI / e2e (pull_request) Successful in 5m50s
c0ab7b338f
Claude left a comment

Verdict: mergeable

Optional: SendAsync_WithTheWrongPassword_IsRefusedByTheRelay uses Should.ThrowAsync<Exception>, so it also passes on a connection failure or a bad address. Assert MailKit.Security.AuthenticationException so it only passes for a refused login. The delivery fact already guards the happy path, so this isn't blocking.

Verdict: mergeable Optional: `SendAsync_WithTheWrongPassword_IsRefusedByTheRelay` uses `Should.ThrowAsync<Exception>`, so it also passes on a connection failure or a bad address. Assert `MailKit.Security.AuthenticationException` so it only passes for a refused login. The delivery fact already guards the happy path, so this isn't blocking.
rob merged commit 7093f2546a into main 2026-11-21 15:02:59 +00:00
rob deleted branch password-reset 2026-11-21 15:02:59 +00:00
Sign in to join this conversation.
No reviewers
No labels
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
rob/PlaceMark!215
No description provided.