feat(identity): confirm registration email atomically
This commit is contained in:
1 parent
8e7ce8d71c
commit
fade4e76e4
75 files changed
+4188
-403
No files matched your search
@@ -0,0 +1,192 @@
|
||||
-- Bind the registration C1 to the registration whose pending credentials are
|
||||
-- held by its verification token. Older registration code omits this column;
|
||||
-- the insert trigger below fills it from the account row, which the
|
||||
-- registration transaction updates before it grants C1.
|
||||
-- +goose Up
|
||||
ALTER TABLE consent_records
|
||||
ADD COLUMN registration_version bigint;
|
||||
|
||||
-- Registration and re-registration delete the earlier registration C1 in
|
||||
-- the same transaction that advances users.registration_version. The new C1
|
||||
-- is granted after that update, so the current account version is the only
|
||||
-- version an existing registration C1 can belong to. Refuse to guess if a
|
||||
-- row predates the account's latest registration or its account is missing.
|
||||
-- +goose StatementBegin
|
||||
DO $$
|
||||
BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1
|
||||
FROM consent_records AS consent
|
||||
LEFT JOIN users AS account ON account.id = consent.subject_id
|
||||
WHERE consent.source = 'registration'
|
||||
AND consent.purpose = 'c1'
|
||||
AND (
|
||||
account.id IS NULL
|
||||
OR consent.granted_at < account.last_registered_at
|
||||
)
|
||||
) THEN
|
||||
RAISE EXCEPTION 'registration C1 cannot be tied to the current account registration';
|
||||
END IF;
|
||||
IF EXISTS (
|
||||
SELECT 1
|
||||
FROM consent_records
|
||||
WHERE source = 'registration' AND purpose = 'c1'
|
||||
GROUP BY subject_id
|
||||
HAVING count(*) FILTER (WHERE revoked_at IS NULL) > 1
|
||||
) THEN
|
||||
RAISE EXCEPTION 'account has more than one current registration C1';
|
||||
END IF;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
-- Consent records are append-only. Temporarily remove the update guard only
|
||||
-- for this one-time binding, then restore it with the new column protected.
|
||||
DROP TRIGGER consent_records_refuse_change ON consent_records;
|
||||
|
||||
UPDATE consent_records AS consent
|
||||
SET registration_version = account.registration_version
|
||||
FROM users AS account
|
||||
WHERE
|
||||
consent.subject_id = account.id
|
||||
AND consent.source = 'registration'
|
||||
AND consent.purpose = 'c1';
|
||||
|
||||
ALTER TABLE consent_records
|
||||
ADD CONSTRAINT consent_records_registration_version CHECK (
|
||||
(
|
||||
source = 'registration'
|
||||
AND purpose = 'c1'
|
||||
AND registration_version IS NOT NULL
|
||||
AND registration_version > 0
|
||||
)
|
||||
OR (
|
||||
source <> 'registration'
|
||||
AND registration_version IS NULL
|
||||
)
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX consent_records_registration_version_key
|
||||
ON consent_records (subject_id, registration_version)
|
||||
WHERE
|
||||
source = 'registration'
|
||||
AND purpose = 'c1'
|
||||
AND revoked_at IS NULL;
|
||||
|
||||
-- The existing immutable trigger permits only a one-time revocation. It now
|
||||
-- also protects registration_version from being changed with that stamp.
|
||||
-- +goose StatementBegin
|
||||
CREATE OR REPLACE FUNCTION consent_records_refuse_change() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF OLD.revoked_at IS NOT NULL
|
||||
OR NEW.revoked_at IS NULL
|
||||
OR (
|
||||
NEW.id, NEW.subject_id, NEW.purpose, NEW.text_version,
|
||||
NEW.text_hash, NEW.source, NEW.registration_version,
|
||||
NEW.organization_id, NEW.organization_name, NEW.field_set,
|
||||
NEW.invitation_id, NEW.invitation_terms_version, NEW.granted_at
|
||||
) IS DISTINCT FROM (
|
||||
OLD.id, OLD.subject_id, OLD.purpose, OLD.text_version,
|
||||
OLD.text_hash, OLD.source, OLD.registration_version,
|
||||
OLD.organization_id, OLD.organization_name, OLD.field_set,
|
||||
OLD.invitation_id, OLD.invitation_terms_version, OLD.granted_at
|
||||
) THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = 'integrity_constraint_violation',
|
||||
CONSTRAINT = 'consent_records_immutable',
|
||||
TABLE = 'consent_records',
|
||||
MESSAGE = 'consent records are append-only: only an unrevoked record can be revoked, once';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER consent_records_refuse_change
|
||||
BEFORE UPDATE ON consent_records
|
||||
FOR EACH ROW EXECUTE FUNCTION consent_records_refuse_change();
|
||||
|
||||
-- Fills the registration version for an older application binary and checks
|
||||
-- values supplied by the new binary. The registration transaction updates
|
||||
-- the account before it inserts C1, so this is the current version even when
|
||||
-- the account row is already locked by that transaction.
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION consent_records_bind_registration_version() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
DECLARE
|
||||
current_version bigint;
|
||||
BEGIN
|
||||
IF NEW.source <> 'registration' OR NEW.purpose <> 'c1' THEN
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
|
||||
SELECT registration_version
|
||||
INTO current_version
|
||||
FROM users
|
||||
WHERE id = NEW.subject_id;
|
||||
|
||||
IF NOT FOUND THEN
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
|
||||
IF NEW.registration_version IS NULL THEN
|
||||
NEW.registration_version := current_version;
|
||||
ELSIF NEW.registration_version <> current_version THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = 'check_violation',
|
||||
CONSTRAINT = 'consent_records_registration_version_matches_user',
|
||||
TABLE = 'consent_records',
|
||||
MESSAGE = 'registration C1 must match the current account registration';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER consent_records_bind_registration_version
|
||||
BEFORE INSERT ON consent_records
|
||||
FOR EACH ROW EXECUTE FUNCTION consent_records_bind_registration_version();
|
||||
|
||||
-- +goose Down
|
||||
DROP TRIGGER consent_records_bind_registration_version ON consent_records;
|
||||
DROP FUNCTION consent_records_bind_registration_version();
|
||||
DROP INDEX consent_records_registration_version_key;
|
||||
DROP TRIGGER consent_records_refuse_change ON consent_records;
|
||||
|
||||
-- Restore the prior immutability check before removing its column.
|
||||
-- +goose StatementBegin
|
||||
CREATE OR REPLACE FUNCTION consent_records_refuse_change() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF OLD.revoked_at IS NOT NULL
|
||||
OR NEW.revoked_at IS NULL
|
||||
OR (
|
||||
NEW.id, NEW.subject_id, NEW.purpose, NEW.text_version,
|
||||
NEW.text_hash, NEW.source, NEW.organization_id,
|
||||
NEW.organization_name, NEW.field_set,
|
||||
NEW.invitation_id, NEW.invitation_terms_version, NEW.granted_at
|
||||
) IS DISTINCT FROM (
|
||||
OLD.id, OLD.subject_id, OLD.purpose, OLD.text_version,
|
||||
OLD.text_hash, OLD.source, OLD.organization_id,
|
||||
OLD.organization_name, OLD.field_set,
|
||||
OLD.invitation_id, OLD.invitation_terms_version, OLD.granted_at
|
||||
) THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = 'integrity_constraint_violation',
|
||||
CONSTRAINT = 'consent_records_immutable',
|
||||
TABLE = 'consent_records',
|
||||
MESSAGE = 'consent records are append-only: only an unrevoked record can be revoked, once';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
CREATE TRIGGER consent_records_refuse_change
|
||||
BEFORE UPDATE ON consent_records
|
||||
FOR EACH ROW EXECUTE FUNCTION consent_records_refuse_change();
|
||||
|
||||
ALTER TABLE consent_records
|
||||
DROP CONSTRAINT consent_records_registration_version,
|
||||
DROP COLUMN registration_version;
|
||||
@@ -39,6 +39,7 @@ INSERT INTO consent_records (
|
||||
text_version,
|
||||
text_hash,
|
||||
source,
|
||||
registration_version,
|
||||
granted_at
|
||||
) VALUES (
|
||||
sqlc.arg(id),
|
||||
@@ -47,6 +48,7 @@ INSERT INTO consent_records (
|
||||
sqlc.arg(text_version),
|
||||
sqlc.arg(text_hash),
|
||||
sqlc.arg(source),
|
||||
sqlc.narg(registration_version)::bigint,
|
||||
sqlc.arg(granted_at)
|
||||
)
|
||||
ON CONFLICT (subject_id, purpose, text_version)
|
||||
@@ -59,6 +61,7 @@ RETURNING
|
||||
text_version,
|
||||
text_hash,
|
||||
source,
|
||||
registration_version,
|
||||
organization_id,
|
||||
organization_name,
|
||||
field_set,
|
||||
@@ -93,6 +96,7 @@ INSERT INTO consent_records (
|
||||
text_version,
|
||||
text_hash,
|
||||
source,
|
||||
registration_version,
|
||||
organization_id,
|
||||
organization_name,
|
||||
field_set,
|
||||
@@ -106,6 +110,7 @@ INSERT INTO consent_records (
|
||||
sqlc.arg(text_version),
|
||||
sqlc.arg(text_hash),
|
||||
'invitation_acceptance',
|
||||
NULL,
|
||||
sqlc.arg(organization_id),
|
||||
sqlc.arg(organization_name),
|
||||
sqlc.arg(field_set)::text [],
|
||||
@@ -122,6 +127,7 @@ RETURNING
|
||||
text_version,
|
||||
text_hash,
|
||||
source,
|
||||
registration_version,
|
||||
organization_id,
|
||||
organization_name,
|
||||
field_set,
|
||||
@@ -140,6 +146,7 @@ SELECT
|
||||
record.text_version,
|
||||
record.text_hash,
|
||||
record.source,
|
||||
record.registration_version,
|
||||
record.organization_id,
|
||||
record.organization_name,
|
||||
record.field_set,
|
||||
@@ -177,6 +184,7 @@ SELECT
|
||||
text_version,
|
||||
text_hash,
|
||||
source,
|
||||
registration_version,
|
||||
organization_id,
|
||||
organization_name,
|
||||
field_set,
|
||||
@@ -202,6 +210,7 @@ SELECT
|
||||
text_version,
|
||||
text_hash,
|
||||
source,
|
||||
registration_version,
|
||||
organization_id,
|
||||
organization_name,
|
||||
field_set,
|
||||
@@ -220,6 +229,34 @@ WHERE
|
||||
ORDER BY granted_at DESC, id DESC
|
||||
LIMIT 1;
|
||||
|
||||
-- Locks the active registration C1 while its pending registration is applied.
|
||||
-- name: LockRegistrationConsentRecord :one
|
||||
SELECT
|
||||
id,
|
||||
subject_id,
|
||||
purpose,
|
||||
text_version,
|
||||
text_hash,
|
||||
source,
|
||||
registration_version,
|
||||
organization_id,
|
||||
organization_name,
|
||||
field_set,
|
||||
invitation_id,
|
||||
invitation_terms_version,
|
||||
granted_at,
|
||||
revoked_at,
|
||||
revocation_source,
|
||||
'active'::text AS state
|
||||
FROM consent_records
|
||||
WHERE
|
||||
subject_id = sqlc.arg(subject_id)
|
||||
AND purpose = 'c1'
|
||||
AND source = 'registration'
|
||||
AND registration_version = sqlc.arg(registration_version)
|
||||
AND revoked_at IS NULL
|
||||
FOR UPDATE;
|
||||
|
||||
-- name: ListCurrentContactConsentRecords :many
|
||||
SELECT
|
||||
id,
|
||||
@@ -228,6 +265,7 @@ SELECT
|
||||
text_version,
|
||||
text_hash,
|
||||
source,
|
||||
registration_version,
|
||||
organization_id,
|
||||
organization_name,
|
||||
field_set,
|
||||
@@ -265,6 +303,7 @@ RETURNING
|
||||
text_version,
|
||||
text_hash,
|
||||
source,
|
||||
registration_version,
|
||||
organization_id,
|
||||
organization_name,
|
||||
field_set,
|
||||
@@ -294,6 +333,7 @@ RETURNING
|
||||
text_version,
|
||||
text_hash,
|
||||
source,
|
||||
registration_version,
|
||||
organization_id,
|
||||
organization_name,
|
||||
field_set,
|
||||
@@ -320,6 +360,7 @@ WITH ledger AS (
|
||||
record.text_version,
|
||||
record.text_hash,
|
||||
record.source,
|
||||
record.registration_version,
|
||||
record.organization_id,
|
||||
record.organization_name,
|
||||
record.field_set,
|
||||
@@ -354,6 +395,7 @@ SELECT
|
||||
ledger.text_version,
|
||||
ledger.text_hash,
|
||||
ledger.source,
|
||||
ledger.registration_version,
|
||||
ledger.organization_id,
|
||||
ledger.organization_name,
|
||||
ledger.field_set,
|
||||
|
||||
+101
-24
@@ -149,6 +149,36 @@ RETURNING
|
||||
created_at,
|
||||
updated_at;
|
||||
|
||||
-- Applies the registration carried by its token and verifies the address in
|
||||
-- one optimistic update. The caller holds the token lock and checks the
|
||||
-- matching C1 in the same transaction.
|
||||
-- name: ConfirmUserEmail :one
|
||||
UPDATE users
|
||||
SET
|
||||
password_hash = sqlc.arg(password_hash),
|
||||
scenario = sqlc.arg(scenario),
|
||||
onboarding_step = sqlc.arg(onboarding_step),
|
||||
email_verified_at = sqlc.arg(verified_at),
|
||||
updated_at = sqlc.arg(verified_at),
|
||||
version = version + 1
|
||||
WHERE
|
||||
id = sqlc.arg(id)
|
||||
AND registration_version = sqlc.arg(registration_version)
|
||||
AND email_verified_at IS NULL
|
||||
RETURNING
|
||||
id,
|
||||
email,
|
||||
email_normalized,
|
||||
password_hash,
|
||||
scenario,
|
||||
onboarding_step,
|
||||
email_verified_at,
|
||||
registration_version,
|
||||
last_registered_at,
|
||||
version,
|
||||
created_at,
|
||||
updated_at;
|
||||
|
||||
-- Deletes one batch of accounts that stayed unverified since before cutoff,
|
||||
-- oldest first, with their tokens, sessions, mail requests, mail deliveries
|
||||
-- (and through the deliveries their attempts), and consent records. The
|
||||
@@ -306,6 +336,26 @@ WHERE
|
||||
ORDER BY created_at DESC, id DESC
|
||||
LIMIT 1;
|
||||
|
||||
-- Reads a token before password verification; Consume rechecks it in the
|
||||
-- confirmation transaction and clears pending credentials when it succeeds.
|
||||
-- name: GetEmailTokenByHash :one
|
||||
SELECT
|
||||
id,
|
||||
user_id,
|
||||
purpose,
|
||||
token_hash,
|
||||
registration_version,
|
||||
created_at,
|
||||
expires_at,
|
||||
consumed_at,
|
||||
invalidated_at,
|
||||
pending_password_hash,
|
||||
pending_scenario,
|
||||
pending_onboarding_step
|
||||
FROM email_tokens
|
||||
WHERE token_hash = sqlc.arg(token_hash)
|
||||
AND purpose = sqlc.arg(purpose);
|
||||
|
||||
-- Starts a new registration of an unverified account without touching its
|
||||
-- credentials, scenario, or onboarding step: the new registration carries
|
||||
-- them on its verification token. Advances the registration version, which
|
||||
@@ -386,30 +436,57 @@ WHERE
|
||||
-- returned registration version in the same transaction, rolled back when it
|
||||
-- matches no row.
|
||||
-- name: ConsumeEmailToken :one
|
||||
UPDATE email_tokens AS token
|
||||
SET consumed_at = sqlc.arg(consumed_at)
|
||||
FROM users AS owner
|
||||
WHERE
|
||||
token.token_hash = sqlc.arg(token_hash)
|
||||
AND token.purpose = sqlc.arg(purpose)
|
||||
AND token.consumed_at IS NULL
|
||||
AND token.invalidated_at IS NULL
|
||||
AND token.expires_at > sqlc.arg(consumed_at)
|
||||
AND owner.id = token.user_id
|
||||
AND owner.registration_version = token.registration_version
|
||||
RETURNING
|
||||
token.id,
|
||||
token.user_id,
|
||||
token.purpose,
|
||||
token.token_hash,
|
||||
token.registration_version,
|
||||
token.created_at,
|
||||
token.expires_at,
|
||||
token.consumed_at,
|
||||
token.invalidated_at,
|
||||
token.pending_password_hash,
|
||||
token.pending_scenario,
|
||||
token.pending_onboarding_step;
|
||||
WITH candidate AS MATERIALIZED (
|
||||
SELECT
|
||||
token.id,
|
||||
token.user_id,
|
||||
token.purpose,
|
||||
token.token_hash,
|
||||
token.registration_version,
|
||||
token.created_at,
|
||||
token.expires_at,
|
||||
token.pending_password_hash,
|
||||
token.pending_scenario,
|
||||
token.pending_onboarding_step
|
||||
FROM email_tokens AS token
|
||||
INNER JOIN users AS owner ON owner.id = token.user_id
|
||||
WHERE
|
||||
token.token_hash = sqlc.arg(token_hash)
|
||||
AND token.purpose = sqlc.arg(purpose)
|
||||
AND token.consumed_at IS NULL
|
||||
AND token.invalidated_at IS NULL
|
||||
AND token.expires_at > sqlc.arg(consumed_at)
|
||||
AND owner.registration_version = token.registration_version
|
||||
FOR UPDATE OF token
|
||||
),
|
||||
|
||||
consumed AS (
|
||||
UPDATE email_tokens AS token
|
||||
SET
|
||||
consumed_at = sqlc.arg(consumed_at),
|
||||
pending_password_hash = NULL,
|
||||
pending_scenario = NULL,
|
||||
pending_onboarding_step = NULL
|
||||
FROM candidate
|
||||
WHERE token.id = candidate.id
|
||||
RETURNING token.id, token.consumed_at, token.invalidated_at
|
||||
)
|
||||
|
||||
SELECT
|
||||
candidate.id,
|
||||
candidate.user_id,
|
||||
candidate.purpose,
|
||||
candidate.token_hash,
|
||||
candidate.registration_version,
|
||||
candidate.created_at,
|
||||
candidate.expires_at,
|
||||
consumed.consumed_at,
|
||||
consumed.invalidated_at,
|
||||
candidate.pending_password_hash,
|
||||
candidate.pending_scenario,
|
||||
candidate.pending_onboarding_step
|
||||
FROM candidate
|
||||
INNER JOIN consumed ON consumed.id = candidate.id;
|
||||
|
||||
-- Explains why ConsumeEmailToken matched no row.
|
||||
-- name: GetEmailTokenState :one
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
//go:build integration
|
||||
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/testcontainers/testcontainers-go"
|
||||
)
|
||||
|
||||
const rootlessPortBindFailureMessage = "Error response from daemon: failed to set up container networking: driver failed programming external connectivity on endpoint lincodex (0123456789abcdef): error while calling RootlessKit PortManager.AddPort(): listen tcp4 0.0.0.0:32912: bind: address already in use"
|
||||
|
||||
type retryTestContainer struct {
|
||||
testcontainers.Container
|
||||
terminateCalls int
|
||||
terminateErr error
|
||||
}
|
||||
|
||||
func (container *retryTestContainer) Terminate(context.Context, ...testcontainers.TerminateOption) error {
|
||||
container.terminateCalls++
|
||||
return container.terminateErr
|
||||
}
|
||||
|
||||
func TestIsRootlessPortBindFailure(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
err error
|
||||
want bool
|
||||
}{
|
||||
{name: "rootless host port collision", err: errors.New(rootlessPortBindFailureMessage), want: true},
|
||||
{name: "unrelated address collision", err: errors.New("listen tcp4 0.0.0.0:32912: bind: address already in use")},
|
||||
{name: "rootless service bind failure", err: errors.New("Error response from daemon: failed to set up container networking: driver failed programming external connectivity on endpoint lincodex (0123456789abcdef): error while calling RootlessKit PortManager.AddPort(): listen tcp4 0.0.0.0:32912: bind: permission denied")},
|
||||
{name: "rootless IPv6 bind failure", err: errors.New("Error response from daemon: failed to set up container networking: driver failed programming external connectivity on endpoint lincodex (0123456789abcdef): error while calling RootlessKit PortManager.AddPort(): listen tcp6 [::]:32912: bind: address already in use")},
|
||||
{name: "nil error", err: nil},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
if got := isRootlessPortBindFailure(test.err); got != test.want {
|
||||
t.Fatalf("isRootlessPortBindFailure(%v) = %t, want %t", test.err, got, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartWithRootlessPortRetryCleansPartialContainer(t *testing.T) {
|
||||
first := &retryTestContainer{}
|
||||
second := &retryTestContainer{}
|
||||
attempts := 0
|
||||
container, err := startWithRootlessPortRetry(
|
||||
context.Background(),
|
||||
func(context.Context) (testcontainers.Container, error) {
|
||||
attempts++
|
||||
if attempts == 1 {
|
||||
return first, errors.New(rootlessPortBindFailureMessage)
|
||||
}
|
||||
return second, nil
|
||||
},
|
||||
func(ctx context.Context, container testcontainers.Container) error {
|
||||
return container.Terminate(ctx)
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("startWithRootlessPortRetry() error = %v", err)
|
||||
}
|
||||
if container != second {
|
||||
t.Fatalf("startWithRootlessPortRetry() container = %v, want second container", container)
|
||||
}
|
||||
if attempts != 2 {
|
||||
t.Fatalf("start attempts = %d, want 2", attempts)
|
||||
}
|
||||
if first.terminateCalls != 1 {
|
||||
t.Fatalf("first container cleanup calls = %d, want 1", first.terminateCalls)
|
||||
}
|
||||
if second.terminateCalls != 0 {
|
||||
t.Fatalf("successful container cleanup calls = %d, want 0", second.terminateCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartWithRootlessPortRetryStopsAtLimit(t *testing.T) {
|
||||
startErr := errors.New(rootlessPortBindFailureMessage)
|
||||
attempts := 0
|
||||
containers := make([]*retryTestContainer, 0, rootlessPortStartLimit)
|
||||
container, err := startWithRootlessPortRetry(
|
||||
context.Background(),
|
||||
func(context.Context) (testcontainers.Container, error) {
|
||||
attempts++
|
||||
partial := &retryTestContainer{}
|
||||
containers = append(containers, partial)
|
||||
return partial, startErr
|
||||
},
|
||||
func(ctx context.Context, container testcontainers.Container) error {
|
||||
return container.Terminate(ctx)
|
||||
},
|
||||
)
|
||||
if err == nil {
|
||||
t.Fatal("startWithRootlessPortRetry() error = nil, want attempt limit error")
|
||||
}
|
||||
if !errors.Is(err, startErr) {
|
||||
t.Fatalf("startWithRootlessPortRetry() error = %v, want startup cause", err)
|
||||
}
|
||||
if container != containers[len(containers)-1] {
|
||||
t.Fatalf("startWithRootlessPortRetry() container = %v, want final partial container", container)
|
||||
}
|
||||
if attempts != rootlessPortStartLimit {
|
||||
t.Fatalf("start attempts = %d, want %d", attempts, rootlessPortStartLimit)
|
||||
}
|
||||
for index, partial := range containers[:len(containers)-1] {
|
||||
if partial.terminateCalls != 1 {
|
||||
t.Fatalf("retried container %d cleanup calls = %d, want 1", index, partial.terminateCalls)
|
||||
}
|
||||
}
|
||||
final := containers[len(containers)-1]
|
||||
if final.terminateCalls != 0 {
|
||||
t.Fatalf("final container cleanup calls = %d, want caller-owned cleanup", final.terminateCalls)
|
||||
}
|
||||
if err := final.Terminate(context.Background()); err != nil {
|
||||
t.Fatalf("caller cleanup of final container: %v", err)
|
||||
}
|
||||
if final.terminateCalls != 1 {
|
||||
t.Fatalf("final container cleanup calls after caller cleanup = %d, want 1", final.terminateCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartWithRootlessPortRetryPreservesCleanupFailure(t *testing.T) {
|
||||
startErr := errors.New(rootlessPortBindFailureMessage)
|
||||
cleanupErr := errors.New("container remove failed")
|
||||
partial := &retryTestContainer{}
|
||||
attempts := 0
|
||||
container, err := startWithRootlessPortRetry(
|
||||
context.Background(),
|
||||
func(context.Context) (testcontainers.Container, error) {
|
||||
attempts++
|
||||
return partial, startErr
|
||||
},
|
||||
func(context.Context, testcontainers.Container) error {
|
||||
return cleanupErr
|
||||
},
|
||||
)
|
||||
if !errors.Is(err, startErr) || !errors.Is(err, cleanupErr) {
|
||||
t.Fatalf("startWithRootlessPortRetry() error = %v, want start and cleanup causes", err)
|
||||
}
|
||||
if container != partial {
|
||||
t.Fatalf("startWithRootlessPortRetry() container = %v, want partial container for final cleanup", container)
|
||||
}
|
||||
if attempts != 1 {
|
||||
t.Fatalf("start attempts = %d, want 1 after cleanup failure", attempts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartWithRootlessPortRetryDoesNotRetryStartupFailure(t *testing.T) {
|
||||
startErr := errors.New("service readiness failed")
|
||||
partial := &retryTestContainer{}
|
||||
attempts := 0
|
||||
container, err := startWithRootlessPortRetry(
|
||||
context.Background(),
|
||||
func(context.Context) (testcontainers.Container, error) {
|
||||
attempts++
|
||||
return partial, startErr
|
||||
},
|
||||
func(ctx context.Context, container testcontainers.Container) error {
|
||||
return container.Terminate(ctx)
|
||||
},
|
||||
)
|
||||
if !errors.Is(err, startErr) {
|
||||
t.Fatalf("startWithRootlessPortRetry() error = %v, want startup error", err)
|
||||
}
|
||||
if container != partial {
|
||||
t.Fatalf("startWithRootlessPortRetry() container = %v, want partial container for caller cleanup", container)
|
||||
}
|
||||
if attempts != 1 {
|
||||
t.Fatalf("start attempts = %d, want 1", attempts)
|
||||
}
|
||||
if partial.terminateCalls != 0 {
|
||||
t.Fatalf("partial container cleanup calls = %d, want caller-owned cleanup", partial.terminateCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartWithRootlessPortRetryStopsWhenContextIsCanceled(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
startErr := errors.New(rootlessPortBindFailureMessage)
|
||||
partial := &retryTestContainer{}
|
||||
attempts := 0
|
||||
container, err := startWithRootlessPortRetry(
|
||||
ctx,
|
||||
func(context.Context) (testcontainers.Container, error) {
|
||||
attempts++
|
||||
cancel()
|
||||
return partial, startErr
|
||||
},
|
||||
func(ctx context.Context, container testcontainers.Container) error {
|
||||
return container.Terminate(ctx)
|
||||
},
|
||||
)
|
||||
if !errors.Is(err, context.Canceled) || !errors.Is(err, startErr) {
|
||||
t.Fatalf("startWithRootlessPortRetry() error = %v, want cancellation and startup cause", err)
|
||||
}
|
||||
if container != nil {
|
||||
t.Fatalf("startWithRootlessPortRetry() container = %v, want nil after cleanup", container)
|
||||
}
|
||||
if attempts != 1 {
|
||||
t.Fatalf("start attempts = %d, want 1", attempts)
|
||||
}
|
||||
if partial.terminateCalls != 1 {
|
||||
t.Fatalf("partial container cleanup calls = %d, want 1", partial.terminateCalls)
|
||||
}
|
||||
}
|
||||
@@ -7,9 +7,11 @@ import (
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -47,6 +49,7 @@ const (
|
||||
cleanupTimeout = 30 * time.Second
|
||||
stopTimeout = 15 * time.Second
|
||||
shutdownTimeout = 5 * time.Second
|
||||
rootlessPortStartLimit = 3
|
||||
seaweedfsStartupTimeout = time.Minute
|
||||
storageReadyTimeout = 30 * time.Second
|
||||
readinessInterval = 100 * time.Millisecond
|
||||
@@ -74,6 +77,8 @@ const (
|
||||
kafkaClusterIDSize = 16
|
||||
)
|
||||
|
||||
var rootlessPortBindFailure = regexp.MustCompile(`Error response from daemon: failed to set up container networking: driver failed programming external connectivity on endpoint [^\s]+ \([^)]*\): error while calling RootlessKit PortManager\.AddPort\(\): listen tcp4 0\.0\.0\.0:[1-9][0-9]{0,4}: bind: address already in use$`)
|
||||
|
||||
type service uint8
|
||||
|
||||
const (
|
||||
@@ -181,6 +186,64 @@ func (env *testEnvironment) cleanupContainer(ctx context.Context, container test
|
||||
})
|
||||
}
|
||||
|
||||
// startWithRootlessPortRetry retries only the daemon's rootless host-port bind
|
||||
// collision. Docker reports this remote failure as text rather than syscall.Errno.
|
||||
func startWithRootlessPortRetry(
|
||||
ctx context.Context,
|
||||
start func(context.Context) (testcontainers.Container, error),
|
||||
terminate func(context.Context, testcontainers.Container) error,
|
||||
) (testcontainers.Container, error) {
|
||||
for attempt := 1; attempt <= rootlessPortStartLimit; attempt++ {
|
||||
container, err := start(ctx)
|
||||
if err == nil {
|
||||
return container, nil
|
||||
}
|
||||
|
||||
if attempt == rootlessPortStartLimit || !isRootlessPortBindFailure(err) {
|
||||
return container, fmt.Errorf("integration_test.startWithRootlessPortRetry - start attempt %d: %w", attempt, err)
|
||||
}
|
||||
|
||||
if container != nil {
|
||||
if cleanupErr := terminateFailedStart(ctx, container, terminate); cleanupErr != nil {
|
||||
return container, errors.Join(
|
||||
fmt.Errorf("integration_test.startWithRootlessPortRetry - start attempt %d: %w", attempt, err),
|
||||
fmt.Errorf("integration_test.startWithRootlessPortRetry - clean up failed container: %w", cleanupErr),
|
||||
)
|
||||
}
|
||||
}
|
||||
if ctxErr := ctx.Err(); ctxErr != nil {
|
||||
return nil, errors.Join(
|
||||
fmt.Errorf("integration_test.startWithRootlessPortRetry - start attempt %d: %w", attempt, err),
|
||||
fmt.Errorf("integration_test.startWithRootlessPortRetry - retry canceled: %w", ctxErr),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return nil, errors.New("integration_test.startWithRootlessPortRetry - attempt limit reached")
|
||||
}
|
||||
|
||||
func terminateFailedStart(
|
||||
ctx context.Context,
|
||||
container testcontainers.Container,
|
||||
terminate func(context.Context, testcontainers.Container) error,
|
||||
) error {
|
||||
cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), cleanupTimeout)
|
||||
defer cancel()
|
||||
return terminate(cleanupCtx, container)
|
||||
}
|
||||
|
||||
func terminateTestContainer(ctx context.Context, container testcontainers.Container) error {
|
||||
return testcontainers.TerminateContainer(
|
||||
container,
|
||||
testcontainers.StopContext(ctx),
|
||||
testcontainers.StopTimeout(shutdownTimeout),
|
||||
)
|
||||
}
|
||||
|
||||
func isRootlessPortBindFailure(err error) bool {
|
||||
return err != nil && rootlessPortBindFailure.MatchString(err.Error())
|
||||
}
|
||||
|
||||
// logContainerTail prints the end of a container log after a failed start,
|
||||
// so a startup timeout shows what the service was doing.
|
||||
func logContainerTail(ctx context.Context, t *testing.T, container testcontainers.Container, name string) {
|
||||
@@ -208,17 +271,27 @@ func logContainerTail(ctx context.Context, t *testing.T, container testcontainer
|
||||
|
||||
func (env *testEnvironment) startPostgres(ctx context.Context, t *testing.T) {
|
||||
t.Helper()
|
||||
container, err := postgres.Run(ctx, postgresImage,
|
||||
postgres.WithDatabase(postgresDatabase),
|
||||
postgres.WithUsername(postgresUser),
|
||||
postgres.WithPassword(postgresPassword),
|
||||
postgres.BasicWaitStrategies(),
|
||||
)
|
||||
container, err := startWithRootlessPortRetry(ctx, func(ctx context.Context) (testcontainers.Container, error) {
|
||||
postgresContainer, err := postgres.Run(ctx, postgresImage,
|
||||
postgres.WithDatabase(postgresDatabase),
|
||||
postgres.WithUsername(postgresUser),
|
||||
postgres.WithPassword(postgresPassword),
|
||||
postgres.BasicWaitStrategies(),
|
||||
)
|
||||
if postgresContainer == nil {
|
||||
return nil, err
|
||||
}
|
||||
return postgresContainer, err
|
||||
}, terminateTestContainer)
|
||||
env.cleanupContainer(ctx, container, "PostgreSQL")
|
||||
if err != nil {
|
||||
t.Fatalf("start PostgreSQL container: %v", err)
|
||||
}
|
||||
databaseURL, err := container.ConnectionString(ctx, "sslmode=disable")
|
||||
postgresContainer, ok := container.(*postgres.PostgresContainer)
|
||||
if !ok {
|
||||
t.Fatalf("start PostgreSQL container: unexpected container type %T", container)
|
||||
}
|
||||
databaseURL, err := postgresContainer.ConnectionString(ctx, "sslmode=disable")
|
||||
if err != nil {
|
||||
t.Fatalf("get PostgreSQL connection string: %v", err)
|
||||
}
|
||||
@@ -237,15 +310,17 @@ func (env *testEnvironment) startPostgres(ctx context.Context, t *testing.T) {
|
||||
|
||||
func (env *testEnvironment) startRedis(ctx context.Context, t *testing.T) {
|
||||
t.Helper()
|
||||
container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
|
||||
ContainerRequest: testcontainers.ContainerRequest{
|
||||
Image: redisImage,
|
||||
ExposedPorts: []string{"6379/tcp"},
|
||||
Cmd: []string{"redis-server", "--requirepass", env.Config.RedisPassword, "--save", "", "--appendonly", "no"},
|
||||
WaitingFor: wait.ForLog("Ready to accept connections"),
|
||||
},
|
||||
Started: true,
|
||||
})
|
||||
container, err := startWithRootlessPortRetry(ctx, func(ctx context.Context) (testcontainers.Container, error) {
|
||||
return testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
|
||||
ContainerRequest: testcontainers.ContainerRequest{
|
||||
Image: redisImage,
|
||||
ExposedPorts: []string{"6379/tcp"},
|
||||
Cmd: []string{"redis-server", "--requirepass", env.Config.RedisPassword, "--save", "", "--appendonly", "no"},
|
||||
WaitingFor: wait.ForLog("Ready to accept connections"),
|
||||
},
|
||||
Started: true,
|
||||
})
|
||||
}, terminateTestContainer)
|
||||
env.cleanupContainer(ctx, container, "Redis")
|
||||
if err != nil {
|
||||
t.Fatalf("start Redis container: %v", err)
|
||||
@@ -300,29 +375,31 @@ func (env *testEnvironment) prepareStorageVolume() {
|
||||
|
||||
func (env *testEnvironment) startSeaweedFS(ctx context.Context, t *testing.T) {
|
||||
t.Helper()
|
||||
container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
|
||||
ContainerRequest: testcontainers.ContainerRequest{
|
||||
Image: seaweedfsImage,
|
||||
// Only the S3 port is used by the adapter. The internal ports are
|
||||
// published so tests can prove they refuse unauthenticated access.
|
||||
ExposedPorts: []string{seaweedfsS3Port, seaweedfsFilerPort, seaweedfsMasterPort, seaweedfsVolumePort},
|
||||
Entrypoint: seaweedfsEntrypoint,
|
||||
Env: map[string]string{
|
||||
"AWS_ACCESS_KEY_ID": env.Config.SeaweedFSAccessKey,
|
||||
"AWS_SECRET_ACCESS_KEY": env.Config.SeaweedFSSecretKey,
|
||||
"S3_BUCKET": env.Config.SeaweedFSBucket,
|
||||
container, err := startWithRootlessPortRetry(ctx, func(ctx context.Context) (testcontainers.Container, error) {
|
||||
return testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
|
||||
ContainerRequest: testcontainers.ContainerRequest{
|
||||
Image: seaweedfsImage,
|
||||
// Only the S3 port is used by the adapter. The internal ports are
|
||||
// published so tests can prove they refuse unauthenticated access.
|
||||
ExposedPorts: []string{seaweedfsS3Port, seaweedfsFilerPort, seaweedfsMasterPort, seaweedfsVolumePort},
|
||||
Entrypoint: seaweedfsEntrypoint,
|
||||
Env: map[string]string{
|
||||
"AWS_ACCESS_KEY_ID": env.Config.SeaweedFSAccessKey,
|
||||
"AWS_SECRET_ACCESS_KEY": env.Config.SeaweedFSSecretKey,
|
||||
"S3_BUCKET": env.Config.SeaweedFSBucket,
|
||||
},
|
||||
Cmd: []string{
|
||||
"mini", "-dir=/data", "-ip=127.0.0.1", "-ip.bind=0.0.0.0", "-whiteList=127.0.0.1,@",
|
||||
"-webdav=false", "-admin.ui=false", "-s3.iam=false",
|
||||
"-s3.port.iceberg=0", "-s3.port.lance=0", "-s3.autoCreateBucket=false",
|
||||
"-s3.allowDeleteBucketNotEmpty=false", "-master.telemetry=false",
|
||||
},
|
||||
Mounts: testcontainers.ContainerMounts{testcontainers.VolumeMount(env.seaweedfsVolume, "/data")},
|
||||
WaitingFor: wait.ForHTTP("/healthz").WithPort(seaweedfsS3Port).WithStartupTimeout(seaweedfsStartupTimeout),
|
||||
},
|
||||
Cmd: []string{
|
||||
"mini", "-dir=/data", "-ip=127.0.0.1", "-ip.bind=0.0.0.0", "-whiteList=127.0.0.1,@",
|
||||
"-webdav=false", "-admin.ui=false", "-s3.iam=false",
|
||||
"-s3.port.iceberg=0", "-s3.port.lance=0", "-s3.autoCreateBucket=false",
|
||||
"-s3.allowDeleteBucketNotEmpty=false", "-master.telemetry=false",
|
||||
},
|
||||
Mounts: testcontainers.ContainerMounts{testcontainers.VolumeMount(env.seaweedfsVolume, "/data")},
|
||||
WaitingFor: wait.ForHTTP("/healthz").WithPort(seaweedfsS3Port).WithStartupTimeout(seaweedfsStartupTimeout),
|
||||
},
|
||||
Started: true,
|
||||
})
|
||||
Started: true,
|
||||
})
|
||||
}, terminateTestContainer)
|
||||
env.cleanupContainer(ctx, container, "SeaweedFS")
|
||||
if err != nil {
|
||||
t.Fatalf("start SeaweedFS container: %v", err)
|
||||
@@ -404,30 +481,32 @@ func (env *testEnvironment) startKafka(ctx context.Context, t *testing.T) {
|
||||
if _, err := rand.Read(clusterID); err != nil {
|
||||
t.Fatalf("generate Kafka cluster ID: %v", err)
|
||||
}
|
||||
container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
|
||||
ContainerRequest: testcontainers.ContainerRequest{
|
||||
Image: kafkaImage,
|
||||
ExposedPorts: []string{kafkaClientPort},
|
||||
Env: kafkaEnvironment(base64.RawURLEncoding.EncodeToString(clusterID)),
|
||||
// The advertised client address contains the host port, which is
|
||||
// known only after the container starts.
|
||||
Entrypoint: []string{"sh", "-c", "while [ ! -s " + kafkaListenersFile + " ]; do sleep 0.1; done; " +
|
||||
"KAFKA_ADVERTISED_LISTENERS=\"$(cat " + kafkaListenersFile + ")\" exec /__cacert_entrypoint.sh /etc/kafka/docker/run"},
|
||||
// The image declares these paths as volumes. Compose keeps data in a
|
||||
// named volume; a test broker needs no persistence, so tmpfs for all
|
||||
// three leaves no anonymous volumes behind.
|
||||
Tmpfs: map[string]string{
|
||||
"/var/lib/kafka/data": "rw,size=256m,mode=1777",
|
||||
"/etc/kafka/secrets": "rw,size=1m,mode=0755",
|
||||
"/mnt/shared/config": "rw,size=1m,mode=0755",
|
||||
container, err := startWithRootlessPortRetry(ctx, func(ctx context.Context) (testcontainers.Container, error) {
|
||||
return testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
|
||||
ContainerRequest: testcontainers.ContainerRequest{
|
||||
Image: kafkaImage,
|
||||
ExposedPorts: []string{kafkaClientPort},
|
||||
Env: kafkaEnvironment(base64.RawURLEncoding.EncodeToString(clusterID)),
|
||||
// The advertised client address contains the host port, which is
|
||||
// known only after the container starts.
|
||||
Entrypoint: []string{"sh", "-c", "while [ ! -s " + kafkaListenersFile + " ]; do sleep 0.1; done; " +
|
||||
"KAFKA_ADVERTISED_LISTENERS=\"$(cat " + kafkaListenersFile + ")\" exec /__cacert_entrypoint.sh /etc/kafka/docker/run"},
|
||||
// The image declares these paths as volumes. Compose keeps data in a
|
||||
// named volume; a test broker needs no persistence, so tmpfs for all
|
||||
// three leaves no anonymous volumes behind.
|
||||
Tmpfs: map[string]string{
|
||||
"/var/lib/kafka/data": "rw,size=256m,mode=1777",
|
||||
"/etc/kafka/secrets": "rw,size=1m,mode=0755",
|
||||
"/mnt/shared/config": "rw,size=1m,mode=0755",
|
||||
},
|
||||
LifecycleHooks: []testcontainers.ContainerLifecycleHooks{{
|
||||
PostStarts: []testcontainers.ContainerHook{advertiseKafkaListeners},
|
||||
}},
|
||||
WaitingFor: wait.ForLog("Kafka Server started").WithStartupTimeout(kafkaStartupTimeout),
|
||||
},
|
||||
LifecycleHooks: []testcontainers.ContainerLifecycleHooks{{
|
||||
PostStarts: []testcontainers.ContainerHook{advertiseKafkaListeners},
|
||||
}},
|
||||
WaitingFor: wait.ForLog("Kafka Server started").WithStartupTimeout(kafkaStartupTimeout),
|
||||
},
|
||||
Started: true,
|
||||
})
|
||||
Started: true,
|
||||
})
|
||||
}, terminateTestContainer)
|
||||
env.cleanupContainer(ctx, container, "Kafka")
|
||||
if err != nil {
|
||||
logContainerTail(ctx, t, container, "Kafka")
|
||||
|
||||
@@ -373,7 +373,8 @@ func TestConsentLedger(t *testing.T) {
|
||||
{"C4 with a repeated field", insert("c4", "c4-2026-10-01", publicationHash[:], "invitation_acceptance", &organization, []string{"email", "email"}, nil), consentCheckViolation, "consent_records_c4_scope"},
|
||||
{"C4 with an unknown field", insert("c4", "c4-2026-10-01", publicationHash[:], "invitation_acceptance", &organization, []string{"address"}, nil), consentCheckViolation, "consent_records_c4_scope"},
|
||||
{"C2 with a scope", insert("c2", "c2-2026-10-01", publicationHash[:], "consent_settings", &organization, []string{"email"}, nil), consentCheckViolation, "consent_records_c4_scope"},
|
||||
{"C2 from the registration", insert("c2", "c2-2026-10-01", publicationHash[:], "registration", nil, nil, nil), consentCheckViolation, "consent_records_source_of_purpose"},
|
||||
{"C2 from the registration", insert("c2", "c2-2026-10-01", publicationHash[:], "registration", nil, nil, nil), consentCheckViolation, "consent_records_registration_version"},
|
||||
{"C2 from an invitation", insert("c2", "c2-2026-10-01", publicationHash[:], "invitation_acceptance", nil, nil, nil), consentCheckViolation, "consent_records_source_of_purpose"},
|
||||
{"revocation without a source", insert("c2", "c2-2026-10-01", publicationHash[:], "consent_settings", nil, nil, &empty), consentCheckViolation, "consent_records_revocation_stamp"},
|
||||
{"hash of another text", insert("c3", "c3-2026-10-01", publicationHash[:], "consent_settings", nil, nil, nil), consentForeignKeyViolation, "consent_records_published_text_fkey"},
|
||||
} {
|
||||
@@ -658,11 +659,14 @@ func TestConsentLedger(t *testing.T) {
|
||||
t.Fatalf("ReRegister() error = %v", err)
|
||||
}
|
||||
var replacement domain.ConsentRecord
|
||||
var registered domain.User
|
||||
err = fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if _, err := unit.Users().UpdateRegistration(ctx, changed); err != nil {
|
||||
var err error
|
||||
registered, err = unit.Users().UpdateRegistration(ctx, changed)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
grant := fixture.newGrant(t, first.ID, domain.ConsentPurposePersonalData, "c1-2026-10-01", domain.ConsentSourceRegistration, now)
|
||||
grant := fixture.newGrant(t, first.ID, domain.ConsentPurposePersonalData, "c1-2026-10-01", domain.ConsentSourceRegistration, now, registered.RegistrationVersion)
|
||||
var created bool
|
||||
replacement, created, err = unit.ConsentLedger().Grant(ctx, grant)
|
||||
if err == nil && !created {
|
||||
@@ -678,6 +682,9 @@ func TestConsentLedger(t *testing.T) {
|
||||
if replacement.ID() == earlier.ID() {
|
||||
t.Fatal("the earlier registrant's C1 survived the re-registration")
|
||||
}
|
||||
if replacement.RegistrationVersion() != registered.RegistrationVersion {
|
||||
t.Fatalf("replacement C1 registration version = %d, want %d", replacement.RegistrationVersion(), registered.RegistrationVersion)
|
||||
}
|
||||
|
||||
// A stale re-registration changes nothing and deletes nothing.
|
||||
if _, err := fixture.identity.store.Users().UpdateRegistration(ctx, changed); !errors.Is(err, outbound.ErrUserVersionConflict) {
|
||||
@@ -836,14 +843,26 @@ func (fixture consentFixture) newGrant(
|
||||
version domain.ConsentTextVersion,
|
||||
source domain.ConsentSource,
|
||||
at time.Time,
|
||||
registrationVersions ...int64,
|
||||
) domain.ConsentGrant {
|
||||
t.Helper()
|
||||
registrationVersion := int64(0)
|
||||
if source == domain.ConsentSourceRegistration {
|
||||
registrationVersion = 1
|
||||
}
|
||||
if len(registrationVersions) > 1 {
|
||||
t.Fatal("newGrant received more than one registration version")
|
||||
}
|
||||
if len(registrationVersions) == 1 {
|
||||
registrationVersion = registrationVersions[0]
|
||||
}
|
||||
text, err := fixture.store.ConsentTexts().Get(fixture.ctx, purpose, version)
|
||||
if err != nil {
|
||||
t.Fatalf("ConsentTexts().Get(%s, %s) error = %v", purpose, version, err)
|
||||
}
|
||||
grant, err := domain.NewConsentGrant(domain.ConsentGrantInput{
|
||||
SubjectID: subject, Purpose: purpose, TextVersion: text.Version(), TextHash: text.Hash(), Source: source, GrantedAt: at,
|
||||
SubjectID: subject, Purpose: purpose, TextVersion: text.Version(), TextHash: text.Hash(),
|
||||
Source: source, RegistrationVersion: registrationVersion, GrantedAt: at,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewConsentGrant() error = %v", err)
|
||||
|
||||
@@ -66,12 +66,12 @@ func (fixture consentGrantsFixture) grantInput(t *testing.T, subject uuid.UUID,
|
||||
|
||||
// registerC1 records the registration C1 of an existing account in its own
|
||||
// transaction.
|
||||
func (fixture consentGrantsFixture) registerC1(t *testing.T, subject uuid.UUID) domain.ConsentRecord {
|
||||
func (fixture consentGrantsFixture) registerC1(t *testing.T, user domain.User) domain.ConsentRecord {
|
||||
t.Helper()
|
||||
var result consent.GrantResult
|
||||
err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
var err error
|
||||
result, err = fixture.service.GrantAtRegistration(ctx, unit, subject, fixture.currentVersion(t, domain.ConsentPurposePersonalData))
|
||||
result, err = fixture.service.GrantAtRegistration(ctx, unit, user.ID, user.RegistrationVersion, fixture.currentVersion(t, domain.ConsentPurposePersonalData))
|
||||
return err
|
||||
})
|
||||
if err != nil || !result.Created {
|
||||
@@ -170,7 +170,7 @@ func TestConsentGrants(t *testing.T) {
|
||||
return err
|
||||
}
|
||||
var err error
|
||||
registered, err = fixture.service.GrantAtRegistration(ctx, unit, user.ID, c1)
|
||||
registered, err = fixture.service.GrantAtRegistration(ctx, unit, user.ID, user.RegistrationVersion, c1)
|
||||
return err
|
||||
})
|
||||
if err != nil || !registered.Created {
|
||||
@@ -180,6 +180,7 @@ func TestConsentGrants(t *testing.T) {
|
||||
assertRowCount(ctx, t, pool, sessionsTable, 0)
|
||||
assertRowCount(ctx, t, pool, consentRecordsTable, 1)
|
||||
if record := registered.Record; record.SubjectID() != user.ID || record.Source() != domain.ConsentSourceRegistration ||
|
||||
record.RegistrationVersion() != user.RegistrationVersion ||
|
||||
record.TextVersion() != consentSecondC1Version || !record.GrantedAt().Equal(start) {
|
||||
t.Fatalf("registration C1 = %s %s %v, want the current text at the application time", record.Source(), record.TextVersion(), record.GrantedAt())
|
||||
}
|
||||
@@ -228,7 +229,7 @@ func TestConsentGrants(t *testing.T) {
|
||||
if err := unit.Users().Create(ctx, user); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := fixture.service.GrantAtRegistration(ctx, unit, user.ID, c1); err != nil {
|
||||
if _, err := fixture.service.GrantAtRegistration(ctx, unit, user.ID, user.RegistrationVersion, c1); err != nil {
|
||||
return err
|
||||
}
|
||||
return errForcedRollback
|
||||
@@ -242,7 +243,7 @@ func TestConsentGrants(t *testing.T) {
|
||||
// A grant for a subject that has no account is refused by the ledger
|
||||
// and stores nothing.
|
||||
err = transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
_, err := fixture.service.GrantAtRegistration(ctx, unit, uuid.New(), c1)
|
||||
_, err := fixture.service.GrantAtRegistration(ctx, unit, uuid.New(), 1, c1)
|
||||
return err
|
||||
})
|
||||
if !errors.Is(err, outbound.ErrUserNotFound) {
|
||||
@@ -379,30 +380,31 @@ func TestConsentGrants(t *testing.T) {
|
||||
reregister := func(t *testing.T, rawEmail string, grantFirst bool) (granted consent.GrantResult, earlier domain.ConsentRecord) {
|
||||
t.Helper()
|
||||
first := fixture.identity.createUser(t, rawEmail, domain.ScenarioCandidate, start.Add(-72*time.Hour))
|
||||
earlier = fixture.registerC1(t, first.ID)
|
||||
earlier = fixture.registerC1(t, first)
|
||||
changed, err := first.ReRegister(fixture.identity.registration(t, rawEmail, domain.ScenarioEmployer, start))
|
||||
if err != nil {
|
||||
t.Fatalf("ReRegister() error = %v", err)
|
||||
}
|
||||
version := fixture.currentVersion(t, domain.ConsentPurposePersonalData)
|
||||
err = transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
grant := func() error {
|
||||
grant := func(registrationVersion int64) error {
|
||||
var err error
|
||||
granted, err = fixture.service.GrantAtRegistration(ctx, unit, first.ID, version)
|
||||
granted, err = fixture.service.GrantAtRegistration(ctx, unit, first.ID, registrationVersion, version)
|
||||
return err
|
||||
}
|
||||
if grantFirst {
|
||||
if err := grant(); err != nil {
|
||||
if err := grant(first.RegistrationVersion); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if _, err := unit.Users().UpdateRegistration(ctx, changed); err != nil {
|
||||
registered, err := unit.Users().UpdateRegistration(ctx, changed)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if grantFirst {
|
||||
return nil
|
||||
}
|
||||
return grant()
|
||||
return grant(registered.RegistrationVersion)
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("re-registration transaction error = %v", err)
|
||||
@@ -498,7 +500,7 @@ func TestConsentGrants(t *testing.T) {
|
||||
reset(t)
|
||||
user := fixture.identity.createUser(t, "restart@example.com", domain.ScenarioCandidate, start.Add(-72*time.Hour))
|
||||
grantedAt := map[uuid.UUID]time.Time{}
|
||||
c1 := fixture.registerC1(t, user.ID)
|
||||
c1 := fixture.registerC1(t, user)
|
||||
grantedAt[c1.ID()] = fixture.now()
|
||||
fixture.advance(time.Minute)
|
||||
c2 := fixture.grant(t, fixture.grantInput(t, user.ID, domain.ConsentPurposePublication))
|
||||
|
||||
@@ -0,0 +1,677 @@
|
||||
//go:build integration
|
||||
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"mime"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
const (
|
||||
confirmationTestTimeout = 5 * time.Minute
|
||||
confirmationRetryWindow = time.Hour
|
||||
confirmationSecondPassword = "another correct horse battery staple"
|
||||
confirmationWrongPassword = "this is the wrong password"
|
||||
confirmationUnknownToken = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
|
||||
confirmationFailureFunction = "integration_reject_email_confirmation"
|
||||
confirmationFailureTrigger = "integration_reject_email_confirmation_event"
|
||||
)
|
||||
|
||||
type confirmationState struct {
|
||||
scenario string
|
||||
onboardingStep string
|
||||
passwordHash string
|
||||
emailVerifiedAt *time.Time
|
||||
registrationVersion int64
|
||||
userVersion int64
|
||||
tokenRegistrationVersion int64
|
||||
tokenConsumedAt *time.Time
|
||||
tokenInvalidatedAt *time.Time
|
||||
pendingPasswordHash *string
|
||||
pendingScenario *string
|
||||
pendingOnboardingStep *string
|
||||
c1RegistrationVersion *int64
|
||||
tokenCount int
|
||||
sessionCount int
|
||||
confirmationEventCount int
|
||||
}
|
||||
|
||||
func TestEmailVerificationOverHTTP(t *testing.T) {
|
||||
env := bootstrap(t, postgresService, redisService)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), confirmationTestTimeout)
|
||||
defer cancel()
|
||||
harness := newRegistrationHarness(ctx, t, env, 1000)
|
||||
reset := func(t *testing.T) {
|
||||
t.Helper()
|
||||
harness.truncate(ctx, t)
|
||||
harness.clock.Set(harness.start)
|
||||
}
|
||||
publicOrigin := env.Config.AppPublicURL
|
||||
|
||||
t.Run("a candidate and employer confirm the registration received by mail", func(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
email string
|
||||
scenario string
|
||||
step string
|
||||
}{
|
||||
{name: "candidate", email: "confirm.candidate@example.com", scenario: "candidate", step: "candidate_consents"},
|
||||
{name: "employer", email: "confirm.employer@example.com", scenario: "employer", step: "employer_company"},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
reset(t)
|
||||
token := harness.registerAndSendVerification(ctx, t, test.email, test.scenario, registrationPassword)
|
||||
before := readConfirmationState(ctx, t, harness, test.email, token)
|
||||
if before.pendingPasswordHash == nil || before.c1RegistrationVersion == nil ||
|
||||
*before.c1RegistrationVersion != before.tokenRegistrationVersion {
|
||||
t.Fatal("registration did not bind its C1 record and pending password to the emailed token")
|
||||
}
|
||||
|
||||
response := harness.confirm(t, token, registrationPassword, &publicOrigin)
|
||||
requireConfirmationSuccess(t, response, test.scenario, test.step)
|
||||
after := readConfirmationState(ctx, t, harness, test.email, token)
|
||||
assertConfirmationApplied(t, before, after, test.scenario, test.step)
|
||||
assertSingleConfirmationEvent(ctx, t, harness, test.email)
|
||||
if after.sessionCount != 0 {
|
||||
t.Fatalf("confirmation created %d sessions, want none", after.sessionCount)
|
||||
}
|
||||
harness.assertLogsHoldNoSecrets(t, test.email, registrationPassword, token)
|
||||
|
||||
// A consumed link cannot be replayed and leaves the committed account alone.
|
||||
replay := harness.confirm(t, token, registrationPassword, &publicOrigin)
|
||||
requireProblemStatus(t, replay, http.StatusBadRequest, "verification_token_invalid")
|
||||
if replay.setCookie != "" || !sameConfirmationState(after, readConfirmationState(ctx, t, harness, test.email, token)) {
|
||||
t.Fatal("replaying a consumed token changed the account or set a cookie")
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("an unknown token is refused without creating identity state", func(t *testing.T) {
|
||||
reset(t)
|
||||
response := harness.confirm(t, confirmationUnknownToken, registrationPassword, &publicOrigin)
|
||||
requireProblemStatus(t, response, http.StatusBadRequest, "verification_token_invalid")
|
||||
if response.retryAfter != "" || response.setCookie != "" ||
|
||||
harness.count(ctx, t, `SELECT count(*) FROM users`) != 0 ||
|
||||
harness.count(ctx, t, `SELECT count(*) FROM email_tokens`) != 0 ||
|
||||
harness.count(ctx, t, `SELECT count(*) FROM sessions`) != 0 ||
|
||||
harness.count(ctx, t, `SELECT count(*) FROM outbox_events WHERE event_type = 'identity.email_verified'`) != 0 {
|
||||
t.Fatal("an unknown token changed identity state or returned rate-limit/session headers")
|
||||
}
|
||||
harness.assertLogsHoldNoSecrets(t, confirmationUnknownToken, registrationPassword)
|
||||
})
|
||||
|
||||
t.Run("an expired token remains unconsumed", func(t *testing.T) {
|
||||
reset(t)
|
||||
const email = "confirm.expired@example.com"
|
||||
token := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword)
|
||||
before := readConfirmationState(ctx, t, harness, email, token)
|
||||
expiresAt := tokenExpiresAt(ctx, t, harness, token)
|
||||
harness.clock.Set(expiresAt.Add(time.Second))
|
||||
|
||||
response := harness.confirm(t, token, registrationPassword, &publicOrigin)
|
||||
requireProblemStatus(t, response, http.StatusBadRequest, "verification_token_expired")
|
||||
if response.retryAfter != "" || response.setCookie != "" ||
|
||||
!sameConfirmationState(before, readConfirmationState(ctx, t, harness, email, token)) {
|
||||
t.Fatal("an expired token changed the account or returned rate-limit/session headers")
|
||||
}
|
||||
harness.assertLogsHoldNoSecrets(t, email, registrationPassword, token)
|
||||
})
|
||||
|
||||
t.Run("an expired active token from an earlier registration version is invalid", func(t *testing.T) {
|
||||
reset(t)
|
||||
const email = "confirm.stale-active-version@example.com"
|
||||
token := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword)
|
||||
hash := sha256.Sum256([]byte(token))
|
||||
deadline := harness.clock.Now().Add(time.Second)
|
||||
harness.exec(ctx, t, `UPDATE email_tokens SET expires_at = $1 WHERE token_hash = $2`, deadline, hash[:])
|
||||
harness.clock.Set(deadline.Add(time.Second))
|
||||
harness.exec(ctx, t, `UPDATE users SET registration_version = registration_version + 1, version = version + 1, updated_at = $1 WHERE email_normalized = $2`,
|
||||
harness.clock.Now(), strings.ToLower(email))
|
||||
before := readConfirmationState(ctx, t, harness, email, token)
|
||||
if before.tokenInvalidatedAt != nil || before.pendingPasswordHash == nil ||
|
||||
before.registrationVersion == before.tokenRegistrationVersion || !deadline.Before(harness.clock.Now()) {
|
||||
t.Fatal("fixture does not contain an expired, active token for an earlier account version")
|
||||
}
|
||||
|
||||
response := harness.confirm(t, token, registrationPassword, &publicOrigin)
|
||||
requireProblemStatus(t, response, http.StatusBadRequest, "verification_token_invalid")
|
||||
if response.retryAfter != "" || response.setCookie != "" ||
|
||||
!sameConfirmationState(before, readConfirmationState(ctx, t, harness, email, token)) {
|
||||
t.Fatal("an expired active token from an earlier account version changed identity state")
|
||||
}
|
||||
harness.assertLogsHoldNoSecrets(t, email, registrationPassword, token)
|
||||
})
|
||||
|
||||
t.Run("expiry is checked after confirmation waits for token, consent, or user locks", func(t *testing.T) {
|
||||
for _, target := range []struct {
|
||||
name string
|
||||
query string
|
||||
}{
|
||||
{name: "token", query: `SELECT 1 FROM email_tokens WHERE token_hash = $1 FOR UPDATE`},
|
||||
{name: "registration consent", query: `
|
||||
SELECT 1 FROM consent_records AS consent
|
||||
JOIN users AS account ON account.id = consent.subject_id
|
||||
WHERE account.email_normalized = $1 AND consent.purpose = 'c1'
|
||||
AND consent.source = 'registration' AND consent.revoked_at IS NULL
|
||||
FOR UPDATE OF consent`},
|
||||
{name: "user", query: `SELECT 1 FROM users WHERE email_normalized = $1 FOR UPDATE`},
|
||||
} {
|
||||
t.Run(target.name, func(t *testing.T) {
|
||||
reset(t)
|
||||
email := "confirm.lock-expiry-" + strings.ReplaceAll(target.name, " ", "-") + "@example.com"
|
||||
token := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword)
|
||||
before := readConfirmationState(ctx, t, harness, email, token)
|
||||
expiresAt := tokenExpiresAt(ctx, t, harness, token)
|
||||
monitorPool := env.newPool(ctx, t)
|
||||
holder, err := harness.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("begin %s lock: %v", target.name, err)
|
||||
}
|
||||
defer func() {
|
||||
if err := holder.Rollback(context.WithoutCancel(ctx)); err != nil && !errors.Is(err, pgx.ErrTxClosed) {
|
||||
t.Errorf("release %s lock: %v", target.name, err)
|
||||
}
|
||||
}()
|
||||
|
||||
var lockKey any = strings.ToLower(email)
|
||||
if target.name == "token" {
|
||||
hash := sha256.Sum256([]byte(token))
|
||||
lockKey = hash[:]
|
||||
}
|
||||
var locked int
|
||||
if err := holder.QueryRow(ctx, target.query, lockKey).Scan(&locked); err != nil {
|
||||
t.Fatalf("lock the emailed %s row: %v", target.name, err)
|
||||
}
|
||||
|
||||
type confirmationReply struct{ response registrationResponse }
|
||||
reply := make(chan confirmationReply, 1)
|
||||
go func() {
|
||||
reply <- confirmationReply{response: harness.confirm(t, token, registrationPassword, &publicOrigin)}
|
||||
}()
|
||||
waitEvent, observed := waitForLockWait(ctx, monitorPool, registrationApplication)
|
||||
if !observed {
|
||||
_ = holder.Rollback(context.WithoutCancel(ctx))
|
||||
<-reply
|
||||
t.Fatalf("confirmation did not wait on the %s row lock (last wait event %q)", target.name, waitEvent)
|
||||
}
|
||||
harness.clock.Set(expiresAt.Add(time.Second))
|
||||
if err := holder.Commit(ctx); err != nil {
|
||||
t.Fatalf("release the %s lock: %v", target.name, err)
|
||||
}
|
||||
response := (<-reply).response
|
||||
requireProblemStatus(t, response, http.StatusBadRequest, "verification_token_expired")
|
||||
if response.setCookie != "" || !sameConfirmationState(before, readConfirmationState(ctx, t, harness, email, token)) {
|
||||
t.Fatalf("a request queued on the %s lock consumed the token after its deadline", target.name)
|
||||
}
|
||||
harness.assertLogsHoldNoSecrets(t, email, registrationPassword, token)
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("missing, null, and foreign Origin values are rejected without consuming the token", func(t *testing.T) {
|
||||
reset(t)
|
||||
const email = "confirm.origin@example.com"
|
||||
token := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword)
|
||||
before := readConfirmationState(ctx, t, harness, email, token)
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
origin *string
|
||||
}{
|
||||
{name: "missing"},
|
||||
{name: "null", origin: stringPointer("null")},
|
||||
{name: "foreign", origin: stringPointer("https://foreign.example")},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
response := harness.confirm(t, token, registrationPassword, test.origin)
|
||||
requireProblemStatus(t, response, http.StatusForbidden, "csrf_check_failed")
|
||||
if response.retryAfter != "" || response.setCookie != "" ||
|
||||
!sameConfirmationState(before, readConfirmationState(ctx, t, harness, email, token)) {
|
||||
t.Fatal("an invalid Origin changed the account or returned rate-limit/session headers")
|
||||
}
|
||||
})
|
||||
}
|
||||
response := harness.confirm(t, token, registrationPassword, &publicOrigin)
|
||||
requireConfirmationSuccess(t, response, "candidate", "candidate_consents")
|
||||
harness.assertLogsHoldNoSecrets(t, email, registrationPassword, token)
|
||||
})
|
||||
|
||||
t.Run("the second registrant confirms only with its own password and token", func(t *testing.T) {
|
||||
reset(t)
|
||||
const email = "confirm.replaced@example.com"
|
||||
firstToken := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword)
|
||||
firstHash := sha256.Sum256([]byte(firstToken))
|
||||
firstDeadline := harness.clock.Now().Add(time.Second)
|
||||
harness.exec(ctx, t, `UPDATE email_tokens SET expires_at = $1 WHERE token_hash = $2`, firstDeadline, firstHash[:])
|
||||
harness.clock.Set(firstDeadline.Add(time.Second))
|
||||
time.Sleep(registrationMinInterval + 100*time.Millisecond)
|
||||
secondToken := harness.registerAndSendVerification(ctx, t, email, "employer", confirmationSecondPassword)
|
||||
oldBefore := readConfirmationState(ctx, t, harness, email, firstToken)
|
||||
if oldBefore.tokenInvalidatedAt == nil || oldBefore.pendingPasswordHash != nil {
|
||||
t.Fatal("re-registration did not invalidate the old token and clear its pending credentials")
|
||||
}
|
||||
|
||||
old := harness.confirm(t, firstToken, registrationPassword, &publicOrigin)
|
||||
requireProblemStatus(t, old, http.StatusBadRequest, "verification_token_invalid")
|
||||
if !sameConfirmationState(oldBefore, readConfirmationState(ctx, t, harness, email, firstToken)) {
|
||||
t.Fatal("an expired token from a replaced registration changed account or token rows")
|
||||
}
|
||||
|
||||
currentBefore := readConfirmationState(ctx, t, harness, email, secondToken)
|
||||
wrong := harness.confirm(t, secondToken, registrationPassword, &publicOrigin)
|
||||
requireProblemStatus(t, wrong, http.StatusBadRequest, "verification_token_invalid")
|
||||
if !sameConfirmationState(currentBefore, readConfirmationState(ctx, t, harness, email, secondToken)) {
|
||||
t.Fatal("a wrong password consumed the current token or changed the account")
|
||||
}
|
||||
|
||||
accepted := harness.confirm(t, secondToken, confirmationSecondPassword, &publicOrigin)
|
||||
requireConfirmationSuccess(t, accepted, "employer", "employer_company")
|
||||
after := readConfirmationState(ctx, t, harness, email, secondToken)
|
||||
assertConfirmationApplied(t, currentBefore, after, "employer", "employer_company")
|
||||
assertSingleConfirmationEvent(ctx, t, harness, email)
|
||||
harness.assertLogsHoldNoSecrets(t, email, registrationPassword, confirmationSecondPassword, firstToken, secondToken)
|
||||
})
|
||||
|
||||
t.Run("the original registrant can replace a second registrant before confirmation", func(t *testing.T) {
|
||||
reset(t)
|
||||
const email = "confirm.owner-first@example.com"
|
||||
firstToken := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword)
|
||||
time.Sleep(registrationMinInterval + 100*time.Millisecond)
|
||||
secondToken := harness.registerAndSendVerification(ctx, t, email, "employer", confirmationSecondPassword)
|
||||
firstAfterReplacement := readConfirmationState(ctx, t, harness, email, firstToken)
|
||||
if firstAfterReplacement.tokenInvalidatedAt == nil || firstAfterReplacement.pendingPasswordHash != nil {
|
||||
t.Fatal("the second registration did not invalidate the original token and clear its pending credentials")
|
||||
}
|
||||
|
||||
old := harness.confirm(t, firstToken, registrationPassword, &publicOrigin)
|
||||
requireProblemStatus(t, old, http.StatusBadRequest, "verification_token_invalid")
|
||||
if !sameConfirmationState(firstAfterReplacement, readConfirmationState(ctx, t, harness, email, firstToken)) {
|
||||
t.Fatal("the original registrant's replaced token changed account or token rows")
|
||||
}
|
||||
|
||||
secondBefore := readConfirmationState(ctx, t, harness, email, secondToken)
|
||||
wrong := harness.confirm(t, secondToken, registrationPassword, &publicOrigin)
|
||||
requireProblemStatus(t, wrong, http.StatusBadRequest, "verification_token_invalid")
|
||||
if !sameConfirmationState(secondBefore, readConfirmationState(ctx, t, harness, email, secondToken)) {
|
||||
t.Fatal("the original password consumed the second registrant's token or changed the account")
|
||||
}
|
||||
|
||||
time.Sleep(registrationMinInterval + 100*time.Millisecond)
|
||||
harness.clock.Advance(registrationMinInterval + time.Second)
|
||||
thirdToken := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword)
|
||||
secondAfterReplacement := readConfirmationState(ctx, t, harness, email, secondToken)
|
||||
if secondAfterReplacement.tokenInvalidatedAt == nil || secondAfterReplacement.pendingPasswordHash != nil {
|
||||
t.Fatal("the original registrant's new registration did not invalidate the second token")
|
||||
}
|
||||
superseded := harness.confirm(t, secondToken, confirmationSecondPassword, &publicOrigin)
|
||||
requireProblemStatus(t, superseded, http.StatusBadRequest, "verification_token_invalid")
|
||||
if !sameConfirmationState(secondAfterReplacement, readConfirmationState(ctx, t, harness, email, secondToken)) {
|
||||
t.Fatal("confirming the superseded second registration changed account or token rows")
|
||||
}
|
||||
|
||||
thirdBefore := readConfirmationState(ctx, t, harness, email, thirdToken)
|
||||
accepted := harness.confirm(t, thirdToken, registrationPassword, &publicOrigin)
|
||||
requireConfirmationSuccess(t, accepted, "candidate", "candidate_consents")
|
||||
after := readConfirmationState(ctx, t, harness, email, thirdToken)
|
||||
assertConfirmationApplied(t, thirdBefore, after, "candidate", "candidate_consents")
|
||||
assertSingleConfirmationEvent(ctx, t, harness, email)
|
||||
harness.assertLogsHoldNoSecrets(t, email, registrationPassword, confirmationSecondPassword, firstToken, secondToken, thirdToken)
|
||||
})
|
||||
|
||||
t.Run("a confirmed registration stays current if another registration follows", func(t *testing.T) {
|
||||
reset(t)
|
||||
const email = "confirm.before-reregistration@example.com"
|
||||
token := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword)
|
||||
before := readConfirmationState(ctx, t, harness, email, token)
|
||||
response := harness.confirm(t, token, registrationPassword, &publicOrigin)
|
||||
requireConfirmationSuccess(t, response, "candidate", "candidate_consents")
|
||||
confirmed := readConfirmationState(ctx, t, harness, email, token)
|
||||
assertConfirmationApplied(t, before, confirmed, "candidate", "candidate_consents")
|
||||
|
||||
time.Sleep(registrationMinInterval + 100*time.Millisecond)
|
||||
registrationResponse := harness.registerBody(t, registrationBody(email, "employer", confirmationSecondPassword, registrationC1), "")
|
||||
requireAccepted(t, registrationResponse)
|
||||
if registrationResponse.setCookie != "" || !sameConfirmationState(confirmed, readConfirmationState(ctx, t, harness, email, token)) {
|
||||
t.Fatal("a registration after confirmation changed the verified account")
|
||||
}
|
||||
assertSingleConfirmationEvent(ctx, t, harness, email)
|
||||
harness.assertLogsHoldNoSecrets(t, email, registrationPassword, token, confirmationSecondPassword)
|
||||
})
|
||||
|
||||
t.Run("a token cannot use the C1 record of another registration version", func(t *testing.T) {
|
||||
reset(t)
|
||||
const email = "confirm.c1-version@example.com"
|
||||
token := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword)
|
||||
before := readConfirmationState(ctx, t, harness, email, token)
|
||||
if before.c1RegistrationVersion == nil || *before.c1RegistrationVersion != before.tokenRegistrationVersion {
|
||||
t.Fatal("initial C1 record is not bound to the token registration version")
|
||||
}
|
||||
hash := sha256.Sum256([]byte(token))
|
||||
harness.exec(ctx, t, `UPDATE users SET registration_version = registration_version + 1, version = version + 1, updated_at = $1 WHERE email_normalized = $2`,
|
||||
harness.clock.Now().Add(time.Second), strings.ToLower(email))
|
||||
harness.exec(ctx, t, `UPDATE email_tokens SET registration_version = registration_version + 1 WHERE token_hash = $1`, hash[:])
|
||||
stale := readConfirmationState(ctx, t, harness, email, token)
|
||||
if stale.registrationVersion != stale.tokenRegistrationVersion || stale.c1RegistrationVersion == nil ||
|
||||
*stale.c1RegistrationVersion == stale.tokenRegistrationVersion {
|
||||
t.Fatal("fixture did not create a token and account version newer than its C1 record")
|
||||
}
|
||||
|
||||
response := harness.confirm(t, token, registrationPassword, &publicOrigin)
|
||||
requireProblemStatus(t, response, http.StatusBadRequest, "verification_token_invalid")
|
||||
if response.setCookie != "" || !sameConfirmationState(stale, readConfirmationState(ctx, t, harness, email, token)) {
|
||||
t.Fatal("a token without current-version C1 changed the account or token")
|
||||
}
|
||||
harness.assertLogsHoldNoSecrets(t, email, registrationPassword, token)
|
||||
})
|
||||
|
||||
t.Run("a token without pending registration credentials cannot be confirmed", func(t *testing.T) {
|
||||
reset(t)
|
||||
const email = "confirm.no-pending@example.com"
|
||||
token := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword)
|
||||
hash := sha256.Sum256([]byte(token))
|
||||
harness.exec(ctx, t, `UPDATE email_tokens SET pending_password_hash = NULL, pending_scenario = NULL, pending_onboarding_step = NULL WHERE token_hash = $1`, hash[:])
|
||||
before := readConfirmationState(ctx, t, harness, email, token)
|
||||
if before.pendingPasswordHash != nil || before.pendingScenario != nil || before.pendingOnboardingStep != nil {
|
||||
t.Fatal("test token still has pending registration data")
|
||||
}
|
||||
|
||||
response := harness.confirm(t, token, registrationPassword, &publicOrigin)
|
||||
requireProblemStatus(t, response, http.StatusBadRequest, "verification_token_invalid")
|
||||
if response.setCookie != "" || !sameConfirmationState(before, readConfirmationState(ctx, t, harness, email, token)) {
|
||||
t.Fatal("a token without pending registration data changed the account or token")
|
||||
}
|
||||
harness.assertLogsHoldNoSecrets(t, email, registrationPassword, token)
|
||||
})
|
||||
|
||||
t.Run("confirmation rate limits refusals and reports Retry-After", func(t *testing.T) {
|
||||
reset(t)
|
||||
const email = "confirm.rate-limit@example.com"
|
||||
token := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword)
|
||||
before := readConfirmationState(ctx, t, harness, email, token)
|
||||
for range 2 {
|
||||
response := harness.confirm(t, token, confirmationWrongPassword, &publicOrigin)
|
||||
requireProblemStatus(t, response, http.StatusBadRequest, "verification_token_invalid")
|
||||
if response.retryAfter != "" || response.setCookie != "" ||
|
||||
!sameConfirmationState(before, readConfirmationState(ctx, t, harness, email, token)) {
|
||||
t.Fatal("a refused password attempt changed identity state or returned rate-limit/session headers")
|
||||
}
|
||||
}
|
||||
limited := harness.confirm(t, token, confirmationWrongPassword, &publicOrigin)
|
||||
requireProblemStatus(t, limited, http.StatusTooManyRequests, "rate_limited")
|
||||
requirePositiveRetryAfter(t, limited)
|
||||
if limited.setCookie != "" || !sameConfirmationState(before, readConfirmationState(ctx, t, harness, email, token)) {
|
||||
t.Fatal("a rate-limited confirmation changed identity state or set a cookie")
|
||||
}
|
||||
harness.assertLogsHoldNoSecrets(t, email, registrationPassword, confirmationWrongPassword, token)
|
||||
})
|
||||
|
||||
t.Run("an outbox failure rolls back token consumption and account confirmation", func(t *testing.T) {
|
||||
reset(t)
|
||||
const email = "confirm.rollback@example.com"
|
||||
token := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword)
|
||||
before := readConfirmationState(ctx, t, harness, email, token)
|
||||
installConfirmationOutboxFailure(ctx, t, harness)
|
||||
|
||||
response := harness.confirm(t, token, registrationPassword, &publicOrigin)
|
||||
requireProblemStatus(t, response, http.StatusInternalServerError, "internal")
|
||||
if response.setCookie != "" || !sameConfirmationState(before, readConfirmationState(ctx, t, harness, email, token)) {
|
||||
t.Fatal("a failed confirmation outbox insert did not roll back all account and token changes")
|
||||
}
|
||||
harness.assertLogsHoldNoSecrets(t, email, registrationPassword, token)
|
||||
})
|
||||
|
||||
t.Run("two concurrent HTTP confirmations produce one success and one event", func(t *testing.T) {
|
||||
reset(t)
|
||||
const email = "confirm.concurrent@example.com"
|
||||
token := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword)
|
||||
before := readConfirmationState(ctx, t, harness, email, token)
|
||||
responses := make([]registrationResponse, 2)
|
||||
start := make(chan struct{})
|
||||
finished := make(chan int, len(responses))
|
||||
for index := range responses {
|
||||
go func(index int) {
|
||||
<-start
|
||||
responses[index] = harness.confirm(t, token, registrationPassword, &publicOrigin)
|
||||
finished <- index
|
||||
}(index)
|
||||
}
|
||||
close(start)
|
||||
<-finished
|
||||
<-finished
|
||||
|
||||
successes := 0
|
||||
refusals := 0
|
||||
for _, response := range responses {
|
||||
switch response.status {
|
||||
case http.StatusOK:
|
||||
successes++
|
||||
requireConfirmationSuccess(t, response, "candidate", "candidate_consents")
|
||||
case http.StatusBadRequest:
|
||||
refusals++
|
||||
requireProblemStatus(t, response, http.StatusBadRequest, "verification_token_invalid")
|
||||
default:
|
||||
t.Fatalf("concurrent confirmation returned status %d, want one success and one invalid-token refusal", response.status)
|
||||
}
|
||||
if response.setCookie != "" {
|
||||
t.Fatal("confirmation set a cookie")
|
||||
}
|
||||
}
|
||||
if successes != 1 || refusals != 1 {
|
||||
t.Fatalf("concurrent confirmations had %d successes and %d refusals, want one each", successes, refusals)
|
||||
}
|
||||
after := readConfirmationState(ctx, t, harness, email, token)
|
||||
assertConfirmationApplied(t, before, after, "candidate", "candidate_consents")
|
||||
assertSingleConfirmationEvent(ctx, t, harness, email)
|
||||
if after.sessionCount != 0 {
|
||||
t.Fatalf("concurrent confirmation created %d sessions, want none", after.sessionCount)
|
||||
}
|
||||
harness.assertLogsHoldNoSecrets(t, email, registrationPassword, token)
|
||||
})
|
||||
}
|
||||
|
||||
func (harness *registrationHarness) confirm(t *testing.T, token, password string, origin *string) registrationResponse {
|
||||
t.Helper()
|
||||
headers := make(map[string]string)
|
||||
if origin != nil {
|
||||
headers["Origin"] = *origin
|
||||
}
|
||||
body, err := json.Marshal(struct {
|
||||
Token string `json:"token"`
|
||||
Password string `json:"password"`
|
||||
}{Token: token, Password: password})
|
||||
if err != nil {
|
||||
t.Fatalf("encode confirmation request: %v", err)
|
||||
}
|
||||
return harness.post(t, emailVerificationPath, string(body), headers)
|
||||
}
|
||||
|
||||
func readConfirmationState(ctx context.Context, t *testing.T, harness *registrationHarness, email, rawToken string) confirmationState {
|
||||
t.Helper()
|
||||
hash := sha256.Sum256([]byte(rawToken))
|
||||
var state confirmationState
|
||||
err := harness.pool.QueryRow(ctx, `
|
||||
SELECT account.scenario, account.onboarding_step, account.password_hash,
|
||||
account.email_verified_at, account.registration_version, account.version,
|
||||
token.registration_version, token.consumed_at, token.invalidated_at,
|
||||
token.pending_password_hash, token.pending_scenario, token.pending_onboarding_step,
|
||||
consent.registration_version,
|
||||
(SELECT count(*)::integer FROM email_tokens WHERE user_id = account.id),
|
||||
(SELECT count(*)::integer FROM sessions WHERE user_id = account.id),
|
||||
(SELECT count(*)::integer FROM outbox_events
|
||||
WHERE aggregate_id = account.id AND event_type = 'identity.email_verified')
|
||||
FROM users AS account
|
||||
JOIN email_tokens AS token ON token.user_id = account.id AND token.token_hash = $1
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT registration_version FROM consent_records
|
||||
WHERE subject_id = account.id AND purpose = 'c1' AND source = 'registration' AND revoked_at IS NULL
|
||||
ORDER BY granted_at DESC, id DESC LIMIT 1
|
||||
) AS consent ON TRUE
|
||||
WHERE account.email_normalized = $2`, hash[:], strings.ToLower(email)).Scan(
|
||||
&state.scenario, &state.onboardingStep, &state.passwordHash,
|
||||
&state.emailVerifiedAt, &state.registrationVersion, &state.userVersion,
|
||||
&state.tokenRegistrationVersion, &state.tokenConsumedAt, &state.tokenInvalidatedAt,
|
||||
&state.pendingPasswordHash, &state.pendingScenario, &state.pendingOnboardingStep,
|
||||
&state.c1RegistrationVersion, &state.tokenCount, &state.sessionCount, &state.confirmationEventCount,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("read confirmation state: %v", err)
|
||||
}
|
||||
return state
|
||||
}
|
||||
|
||||
func tokenExpiresAt(ctx context.Context, t *testing.T, harness *registrationHarness, rawToken string) time.Time {
|
||||
t.Helper()
|
||||
hash := sha256.Sum256([]byte(rawToken))
|
||||
var expiresAt time.Time
|
||||
if err := harness.pool.QueryRow(ctx, `SELECT expires_at FROM email_tokens WHERE token_hash = $1`, hash[:]).Scan(&expiresAt); err != nil {
|
||||
t.Fatalf("read emailed token deadline: %v", err)
|
||||
}
|
||||
return expiresAt
|
||||
}
|
||||
|
||||
func sameConfirmationState(left, right confirmationState) bool {
|
||||
return left.scenario == right.scenario && left.onboardingStep == right.onboardingStep &&
|
||||
left.passwordHash == right.passwordHash && sameOptionalTime(left.emailVerifiedAt, right.emailVerifiedAt) &&
|
||||
left.registrationVersion == right.registrationVersion && left.userVersion == right.userVersion &&
|
||||
left.tokenRegistrationVersion == right.tokenRegistrationVersion &&
|
||||
sameOptionalTime(left.tokenConsumedAt, right.tokenConsumedAt) &&
|
||||
sameOptionalTime(left.tokenInvalidatedAt, right.tokenInvalidatedAt) &&
|
||||
sameOptionalString(left.pendingPasswordHash, right.pendingPasswordHash) &&
|
||||
sameOptionalString(left.pendingScenario, right.pendingScenario) &&
|
||||
sameOptionalString(left.pendingOnboardingStep, right.pendingOnboardingStep) &&
|
||||
sameOptionalInt64(left.c1RegistrationVersion, right.c1RegistrationVersion) &&
|
||||
left.tokenCount == right.tokenCount && left.sessionCount == right.sessionCount &&
|
||||
left.confirmationEventCount == right.confirmationEventCount
|
||||
}
|
||||
|
||||
func assertConfirmationApplied(t *testing.T, before, after confirmationState, scenario, step string) {
|
||||
t.Helper()
|
||||
if after.scenario != scenario || after.onboardingStep != step || after.emailVerifiedAt == nil ||
|
||||
after.registrationVersion != before.tokenRegistrationVersion ||
|
||||
after.userVersion != before.userVersion+1 || after.tokenConsumedAt == nil ||
|
||||
after.tokenInvalidatedAt != nil || after.pendingPasswordHash != nil ||
|
||||
after.pendingScenario != nil || after.pendingOnboardingStep != nil ||
|
||||
after.c1RegistrationVersion == nil || *after.c1RegistrationVersion != after.tokenRegistrationVersion ||
|
||||
before.pendingPasswordHash == nil || after.passwordHash != *before.pendingPasswordHash ||
|
||||
after.tokenCount != before.tokenCount || after.sessionCount != 0 || after.confirmationEventCount != 1 {
|
||||
t.Fatal("confirmation did not atomically apply the emailed registration and consume its token")
|
||||
}
|
||||
}
|
||||
|
||||
func assertSingleConfirmationEvent(ctx context.Context, t *testing.T, harness *registrationHarness, email string) {
|
||||
t.Helper()
|
||||
var userID string
|
||||
if err := harness.pool.QueryRow(ctx, `SELECT id::text FROM users WHERE email_normalized = $1`, strings.ToLower(email)).Scan(&userID); err != nil {
|
||||
t.Fatalf("read confirmed account ID: %v", err)
|
||||
}
|
||||
var count int
|
||||
var eventType, aggregateType, aggregateID, payload string
|
||||
var aggregateVersion int64
|
||||
rows, err := harness.pool.Query(ctx, `SELECT event_type, aggregate_type, aggregate_id::text, aggregate_version, payload::text
|
||||
FROM outbox_events WHERE event_type = 'identity.email_verified' AND aggregate_id = $1`, userID)
|
||||
if err != nil {
|
||||
t.Fatalf("read confirmation outbox event: %v", err)
|
||||
}
|
||||
for rows.Next() {
|
||||
count++
|
||||
if err := rows.Scan(&eventType, &aggregateType, &aggregateID, &aggregateVersion, &payload); err != nil {
|
||||
rows.Close()
|
||||
t.Fatalf("scan confirmation outbox event: %v", err)
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
rows.Close()
|
||||
t.Fatalf("read confirmation outbox events: %v", err)
|
||||
}
|
||||
rows.Close()
|
||||
var userVersion int64
|
||||
if err := harness.pool.QueryRow(ctx, `SELECT version FROM users WHERE id = $1::uuid`, userID).Scan(&userVersion); err != nil {
|
||||
t.Fatalf("read confirmed account version: %v", err)
|
||||
}
|
||||
if count != 1 || eventType != "identity.email_verified" || aggregateType != "user" ||
|
||||
aggregateID != userID || aggregateVersion != userVersion || payload != "{}" {
|
||||
t.Fatal("confirmation outbox event count or contents do not match the confirmed account")
|
||||
}
|
||||
}
|
||||
|
||||
func requireConfirmationSuccess(t *testing.T, response registrationResponse, scenario, step string) {
|
||||
t.Helper()
|
||||
want := fmt.Sprintf(`{"email_verified":true,"scenario":%q,"onboarding_step":%q}`, scenario, step)
|
||||
mediaType, _, contentTypeErr := mime.ParseMediaType(response.contentType)
|
||||
if response.status != http.StatusOK || response.body != want || contentTypeErr != nil || mediaType != "application/json" ||
|
||||
response.setCookie != "" || response.retryAfter != "" {
|
||||
t.Fatalf("confirmation response = %d %q (content type %q, Set-Cookie present %t, Retry-After %q), want 200 %q with JSON media type and no session or rate-limit headers",
|
||||
response.status, response.body, response.contentType, response.setCookie != "", response.retryAfter, want)
|
||||
}
|
||||
}
|
||||
|
||||
func requirePositiveRetryAfter(t *testing.T, response registrationResponse) {
|
||||
t.Helper()
|
||||
seconds, err := strconv.Atoi(response.retryAfter)
|
||||
if err != nil || seconds < 1 || seconds > int(confirmationRetryWindow/time.Second) {
|
||||
t.Fatalf("Retry-After = %q, want 1 to %d seconds", response.retryAfter, int(confirmationRetryWindow/time.Second))
|
||||
}
|
||||
}
|
||||
|
||||
func installConfirmationOutboxFailure(ctx context.Context, t *testing.T, harness *registrationHarness) {
|
||||
t.Helper()
|
||||
harness.exec(ctx, t, fmt.Sprintf(`CREATE FUNCTION %s() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF NEW.event_type = 'identity.email_verified' THEN
|
||||
RAISE EXCEPTION USING ERRCODE = 'P0001', MESSAGE = 'test confirmation outbox failure';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$`, pgx.Identifier{confirmationFailureFunction}.Sanitize()))
|
||||
harness.exec(ctx, t, fmt.Sprintf(`CREATE TRIGGER %s BEFORE INSERT ON outbox_events
|
||||
FOR EACH ROW EXECUTE FUNCTION %s()`,
|
||||
pgx.Identifier{confirmationFailureTrigger}.Sanitize(),
|
||||
pgx.Identifier{confirmationFailureFunction}.Sanitize()))
|
||||
t.Cleanup(func() {
|
||||
cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), cleanupTimeout)
|
||||
defer cancel()
|
||||
if _, err := harness.pool.Exec(cleanupCtx, fmt.Sprintf(`DROP TRIGGER IF EXISTS %s ON outbox_events`,
|
||||
pgx.Identifier{confirmationFailureTrigger}.Sanitize())); err != nil {
|
||||
t.Errorf("drop confirmation outbox trigger: %v", err)
|
||||
}
|
||||
if _, err := harness.pool.Exec(cleanupCtx, fmt.Sprintf(`DROP FUNCTION IF EXISTS %s()`,
|
||||
pgx.Identifier{confirmationFailureFunction}.Sanitize())); err != nil {
|
||||
t.Errorf("drop confirmation outbox trigger function: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func stringPointer(value string) *string { return &value }
|
||||
|
||||
func sameOptionalString(left, right *string) bool {
|
||||
if left == nil || right == nil {
|
||||
return left == nil && right == nil
|
||||
}
|
||||
return *left == *right
|
||||
}
|
||||
|
||||
func sameOptionalTime(left, right *time.Time) bool {
|
||||
if left == nil || right == nil {
|
||||
return left == nil && right == nil
|
||||
}
|
||||
return left.Equal(*right)
|
||||
}
|
||||
|
||||
func sameOptionalInt64(left, right *int64) bool {
|
||||
if left == nil || right == nil {
|
||||
return left == nil && right == nil
|
||||
}
|
||||
return *left == *right
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
//go:build integration
|
||||
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
const registrationConsentMigrationName = "00016_bind_registration_consent.sql"
|
||||
|
||||
func TestRegistrationConsentMigration(t *testing.T) {
|
||||
env := bootstrap(t, postgresService)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout)
|
||||
defer cancel()
|
||||
|
||||
t.Run("binds legacy C1 rows and survives down and up", func(t *testing.T) {
|
||||
databaseURL := env.createIsolatedDatabase(ctx, t)
|
||||
migrator := newMigrator(t, databaseURL)
|
||||
pool := newPoolFor(ctx, t, databaseURL)
|
||||
if _, err := migrator.Up(ctx); err != nil {
|
||||
t.Fatalf("apply migrations before preparing legacy data: %v", err)
|
||||
}
|
||||
rolledBack, err := migrator.DownOne(ctx)
|
||||
if err != nil || rolledBack.Name != registrationConsentMigrationName {
|
||||
t.Fatalf("roll back the registration-consent migration = %+v, %v", rolledBack, err)
|
||||
}
|
||||
assertRegistrationConsentColumn(ctx, t, pool, false)
|
||||
|
||||
const userID = "018f0000-0000-7000-8000-000000000001"
|
||||
const registrationConsentID = "018f0000-0000-7000-8000-000000000002"
|
||||
const settingsConsentID = "018f0000-0000-7000-8000-000000000003"
|
||||
const otherConsentID = "018f0000-0000-7000-8000-000000000004"
|
||||
const c1SettingsVersion = "c1-migration-settings"
|
||||
createdAt := time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC)
|
||||
registrationAt := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
|
||||
settingsAt := time.Date(2026, 10, 5, 12, 0, 0, 0, time.UTC)
|
||||
seedRegistrationConsentFixture(ctx, t, pool, userID, createdAt, registrationAt, registrationConsentID, settingsConsentID, otherConsentID, c1SettingsVersion, settingsAt)
|
||||
|
||||
applied, err := migrator.Up(ctx)
|
||||
if err != nil || len(applied) != 1 || applied[0].Name != registrationConsentMigrationName {
|
||||
t.Fatalf("apply registration-consent migration = %+v, %v", applied, err)
|
||||
}
|
||||
assertConsentRegistrationVersion(ctx, t, pool, registrationConsentID, 2)
|
||||
assertConsentRegistrationVersionNull(ctx, t, pool, settingsConsentID, otherConsentID)
|
||||
|
||||
// Model a later registration after its former C1 was discarded. Old
|
||||
// binaries omit registration_version; the insert trigger must bind the
|
||||
// new C1 to the account version in effect at insert time.
|
||||
if _, err := pool.Exec(ctx, `DELETE FROM consent_records WHERE id = $1::uuid`, registrationConsentID); err != nil {
|
||||
t.Fatalf("remove the previous unverified registration C1: %v", err)
|
||||
}
|
||||
nextRegistrationAt := registrationAt.Add(24 * time.Hour)
|
||||
if _, err := pool.Exec(ctx, `UPDATE users SET registration_version = 3, last_registered_at = $2, version = version + 1, updated_at = $2 WHERE id = $1::uuid`, userID, nextRegistrationAt); err != nil {
|
||||
t.Fatalf("advance the synthetic registration: %v", err)
|
||||
}
|
||||
const compatibilityConsentID = "018f0000-0000-7000-8000-000000000005"
|
||||
insertLegacyRegistrationC1(ctx, t, pool, compatibilityConsentID, userID, "c1-2026-10-01", nextRegistrationAt)
|
||||
assertConsentRegistrationVersion(ctx, t, pool, compatibilityConsentID, 3)
|
||||
|
||||
beforeMismatch := countConsentRecords(ctx, t, pool)
|
||||
const mismatchedConsentID = "018f0000-0000-7000-8000-000000000006"
|
||||
_, err = pool.Exec(ctx, `
|
||||
INSERT INTO consent_records (
|
||||
id, subject_id, purpose, text_version, text_hash, source, granted_at, registration_version
|
||||
)
|
||||
SELECT $1::uuid, $2::uuid, text.purpose, text.version, text.body_sha256,
|
||||
'registration', $3, 2
|
||||
FROM consent_texts AS text
|
||||
WHERE text.purpose = 'c1' AND text.version = 'c1-2026-10-01'`, mismatchedConsentID, userID, nextRegistrationAt)
|
||||
assertSQLError(t, "registration C1 with an explicitly mismatched version", err, "23514", "consent_records_registration_version_matches_user")
|
||||
if countConsentRecords(ctx, t, pool) != beforeMismatch {
|
||||
t.Fatal("a registration C1 with a mismatched account version was inserted")
|
||||
}
|
||||
|
||||
_, err = pool.Exec(ctx, `UPDATE consent_records
|
||||
SET registration_version = 4, revoked_at = granted_at, revocation_source = 'support_request'
|
||||
WHERE id = $1::uuid`, compatibilityConsentID)
|
||||
assertSQLError(t, "changing a bound registration C1 version during revocation", err, "23000", "consent_records_immutable")
|
||||
var version int64
|
||||
var revokedAt *time.Time
|
||||
if err := pool.QueryRow(ctx, `SELECT registration_version, revoked_at FROM consent_records WHERE id = $1::uuid`, compatibilityConsentID).Scan(&version, &revokedAt); err != nil {
|
||||
t.Fatalf("read C1 after refused version change: %v", err)
|
||||
}
|
||||
if version != 3 || revokedAt != nil {
|
||||
t.Fatal("a refused registration C1 version change altered its version or revocation state")
|
||||
}
|
||||
|
||||
rolledBack, err = migrator.DownOne(ctx)
|
||||
if err != nil || rolledBack.Name != registrationConsentMigrationName {
|
||||
t.Fatalf("roll back registration-consent migration = %+v, %v", rolledBack, err)
|
||||
}
|
||||
assertRegistrationConsentColumn(ctx, t, pool, false)
|
||||
if countConsentRecords(ctx, t, pool) != beforeMismatch {
|
||||
t.Fatal("rolling back the registration-consent migration changed the consent ledger")
|
||||
}
|
||||
applied, err = migrator.Up(ctx)
|
||||
if err != nil || len(applied) != 1 || applied[0].Name != registrationConsentMigrationName {
|
||||
t.Fatalf("reapply registration-consent migration = %+v, %v", applied, err)
|
||||
}
|
||||
assertRegistrationConsentColumn(ctx, t, pool, true)
|
||||
assertConsentRegistrationVersion(ctx, t, pool, compatibilityConsentID, 3)
|
||||
assertConsentRegistrationVersionNull(ctx, t, pool, settingsConsentID, otherConsentID)
|
||||
})
|
||||
|
||||
t.Run("refuses stale legacy registration C1 without a partial migration", func(t *testing.T) {
|
||||
databaseURL := env.createIsolatedDatabase(ctx, t)
|
||||
migrator := newMigrator(t, databaseURL)
|
||||
pool := newPoolFor(ctx, t, databaseURL)
|
||||
if _, err := migrator.Up(ctx); err != nil {
|
||||
t.Fatalf("apply migrations before preparing stale legacy data: %v", err)
|
||||
}
|
||||
rolledBack, err := migrator.DownOne(ctx)
|
||||
if err != nil || rolledBack.Name != registrationConsentMigrationName {
|
||||
t.Fatalf("roll back the registration-consent migration = %+v, %v", rolledBack, err)
|
||||
}
|
||||
assertRegistrationConsentColumn(ctx, t, pool, false)
|
||||
|
||||
const userID = "018f0000-0000-7000-8000-000000000101"
|
||||
const consentID = "018f0000-0000-7000-8000-000000000102"
|
||||
createdAt := time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC)
|
||||
grantAt := time.Date(2026, 10, 6, 12, 0, 0, 0, time.UTC)
|
||||
lastRegisteredAt := grantAt.Add(24 * time.Hour)
|
||||
seedRegistrationMigrationUser(ctx, t, pool, userID, createdAt, lastRegisteredAt, 1)
|
||||
insertLegacyRegistrationC1(ctx, t, pool, consentID, userID, "c1-2026-10-01", grantAt)
|
||||
|
||||
if _, err := migrator.Up(ctx); err == nil {
|
||||
t.Fatal("migration accepted a registration C1 older than the account's latest registration")
|
||||
}
|
||||
assertRegistrationConsentColumn(ctx, t, pool, false)
|
||||
if countConsentRecords(ctx, t, pool) != 1 {
|
||||
t.Fatal("a failed migration partially changed the legacy consent record")
|
||||
}
|
||||
statuses, err := migrator.Status(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("read migration status after failed migration: %v", err)
|
||||
}
|
||||
for _, status := range statuses {
|
||||
if status.Name == registrationConsentMigrationName && status.Applied {
|
||||
t.Fatal("failed migration was recorded as applied")
|
||||
}
|
||||
}
|
||||
|
||||
if _, err := pool.Exec(ctx, `UPDATE users SET last_registered_at = $2, updated_at = $2 WHERE id = $1::uuid`, userID, grantAt); err != nil {
|
||||
t.Fatalf("correct the synthetic legacy registration timestamp: %v", err)
|
||||
}
|
||||
if _, err := migrator.Up(ctx); err != nil {
|
||||
t.Fatalf("migration did not succeed after the legacy data was corrected: %v", err)
|
||||
}
|
||||
assertRegistrationConsentColumn(ctx, t, pool, true)
|
||||
assertConsentRegistrationVersion(ctx, t, pool, consentID, 1)
|
||||
})
|
||||
}
|
||||
|
||||
func seedRegistrationConsentFixture(
|
||||
ctx context.Context,
|
||||
t *testing.T,
|
||||
pool *pgxpool.Pool,
|
||||
userID string,
|
||||
createdAt, registrationAt time.Time,
|
||||
registrationConsentID, settingsConsentID, otherConsentID, c1SettingsVersion string,
|
||||
settingsAt time.Time,
|
||||
) {
|
||||
t.Helper()
|
||||
seedRegistrationMigrationUser(ctx, t, pool, userID, createdAt, registrationAt, 2)
|
||||
if _, err := pool.Exec(ctx, `
|
||||
INSERT INTO consent_texts (purpose, version, body, body_sha256, kind, published_at)
|
||||
SELECT purpose, $1, body, sha256(convert_to(body, 'UTF8')), kind, $2
|
||||
FROM consent_texts WHERE purpose = 'c1' AND version = 'c1-2026-10-01'`, c1SettingsVersion, createdAt.Add(24*time.Hour)); err != nil {
|
||||
t.Fatalf("insert synthetic C1 text for a settings consent: %v", err)
|
||||
}
|
||||
insertLegacyRegistrationC1(ctx, t, pool, registrationConsentID, userID, "c1-2026-10-01", registrationAt)
|
||||
insertLegacyConsent(ctx, t, pool, settingsConsentID, userID, "c1", c1SettingsVersion, "consent_settings", settingsAt)
|
||||
insertLegacyConsent(ctx, t, pool, otherConsentID, userID, "c2", "c2-2026-10-01", "consent_settings", settingsAt)
|
||||
}
|
||||
|
||||
func seedRegistrationMigrationUser(
|
||||
ctx context.Context,
|
||||
t *testing.T,
|
||||
pool *pgxpool.Pool,
|
||||
userID string,
|
||||
createdAt, lastRegisteredAt time.Time,
|
||||
registrationVersion int64,
|
||||
) {
|
||||
t.Helper()
|
||||
const passwordHash = "$argon2id$v=19$m=1,t=1,p=1$c2FsdA$cGFzcw"
|
||||
if _, err := pool.Exec(ctx, `
|
||||
INSERT INTO users (
|
||||
id, email, email_normalized, password_hash, scenario, onboarding_step,
|
||||
registration_version, last_registered_at, version, created_at, updated_at
|
||||
) VALUES ($1::uuid, 'migration.owner@example.test', 'migration.owner@example.test', $2,
|
||||
'candidate', 'candidate_consents', $3, $4, 1, $5, $4)`,
|
||||
userID, passwordHash, registrationVersion, lastRegisteredAt, createdAt); err != nil {
|
||||
t.Fatalf("insert synthetic account before migration: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func insertLegacyRegistrationC1(ctx context.Context, t *testing.T, pool *pgxpool.Pool, consentID, userID, version string, grantedAt time.Time) {
|
||||
t.Helper()
|
||||
insertLegacyConsent(ctx, t, pool, consentID, userID, "c1", version, "registration", grantedAt)
|
||||
}
|
||||
|
||||
func insertLegacyConsent(ctx context.Context, t *testing.T, pool *pgxpool.Pool, consentID, userID, purpose, version, source string, grantedAt time.Time) {
|
||||
t.Helper()
|
||||
if _, err := pool.Exec(ctx, `
|
||||
INSERT INTO consent_records (id, subject_id, purpose, text_version, text_hash, source, granted_at)
|
||||
SELECT $1::uuid, $2::uuid, text.purpose, text.version, text.body_sha256, $5, $6
|
||||
FROM consent_texts AS text WHERE text.purpose = $3 AND text.version = $4`,
|
||||
consentID, userID, purpose, version, source, grantedAt); err != nil {
|
||||
t.Fatalf("insert synthetic legacy consent: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func assertRegistrationConsentColumn(ctx context.Context, t *testing.T, pool *pgxpool.Pool, want bool) {
|
||||
t.Helper()
|
||||
var exists bool
|
||||
if err := pool.QueryRow(ctx, `SELECT EXISTS (
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_schema = 'public' AND table_name = 'consent_records' AND column_name = 'registration_version'
|
||||
)`).Scan(&exists); err != nil {
|
||||
t.Fatalf("check registration-version column: %v", err)
|
||||
}
|
||||
if exists != want {
|
||||
t.Fatalf("registration-version column exists = %t, want %t", exists, want)
|
||||
}
|
||||
}
|
||||
|
||||
func assertConsentRegistrationVersion(ctx context.Context, t *testing.T, pool *pgxpool.Pool, consentID string, want int64) {
|
||||
t.Helper()
|
||||
var got int64
|
||||
if err := pool.QueryRow(ctx, `SELECT registration_version FROM consent_records WHERE id = $1::uuid`, consentID).Scan(&got); err != nil {
|
||||
t.Fatalf("read bound consent version: %v", err)
|
||||
}
|
||||
if got != want {
|
||||
t.Fatalf("consent registration version = %d, want %d", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func assertConsentRegistrationVersionNull(ctx context.Context, t *testing.T, pool *pgxpool.Pool, consentIDs ...string) {
|
||||
t.Helper()
|
||||
for _, consentID := range consentIDs {
|
||||
var version *int64
|
||||
if err := pool.QueryRow(ctx, `SELECT registration_version FROM consent_records WHERE id = $1::uuid`, consentID).Scan(&version); err != nil {
|
||||
t.Fatalf("read unbound consent version: %v", err)
|
||||
}
|
||||
if version != nil {
|
||||
t.Fatalf("non-registration consent has registration version %d", *version)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func countConsentRecords(ctx context.Context, t *testing.T, pool *pgxpool.Pool) int {
|
||||
t.Helper()
|
||||
var count int
|
||||
if err := pool.QueryRow(ctx, `SELECT count(*)::integer FROM consent_records`).Scan(&count); err != nil {
|
||||
t.Fatalf("count consent records: %v", err)
|
||||
}
|
||||
return count
|
||||
}
|
||||
@@ -42,6 +42,7 @@ const (
|
||||
registrationTestTimeout = 5 * time.Minute
|
||||
registrationPath = "/api/v1/identity/registrations"
|
||||
resendPath = "/api/v1/identity/email-verification-requests"
|
||||
emailVerificationPath = "/api/v1/identity/email-verifications"
|
||||
registrationPassword = "correct horse battery staple"
|
||||
registrationC1 = `{"text_version":"c1-2026-10-01","accepted":true}`
|
||||
// registrationMinInterval is long enough that one request, including the
|
||||
@@ -50,10 +51,15 @@ const (
|
||||
registrationMinInterval = 3 * time.Second
|
||||
registrationDailyLimit = 3
|
||||
registrationSecret = "integration-test-identity-key-secret-0123456789"
|
||||
registrationApplication = "registration_http"
|
||||
)
|
||||
|
||||
var (
|
||||
registrationTables = slices.Concat(mailSenderTables, usersDependentTables, []pgx.Identifier{{"idempotency_records"}})
|
||||
registrationTables = slices.Concat(
|
||||
mailSenderTables,
|
||||
usersDependentTables,
|
||||
[]pgx.Identifier{{"idempotency_records"}, {"outbox_events"}},
|
||||
)
|
||||
// verificationLinkToken finds the token in the fragment of the link of
|
||||
// the sent message.
|
||||
verificationLinkToken = regexp.MustCompile(`#token=([A-Za-z0-9_-]{32,128})`)
|
||||
@@ -77,7 +83,17 @@ type registrationHarness struct {
|
||||
|
||||
func newRegistrationHarness(ctx context.Context, t *testing.T, env *testEnvironment, clientHourlyLimit int64) *registrationHarness {
|
||||
t.Helper()
|
||||
pool := env.newPoolWithMaxConns(ctx, t, 16)
|
||||
poolConfig, err := pgxpool.ParseConfig(env.Config.DatabaseURL)
|
||||
if err != nil {
|
||||
t.Fatalf("parse bootstrap database URL: %v", err)
|
||||
}
|
||||
poolConfig.MaxConns = 16
|
||||
poolConfig.ConnConfig.RuntimeParams["application_name"] = registrationApplication
|
||||
pool, err := pgxpool.NewWithConfig(ctx, poolConfig)
|
||||
if err != nil {
|
||||
t.Fatalf("create registration PostgreSQL pool: %v", err)
|
||||
}
|
||||
t.Cleanup(pool.Close)
|
||||
// The demo policy is effective from its publication by the database clock,
|
||||
// so the application clock must not be earlier than now.
|
||||
clock := &testClock{now: time.Now().UTC().Add(time.Minute).Truncate(time.Microsecond)}
|
||||
@@ -114,16 +130,19 @@ func newRegistrationHarness(ctx context.Context, t *testing.T, env *testEnvironm
|
||||
}
|
||||
transactor := postgresadapter.NewTransactor(pool)
|
||||
identityStore := postgresadapter.NewIdentityStore(pool)
|
||||
credentials := identity.NewCredentials(hasher)
|
||||
metrics := prometheus.New()
|
||||
registration, err := identity.NewRegistration(identity.RegistrationDependencies{
|
||||
Transactor: transactor,
|
||||
ConsentTexts: postgresadapter.NewConsentStore(pool),
|
||||
Idempotency: identityStore.IdempotencyRecords(),
|
||||
Consents: consent.NewService(transactor, clock.Now),
|
||||
Credentials: identity.NewCredentials(hasher),
|
||||
Credentials: credentials,
|
||||
Mailer: notification.NewServiceMailer(notification.NewTemplateRenderer(templates), account, clock.Now),
|
||||
Limiter: env.Redis,
|
||||
Keyring: keyring,
|
||||
Clock: clock.Now,
|
||||
Metrics: metrics,
|
||||
}, identity.RegistrationSettings{
|
||||
MailMinInterval: registrationMinInterval,
|
||||
MailDailyLimit: registrationDailyLimit,
|
||||
@@ -132,11 +151,28 @@ func newRegistrationHarness(ctx context.Context, t *testing.T, env *testEnvironm
|
||||
if err != nil {
|
||||
t.Fatalf("NewRegistration() error = %v", err)
|
||||
}
|
||||
confirmation, err := identity.NewEmailConfirmation(identity.ConfirmationDependencies{
|
||||
Transactor: transactor,
|
||||
Tokens: identityStore.EmailTokens(),
|
||||
Credentials: credentials,
|
||||
Limiter: env.Redis,
|
||||
Keyring: keyring,
|
||||
Clock: clock.Now,
|
||||
Metrics: metrics,
|
||||
}, identity.ConfirmationSettings{
|
||||
TokenHourlyLimit: 2,
|
||||
ClientHourlyLimit: clientHourlyLimit,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewEmailConfirmation() error = %v", err)
|
||||
}
|
||||
|
||||
responder := problem.NewResponder(logger)
|
||||
healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second)
|
||||
handler := v1.NewHandler(healthHandler, responder, v1.WithIdentity(v1.NewIdentityHandler(registration)))
|
||||
router, err := httpadapter.NewRouter(healthHandler, handler, v1.NewDenyAllSecurity(), responder, prometheus.New(), logger, nil)
|
||||
handler := v1.NewHandler(healthHandler, responder, v1.WithIdentity(v1.NewIdentityHandler(
|
||||
registration, v1.WithEmailConfirmation(confirmation, env.Config.AppPublicURL),
|
||||
)))
|
||||
router, err := httpadapter.NewRouter(healthHandler, handler, v1.NewDenyAllSecurity(), responder, metrics, logger, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewRouter() error = %v", err)
|
||||
}
|
||||
@@ -170,6 +206,7 @@ type registrationResponse struct {
|
||||
retryAfter string
|
||||
// contentType is part of the shape that must not depend on the branch.
|
||||
contentType string
|
||||
setCookie string
|
||||
}
|
||||
|
||||
func (harness *registrationHarness) post(t *testing.T, path, body string, headers map[string]string) registrationResponse {
|
||||
@@ -186,6 +223,7 @@ func (harness *registrationHarness) post(t *testing.T, path, body string, header
|
||||
body: recorder.Body.String(),
|
||||
retryAfter: recorder.Header().Get("Retry-After"),
|
||||
contentType: recorder.Header().Get("Content-Type"),
|
||||
setCookie: recorder.Header().Get("Set-Cookie"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -242,6 +280,31 @@ func (harness *registrationHarness) drain(ctx context.Context, t *testing.T) int
|
||||
return settled
|
||||
}
|
||||
|
||||
// registerAndSendVerification follows the real registration message through
|
||||
// the local Resend receiver and returns the token from the received link.
|
||||
func (harness *registrationHarness) registerAndSendVerification(
|
||||
ctx context.Context,
|
||||
t *testing.T,
|
||||
email, scenario, password string,
|
||||
) string {
|
||||
t.Helper()
|
||||
requestCount := len(harness.fixture.Requests())
|
||||
response := harness.registerBody(t, registrationBody(email, scenario, password, registrationC1), "")
|
||||
requireAccepted(t, response)
|
||||
if settled := harness.drain(ctx, t); settled != 1 {
|
||||
t.Fatalf("settled %d deliveries, want 1", settled)
|
||||
}
|
||||
received := harness.fixture.Requests()[requestCount:]
|
||||
if len(received) != 1 || !slices.Equal(received[0].To, []string{email}) {
|
||||
t.Fatalf("fixture received %d messages for the registration, want one to the registered address", len(received))
|
||||
}
|
||||
link := verificationLinkToken.FindStringSubmatch(received[0].Text)
|
||||
if link == nil {
|
||||
t.Fatal("the received verification message has no token in its link fragment")
|
||||
}
|
||||
return link[1]
|
||||
}
|
||||
|
||||
// truncate empties the tables of the flow. CASCADE also empties tables that
|
||||
// later migrations add with a reference to users, so this suite does not
|
||||
// depend on usersDependentTables being kept up to date by other tasks.
|
||||
|
||||
@@ -594,10 +594,18 @@ func (s *Server) handleCancelMyInvitationRequest(args [1]string, argsEscaped boo
|
||||
//
|
||||
// The server looks up the token by its hash and, in one transaction, checks that it is unused, not
|
||||
// expired, and bound to the current registration version, marks it used, and marks the email verified.
|
||||
// Only one of several parallel requests with the same token succeeds. An expired token answers
|
||||
// verification_token_expired; an unknown, used, replaced, or superseded token answers
|
||||
// verification_token_invalid; neither changes anything. For both, the client offers a new link and
|
||||
// sign-in, because the address may already be verified.
|
||||
// Only one of several parallel requests with the same token succeeds. An expired token of the current
|
||||
// registration answers verification_token_expired; an unknown, used, replaced, or superseded token
|
||||
// answers verification_token_invalid, even when that token is also expired. Neither refusal changes
|
||||
// anything. For both, the client offers a new link and sign-in, because the address may already be
|
||||
// verified.
|
||||
//
|
||||
// Confirmation also requires the password chosen for the registration that issued this token. A token
|
||||
// from a replaced registration cannot apply another registration's password or scenario. The server
|
||||
// checks the password against the token's pending password hash before consuming the token, then
|
||||
// applies that token's password, scenario, and onboarding step only if the current registration's C1
|
||||
// consent matches its registration version. A wrong password or token without pending registration
|
||||
// data answers verification_token_invalid and leaves the account and token unchanged.
|
||||
//
|
||||
// A repeated confirmation with an already used token is not an idempotent 200: exactly one request may
|
||||
// succeed for a token, so the outcome of parallel requests stays unambiguous, and the next step after
|
||||
@@ -606,7 +614,8 @@ func (s *Server) handleCancelMyInvitationRequest(args [1]string, argsEscaped boo
|
||||
// Success does not start a session: the link may be opened on another device or by a mail scanner, and
|
||||
// a session must come only from the password. The response returns the scenario and the saved
|
||||
// onboarding step so the client can continue after sign-in. The operation is rate-limited and requires
|
||||
// an allowed Origin.
|
||||
// an allowed Origin. Missing Origin, the special value `null`, or an Origin other than the configured
|
||||
// public application origin answers csrf_check_failed.
|
||||
//
|
||||
// POST /api/v1/identity/email-verifications
|
||||
func (s *Server) handleConfirmEmailRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
|
||||
@@ -680,6 +689,16 @@ func (s *Server) handleConfirmEmailRequest(args [0]string, argsEscaped bool, w h
|
||||
ID: "ConfirmEmail",
|
||||
}
|
||||
)
|
||||
params, err := decodeConfirmEmailParams(args, argsEscaped, r)
|
||||
if err != nil {
|
||||
err = &ogenerrors.DecodeParamsError{
|
||||
OperationContext: opErrContext,
|
||||
Err: err,
|
||||
}
|
||||
defer recordError("DecodeParams", err)
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
var rawBody []byte
|
||||
request, rawBody, close, err := s.decodeConfirmEmailRequest(r)
|
||||
@@ -707,13 +726,18 @@ func (s *Server) handleConfirmEmailRequest(args [0]string, argsEscaped bool, w h
|
||||
OperationID: "ConfirmEmail",
|
||||
Body: request,
|
||||
RawBody: rawBody,
|
||||
Params: middleware.Parameters{},
|
||||
Raw: r,
|
||||
Params: middleware.Parameters{
|
||||
{
|
||||
Name: "Origin",
|
||||
In: "header",
|
||||
}: params.Origin,
|
||||
},
|
||||
Raw: r,
|
||||
}
|
||||
|
||||
type (
|
||||
Request = *EmailVerificationRequest
|
||||
Params = struct{}
|
||||
Params = ConfirmEmailParams
|
||||
Response = ConfirmEmailRes
|
||||
)
|
||||
response, err = middleware.HookMiddleware[
|
||||
@@ -723,14 +747,14 @@ func (s *Server) handleConfirmEmailRequest(args [0]string, argsEscaped bool, w h
|
||||
](
|
||||
m,
|
||||
mreq,
|
||||
nil,
|
||||
unpackConfirmEmailParams,
|
||||
func(ctx context.Context, request Request, params Params) (response Response, err error) {
|
||||
response, err = s.h.ConfirmEmail(ctx, request)
|
||||
response, err = s.h.ConfirmEmail(ctx, request, params)
|
||||
return response, err
|
||||
},
|
||||
)
|
||||
} else {
|
||||
response, err = s.h.ConfirmEmail(ctx, request)
|
||||
response, err = s.h.ConfirmEmail(ctx, request, params)
|
||||
}
|
||||
if err != nil {
|
||||
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
|
||||
@@ -9199,12 +9223,14 @@ func (s *Server) handleRaiseOrganizationInvitationSalaryRequest(args [2]string,
|
||||
//
|
||||
// - New email: the server creates an unverified account with the scenario and the first onboarding
|
||||
// step, records C1 with its text version and text hash, stores only the hash of a one-time
|
||||
// verification token, and queues the verification message, all in one transaction.
|
||||
// verification token plus the pending registration credentials, and queues the verification
|
||||
// message, all in one transaction.
|
||||
// - Registered but not verified: the server treats the request as a new registration of that address.
|
||||
// In one transaction it replaces the password hash, the scenario, the onboarding step, and the C1
|
||||
// record, advances the registration version, invalidates every earlier verification token, and
|
||||
// queues a message with a new token. A pre-registration with someone else's password therefore
|
||||
// never survives the address owner's own registration.
|
||||
// In one transaction it advances the registration version, replaces the C1 record, invalidates
|
||||
// every earlier verification token, and queues a message with a new token carrying the pending
|
||||
// password hash, scenario, and onboarding step. The account's saved credentials and scenario change
|
||||
// only when the address owner confirms that token with its registration password, so a
|
||||
// pre-registration with someone else's password cannot take over the account.
|
||||
// - Verified: nothing changes. The server may queue a rate-limited "you already have an account"
|
||||
// notice to the address.
|
||||
//
|
||||
|
||||
@@ -12353,10 +12353,15 @@ func (s *EmailVerificationRequest) encodeFields(e *jx.Encoder) {
|
||||
e.FieldStart("token")
|
||||
s.Token.Encode(e)
|
||||
}
|
||||
{
|
||||
e.FieldStart("password")
|
||||
e.Str(s.Password)
|
||||
}
|
||||
}
|
||||
|
||||
var jsonFieldsNameOfEmailVerificationRequest = [1]string{
|
||||
var jsonFieldsNameOfEmailVerificationRequest = [2]string{
|
||||
0: "token",
|
||||
1: "password",
|
||||
}
|
||||
|
||||
// Decode decodes EmailVerificationRequest from json.
|
||||
@@ -12378,6 +12383,18 @@ func (s *EmailVerificationRequest) Decode(d *jx.Decoder) error {
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"token\"")
|
||||
}
|
||||
case "password":
|
||||
requiredBitSet[0] |= 1 << 1
|
||||
if err := func() error {
|
||||
v, err := d.Str()
|
||||
s.Password = string(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"password\"")
|
||||
}
|
||||
default:
|
||||
return errors.Errorf("unexpected field %q", k)
|
||||
}
|
||||
@@ -12388,7 +12405,7 @@ func (s *EmailVerificationRequest) Decode(d *jx.Decoder) error {
|
||||
// Validate required fields.
|
||||
var failures []validate.FieldError
|
||||
for i, mask := range [1]uint8{
|
||||
0b00000001,
|
||||
0b00000011,
|
||||
} {
|
||||
if result := (requiredBitSet[i] & mask) ^ mask; result != 0 {
|
||||
// Mask only required fields and check equality to mask using XOR.
|
||||
|
||||
@@ -315,6 +315,98 @@ func decodeCancelMyInvitationParams(args [1]string, argsEscaped bool, r *http.Re
|
||||
return params, nil
|
||||
}
|
||||
|
||||
// ConfirmEmailParams is parameters of ConfirmEmail operation.
|
||||
type ConfirmEmailParams struct {
|
||||
// The exact configured public application origin. This optional parameter is read by the server as
|
||||
// empty when absent, so the operation answers csrf_check_failed rather than treating a missing Origin
|
||||
// as an allowed request.
|
||||
Origin OptString `json:",omitempty,omitzero"`
|
||||
}
|
||||
|
||||
func unpackConfirmEmailParams(packed middleware.Parameters) (params ConfirmEmailParams) {
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "Origin",
|
||||
In: "header",
|
||||
}
|
||||
if v, ok := packed[key]; ok {
|
||||
params.Origin = v.(OptString)
|
||||
}
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
func decodeConfirmEmailParams(args [0]string, argsEscaped bool, r *http.Request) (params ConfirmEmailParams, _ error) {
|
||||
h := uri.NewHeaderDecoder(r.Header)
|
||||
// Decode header: Origin.
|
||||
if err := func() error {
|
||||
cfg := uri.HeaderParameterDecodingConfig{
|
||||
Name: "Origin",
|
||||
Explode: false,
|
||||
}
|
||||
if err := h.HasParam(cfg); err == nil {
|
||||
if err := h.DecodeParam(cfg, func(d uri.Decoder) error {
|
||||
var paramsDotOriginVal string
|
||||
if err := func() error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToString(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
paramsDotOriginVal = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
params.Origin.SetTo(paramsDotOriginVal)
|
||||
return nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := func() error {
|
||||
if value, ok := params.Origin.Get(); ok {
|
||||
if err := func() error {
|
||||
if err := (validate.String{
|
||||
MinLength: 1,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 2048,
|
||||
MaxLengthSet: true,
|
||||
Email: false,
|
||||
Hostname: false,
|
||||
Regex: nil,
|
||||
MinNumeric: 0,
|
||||
MinNumericSet: false,
|
||||
MaxNumeric: 0,
|
||||
MaxNumericSet: false,
|
||||
}).Validate(string(value)); err != nil {
|
||||
return errors.Wrap(err, "string")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "Origin",
|
||||
In: "header",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
return params, nil
|
||||
}
|
||||
|
||||
// CreateMyAssessmentAttemptParams is parameters of CreateMyAssessmentAttempt operation.
|
||||
type CreateMyAssessmentAttemptParams struct {
|
||||
// Client-generated key that makes a retried mutating command safe; a UUID v4 is recommended. The value
|
||||
|
||||
@@ -15,7 +15,7 @@ var (
|
||||
"POST": "Content-Type",
|
||||
}
|
||||
rn7AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type",
|
||||
"POST": "Content-Type,Origin",
|
||||
}
|
||||
rn57AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key",
|
||||
|
||||
@@ -5602,10 +5602,15 @@ func (s *DirectionCode) UnmarshalText(data []byte) error {
|
||||
|
||||
type EmailAddress string
|
||||
|
||||
// Token from the email verification link.
|
||||
// One-time token copied from the verification link and the password chosen for the registration that
|
||||
// issued it. The password is never included in the link.
|
||||
// Ref: #/components/schemas/EmailVerificationRequest
|
||||
type EmailVerificationRequest struct {
|
||||
Token VerificationToken `json:"token"`
|
||||
// Password chosen for the registration that issued this token. It is sent in the request body and
|
||||
// never appears in the verification link. The server applies NFKC normalization and the login length
|
||||
// bounds, without reapplying the current new-registration blocklist.
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
// GetToken returns the value of Token.
|
||||
@@ -5613,11 +5618,21 @@ func (s *EmailVerificationRequest) GetToken() VerificationToken {
|
||||
return s.Token
|
||||
}
|
||||
|
||||
// GetPassword returns the value of Password.
|
||||
func (s *EmailVerificationRequest) GetPassword() string {
|
||||
return s.Password
|
||||
}
|
||||
|
||||
// SetToken sets the value of Token.
|
||||
func (s *EmailVerificationRequest) SetToken(val VerificationToken) {
|
||||
s.Token = val
|
||||
}
|
||||
|
||||
// SetPassword sets the value of Password.
|
||||
func (s *EmailVerificationRequest) SetPassword(val string) {
|
||||
s.Password = val
|
||||
}
|
||||
|
||||
// Address that should receive a new verification link.
|
||||
// Ref: #/components/schemas/EmailVerificationResendRequest
|
||||
type EmailVerificationResendRequest struct {
|
||||
|
||||
@@ -107,10 +107,18 @@ type Handler interface {
|
||||
//
|
||||
// The server looks up the token by its hash and, in one transaction, checks that it is unused, not
|
||||
// expired, and bound to the current registration version, marks it used, and marks the email verified.
|
||||
// Only one of several parallel requests with the same token succeeds. An expired token answers
|
||||
// verification_token_expired; an unknown, used, replaced, or superseded token answers
|
||||
// verification_token_invalid; neither changes anything. For both, the client offers a new link and
|
||||
// sign-in, because the address may already be verified.
|
||||
// Only one of several parallel requests with the same token succeeds. An expired token of the current
|
||||
// registration answers verification_token_expired; an unknown, used, replaced, or superseded token
|
||||
// answers verification_token_invalid, even when that token is also expired. Neither refusal changes
|
||||
// anything. For both, the client offers a new link and sign-in, because the address may already be
|
||||
// verified.
|
||||
//
|
||||
// Confirmation also requires the password chosen for the registration that issued this token. A token
|
||||
// from a replaced registration cannot apply another registration's password or scenario. The server
|
||||
// checks the password against the token's pending password hash before consuming the token, then
|
||||
// applies that token's password, scenario, and onboarding step only if the current registration's C1
|
||||
// consent matches its registration version. A wrong password or token without pending registration
|
||||
// data answers verification_token_invalid and leaves the account and token unchanged.
|
||||
//
|
||||
// A repeated confirmation with an already used token is not an idempotent 200: exactly one request may
|
||||
// succeed for a token, so the outcome of parallel requests stays unambiguous, and the next step after
|
||||
@@ -119,10 +127,11 @@ type Handler interface {
|
||||
// Success does not start a session: the link may be opened on another device or by a mail scanner, and
|
||||
// a session must come only from the password. The response returns the scenario and the saved
|
||||
// onboarding step so the client can continue after sign-in. The operation is rate-limited and requires
|
||||
// an allowed Origin.
|
||||
// an allowed Origin. Missing Origin, the special value `null`, or an Origin other than the configured
|
||||
// public application origin answers csrf_check_failed.
|
||||
//
|
||||
// POST /api/v1/identity/email-verifications
|
||||
ConfirmEmail(ctx context.Context, req *EmailVerificationRequest) (ConfirmEmailRes, error)
|
||||
ConfirmEmail(ctx context.Context, req *EmailVerificationRequest, params ConfirmEmailParams) (ConfirmEmailRes, error)
|
||||
// CreateMyAssessmentAttempt implements CreateMyAssessmentAttempt operation.
|
||||
//
|
||||
// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token,
|
||||
@@ -1150,12 +1159,14 @@ type Handler interface {
|
||||
//
|
||||
// - New email: the server creates an unverified account with the scenario and the first onboarding
|
||||
// step, records C1 with its text version and text hash, stores only the hash of a one-time
|
||||
// verification token, and queues the verification message, all in one transaction.
|
||||
// verification token plus the pending registration credentials, and queues the verification
|
||||
// message, all in one transaction.
|
||||
// - Registered but not verified: the server treats the request as a new registration of that address.
|
||||
// In one transaction it replaces the password hash, the scenario, the onboarding step, and the C1
|
||||
// record, advances the registration version, invalidates every earlier verification token, and
|
||||
// queues a message with a new token. A pre-registration with someone else's password therefore
|
||||
// never survives the address owner's own registration.
|
||||
// In one transaction it advances the registration version, replaces the C1 record, invalidates
|
||||
// every earlier verification token, and queues a message with a new token carrying the pending
|
||||
// password hash, scenario, and onboarding step. The account's saved credentials and scenario change
|
||||
// only when the address owner confirms that token with its registration password, so a
|
||||
// pre-registration with someone else's password cannot take over the account.
|
||||
// - Verified: nothing changes. The server may queue a rate-limited "you already have an account"
|
||||
// notice to the address.
|
||||
//
|
||||
|
||||
@@ -118,10 +118,18 @@ func (UnimplementedHandler) CancelMyInvitation(ctx context.Context, req *Invitat
|
||||
//
|
||||
// The server looks up the token by its hash and, in one transaction, checks that it is unused, not
|
||||
// expired, and bound to the current registration version, marks it used, and marks the email verified.
|
||||
// Only one of several parallel requests with the same token succeeds. An expired token answers
|
||||
// verification_token_expired; an unknown, used, replaced, or superseded token answers
|
||||
// verification_token_invalid; neither changes anything. For both, the client offers a new link and
|
||||
// sign-in, because the address may already be verified.
|
||||
// Only one of several parallel requests with the same token succeeds. An expired token of the current
|
||||
// registration answers verification_token_expired; an unknown, used, replaced, or superseded token
|
||||
// answers verification_token_invalid, even when that token is also expired. Neither refusal changes
|
||||
// anything. For both, the client offers a new link and sign-in, because the address may already be
|
||||
// verified.
|
||||
//
|
||||
// Confirmation also requires the password chosen for the registration that issued this token. A token
|
||||
// from a replaced registration cannot apply another registration's password or scenario. The server
|
||||
// checks the password against the token's pending password hash before consuming the token, then
|
||||
// applies that token's password, scenario, and onboarding step only if the current registration's C1
|
||||
// consent matches its registration version. A wrong password or token without pending registration
|
||||
// data answers verification_token_invalid and leaves the account and token unchanged.
|
||||
//
|
||||
// A repeated confirmation with an already used token is not an idempotent 200: exactly one request may
|
||||
// succeed for a token, so the outcome of parallel requests stays unambiguous, and the next step after
|
||||
@@ -130,10 +138,11 @@ func (UnimplementedHandler) CancelMyInvitation(ctx context.Context, req *Invitat
|
||||
// Success does not start a session: the link may be opened on another device or by a mail scanner, and
|
||||
// a session must come only from the password. The response returns the scenario and the saved
|
||||
// onboarding step so the client can continue after sign-in. The operation is rate-limited and requires
|
||||
// an allowed Origin.
|
||||
// an allowed Origin. Missing Origin, the special value `null`, or an Origin other than the configured
|
||||
// public application origin answers csrf_check_failed.
|
||||
//
|
||||
// POST /api/v1/identity/email-verifications
|
||||
func (UnimplementedHandler) ConfirmEmail(ctx context.Context, req *EmailVerificationRequest) (r ConfirmEmailRes, _ error) {
|
||||
func (UnimplementedHandler) ConfirmEmail(ctx context.Context, req *EmailVerificationRequest, params ConfirmEmailParams) (r ConfirmEmailRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
@@ -1278,12 +1287,14 @@ func (UnimplementedHandler) RaiseOrganizationInvitationSalary(ctx context.Contex
|
||||
//
|
||||
// - New email: the server creates an unverified account with the scenario and the first onboarding
|
||||
// step, records C1 with its text version and text hash, stores only the hash of a one-time
|
||||
// verification token, and queues the verification message, all in one transaction.
|
||||
// verification token plus the pending registration credentials, and queues the verification
|
||||
// message, all in one transaction.
|
||||
// - Registered but not verified: the server treats the request as a new registration of that address.
|
||||
// In one transaction it replaces the password hash, the scenario, the onboarding step, and the C1
|
||||
// record, advances the registration version, invalidates every earlier verification token, and
|
||||
// queues a message with a new token. A pre-registration with someone else's password therefore
|
||||
// never survives the address owner's own registration.
|
||||
// In one transaction it advances the registration version, replaces the C1 record, invalidates
|
||||
// every earlier verification token, and queues a message with a new token carrying the pending
|
||||
// password hash, scenario, and onboarding step. The account's saved credentials and scenario change
|
||||
// only when the address owner confirms that token with its registration password, so a
|
||||
// pre-registration with someone else's password cannot take over the account.
|
||||
// - Verified: nothing changes. The server may queue a rate-limited "you already have an account"
|
||||
// notice to the address.
|
||||
//
|
||||
|
||||
@@ -5871,6 +5871,29 @@ func (s *EmailVerificationRequest) Validate() error {
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := (validate.String{
|
||||
MinLength: 1,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 128,
|
||||
MaxLengthSet: true,
|
||||
Email: false,
|
||||
Hostname: false,
|
||||
Regex: nil,
|
||||
MinNumeric: 0,
|
||||
MinNumericSet: false,
|
||||
MaxNumeric: 0,
|
||||
MaxNumericSet: false,
|
||||
}).Validate(string(s.Password)); err != nil {
|
||||
return errors.Wrap(err, "string")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "password",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
package httpadapter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
"lincodex/backend/internal/adapter/primary/http/problem"
|
||||
v1 "lincodex/backend/internal/adapter/primary/http/v1"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/usecase/identity"
|
||||
)
|
||||
|
||||
const confirmationPath = "/api/v1/identity/email-verifications"
|
||||
|
||||
type scriptedConfirmation struct {
|
||||
err error
|
||||
command identity.ConfirmCommand
|
||||
result identity.ConfirmationResult
|
||||
calls int
|
||||
}
|
||||
|
||||
func (confirmation *scriptedConfirmation) Confirm(_ context.Context, command identity.ConfirmCommand) (identity.ConfirmationResult, error) {
|
||||
confirmation.calls++
|
||||
confirmation.command = command
|
||||
return confirmation.result, confirmation.err
|
||||
}
|
||||
|
||||
func newConfirmationRouter(t *testing.T, confirmation v1.EmailConfirmation) http.Handler {
|
||||
t.Helper()
|
||||
logger := slog.New(slog.DiscardHandler)
|
||||
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
|
||||
identityHandler := v1.NewIdentityHandler(nil, v1.WithEmailConfirmation(confirmation, "https://app.example"))
|
||||
handler := v1.NewHandler(healthHandler, problem.NewResponder(logger), v1.WithIdentity(identityHandler))
|
||||
return newTestRouterWithAPI(t, healthHandler, handler, logger)
|
||||
}
|
||||
|
||||
func TestConfirmEmailRequiresConfiguredOriginBeforeUsecase(t *testing.T) {
|
||||
confirmation := &scriptedConfirmation{}
|
||||
router := newConfirmationRouter(t, confirmation)
|
||||
body := `{"token":"` + strings.Repeat("A", 64) + `","password":"correct horse battery staple"}`
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
origin string
|
||||
set bool
|
||||
}{
|
||||
{name: "missing"},
|
||||
{name: "null", origin: "null", set: true},
|
||||
{name: "foreign", origin: "https://foreign.example", set: true},
|
||||
{name: "same host with different port", origin: "https://app.example:443", set: true},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
before := confirmation.calls
|
||||
headers := map[string]string{}
|
||||
if test.set {
|
||||
headers["Origin"] = test.origin
|
||||
}
|
||||
response := serveIdentityRequest(t, router, identityRequest{
|
||||
method: http.MethodPost, path: confirmationPath, body: body, headers: headers,
|
||||
})
|
||||
requireProblem(t, response, http.StatusForbidden, api.ProblemCodeCsrfCheckFailed)
|
||||
if confirmation.calls != before {
|
||||
t.Fatal("confirmation usecase ran before the origin check")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfirmEmailPassesRequestAndReturnsSavedDestination(t *testing.T) {
|
||||
confirmation := &scriptedConfirmation{result: identity.ConfirmationResult{
|
||||
Scenario: domain.ScenarioCandidate,
|
||||
OnboardingStep: domain.OnboardingStepCandidateProfile,
|
||||
}}
|
||||
router := newConfirmationRouter(t, confirmation)
|
||||
token := strings.Repeat("A", 64)
|
||||
password := `correct "quoted" horse battery staple`
|
||||
requestBody, err := json.Marshal(struct {
|
||||
Token string `json:"token"`
|
||||
Password string `json:"password"`
|
||||
}{Token: token, Password: password})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
response := serveIdentityRequest(t, router, identityRequest{
|
||||
method: http.MethodPost,
|
||||
path: confirmationPath,
|
||||
body: string(requestBody),
|
||||
headers: map[string]string{"Origin": "https://app.example"},
|
||||
})
|
||||
if response.Code != http.StatusOK || response.Header().Get("Set-Cookie") != "" {
|
||||
t.Fatalf("response = %d, Set-Cookie %q, body %s", response.Code, response.Header().Get("Set-Cookie"), response.Body.String())
|
||||
}
|
||||
var result map[string]any
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &result); err != nil {
|
||||
t.Fatalf("decode response: %v", err)
|
||||
}
|
||||
if result["email_verified"] != true || result["scenario"] != "candidate" || result["onboarding_step"] != "candidate_profile" {
|
||||
t.Fatalf("response body = %v", result)
|
||||
}
|
||||
if confirmation.calls != 1 || confirmation.command.Token != token || confirmation.command.Password != password || confirmation.command.ClientKey == "" {
|
||||
t.Fatalf("confirmation call = %d, command %+v", confirmation.calls, confirmation.command)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfirmEmailRequiresPassword(t *testing.T) {
|
||||
confirmation := &scriptedConfirmation{}
|
||||
response := serveIdentityRequest(t, newConfirmationRouter(t, confirmation), identityRequest{
|
||||
method: http.MethodPost,
|
||||
path: confirmationPath,
|
||||
body: `{"token":"` + strings.Repeat("A", 64) + `"}`,
|
||||
headers: map[string]string{"Origin": "https://app.example"},
|
||||
})
|
||||
requireProblem(t, response, http.StatusBadRequest, api.ProblemCodeValidationFailed)
|
||||
if confirmation.calls != 0 {
|
||||
t.Fatal("confirmation usecase ran without the required registration password")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfirmEmailMapsExpectedUsecaseFailures(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
err error
|
||||
statusCode int
|
||||
code api.ProblemCode
|
||||
retryAfter string
|
||||
}{
|
||||
{name: "invalid token", err: identity.ErrVerificationTokenInvalid, statusCode: http.StatusBadRequest, code: api.ProblemCodeVerificationTokenInvalid},
|
||||
{name: "expired token", err: identity.ErrVerificationTokenExpired, statusCode: http.StatusBadRequest, code: api.ProblemCodeVerificationTokenExpired},
|
||||
{name: "limited", err: &identity.RateLimitedError{RetryAfter: 1500 * time.Millisecond}, statusCode: http.StatusTooManyRequests, code: api.ProblemCodeRateLimited, retryAfter: "2"},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
confirmation := &scriptedConfirmation{err: test.err}
|
||||
response := serveIdentityRequest(t, newConfirmationRouter(t, confirmation), identityRequest{
|
||||
method: http.MethodPost,
|
||||
path: confirmationPath,
|
||||
body: `{"token":"` + strings.Repeat("A", 64) + `","password":"correct horse battery staple"}`,
|
||||
headers: map[string]string{"Origin": "https://app.example"},
|
||||
})
|
||||
requireProblem(t, response, test.statusCode, test.code)
|
||||
if got := response.Header().Get("Retry-After"); got != test.retryAfter {
|
||||
t.Fatalf("Retry-After = %q, want %q", got, test.retryAfter)
|
||||
}
|
||||
if confirmation.calls != 1 {
|
||||
t.Fatalf("confirmation calls = %d, want 1", confirmation.calls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfirmEmailDoesNotConvertUnexpectedUsecaseErrors(t *testing.T) {
|
||||
confirmation := &scriptedConfirmation{err: errors.New("storage unavailable")}
|
||||
response := serveIdentityRequest(t, newConfirmationRouter(t, confirmation), identityRequest{
|
||||
method: http.MethodPost,
|
||||
path: confirmationPath,
|
||||
body: `{"token":"` + strings.Repeat("A", 64) + `","password":"correct horse battery staple"}`,
|
||||
headers: map[string]string{"Origin": "https://app.example"},
|
||||
})
|
||||
requireProblem(t, response, http.StatusInternalServerError, api.ProblemCodeInternal)
|
||||
if strings.Contains(response.Body.String(), "storage unavailable") {
|
||||
t.Fatal("internal error text leaked into the response")
|
||||
}
|
||||
}
|
||||
@@ -180,7 +180,7 @@ func TestIdentityOperationsBeforeImplementation(t *testing.T) {
|
||||
name: "public email confirmation",
|
||||
request: identityRequest{
|
||||
method: http.MethodPost, path: "/api/v1/identity/email-verifications",
|
||||
body: `{"token":"q3Zt9b2Kx7LmP4vR8sW1yC6nD0fH5jA2eG9uI3oT7kE"}`,
|
||||
body: `{"token":"q3Zt9b2Kx7LmP4vR8sW1yC6nD0fH5jA2eG9uI3oT7kE","password":"correct horse battery staple"}`,
|
||||
},
|
||||
statusCode: http.StatusNotImplemented,
|
||||
code: api.ProblemCodeNotImplemented,
|
||||
|
||||
@@ -81,6 +81,17 @@ func (handler *Handler) ResendEmailVerification(
|
||||
return handler.identity.ResendEmailVerification(ctx, request)
|
||||
}
|
||||
|
||||
func (handler *Handler) ConfirmEmail(
|
||||
ctx context.Context,
|
||||
request *api.EmailVerificationRequest,
|
||||
params api.ConfirmEmailParams,
|
||||
) (api.ConfirmEmailRes, error) {
|
||||
if handler.identity == nil || handler.identity.confirmation == nil {
|
||||
return handler.UnimplementedHandler.ConfirmEmail(ctx, request, params)
|
||||
}
|
||||
return handler.identity.ConfirmEmail(ctx, request, params)
|
||||
}
|
||||
|
||||
// NewError implements api.Handler for errors returned by operations.
|
||||
func (handler *Handler) NewError(ctx context.Context, err error) *api.ProblemStatusCode {
|
||||
return handler.problems.HandlerError(ctx, err)
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"math"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
@@ -19,14 +20,37 @@ type AccountRegistration interface {
|
||||
ResendVerification(ctx context.Context, command identity.ResendCommand) error
|
||||
}
|
||||
|
||||
// IdentityHandler serves the anonymous registration operations. Both answer
|
||||
// the same neutral 202 whatever the state of the address; see the contract.
|
||||
type IdentityHandler struct {
|
||||
registration AccountRegistration
|
||||
// EmailConfirmation is what IdentityHandler needs from the confirmation usecase.
|
||||
type EmailConfirmation interface {
|
||||
Confirm(ctx context.Context, command identity.ConfirmCommand) (identity.ConfirmationResult, error)
|
||||
}
|
||||
|
||||
func NewIdentityHandler(registration AccountRegistration) *IdentityHandler {
|
||||
return &IdentityHandler{registration: registration}
|
||||
// IdentityHandlerOption configures an optional identity operation.
|
||||
type IdentityHandlerOption func(*IdentityHandler)
|
||||
|
||||
// IdentityHandler serves anonymous registration, resend, and confirmation
|
||||
// operations.
|
||||
type IdentityHandler struct {
|
||||
registration AccountRegistration
|
||||
confirmation EmailConfirmation
|
||||
confirmationOrigin string
|
||||
}
|
||||
|
||||
func NewIdentityHandler(registration AccountRegistration, options ...IdentityHandlerOption) *IdentityHandler {
|
||||
handler := &IdentityHandler{registration: registration}
|
||||
for _, option := range options {
|
||||
option(handler)
|
||||
}
|
||||
return handler
|
||||
}
|
||||
|
||||
// WithEmailConfirmation serves ConfirmEmail and compares Origin with the
|
||||
// configured public application origin. The request Host is never trusted.
|
||||
func WithEmailConfirmation(confirmation EmailConfirmation, publicOrigin string) IdentityHandlerOption {
|
||||
return func(handler *IdentityHandler) {
|
||||
handler.confirmation = confirmation
|
||||
handler.confirmationOrigin = publicOrigin
|
||||
}
|
||||
}
|
||||
|
||||
func (handler *IdentityHandler) RegisterAccount(
|
||||
@@ -60,6 +84,9 @@ func (handler *IdentityHandler) ResendEmailVerification(
|
||||
ctx context.Context,
|
||||
request *api.EmailVerificationResendRequest,
|
||||
) (api.ResendEmailVerificationRes, error) {
|
||||
if handler.registration == nil {
|
||||
return nil, errors.New("IdentityHandler.ResendEmailVerification - registration is not configured")
|
||||
}
|
||||
err := handler.registration.ResendVerification(ctx, identity.ResendCommand{
|
||||
Email: string(request.Email),
|
||||
ClientKey: clientKey(ctx),
|
||||
@@ -76,6 +103,42 @@ func (handler *IdentityHandler) ResendEmailVerification(
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func (handler *IdentityHandler) ConfirmEmail(
|
||||
ctx context.Context,
|
||||
request *api.EmailVerificationRequest,
|
||||
params api.ConfirmEmailParams,
|
||||
) (api.ConfirmEmailRes, error) {
|
||||
if handler.confirmation == nil {
|
||||
return nil, errors.New("IdentityHandler.ConfirmEmail - confirmation is not configured")
|
||||
}
|
||||
origin, ok := params.Origin.Get()
|
||||
if !ok || strings.TrimSpace(origin) == "" || origin != handler.confirmationOrigin {
|
||||
return (*api.ConfirmEmailForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil
|
||||
}
|
||||
|
||||
result, err := handler.confirmation.Confirm(ctx, identity.ConfirmCommand{
|
||||
Token: string(request.Token),
|
||||
Password: request.Password,
|
||||
ClientKey: clientKey(ctx),
|
||||
})
|
||||
switch {
|
||||
case err == nil:
|
||||
return &api.EmailVerificationResult{
|
||||
EmailVerified: api.EmailVerificationResultEmailVerifiedTrue,
|
||||
Scenario: api.AccountScenario(result.Scenario),
|
||||
OnboardingStep: api.OnboardingStep(result.OnboardingStep),
|
||||
}, nil
|
||||
case errors.Is(err, identity.ErrVerificationTokenInvalid):
|
||||
return (*api.ConfirmEmailBadRequest)(&problem.New(ctx, api.ProblemCodeVerificationTokenInvalid).Response), nil
|
||||
case errors.Is(err, identity.ErrVerificationTokenExpired):
|
||||
return (*api.ConfirmEmailBadRequest)(&problem.New(ctx, api.ProblemCodeVerificationTokenExpired).Response), nil
|
||||
}
|
||||
if limited, ok := rateLimited(ctx, err); ok {
|
||||
return limited, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func accepted() *api.IdentityRequestAccepted {
|
||||
return &api.IdentityRequestAccepted{Status: api.IdentityRequestAcceptedStatusAccepted}
|
||||
}
|
||||
|
||||
@@ -144,7 +144,11 @@ func (ledger consentLedger) Grant(ctx context.Context, grant domain.ConsentGrant
|
||||
TextVersion: string(grant.TextVersion()),
|
||||
TextHash: hash[:],
|
||||
Source: string(grant.Source()),
|
||||
GrantedAt: pgTime(grant.GrantedAt()),
|
||||
RegistrationVersion: pgtype.Int8{
|
||||
Int64: grant.RegistrationVersion(),
|
||||
Valid: grant.RegistrationVersion() > 0,
|
||||
},
|
||||
GrantedAt: pgTime(grant.GrantedAt()),
|
||||
})
|
||||
if err == nil {
|
||||
record, err := consentRecordFromRow(consentRecordRow(row))
|
||||
@@ -251,6 +255,25 @@ func (ledger consentLedger) Current(ctx context.Context, subjectID uuid.UUID, pu
|
||||
return consentRecordFromRow(consentRecordRow(row))
|
||||
}
|
||||
|
||||
func (ledger consentLedger) LockRegistration(
|
||||
ctx context.Context,
|
||||
subjectID uuid.UUID,
|
||||
registrationVersion int64,
|
||||
) (domain.ConsentRecord, error) {
|
||||
const location = "consentLedger.LockRegistration"
|
||||
if subjectID == uuid.Nil || registrationVersion <= 0 {
|
||||
return domain.ConsentRecord{}, fmt.Errorf("%s - subject and registration version must be set: %w", location, domain.ErrInvalidConsent)
|
||||
}
|
||||
row, err := ledger.queries.LockRegistrationConsentRecord(ctx, sqlc.LockRegistrationConsentRecordParams{
|
||||
SubjectID: pgUUID(subjectID),
|
||||
RegistrationVersion: pgtype.Int8{Int64: registrationVersion, Valid: true},
|
||||
})
|
||||
if err != nil {
|
||||
return domain.ConsentRecord{}, fmt.Errorf("%s - lock registration C1: %w", location, mapConsentNoRows(err, outbound.ErrConsentNotFound))
|
||||
}
|
||||
return consentRecordFromRow(consentRecordRow(row))
|
||||
}
|
||||
|
||||
func (ledger consentLedger) CurrentContact(ctx context.Context, subjectID, organizationID uuid.UUID) ([]domain.ConsentRecord, error) {
|
||||
rows, err := ledger.queries.ListCurrentContactConsentRecords(ctx, sqlc.ListCurrentContactConsentRecordsParams{
|
||||
SubjectID: pgUUID(subjectID),
|
||||
@@ -312,6 +335,7 @@ type consentRecordRow struct {
|
||||
TextVersion string
|
||||
TextHash []byte
|
||||
Source string
|
||||
RegistrationVersion pgtype.Int8
|
||||
OrganizationID pgtype.UUID
|
||||
OrganizationName pgtype.Text
|
||||
FieldSet []string
|
||||
@@ -331,6 +355,7 @@ func consentRecordFromRow(row consentRecordRow) (domain.ConsentRecord, error) {
|
||||
TextVersion: row.TextVersion,
|
||||
TextHash: row.TextHash,
|
||||
Source: row.Source,
|
||||
RegistrationVersion: optionalConsentRegistrationVersion(row.RegistrationVersion),
|
||||
State: row.State,
|
||||
GrantedAt: row.GrantedAt.Time,
|
||||
RevokedAt: optionalTime(row.RevokedAt),
|
||||
@@ -347,6 +372,13 @@ func consentRecordFromRow(row consentRecordRow) (domain.ConsentRecord, error) {
|
||||
return record, nil
|
||||
}
|
||||
|
||||
func optionalConsentRegistrationVersion(value pgtype.Int8) int64 {
|
||||
if !value.Valid {
|
||||
return 0
|
||||
}
|
||||
return value.Int64
|
||||
}
|
||||
|
||||
func consentRecordsFromRows[Row any](rows []Row, convert func(Row) consentRecordRow) ([]domain.ConsentRecord, error) {
|
||||
records := make([]domain.ConsentRecord, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
|
||||
@@ -152,14 +152,15 @@ func TestConsentRecordFromRowMapsNullableScope(t *testing.T) {
|
||||
}
|
||||
|
||||
personalData, err := consentRecordFromRow(consentRecordRow{
|
||||
ID: pgUUID(uuid.Must(uuid.NewV7())),
|
||||
SubjectID: pgUUID(subject),
|
||||
Purpose: "c1",
|
||||
TextVersion: "c1-2026-10-01",
|
||||
TextHash: hash[:],
|
||||
Source: "registration",
|
||||
GrantedAt: pgTime(grantedAt),
|
||||
State: "active",
|
||||
ID: pgUUID(uuid.Must(uuid.NewV7())),
|
||||
SubjectID: pgUUID(subject),
|
||||
Purpose: "c1",
|
||||
TextVersion: "c1-2026-10-01",
|
||||
TextHash: hash[:],
|
||||
Source: "registration",
|
||||
RegistrationVersion: pgtype.Int8{Int64: 1, Valid: true},
|
||||
GrantedAt: pgTime(grantedAt),
|
||||
State: "active",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("consentRecordFromRow(C1) error = %v", err)
|
||||
|
||||
@@ -274,6 +274,34 @@ func (repository userRepository) MarkEmailVerified(
|
||||
return userFromRow(row)
|
||||
}
|
||||
|
||||
func (repository userRepository) ConfirmEmail(
|
||||
ctx context.Context,
|
||||
id uuid.UUID,
|
||||
registrationVersion int64,
|
||||
pending domain.PendingRegistration,
|
||||
at time.Time,
|
||||
) (domain.User, error) {
|
||||
const location = "userRepository.ConfirmEmail"
|
||||
if err := requireTime(location, at, domain.ErrInvalidUser); err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
if pending.PasswordHash.IsZero() || !pending.Scenario.AllowsStep(pending.OnboardingStep) {
|
||||
return domain.User{}, fmt.Errorf("%s - pending registration was not built by domain.NewPendingRegistration: %w", location, domain.ErrInvalidUser)
|
||||
}
|
||||
row, err := repository.queries.ConfirmUserEmail(ctx, sqlc.ConfirmUserEmailParams{
|
||||
ID: pgUUID(id),
|
||||
RegistrationVersion: registrationVersion,
|
||||
PasswordHash: pending.PasswordHash.PHC(),
|
||||
Scenario: string(pending.Scenario),
|
||||
OnboardingStep: string(pending.OnboardingStep),
|
||||
VerifiedAt: pgTime(at),
|
||||
})
|
||||
if err != nil {
|
||||
return domain.User{}, fmt.Errorf("%s - apply pending registration: %w", location, mapNoRows(err, outbound.ErrUserVersionConflict))
|
||||
}
|
||||
return userFromRow(row)
|
||||
}
|
||||
|
||||
func (repository userRepository) DeleteUnverifiedRegisteredBefore(ctx context.Context, cutoff time.Time, limit int32) (int64, error) {
|
||||
if err := requireTime("userRepository.DeleteUnverifiedRegisteredBefore", cutoff, domain.ErrInvalidUser); err != nil {
|
||||
return 0, err
|
||||
@@ -342,6 +370,35 @@ type emailTokenRepository struct {
|
||||
queries *sqlc.Queries
|
||||
}
|
||||
|
||||
func (repository emailTokenRepository) FindByHash(
|
||||
ctx context.Context,
|
||||
hash domain.SecretTokenHash,
|
||||
purpose domain.EmailTokenPurpose,
|
||||
) (domain.EmailToken, error) {
|
||||
const location = "emailTokenRepository.FindByHash"
|
||||
if hash.IsZero() {
|
||||
return domain.EmailToken{}, fmt.Errorf("%s - token hash must be set: %w", location, domain.ErrInvalidEmailToken)
|
||||
}
|
||||
if _, err := domain.ParseEmailTokenPurpose(string(purpose)); err != nil {
|
||||
return domain.EmailToken{}, fmt.Errorf("%s - validate purpose: %w", location, err)
|
||||
}
|
||||
row, err := repository.queries.GetEmailTokenByHash(ctx, sqlc.GetEmailTokenByHashParams{
|
||||
TokenHash: hash[:],
|
||||
Purpose: string(purpose),
|
||||
})
|
||||
if err != nil {
|
||||
return domain.EmailToken{}, fmt.Errorf("%s - select email token: %w", location, mapNoRows(err, outbound.ErrEmailTokenNotFound))
|
||||
}
|
||||
owner, err := repository.queries.GetUserByID(ctx, row.UserID)
|
||||
if err != nil {
|
||||
return domain.EmailToken{}, fmt.Errorf("%s - read token owner: %w", location, mapNoRows(err, outbound.ErrEmailTokenInvalidated))
|
||||
}
|
||||
if owner.RegistrationVersion != row.RegistrationVersion {
|
||||
return domain.EmailToken{}, fmt.Errorf("%s - token belongs to an earlier registration: %w", location, outbound.ErrEmailTokenInvalidated)
|
||||
}
|
||||
return emailTokenFromRow(row)
|
||||
}
|
||||
|
||||
func (repository emailTokenRepository) Insert(ctx context.Context, token domain.EmailToken) error {
|
||||
if token.ID == uuid.Nil || token.TokenHash.IsZero() {
|
||||
return fmt.Errorf("emailTokenRepository.Insert - token was not built by domain.NewEmailToken: %w", domain.ErrInvalidEmailToken)
|
||||
@@ -445,7 +502,7 @@ func (repository emailTokenRepository) Consume(
|
||||
ConsumedAt: pgTime(at),
|
||||
})
|
||||
if err == nil {
|
||||
return emailTokenFromRow(row)
|
||||
return emailTokenFromRow(sqlc.EmailToken(row))
|
||||
}
|
||||
if !errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.EmailToken{}, fmt.Errorf("emailTokenRepository.Consume - update email token: %w", mapIdentityError(err))
|
||||
|
||||
@@ -52,6 +52,7 @@ SELECT
|
||||
text_version,
|
||||
text_hash,
|
||||
source,
|
||||
registration_version,
|
||||
organization_id,
|
||||
organization_name,
|
||||
field_set,
|
||||
@@ -81,6 +82,7 @@ type GetContactConsentRecordByInvitationRow struct {
|
||||
TextVersion string
|
||||
TextHash []byte
|
||||
Source string
|
||||
RegistrationVersion pgtype.Int8
|
||||
OrganizationID pgtype.UUID
|
||||
OrganizationName pgtype.Text
|
||||
FieldSet []string
|
||||
@@ -102,6 +104,7 @@ func (q *Queries) GetContactConsentRecordByInvitation(ctx context.Context, arg G
|
||||
&i.TextVersion,
|
||||
&i.TextHash,
|
||||
&i.Source,
|
||||
&i.RegistrationVersion,
|
||||
&i.OrganizationID,
|
||||
&i.OrganizationName,
|
||||
&i.FieldSet,
|
||||
@@ -123,6 +126,7 @@ SELECT
|
||||
text_version,
|
||||
text_hash,
|
||||
source,
|
||||
registration_version,
|
||||
organization_id,
|
||||
organization_name,
|
||||
field_set,
|
||||
@@ -154,6 +158,7 @@ type GetCurrentConsentRecordRow struct {
|
||||
TextVersion string
|
||||
TextHash []byte
|
||||
Source string
|
||||
RegistrationVersion pgtype.Int8
|
||||
OrganizationID pgtype.UUID
|
||||
OrganizationName pgtype.Text
|
||||
FieldSet []string
|
||||
@@ -176,6 +181,7 @@ func (q *Queries) GetCurrentConsentRecord(ctx context.Context, arg GetCurrentCon
|
||||
&i.TextVersion,
|
||||
&i.TextHash,
|
||||
&i.Source,
|
||||
&i.RegistrationVersion,
|
||||
&i.OrganizationID,
|
||||
&i.OrganizationName,
|
||||
&i.FieldSet,
|
||||
@@ -234,6 +240,7 @@ SELECT
|
||||
record.text_version,
|
||||
record.text_hash,
|
||||
record.source,
|
||||
record.registration_version,
|
||||
record.organization_id,
|
||||
record.organization_name,
|
||||
record.field_set,
|
||||
@@ -277,6 +284,7 @@ type GetUnrevokedConsentRecordByVersionRow struct {
|
||||
TextVersion string
|
||||
TextHash []byte
|
||||
Source string
|
||||
RegistrationVersion pgtype.Int8
|
||||
OrganizationID pgtype.UUID
|
||||
OrganizationName pgtype.Text
|
||||
FieldSet []string
|
||||
@@ -298,6 +306,7 @@ func (q *Queries) GetUnrevokedConsentRecordByVersion(ctx context.Context, arg Ge
|
||||
&i.TextVersion,
|
||||
&i.TextHash,
|
||||
&i.Source,
|
||||
&i.RegistrationVersion,
|
||||
&i.OrganizationID,
|
||||
&i.OrganizationName,
|
||||
&i.FieldSet,
|
||||
@@ -319,6 +328,7 @@ INSERT INTO consent_records (
|
||||
text_version,
|
||||
text_hash,
|
||||
source,
|
||||
registration_version,
|
||||
granted_at
|
||||
) VALUES (
|
||||
$1,
|
||||
@@ -327,7 +337,8 @@ INSERT INTO consent_records (
|
||||
$4,
|
||||
$5,
|
||||
$6,
|
||||
$7
|
||||
$7::bigint,
|
||||
$8
|
||||
)
|
||||
ON CONFLICT (subject_id, purpose, text_version)
|
||||
WHERE revoked_at IS NULL AND purpose <> 'c4'
|
||||
@@ -339,6 +350,7 @@ RETURNING
|
||||
text_version,
|
||||
text_hash,
|
||||
source,
|
||||
registration_version,
|
||||
organization_id,
|
||||
organization_name,
|
||||
field_set,
|
||||
@@ -364,13 +376,14 @@ RETURNING
|
||||
`
|
||||
|
||||
type InsertConsentRecordParams struct {
|
||||
ID pgtype.UUID
|
||||
SubjectID pgtype.UUID
|
||||
Purpose string
|
||||
TextVersion string
|
||||
TextHash []byte
|
||||
Source string
|
||||
GrantedAt pgtype.Timestamptz
|
||||
ID pgtype.UUID
|
||||
SubjectID pgtype.UUID
|
||||
Purpose string
|
||||
TextVersion string
|
||||
TextHash []byte
|
||||
Source string
|
||||
RegistrationVersion pgtype.Int8
|
||||
GrantedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type InsertConsentRecordRow struct {
|
||||
@@ -380,6 +393,7 @@ type InsertConsentRecordRow struct {
|
||||
TextVersion string
|
||||
TextHash []byte
|
||||
Source string
|
||||
RegistrationVersion pgtype.Int8
|
||||
OrganizationID pgtype.UUID
|
||||
OrganizationName pgtype.Text
|
||||
FieldSet []string
|
||||
@@ -402,6 +416,7 @@ func (q *Queries) InsertConsentRecord(ctx context.Context, arg InsertConsentReco
|
||||
arg.TextVersion,
|
||||
arg.TextHash,
|
||||
arg.Source,
|
||||
arg.RegistrationVersion,
|
||||
arg.GrantedAt,
|
||||
)
|
||||
var i InsertConsentRecordRow
|
||||
@@ -412,6 +427,7 @@ func (q *Queries) InsertConsentRecord(ctx context.Context, arg InsertConsentReco
|
||||
&i.TextVersion,
|
||||
&i.TextHash,
|
||||
&i.Source,
|
||||
&i.RegistrationVersion,
|
||||
&i.OrganizationID,
|
||||
&i.OrganizationName,
|
||||
&i.FieldSet,
|
||||
@@ -433,6 +449,7 @@ INSERT INTO consent_records (
|
||||
text_version,
|
||||
text_hash,
|
||||
source,
|
||||
registration_version,
|
||||
organization_id,
|
||||
organization_name,
|
||||
field_set,
|
||||
@@ -446,6 +463,7 @@ INSERT INTO consent_records (
|
||||
$3,
|
||||
$4,
|
||||
'invitation_acceptance',
|
||||
NULL,
|
||||
$5,
|
||||
$6,
|
||||
$7::text [],
|
||||
@@ -462,6 +480,7 @@ RETURNING
|
||||
text_version,
|
||||
text_hash,
|
||||
source,
|
||||
registration_version,
|
||||
organization_id,
|
||||
organization_name,
|
||||
field_set,
|
||||
@@ -493,6 +512,7 @@ type InsertContactConsentRecordRow struct {
|
||||
TextVersion string
|
||||
TextHash []byte
|
||||
Source string
|
||||
RegistrationVersion pgtype.Int8
|
||||
OrganizationID pgtype.UUID
|
||||
OrganizationName pgtype.Text
|
||||
FieldSet []string
|
||||
@@ -528,6 +548,7 @@ func (q *Queries) InsertContactConsentRecord(ctx context.Context, arg InsertCont
|
||||
&i.TextVersion,
|
||||
&i.TextHash,
|
||||
&i.Source,
|
||||
&i.RegistrationVersion,
|
||||
&i.OrganizationID,
|
||||
&i.OrganizationName,
|
||||
&i.FieldSet,
|
||||
@@ -550,6 +571,7 @@ WITH ledger AS (
|
||||
record.text_version,
|
||||
record.text_hash,
|
||||
record.source,
|
||||
record.registration_version,
|
||||
record.organization_id,
|
||||
record.organization_name,
|
||||
record.field_set,
|
||||
@@ -584,6 +606,7 @@ SELECT
|
||||
ledger.text_version,
|
||||
ledger.text_hash,
|
||||
ledger.source,
|
||||
ledger.registration_version,
|
||||
ledger.organization_id,
|
||||
ledger.organization_name,
|
||||
ledger.field_set,
|
||||
@@ -622,6 +645,7 @@ type ListConsentRecordsRow struct {
|
||||
TextVersion string
|
||||
TextHash []byte
|
||||
Source string
|
||||
RegistrationVersion pgtype.Int8
|
||||
OrganizationID pgtype.UUID
|
||||
OrganizationName pgtype.Text
|
||||
FieldSet []string
|
||||
@@ -662,6 +686,7 @@ func (q *Queries) ListConsentRecords(ctx context.Context, arg ListConsentRecords
|
||||
&i.TextVersion,
|
||||
&i.TextHash,
|
||||
&i.Source,
|
||||
&i.RegistrationVersion,
|
||||
&i.OrganizationID,
|
||||
&i.OrganizationName,
|
||||
&i.FieldSet,
|
||||
@@ -690,6 +715,7 @@ SELECT
|
||||
text_version,
|
||||
text_hash,
|
||||
source,
|
||||
registration_version,
|
||||
organization_id,
|
||||
organization_name,
|
||||
field_set,
|
||||
@@ -720,6 +746,7 @@ type ListCurrentContactConsentRecordsRow struct {
|
||||
TextVersion string
|
||||
TextHash []byte
|
||||
Source string
|
||||
RegistrationVersion pgtype.Int8
|
||||
OrganizationID pgtype.UUID
|
||||
OrganizationName pgtype.Text
|
||||
FieldSet []string
|
||||
@@ -747,6 +774,7 @@ func (q *Queries) ListCurrentContactConsentRecords(ctx context.Context, arg List
|
||||
&i.TextVersion,
|
||||
&i.TextHash,
|
||||
&i.Source,
|
||||
&i.RegistrationVersion,
|
||||
&i.OrganizationID,
|
||||
&i.OrganizationName,
|
||||
&i.FieldSet,
|
||||
@@ -767,6 +795,83 @@ func (q *Queries) ListCurrentContactConsentRecords(ctx context.Context, arg List
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const lockRegistrationConsentRecord = `-- name: LockRegistrationConsentRecord :one
|
||||
SELECT
|
||||
id,
|
||||
subject_id,
|
||||
purpose,
|
||||
text_version,
|
||||
text_hash,
|
||||
source,
|
||||
registration_version,
|
||||
organization_id,
|
||||
organization_name,
|
||||
field_set,
|
||||
invitation_id,
|
||||
invitation_terms_version,
|
||||
granted_at,
|
||||
revoked_at,
|
||||
revocation_source,
|
||||
'active'::text AS state
|
||||
FROM consent_records
|
||||
WHERE
|
||||
subject_id = $1
|
||||
AND purpose = 'c1'
|
||||
AND source = 'registration'
|
||||
AND registration_version = $2
|
||||
AND revoked_at IS NULL
|
||||
FOR UPDATE
|
||||
`
|
||||
|
||||
type LockRegistrationConsentRecordParams struct {
|
||||
SubjectID pgtype.UUID
|
||||
RegistrationVersion pgtype.Int8
|
||||
}
|
||||
|
||||
type LockRegistrationConsentRecordRow struct {
|
||||
ID pgtype.UUID
|
||||
SubjectID pgtype.UUID
|
||||
Purpose string
|
||||
TextVersion string
|
||||
TextHash []byte
|
||||
Source string
|
||||
RegistrationVersion pgtype.Int8
|
||||
OrganizationID pgtype.UUID
|
||||
OrganizationName pgtype.Text
|
||||
FieldSet []string
|
||||
InvitationID pgtype.UUID
|
||||
InvitationTermsVersion pgtype.Int8
|
||||
GrantedAt pgtype.Timestamptz
|
||||
RevokedAt pgtype.Timestamptz
|
||||
RevocationSource pgtype.Text
|
||||
State string
|
||||
}
|
||||
|
||||
// Locks the active registration C1 while its pending registration is applied.
|
||||
func (q *Queries) LockRegistrationConsentRecord(ctx context.Context, arg LockRegistrationConsentRecordParams) (LockRegistrationConsentRecordRow, error) {
|
||||
row := q.db.QueryRow(ctx, lockRegistrationConsentRecord, arg.SubjectID, arg.RegistrationVersion)
|
||||
var i LockRegistrationConsentRecordRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.SubjectID,
|
||||
&i.Purpose,
|
||||
&i.TextVersion,
|
||||
&i.TextHash,
|
||||
&i.Source,
|
||||
&i.RegistrationVersion,
|
||||
&i.OrganizationID,
|
||||
&i.OrganizationName,
|
||||
&i.FieldSet,
|
||||
&i.InvitationID,
|
||||
&i.InvitationTermsVersion,
|
||||
&i.GrantedAt,
|
||||
&i.RevokedAt,
|
||||
&i.RevocationSource,
|
||||
&i.State,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const revokeConsentRecords = `-- name: RevokeConsentRecords :many
|
||||
UPDATE consent_records
|
||||
SET
|
||||
@@ -784,6 +889,7 @@ RETURNING
|
||||
text_version,
|
||||
text_hash,
|
||||
source,
|
||||
registration_version,
|
||||
organization_id,
|
||||
organization_name,
|
||||
field_set,
|
||||
@@ -809,6 +915,7 @@ type RevokeConsentRecordsRow struct {
|
||||
TextVersion string
|
||||
TextHash []byte
|
||||
Source string
|
||||
RegistrationVersion pgtype.Int8
|
||||
OrganizationID pgtype.UUID
|
||||
OrganizationName pgtype.Text
|
||||
FieldSet []string
|
||||
@@ -844,6 +951,7 @@ func (q *Queries) RevokeConsentRecords(ctx context.Context, arg RevokeConsentRec
|
||||
&i.TextVersion,
|
||||
&i.TextHash,
|
||||
&i.Source,
|
||||
&i.RegistrationVersion,
|
||||
&i.OrganizationID,
|
||||
&i.OrganizationName,
|
||||
&i.FieldSet,
|
||||
@@ -881,6 +989,7 @@ RETURNING
|
||||
text_version,
|
||||
text_hash,
|
||||
source,
|
||||
registration_version,
|
||||
organization_id,
|
||||
organization_name,
|
||||
field_set,
|
||||
@@ -906,6 +1015,7 @@ type RevokeContactConsentRecordsRow struct {
|
||||
TextVersion string
|
||||
TextHash []byte
|
||||
Source string
|
||||
RegistrationVersion pgtype.Int8
|
||||
OrganizationID pgtype.UUID
|
||||
OrganizationName pgtype.Text
|
||||
FieldSet []string
|
||||
@@ -940,6 +1050,7 @@ func (q *Queries) RevokeContactConsentRecords(ctx context.Context, arg RevokeCon
|
||||
&i.TextVersion,
|
||||
&i.TextHash,
|
||||
&i.Source,
|
||||
&i.RegistrationVersion,
|
||||
&i.OrganizationID,
|
||||
&i.OrganizationName,
|
||||
&i.FieldSet,
|
||||
|
||||
@@ -109,37 +109,146 @@ func (q *Queries) AdvanceUserRegistration(ctx context.Context, arg AdvanceUserRe
|
||||
return i, err
|
||||
}
|
||||
|
||||
const consumeEmailToken = `-- name: ConsumeEmailToken :one
|
||||
UPDATE email_tokens AS token
|
||||
SET consumed_at = $1
|
||||
FROM users AS owner
|
||||
const confirmUserEmail = `-- name: ConfirmUserEmail :one
|
||||
UPDATE users
|
||||
SET
|
||||
password_hash = $1,
|
||||
scenario = $2,
|
||||
onboarding_step = $3,
|
||||
email_verified_at = $4,
|
||||
updated_at = $4,
|
||||
version = version + 1
|
||||
WHERE
|
||||
token.token_hash = $2
|
||||
AND token.purpose = $3
|
||||
AND token.consumed_at IS NULL
|
||||
AND token.invalidated_at IS NULL
|
||||
AND token.expires_at > $1
|
||||
AND owner.id = token.user_id
|
||||
AND owner.registration_version = token.registration_version
|
||||
id = $5
|
||||
AND registration_version = $6
|
||||
AND email_verified_at IS NULL
|
||||
RETURNING
|
||||
token.id,
|
||||
token.user_id,
|
||||
token.purpose,
|
||||
token.token_hash,
|
||||
token.registration_version,
|
||||
token.created_at,
|
||||
token.expires_at,
|
||||
token.consumed_at,
|
||||
token.invalidated_at,
|
||||
token.pending_password_hash,
|
||||
token.pending_scenario,
|
||||
token.pending_onboarding_step
|
||||
id,
|
||||
email,
|
||||
email_normalized,
|
||||
password_hash,
|
||||
scenario,
|
||||
onboarding_step,
|
||||
email_verified_at,
|
||||
registration_version,
|
||||
last_registered_at,
|
||||
version,
|
||||
created_at,
|
||||
updated_at
|
||||
`
|
||||
|
||||
type ConfirmUserEmailParams struct {
|
||||
PasswordHash string
|
||||
Scenario string
|
||||
OnboardingStep string
|
||||
VerifiedAt pgtype.Timestamptz
|
||||
ID pgtype.UUID
|
||||
RegistrationVersion int64
|
||||
}
|
||||
|
||||
// Applies the registration carried by its token and verifies the address in
|
||||
// one optimistic update. The caller holds the token lock and checks the
|
||||
// matching C1 in the same transaction.
|
||||
func (q *Queries) ConfirmUserEmail(ctx context.Context, arg ConfirmUserEmailParams) (User, error) {
|
||||
row := q.db.QueryRow(ctx, confirmUserEmail,
|
||||
arg.PasswordHash,
|
||||
arg.Scenario,
|
||||
arg.OnboardingStep,
|
||||
arg.VerifiedAt,
|
||||
arg.ID,
|
||||
arg.RegistrationVersion,
|
||||
)
|
||||
var i User
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Email,
|
||||
&i.EmailNormalized,
|
||||
&i.PasswordHash,
|
||||
&i.Scenario,
|
||||
&i.OnboardingStep,
|
||||
&i.EmailVerifiedAt,
|
||||
&i.RegistrationVersion,
|
||||
&i.LastRegisteredAt,
|
||||
&i.Version,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const consumeEmailToken = `-- name: ConsumeEmailToken :one
|
||||
WITH candidate AS MATERIALIZED (
|
||||
SELECT
|
||||
token.id,
|
||||
token.user_id,
|
||||
token.purpose,
|
||||
token.token_hash,
|
||||
token.registration_version,
|
||||
token.created_at,
|
||||
token.expires_at,
|
||||
token.pending_password_hash,
|
||||
token.pending_scenario,
|
||||
token.pending_onboarding_step
|
||||
FROM email_tokens AS token
|
||||
INNER JOIN users AS owner ON owner.id = token.user_id
|
||||
WHERE
|
||||
token.token_hash = $1
|
||||
AND token.purpose = $2
|
||||
AND token.consumed_at IS NULL
|
||||
AND token.invalidated_at IS NULL
|
||||
AND token.expires_at > $3
|
||||
AND owner.registration_version = token.registration_version
|
||||
FOR UPDATE OF token
|
||||
),
|
||||
|
||||
consumed AS (
|
||||
UPDATE email_tokens AS token
|
||||
SET
|
||||
consumed_at = $3,
|
||||
pending_password_hash = NULL,
|
||||
pending_scenario = NULL,
|
||||
pending_onboarding_step = NULL
|
||||
FROM candidate
|
||||
WHERE token.id = candidate.id
|
||||
RETURNING token.id, token.consumed_at, token.invalidated_at
|
||||
)
|
||||
|
||||
SELECT
|
||||
candidate.id,
|
||||
candidate.user_id,
|
||||
candidate.purpose,
|
||||
candidate.token_hash,
|
||||
candidate.registration_version,
|
||||
candidate.created_at,
|
||||
candidate.expires_at,
|
||||
consumed.consumed_at,
|
||||
consumed.invalidated_at,
|
||||
candidate.pending_password_hash,
|
||||
candidate.pending_scenario,
|
||||
candidate.pending_onboarding_step
|
||||
FROM candidate
|
||||
INNER JOIN consumed ON consumed.id = candidate.id
|
||||
`
|
||||
|
||||
type ConsumeEmailTokenParams struct {
|
||||
ConsumedAt pgtype.Timestamptz
|
||||
TokenHash []byte
|
||||
Purpose string
|
||||
ConsumedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type ConsumeEmailTokenRow struct {
|
||||
ID pgtype.UUID
|
||||
UserID pgtype.UUID
|
||||
Purpose string
|
||||
TokenHash []byte
|
||||
RegistrationVersion int64
|
||||
CreatedAt pgtype.Timestamptz
|
||||
ExpiresAt pgtype.Timestamptz
|
||||
ConsumedAt pgtype.Timestamptz
|
||||
InvalidatedAt pgtype.Timestamptz
|
||||
PendingPasswordHash pgtype.Text
|
||||
PendingScenario pgtype.Text
|
||||
PendingOnboardingStep pgtype.Text
|
||||
}
|
||||
|
||||
// Consumes a token in one statement. Concurrent callers queue on the token
|
||||
@@ -151,9 +260,9 @@ type ConsumeEmailTokenParams struct {
|
||||
// The confirmation guarantee therefore needs MarkUserEmailVerified with the
|
||||
// returned registration version in the same transaction, rolled back when it
|
||||
// matches no row.
|
||||
func (q *Queries) ConsumeEmailToken(ctx context.Context, arg ConsumeEmailTokenParams) (EmailToken, error) {
|
||||
row := q.db.QueryRow(ctx, consumeEmailToken, arg.ConsumedAt, arg.TokenHash, arg.Purpose)
|
||||
var i EmailToken
|
||||
func (q *Queries) ConsumeEmailToken(ctx context.Context, arg ConsumeEmailTokenParams) (ConsumeEmailTokenRow, error) {
|
||||
row := q.db.QueryRow(ctx, consumeEmailToken, arg.TokenHash, arg.Purpose, arg.ConsumedAt)
|
||||
var i ConsumeEmailTokenRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.UserID,
|
||||
@@ -339,6 +448,52 @@ func (q *Queries) GetActiveSessionByTokenHash(ctx context.Context, arg GetActive
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getEmailTokenByHash = `-- name: GetEmailTokenByHash :one
|
||||
SELECT
|
||||
id,
|
||||
user_id,
|
||||
purpose,
|
||||
token_hash,
|
||||
registration_version,
|
||||
created_at,
|
||||
expires_at,
|
||||
consumed_at,
|
||||
invalidated_at,
|
||||
pending_password_hash,
|
||||
pending_scenario,
|
||||
pending_onboarding_step
|
||||
FROM email_tokens
|
||||
WHERE token_hash = $1
|
||||
AND purpose = $2
|
||||
`
|
||||
|
||||
type GetEmailTokenByHashParams struct {
|
||||
TokenHash []byte
|
||||
Purpose string
|
||||
}
|
||||
|
||||
// Reads a token before password verification; Consume rechecks it in the
|
||||
// confirmation transaction and clears pending credentials when it succeeds.
|
||||
func (q *Queries) GetEmailTokenByHash(ctx context.Context, arg GetEmailTokenByHashParams) (EmailToken, error) {
|
||||
row := q.db.QueryRow(ctx, getEmailTokenByHash, arg.TokenHash, arg.Purpose)
|
||||
var i EmailToken
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.UserID,
|
||||
&i.Purpose,
|
||||
&i.TokenHash,
|
||||
&i.RegistrationVersion,
|
||||
&i.CreatedAt,
|
||||
&i.ExpiresAt,
|
||||
&i.ConsumedAt,
|
||||
&i.InvalidatedAt,
|
||||
&i.PendingPasswordHash,
|
||||
&i.PendingScenario,
|
||||
&i.PendingOnboardingStep,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getEmailTokenState = `-- name: GetEmailTokenState :one
|
||||
SELECT
|
||||
token.consumed_at,
|
||||
|
||||
@@ -126,6 +126,7 @@ type ConsentRecord struct {
|
||||
GrantedAt pgtype.Timestamptz
|
||||
RevokedAt pgtype.Timestamptz
|
||||
RevocationSource pgtype.Text
|
||||
RegistrationVersion pgtype.Int8
|
||||
}
|
||||
|
||||
type ConsentText struct {
|
||||
|
||||
@@ -78,6 +78,10 @@ type Querier interface {
|
||||
// the lease owner and the attempt, so a worker that lost its lease cannot
|
||||
// complete the job.
|
||||
CompleteScheduledJob(ctx context.Context, arg CompleteScheduledJobParams) (int64, error)
|
||||
// Applies the registration carried by its token and verifies the address in
|
||||
// one optimistic update. The caller holds the token lock and checks the
|
||||
// matching C1 in the same transaction.
|
||||
ConfirmUserEmail(ctx context.Context, arg ConfirmUserEmailParams) (User, error)
|
||||
// Consumes a token in one statement. Concurrent callers queue on the token
|
||||
// row lock; under READ COMMITTED each waiter re-checks the WHERE clause
|
||||
// against the committed row, so exactly one of them updates it. The join
|
||||
@@ -87,7 +91,7 @@ type Querier interface {
|
||||
// The confirmation guarantee therefore needs MarkUserEmailVerified with the
|
||||
// returned registration version in the same transaction, rolled back when it
|
||||
// matches no row.
|
||||
ConsumeEmailToken(ctx context.Context, arg ConsumeEmailTokenParams) (EmailToken, error)
|
||||
ConsumeEmailToken(ctx context.Context, arg ConsumeEmailTokenParams) (ConsumeEmailTokenRow, error)
|
||||
// Counts the hiding records of one candidate for the settings read.
|
||||
CountCandidateHiddenOrganizations(ctx context.Context, userID pgtype.UUID) (int64, error)
|
||||
// Counts the families of a category that have at least one published
|
||||
@@ -171,6 +175,9 @@ type Querier interface {
|
||||
// version published after it. The unique (policy_key, version) index serves
|
||||
// the backward scan.
|
||||
GetEffectivePolicyVersion(ctx context.Context, arg GetEffectivePolicyVersionParams) (PolicyVersion, error)
|
||||
// Reads a token before password verification; Consume rechecks it in the
|
||||
// confirmation transaction and clears pending credentials when it succeeds.
|
||||
GetEmailTokenByHash(ctx context.Context, arg GetEmailTokenByHashParams) (EmailToken, error)
|
||||
// Explains why ConsumeEmailToken matched no row.
|
||||
GetEmailTokenState(ctx context.Context, arg GetEmailTokenStateParams) (GetEmailTokenStateRow, error)
|
||||
GetLatestAssessmentFamily(ctx context.Context, familyKey string) (AssessmentFamily, error)
|
||||
@@ -397,6 +404,8 @@ type Querier interface {
|
||||
// because aggregate writers check the expected version, so scanning without a
|
||||
// position watermark cannot overtake an earlier version.
|
||||
LockPendingOutboxEvents(ctx context.Context, batchLimit int32) ([]LockPendingOutboxEventsRow, error)
|
||||
// Locks the active registration C1 while its pending registration is applied.
|
||||
LockRegistrationConsentRecord(ctx context.Context, arg LockRegistrationConsentRecordParams) (LockRegistrationConsentRecordRow, error)
|
||||
// Notes that the first request of a claimed delivery is about to start, by the
|
||||
// database clock, and clears the count of worker failures: the claim and the
|
||||
// preparation succeeded, so the failures are no longer consecutive. The provider keeps the idempotency key for a window counted
|
||||
|
||||
@@ -39,9 +39,8 @@ type mailMetrics struct {
|
||||
// senderCancelled counts deliveries that the sending worker ended without
|
||||
// sending, by cancel reason, a closed set from the domain.
|
||||
senderCancelled *client.CounterVec
|
||||
// identityRateLimited counts registration and resend requests that the
|
||||
// identity limiter refused, by scope: address or client. No address,
|
||||
// email, or key is ever a label.
|
||||
// identityRateLimited counts identity requests the limiter refused, by
|
||||
// scope: address, client, or token. No address, email, or key is a label.
|
||||
identityRateLimited *client.CounterVec
|
||||
}
|
||||
|
||||
@@ -95,7 +94,7 @@ func newMailMetrics() mailMetrics {
|
||||
}, []string{"reason"}),
|
||||
identityRateLimited: client.NewCounterVec(client.CounterOpts{
|
||||
Name: "lincodex_identity_rate_limit_refusals_total",
|
||||
Help: "Registration and verification resend requests refused with 429 by the identity limiter, by scope: address (per email address) or client (per network address). A large share of client refusals hints at a broken proxy chain, where many clients share one address; a rise of address refusals can mean a targeted lockout of one address.",
|
||||
Help: "Identity requests refused with 429 by the limiter, by scope: address (per email address), client (per network address), or token (per verification token). A large share of client refusals hints at a broken proxy chain, where many clients share one address; a rise of address refusals can mean a targeted lockout of one address.",
|
||||
}, []string{"scope"}),
|
||||
senderRunning: client.NewGauge(client.GaugeOpts{
|
||||
Name: "lincodex_mail_sender_running",
|
||||
@@ -107,7 +106,7 @@ func newMailMetrics() mailMetrics {
|
||||
for _, reason := range domain.DeliveryCancelReasons() {
|
||||
metrics.senderCancelled.WithLabelValues(string(reason))
|
||||
}
|
||||
for _, scope := range []string{IdentityScopeAddress, IdentityScopeClient} {
|
||||
for _, scope := range []string{IdentityScopeAddress, IdentityScopeClient, IdentityScopeToken} {
|
||||
metrics.identityRateLimited.WithLabelValues(scope)
|
||||
}
|
||||
return metrics
|
||||
@@ -117,12 +116,13 @@ func newMailMetrics() mailMetrics {
|
||||
const (
|
||||
IdentityScopeAddress = "address"
|
||||
IdentityScopeClient = "client"
|
||||
IdentityScopeToken = "token"
|
||||
)
|
||||
|
||||
// ObserveIdentityRateLimited counts one refused identity request. A scope
|
||||
// outside the two known ones counts as address, so the label stays bounded.
|
||||
// outside the known scopes counts as address, so the label stays bounded.
|
||||
func (metrics *Metrics) ObserveIdentityRateLimited(scope string) {
|
||||
if scope != IdentityScopeClient {
|
||||
if scope != IdentityScopeClient && scope != IdentityScopeToken {
|
||||
scope = IdentityScopeAddress
|
||||
}
|
||||
metrics.mail.identityRateLimited.WithLabelValues(scope).Inc()
|
||||
|
||||
@@ -44,10 +44,12 @@ func TestIdentityRateLimitRefusalsAreCountedByBoundedScope(t *testing.T) {
|
||||
metrics := New()
|
||||
metrics.ObserveIdentityRateLimited(IdentityScopeClient)
|
||||
metrics.ObserveIdentityRateLimited(IdentityScopeAddress)
|
||||
metrics.ObserveIdentityRateLimited(IdentityScopeToken)
|
||||
metrics.ObserveIdentityRateLimited("203.0.113.9")
|
||||
body := scrape(t, metrics)
|
||||
requireSeries(t, body, `lincodex_identity_rate_limit_refusals_total{scope="client"} 1`)
|
||||
requireSeries(t, body, `lincodex_identity_rate_limit_refusals_total{scope="address"} 2`)
|
||||
requireSeries(t, body, `lincodex_identity_rate_limit_refusals_total{scope="token"} 1`)
|
||||
if strings.Contains(body, "203.0.113.9") {
|
||||
t.Fatal("an unknown scope became a label value")
|
||||
}
|
||||
|
||||
@@ -72,12 +72,14 @@ func newIdentityHandler(
|
||||
return nil, nil, fmt.Errorf("bootstrap.newIdentityHandler - create pool: %w", err)
|
||||
}
|
||||
transactor := postgres.NewTransactor(pool)
|
||||
store := postgres.NewIdentityStore(pool)
|
||||
credentials := identity.NewCredentials(hasher)
|
||||
registration, err := identity.NewRegistration(identity.RegistrationDependencies{
|
||||
Transactor: transactor,
|
||||
ConsentTexts: postgres.NewConsentStore(pool),
|
||||
Idempotency: postgres.NewIdentityStore(pool).IdempotencyRecords(),
|
||||
Idempotency: store.IdempotencyRecords(),
|
||||
Consents: consent.NewService(transactor, time.Now),
|
||||
Credentials: identity.NewCredentials(hasher),
|
||||
Credentials: credentials,
|
||||
Mailer: notification.NewServiceMailer(notification.NewTemplateRenderer(renderer), account, time.Now),
|
||||
Limiter: cache,
|
||||
Keyring: keyring,
|
||||
@@ -92,9 +94,25 @@ func newIdentityHandler(
|
||||
pool.Close()
|
||||
return nil, nil, fmt.Errorf("bootstrap.newIdentityHandler - create registration: %w", err)
|
||||
}
|
||||
confirmation, err := identity.NewEmailConfirmation(identity.ConfirmationDependencies{
|
||||
Transactor: transactor,
|
||||
Tokens: store.EmailTokens(),
|
||||
Credentials: credentials,
|
||||
Limiter: cache,
|
||||
Keyring: keyring,
|
||||
Clock: time.Now,
|
||||
Metrics: metrics,
|
||||
}, identity.ConfirmationSettings{
|
||||
TokenHourlyLimit: identity.DefaultTokenHourlyLimit,
|
||||
ClientHourlyLimit: int64(settings.IdentityClientHourlyLimit),
|
||||
})
|
||||
if err != nil {
|
||||
pool.Close()
|
||||
return nil, nil, fmt.Errorf("bootstrap.newIdentityHandler - create confirmation: %w", err)
|
||||
}
|
||||
// The HTTP server stops before this cleanup runs, so no request uses the
|
||||
// pool while it closes.
|
||||
return v1.NewIdentityHandler(registration), pool.Close, nil
|
||||
return v1.NewIdentityHandler(registration, v1.WithEmailConfirmation(confirmation, settings.AppPublicURL)), pool.Close, nil
|
||||
}
|
||||
|
||||
// newIdentityKeyring keys the idempotency scopes and rate limit buckets with
|
||||
|
||||
@@ -379,20 +379,25 @@ type ConsentGrantInput struct {
|
||||
TextVersion ConsentTextVersion
|
||||
TextHash ConsentTextHash
|
||||
Source ConsentSource
|
||||
GrantedAt time.Time
|
||||
// RegistrationVersion binds a registration C1 to the account registration
|
||||
// whose email token carries its pending credentials. It is zero for every
|
||||
// other consent source.
|
||||
RegistrationVersion int64
|
||||
GrantedAt time.Time
|
||||
}
|
||||
|
||||
// ConsentGrant is a validated grant of C1, C2, C3, or C5, ready for the
|
||||
// ledger. C4 is never a ConsentGrant: it needs its organization scope, see
|
||||
// ContactConsentGrant.
|
||||
type ConsentGrant struct {
|
||||
id uuid.UUID
|
||||
subjectID uuid.UUID
|
||||
purpose ConsentPurpose
|
||||
textVersion ConsentTextVersion
|
||||
textHash ConsentTextHash
|
||||
source ConsentSource
|
||||
grantedAt time.Time
|
||||
id uuid.UUID
|
||||
subjectID uuid.UUID
|
||||
purpose ConsentPurpose
|
||||
textVersion ConsentTextVersion
|
||||
textHash ConsentTextHash
|
||||
source ConsentSource
|
||||
registrationVersion int64
|
||||
grantedAt time.Time
|
||||
}
|
||||
|
||||
// NewConsentGrant validates input and assigns a UUIDv7 identifier.
|
||||
@@ -412,6 +417,10 @@ func NewConsentGrant(input ConsentGrantInput) (ConsentGrant, error) {
|
||||
return ConsentGrant{}, fmt.Errorf("%s - subject ID must not be nil: %w", location, ErrInvalidConsent)
|
||||
case !input.Source.allowedFor(input.Purpose):
|
||||
return ConsentGrant{}, fmt.Errorf("%s - source does not allow the purpose: %w", location, ErrInvalidConsent)
|
||||
case input.Source == ConsentSourceRegistration && input.RegistrationVersion <= 0:
|
||||
return ConsentGrant{}, fmt.Errorf("%s - registration C1 requires a positive registration version: %w", location, ErrInvalidConsent)
|
||||
case input.Source != ConsentSourceRegistration && input.RegistrationVersion != 0:
|
||||
return ConsentGrant{}, fmt.Errorf("%s - only registration C1 carries a registration version: %w", location, ErrInvalidConsent)
|
||||
case input.GrantedAt.IsZero():
|
||||
return ConsentGrant{}, fmt.Errorf("%s - grant time must be set: %w", location, ErrInvalidConsent)
|
||||
}
|
||||
@@ -420,13 +429,14 @@ func NewConsentGrant(input ConsentGrantInput) (ConsentGrant, error) {
|
||||
return ConsentGrant{}, fmt.Errorf("%s - generate record ID: %w", location, err)
|
||||
}
|
||||
return ConsentGrant{
|
||||
id: id,
|
||||
subjectID: input.SubjectID,
|
||||
purpose: input.Purpose,
|
||||
textVersion: input.TextVersion,
|
||||
textHash: input.TextHash,
|
||||
source: input.Source,
|
||||
grantedAt: input.GrantedAt,
|
||||
id: id,
|
||||
subjectID: input.SubjectID,
|
||||
purpose: input.Purpose,
|
||||
textVersion: input.TextVersion,
|
||||
textHash: input.TextHash,
|
||||
source: input.Source,
|
||||
registrationVersion: input.RegistrationVersion,
|
||||
grantedAt: input.GrantedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -436,6 +446,7 @@ func (grant ConsentGrant) Purpose() ConsentPurpose { return grant.purpos
|
||||
func (grant ConsentGrant) TextVersion() ConsentTextVersion { return grant.textVersion }
|
||||
func (grant ConsentGrant) TextHash() ConsentTextHash { return grant.textHash }
|
||||
func (grant ConsentGrant) Source() ConsentSource { return grant.source }
|
||||
func (grant ConsentGrant) RegistrationVersion() int64 { return grant.registrationVersion }
|
||||
func (grant ConsentGrant) GrantedAt() time.Time { return grant.grantedAt }
|
||||
|
||||
// IsZero reports a grant not built by NewConsentGrant.
|
||||
@@ -656,6 +667,7 @@ type ConsentRecord struct {
|
||||
textVersion ConsentTextVersion
|
||||
textHash ConsentTextHash
|
||||
source ConsentSource
|
||||
registrationVersion int64
|
||||
state ConsentState
|
||||
grantedAt time.Time
|
||||
revokedAt time.Time
|
||||
@@ -677,6 +689,7 @@ type StoredConsentRecord struct {
|
||||
TextVersion string
|
||||
TextHash []byte
|
||||
Source string
|
||||
RegistrationVersion int64
|
||||
State string
|
||||
GrantedAt time.Time
|
||||
RevokedAt *time.Time
|
||||
@@ -716,6 +729,7 @@ func RestoreConsentRecord(stored StoredConsentRecord) (ConsentRecord, error) {
|
||||
textVersion: version,
|
||||
textHash: hash,
|
||||
source: ConsentSource(stored.Source),
|
||||
registrationVersion: stored.RegistrationVersion,
|
||||
state: state,
|
||||
grantedAt: stored.GrantedAt,
|
||||
revocationSource: ConsentRevocationSource(stored.RevocationSource),
|
||||
@@ -760,6 +774,10 @@ func (record ConsentRecord) validate(hasFieldSet bool) error {
|
||||
return fmt.Errorf("record and subject IDs must not be nil: %w", ErrInvalidConsent)
|
||||
case !record.source.allowedFor(record.purpose):
|
||||
return fmt.Errorf("source does not allow the purpose: %w", ErrInvalidConsent)
|
||||
case record.source == ConsentSourceRegistration && record.registrationVersion <= 0:
|
||||
return fmt.Errorf("registration C1 requires a positive registration version: %w", ErrInvalidConsent)
|
||||
case record.source != ConsentSourceRegistration && record.registrationVersion != 0:
|
||||
return fmt.Errorf("only registration C1 carries a registration version: %w", ErrInvalidConsent)
|
||||
case record.grantedAt.IsZero():
|
||||
return fmt.Errorf("grant time must be set: %w", ErrInvalidConsent)
|
||||
}
|
||||
@@ -810,6 +828,7 @@ func (record ConsentRecord) Purpose() ConsentPurpose { return record.pur
|
||||
func (record ConsentRecord) TextVersion() ConsentTextVersion { return record.textVersion }
|
||||
func (record ConsentRecord) TextHash() ConsentTextHash { return record.textHash }
|
||||
func (record ConsentRecord) Source() ConsentSource { return record.source }
|
||||
func (record ConsentRecord) RegistrationVersion() int64 { return record.registrationVersion }
|
||||
func (record ConsentRecord) State() ConsentState { return record.state }
|
||||
func (record ConsentRecord) GrantedAt() time.Time { return record.grantedAt }
|
||||
|
||||
|
||||
@@ -171,12 +171,13 @@ func TestNewContactFieldSetIsCanonicalAndRefusesDuplicates(t *testing.T) {
|
||||
|
||||
func validGrantInput() ConsentGrantInput {
|
||||
return ConsentGrantInput{
|
||||
SubjectID: uuid.Must(uuid.NewV7()),
|
||||
Purpose: ConsentPurposePersonalData,
|
||||
TextVersion: consentTestVersion,
|
||||
TextHash: HashConsentText("I consent."),
|
||||
Source: ConsentSourceRegistration,
|
||||
GrantedAt: consentTestTime,
|
||||
SubjectID: uuid.Must(uuid.NewV7()),
|
||||
Purpose: ConsentPurposePersonalData,
|
||||
TextVersion: consentTestVersion,
|
||||
TextHash: HashConsentText("I consent."),
|
||||
Source: ConsentSourceRegistration,
|
||||
RegistrationVersion: 1,
|
||||
GrantedAt: consentTestTime,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -185,7 +186,7 @@ func TestNewConsentGrantValidatesEveryField(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("NewConsentGrant() error = %v", err)
|
||||
}
|
||||
if grant.ID().Version() != 7 || grant.Purpose() != ConsentPurposePersonalData || grant.IsZero() {
|
||||
if grant.ID().Version() != 7 || grant.Purpose() != ConsentPurposePersonalData || grant.RegistrationVersion() != 1 || grant.IsZero() {
|
||||
t.Fatalf("grant = %s %s, want a UUIDv7 C1 grant", grant.ID(), grant.Purpose())
|
||||
}
|
||||
for name, change := range map[string]func(*ConsentGrantInput){
|
||||
@@ -197,7 +198,13 @@ func TestNewConsentGrantValidatesEveryField(t *testing.T) {
|
||||
"malformed text version": func(input *ConsentGrantInput) { input.TextVersion = "c1 v2" },
|
||||
"missing text hash": func(input *ConsentGrantInput) { input.TextHash = ConsentTextHash{} },
|
||||
"missing subject": func(input *ConsentGrantInput) { input.SubjectID = uuid.Nil },
|
||||
"registration of C2": func(input *ConsentGrantInput) { input.Purpose = ConsentPurposePublication },
|
||||
"missing registration version": func(input *ConsentGrantInput) {
|
||||
input.RegistrationVersion = 0
|
||||
},
|
||||
"settings grant with registration version": func(input *ConsentGrantInput) {
|
||||
input.Source = ConsentSourceConsentSettings
|
||||
},
|
||||
"registration of C2": func(input *ConsentGrantInput) { input.Purpose = ConsentPurposePublication },
|
||||
"invitation acceptance of C3": func(input *ConsentGrantInput) {
|
||||
input.Purpose, input.Source = ConsentPurposeAutoCategorization, ConsentSourceInvitationAcceptance
|
||||
},
|
||||
|
||||
@@ -121,6 +121,14 @@ type ConsentLedger interface {
|
||||
// CurrentContact.
|
||||
Current(ctx context.Context, subjectID uuid.UUID, purpose domain.ConsentPurpose) (domain.ConsentRecord, error)
|
||||
|
||||
// LockRegistration returns and locks the active registration C1 for one
|
||||
// registration version, or ErrConsentNotFound. Email confirmation calls it
|
||||
// inside the same transaction after consuming the token and applying the
|
||||
// pending credentials to the account, in token -> account -> registration C1
|
||||
// lock order. Keep all confirmation effects in that transaction so they
|
||||
// commit together after this check succeeds or roll back together on error.
|
||||
LockRegistration(ctx context.Context, subjectID uuid.UUID, registrationVersion int64) (domain.ConsentRecord, error)
|
||||
|
||||
// CurrentContact returns the unrevoked C4 records of the subject for the
|
||||
// organization, newest first, one per accepted invitation. The result
|
||||
// is empty when there is none.
|
||||
|
||||
@@ -54,8 +54,8 @@ var (
|
||||
// a time rejects the zero time.
|
||||
//
|
||||
// Lock order: an operation that changes both an account and its email tokens
|
||||
// locks the tokens first and the account second, as Consume and
|
||||
// MarkEmailVerified do in a confirmation. A re-registration or a resend
|
||||
// locks the tokens first and the account second, as Consume and ConfirmEmail
|
||||
// do in a confirmation. A re-registration or a resend
|
||||
// therefore calls InvalidateActive before UpdateRegistration or Insert; the
|
||||
// opposite order can deadlock against a concurrent confirmation. The only
|
||||
// exception is DeleteUnverifiedRegisteredBefore, which locks the account
|
||||
@@ -112,11 +112,17 @@ type UserRepository interface {
|
||||
|
||||
// MarkEmailVerified sets the verification time when the account is still
|
||||
// unverified and still has registrationVersion, and returns the stored
|
||||
// account. Otherwise it returns ErrUserVersionConflict. A confirmation
|
||||
// calls it after EmailTokenRepository.Consume in the same transaction; see
|
||||
// Consume.
|
||||
// account. Otherwise it returns ErrUserVersionConflict. It keeps the
|
||||
// storage operation available to existing callers; registration-token
|
||||
// confirmation uses ConfirmEmail to apply pending credentials as well.
|
||||
MarkEmailVerified(ctx context.Context, id uuid.UUID, registrationVersion int64, at time.Time) (domain.User, error)
|
||||
|
||||
// ConfirmEmail applies the pending credentials of one registration and
|
||||
// verifies the account only while that registration version is current.
|
||||
// It returns ErrUserVersionConflict when the account is already verified
|
||||
// or its registration has changed.
|
||||
ConfirmEmail(ctx context.Context, id uuid.UUID, registrationVersion int64, pending domain.PendingRegistration, at time.Time) (domain.User, error)
|
||||
|
||||
// DeleteUnverifiedRegisteredBefore deletes at most limit accounts that are
|
||||
// unverified and were last registered before cutoff, oldest first, with
|
||||
// their tokens, sessions, mail deliveries, and consent records, and
|
||||
@@ -133,6 +139,13 @@ type UserRepository interface {
|
||||
// EmailTokenRepository stores email token hashes. It never receives a raw
|
||||
// token.
|
||||
type EmailTokenRepository interface {
|
||||
// FindByHash returns the token row, including pending registration data,
|
||||
// whether or not it has already ended. It returns ErrEmailTokenNotFound
|
||||
// when the hash or purpose does not match, and ErrEmailTokenInvalidated
|
||||
// when its registration version is no longer current. Callers that use this
|
||||
// read to prepare work must recheck the token with Consume in their transaction.
|
||||
FindByHash(ctx context.Context, hash domain.SecretTokenHash, purpose domain.EmailTokenPurpose) (domain.EmailToken, error)
|
||||
|
||||
// Insert returns ErrUserNotFound when the account does not exist and
|
||||
// ErrTokenHashConflict for a duplicate hash.
|
||||
Insert(ctx context.Context, token domain.EmailToken) error
|
||||
@@ -147,8 +160,9 @@ type EmailTokenRepository interface {
|
||||
// many it marked.
|
||||
InvalidateActive(ctx context.Context, userID uuid.UUID, purpose domain.EmailTokenPurpose, at time.Time) (int64, error)
|
||||
|
||||
// Consume atomically marks the token consumed at the given time and
|
||||
// returns it. Of concurrent calls with the same hash exactly one succeeds;
|
||||
// Consume atomically marks the token consumed at the given time, clears its
|
||||
// pending registration data, and returns the token with that data from
|
||||
// before the update. Of concurrent calls with the same hash exactly one succeeds;
|
||||
// the others wait for its transaction and then fail. It fails with
|
||||
// ErrEmailTokenNotFound, ErrEmailTokenConsumed, ErrEmailTokenInvalidated,
|
||||
// or ErrEmailTokenExpired, in that order of precedence.
|
||||
@@ -157,7 +171,7 @@ type EmailTokenRepository interface {
|
||||
// as its statement reads the account, without locking it, so a
|
||||
// re-registration that commits right after it is not detected. Binding the
|
||||
// token to the current registration therefore requires a confirmation to
|
||||
// call Users().MarkEmailVerified(token.UserID, token.RegistrationVersion)
|
||||
// call Users().ConfirmEmail(token.UserID, token.RegistrationVersion, ...)
|
||||
// in the same transaction and to roll back when it returns
|
||||
// ErrUserVersionConflict; the rollback also restores the token. The
|
||||
// confirmation usecase maps that outcome to verification_token_invalid.
|
||||
|
||||
@@ -153,13 +153,15 @@ func (service *Service) GrantAtRegistration(
|
||||
ctx context.Context,
|
||||
repositories outbound.ConsentRepositories,
|
||||
subjectID uuid.UUID,
|
||||
registrationVersion int64,
|
||||
version domain.ConsentTextVersion,
|
||||
) (GrantResult, error) {
|
||||
result, err := service.grant(ctx, repositories, grantRequest{
|
||||
subjectID: subjectID,
|
||||
purpose: domain.ConsentPurposePersonalData,
|
||||
version: version,
|
||||
source: domain.ConsentSourceRegistration,
|
||||
subjectID: subjectID,
|
||||
purpose: domain.ConsentPurposePersonalData,
|
||||
version: version,
|
||||
source: domain.ConsentSourceRegistration,
|
||||
registrationVersion: registrationVersion,
|
||||
})
|
||||
if err != nil {
|
||||
return GrantResult{}, fmt.Errorf("Service.GrantAtRegistration - %w", err)
|
||||
@@ -236,10 +238,11 @@ func (service *Service) GrantInSettingsInNewTransaction(ctx context.Context, inp
|
||||
// grantRequest is a grant of C1, C2, C3, or C5 with its source, which the
|
||||
// public entry points fix.
|
||||
type grantRequest struct {
|
||||
subjectID uuid.UUID
|
||||
purpose domain.ConsentPurpose
|
||||
version domain.ConsentTextVersion
|
||||
source domain.ConsentSource
|
||||
subjectID uuid.UUID
|
||||
purpose domain.ConsentPurpose
|
||||
version domain.ConsentTextVersion
|
||||
source domain.ConsentSource
|
||||
registrationVersion int64
|
||||
}
|
||||
|
||||
func (service *Service) grant(ctx context.Context, repositories outbound.ConsentRepositories, request grantRequest) (GrantResult, error) {
|
||||
@@ -259,12 +262,13 @@ func (service *Service) grant(ctx context.Context, repositories outbound.Consent
|
||||
return GrantResult{}, fmt.Errorf("check text version: %w", err)
|
||||
}
|
||||
grant, err := domain.NewConsentGrant(domain.ConsentGrantInput{
|
||||
SubjectID: request.subjectID,
|
||||
Purpose: request.purpose,
|
||||
TextVersion: text.Version(),
|
||||
TextHash: text.Hash(),
|
||||
Source: request.source,
|
||||
GrantedAt: now,
|
||||
SubjectID: request.subjectID,
|
||||
Purpose: request.purpose,
|
||||
TextVersion: text.Version(),
|
||||
TextHash: text.Hash(),
|
||||
Source: request.source,
|
||||
RegistrationVersion: request.registrationVersion,
|
||||
GrantedAt: now,
|
||||
})
|
||||
if err != nil {
|
||||
return GrantResult{}, fmt.Errorf("build grant: %w", err)
|
||||
|
||||
@@ -71,17 +71,18 @@ func TestGrantAtRegistrationRecordsC1WithTheRegistrationSource(t *testing.T) {
|
||||
harness := newHarness(t)
|
||||
subject := uuid.New()
|
||||
|
||||
result, err := harness.service.GrantAtRegistration(t.Context(), harness.repositories, subject, harness.version(domain.ConsentPurposePersonalData))
|
||||
result, err := harness.service.GrantAtRegistration(t.Context(), harness.repositories, subject, 1, harness.version(domain.ConsentPurposePersonalData))
|
||||
if err != nil || !result.Created {
|
||||
t.Fatalf("GrantAtRegistration() = %v, %v, want a new record", result.Created, err)
|
||||
}
|
||||
record := result.Record
|
||||
if record.Purpose() != domain.ConsentPurposePersonalData || record.Source() != domain.ConsentSourceRegistration ||
|
||||
record.RegistrationVersion() != 1 ||
|
||||
record.SubjectID() != subject || !record.GrantedAt().Equal(clockStart) {
|
||||
t.Fatalf("GrantAtRegistration() record = %s %s, want the registration C1 at the application clock", record.Purpose(), record.Source())
|
||||
}
|
||||
|
||||
_, err = harness.service.GrantAtRegistration(t.Context(), harness.repositories, subject, "c1-1999-01-01")
|
||||
_, err = harness.service.GrantAtRegistration(t.Context(), harness.repositories, subject, 1, "c1-1999-01-01")
|
||||
if !errors.Is(err, consent.ErrStaleConsentText) {
|
||||
t.Fatalf("GrantAtRegistration(outdated) error = %v, want ErrStaleConsentText", err)
|
||||
}
|
||||
@@ -315,7 +316,7 @@ func TestPurposesAreIndependent(t *testing.T) {
|
||||
var result consent.GrantResult
|
||||
var err error
|
||||
if purpose == domain.ConsentPurposePersonalData {
|
||||
result, err = harness.service.GrantAtRegistration(t.Context(), harness.repositories, subject, harness.version(purpose))
|
||||
result, err = harness.service.GrantAtRegistration(t.Context(), harness.repositories, subject, 1, harness.version(purpose))
|
||||
} else {
|
||||
result, err = harness.service.GrantInSettings(t.Context(), harness.repositories, consent.SettingsGrantInput{
|
||||
SubjectID: subject, Purpose: purpose, TextVersion: harness.version(purpose),
|
||||
@@ -621,7 +622,8 @@ func (ledger *fakeLedger) Grant(_ context.Context, grant domain.ConsentGrant) (d
|
||||
hash := grant.TextHash()
|
||||
record, err := domain.RestoreConsentRecord(domain.StoredConsentRecord{
|
||||
ID: grant.ID(), SubjectID: grant.SubjectID(), Purpose: string(grant.Purpose()), TextVersion: string(grant.TextVersion()),
|
||||
TextHash: hash[:], Source: string(grant.Source()), State: string(domain.ConsentStateActive), GrantedAt: grant.GrantedAt(),
|
||||
TextHash: hash[:], Source: string(grant.Source()), RegistrationVersion: grant.RegistrationVersion(),
|
||||
State: string(domain.ConsentStateActive), GrantedAt: grant.GrantedAt(),
|
||||
})
|
||||
if err != nil {
|
||||
return domain.ConsentRecord{}, false, err
|
||||
@@ -674,6 +676,17 @@ func (ledger *fakeLedger) Current(_ context.Context, subjectID uuid.UUID, purpos
|
||||
return domain.ConsentRecord{}, outbound.ErrConsentNotFound
|
||||
}
|
||||
|
||||
func (ledger *fakeLedger) LockRegistration(_ context.Context, subjectID uuid.UUID, registrationVersion int64) (domain.ConsentRecord, error) {
|
||||
for index := len(ledger.records) - 1; index >= 0; index-- {
|
||||
if record := ledger.records[index]; record.SubjectID() == subjectID &&
|
||||
record.Purpose() == domain.ConsentPurposePersonalData && record.Source() == domain.ConsentSourceRegistration &&
|
||||
record.RegistrationVersion() == registrationVersion && record.State() == domain.ConsentStateActive {
|
||||
return record, nil
|
||||
}
|
||||
}
|
||||
return domain.ConsentRecord{}, outbound.ErrConsentNotFound
|
||||
}
|
||||
|
||||
func (ledger *fakeLedger) CurrentContact(context.Context, uuid.UUID, uuid.UUID) ([]domain.ConsentRecord, error) {
|
||||
panic("the consent usecase does not read C4")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
package identity
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const (
|
||||
// DefaultTokenHourlyLimit bounds confirmation attempts for one token.
|
||||
DefaultTokenHourlyLimit = 5
|
||||
|
||||
verificationEventType = "identity.email_verified"
|
||||
verificationAggregateType = "user"
|
||||
verificationSchemaVersion = 1
|
||||
)
|
||||
|
||||
// ConfirmationDependencies are the collaborators of EmailConfirmation.
|
||||
// Every field is required except Metrics.
|
||||
type ConfirmationDependencies struct {
|
||||
Transactor outbound.Transactor
|
||||
Tokens outbound.EmailTokenRepository
|
||||
Credentials *Credentials
|
||||
Limiter outbound.RateLimiter
|
||||
Keyring *Keyring
|
||||
Clock func() time.Time
|
||||
Metrics RateLimitMetrics
|
||||
}
|
||||
|
||||
// ConfirmationSettings contains the attempt limits for one token and one
|
||||
// client. The client limit matches registration and resend.
|
||||
type ConfirmationSettings struct {
|
||||
TokenHourlyLimit int64
|
||||
ClientHourlyLimit int64
|
||||
}
|
||||
|
||||
// EmailConfirmation confirms the address and applies the credentials of the
|
||||
// registration carried by its token. It holds no mutable state.
|
||||
type EmailConfirmation struct {
|
||||
deps ConfirmationDependencies
|
||||
settings ConfirmationSettings
|
||||
}
|
||||
|
||||
// NewEmailConfirmation checks the collaborators and limits once, so a wiring
|
||||
// mistake fails at startup rather than on the first confirmation.
|
||||
func NewEmailConfirmation(deps ConfirmationDependencies, settings ConfirmationSettings) (*EmailConfirmation, error) {
|
||||
switch {
|
||||
case deps.Transactor == nil, deps.Tokens == nil, deps.Credentials == nil,
|
||||
deps.Limiter == nil, deps.Keyring == nil, deps.Clock == nil:
|
||||
return nil, errors.New("identity.NewEmailConfirmation - every dependency must be set")
|
||||
case settings.TokenHourlyLimit < 1, settings.ClientHourlyLimit < 1:
|
||||
return nil, errors.New("identity.NewEmailConfirmation - confirmation limits must be positive")
|
||||
}
|
||||
return &EmailConfirmation{deps: deps, settings: settings}, nil
|
||||
}
|
||||
|
||||
// ConfirmCommand is the content of an email confirmation request.
|
||||
type ConfirmCommand struct {
|
||||
Token string
|
||||
Password string
|
||||
// ClientKey is the opaque limiter key of the client network address.
|
||||
ClientKey string
|
||||
}
|
||||
|
||||
// ConfirmationResult is the saved destination after the user signs in.
|
||||
type ConfirmationResult struct {
|
||||
Scenario domain.Scenario
|
||||
OnboardingStep domain.OnboardingStep
|
||||
}
|
||||
|
||||
// Confirm verifies the registration password outside the database
|
||||
// transaction, then rechecks and consumes the token with the account and its
|
||||
// registration C1 in one transaction.
|
||||
func (confirmation *EmailConfirmation) Confirm(ctx context.Context, command ConfirmCommand) (ConfirmationResult, error) {
|
||||
const location = "EmailConfirmation.Confirm"
|
||||
if err := confirmation.takeAttempt(ctx, command); err != nil {
|
||||
return ConfirmationResult{}, fmt.Errorf("%s - limit confirmation: %w", location, err)
|
||||
}
|
||||
token, err := domain.ParseSecretToken(command.Token)
|
||||
if err != nil {
|
||||
return ConfirmationResult{}, fmt.Errorf("%s - parse token: %w", location, ErrVerificationTokenInvalid)
|
||||
}
|
||||
prepared, err := confirmation.deps.Tokens.FindByHash(ctx, token.Hash(), domain.EmailTokenPurposeEmailVerification)
|
||||
if errors.Is(err, outbound.ErrEmailTokenNotFound) || errors.Is(err, outbound.ErrEmailTokenInvalidated) {
|
||||
return ConfirmationResult{}, fmt.Errorf("%s - read token: %w", location, ErrVerificationTokenInvalid)
|
||||
}
|
||||
if err != nil {
|
||||
return ConfirmationResult{}, fmt.Errorf("%s - read token: %w", location, err)
|
||||
}
|
||||
if prepared.ConsumedAt != nil || prepared.InvalidatedAt != nil || prepared.Pending == nil {
|
||||
return ConfirmationResult{}, fmt.Errorf("%s - token cannot confirm a registration: %w", location, ErrVerificationTokenInvalid)
|
||||
}
|
||||
if !prepared.ExpiresAt.After(confirmation.deps.Clock()) {
|
||||
return ConfirmationResult{}, fmt.Errorf("%s - check token expiry: %w", location, ErrVerificationTokenExpired)
|
||||
}
|
||||
if err := confirmation.deps.Credentials.VerifyLoginPassword(ctx, command.Password, prepared.Pending.PasswordHash); err != nil {
|
||||
if errors.Is(err, outbound.ErrPasswordMismatch) || errors.Is(err, domain.ErrInvalidPassword) {
|
||||
return ConfirmationResult{}, fmt.Errorf("%s - verify registration password: %w", location, ErrVerificationTokenInvalid)
|
||||
}
|
||||
return ConfirmationResult{}, fmt.Errorf("%s - verify registration password: %w", location, err)
|
||||
}
|
||||
|
||||
var result ConfirmationResult
|
||||
err = confirmation.deps.Transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
return confirmation.confirmInTransaction(ctx, unit, token.Hash(), prepared, &result)
|
||||
})
|
||||
if err != nil {
|
||||
return ConfirmationResult{}, fmt.Errorf("%s - confirm registration: %w", location, confirmationOutcomeError(err))
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func confirmationOutcomeError(err error) error {
|
||||
switch {
|
||||
case errors.Is(err, outbound.ErrEmailTokenExpired):
|
||||
return ErrVerificationTokenExpired
|
||||
case errors.Is(err, outbound.ErrEmailTokenNotFound),
|
||||
errors.Is(err, outbound.ErrEmailTokenConsumed),
|
||||
errors.Is(err, outbound.ErrEmailTokenInvalidated),
|
||||
errors.Is(err, outbound.ErrConsentNotFound),
|
||||
errors.Is(err, outbound.ErrUserVersionConflict),
|
||||
errors.Is(err, ErrVerificationTokenInvalid):
|
||||
return ErrVerificationTokenInvalid
|
||||
default:
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
func (confirmation *EmailConfirmation) takeAttempt(ctx context.Context, command ConfirmCommand) error {
|
||||
const location = "EmailConfirmation.takeAttempt"
|
||||
type attemptCheck struct {
|
||||
key string
|
||||
scope string
|
||||
rule outbound.RateLimitRule
|
||||
}
|
||||
checks := make([]attemptCheck, 0, 2)
|
||||
if command.ClientKey != "" {
|
||||
checks = append(checks, attemptCheck{
|
||||
key: confirmation.deps.Keyring.ClientBucket(command.ClientKey),
|
||||
scope: ScopeClient,
|
||||
rule: outbound.RateLimitRule{Window: clientWindow, Limit: confirmation.settings.ClientHourlyLimit},
|
||||
})
|
||||
}
|
||||
checks = append(checks, attemptCheck{
|
||||
key: confirmation.deps.Keyring.VerificationTokenBucket(command.Token),
|
||||
scope: ScopeToken,
|
||||
rule: outbound.RateLimitRule{Window: time.Hour, Limit: confirmation.settings.TokenHourlyLimit},
|
||||
})
|
||||
for _, check := range checks {
|
||||
decision, err := confirmation.deps.Limiter.Take(ctx, check.key, check.rule)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - take %s limit: %w", location, check.scope, err)
|
||||
}
|
||||
if !decision.Allowed {
|
||||
if confirmation.deps.Metrics != nil {
|
||||
confirmation.deps.Metrics.ObserveIdentityRateLimited(check.scope)
|
||||
}
|
||||
return &RateLimitedError{RetryAfter: decision.RetryAfter}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (confirmation *EmailConfirmation) confirmInTransaction(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
hash domain.SecretTokenHash,
|
||||
prepared domain.EmailToken,
|
||||
result *ConfirmationResult,
|
||||
) error {
|
||||
const location = "EmailConfirmation.confirmInTransaction"
|
||||
consumedAt := confirmation.deps.Clock()
|
||||
token, err := unit.EmailTokens().Consume(ctx, hash, domain.EmailTokenPurposeEmailVerification, consumedAt)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - consume token: %w", location, err)
|
||||
}
|
||||
if !token.ExpiresAt.After(confirmation.deps.Clock()) {
|
||||
return fmt.Errorf("%s - token expired while waiting: %w", location, outbound.ErrEmailTokenExpired)
|
||||
}
|
||||
if token.Pending == nil || prepared.Pending == nil || !samePendingRegistration(*prepared.Pending, *token.Pending) {
|
||||
return fmt.Errorf("%s - pending registration does not match: %w", location, ErrVerificationTokenInvalid)
|
||||
}
|
||||
if token.ConsumedAt == nil {
|
||||
return fmt.Errorf("%s - consumed token has no consumption time: %w", location, domain.ErrInvalidEmailToken)
|
||||
}
|
||||
user, err := unit.Users().ConfirmEmail(ctx, token.UserID, token.RegistrationVersion, *token.Pending, *token.ConsumedAt)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - apply pending registration: %w", location, err)
|
||||
}
|
||||
if !token.ExpiresAt.After(confirmation.deps.Clock()) {
|
||||
return fmt.Errorf("%s - token expired while waiting for account lock: %w", location, outbound.ErrEmailTokenExpired)
|
||||
}
|
||||
if _, err := unit.ConsentLedger().LockRegistration(ctx, token.UserID, token.RegistrationVersion); err != nil {
|
||||
return fmt.Errorf("%s - lock registration C1: %w", location, err)
|
||||
}
|
||||
if !token.ExpiresAt.After(confirmation.deps.Clock()) {
|
||||
return fmt.Errorf("%s - token expired while waiting for consent lock: %w", location, outbound.ErrEmailTokenExpired)
|
||||
}
|
||||
event, err := domain.NewDomainEvent(domain.DomainEventInput{
|
||||
EventType: verificationEventType,
|
||||
SchemaVersion: verificationSchemaVersion,
|
||||
AggregateType: verificationAggregateType,
|
||||
AggregateID: user.ID,
|
||||
AggregateVersion: user.Version,
|
||||
Payload: []byte("{}"),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - build verification event: %w", location, err)
|
||||
}
|
||||
if err := unit.Outbox().Append(ctx, event); err != nil {
|
||||
return fmt.Errorf("%s - append verification event: %w", location, err)
|
||||
}
|
||||
*result = ConfirmationResult{Scenario: user.Scenario, OnboardingStep: user.OnboardingStep}
|
||||
return nil
|
||||
}
|
||||
|
||||
func samePendingRegistration(left, right domain.PendingRegistration) bool {
|
||||
return left.PasswordHash.PHC() == right.PasswordHash.PHC() &&
|
||||
left.Scenario == right.Scenario && left.OnboardingStep == right.OnboardingStep
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package identity
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const confirmationTestPasswordHash = "$argon2id$v=19$m=65536,t=3,p=4$c2FsdHNhbHRzYWx0c2FsdA$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaGhhc2g"
|
||||
|
||||
type confirmationTokenReader struct {
|
||||
outbound.EmailTokenRepository
|
||||
|
||||
token domain.EmailToken
|
||||
err error
|
||||
calls int
|
||||
}
|
||||
|
||||
func (repository *confirmationTokenReader) FindByHash(context.Context, domain.SecretTokenHash, domain.EmailTokenPurpose) (domain.EmailToken, error) {
|
||||
repository.calls++
|
||||
return repository.token, repository.err
|
||||
}
|
||||
|
||||
type confirmationTestLimiter struct {
|
||||
keys []string
|
||||
first outbound.RateLimitDecision
|
||||
firstError error
|
||||
}
|
||||
|
||||
func (limiter *confirmationTestLimiter) Take(_ context.Context, key string, _ ...outbound.RateLimitRule) (outbound.RateLimitDecision, error) {
|
||||
limiter.keys = append(limiter.keys, key)
|
||||
if len(limiter.keys) == 1 {
|
||||
return limiter.first, limiter.firstError
|
||||
}
|
||||
return outbound.RateLimitDecision{Allowed: true}, nil
|
||||
}
|
||||
|
||||
type confirmationTestTransactor struct {
|
||||
calls int
|
||||
}
|
||||
|
||||
func (transactor *confirmationTestTransactor) WithinTransaction(context.Context, func(context.Context, outbound.UnitOfWork) error) error {
|
||||
transactor.calls++
|
||||
return errors.New("unexpected transaction")
|
||||
}
|
||||
|
||||
func TestEmailConfirmationKeepsInvalidTokenPrecedenceOverExpiry(t *testing.T) {
|
||||
now := time.Date(2026, time.October, 7, 12, 0, 0, 0, time.UTC)
|
||||
raw, err := domain.NewSecretToken()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
expired := now.Add(-time.Second)
|
||||
passwordHash, err := domain.NewPasswordHash(confirmationTestPasswordHash)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pending, err := domain.NewPendingRegistration(passwordHash, domain.ScenarioCandidate)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
consumedAt := now.Add(-time.Minute)
|
||||
invalidatedAt := now.Add(-time.Minute)
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
token domain.EmailToken
|
||||
readError error
|
||||
want error
|
||||
}{
|
||||
{
|
||||
name: "consumed",
|
||||
token: domain.EmailToken{ExpiresAt: expired, ConsumedAt: &consumedAt},
|
||||
want: ErrVerificationTokenInvalid,
|
||||
},
|
||||
{
|
||||
name: "invalidated",
|
||||
token: domain.EmailToken{ExpiresAt: expired, InvalidatedAt: &invalidatedAt},
|
||||
want: ErrVerificationTokenInvalid,
|
||||
},
|
||||
{
|
||||
name: "superseded registration",
|
||||
readError: outbound.ErrEmailTokenInvalidated,
|
||||
want: ErrVerificationTokenInvalid,
|
||||
},
|
||||
{
|
||||
name: "current expired token",
|
||||
token: domain.EmailToken{
|
||||
UserID: uuid.New(), Purpose: domain.EmailTokenPurposeEmailVerification,
|
||||
TokenHash: raw.Hash(), ExpiresAt: expired, Pending: &pending,
|
||||
},
|
||||
want: ErrVerificationTokenExpired,
|
||||
},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
tokens := &confirmationTokenReader{token: test.token, err: test.readError}
|
||||
transactor := &confirmationTestTransactor{}
|
||||
limiter := &confirmationTestLimiter{first: outbound.RateLimitDecision{Allowed: true}}
|
||||
keyring, err := NewKeyring([]byte("confirmation key with enough entropy"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
confirmation, err := NewEmailConfirmation(ConfirmationDependencies{
|
||||
Transactor: transactor, Tokens: tokens, Credentials: NewCredentials(nil),
|
||||
Limiter: limiter, Keyring: keyring, Clock: func() time.Time { return now },
|
||||
}, ConfirmationSettings{TokenHourlyLimit: 5, ClientHourlyLimit: 20})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = confirmation.Confirm(context.Background(), ConfirmCommand{Token: raw.Reveal(), Password: "correct horse battery staple"})
|
||||
if !errors.Is(err, test.want) {
|
||||
t.Fatalf("Confirm() error = %v, want %v", err, test.want)
|
||||
}
|
||||
if transactor.calls != 0 {
|
||||
t.Fatalf("transaction calls = %d, want 0", transactor.calls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmailConfirmationClientLimitRunsBeforeTokenLookup(t *testing.T) {
|
||||
raw, err := domain.NewSecretToken()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
keyring, err := NewKeyring([]byte("confirmation key with enough entropy"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tokens := &confirmationTokenReader{}
|
||||
transactor := &confirmationTestTransactor{}
|
||||
limiter := &confirmationTestLimiter{first: outbound.RateLimitDecision{Allowed: false, RetryAfter: time.Minute}}
|
||||
confirmation, err := NewEmailConfirmation(ConfirmationDependencies{
|
||||
Transactor: transactor, Tokens: tokens, Credentials: NewCredentials(nil),
|
||||
Limiter: limiter, Keyring: keyring, Clock: time.Now,
|
||||
}, ConfirmationSettings{TokenHourlyLimit: 5, ClientHourlyLimit: 20})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = confirmation.Confirm(context.Background(), ConfirmCommand{
|
||||
Token: raw.Reveal(), Password: "correct horse battery staple", ClientKey: "client-key",
|
||||
})
|
||||
var limited *RateLimitedError
|
||||
if !errors.As(err, &limited) || limited.RetryAfter != time.Minute {
|
||||
t.Fatalf("Confirm() error = %v, want one-minute rate limit", err)
|
||||
}
|
||||
if len(limiter.keys) != 1 || limiter.keys[0] != keyring.ClientBucket("client-key") {
|
||||
t.Fatalf("limiter keys = %v, want only the client bucket first", limiter.keys)
|
||||
}
|
||||
if tokens.calls != 0 || transactor.calls != 0 {
|
||||
t.Fatalf("storage calls = lookup %d, transaction %d, want none", tokens.calls, transactor.calls)
|
||||
}
|
||||
}
|
||||
@@ -37,3 +37,18 @@ func (credentials *Credentials) HashNewPassword(ctx context.Context, raw string)
|
||||
}
|
||||
return hash, nil
|
||||
}
|
||||
|
||||
// VerifyLoginPassword normalizes and checks a password with the login bounds.
|
||||
// It does not apply the registration blocklist, so an existing registration
|
||||
// can confirm even when that password is no longer accepted for new accounts.
|
||||
func (credentials *Credentials) VerifyLoginPassword(ctx context.Context, raw string, stored domain.PasswordHash) error {
|
||||
const location = "Credentials.VerifyLoginPassword"
|
||||
password, err := domain.ParseLoginPassword(raw)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - validate password: %w", location, err)
|
||||
}
|
||||
if _, err := credentials.hasher.Verify(ctx, password, stored); err != nil {
|
||||
return fmt.Errorf("%s - verify password: %w", location, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -12,21 +12,30 @@ import (
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const testPasswordPHC = "$argon2id$v=19$m=65536,t=3,p=4$c2FsdHNhbHRzYWx0c2FsdA$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaGhhc2g"
|
||||
|
||||
// countingHasher records calls so a test can prove that validation stops a
|
||||
// password before any hashing.
|
||||
type countingHasher struct {
|
||||
hashCalls int
|
||||
hashed domain.Password
|
||||
hashCalls int
|
||||
hashed domain.Password
|
||||
verifyCalls int
|
||||
verified domain.Password
|
||||
stored domain.PasswordHash
|
||||
verifyErr error
|
||||
}
|
||||
|
||||
func (hasher *countingHasher) Hash(_ context.Context, password domain.Password) (domain.PasswordHash, error) {
|
||||
hasher.hashCalls++
|
||||
hasher.hashed = password
|
||||
return domain.NewPasswordHash("$argon2id$v=19$m=65536,t=3,p=4$c2FsdHNhbHRzYWx0c2FsdA$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaGhhc2g")
|
||||
return domain.NewPasswordHash(testPasswordPHC)
|
||||
}
|
||||
|
||||
func (hasher *countingHasher) Verify(context.Context, domain.Password, domain.PasswordHash) (bool, error) {
|
||||
return false, errors.New("countingHasher.Verify - not used")
|
||||
func (hasher *countingHasher) Verify(_ context.Context, password domain.Password, stored domain.PasswordHash) (bool, error) {
|
||||
hasher.verifyCalls++
|
||||
hasher.verified = password
|
||||
hasher.stored = stored
|
||||
return false, hasher.verifyErr
|
||||
}
|
||||
|
||||
func (hasher *countingHasher) VerifyDummy(context.Context, domain.Password) error {
|
||||
@@ -81,3 +90,29 @@ func TestHashNewPasswordHashesTheNormalizedPassword(t *testing.T) {
|
||||
t.Fatalf("hasher received %d calls, want one with the NFKC form", hasher.hashCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyLoginPasswordUsesLoginBoundsAndNFKC(t *testing.T) {
|
||||
hasher := &countingHasher{}
|
||||
stored, err := domain.NewPasswordHash(testPasswordPHC)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := NewCredentials(hasher).VerifyLoginPassword(context.Background(), "x", stored); err != nil {
|
||||
t.Fatalf("VerifyLoginPassword() error = %v", err)
|
||||
}
|
||||
if hasher.verifyCalls != 1 || hasher.verified.Reveal() != "x" || hasher.stored.PHC() != stored.PHC() {
|
||||
t.Fatalf("Verify calls = %d, password = %q, stored hash matched = %v", hasher.verifyCalls, hasher.verified.Reveal(), hasher.stored.PHC() == stored.PHC())
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyLoginPasswordRejectsEmptyInputBeforeKDF(t *testing.T) {
|
||||
hasher := &countingHasher{}
|
||||
stored, err := domain.NewPasswordHash(testPasswordPHC)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
err = NewCredentials(hasher).VerifyLoginPassword(context.Background(), "", stored)
|
||||
if !errors.Is(err, domain.ErrInvalidPassword) || hasher.verifyCalls != 0 {
|
||||
t.Fatalf("VerifyLoginPassword(empty) = %v after %d verify calls, want ErrInvalidPassword before KDF", err, hasher.verifyCalls)
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,14 @@ var (
|
||||
// ErrInvalidField reports a request value outside its rules.
|
||||
// errors.As with *InvalidFieldError yields the JSON Pointer of the field.
|
||||
ErrInvalidField = errors.New("invalid request field")
|
||||
|
||||
// ErrVerificationTokenInvalid reports an unknown, used, replaced, or
|
||||
// otherwise unusable email verification token.
|
||||
ErrVerificationTokenInvalid = errors.New("verification token invalid")
|
||||
|
||||
// ErrVerificationTokenExpired reports an email verification token past its
|
||||
// expiry time.
|
||||
ErrVerificationTokenExpired = errors.New("verification token expired")
|
||||
)
|
||||
|
||||
// RateLimitedError carries how long the caller waits before a repeat can be
|
||||
|
||||
@@ -19,6 +19,7 @@ const (
|
||||
labelFingerprint = "lincodex/identity/request-fingerprint/v1"
|
||||
labelEmailBucket = "lincodex/identity/email-bucket/v1"
|
||||
labelClientBucket = "lincodex/identity/client-bucket/v1"
|
||||
labelTokenBucket = "lincodex/identity/verification-token-bucket/v1"
|
||||
)
|
||||
|
||||
// Keyring computes the keyed digests of the anonymous identity operations:
|
||||
@@ -31,6 +32,7 @@ type Keyring struct {
|
||||
fingerprintKey []byte
|
||||
bucketKey []byte
|
||||
clientKey []byte
|
||||
tokenKey []byte
|
||||
}
|
||||
|
||||
// NewKeyring derives the purpose keys from secret.
|
||||
@@ -43,6 +45,7 @@ func NewKeyring(secret []byte) (*Keyring, error) {
|
||||
fingerprintKey: derive(secret, labelFingerprint),
|
||||
bucketKey: derive(secret, labelEmailBucket),
|
||||
clientKey: derive(secret, labelClientBucket),
|
||||
tokenKey: derive(secret, labelTokenBucket),
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -88,3 +91,11 @@ func (keyring *Keyring) ClientBucket(clientKey string) string {
|
||||
mac.Write([]byte(clientKey))
|
||||
return "identity:client:" + hex.EncodeToString(mac.Sum(nil))
|
||||
}
|
||||
|
||||
// VerificationTokenBucket names the rate limit counter for a raw
|
||||
// verification token without putting the token itself in the limiter store.
|
||||
func (keyring *Keyring) VerificationTokenBucket(rawToken string) string {
|
||||
mac := hmac.New(sha256.New, keyring.tokenKey)
|
||||
mac.Write([]byte(rawToken))
|
||||
return "identity:verification-token:" + hex.EncodeToString(mac.Sum(nil))
|
||||
}
|
||||
@@ -102,6 +102,7 @@ type RegistrationDependencies struct {
|
||||
const (
|
||||
ScopeAddress = "address"
|
||||
ScopeClient = "client"
|
||||
ScopeToken = "token"
|
||||
)
|
||||
|
||||
// RateLimitMetrics counts refused requests by scope, never by address.
|
||||
@@ -319,7 +320,7 @@ func (registration *Registration) createAccount(ctx context.Context, unit outbou
|
||||
if err := unit.Users().Create(ctx, user); err != nil {
|
||||
return fmt.Errorf("%s - store account: %w", location, err)
|
||||
}
|
||||
if _, err := registration.deps.Consents.GrantAtRegistration(ctx, unit, user.ID, input.version); err != nil {
|
||||
if _, err := registration.deps.Consents.GrantAtRegistration(ctx, unit, user.ID, user.RegistrationVersion, input.version); err != nil {
|
||||
return fmt.Errorf("%s - record C1: %w", location, err)
|
||||
}
|
||||
pending, err := domain.NewPendingRegistration(input.hash, input.scenario)
|
||||
@@ -353,7 +354,7 @@ func (registration *Registration) reRegister(
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - advance registration: %w", location, err)
|
||||
}
|
||||
if _, err := registration.deps.Consents.GrantAtRegistration(ctx, unit, advanced.ID, input.version); err != nil {
|
||||
if _, err := registration.deps.Consents.GrantAtRegistration(ctx, unit, advanced.ID, advanced.RegistrationVersion, input.version); err != nil {
|
||||
return fmt.Errorf("%s - record C1: %w", location, err)
|
||||
}
|
||||
pending, err := domain.NewPendingRegistration(input.hash, input.scenario)
|
||||
|
||||
Reference in new issue
Block a user