diff --git a/backend/docs/RESILIENCE_DLQ_CACHE_CONCURRENCY.md b/backend/docs/RESILIENCE_DLQ_CACHE_CONCURRENCY.md new file mode 100644 index 0000000..977f46e --- /dev/null +++ b/backend/docs/RESILIENCE_DLQ_CACHE_CONCURRENCY.md @@ -0,0 +1,72 @@ +# Dead-letter recovery, validator caching and merchant concurrency control + +Covers issues #1776, #1765, #1772 and #1771. + +## Shared building block: `RecoveryQueue` (`src/lib/recovery-queue.js`) + +A bounded in-memory dead-letter queue used by #1776 and #1771. + +| Property | Behaviour | +|----------|-----------| +| Capacity | 500 entries; when full, the oldest _exhausted_ entry is evicted first, then the oldest pending one | +| De-duplication | Re-enqueueing a key refreshes the entry instead of adding another | +| Backoff | Full-jitter exponential, base 2s, capped at 60s | +| Poison pills | After 5 failed recoveries, or an error with `retryable === false`, an entry is isolated as `exhausted` and never retried automatically | +| Safety | No overlapping recovery runs; bounded batch size; `list()` never exposes payloads; error messages are control-character stripped and truncated | + +Entries live in process memory and are lost on restart. They absorb transient outages; they are not a durable store. + +## #1776 Public Hosted Checkout Session Route (`routes/paymentDetails.js`) + +The Horizon transaction lookup behind `GET /api/payments/:id` used to drop the `stellar_tx` block on any transient failure. + +1. Transient failures (network errors, 408, 429, 5xx) are retried with backoff inside the request (3 attempts, <= 1.5s delay). +2. 404 (not yet propagated) and other 4xx are never retried. +3. A lookup that still fails transiently is dead-lettered **by transaction id only**, then re-driven in the background (throttled to one run per 15s, started only after a failure, `unref`'d). +4. A recovered lookup is cached for 10 minutes (max 1,000 entries), so the next request is served without another Horizon call. +5. `tx_id` must be a 64-hex hash before it is used in a Horizon request. + +The response shape is unchanged. Metrics: `payment_details_horizon_fetch_total{outcome}`, `payment_details_horizon_retries_total`, `payment_details_dlq_depth`, `payment_details_dlq_operations_total{action,status}`. + +Config: `PAYMENT_DETAILS_RETRY_MAX_ATTEMPTS` (1-5), `PAYMENT_DETAILS_RETRY_BASE_DELAY_MS`, `PAYMENT_DETAILS_RETRY_MAX_DELAY_MS`. + +## #1765 Stellar Account & Ledger Key Validator (`lib/stellar/validators*.js`) + +`resolveFederatedAddress` costs two HTTPS round trips, so successful results are now cached and concurrent identical lookups are coalesced. + +- Redis (shared across instances) with an in-memory LRU fallback (1,000 entries). A Redis outage degrades to per-instance caching and never fails a validation. +- **Opt-in:** set `VALIDATOR_CACHE_ENABLED=true`. Per call, `{ cache: false }` bypasses and `{ cache: }` supplies a store. +- TTL: `VALIDATOR_CACHE_TTL_SECONDS`, default 300, clamped to 1s-1h. +- Only successes are cached. Keys are `validator:v1:federation:`. Anything read back is re-validated (account id must be a valid public key, memo must pass `validateMemo`); a poisoned or corrupt entry is deleted and treated as a miss. + +Telemetry: `stellar_validator_throughput_per_second{operation}` (60s rolling window, refreshed at scrape time and bounded to 32 operations) and `stellar_validator_cache_operations_total{operation,result,backend}` where `result` is `hit | miss | set | invalid | error | coalesced`. `getValidatorThroughput()` is exported for in-process use. + +## #1772 Merchant Onboarding and Key Lifecycle Route (`routes/merchants.js`) + +Concurrency control and atomic credential writes (`lib/merchant-key-lifecycle.js`). + +- **Locking:** registration is serialized per email (SHA-256 of the lowercased address) and every key or secret operation per merchant id, using the Redis `SET NX PX` + compare-and-delete lock from `payment-session-lock.js` (in-process fallback when Redis is down). A losing request gets **409** `MERCHANT_LIFECYCLE_BUSY`; nothing queues. +- **Compare-and-swap:** `rotate-key`, `generate-api-key`, `regenerate-webhook-secret` and `rotate-webhook-secret` now update with `WHERE id = ? AND = `. If it no longer matches, the request gets **409** `MERCHANT_CREDENTIAL_CONFLICT` instead of overwriting the newer credential. The CAS is the correctness backstop if a lock expires or Redis is unreachable on one node. +- **Registration:** a unique violation (`23505`) on insert maps to the same 409 as the existence check. + +Metrics: `merchant_lifecycle_lock_total{operation,outcome}`, `merchant_lifecycle_lock_held_seconds`, `merchant_credential_conflicts_total`. + +## #1771 Merchant dead-letter recovery (`lib/merchant-recovery.js`) + +`POST /webhook-settings/verify` fetches a proof file from the merchant's domain and then persists the result. A transient persistence failure used to discard that result with a 500. + +1. The write is retried with backoff (3 attempts) on transient errors. +2. If it still fails, the verification result is dead-lettered (one entry per merchant) and the route answers **202** `{ webhook_domain_verification, persisted: false, recovery: "queued" }`. +3. Recovery does a read-merge-write of **only** the `webhook_domain_verification` metadata key, so a late recovery cannot overwrite other metadata. A merchant that no longer exists, or a non-transient error, isolates the entry immediately. + +Credential rotations are deliberately **not** retried or dead-lettered: they are not idempotent, and queueing a secret would hold it in memory. Locking plus compare-and-swap protect them instead. + +Metrics: `merchant_lifecycle_dlq_depth`, `merchant_lifecycle_dlq_operations_total{action,status}`, `merchant_lifecycle_persist_retries_total`. Config: `MERCHANT_PERSIST_RETRY_MAX_ATTEMPTS` (1-5), `..._BASE_DELAY_MS`, `..._MAX_DELAY_MS`. + +## Security notes + +- No secret (API key, webhook secret, password) is ever placed in a queue entry, lock key, metric label, log line or error message. +- Cache and lock keys are hashed/namespaced, so user input cannot inject separators or create oversized keys. +- Cached data is treated as untrusted on read. +- Memory is bounded everywhere (queue capacity, cache size, tracked operations); there are no import-time timers. +- Background recovery is throttled and non-overlapping, so a failing dependency cannot cause a retry storm. diff --git a/backend/src/lib/merchant-key-lifecycle.js b/backend/src/lib/merchant-key-lifecycle.js new file mode 100644 index 0000000..fec800d --- /dev/null +++ b/backend/src/lib/merchant-key-lifecycle.js @@ -0,0 +1,157 @@ +/** + * merchant-key-lifecycle.js + * + * Concurrency control and atomic credential updates for the Merchant + * Onboarding and Key Lifecycle Route (#1772). + * + * Problems this closes + * -------------------- + * 1. Duplicate registration. `register-merchant` checks "does this email + * exist?" and then inserts. Two concurrent requests for one email can both + * pass the check. Registration now runs under a per-email lock, and a + * database unique violation (23505) is mapped to the same 409. + * + * 2. Lost / interleaved rotations. Key and secret rotations were blind + * read-modify-writes: the "old" credential written to the grace-period slot + * came from the request context loaded BEFORE the update, so two concurrent + * rotations could overwrite each other and leave the merchant holding a key + * nobody was ever given. Rotations now (a) serialize per merchant under a + * distributed lock, and (b) write with a compare-and-swap on the credential + * that was read, so a stale writer is rejected (409) instead of clobbering + * the winner. The lock is the fast path; the CAS is the correctness + * backstop that still holds if the lock expires or Redis is down on one node. + * + * Locking reuses the Redis `SET NX PX` + compare-and-delete implementation from + * payment-session-lock.js (with its in-process fallback when Redis is + * unreachable). Lock keys use the merchant id, or a SHA-256 of the email, so + * user input never reaches the key namespace. + * + * A request that loses the race receives HTTP 409. It never queues, so there is + * no head-of-line blocking; the client retries. + */ + +import { createHash } from "node:crypto"; +import { acquireSessionLock } from "./payment-session-lock.js"; +import { logger } from "./logger.js"; +import { + merchantLockTotal, + merchantLockHeldSeconds, + merchantCredentialConflictsTotal, +} from "./merchant-lifecycle-metrics.js"; + +export const MERCHANT_LIFECYCLE_BUSY = "MERCHANT_LIFECYCLE_BUSY"; +export const MERCHANT_CREDENTIAL_CONFLICT = "MERCHANT_CREDENTIAL_CONFLICT"; + +/** Long enough for a rotation (one DB write), short enough to self-heal. */ +export const MERCHANT_LOCK_TTL_MS = 15_000; + +const LOCK_PREFIX = "lock:merchant"; + +/** + * @param {"key"|"register"} scope + * @param {string} id Merchant id for "key", email for "register" + */ +export function buildMerchantLockKey(scope, id) { + if (scope !== "key" && scope !== "register") { + throw new TypeError(`Unknown merchant lock scope: ${scope}`); + } + if (!id || typeof id !== "string") { + throw new TypeError("A merchant lock requires a non-empty string id"); + } + const part = + scope === "register" + ? createHash("sha256").update(id.trim().toLowerCase()).digest("hex") + : id; + return `${LOCK_PREFIX}:${scope}:${part}`; +} + +export function createLifecycleBusyError(operation) { + const error = new Error( + "Another credential operation for this merchant is in progress. Retry shortly.", + ); + error.status = 409; + error.code = MERCHANT_LIFECYCLE_BUSY; + error.retryable = false; + error.operation = operation; + return error; +} + +export function createCredentialConflictError(operation) { + const error = new Error( + "The credential changed while this request was running. Re-fetch and retry.", + ); + error.status = 409; + error.code = MERCHANT_CREDENTIAL_CONFLICT; + error.retryable = false; + error.operation = operation; + return error; +} + +/** + * Run `fn` while holding the merchant lock; reject with 409 when it is held. + * + * @template T + * @param {{ scope: "key"|"register", id: string, operation: string }} lockScope + * @param {() => Promise} fn + * @param {{ ttlMs?: number, getRedis?: () => Promise }} [options] + * @returns {Promise} + */ +export async function withMerchantLock({ scope, id, operation }, fn, options = {}) { + const key = buildMerchantLockKey(scope, id); + const lock = await acquireSessionLock(key, { + ttlMs: options.ttlMs ?? MERCHANT_LOCK_TTL_MS, + ...(options.getRedis ? { getRedis: options.getRedis } : {}), + }); + + if (!lock) { + merchantLockTotal.inc({ operation, outcome: "contended" }); + logger.warn({ operation, scope }, "Merchant lifecycle request rejected: lock held"); + throw createLifecycleBusyError(operation); + } + + merchantLockTotal.inc({ operation, outcome: "acquired" }); + const startedAt = Date.now(); + try { + return await fn(); + } finally { + merchantLockHeldSeconds.observe({ operation }, (Date.now() - startedAt) / 1000); + await lock.release(); + } +} + +/** + * Atomically replace a merchant credential: the update only applies if + * `expected.column` still equals `expected.value`. + * + * `supabase` is injected so callers (and tests) control the client. A missing + * stored credential (`null`) is matched with IS NULL. + * + * @throws 409 (MERCHANT_CREDENTIAL_CONFLICT) when the stored value changed or + * the merchant no longer exists; the original database error (status 500) + * for any other failure. + */ +export async function compareAndSwapMerchant( + supabase, + merchantId, + expected, + patch, + operation = "credential_update", +) { + let query = supabase.from("merchants").update(patch).eq("id", merchantId); + query = + expected.value === null || expected.value === undefined + ? query.is(expected.column, null) + : query.eq(expected.column, expected.value); + + const { data, error } = await query.select("id"); + + if (error) { + error.status = 500; + throw error; + } + if (!Array.isArray(data) || data.length === 0) { + merchantCredentialConflictsTotal.inc({ operation }); + throw createCredentialConflictError(operation); + } + return data[0]; +} diff --git a/backend/src/lib/merchant-key-lifecycle.test.js b/backend/src/lib/merchant-key-lifecycle.test.js new file mode 100644 index 0000000..7fae253 --- /dev/null +++ b/backend/src/lib/merchant-key-lifecycle.test.js @@ -0,0 +1,254 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { + buildMerchantLockKey, + withMerchantLock, + compareAndSwapMerchant, + createLifecycleBusyError, + MERCHANT_LIFECYCLE_BUSY, + MERCHANT_CREDENTIAL_CONFLICT, +} from "./merchant-key-lifecycle.js"; +import { resetLocalSessionLocksForTests } from "./payment-session-lock.js"; +import { + merchantLifecycleRegister, + resetMerchantLifecycleMetrics, +} from "./merchant-lifecycle-metrics.js"; + +// A no-op Redis client forces the in-process lock, which is what we can test deterministically. +const noRedis = async () => ({ isOpen: false }); + +async function metric(name, labels = {}) { + const m = await merchantLifecycleRegister.getSingleMetric(name).get(); + const hit = m.values.find((v) => Object.entries(labels).every(([k, val]) => v.labels[k] === val)); + return hit ? hit.value : 0; +} + +function deferred() { + let resolve; + const promise = new Promise((r) => { + resolve = r; + }); + return { promise, resolve }; +} + +/** Minimal chainable supabase double for the CAS update. */ +function supabaseReturning(result) { + const calls = { eq: [], is: [], update: null }; + const builder = { + update(patch) { + calls.update = patch; + return builder; + }, + eq(col, val) { + calls.eq.push([col, val]); + return builder; + }, + is(col, val) { + calls.is.push([col, val]); + return builder; + }, + select: vi.fn(async () => result), + }; + return { client: { from: vi.fn(() => builder) }, calls, builder }; +} + +describe("buildMerchantLockKey", () => { + it("scopes key locks by merchant id", () => { + expect(buildMerchantLockKey("key", "m-1")).toBe("lock:merchant:key:m-1"); + }); + + it("hashes and lowercases the email for registration locks", () => { + const a = buildMerchantLockKey("register", "Alice@Example.com"); + const b = buildMerchantLockKey("register", " alice@example.com "); + expect(a).toBe(b); + expect(a).toMatch(/^lock:merchant:register:[0-9a-f]{64}$/); + expect(a).not.toContain("alice"); + }); + + it("rejects bad input", () => { + expect(() => buildMerchantLockKey("nope", "x")).toThrow(TypeError); + expect(() => buildMerchantLockKey("key", "")).toThrow(TypeError); + expect(() => buildMerchantLockKey("key", 5)).toThrow(TypeError); + }); +}); + +describe("withMerchantLock", () => { + beforeEach(() => { + resetLocalSessionLocksForTests(); + resetMerchantLifecycleMetrics(); + }); + + it("runs the function and returns its result", async () => { + const result = await withMerchantLock( + { scope: "key", id: "m-1", operation: "rotate_key" }, + async () => "done", + { getRedis: noRedis }, + ); + expect(result).toBe("done"); + expect(await metric("merchant_lifecycle_lock_total", { operation: "rotate_key", outcome: "acquired" })).toBe(1); + }); + + it("rejects a concurrent operation for the same merchant with 409", async () => { + const gate = deferred(); + const first = withMerchantLock( + { scope: "key", id: "m-1", operation: "rotate_key" }, + () => gate.promise, + { getRedis: noRedis }, + ); + + await expect( + withMerchantLock({ scope: "key", id: "m-1", operation: "rotate_webhook_secret" }, async () => "x", { + getRedis: noRedis, + }), + ).rejects.toMatchObject({ status: 409, code: MERCHANT_LIFECYCLE_BUSY }); + + gate.resolve("ok"); + await first; + expect( + await metric("merchant_lifecycle_lock_total", { operation: "rotate_webhook_secret", outcome: "contended" }), + ).toBe(1); + }); + + it("allows different merchants to run in parallel", async () => { + const gate = deferred(); + const first = withMerchantLock({ scope: "key", id: "m-1", operation: "rotate_key" }, () => gate.promise, { + getRedis: noRedis, + }); + const other = await withMerchantLock({ scope: "key", id: "m-2", operation: "rotate_key" }, async () => "ok", { + getRedis: noRedis, + }); + expect(other).toBe("ok"); + gate.resolve(); + await first; + }); + + it("keeps registration and key locks independent", async () => { + const gate = deferred(); + const reg = withMerchantLock({ scope: "register", id: "a@b.co", operation: "register" }, () => gate.promise, { + getRedis: noRedis, + }); + const key = await withMerchantLock({ scope: "key", id: "a@b.co", operation: "rotate_key" }, async () => 1, { + getRedis: noRedis, + }); + expect(key).toBe(1); + gate.resolve(); + await reg; + }); + + it("releases the lock after success so the next request proceeds", async () => { + const scope = { scope: "key", id: "m-1", operation: "rotate_key" }; + await withMerchantLock(scope, async () => 1, { getRedis: noRedis }); + await expect(withMerchantLock(scope, async () => 2, { getRedis: noRedis })).resolves.toBe(2); + }); + + it("releases the lock when the function throws", async () => { + const scope = { scope: "key", id: "m-1", operation: "rotate_key" }; + await expect( + withMerchantLock( + scope, + async () => { + throw new Error("db down"); + }, + { getRedis: noRedis }, + ), + ).rejects.toThrow("db down"); + await expect(withMerchantLock(scope, async () => "ok", { getRedis: noRedis })).resolves.toBe("ok"); + }); + + it("serializes N concurrent callers so exactly one wins", async () => { + const gate = deferred(); + let entered = 0; + const attempts = Array.from({ length: 5 }, () => + withMerchantLock( + { scope: "key", id: "m-1", operation: "rotate_key" }, + async () => { + entered += 1; + await gate.promise; + }, + { getRedis: noRedis }, + ).then( + () => "won", + (err) => err.code, + ), + ); + await new Promise((r) => setTimeout(r, 10)); + gate.resolve(); + const outcomes = await Promise.all(attempts); + + expect(entered).toBe(1); + expect(outcomes.filter((o) => o === "won")).toHaveLength(1); + expect(outcomes.filter((o) => o === MERCHANT_LIFECYCLE_BUSY)).toHaveLength(4); + }); + + it("builds a retry-safe busy error", () => { + const err = createLifecycleBusyError("rotate_key"); + expect(err.status).toBe(409); + expect(err.retryable).toBe(false); + expect(err.message).not.toMatch(/sk_|whsec_/); + }); +}); + +describe("compareAndSwapMerchant", () => { + beforeEach(() => resetMerchantLifecycleMetrics()); + + it("updates only when the stored credential still matches", async () => { + const { client, calls } = supabaseReturning({ data: [{ id: "m-1" }], error: null }); + + const row = await compareAndSwapMerchant( + client, + "m-1", + { column: "api_key", value: "sk_old" }, + { api_key: "sk_new" }, + "rotate_key", + ); + + expect(row).toEqual({ id: "m-1" }); + expect(calls.update).toEqual({ api_key: "sk_new" }); + expect(calls.eq).toEqual([ + ["id", "m-1"], + ["api_key", "sk_old"], + ]); + }); + + it("matches a missing credential with IS NULL", async () => { + const { client, calls } = supabaseReturning({ data: [{ id: "m-1" }], error: null }); + await compareAndSwapMerchant(client, "m-1", { column: "api_key", value: null }, { api_key: "sk_new" }); + expect(calls.is).toEqual([["api_key", null]]); + expect(calls.eq).toEqual([["id", "m-1"]]); + }); + + it("throws 409 when no row matched (stale credential or deleted merchant)", async () => { + const { client } = supabaseReturning({ data: [], error: null }); + + await expect( + compareAndSwapMerchant(client, "m-1", { column: "api_key", value: "sk_old" }, { api_key: "sk_new" }, "rotate_key"), + ).rejects.toMatchObject({ status: 409, code: MERCHANT_CREDENTIAL_CONFLICT }); + expect(await metric("merchant_credential_conflicts_total", { operation: "rotate_key" })).toBe(1); + }); + + it("treats a null data result as a conflict", async () => { + const { client } = supabaseReturning({ data: null, error: null }); + await expect( + compareAndSwapMerchant(client, "m-1", { column: "api_key", value: "x" }, {}), + ).rejects.toMatchObject({ status: 409 }); + }); + + it("propagates database errors as 500", async () => { + const dbError = new Error("connection lost"); + const { client } = supabaseReturning({ data: null, error: dbError }); + + await expect( + compareAndSwapMerchant(client, "m-1", { column: "api_key", value: "x" }, {}), + ).rejects.toMatchObject({ status: 500, message: "connection lost" }); + }); + + it("never puts credentials in the conflict error", async () => { + const { client } = supabaseReturning({ data: [], error: null }); + const err = await compareAndSwapMerchant( + client, + "m-1", + { column: "api_key", value: "sk_supersecret" }, + { api_key: "sk_newsecret" }, + ).catch((e) => e); + expect(JSON.stringify({ message: err.message, code: err.code })).not.toMatch(/supersecret|newsecret/); + }); +}); diff --git a/backend/src/lib/merchant-lifecycle-metrics.js b/backend/src/lib/merchant-lifecycle-metrics.js new file mode 100644 index 0000000..7f0d403 --- /dev/null +++ b/backend/src/lib/merchant-lifecycle-metrics.js @@ -0,0 +1,65 @@ +import client from "prom-client"; + +/** + * Metrics for the Merchant Onboarding and Key Lifecycle Route: concurrency + * control (#1772) and dead-letter recovery (#1771). Isolated registry, merged + * into /metrics by routes/prometheus.js. + */ +export const merchantLifecycleRegister = new client.Registry(); +merchantLifecycleRegister.setDefaultLabels({ app: "stellar-payment-api" }); + +/** + * operation: register | rotate_api_key | generate_api_key | regenerate_webhook_secret | rotate_webhook_secret + * outcome: acquired | contended + */ +export const merchantLockTotal = new client.Counter({ + name: "merchant_lifecycle_lock_total", + help: "Merchant lifecycle lock acquisitions by operation and outcome", + labelNames: ["operation", "outcome"], + registers: [merchantLifecycleRegister], +}); + +export const merchantLockHeldSeconds = new client.Histogram({ + name: "merchant_lifecycle_lock_held_seconds", + help: "How long a merchant lifecycle lock was held", + labelNames: ["operation"], + buckets: [0.005, 0.025, 0.1, 0.25, 0.5, 1, 2.5, 5, 15], + registers: [merchantLifecycleRegister], +}); + +/** A credential update rejected because the stored credential changed underneath it. */ +export const merchantCredentialConflictsTotal = new client.Counter({ + name: "merchant_credential_conflicts_total", + help: "Credential updates rejected by the compare-and-swap guard", + labelNames: ["operation"], + registers: [merchantLifecycleRegister], +}); + +export const merchantPersistRetriesTotal = new client.Counter({ + name: "merchant_lifecycle_persist_retries_total", + help: "Retried transient merchant metadata persistence failures", + registers: [merchantLifecycleRegister], +}); + +export const merchantDlqDepth = new client.Gauge({ + name: "merchant_lifecycle_dlq_depth", + help: "Current number of merchant writes in the dead-letter queue", + registers: [merchantLifecycleRegister], +}); + +/** action: push | recover | retry | exhaust | evict | clear */ +export const merchantDlqOperationsTotal = new client.Counter({ + name: "merchant_lifecycle_dlq_operations_total", + help: "Merchant lifecycle dead-letter queue operations by action and status", + labelNames: ["action", "status"], + registers: [merchantLifecycleRegister], +}); + +export function resetMerchantLifecycleMetrics() { + merchantLockTotal.reset(); + merchantLockHeldSeconds.reset(); + merchantCredentialConflictsTotal.reset(); + merchantPersistRetriesTotal.reset(); + merchantDlqDepth.reset(); + merchantDlqOperationsTotal.reset(); +} diff --git a/backend/src/lib/merchant-recovery.js b/backend/src/lib/merchant-recovery.js new file mode 100644 index 0000000..b5a92b9 --- /dev/null +++ b/backend/src/lib/merchant-recovery.js @@ -0,0 +1,176 @@ +/** + * merchant-recovery.js + * + * Automated retry and dead-letter recovery for the Merchant Onboarding and Key + * Lifecycle Route (#1771). + * + * Webhook domain verification does network work (fetching a proof file from the + * merchant's domain) and then persists the result on the merchant row. If that + * persistence fails transiently, the verification result is lost and the + * merchant must repeat a slow, rate-limited action. Now: + * + * 1. The write is retried with full-jitter backoff on transient failures + * (network errors, 408/429/5xx, connection-class Postgres errors). + * 2. If it still fails transiently, the verification RESULT is dead-lettered + * (keyed per merchant, so retries coalesce) and the route answers 202 with + * the result and `persisted: false`, instead of a 500 that discards it. + * 3. Dead-lettered writes are recovered in the background with backoff, and + * after repeated failure are isolated as poison pills. + * + * Recovery is a read-merge-write of ONLY the `webhook_domain_verification` + * metadata key, never a replacement of the whole metadata object, so a late + * recovery cannot overwrite other metadata the merchant changed in the meantime. + * + * Credential rotations are deliberately NOT retried or dead-lettered: they are + * not idempotent, and queueing a secret would put it in process memory. They are + * protected by locking and compare-and-swap instead (merchant-key-lifecycle.js). + * + * Queue entries contain the merchant id and the verification record (domain, + * challenge token, status) and never an API key, webhook secret or password. + */ + +import { logger as defaultLogger } from "./logger.js"; +import { retrySupabaseRead, resolveBackoffOptions } from "./backoff-retry.js"; +import { isRetryableSessionError } from "./payment-session-retry.js"; +import { RecoveryQueue } from "./recovery-queue.js"; +import { + merchantDlqDepth, + merchantDlqOperationsTotal, + merchantPersistRetriesTotal, +} from "./merchant-lifecycle-metrics.js"; + +export const VERIFICATION_METADATA_KEY = "webhook_domain_verification"; + +const RETRY_SPEC = Object.freeze({ + envPrefix: "MERCHANT_PERSIST_RETRY", + defaults: { maxAttempts: 3, baseDelayMs: 100, maxDelayMs: 1_000 }, + maxAttemptsCeiling: 5, + maxDelayCeilingMs: 5_000, +}); + +const RECOVERY_MIN_INTERVAL_MS = 15_000; + +export const merchantDlq = new RecoveryQueue({ + name: "merchant_lifecycle", + maxCapacity: 500, + maxAttempts: 5, + baseDelayMs: 2_000, + maxDelayMs: 60_000, + metrics: { + onDepth: (n) => merchantDlqDepth.set(n), + onOperation: (action, status) => merchantDlqOperationsTotal.inc({ action, status }), + }, +}); + +let lastRecoveryStartedAt = 0; + +export function resetMerchantRecoveryForTests() { + merchantDlq.clear(); + lastRecoveryStartedAt = 0; +} + +function dlqKey(merchantId) { + return `verification:${merchantId}`; +} + +/** + * Persist a webhook domain verification result with retry and dead-lettering. + * + * @param {object} supabase + * @param {{ merchantId: string, metadata: object, verification: object }} data + * `metadata` is the full next metadata (used for the immediate write); + * `verification` is the single record that is re-applied on recovery. + * @returns {Promise<{ persisted: true } | { persisted: false, queued: true }>} + * @throws the database error (status 500) when the failure is not transient. + */ +export async function persistVerificationWithRecovery( + supabase, + { merchantId, metadata, verification }, + options = {}, +) { + const { logger = defaultLogger, sleep, random, scheduleRecovery: shouldSchedule = true } = options; + + const result = await retrySupabaseRead( + () => supabase.from("merchants").update({ metadata }).eq("id", merchantId), + { + resolved: resolveBackoffOptions({}, process.env, RETRY_SPEC), + label: "merchant_verification_persist", + onRetry: () => merchantPersistRetriesTotal.inc(), + ...(sleep ? { sleep } : {}), + ...(random ? { random } : {}), + logger, + }, + ); + + const error = result?.error; + if (!error) return { persisted: true }; + + if (isRetryableSessionError(error)) { + merchantDlq.enqueue(dlqKey(merchantId), { merchantId, verification }, error); + if (shouldSchedule) scheduleMerchantRecovery({ supabase, logger }); + return { persisted: false, queued: true }; + } + + error.status = 500; + throw error; +} + +/** + * Re-apply one dead-lettered verification: read the current metadata, merge only + * the verification record, write it back. Throws to signal failure; errors that + * can never succeed are marked non-retryable so the entry is isolated at once. + */ +async function applyVerification(supabase, entry) { + const { merchantId, verification } = entry.payload; + + const { data, error: readError } = await supabase + .from("merchants") + .select("metadata") + .eq("id", merchantId) + .maybeSingle(); + if (readError) throw readError; + if (!data) { + const gone = new Error("Merchant no longer exists"); + gone.retryable = false; + throw gone; + } + + const current = + data.metadata && typeof data.metadata === "object" && !Array.isArray(data.metadata) + ? data.metadata + : {}; + const { error: writeError } = await supabase + .from("merchants") + .update({ metadata: { ...current, [VERIFICATION_METADATA_KEY]: verification } }) + .eq("id", merchantId); + if (writeError) { + if (!isRetryableSessionError(writeError)) writeError.retryable = false; + throw writeError; + } +} + +/** + * Re-drive due dead-lettered merchant writes. Also suitable for a scheduled job. + */ +export async function recoverMerchantDlq({ supabase, maxBatch = 10 } = {}) { + if (!supabase) throw new TypeError("recoverMerchantDlq requires a supabase client"); + return merchantDlq.recover((entry) => applyVerification(supabase, entry), { maxBatch }); +} + +/** + * Throttled, fire-and-forget recovery. At most one run per + * RECOVERY_MIN_INTERVAL_MS; no timer exists until a failure occurs. + */ +export function scheduleMerchantRecovery({ supabase, now = Date.now, logger = defaultLogger } = {}) { + const current = now(); + if (current - lastRecoveryStartedAt < RECOVERY_MIN_INTERVAL_MS) return false; + lastRecoveryStartedAt = current; + + const timer = setTimeout(() => { + recoverMerchantDlq({ supabase }).catch((err) => { + logger.error?.({ err: err?.message }, "Merchant DLQ recovery run failed"); + }); + }, 0); + timer.unref?.(); + return true; +} diff --git a/backend/src/lib/merchant-recovery.test.js b/backend/src/lib/merchant-recovery.test.js new file mode 100644 index 0000000..a630029 --- /dev/null +++ b/backend/src/lib/merchant-recovery.test.js @@ -0,0 +1,222 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { + persistVerificationWithRecovery, + recoverMerchantDlq, + scheduleMerchantRecovery, + merchantDlq, + resetMerchantRecoveryForTests, + VERIFICATION_METADATA_KEY, +} from "./merchant-recovery.js"; +import { + merchantLifecycleRegister, + resetMerchantLifecycleMetrics, +} from "./merchant-lifecycle-metrics.js"; + +const silentLogger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() }; +const noSleep = async () => {}; +const VERIFICATION = { + status: "verified", + domain: "shop.example.com", + verification_token: "tok_public_challenge", + checked_at: "2026-01-01T00:00:00Z", +}; + +function pgError(code, message = `pg ${code}`) { + return Object.assign(new Error(message), { code }); +} + +/** Supabase double where update() results come from a queue. */ +function makeSupabase({ updateResults = [], row = { metadata: { other: 1 } }, readError = null } = {}) { + const updates = []; + const queue = [...updateResults]; + const from = vi.fn(() => ({ + update(patch) { + updates.push(patch); + return { + eq: vi.fn(async () => (queue.length ? queue.shift() : { error: null })), + }; + }, + select() { + return { + eq: () => ({ maybeSingle: async () => ({ data: row, error: readError }) }), + }; + }, + })); + return { client: { from }, updates }; +} + +async function metric(name, labels = {}) { + const m = await merchantLifecycleRegister.getSingleMetric(name).get(); + const hit = m.values.find((v) => Object.entries(labels).every(([k, val]) => v.labels[k] === val)); + return hit ? hit.value : 0; +} + +function persist(client, extra = {}) { + return persistVerificationWithRecovery( + client, + { merchantId: "m-1", metadata: { [VERIFICATION_METADATA_KEY]: VERIFICATION }, verification: VERIFICATION }, + { sleep: noSleep, random: () => 0, logger: silentLogger, scheduleRecovery: false, ...extra }, + ); +} + +describe("persistVerificationWithRecovery", () => { + beforeEach(() => { + resetMerchantRecoveryForTests(); + resetMerchantLifecycleMetrics(); + vi.clearAllMocks(); + }); + + it("persists on the first attempt", async () => { + const { client, updates } = makeSupabase(); + + expect(await persist(client)).toEqual({ persisted: true }); + expect(updates).toHaveLength(1); + expect(merchantDlq.size).toBe(0); + }); + + it("retries a transient failure and then persists", async () => { + const { client, updates } = makeSupabase({ + updateResults: [{ error: pgError("08006") }, { error: { message: "x", status: 503 } }, { error: null }], + }); + + expect(await persist(client)).toEqual({ persisted: true }); + expect(updates).toHaveLength(3); + expect(await metric("merchant_lifecycle_persist_retries_total")).toBe(2); + }); + + it("dead-letters the result when transient failures persist", async () => { + const down = { error: pgError("08006", "connection failure") }; + const { client } = makeSupabase({ updateResults: [down, down, down] }); + + expect(await persist(client)).toEqual({ persisted: false, queued: true }); + expect(merchantDlq.size).toBe(1); + expect(merchantDlq.has("verification:m-1")).toBe(true); + expect(await metric("merchant_lifecycle_dlq_operations_total", { action: "push", status: "success" })).toBe(1); + }); + + it("does not retry or dead-letter a non-transient error", async () => { + const constraint = pgError("23505", "duplicate"); + const { client, updates } = makeSupabase({ updateResults: [{ error: constraint }] }); + + await expect(persist(client)).rejects.toMatchObject({ status: 500, code: "23505" }); + expect(updates).toHaveLength(1); + expect(merchantDlq.size).toBe(0); + }); + + it("coalesces repeated failures for one merchant", async () => { + const down = { error: pgError("08006") }; + const { client } = makeSupabase({ updateResults: [down, down, down, down, down, down] }); + await persist(client); + await persist(client); + expect(merchantDlq.size).toBe(1); + }); + + it("never queues credentials", async () => { + const down = { error: pgError("08006") }; + const { client } = makeSupabase({ updateResults: [down, down, down] }); + await persist(client); + + const entry = merchantDlq._entries.get("verification:m-1"); + expect(Object.keys(entry.payload).sort()).toEqual(["merchantId", "verification"]); + expect(JSON.stringify(entry)).not.toMatch(/api_key|webhook_secret|password|sk_|whsec_/); + }); +}); + +describe("recoverMerchantDlq", () => { + beforeEach(() => { + resetMerchantRecoveryForTests(); + resetMerchantLifecycleMetrics(); + vi.clearAllMocks(); + }); + + async function deadLetter() { + const down = { error: pgError("08006") }; + await persist(makeSupabase({ updateResults: [down, down, down] }).client); + merchantDlq._entries.get("verification:m-1").nextRetryAt = 0; + } + + it("requires a supabase client", async () => { + await expect(recoverMerchantDlq({})).rejects.toThrow(TypeError); + }); + + it("merges only the verification key into the current metadata", async () => { + await deadLetter(); + const { client, updates } = makeSupabase({ row: { metadata: { other: 1, theme: "dark" } } }); + + const result = await recoverMerchantDlq({ supabase: client }); + + expect(result).toMatchObject({ recovered: 1, failed: 0, exhausted: 0 }); + expect(updates).toEqual([ + { metadata: { other: 1, theme: "dark", [VERIFICATION_METADATA_KEY]: VERIFICATION } }, + ]); + expect(merchantDlq.size).toBe(0); + }); + + it("handles a merchant with no metadata yet", async () => { + await deadLetter(); + const { client, updates } = makeSupabase({ row: { metadata: null } }); + + await recoverMerchantDlq({ supabase: client }); + + expect(updates[0]).toEqual({ metadata: { [VERIFICATION_METADATA_KEY]: VERIFICATION } }); + }); + + it("isolates the entry at once when the merchant no longer exists", async () => { + await deadLetter(); + const { client } = makeSupabase({ row: null }); + + const result = await recoverMerchantDlq({ supabase: client }); + + expect(result.exhausted).toBe(1); + expect(merchantDlq.stats()).toEqual({ total: 1, pending: 0, exhausted: 1 }); + }); + + it("isolates the entry at once on a non-transient write error", async () => { + await deadLetter(); + const { client } = makeSupabase({ updateResults: [{ error: pgError("23514", "check violation") }] }); + + const result = await recoverMerchantDlq({ supabase: client }); + + expect(result.exhausted).toBe(1); + }); + + it("backs off on a transient failure and keeps the entry", async () => { + await deadLetter(); + const { client } = makeSupabase({ updateResults: [{ error: pgError("08006") }] }); + + const result = await recoverMerchantDlq({ supabase: client }); + + expect(result).toMatchObject({ failed: 1, exhausted: 0 }); + expect(merchantDlq.size).toBe(1); + expect(merchantDlq.list()[0].attempts).toBe(1); + }); + + it("surfaces a read failure as a retryable failure", async () => { + await deadLetter(); + const { client } = makeSupabase({ readError: pgError("08006") }); + + const result = await recoverMerchantDlq({ supabase: client }); + + expect(result.failed).toBe(1); + expect(merchantDlq.size).toBe(1); + }); + + it("throttles background recovery to one run per window", async () => { + vi.useFakeTimers(); + try { + await deadLetter(); + const { client } = makeSupabase(); + let now = 5_000_000; + + expect(scheduleMerchantRecovery({ supabase: client, now: () => now, logger: silentLogger })).toBe(true); + expect(scheduleMerchantRecovery({ supabase: client, now: () => now + 500, logger: silentLogger })).toBe(false); + await vi.runAllTimersAsync(); + expect(merchantDlq.size).toBe(0); + + now += 20_000; + expect(scheduleMerchantRecovery({ supabase: client, now: () => now, logger: silentLogger })).toBe(true); + } finally { + vi.useRealTimers(); + } + }); +}); diff --git a/backend/src/lib/payment-details-metrics.js b/backend/src/lib/payment-details-metrics.js new file mode 100644 index 0000000..89f2d54 --- /dev/null +++ b/backend/src/lib/payment-details-metrics.js @@ -0,0 +1,44 @@ +import client from "prom-client"; + +/** + * Metrics for the Public Hosted Checkout Session Route's Horizon lookups and + * dead-letter recovery (#1776). Isolated registry, merged into /metrics by + * routes/prometheus.js. + */ +export const paymentDetailsRegister = new client.Registry(); +paymentDetailsRegister.setDefaultLabels({ app: "stellar-payment-api" }); + +/** outcome: success | cache_hit | not_found | error | dead_lettered */ +export const paymentDetailsHorizonFetchTotal = new client.Counter({ + name: "payment_details_horizon_fetch_total", + help: "Horizon transaction lookups for payment details by outcome", + labelNames: ["outcome"], + registers: [paymentDetailsRegister], +}); + +export const paymentDetailsHorizonRetriesTotal = new client.Counter({ + name: "payment_details_horizon_retries_total", + help: "Retried Horizon transaction lookups for payment details", + registers: [paymentDetailsRegister], +}); + +export const paymentDetailsDlqDepth = new client.Gauge({ + name: "payment_details_dlq_depth", + help: "Current number of payment-details lookups in the dead-letter queue", + registers: [paymentDetailsRegister], +}); + +/** action: push | recover | retry | exhaust | evict | clear */ +export const paymentDetailsDlqOperationsTotal = new client.Counter({ + name: "payment_details_dlq_operations_total", + help: "Payment-details dead-letter queue operations by action and status", + labelNames: ["action", "status"], + registers: [paymentDetailsRegister], +}); + +export function resetPaymentDetailsMetrics() { + paymentDetailsHorizonFetchTotal.reset(); + paymentDetailsHorizonRetriesTotal.reset(); + paymentDetailsDlqDepth.reset(); + paymentDetailsDlqOperationsTotal.reset(); +} diff --git a/backend/src/lib/payment-details-recovery.js b/backend/src/lib/payment-details-recovery.js new file mode 100644 index 0000000..4035e7f --- /dev/null +++ b/backend/src/lib/payment-details-recovery.js @@ -0,0 +1,225 @@ +/** + * payment-details-recovery.js + * + * Automated retry and dead-letter recovery for the Horizon transaction lookup + * behind the Public Hosted Checkout Session Route (#1776). + * + * The route always returns the payment record; the on-chain `stellar_tx` block + * is best effort. Previously one transient Horizon failure silently dropped it. + * Now: + * + * 1. Transient failures (network errors, 408, 429, 5xx) are retried with + * full-jitter backoff inside the request, bounded so the response stays fast. + * 404 (not yet propagated) and other 4xx are never retried in-request. + * 2. A lookup that still fails transiently is dead-lettered by transaction id + * (never by payment data) and re-driven in the background with backoff. + * 3. A recovered lookup is stored in a small TTL cache, so the next request + * for that transaction is served without another Horizon call. Completed + * transactions are immutable, so the cache cannot go stale. + * + * Background recovery is opportunistic: a throttled, fire-and-forget run is + * triggered after a dead-letter, so no timer is created at import time and + * nothing keeps the process alive. `recoverPaymentDetailsDlq()` is also exported + * for a scheduled job. + * + * Security: queue entries hold only the tx id (a public, 64-hex Horizon + * identifier). Logs never include payment amounts, recipients or memos. + */ + +import { logger as defaultLogger } from "./logger.js"; +import { retryWithBackoff, resolveBackoffOptions } from "./backoff-retry.js"; +import { RecoveryQueue } from "./recovery-queue.js"; +import { + paymentDetailsHorizonFetchTotal, + paymentDetailsHorizonRetriesTotal, + paymentDetailsDlqDepth, + paymentDetailsDlqOperationsTotal, +} from "./payment-details-metrics.js"; + +export const TX_ID_PATTERN = /^[0-9a-fA-F]{64}$/; + +const RETRY_SPEC = Object.freeze({ + envPrefix: "PAYMENT_DETAILS_RETRY", + defaults: { maxAttempts: 3, baseDelayMs: 150, maxDelayMs: 1_500 }, + maxAttemptsCeiling: 5, + maxDelayCeilingMs: 5_000, +}); + +const CACHE_TTL_MS = 10 * 60 * 1000; +const CACHE_MAX_ENTRIES = 1_000; +const RECOVERY_MIN_INTERVAL_MS = 15_000; + +const RETRYABLE_NETWORK_CODES = new Set([ + "ECONNRESET", + "ECONNREFUSED", + "ECONNABORTED", + "ETIMEDOUT", + "EPIPE", + "EAI_AGAIN", + "ENOTFOUND", + "EHOSTUNREACH", + "ENETUNREACH", +]); + +function statusOf(err) { + const status = err?.response?.status ?? err?.status ?? err?.statusCode; + return typeof status === "number" ? status : null; +} + +export function isHorizonNotFound(err) { + return statusOf(err) === 404; +} + +/** Transient Horizon failures worth retrying. 404 and other 4xx are deterministic. */ +export function isHorizonRetryable(err) { + if (!err || typeof err !== "object") return false; + if (err.retryable === false) return false; + const status = statusOf(err); + if (status !== null) { + if (status === 408 || status === 429) return true; + return status >= 500 && status !== 501; + } + if (RETRYABLE_NETWORK_CODES.has(err.code)) return true; + return /fetch failed|socket hang up|network error|timed? ?out/i.test(String(err.message ?? "")); +} + +export const paymentDetailsDlq = new RecoveryQueue({ + name: "payment_details", + maxCapacity: 500, + maxAttempts: 5, + baseDelayMs: 2_000, + maxDelayMs: 60_000, + metrics: { + onDepth: (n) => paymentDetailsDlqDepth.set(n), + onOperation: (action, status) => paymentDetailsDlqOperationsTotal.inc({ action, status }), + }, +}); + +// ── Recovered-metadata cache ──────────────────────────────────────────────── + +const metaCache = new Map(); // txId -> { value, expiresAt } + +function cacheGet(txId, now) { + const hit = metaCache.get(txId); + if (!hit) return null; + if (hit.expiresAt <= now) { + metaCache.delete(txId); + return null; + } + return hit.value; +} + +function cacheSet(txId, value, now) { + if (metaCache.size >= CACHE_MAX_ENTRIES) { + // Map iterates in insertion order: drop the oldest entry. + metaCache.delete(metaCache.keys().next().value); + } + metaCache.set(txId, { value, expiresAt: now + CACHE_TTL_MS }); +} + +export function resetPaymentDetailsRecoveryForTests() { + metaCache.clear(); + paymentDetailsDlq.clear(); + lastRecoveryStartedAt = 0; +} + +// ── Lookup with retry + dead-lettering ────────────────────────────────────── + +let lastRecoveryStartedAt = 0; + +/** + * Look up Horizon metadata for a transaction. Never throws: returns the + * metadata, or `null` when it is unavailable (the route then omits `stellar_tx`). + * + * @param {string} txId + * @param {object} options + * @param {(txId:string) => Promise} options.fetchTx Throws on failure + * @param {boolean} [options.scheduleRecovery=true] + * @param {() => number} [options.now] + */ +export async function fetchTxMetaWithRecovery(txId, options) { + const { + fetchTx, + scheduleRecovery: shouldSchedule = true, + now = Date.now, + sleep, + random, + logger = defaultLogger, + } = options; + + if (!txId || typeof txId !== "string" || !TX_ID_PATTERN.test(txId)) return null; + + const cached = cacheGet(txId, now()); + if (cached) { + paymentDetailsHorizonFetchTotal.inc({ outcome: "cache_hit" }); + return cached; + } + + try { + const meta = await retryWithBackoff(() => fetchTx(txId), { + resolved: resolveBackoffOptions({}, process.env, RETRY_SPEC), + label: "payment_details_horizon_lookup", + shouldRetry: isHorizonRetryable, + onRetry: () => paymentDetailsHorizonRetriesTotal.inc(), + ...(sleep ? { sleep } : {}), + ...(random ? { random } : {}), + logger, + }); + cacheSet(txId, meta, now()); + paymentDetailsHorizonFetchTotal.inc({ outcome: "success" }); + return meta; + } catch (err) { + if (isHorizonNotFound(err)) { + // Not yet visible on Horizon: normal for a fresh transaction. Silent. + paymentDetailsHorizonFetchTotal.inc({ outcome: "not_found" }); + return null; + } + + if (isHorizonRetryable(err)) { + paymentDetailsDlq.enqueue(txId, { txId }, err); + paymentDetailsHorizonFetchTotal.inc({ outcome: "dead_lettered" }); + if (shouldSchedule) scheduleRecovery({ fetchTx, now, logger }); + } else { + paymentDetailsHorizonFetchTotal.inc({ outcome: "error" }); + logger.warn?.({ err: err?.message, status: statusOf(err) }, "Horizon lookup failed (not retryable)"); + } + return null; + } +} + +// ── Recovery ──────────────────────────────────────────────────────────────── + +/** + * Re-drive due dead-lettered lookups with a single attempt each. Successes are + * cached; failures back off or, after repeated failure, are isolated. + */ +export async function recoverPaymentDetailsDlq({ fetchTx, now = Date.now, maxBatch = 10 } = {}) { + if (typeof fetchTx !== "function") { + throw new TypeError("recoverPaymentDetailsDlq requires a fetchTx function"); + } + return paymentDetailsDlq.recover( + async (entry) => { + const meta = await fetchTx(entry.payload.txId); + cacheSet(entry.payload.txId, meta, now()); + }, + { maxBatch }, + ); +} + +/** + * Throttled, fire-and-forget background recovery. Safe to call on every failure: + * at most one run is started per RECOVERY_MIN_INTERVAL_MS, and runs never overlap. + */ +export function scheduleRecovery({ fetchTx, now = Date.now, logger = defaultLogger } = {}) { + const current = now(); + if (current - lastRecoveryStartedAt < RECOVERY_MIN_INTERVAL_MS) return false; + lastRecoveryStartedAt = current; + + const timer = setTimeout(() => { + recoverPaymentDetailsDlq({ fetchTx, now }).catch((err) => { + logger.error?.({ err: err?.message }, "Payment details DLQ recovery run failed"); + }); + }, 0); + timer.unref?.(); + return true; +} diff --git a/backend/src/lib/payment-details-recovery.test.js b/backend/src/lib/payment-details-recovery.test.js new file mode 100644 index 0000000..2bf1092 --- /dev/null +++ b/backend/src/lib/payment-details-recovery.test.js @@ -0,0 +1,230 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { + fetchTxMetaWithRecovery, + recoverPaymentDetailsDlq, + scheduleRecovery, + isHorizonRetryable, + isHorizonNotFound, + paymentDetailsDlq, + resetPaymentDetailsRecoveryForTests, +} from "./payment-details-recovery.js"; +import { + paymentDetailsRegister, + resetPaymentDetailsMetrics, +} from "./payment-details-metrics.js"; + +const TX = "a".repeat(64); +const META = { tx_hash: TX, ledger: 123, timestamp: "2026-01-01T00:00:00Z" }; +const silentLogger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() }; +const noSleep = async () => {}; + +function httpError(status, message = `HTTP ${status}`) { + const err = new Error(message); + err.response = { status }; + return err; +} + +async function counter(name, labels = {}) { + const metric = await paymentDetailsRegister.getSingleMetric(name).get(); + const match = metric.values.find((v) => + Object.entries(labels).every(([k, val]) => v.labels[k] === val), + ); + return match ? match.value : 0; +} + +function lookup(fetchTx, extra = {}) { + return fetchTxMetaWithRecovery(TX, { + fetchTx, + sleep: noSleep, + random: () => 0, + logger: silentLogger, + scheduleRecovery: false, + ...extra, + }); +} + +describe("error classification", () => { + it("retries network errors, 408, 429 and 5xx", () => { + expect(isHorizonRetryable(httpError(503))).toBe(true); + expect(isHorizonRetryable(httpError(500))).toBe(true); + expect(isHorizonRetryable(httpError(429))).toBe(true); + expect(isHorizonRetryable(httpError(408))).toBe(true); + expect(isHorizonRetryable(Object.assign(new Error("x"), { code: "ECONNRESET" }))).toBe(true); + expect(isHorizonRetryable(new Error("fetch failed"))).toBe(true); + }); + + it("does not retry 404, other 4xx, 501 or explicit opt-outs", () => { + expect(isHorizonRetryable(httpError(404))).toBe(false); + expect(isHorizonRetryable(httpError(400))).toBe(false); + expect(isHorizonRetryable(httpError(501))).toBe(false); + expect(isHorizonRetryable(Object.assign(httpError(503), { retryable: false }))).toBe(false); + expect(isHorizonRetryable(null)).toBe(false); + expect(isHorizonRetryable("boom")).toBe(false); + }); + + it("recognizes a 404", () => { + expect(isHorizonNotFound(httpError(404))).toBe(true); + expect(isHorizonNotFound(httpError(500))).toBe(false); + }); +}); + +describe("fetchTxMetaWithRecovery", () => { + beforeEach(() => { + resetPaymentDetailsRecoveryForTests(); + resetPaymentDetailsMetrics(); + vi.clearAllMocks(); + }); + + it("returns metadata on the first success", async () => { + const fetchTx = vi.fn().mockResolvedValue(META); + + expect(await lookup(fetchTx)).toEqual(META); + expect(fetchTx).toHaveBeenCalledTimes(1); + expect(await counter("payment_details_horizon_fetch_total", { outcome: "success" })).toBe(1); + }); + + it("serves a repeat lookup from the cache without calling Horizon", async () => { + const fetchTx = vi.fn().mockResolvedValue(META); + await lookup(fetchTx); + await lookup(fetchTx); + + expect(fetchTx).toHaveBeenCalledTimes(1); + expect(await counter("payment_details_horizon_fetch_total", { outcome: "cache_hit" })).toBe(1); + }); + + it("expires cached entries after the TTL", async () => { + let now = 1_000; + const fetchTx = vi.fn().mockResolvedValue(META); + await lookup(fetchTx, { now: () => now }); + now += 11 * 60 * 1000; + await lookup(fetchTx, { now: () => now }); + + expect(fetchTx).toHaveBeenCalledTimes(2); + }); + + it("retries transient failures and then succeeds", async () => { + const fetchTx = vi + .fn() + .mockRejectedValueOnce(httpError(503)) + .mockRejectedValueOnce(Object.assign(new Error("reset"), { code: "ECONNRESET" })) + .mockResolvedValue(META); + + expect(await lookup(fetchTx)).toEqual(META); + expect(fetchTx).toHaveBeenCalledTimes(3); + expect(await counter("payment_details_horizon_retries_total")).toBe(2); + expect(paymentDetailsDlq.size).toBe(0); + }); + + it("returns null for 404 without retrying or dead-lettering", async () => { + const fetchTx = vi.fn().mockRejectedValue(httpError(404)); + + expect(await lookup(fetchTx)).toBeNull(); + expect(fetchTx).toHaveBeenCalledTimes(1); + expect(paymentDetailsDlq.size).toBe(0); + expect(await counter("payment_details_horizon_fetch_total", { outcome: "not_found" })).toBe(1); + }); + + it("returns null for a non-retryable error without dead-lettering", async () => { + const fetchTx = vi.fn().mockRejectedValue(httpError(400)); + + expect(await lookup(fetchTx)).toBeNull(); + expect(fetchTx).toHaveBeenCalledTimes(1); + expect(paymentDetailsDlq.size).toBe(0); + expect(await counter("payment_details_horizon_fetch_total", { outcome: "error" })).toBe(1); + }); + + it("dead-letters a lookup that keeps failing transiently, keyed by tx id only", async () => { + const fetchTx = vi.fn().mockRejectedValue(httpError(503)); + + expect(await lookup(fetchTx)).toBeNull(); + expect(fetchTx).toHaveBeenCalledTimes(3); + expect(paymentDetailsDlq.size).toBe(1); + expect(paymentDetailsDlq.has(TX)).toBe(true); + expect(await counter("payment_details_horizon_fetch_total", { outcome: "dead_lettered" })).toBe(1); + expect(paymentDetailsDlq.list()[0]).not.toHaveProperty("payload"); + }); + + it("coalesces repeated failures for one transaction into one entry", async () => { + const fetchTx = vi.fn().mockRejectedValue(httpError(503)); + await lookup(fetchTx); + await lookup(fetchTx); + + expect(paymentDetailsDlq.size).toBe(1); + }); + + it("rejects ids that are not 64-hex transaction hashes without calling Horizon", async () => { + const fetchTx = vi.fn().mockResolvedValue(META); + for (const bad of ["", null, undefined, "short", "../../etc/passwd", `${"a".repeat(63)}z`]) { + expect(await fetchTxMetaWithRecovery(bad, { fetchTx, logger: silentLogger })).toBeNull(); + } + expect(fetchTx).not.toHaveBeenCalled(); + }); +}); + +describe("recoverPaymentDetailsDlq", () => { + beforeEach(() => { + resetPaymentDetailsRecoveryForTests(); + resetPaymentDetailsMetrics(); + vi.clearAllMocks(); + }); + + async function deadLetter() { + await lookup(vi.fn().mockRejectedValue(httpError(503))); + // Make the entry due immediately. + paymentDetailsDlq._entries.get(TX).nextRetryAt = 0; + } + + it("requires a fetchTx function", async () => { + await expect(recoverPaymentDetailsDlq({})).rejects.toThrow(TypeError); + }); + + it("recovers a dead-lettered lookup, caches it and empties the queue", async () => { + await deadLetter(); + const fetchTx = vi.fn().mockResolvedValue(META); + + const result = await recoverPaymentDetailsDlq({ fetchTx }); + + expect(result).toMatchObject({ recovered: 1, failed: 0, exhausted: 0 }); + expect(paymentDetailsDlq.size).toBe(0); + + // The recovered metadata now serves requests without hitting Horizon. + const guard = vi.fn(); + expect(await fetchTxMetaWithRecovery(TX, { fetchTx: guard, logger: silentLogger })).toEqual(META); + expect(guard).not.toHaveBeenCalled(); + }); + + it("keeps the entry and backs off when recovery fails again", async () => { + await deadLetter(); + const fetchTx = vi.fn().mockRejectedValue(httpError(503)); + + const result = await recoverPaymentDetailsDlq({ fetchTx }); + + expect(result).toMatchObject({ recovered: 0, failed: 1 }); + expect(paymentDetailsDlq.size).toBe(1); + expect(paymentDetailsDlq.list()[0].attempts).toBe(1); + }); + + it("runs the background recovery once per throttle window", async () => { + vi.useFakeTimers(); + try { + await deadLetter(); + const fetchTx = vi.fn().mockResolvedValue(META); + + let now = 1_000_000; + expect(scheduleRecovery({ fetchTx, now: () => now, logger: silentLogger })).toBe(true); + expect(scheduleRecovery({ fetchTx, now: () => now + 1_000, logger: silentLogger })).toBe(false); + + await vi.runAllTimersAsync(); + expect(fetchTx).toHaveBeenCalledTimes(1); + + now += 16_000; + expect(scheduleRecovery({ fetchTx, now: () => now, logger: silentLogger })).toBe(true); + } finally { + vi.useRealTimers(); + } + }); +}); + +afterEach(() => { + vi.useRealTimers(); +}); diff --git a/backend/src/lib/recovery-queue.js b/backend/src/lib/recovery-queue.js new file mode 100644 index 0000000..7c9122d --- /dev/null +++ b/backend/src/lib/recovery-queue.js @@ -0,0 +1,237 @@ +/** + * recovery-queue.js + * + * A small, bounded dead-letter queue with automated recovery, shared by the + * Public Hosted Checkout Session Route (#1776) and the Merchant Onboarding and + * Key Lifecycle Route (#1771). + * + * What it guarantees + * ------------------ + * - Bounded memory: at most `maxCapacity` entries. When full, the oldest + * exhausted entry is evicted first, then the oldest pending one. + * - De-duplication: enqueueing the same `key` again refreshes the existing + * entry instead of adding a second one, so a hot failing resource cannot + * flood the queue. + * - Full-jitter exponential backoff between recovery attempts. + * - Poison-pill isolation: after `maxAttempts` failed recoveries, or on an + * error that is explicitly not retryable (`err.retryable === false`), the + * entry is marked `exhausted` and is never retried automatically again. + * - No overlapping recovery runs for one queue (`recover()` is re-entrancy + * safe) and a bounded batch size per run. + * - Only safe fields are exposed: `list()` omits the payload, and error + * messages are control-character stripped and truncated. + * + * Callers must keep secrets (API keys, webhook secrets, passwords) OUT of + * payloads. Queue entries are held in process memory and are lost on restart; + * they exist to absorb transient outages, not to be a durable store. + */ + +import { randomUUID } from "node:crypto"; +import { logger as defaultLogger } from "./logger.js"; + +const MAX_ERROR_MESSAGE_LENGTH = 200; +// eslint-disable-next-line no-control-regex +const CONTROL_CHARS = /[\u0000-\u001F\u007F]/g; + +export function sanitizeErrorMessage(err) { + const raw = err instanceof Error ? err.message : String(err ?? "unknown error"); + return raw.replace(CONTROL_CHARS, " ").slice(0, MAX_ERROR_MESSAGE_LENGTH); +} + +function clampInt(value, fallback, min, max) { + const n = Number(value); + if (!Number.isFinite(n)) return fallback; + return Math.min(Math.max(Math.trunc(n), min), max); +} + +export class RecoveryQueue { + /** + * @param {object} [options] + * @param {string} [options.name] Label used in logs + * @param {number} [options.maxCapacity=500] + * @param {number} [options.maxAttempts=5] Recovery attempts before an entry is exhausted + * @param {number} [options.baseDelayMs=1000] + * @param {number} [options.maxDelayMs=60000] + * @param {() => number} [options.now] + * @param {() => number} [options.random] + * @param {{ onDepth?: (n:number)=>void, onOperation?: (action:string, status:string)=>void }} [options.metrics] + * @param {object} [options.logger] + */ + constructor(options = {}) { + this.name = options.name || "recovery-queue"; + this.maxCapacity = clampInt(options.maxCapacity, 500, 1, 10_000); + this.maxAttempts = clampInt(options.maxAttempts, 5, 1, 20); + this.baseDelayMs = clampInt(options.baseDelayMs, 1_000, 0, 600_000); + this.maxDelayMs = clampInt(options.maxDelayMs, 60_000, this.baseDelayMs, 3_600_000); + this.now = options.now || Date.now; + this.random = options.random || Math.random; + this.metrics = options.metrics || {}; + this.logger = options.logger || defaultLogger; + this._entries = new Map(); // key -> entry + this._recovering = false; + } + + get size() { + return this._entries.size; + } + + stats() { + let pending = 0; + let exhausted = 0; + for (const entry of this._entries.values()) { + if (entry.status === "exhausted") exhausted += 1; + else pending += 1; + } + return { total: this._entries.size, pending, exhausted }; + } + + /** Entries without their payload, safe to expose to operators. */ + list() { + return [...this._entries.values()].map(({ payload: _payload, ...safe }) => ({ ...safe })); + } + + has(key) { + return this._entries.has(key); + } + + _delayFor(attempts) { + const exponent = Math.min(Math.max(attempts, 0), 30); + const ceiling = Math.min(this.maxDelayMs, this.baseDelayMs * 2 ** exponent); + if (!Number.isFinite(ceiling) || ceiling <= 0) return 0; + const r = Math.min(Math.max(Number(this.random()) || 0, 0), 1); + return Math.floor(r * ceiling); + } + + _publishDepth() { + this.metrics.onDepth?.(this._entries.size); + } + + _record(action, status) { + this.metrics.onOperation?.(action, status); + } + + _evictOne() { + let victimKey = null; + for (const [key, entry] of this._entries) { + if (entry.status === "exhausted") { + victimKey = key; + break; + } + if (victimKey === null) victimKey = key; + } + if (victimKey !== null) { + this._entries.delete(victimKey); + this._record("evict", "capacity"); + this.logger.warn?.({ queue: this.name }, "Recovery queue at capacity; evicted an entry"); + } + } + + /** + * Add a failed unit of work. Re-enqueueing an existing key refreshes its error + * and, if it was exhausted, leaves it exhausted. + * + * @param {string} key Stable identity of the work (e.g. a tx id) + * @param {object} payload Data the recovery handler needs. NO secrets. + * @param {unknown} error The failure that sent it here + */ + enqueue(key, payload, error) { + if (!key || typeof key !== "string") { + throw new TypeError("RecoveryQueue.enqueue requires a string key"); + } + const now = this.now(); + const existing = this._entries.get(key); + const errorInfo = { message: sanitizeErrorMessage(error), code: error?.code ?? null }; + + if (existing) { + existing.error = errorInfo; + existing.lastFailedAt = now; + existing.payload = payload; + this._record("push", "duplicate"); + return existing; + } + + if (this._entries.size >= this.maxCapacity) this._evictOne(); + + const entry = { + id: randomUUID(), + key, + payload, + attempts: 0, + status: "pending", + error: errorInfo, + firstFailedAt: now, + lastFailedAt: now, + nextRetryAt: now + this._delayFor(0), + }; + this._entries.set(key, entry); + this._record("push", "success"); + this._publishDepth(); + this.logger.info?.({ queue: this.name, key }, "Work item dead-lettered for recovery"); + return entry; + } + + /** + * Attempt recovery of due, pending entries. + * + * @param {(entry: object) => Promise} handler Throws to signal failure + * @param {{ maxBatch?: number }} [options] + * @returns {Promise<{ recovered:number, failed:number, exhausted:number, skipped:boolean }>} + */ + async recover(handler, { maxBatch = 10 } = {}) { + const result = { recovered: 0, failed: 0, exhausted: 0, skipped: false }; + if (this._recovering) { + result.skipped = true; + return result; + } + this._recovering = true; + try { + const limit = clampInt(maxBatch, 10, 1, 100); + const due = []; + const now = this.now(); + for (const entry of this._entries.values()) { + if (entry.status === "pending" && entry.nextRetryAt <= now) { + due.push(entry); + if (due.length >= limit) break; + } + } + + for (const entry of due) { + try { + await handler(entry); + this._entries.delete(entry.key); + this._record("recover", "success"); + result.recovered += 1; + } catch (err) { + entry.attempts += 1; + entry.lastFailedAt = this.now(); + entry.error = { message: sanitizeErrorMessage(err), code: err?.code ?? null }; + + if (err?.retryable === false || entry.attempts >= this.maxAttempts) { + entry.status = "exhausted"; + this._record("exhaust", "poison_pill"); + result.exhausted += 1; + this.logger.error?.( + { queue: this.name, key: entry.key, attempts: entry.attempts }, + "Recovery attempts exhausted; entry isolated", + ); + } else { + entry.nextRetryAt = this.now() + this._delayFor(entry.attempts); + this._record("retry", "failure"); + result.failed += 1; + } + } + } + this._publishDepth(); + return result; + } finally { + this._recovering = false; + } + } + + /** Remove everything (tests / operator reset). */ + clear() { + this._entries.clear(); + this._record("clear", "success"); + this._publishDepth(); + } +} diff --git a/backend/src/lib/recovery-queue.test.js b/backend/src/lib/recovery-queue.test.js new file mode 100644 index 0000000..b5484c3 --- /dev/null +++ b/backend/src/lib/recovery-queue.test.js @@ -0,0 +1,237 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { RecoveryQueue, sanitizeErrorMessage } from "./recovery-queue.js"; + +const silentLogger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() }; + +function makeQueue(overrides = {}) { + let now = 1_000_000; + const queue = new RecoveryQueue({ + name: "test", + maxCapacity: 3, + maxAttempts: 3, + baseDelayMs: 1_000, + maxDelayMs: 8_000, + now: () => now, + random: () => 1, // deterministic: full ceiling + logger: silentLogger, + ...overrides, + }); + return { queue, advance: (ms) => (now += ms), clock: () => now }; +} + +describe("RecoveryQueue", () => { + beforeEach(() => vi.clearAllMocks()); + + it("enqueues work and reports stats", () => { + const { queue } = makeQueue(); + queue.enqueue("a", { id: 1 }, new Error("boom")); + + expect(queue.size).toBe(1); + expect(queue.stats()).toEqual({ total: 1, pending: 1, exhausted: 0 }); + expect(queue.has("a")).toBe(true); + }); + + it("requires a string key", () => { + const { queue } = makeQueue(); + expect(() => queue.enqueue("", {}, new Error("x"))).toThrow(TypeError); + expect(() => queue.enqueue(undefined, {}, new Error("x"))).toThrow(TypeError); + }); + + it("de-duplicates by key and refreshes the error instead of adding an entry", () => { + const { queue } = makeQueue(); + queue.enqueue("a", { v: 1 }, new Error("first")); + queue.enqueue("a", { v: 2 }, new Error("second")); + + expect(queue.size).toBe(1); + expect(queue.list()[0].error.message).toBe("second"); + }); + + it("evicts the oldest exhausted entry first, then the oldest pending one, at capacity", async () => { + const { queue, advance } = makeQueue({ maxAttempts: 1 }); + queue.enqueue("b", {}, new Error("x")); + advance(10_000); + await queue.recover(async () => { + throw new Error("fail"); + }); + expect(queue.stats().exhausted).toBe(1); + + queue.enqueue("a", {}, new Error("x")); + queue.enqueue("c", {}, new Error("x")); + queue.enqueue("d", {}, new Error("x")); // full: the exhausted entry makes room + expect(queue.has("b")).toBe(false); + expect(queue.size).toBe(3); + + queue.enqueue("e", {}, new Error("x")); // nothing exhausted now: oldest pending goes + expect(queue.has("a")).toBe(false); + expect(queue.size).toBe(3); + }); + + it("recovers due entries and removes them", async () => { + const { queue, advance } = makeQueue(); + queue.enqueue("a", { n: 1 }, new Error("x")); + advance(5_000); + + const handler = vi.fn(async () => {}); + const result = await queue.recover(handler); + + expect(result).toEqual({ recovered: 1, failed: 0, exhausted: 0, skipped: false }); + expect(handler).toHaveBeenCalledTimes(1); + expect(handler.mock.calls[0][0].payload).toEqual({ n: 1 }); + expect(queue.size).toBe(0); + }); + + it("does not retry an entry before its backoff elapses", async () => { + const { queue, advance } = makeQueue(); + queue.enqueue("a", {}, new Error("x")); + advance(1_000); + const first = await queue.recover(async () => { + throw new Error("still down"); + }); + expect(first.failed).toBe(1); + + const handler = vi.fn(async () => {}); + const immediate = await queue.recover(handler); + expect(handler).not.toHaveBeenCalled(); + expect(immediate.recovered).toBe(0); + }); + + it("backs off exponentially, capped at maxDelayMs", async () => { + const { queue, advance, clock } = makeQueue(); + queue.enqueue("a", {}, new Error("x")); + advance(1_000); + const fail = async () => { + throw new Error("down"); + }; + + const t0 = clock(); + await queue.recover(fail); // attempts=1 -> ceiling 2000 + expect(queue.list()[0].nextRetryAt - t0).toBe(2_000); + + advance(2_000); + const t1 = clock(); + await queue.recover(fail); // attempts=2 -> ceiling 4000 + expect(queue.list()[0].nextRetryAt - t1).toBe(4_000); + }); + + it("isolates an entry as a poison pill after maxAttempts failures", async () => { + const { queue, advance } = makeQueue({ maxAttempts: 2 }); + queue.enqueue("a", {}, new Error("x")); + advance(1_000); + const fail = async () => { + throw new Error("down"); + }; + + await queue.recover(fail); + advance(60_000); + const last = await queue.recover(fail); + + expect(last.exhausted).toBe(1); + expect(queue.stats()).toEqual({ total: 1, pending: 0, exhausted: 1 }); + + advance(60_000); + const handler = vi.fn(async () => {}); + await queue.recover(handler); + expect(handler).not.toHaveBeenCalled(); // exhausted entries are never retried + }); + + it("exhausts immediately on a non-retryable error", async () => { + const { queue, advance } = makeQueue(); + queue.enqueue("a", {}, new Error("x")); + advance(1_000); + + const result = await queue.recover(async () => { + const err = new Error("gone"); + err.retryable = false; + throw err; + }); + + expect(result.exhausted).toBe(1); + }); + + it("limits the batch size per run", async () => { + const { queue, advance } = makeQueue({ maxCapacity: 10 }); + for (let i = 0; i < 5; i += 1) queue.enqueue(`k${i}`, {}, new Error("x")); + advance(5_000); + + const handler = vi.fn(async () => {}); + const result = await queue.recover(handler, { maxBatch: 2 }); + + expect(result.recovered).toBe(2); + expect(queue.size).toBe(3); + }); + + it("does not run overlapping recoveries", async () => { + const { queue, advance } = makeQueue(); + queue.enqueue("a", {}, new Error("x")); + advance(5_000); + + let release; + const gate = new Promise((resolve) => { + release = resolve; + }); + const first = queue.recover(() => gate); + const second = await queue.recover(async () => {}); + + expect(second.skipped).toBe(true); + release(); + expect((await first).recovered).toBe(1); + }); + + it("allows a new recovery after the previous one fails", async () => { + const { queue, advance } = makeQueue(); + queue.enqueue("a", {}, new Error("x")); + advance(5_000); + await queue.recover(async () => { + throw new Error("down"); + }); + advance(60_000); + const again = await queue.recover(async () => {}); + expect(again.skipped).toBe(false); + expect(again.recovered).toBe(1); + }); + + it("list() never exposes the payload", () => { + const { queue } = makeQueue(); + queue.enqueue("a", { secret: "must-not-leak" }, new Error("x")); + + const listed = queue.list(); + expect(JSON.stringify(listed)).not.toContain("must-not-leak"); + expect(listed[0]).not.toHaveProperty("payload"); + }); + + it("sanitizes and truncates error messages", () => { + expect(sanitizeErrorMessage(new Error("a\u0000b\nc"))).toBe("a b c"); + expect(sanitizeErrorMessage(new Error("x".repeat(500))).length).toBe(200); + expect(sanitizeErrorMessage(undefined)).toBe("unknown error"); + }); + + it("reports depth and operations to the metrics hooks", async () => { + const onDepth = vi.fn(); + const onOperation = vi.fn(); + const { queue, advance } = makeQueue({ metrics: { onDepth, onOperation } }); + + queue.enqueue("a", {}, new Error("x")); + expect(onDepth).toHaveBeenLastCalledWith(1); + expect(onOperation).toHaveBeenCalledWith("push", "success"); + + advance(5_000); + await queue.recover(async () => {}); + expect(onOperation).toHaveBeenCalledWith("recover", "success"); + expect(onDepth).toHaveBeenLastCalledWith(0); + + queue.enqueue("b", {}, new Error("x")); + queue.enqueue("b", {}, new Error("y")); + expect(onOperation).toHaveBeenCalledWith("push", "duplicate"); + + queue.clear(); + expect(onOperation).toHaveBeenCalledWith("clear", "success"); + expect(onDepth).toHaveBeenLastCalledWith(0); + }); + + it("clamps unsafe configuration", () => { + const q = new RecoveryQueue({ maxCapacity: -5, maxAttempts: 9999, baseDelayMs: -1, logger: silentLogger }); + expect(q.maxCapacity).toBe(1); + expect(q.maxAttempts).toBe(20); + expect(q.baseDelayMs).toBe(0); + }); +}); diff --git a/backend/src/lib/stellar/validators-cache.js b/backend/src/lib/stellar/validators-cache.js new file mode 100644 index 0000000..dbea79e --- /dev/null +++ b/backend/src/lib/stellar/validators-cache.js @@ -0,0 +1,212 @@ +/** + * validators-cache.js + * + * Distributed (Redis) cache with an in-process fallback for the Stellar + * validators' network-bound work: federated address resolution (#1765). + * + * Resolving `name*domain` costs two HTTPS round trips (stellar.toml, then the + * federation server). Results are stable for minutes, so they are cached: + * + * - Redis (shared across instances) when available, via GET / SET EX. + * - A bounded in-memory LRU when Redis is unavailable or errors, so a Redis + * outage degrades to per-instance caching and never fails a validation. + * + * Safety + * ------ + * - Keys are `validator:v1::`, so user input can + * never inject Redis key separators or create oversized keys. + * - Only SUCCESSFUL results are cached; failures are never cached, so an + * outage cannot be turned into a sticky rejection. + * - Values are JSON. The caller re-validates anything it reads back (see + * `parse`), so a poisoned or corrupt entry is discarded rather than trusted. + * - TTL is clamped (1s..1h). The in-memory store is bounded and expires + * lazily on access and on insert; there are no timers to leak. + * - Redis errors are swallowed, counted and logged without the key or value. + */ + +import { createHash } from "node:crypto"; +import { logger as defaultLogger } from "../logger.js"; +import { connectRedisClient } from "../redis.js"; +import { validatorCacheOperationsTotal } from "./validators-metrics.js"; + +export const DEFAULT_CACHE_TTL_SECONDS = 300; +const MIN_TTL_SECONDS = 1; +const MAX_TTL_SECONDS = 3_600; +const DEFAULT_MAX_MEMORY_ENTRIES = 1_000; +const KEY_PREFIX = "validator:v1"; + +export function resolveCacheTtlSeconds(value, env = process.env) { + const raw = Number(value ?? env.VALIDATOR_CACHE_TTL_SECONDS); + if (!Number.isFinite(raw)) return DEFAULT_CACHE_TTL_SECONDS; + return Math.min(Math.max(Math.trunc(raw), MIN_TTL_SECONDS), MAX_TTL_SECONDS); +} + +export function buildValidatorCacheKey(namespace, input) { + if (!namespace || typeof namespace !== "string" || !/^[a-z0-9_]+$/.test(namespace)) { + throw new TypeError("namespace must be a lowercase [a-z0-9_] string"); + } + const digest = createHash("sha256").update(String(input).toLowerCase()).digest("hex"); + return `${KEY_PREFIX}:${namespace}:${digest}`; +} + +export class ValidatorCache { + /** + * @param {object} [options] + * @param {() => Promise} [options.getRedis] Injected for tests + * @param {number} [options.ttlSeconds] + * @param {number} [options.maxMemoryEntries] + * @param {() => number} [options.now] + * @param {object} [options.logger] + */ + constructor(options = {}) { + this.getRedis = options.getRedis || connectRedisClient; + this.ttlSeconds = resolveCacheTtlSeconds(options.ttlSeconds); + this.maxMemoryEntries = Math.max(1, options.maxMemoryEntries || DEFAULT_MAX_MEMORY_ENTRIES); + this.now = options.now || Date.now; + this.logger = options.logger || defaultLogger; + this._memory = new Map(); // key -> { value, expiresAt } (insertion order = LRU order) + } + + get memorySize() { + return this._memory.size; + } + + async _redis() { + try { + const client = await this.getRedis(); + // connectRedisClient() returns a no-op client (isOpen:false) when Redis is + // unreachable; treat that as "no distributed backend". + if (!client || client.isOpen === false) return null; + return client; + } catch (err) { + this.logger.warn?.({ err: err?.message }, "Validator cache: Redis unavailable, using memory"); + return null; + } + } + + _memoryGet(key) { + const entry = this._memory.get(key); + if (!entry) return null; + if (entry.expiresAt <= this.now()) { + this._memory.delete(key); + return null; + } + // Refresh recency. + this._memory.delete(key); + this._memory.set(key, entry); + return entry.value; + } + + _memorySet(key, serialized, ttlSeconds) { + this._memory.delete(key); + // Make room: drop expired entries first, then the least recently used. + if (this._memory.size >= this.maxMemoryEntries) { + const now = this.now(); + for (const [k, entry] of this._memory) { + if (entry.expiresAt <= now) this._memory.delete(k); + } + while (this._memory.size >= this.maxMemoryEntries) { + this._memory.delete(this._memory.keys().next().value); + } + } + this._memory.set(key, { value: serialized, expiresAt: this.now() + ttlSeconds * 1000 }); + } + + /** + * Read a cached value. + * + * @param {string} operation Metric label, e.g. "federation_resolve" + * @param {string} key From buildValidatorCacheKey() + * @param {(raw: unknown) => unknown|null} parse Re-validates a cached value; + * return null to reject it (the entry is then dropped and treated as a miss). + * @returns {Promise} + */ + async get(operation, key, parse) { + const client = await this._redis(); + let serialized = null; + let backend = "memory"; + + if (client) { + try { + serialized = await client.get(key); + backend = "redis"; + } catch (err) { + validatorCacheOperationsTotal.inc({ operation, result: "error", backend: "redis" }); + this.logger.warn?.({ err: err?.message }, "Validator cache: Redis GET failed, using memory"); + } + } + if (serialized === null || serialized === undefined) { + const fromMemory = this._memoryGet(key); + if (fromMemory !== null) { + serialized = fromMemory; + backend = "memory"; + } + } + + if (serialized === null || serialized === undefined) { + validatorCacheOperationsTotal.inc({ operation, result: "miss", backend }); + return null; + } + + let value = null; + try { + value = parse(JSON.parse(serialized)); + } catch { + value = null; + } + if (value === null || value === undefined) { + // Corrupt or poisoned entry: drop it everywhere and treat as a miss. + validatorCacheOperationsTotal.inc({ operation, result: "invalid", backend }); + await this.delete(key); + return null; + } + + validatorCacheOperationsTotal.inc({ operation, result: "hit", backend }); + return value; + } + + /** Store a successful result. Never throws. */ + async set(operation, key, value, ttlSeconds = this.ttlSeconds) { + const ttl = resolveCacheTtlSeconds(ttlSeconds); + let serialized; + try { + serialized = JSON.stringify(value); + } catch { + return false; + } + this._memorySet(key, serialized, ttl); + + const client = await this._redis(); + if (client) { + try { + await client.set(key, serialized, { EX: ttl }); + validatorCacheOperationsTotal.inc({ operation, result: "set", backend: "redis" }); + return true; + } catch (err) { + validatorCacheOperationsTotal.inc({ operation, result: "error", backend: "redis" }); + this.logger.warn?.({ err: err?.message }, "Validator cache: Redis SET failed, kept in memory"); + } + } + validatorCacheOperationsTotal.inc({ operation, result: "set", backend: "memory" }); + return true; + } + + async delete(key) { + this._memory.delete(key); + const client = await this._redis(); + if (client) { + try { + await client.del(key); + } catch { + // The entry expires on its own via EX. + } + } + } + + clearMemory() { + this._memory.clear(); + } +} + +/** Process-wide cache used by resolveFederatedAddress unless one is injected. */ +export const validatorCache = new ValidatorCache(); diff --git a/backend/src/lib/stellar/validators-cache.test.js b/backend/src/lib/stellar/validators-cache.test.js new file mode 100644 index 0000000..5ba2506 --- /dev/null +++ b/backend/src/lib/stellar/validators-cache.test.js @@ -0,0 +1,342 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { + ValidatorCache, + buildValidatorCacheKey, + resolveCacheTtlSeconds, + DEFAULT_CACHE_TTL_SECONDS, +} from "./validators-cache.js"; +import { + resolveFederatedAddress, + getValidatorThroughput, + isValidStellarPublicKey, +} from "./validators.js"; +import { + validatorRegister, + validatorCacheOperationsTotal, + recordValidatorThroughput, + resetValidatorMetrics, + THROUGHPUT_WINDOW_SECONDS, +} from "./validators-metrics.js"; + +const silentLogger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() }; +const ACCOUNT = "GAAZI4TCR3TY5OJHCTJC2A4QSY6CJWJH5IAJTGKIN2ER7LBNVKOCCWN7"; + +function fakeRedis() { + const store = new Map(); + return { + isOpen: true, + store, + get: vi.fn(async (k) => store.get(k) ?? null), + set: vi.fn(async (k, v) => { + store.set(k, v); + return "OK"; + }), + del: vi.fn(async (k) => (store.delete(k) ? 1 : 0)), + }; +} + +function cacheWith(redis, extra = {}) { + return new ValidatorCache({ + getRedis: async () => redis, + logger: silentLogger, + ...extra, + }); +} + +async function cacheCount(labels) { + const metric = await validatorCacheOperationsTotal.get(); + const hit = metric.values.find((v) => + Object.entries(labels).every(([k, val]) => v.labels[k] === val), + ); + return hit ? hit.value : 0; +} + +const parseAccount = (raw) => (raw && isValidStellarPublicKey(raw.account_id) ? raw : null); + +describe("buildValidatorCacheKey", () => { + it("hashes input so it cannot inject key separators", () => { + const key = buildValidatorCacheKey("federation", "bob*example.com:evil\nflush"); + expect(key).toMatch(/^validator:v1:federation:[0-9a-f]{64}$/); + }); + + it("is case-insensitive and stable", () => { + expect(buildValidatorCacheKey("federation", "Bob*Example.com")).toBe( + buildValidatorCacheKey("federation", "bob*example.com"), + ); + }); + + it("rejects an unsafe namespace", () => { + expect(() => buildValidatorCacheKey("bad:ns", "x")).toThrow(TypeError); + expect(() => buildValidatorCacheKey("", "x")).toThrow(TypeError); + }); +}); + +describe("resolveCacheTtlSeconds", () => { + it("clamps to 1s..1h and falls back on garbage", () => { + expect(resolveCacheTtlSeconds(0)).toBe(1); + expect(resolveCacheTtlSeconds(999_999)).toBe(3_600); + expect(resolveCacheTtlSeconds("abc", {})).toBe(DEFAULT_CACHE_TTL_SECONDS); + expect(resolveCacheTtlSeconds(undefined, { VALIDATOR_CACHE_TTL_SECONDS: "60" })).toBe(60); + }); +}); + +describe("ValidatorCache", () => { + beforeEach(() => { + resetValidatorMetrics(); + vi.clearAllMocks(); + }); + + it("stores in Redis with an expiry and reads it back", async () => { + const redis = fakeRedis(); + const cache = cacheWith(redis); + const key = buildValidatorCacheKey("federation", "a*b.com"); + + await cache.set("federation_resolve", key, { account_id: ACCOUNT }, 120); + const value = await cache.get("federation_resolve", key, parseAccount); + + expect(value).toEqual({ account_id: ACCOUNT }); + expect(redis.set).toHaveBeenCalledWith(key, JSON.stringify({ account_id: ACCOUNT }), { EX: 120 }); + expect(await cacheCount({ result: "hit", backend: "redis" })).toBe(1); + }); + + it("shares entries across instances through Redis", async () => { + const redis = fakeRedis(); + const key = buildValidatorCacheKey("federation", "a*b.com"); + await cacheWith(redis).set("federation_resolve", key, { account_id: ACCOUNT }); + + const other = cacheWith(redis); // fresh memory, same Redis + expect(await other.get("federation_resolve", key, parseAccount)).toEqual({ account_id: ACCOUNT }); + }); + + it("misses on an unknown key", async () => { + const cache = cacheWith(fakeRedis()); + expect(await cache.get("federation_resolve", "validator:v1:federation:x", parseAccount)).toBeNull(); + expect(await cacheCount({ result: "miss" })).toBe(1); + }); + + it("falls back to memory when Redis is a no-op client", async () => { + const cache = cacheWith({ isOpen: false }); + const key = buildValidatorCacheKey("federation", "a*b.com"); + + await cache.set("federation_resolve", key, { account_id: ACCOUNT }); + expect(await cache.get("federation_resolve", key, parseAccount)).toEqual({ account_id: ACCOUNT }); + expect(await cacheCount({ result: "hit", backend: "memory" })).toBe(1); + }); + + it("falls back to memory when getRedis throws", async () => { + const cache = new ValidatorCache({ + getRedis: async () => { + throw new Error("redis down"); + }, + logger: silentLogger, + }); + const key = buildValidatorCacheKey("federation", "a*b.com"); + + await cache.set("federation_resolve", key, { account_id: ACCOUNT }); + expect(await cache.get("federation_resolve", key, parseAccount)).toEqual({ account_id: ACCOUNT }); + }); + + it("survives Redis command errors, serving from memory", async () => { + const redis = fakeRedis(); + redis.get.mockRejectedValue(new Error("boom")); + redis.set.mockRejectedValue(new Error("boom")); + const cache = cacheWith(redis); + const key = buildValidatorCacheKey("federation", "a*b.com"); + + await expect(cache.set("federation_resolve", key, { account_id: ACCOUNT })).resolves.toBe(true); + expect(await cache.get("federation_resolve", key, parseAccount)).toEqual({ account_id: ACCOUNT }); + expect(await cacheCount({ result: "error", backend: "redis" })).toBeGreaterThan(0); + }); + + it("discards and deletes a poisoned entry instead of trusting it", async () => { + const redis = fakeRedis(); + const cache = cacheWith(redis); + const key = buildValidatorCacheKey("federation", "a*b.com"); + redis.store.set(key, JSON.stringify({ account_id: "not-a-stellar-key" })); + + expect(await cache.get("federation_resolve", key, parseAccount)).toBeNull(); + expect(redis.store.has(key)).toBe(false); + expect(await cacheCount({ result: "invalid" })).toBe(1); + }); + + it("discards corrupt JSON", async () => { + const redis = fakeRedis(); + const cache = cacheWith(redis); + const key = buildValidatorCacheKey("federation", "a*b.com"); + redis.store.set(key, "{not json"); + + expect(await cache.get("federation_resolve", key, parseAccount)).toBeNull(); + }); + + it("expires in-memory entries after the TTL", async () => { + let now = 1_000_000; + const cache = cacheWith({ isOpen: false }, { now: () => now }); + const key = buildValidatorCacheKey("federation", "a*b.com"); + + await cache.set("federation_resolve", key, { account_id: ACCOUNT }, 10); + now += 9_000; + expect(await cache.get("federation_resolve", key, parseAccount)).not.toBeNull(); + now += 2_000; + expect(await cache.get("federation_resolve", key, parseAccount)).toBeNull(); + expect(cache.memorySize).toBe(0); + }); + + it("bounds memory with LRU eviction", async () => { + const cache = cacheWith({ isOpen: false }, { maxMemoryEntries: 2 }); + await cache.set("op", "k1", { account_id: ACCOUNT }); + await cache.set("op", "k2", { account_id: ACCOUNT }); + await cache.get("op", "k1", parseAccount); // k1 becomes most recent + await cache.set("op", "k3", { account_id: ACCOUNT }); + + expect(cache.memorySize).toBe(2); + expect(await cache.get("op", "k2", parseAccount)).toBeNull(); // evicted + expect(await cache.get("op", "k1", parseAccount)).not.toBeNull(); + }); + + it("delete and clearMemory remove entries", async () => { + const redis = fakeRedis(); + const cache = cacheWith(redis); + await cache.set("op", "k1", { account_id: ACCOUNT }); + await cache.delete("k1"); + expect(redis.store.has("k1")).toBe(false); + expect(cache.memorySize).toBe(0); + + await cache.set("op", "k2", { account_id: ACCOUNT }); + cache.clearMemory(); + expect(cache.memorySize).toBe(0); + }); +}); + +describe("resolveFederatedAddress with the cache", () => { + const tomlResponse = { + ok: true, + status: 200, + text: async () => 'FEDERATION_SERVER="https://fed.example.com/federation"', + }; + + function makeFetch() { + return vi.fn(async (url) => { + if (String(url).includes("stellar.toml")) return tomlResponse; + return { ok: true, status: 200, json: async () => ({ account_id: ACCOUNT }) }; + }); + } + + beforeEach(() => resetValidatorMetrics()); + + it("resolves once, then serves repeats from the cache", async () => { + const fetchFn = makeFetch(); + const cache = cacheWith({ isOpen: false }); + + const first = await resolveFederatedAddress("bob*example.com", { fetchFn, cache }); + const second = await resolveFederatedAddress("bob*example.com", { fetchFn, cache }); + + expect(first).toEqual({ account_id: ACCOUNT }); + expect(second).toEqual(first); + expect(fetchFn).toHaveBeenCalledTimes(2); // toml + federation, once + expect(await cacheCount({ result: "hit" })).toBe(1); + }); + + it("coalesces concurrent identical lookups into one network resolution", async () => { + const fetchFn = makeFetch(); + const cache = cacheWith({ isOpen: false }); + + const results = await Promise.all([ + resolveFederatedAddress("bob*example.com", { fetchFn, cache }), + resolveFederatedAddress("bob*example.com", { fetchFn, cache }), + resolveFederatedAddress("bob*example.com", { fetchFn, cache }), + ]); + + expect(results.every((r) => r.account_id === ACCOUNT)).toBe(true); + expect(fetchFn).toHaveBeenCalledTimes(2); + expect(await cacheCount({ result: "coalesced" })).toBe(2); + }); + + it("does not cache failures", async () => { + const failing = vi.fn(async () => ({ ok: false, status: 404 })); + const cache = cacheWith({ isOpen: false }); + + await expect(resolveFederatedAddress("bob*example.com", { fetchFn: failing, cache, maxRetries: 0 })).rejects.toThrow(); + const fetchFn = makeFetch(); + await expect(resolveFederatedAddress("bob*example.com", { fetchFn, cache })).resolves.toEqual({ + account_id: ACCOUNT, + }); + expect(fetchFn).toHaveBeenCalled(); + }); + + it("clears the in-flight entry after a failure so a retry can succeed", async () => { + const cache = cacheWith({ isOpen: false }); + const failing = vi.fn(async () => ({ ok: false, status: 404 })); + await expect(resolveFederatedAddress("bob*example.com", { fetchFn: failing, cache, maxRetries: 0 })).rejects.toThrow(); + + const fetchFn = makeFetch(); + expect(await resolveFederatedAddress("bob*example.com", { fetchFn, cache })).toEqual({ account_id: ACCOUNT }); + }); + + it("rejects invalid syntax before touching the cache", async () => { + const cache = cacheWith({ isOpen: false }); + const getSpy = vi.spyOn(cache, "get"); + await expect(resolveFederatedAddress("not-an-address", { fetchFn: makeFetch(), cache })).rejects.toThrow(); + expect(getSpy).not.toHaveBeenCalled(); + }); + + it("bypasses the cache with cache: false", async () => { + const fetchFn = makeFetch(); + await resolveFederatedAddress("bob*example.com", { fetchFn, cache: false }); + await resolveFederatedAddress("bob*example.com", { fetchFn, cache: false }); + expect(fetchFn).toHaveBeenCalledTimes(4); + }); + + it("does not use a cache by default unless VALIDATOR_CACHE_ENABLED=true", async () => { + const fetchFn = makeFetch(); + delete process.env.VALIDATOR_CACHE_ENABLED; + await resolveFederatedAddress("bob*example.com", { fetchFn }); + await resolveFederatedAddress("bob*example.com", { fetchFn }); + expect(fetchFn).toHaveBeenCalledTimes(4); + }); + + it("ignores a poisoned cached value and re-resolves", async () => { + const redis = fakeRedis(); + const cache = cacheWith(redis); + const key = buildValidatorCacheKey("federation", "bob*example.com"); + redis.store.set(key, JSON.stringify({ account_id: "GBAD" })); + + const fetchFn = makeFetch(); + expect(await resolveFederatedAddress("bob*example.com", { fetchFn, cache })).toEqual({ account_id: ACCOUNT }); + expect(fetchFn).toHaveBeenCalledTimes(2); + }); +}); + +describe("validator throughput telemetry", () => { + beforeEach(() => resetValidatorMetrics()); + + it("reports evaluations per second per operation over the window", () => { + const now = 10_000_000; + for (let i = 0; i < 120; i += 1) recordValidatorThroughput("public_key", now); + recordValidatorThroughput("signature_verify", now); + + const rates = getValidatorThroughput(now); + expect(rates.public_key).toBe(120 / THROUGHPUT_WINDOW_SECONDS); + expect(rates.signature_verify).toBe(1 / THROUGHPUT_WINDOW_SECONDS); + }); + + it("decays to zero once traffic leaves the window", () => { + const now = 10_000_000; + recordValidatorThroughput("public_key", now); + expect(getValidatorThroughput(now + (THROUGHPUT_WINDOW_SECONDS + 1) * 1000)).toEqual({}); + }); + + it("bounds the tracked operations", () => { + for (let i = 0; i < 100; i += 1) recordValidatorThroughput(`op_${i}`); + expect(Object.keys(getValidatorThroughput()).length).toBeLessThanOrEqual(32); + }); + + it("is fed by real validator calls and exported as a gauge", async () => { + isValidStellarPublicKey(ACCOUNT); + isValidStellarPublicKey("nope"); + + expect(getValidatorThroughput().public_key).toBeGreaterThan(0); + const text = await validatorRegister.metrics(); + expect(text).toContain("stellar_validator_throughput_per_second"); + expect(text).toContain("stellar_validator_cache_operations_total"); + }); +}); diff --git a/backend/src/lib/stellar/validators-metrics.js b/backend/src/lib/stellar/validators-metrics.js index e34a818..76bdf68 100644 --- a/backend/src/lib/stellar/validators-metrics.js +++ b/backend/src/lib/stellar/validators-metrics.js @@ -61,7 +61,80 @@ export const validatorDlqOperationsTotal = new client.Counter({ labelNames: ["action", "status"], }); +/** + * Cache operations for federated-address resolution (#1765). + * + * result: hit | miss | set | invalid | error | coalesced + * backend: redis | memory + */ +export const validatorCacheOperationsTotal = new client.Counter({ + name: "stellar_validator_cache_operations_total", + help: "Validator cache operations by operation, result and backend", + labelNames: ["operation", "result", "backend"], +}); + +/** + * Throughput over a rolling window, per operation, in evaluations per second. + * Refreshed at scrape time so it decays to zero when traffic stops. + */ +export const validatorThroughputPerSecond = new client.Gauge({ + name: "stellar_validator_throughput_per_second", + help: "Validator evaluations per second over the rolling throughput window", + labelNames: ["operation"], + collect() { + this.reset(); + for (const [operation, perSecond] of Object.entries(getValidatorThroughput())) { + this.set({ operation }, perSecond); + } + }, +}); + +export const THROUGHPUT_WINDOW_SECONDS = 60; +const MAX_TRACKED_OPERATIONS = 32; +// operation -> Map(epochSecond -> count) +const throughputBuckets = new Map(); + +/** + * Record one evaluation of `operation`. O(1); buckets older than the window are + * dropped on write, so memory is bounded by window x operations. + */ +export function recordValidatorThroughput(operation, now = Date.now()) { + const op = String(operation); + let buckets = throughputBuckets.get(op); + if (!buckets) { + if (throughputBuckets.size >= MAX_TRACKED_OPERATIONS) return; + buckets = new Map(); + throughputBuckets.set(op, buckets); + } + const second = Math.floor(now / 1000); + buckets.set(second, (buckets.get(second) || 0) + 1); + const cutoff = second - THROUGHPUT_WINDOW_SECONDS; + for (const key of buckets.keys()) { + if (key <= cutoff) buckets.delete(key); + else break; // keys are inserted in increasing order + } +} + +/** + * Evaluations per second per operation over the last THROUGHPUT_WINDOW_SECONDS. + */ +export function getValidatorThroughput(now = Date.now()) { + const second = Math.floor(now / 1000); + const cutoff = second - THROUGHPUT_WINDOW_SECONDS; + const result = {}; + for (const [operation, buckets] of throughputBuckets) { + let total = 0; + for (const [key, count] of buckets) { + if (key > cutoff) total += count; + } + if (total > 0) result[operation] = total / THROUGHPUT_WINDOW_SECONDS; + } + return result; +} + // Register all metrics with isolated registry +validatorRegister.registerMetric(validatorCacheOperationsTotal); +validatorRegister.registerMetric(validatorThroughputPerSecond); validatorRegister.registerMetric(validatorEvaluationsTotal); validatorRegister.registerMetric(validatorRejectionsTotal); validatorRegister.registerMetric(validatorDuration); @@ -72,6 +145,8 @@ validatorRegister.registerMetric(validatorDlqOperationsTotal); * Reset all validator metrics (useful for isolated tests). */ export function resetValidatorMetrics() { + throughputBuckets.clear(); + validatorCacheOperationsTotal.reset(); validatorEvaluationsTotal.reset(); validatorRejectionsTotal.reset(); validatorDuration.reset(); diff --git a/backend/src/lib/stellar/validators.js b/backend/src/lib/stellar/validators.js index 18e3062..7d587dc 100644 --- a/backend/src/lib/stellar/validators.js +++ b/backend/src/lib/stellar/validators.js @@ -19,9 +19,18 @@ import { validatorRejectionsTotal, validatorDlqDepth, validatorDlqOperationsTotal, + validatorCacheOperationsTotal, + validatorThroughputPerSecond, + recordValidatorThroughput, + getValidatorThroughput, validatorRegister, resetValidatorMetrics, } from "./validators-metrics.js"; +import { + ValidatorCache, + validatorCache, + buildValidatorCacheKey, +} from "./validators-cache.js"; // Re-export metrics and registry for observability scrapers export { @@ -32,7 +41,19 @@ export { validatorDuration, validatorDlqDepth, validatorDlqOperationsTotal, + validatorCacheOperationsTotal, + validatorThroughputPerSecond, + getValidatorThroughput, }; +export { ValidatorCache, validatorCache, buildValidatorCacheKey }; + +/** + * Count an evaluation outcome and feed the throughput window (#1765). + */ +function recordEvaluation(operation, outcome) { + validatorEvaluationsTotal.inc({ operation, outcome }); + recordValidatorThroughput(operation); +} // ─── Constants & Patterns ─────────────────────────────────────────────────── @@ -285,21 +306,21 @@ export function sanitizeStrKey(value, options = {}) { export function isValidStellarPublicKey(value) { const start = Date.now(); if (typeof value !== "string") { - validatorEvaluationsTotal.inc({ operation: "public_key", outcome: "invalid" }); + recordEvaluation("public_key", "invalid"); return false; } const publicKey = value.trim(); if (!STELLAR_PUBLIC_KEY_PATTERN.test(publicKey)) { - validatorEvaluationsTotal.inc({ operation: "public_key", outcome: "invalid" }); + recordEvaluation("public_key", "invalid"); return false; } // SDK verification if available if (typeof StellarSdk.StrKey?.isValidEd25519PublicKey === "function") { const valid = StellarSdk.StrKey.isValidEd25519PublicKey(publicKey); - validatorEvaluationsTotal.inc({ operation: "public_key", outcome: valid ? "valid" : "invalid" }); + recordEvaluation("public_key", valid ? "valid" : "invalid"); validatorDuration.observe({ operation: "public_key" }, (Date.now() - start) / 1000); return valid; } @@ -308,11 +329,11 @@ export function isValidStellarPublicKey(value) { try { const decoded = decodeStrKey(publicKey); const valid = decoded.versionByte === STRKEY_VERSION_BYTES.ed25519PublicKey; - validatorEvaluationsTotal.inc({ operation: "public_key", outcome: valid ? "valid" : "invalid" }); + recordEvaluation("public_key", valid ? "valid" : "invalid"); validatorDuration.observe({ operation: "public_key" }, (Date.now() - start) / 1000); return valid; } catch { - validatorEvaluationsTotal.inc({ operation: "public_key", outcome: "invalid" }); + recordEvaluation("public_key", "invalid"); return false; } } @@ -533,7 +554,7 @@ export function isValidEd25519Signature(signature) { } if (!sigBuf || sigBuf.length !== 64) { - validatorEvaluationsTotal.inc({ operation: "signature_format", outcome: "invalid" }); + recordEvaluation("signature_format", "invalid"); return false; } @@ -541,15 +562,15 @@ export function isValidEd25519Signature(signature) { const s = readLittleEndianBigInt(sigBuf, 32, 32); if (s >= ED25519_L) { validatorRejectionsTotal.inc({ operation: "signature_format", reason: "malleable_scalar" }); - validatorEvaluationsTotal.inc({ operation: "signature_format", outcome: "invalid" }); + recordEvaluation("signature_format", "invalid"); return false; } - validatorEvaluationsTotal.inc({ operation: "signature_format", outcome: "valid" }); + recordEvaluation("signature_format", "valid"); validatorDuration.observe({ operation: "signature_format" }, (Date.now() - start) / 1000); return true; } catch { - validatorEvaluationsTotal.inc({ operation: "signature_format", outcome: "invalid" }); + recordEvaluation("signature_format", "invalid"); return false; } } @@ -612,10 +633,7 @@ export function verifyEd25519Signature(publicKey, data, signature) { const keypair = StellarSdk.Keypair.fromPublicKey(publicKey.trim()); const valid = keypair.verify(dataBuf, sigBuf); - validatorEvaluationsTotal.inc({ - operation: "signature_verify", - outcome: valid ? "valid" : "invalid", - }); + recordEvaluation("signature_verify", valid ? "valid" : "invalid"); validatorDuration.observe({ operation: "signature_verify" }, (Date.now() - start) / 1000); if (!valid) { @@ -624,7 +642,7 @@ export function verifyEd25519Signature(publicKey, data, signature) { return { valid: true }; } catch (err) { - validatorEvaluationsTotal.inc({ operation: "signature_verify", outcome: "error" }); + recordEvaluation("signature_verify", "error"); return { valid: false, reason: err.message || "Signature verification error" }; } } @@ -716,7 +734,7 @@ export function sanitizeFederatedAddress(value) { * @param {ValidatorDeadLetterQueue} [options.dlq] - Dead-letter queue * @returns {Promise<{ account_id: string, memo?: string, memo_type?: string }>} */ -export async function resolveFederatedAddress(federatedAddress, options = {}) { +async function resolveFederatedAddressUncached(federatedAddress, options = {}) { const start = Date.now(); const { fetchFn = globalThis.fetch, @@ -851,7 +869,7 @@ export async function resolveFederatedAddress(federatedAddress, options = {}) { for (let attempt = 0; attempt <= maxRetries; attempt++) { try { const result = await executeResolution(); - validatorEvaluationsTotal.inc({ operation: "federation_resolve", outcome: "valid" }); + recordEvaluation("federation_resolve", "valid"); validatorDuration.observe({ operation: "federation_resolve" }, (Date.now() - start) / 1000); return result; } catch (err) { @@ -873,10 +891,96 @@ export async function resolveFederatedAddress(federatedAddress, options = {}) { ); } - validatorEvaluationsTotal.inc({ operation: "federation_resolve", outcome: "error" }); + recordEvaluation("federation_resolve", "error"); throw lastError; } +// ─── Federated address resolution: Redis cache + request coalescing (#1765) ── + +/** Concurrent identical lookups share one resolution: cacheKey -> Promise. */ +const inFlightResolutions = new Map(); + +/** + * Re-validate a cached federation result. A poisoned or corrupt cache entry + * (wrong shape, invalid account id, bad memo) is rejected, never returned. + */ +function parseCachedFederationResult(raw) { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null; + const accountId = typeof raw.account_id === "string" ? raw.account_id.trim() : ""; + if (!isValidStellarPublicKey(accountId)) return null; + const result = { account_id: accountId }; + if (raw.memo !== undefined) { + const memoType = typeof raw.memo_type === "string" ? raw.memo_type : "text"; + if (typeof raw.memo !== "string" || !validateMemo(raw.memo, memoType).valid) return null; + result.memo = raw.memo; + result.memo_type = memoType; + } + return result; +} + +function resolveFederationCache(option, env = process.env) { + if (option === false || option === null) return null; + if (option && typeof option.get === "function" && typeof option.set === "function") return option; + // Opt-in default: enable with VALIDATOR_CACHE_ENABLED=true (Redis when + // REDIS_URL is reachable, otherwise a bounded in-memory cache). + return env.VALIDATOR_CACHE_ENABLED === "true" ? validatorCache : null; +} + +/** + * Resolve a federated address (`name*domain`) to an account id. + * + * Successful results are cached (Redis, with an in-memory fallback) and + * concurrent identical lookups are coalesced into one network resolution. + * Failures are never cached. Pass `{ cache: false }` to bypass, or + * `{ cache: }` to supply a store; see resolveFederationCache. + * + * Throughput and cache effectiveness are exported as Prometheus metrics + * (`stellar_validator_throughput_per_second`, `stellar_validator_cache_operations_total`). + */ +export async function resolveFederatedAddress(federatedAddress, options = {}) { + const cache = resolveFederationCache(options.cache); + let cacheKey = null; + if (cache) { + try { + cacheKey = buildValidatorCacheKey("federation", sanitizeFederatedAddress(federatedAddress).address); + } catch { + // Invalid syntax: let the uncached path record the rejection and throw. + return resolveFederatedAddressUncached(federatedAddress, options); + } + } + if (!cache || !cacheKey) { + return resolveFederatedAddressUncached(federatedAddress, options); + } + + const start = Date.now(); + const cached = await cache.get("federation_resolve", cacheKey, parseCachedFederationResult); + if (cached) { + recordEvaluation("federation_resolve", "valid"); + validatorDuration.observe({ operation: "federation_resolve" }, (Date.now() - start) / 1000); + return cached; + } + + const inFlight = inFlightResolutions.get(cacheKey); + if (inFlight) { + validatorCacheOperationsTotal.inc({ + operation: "federation_resolve", + result: "coalesced", + backend: "memory", + }); + return inFlight; + } + + const pending = (async () => { + const result = await resolveFederatedAddressUncached(federatedAddress, options); + await cache.set("federation_resolve", cacheKey, result); + return result; + })().finally(() => { + inFlightResolutions.delete(cacheKey); + }); + inFlightResolutions.set(cacheKey, pending); + return pending; +} + // ─── Payload Sanitization & Anti-Tampering ────────────────────────────────── /** diff --git a/backend/src/routes/merchants.js b/backend/src/routes/merchants.js index 0b5f8dc..a014a48 100644 --- a/backend/src/routes/merchants.js +++ b/backend/src/routes/merchants.js @@ -28,6 +28,11 @@ import { readWebhookDomainVerification, verifyWebhookDomain, } from "../lib/webhook-domain-verification.js"; +import { + withMerchantLock, + compareAndSwapMerchant, +} from "../lib/merchant-key-lifecycle.js"; +import { persistVerificationWithRecovery } from "../lib/merchant-recovery.js"; const defaultMerchantRegistrationRateLimit = rateLimit({ windowMs: 60 * 60 * 1000, // 1 hour @@ -126,6 +131,11 @@ function createMerchantsRouter({ const business_name = body.business_name || email.split("@")[0]; const notification_email = body.notification_email || email; + // Serialize registrations per email so the existence check and the + // insert below cannot interleave with a concurrent request (#1772). + await withMerchantLock( + { scope: "register", id: email, operation: "register" }, + async () => { // Check if merchant already exists const { data: existing } = await supabase .from("merchants") @@ -163,6 +173,13 @@ function createMerchantsRouter({ .single(); if (insertError) { + // Unique violation: another instance registered this email between our + // check and insert (e.g. the lock expired or Redis was unreachable). + if (insertError.code === "23505") { + return res + .status(409) + .json({ error: "Merchant with this email already exists" }); + } console.error("Supabase insert error:", JSON.stringify(insertError)); console.error("Supabase insert error details:", insertError.message, insertError.code, insertError.hint); insertError.status = 500; @@ -188,6 +205,8 @@ function createMerchantsRouter({ created_at: merchant.created_at, }, }); + }, + ); } catch (err) { next(err); } @@ -219,15 +238,17 @@ function createMerchantsRouter({ try { const newApiKey = `sk_${randomBytes(24).toString("hex")}`; - const { error } = await supabase - .from("merchants") - .update({ api_key: newApiKey }) - .eq("id", req.merchant.id); - - if (error) { - error.status = 500; - throw error; - } + await withMerchantLock( + { scope: "key", id: req.merchant.id, operation: "rotate_key" }, + () => + compareAndSwapMerchant( + supabase, + req.merchant.id, + { column: "api_key", value: req.merchant.api_key }, + { api_key: newApiKey }, + "rotate_key", + ), + ); res.json({ api_key: newApiKey }); } catch (err) { @@ -290,19 +311,21 @@ function createMerchantsRouter({ const newWebhookSecret = `whsec_${randomBytes(32).toString("hex")}`; - const { error } = await supabase - .from("merchants") - .update({ - webhook_secret_old: req.merchant.webhook_secret, - webhook_secret_expiry: expiryIso, - webhook_secret: newWebhookSecret, - }) - .eq("id", req.merchant.id); - - if (error) { - error.status = 500; - throw error; - } + await withMerchantLock( + { scope: "key", id: req.merchant.id, operation: "rotate_webhook_secret" }, + () => + compareAndSwapMerchant( + supabase, + req.merchant.id, + { column: "webhook_secret", value: req.merchant.webhook_secret }, + { + webhook_secret_old: req.merchant.webhook_secret, + webhook_secret_expiry: expiryIso, + webhook_secret: newWebhookSecret, + }, + "rotate_webhook_secret", + ), + ); res.json({ webhook_secret: newWebhookSecret, @@ -655,14 +678,20 @@ function createMerchantsRouter({ metadata: data.metadata, }); - const { error: updateError } = await supabase - .from("merchants") - .update({ metadata: result.metadata }) - .eq("id", req.merchant.id); + // Retry transient write failures; if they persist, dead-letter the result + // for background recovery and still return it (#1771). + const persistence = await persistVerificationWithRecovery(supabase, { + merchantId: req.merchant.id, + metadata: result.metadata, + verification: result.verification, + }); - if (updateError) { - updateError.status = 500; - throw updateError; + if (!persistence.persisted) { + return res.status(202).json({ + webhook_domain_verification: result.verification, + persisted: false, + recovery: "queued", + }); } res.json({ @@ -695,15 +724,17 @@ function createMerchantsRouter({ try { const newSecret = `whsec_${randomBytes(24).toString("hex")}`; - const { error } = await supabase - .from("merchants") - .update({ webhook_secret: newSecret }) - .eq("id", req.merchant.id); - - if (error) { - error.status = 500; - throw error; - } + await withMerchantLock( + { scope: "key", id: req.merchant.id, operation: "regenerate_webhook_secret" }, + () => + compareAndSwapMerchant( + supabase, + req.merchant.id, + { column: "webhook_secret", value: req.merchant.webhook_secret }, + { webhook_secret: newSecret }, + "regenerate_webhook_secret", + ), + ); res.json({ webhook_secret: newSecret }); } catch (err) { @@ -737,17 +768,19 @@ function createMerchantsRouter({ async (req, res, next) => { try { const newApiKey = `sk_${randomBytes(24).toString("hex")}`; - - const { error } = await supabase - .from("merchants") - .update({ api_key: newApiKey }) - .eq("id", req.merchant.id); - - if (error) { - error.status = 500; - throw error; - } - + + await withMerchantLock( + { scope: "key", id: req.merchant.id, operation: "generate_api_key" }, + () => + compareAndSwapMerchant( + supabase, + req.merchant.id, + { column: "api_key", value: req.merchant.api_key }, + { api_key: newApiKey }, + "generate_api_key", + ), + ); + res.json({ api_key: newApiKey }); @@ -788,9 +821,10 @@ function createMerchantsRouter({ async (req, res, next) => { try { const body = req.body; - const result = await merchantService.rotateApiKey( - req.merchant.id, - body.grace_period_hours + const result = await withMerchantLock( + { scope: "key", id: req.merchant.id, operation: "rotate_api_key" }, + () => + merchantService.rotateApiKey(req.merchant.id, body.grace_period_hours), ); res.json(result); } catch (err) { @@ -850,9 +884,10 @@ function createMerchantsRouter({ async (req, res, next) => { try { const body = req.body; - const result = await merchantService.setApiKeyExpiry( - req.merchant.id, - body.expires_at + const result = await withMerchantLock( + { scope: "key", id: req.merchant.id, operation: "set_api_key_expiry" }, + () => + merchantService.setApiKeyExpiry(req.merchant.id, body.expires_at), ); res.json(result); } catch (err) { diff --git a/backend/src/routes/merchants.test.js b/backend/src/routes/merchants.test.js index 1782834..e145d2c 100644 --- a/backend/src/routes/merchants.test.js +++ b/backend/src/routes/merchants.test.js @@ -3,6 +3,7 @@ import express from "express"; import request from "supertest"; const eq = vi.fn(); +const select = vi.fn(); const update = vi.fn(() => ({ eq })); const from = vi.fn(() => ({ update })); @@ -38,7 +39,9 @@ describe("POST /api/merchants/rotate-webhook-secret", () => { beforeEach(() => { vi.clearAllMocks(); delete process.env.WEBHOOK_SECRET_ROTATION_GRACE_HOURS; - eq.mockResolvedValue({ error: null }); + // The rotation is a compare-and-swap: update().eq(id).eq(col, old).select("id"). + select.mockResolvedValue({ data: [{ id: "merchant-123" }], error: null }); + eq.mockImplementation(() => ({ eq, is: eq, select })); }); it("rotates secret with default 24h grace period", async () => { @@ -75,6 +78,8 @@ describe("POST /api/merchants/rotate-webhook-secret", () => { expect(expiry).toBeLessThanOrEqual(upperBound); expect(eq).toHaveBeenCalledWith("id", "merchant-123"); + // Guarded by the credential that was read, so a stale rotation cannot clobber a newer one. + expect(eq).toHaveBeenCalledWith("webhook_secret", "whsec_old_secret"); expect(res.json).toHaveBeenCalledTimes(1); const responsePayload = res.json.mock.calls[0][0]; @@ -149,3 +154,81 @@ describe("merchant route authentication", () => { expect(response.body).toEqual({ error: "Missing x-api-key header" }); }); }); + +describe("concurrent credential rotation (#1772)", () => { + beforeEach(async () => { + vi.clearAllMocks(); + const { resetLocalSessionLocksForTests } = await import("../lib/payment-session-lock.js"); + resetLocalSessionLocksForTests(); + select.mockResolvedValue({ data: [{ id: "merchant-123" }], error: null }); + eq.mockImplementation(() => ({ eq, is: eq, select })); + }); + + async function rotateHandler() { + const { default: createMerchantsRouter } = await import("./merchants.js"); + return getRotateWebhookSecretHandler(createMerchantsRouter()); + } + + function makeReq() { + return { body: {}, merchant: { id: "merchant-123", webhook_secret: "whsec_old_secret" } }; + } + + it("returns 409 to the caller whose credential changed underneath it, without leaking secrets", async () => { + select.mockResolvedValue({ data: [], error: null }); + const handler = await rotateHandler(); + const res = createResponse(); + const next = vi.fn(); + + await handler(makeReq(), res, next); + + expect(res.json).not.toHaveBeenCalled(); + expect(next).toHaveBeenCalledTimes(1); + const err = next.mock.calls[0][0]; + expect(err.status).toBe(409); + expect(err.code).toBe("MERCHANT_CREDENTIAL_CONFLICT"); + expect(JSON.stringify({ message: err.message })).not.toMatch(/whsec_/); + }); + + it("rejects a second rotation that arrives while the first is in flight", async () => { + let release; + select.mockImplementationOnce( + () => + new Promise((resolve) => { + release = () => resolve({ data: [{ id: "merchant-123" }], error: null }); + }), + ); + const handler = await rotateHandler(); + + const firstRes = createResponse(); + const firstNext = vi.fn(); + const first = handler(makeReq(), firstRes, firstNext); + await new Promise((r) => setTimeout(r, 20)); // let the first acquire the lock + + const secondRes = createResponse(); + const secondNext = vi.fn(); + await handler(makeReq(), secondRes, secondNext); + + expect(secondRes.json).not.toHaveBeenCalled(); + expect(secondNext.mock.calls[0][0]).toMatchObject({ status: 409, code: "MERCHANT_LIFECYCLE_BUSY" }); + + release(); + await first; + expect(firstRes.json).toHaveBeenCalledTimes(1); + expect(firstNext).not.toHaveBeenCalled(); + // Only the winner reached the database. + expect(update).toHaveBeenCalledTimes(1); + }); + + it("surfaces a database failure as a 500 and releases the lock", async () => { + select.mockResolvedValueOnce({ data: null, error: new Error("db down") }); + const handler = await rotateHandler(); + const next = vi.fn(); + + await handler(makeReq(), createResponse(), next); + expect(next.mock.calls[0][0].status).toBe(500); + + const res = createResponse(); + await handler(makeReq(), res, vi.fn()); + expect(res.json).toHaveBeenCalledTimes(1); // lock was released, retry succeeds + }); +}); diff --git a/backend/src/routes/paymentDetails.js b/backend/src/routes/paymentDetails.js index f607ccc..1420eaf 100644 --- a/backend/src/routes/paymentDetails.js +++ b/backend/src/routes/paymentDetails.js @@ -2,6 +2,7 @@ import express from "express"; import { Horizon } from "stellar-sdk"; import { supabase } from "../lib/supabase.js"; import { validateUuidParam } from "../lib/validate-uuid.js"; +import { fetchTxMetaWithRecovery } from "../lib/payment-details-recovery.js"; // ─── Horizon client ─────────────────────────────────────────────────────────── // Mirrors the network selection used elsewhere in the project. @@ -16,30 +17,27 @@ const HORIZON_URL = const horizonServer = new Horizon.Server(HORIZON_URL); // ─── Helper: fetch tx metadata from Horizon ─────────────────────────────────── -// Returns null (non-throwing) when: -// • tx_id is falsy +// Never throws; resolves to null when the metadata is unavailable: +// • tx_id is falsy or not a 64-hex transaction hash // • Horizon 404s (tx not yet propagated) -// • any transient network error +// • a non-retryable Horizon error +// Transient Horizon failures (network errors, 408, 429, 5xx) are retried with +// backoff, and if they still fail the lookup is dead-lettered and recovered in +// the background (#1776), so a later request is served from the recovery cache. // The payment record is always returned regardless. +async function loadTxMeta(txId) { + const tx = await horizonServer.transactions().transaction(txId).call(); + return { + tx_hash: tx.hash, + ledger: tx.ledger, // integer ledger sequence number + timestamp: tx.created_at, // ISO-8601 string from Horizon + }; +} + async function fetchStellarMeta(txId) { if (!txId) return null; - - try { - const tx = await horizonServer.transactions().transaction(txId).call(); - return { - tx_hash: tx.hash, - ledger: tx.ledger, // integer ledger sequence number - timestamp: tx.created_at, // ISO-8601 string from Horizon - }; - } catch (err) { - // 404 = tx not visible on Horizon yet — silent - // anything else is unexpected but non-fatal - if (err?.response?.status !== 404) { - console.warn("[stellar] tx fetch failed", { txId, err: err.message }); - } - return null; - } + return fetchTxMetaWithRecovery(txId, { fetchTx: loadTxMeta }); } // ─── Router ─────────────────────────────────────────────────────────────────── diff --git a/backend/src/routes/prometheus.js b/backend/src/routes/prometheus.js index c5be19f..6758d85 100644 --- a/backend/src/routes/prometheus.js +++ b/backend/src/routes/prometheus.js @@ -21,6 +21,8 @@ import { dbRlsRegister } from "../lib/db-rls-telemetry.js"; // Stellar Account & Ledger Key Validator metrics live in their own registry (issue #1764) // and are merged into the scrape output below. import { validatorRegister } from "../lib/stellar/validators-metrics.js"; +import { paymentDetailsRegister } from "../lib/payment-details-metrics.js"; +import { merchantLifecycleRegister } from "../lib/merchant-lifecycle-metrics.js"; import { logger } from "../lib/logger.js"; const metricRegisters = [ @@ -32,6 +34,8 @@ const metricRegisters = [ exchangeRateOracleRegister, dbRlsRegister, validatorRegister, + paymentDetailsRegister, + merchantLifecycleRegister, ]; export function createPrometheusRouter(registries = metricRegisters, contentType = register.contentType) {