feat(identity): add server sessions and audited mail recovery

This commit is contained in:
TakuyaYagam1 committed 2026-10-07 11:03:46 +03:00
1 parent 20c03288d6
commit 4ee53d9a74
58 files changed
+5359 -567

No files matched your search

@@ -0,0 +1,115 @@
-- +goose Up
-- Resend may accept a request even when the caller loses the response. Keep
-- that delivery unknown, but schedule bounded retries while its provider key
-- is still inside the deduplication window. An operator decision after the
-- automatic cutoff is append-only and single-use; manual send markers never
-- reset the provider's idempotency window.
ALTER TABLE deliveries
ADD COLUMN manual_retry_authorized_at timestamptz,
ADD COLUMN manual_retry_started_at timestamptz,
ADD COLUMN send_started_attempt_count integer;
COMMENT ON COLUMN deliveries.manual_retry_authorized_at IS
'Database time of the latest audited operator authorization to retry a terminal unknown delivery; it does not replace the original send history.';
COMMENT ON COLUMN deliveries.manual_retry_started_at IS
'Database time when the first provider call of the latest manual authorization started; this is a single-use/recovery marker and never resets the provider deduplication window.';
COMMENT ON COLUMN deliveries.send_started_attempt_count IS
'Attempt count when the latest provider call started. Equality with attempt_count means its result was not recorded; a greater attempt_count means a provider result was stored after that send-start.';
ALTER TABLE deliveries ADD CONSTRAINT deliveries_manual_retry_cycle_complete CHECK (
manual_retry_started_at IS NULL OR manual_retry_authorized_at IS NOT NULL
);
ALTER TABLE deliveries ADD CONSTRAINT deliveries_send_started_attempt_count_valid CHECK (
send_started_attempt_count IS NULL
OR (send_started_attempt_count >= 0 AND send_started_attempt_count <= attempt_count)
);
-- Keep the decision after a delivery or account is deleted. This table holds
-- only an opaque delivery ID, attempt number, operator handle, acknowledgement
-- and decision time; it never stores recipient data or message content.
CREATE TABLE delivery_retry_decisions (
decision_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
delivery_id uuid NOT NULL,
attempt_count integer NOT NULL CHECK (attempt_count > 0),
actor text NOT NULL CHECK (
length(actor) <= 128
AND actor ~ '^operator:[a-z0-9][a-z0-9._-]*$'
),
duplicate_risk_acknowledged boolean NOT NULL CHECK (duplicate_risk_acknowledged),
previous_lease_expired boolean NOT NULL,
decided_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
CREATE INDEX delivery_retry_decisions_delivery_idx
ON delivery_retry_decisions (delivery_id, decision_id);
COMMENT ON TABLE delivery_retry_decisions IS
'Append-only record of an operator decision to retry a terminal unknown mail delivery after its provider deduplication window. No foreign key so history survives account deletion.';
COMMENT ON COLUMN delivery_retry_decisions.delivery_id IS
'Opaque ID of the delivery whose current unknown attempt was authorized for another send cycle.';
COMMENT ON COLUMN delivery_retry_decisions.actor IS
'Operator handle in the form operator:<handle>; never an email address or credential.';
COMMENT ON COLUMN delivery_retry_decisions.duplicate_risk_acknowledged IS
'Must be true: after the provider key expires, reusing it does not guarantee deduplication.';
COMMENT ON COLUMN delivery_retry_decisions.previous_lease_expired IS
'True when this decision also cleared an expired worker lease after a manual send began but its result was not recorded.';
-- +goose StatementBegin
CREATE FUNCTION delivery_retry_decisions_refuse_change() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP = 'TRUNCATE' THEN
RAISE EXCEPTION USING
ERRCODE = 'integrity_constraint_violation',
CONSTRAINT = 'delivery_retry_decisions_immutable',
TABLE = 'delivery_retry_decisions',
MESSAGE = 'mail retry decisions are append-only';
END IF;
RAISE EXCEPTION USING
ERRCODE = 'integrity_constraint_violation',
CONSTRAINT = 'delivery_retry_decisions_immutable',
TABLE = 'delivery_retry_decisions',
MESSAGE = 'mail retry decisions are append-only';
END;
$$;
-- +goose StatementEnd
CREATE TRIGGER delivery_retry_decisions_refuse_update_delete
BEFORE UPDATE OR DELETE ON delivery_retry_decisions
FOR EACH ROW EXECUTE FUNCTION delivery_retry_decisions_refuse_change();
CREATE TRIGGER delivery_retry_decisions_refuse_truncate
BEFORE TRUNCATE ON delivery_retry_decisions
FOR EACH STATEMENT EXECUTE FUNCTION delivery_retry_decisions_refuse_change();
-- A due unknown row is claimable only when the retry policy gave it a due
-- time. Keep the worker's single indexed queue broad enough for all due
-- service-mail statuses.
DROP INDEX deliveries_due_idx;
CREATE INDEX deliveries_due_idx
ON deliveries (next_attempt_at, id)
WHERE
status IN ('pending', 'waiting_quota', 'unknown')
AND next_attempt_at IS NOT NULL
AND kind IN ('verification', 'password_reset');
-- +goose Down
-- Rolling back this migration removes its append-only operator decision
-- history. Export or preserve that audit data before an intentional rollback.
DROP INDEX deliveries_due_idx;
CREATE INDEX deliveries_due_idx
ON deliveries (next_attempt_at, id)
WHERE
status IN ('pending', 'waiting_quota')
AND next_attempt_at IS NOT NULL
AND kind IN ('verification', 'password_reset');
DROP TRIGGER delivery_retry_decisions_refuse_update_delete ON delivery_retry_decisions;
DROP TRIGGER delivery_retry_decisions_refuse_truncate ON delivery_retry_decisions;
DROP FUNCTION delivery_retry_decisions_refuse_change();
DROP INDEX delivery_retry_decisions_delivery_idx;
DROP TABLE delivery_retry_decisions;
ALTER TABLE deliveries DROP CONSTRAINT deliveries_manual_retry_cycle_complete;
ALTER TABLE deliveries DROP CONSTRAINT deliveries_send_started_attempt_count_valid;
ALTER TABLE deliveries DROP COLUMN send_started_attempt_count, DROP COLUMN manual_retry_started_at, DROP COLUMN manual_retry_authorized_at;
+206 -14
View File
@@ -86,6 +86,21 @@ SELECT
FROM deliveries
WHERE id = sqlc.arg(id);
-- Reads only the metadata needed by the local operator retry interface. It
-- intentionally does not select the address, token, subject, or message body.
-- name: GetDeliveryRetrySnapshot :one
SELECT
id,
provider,
provider_account,
status,
attempt_count,
next_attempt_at,
first_send_started_at,
manual_retry_started_at
FROM deliveries
WHERE id = sqlc.arg(id);
-- Advances a delivery past one attempt and appends the attempt in one
-- statement, so both happen or neither does, inside or outside a
-- transaction. The update applies only while the stored version still
@@ -219,7 +234,7 @@ WHERE
AND deliveries.version = sqlc.arg(expected_version);
-- Claims the most overdue delivery that the sending worker may send, in one
-- statement: a pending or waiting_quota delivery of the service mail kinds
-- statement: a pending, waiting_quota, or scheduled unknown delivery of the service mail kinds
-- (the literals match the predicate of deliveries_due_idx, so an idle poll
-- reads only that small index) whose next_attempt_at has passed, pinned to the
-- configured provider account (or to rebind_provider before its first
@@ -233,10 +248,15 @@ WHERE
-- stay on the application clock that wrote them. Neither the version nor
-- updated_at changes: a claim is not a change of the delivery.
-- previous_claimed_until is the deadline of an abandoned lease, NULL for a
-- delivery nobody held; since_first_send_seconds is how long ago, by the
-- database clock, its first request started, -1 when none did. now is the
-- application clock. Deliveries that are unknown or wait for an unknown quota
-- reset have no due time here and wait for an operator.
-- delivery nobody held; since_first_send_seconds always measures from the
-- original first request by the database clock, and is -1 when none started.
-- manual_retry_pending is true until the first provider call of the latest
-- manual authorization starts. send_start_unsettled means a provider call
-- started at the current attempt_count but no result was recorded afterward.
-- has_uncertain_attempt keeps an earlier unknown result visible even if a
-- later confirmed refusal moved the current delivery back to pending.
-- now is the application clock. Unknown deliveries without a scheduled retry
-- and quota waits with an unknown reset wait for an operator.
-- name: ClaimDueDelivery :one
WITH candidate AS (
SELECT
@@ -245,12 +265,25 @@ WITH candidate AS (
coalesce(
extract(EPOCH FROM clock_timestamp() - due.first_send_started_at),
-1
)::float8 AS since_first_send_seconds
)::float8 AS since_first_send_seconds,
(due.manual_retry_authorized_at IS NOT NULL AND due.manual_retry_started_at IS NULL)
AS manual_retry_pending,
(due.manual_retry_started_at IS NOT NULL)::boolean AS manual_retry_cycle_started,
(
due.send_started_attempt_count IS NOT NULL
AND due.send_started_attempt_count = due.attempt_count
)::boolean AS send_start_unsettled,
EXISTS (
SELECT 1
FROM delivery_attempts AS prior_attempt
WHERE prior_attempt.delivery_id = due.id
AND prior_attempt.outcome = 'unknown'
)::boolean AS has_uncertain_attempt
FROM deliveries AS due
WHERE
due.kind IN ('verification', 'password_reset')
AND due.kind = any(sqlc.arg(kinds)::text [])
AND due.status IN ('pending', 'waiting_quota')
AND due.status IN ('pending', 'waiting_quota', 'unknown')
AND due.next_attempt_at IS NOT NULL
AND due.next_attempt_at <= sqlc.arg(now)::timestamptz
AND (
@@ -306,7 +339,144 @@ RETURNING
claimed.created_at,
claimed.updated_at,
candidate.previous_claimed_until,
candidate.since_first_send_seconds;
candidate.since_first_send_seconds,
candidate.manual_retry_pending,
candidate.manual_retry_cycle_started,
candidate.send_start_unsettled,
candidate.has_uncertain_attempt;
-- Authorizes one retry of a terminal unknown delivery. The update and append-
-- only decision share one statement and lock the current row, so a second or
-- concurrent operator decision cannot schedule another send for the same
-- unknown attempt. The provider account must still match the delivery's pin.
-- name: AuthorizeUnknownDeliveryRetry :execrows
WITH eligible AS MATERIALIZED (
SELECT
due.id,
(due.claim_owner IS NOT NULL) AS previous_lease_expired,
(
due.manual_retry_started_at IS NOT NULL
AND due.send_started_attempt_count = due.attempt_count
) AS unsettled_manual_send,
greatest(
clock_timestamp(),
due.updated_at,
coalesce(due.last_attempt_at, due.updated_at)
) AS lost_attempt_at
FROM deliveries AS due
WHERE
due.id = sqlc.arg(delivery_id)
AND due.status = 'unknown'
AND due.next_attempt_at IS NULL
AND (
due.claim_owner IS NULL
OR due.claimed_until <= clock_timestamp()
)
AND due.attempt_count > 0
AND due.provider = sqlc.arg(provider)
AND due.provider_account = sqlc.arg(provider_account)
AND due.first_send_started_at IS NOT NULL
AND clock_timestamp() - due.first_send_started_at
>= make_interval(secs => sqlc.arg(minimum_age_seconds)::float8)
AND sqlc.arg(duplicate_risk_acknowledged)::boolean
AND sqlc.arg(actor)::text ~ '^operator:[a-z0-9][a-z0-9._-]*$'
FOR UPDATE
), authorized AS (
UPDATE deliveries AS due
SET
attempt_count = due.attempt_count + CASE WHEN eligible.unsettled_manual_send THEN 1 ELSE 0 END,
last_attempt_at = CASE
WHEN eligible.unsettled_manual_send THEN eligible.lost_attempt_at
ELSE due.last_attempt_at
END,
next_attempt_at = greatest(
sqlc.arg(now)::timestamptz,
due.updated_at,
coalesce(eligible.lost_attempt_at, due.updated_at)
),
manual_retry_authorized_at = clock_timestamp(),
manual_retry_started_at = NULL,
claim_owner = NULL,
claimed_until = NULL,
version = due.version + 1,
updated_at = greatest(
due.updated_at,
sqlc.arg(now)::timestamptz,
coalesce(eligible.lost_attempt_at, due.updated_at)
)
FROM eligible
WHERE due.id = eligible.id
RETURNING
due.id,
due.attempt_count,
eligible.previous_lease_expired,
eligible.unsettled_manual_send,
eligible.lost_attempt_at
), recorded_lost_attempt AS (
-- A manual send whose lease expired after Mark but before settlement has
-- no provider answer. Preserve it as an unknown attempt before this new
-- explicit decision schedules another possible send.
INSERT INTO delivery_attempts (
delivery_id,
attempt_number,
attempted_at,
outcome,
rejection,
provider_code,
provider_message_id,
retry_after_ns,
status_after,
next_attempt_at
)
SELECT
authorized.id,
authorized.attempt_count,
authorized.lost_attempt_at,
'unknown',
NULL,
NULL,
NULL,
0,
'unknown',
NULL
FROM authorized
WHERE authorized.unsettled_manual_send
RETURNING delivery_id
)
INSERT INTO delivery_retry_decisions (
delivery_id,
attempt_count,
actor,
duplicate_risk_acknowledged,
previous_lease_expired,
decided_at
)
SELECT
authorized.id,
authorized.attempt_count,
sqlc.arg(actor),
sqlc.arg(duplicate_risk_acknowledged),
authorized.previous_lease_expired,
clock_timestamp()
FROM authorized;
-- Stops a due automatic retry of an unknown delivery without recording a
-- fictitious provider attempt, for example when the 23-hour safety cutoff is
-- reached after the claim but before the provider call.
-- name: StopUnknownDeliveryRetry :execrows
UPDATE deliveries
SET
status = 'unknown',
next_attempt_at = NULL,
claim_owner = NULL,
claimed_until = NULL,
version = deliveries.version + 1,
updated_at = greatest(deliveries.updated_at, sqlc.arg(now)::timestamptz)
WHERE
id = sqlc.arg(id)
AND status IN ('pending', 'waiting_quota', 'unknown')
AND next_attempt_at IS NOT NULL
AND claim_owner = sqlc.arg(lease_owner)::uuid;
-- Ends a claimed delivery whose stored content no longer matches its hash, so
-- one broken row never blocks the delivery queue. It matches only a delivery
@@ -428,19 +598,41 @@ WHERE
AND claim_owner = sqlc.arg(lease_owner)
FOR UPDATE;
-- 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
-- from this moment, so a later claim can tell whether repeating the request is
-- still safe. It never moves.
-- Notes that a request is about to start, by the database clock, and clears
-- the count of worker failures. For an operator-authorized send, this sets
-- its single-use marker without overwriting the original first-send time. The
-- marker captures the current attempt_count so a lost result can be recovered
-- as unknown instead of silently retried. When require_dedup_window is true,
-- the age check is repeated here after quota work and the row lock, immediately
-- before the network call; manual starts never reset that original window.
-- name: MarkDeliverySendStarted :execrows
UPDATE deliveries
SET
first_send_started_at = coalesce(deliveries.first_send_started_at, clock_timestamp()),
send_started_attempt_count = deliveries.attempt_count,
next_attempt_at = CASE
WHEN deliveries.manual_retry_authorized_at IS NOT NULL
AND deliveries.manual_retry_started_at IS NULL
THEN NULL
ELSE deliveries.next_attempt_at
END,
manual_retry_started_at = CASE
WHEN deliveries.manual_retry_authorized_at IS NOT NULL
AND deliveries.manual_retry_started_at IS NULL
THEN clock_timestamp()
ELSE deliveries.manual_retry_started_at
END,
failure_count = 0
WHERE
id = sqlc.arg(id)
AND claim_owner = sqlc.arg(lease_owner);
AND claim_owner = sqlc.arg(lease_owner)
AND (
NOT sqlc.arg(require_dedup_window)::boolean
OR (deliveries.manual_retry_authorized_at IS NOT NULL AND deliveries.manual_retry_started_at IS NULL)
OR coalesce(deliveries.manual_retry_started_at, deliveries.first_send_started_at) IS NULL
OR clock_timestamp() - coalesce(deliveries.manual_retry_started_at, deliveries.first_send_started_at)
< make_interval(secs => sqlc.arg(retry_window_seconds)::float8)
);
-- Gives a claimed delivery back without changing it, so the next pass may
-- claim it. It matches only the lease of lease_owner: a delivery that another