@davoodmehraban89 / VELYQOR / commits / 99697dc
Fork 0

Intelligence, Advanced Charting & Trading Platform

security(outbox): atomic single-use send permit protects against duplicate worker egress

davoodmehraban89 committed Oct 23, 2026 at 02:36 UTC 99697dc2d8b9b0eef2d8571056e632dd73c2a709
1 file changed +48
db/migrations/0006_alert_runtime_atomic.sql
+48
@@ -277,6 +277,52 @@ BEGIN
277 END;
278 $alert_claim$;
279
280 +-- A message leased to a sender may be processed by overlapping job retries.
281 +-- Atomically consume a single send permit before ANY external network call.
282 +-- If the sender crashes after this point, lease expiry becomes terminal UNKNOWN
283 +-- under PR #34 (at-most-once attempt, possibly no delivery).
284 +ALTER TABLE public.notification_outbox
285 + ADD COLUMN send_started_at TIMESTAMPTZ;
286 +
287 +CREATE FUNCTION public.alert_notification_begin_egress(
288 + p_outbox_id UUID,
289 + p_claim_token UUID,
290 + p_at TIMESTAMPTZ DEFAULT now()
291 +) RETURNS BOOLEAN
292 +LANGUAGE plpgsql
293 +SECURITY INVOKER
294 +SET search_path = pg_catalog, public
295 +AS $egress_begin$
296 +DECLARE
297 + v_id UUID;
298 +BEGIN
299 + IF p_outbox_id IS NULL OR p_claim_token IS NULL OR p_at IS NULL THEN
300 + RAISE EXCEPTION 'invalid one-send authorization parameters'
301 + USING ERRCODE = '22023';
302 + END IF;
303 +
304 + -- The UPDATE row-lock is the linearization point for all overlapping
305 + -- senders using the same lease. WHERE send_started_at IS NULL ensures a
306 + -- repeat caller receives FALSE without attempting a duplicate message.
307 + UPDATE public.notification_outbox AS o
308 + SET send_started_at = p_at, updated_at = p_at
309 + FROM public.alert_notification_consents AS c
310 + WHERE o.id = p_outbox_id
311 + AND o.lease_token = p_claim_token
312 + AND o.status = 'LEASED'
313 + AND o.send_started_at IS NULL
314 + AND o.leased_at <= p_at AND o.lease_until > p_at
315 + AND c.user_id = o.user_id
316 + AND c.channel = o.channel
317 + AND c.recipient_ref = o.recipient_ref
318 + AND c.consented_at <= p_at
319 + AND c.revoked_at IS NULL
320 + RETURNING o.id INTO v_id;
321 +
322 + RETURN v_id IS NOT NULL;
323 +END;
324 +$egress_begin$;
325 +
326 -- Second consent checkpoint immediately before a sender attempts HTTPS.
327 -- A claim-time check alone is insufficient: the user can revoke consent later.
328 -- This function is side-effect-free on a valid row, returns ONLY a boolean,
@@ -326,5 +372,7 @@ REVOKE ALL ON FUNCTION public.alert_notification_claim_consented(
372 TIMESTAMPTZ, INTEGER) FROM PUBLIC;
373 REVOKE ALL ON FUNCTION public.alert_notification_egress_allowed(
374 UUID, UUID, TIMESTAMPTZ) FROM PUBLIC;
375 +REVOKE ALL ON FUNCTION public.alert_notification_begin_egress(
376 + UUID, UUID, TIMESTAMPTZ) FROM PUBLIC;
377
378 COMMIT;