commit 81afe5524aac317811212e51532d56a38bdd9d9d
parent 281c8b2b392c08ef5775b16114949004b6d0d995
Author: Florian Dold <dold@taler.net>
Date: Fri, 27 Nov 2026 18:12:43 +0100
wallet-core: abort merchant payments refused with HTTP 451
Another exchange may already have deposited some of the selected coins.
Use the original selection to request an abort even when the refusal
body cannot be decoded.
Issue: https://bugs.taler.net/n/12291
Diffstat:
3 files changed, 195 insertions(+), 122 deletions(-)
diff --git a/packages/taler-util/src/http-client/merchant.ts b/packages/taler-util/src/http-client/merchant.ts
@@ -100,6 +100,7 @@ import {
codecForWalletTemplateDetails,
codecForWebhookDetails,
codecForWebhookSummaryResponse,
+ makeErrorDetail,
opEmptySuccess,
opFixedSuccess,
opKnownAlternativeHttpFailure,
@@ -112,6 +113,7 @@ import {
import {
HttpRequestLibrary,
HttpResponse,
+ getHttpResponseErrorDetails,
readTalerErrorResponse,
} from "@gnu-taler/taler-util/http";
import { opSuccessFromHttp } from "../operation.js";
@@ -543,12 +545,25 @@ export class TalerMerchantInstanceHttpClient {
return opKnownHttpFailure(resp.status, resp);
case HttpStatusCode.GatewayTimeout:
return opKnownHttpFailure(resp.status, resp);
- case HttpStatusCode.UnavailableForLegalReasons:
- return opKnownAlternativeHttpFailure(
- resp,
- resp.status,
- codecForPaymentDeniedLegallyResponse(),
- );
+ case HttpStatusCode.UnavailableForLegalReasons: {
+ // The wallet must abort even if the merchant's refusal body is
+ // malformed or the connection closes after the status arrives.
+ try {
+ const body = codecForPaymentDeniedLegallyResponse().decode(
+ await resp.json(),
+ );
+ return opKnownFailureWithBody(resp, resp.status, body);
+ } catch (e) {
+ return opKnownHttpFailure(
+ resp.status,
+ resp,
+ makeErrorDetail(TalerErrorCode.WALLET_RECEIVED_MALFORMED_RESPONSE, {
+ ...getHttpResponseErrorDetails(resp),
+ validationError: e instanceof Error ? e.message : String(e),
+ }),
+ );
+ }
+ }
default:
return opUnknownHttpFailure(resp);
}
diff --git a/packages/taler-wallet-core/src/pay-merchant.test.ts b/packages/taler-wallet-core/src/pay-merchant.test.ts
@@ -26,6 +26,7 @@ import {
ChoiceSelectionDetailType,
type MerchantContractTerms,
DenomKeyType,
+ type DepositInfo,
LongpollQueue,
ContractTermsUtil,
decodeCrock,
@@ -2349,60 +2350,160 @@ test("merchant pay failures distinguish stable outcomes from retryable outages",
}
});
-test("legal refusal pauses payment without replacing its coins", async () => {
- const runner = await makeIdbRunner();
- const proposalId = "legal-refusal";
- const purchase = claimPurchase(proposalId, PurchaseStatus.PendingPaying);
- purchase.payInfo = {
- payCoinSelection: {
- coinPubs: ["coin-one", "coin-two"],
- coinContributions: ["TESTKUDOS:1", "TESTKUDOS:2"],
- },
- payCoinSelectionUid: "selection-one",
- totalPayCost: "TESTKUDOS:3",
- };
- const originalPayInfo = structuredClone(purchase.payInfo);
- let stoppedTaskId: string | undefined;
- const wex = {
- async runWalletDbTx<T>(
- f: (tx: WalletDbTransaction) => Promise<T>,
- ): Promise<T> {
- return await runner.runReadWriteTx(f);
- },
- taskScheduler: {
- stopShepherdTask(taskId: string): void {
- stoppedTaskId = taskId;
- },
- },
- } as unknown as WalletExecutionContext;
- try {
- await runner.runReadWriteTx((tx) => tx.upsertPurchase(purchase));
- const ctx = new PayMerchantTransactionContext(wex, proposalId);
- const reason = {
- code: TalerErrorCode.MERCHANT_POST_ORDERS_ID_PAY_EXCHANGE_LEGALLY_REFUSED,
- exchangeBaseUrls: ["https://exchange.example/"],
- };
-
- assert.strictEqual(await ctx.suspendPayForLegalRefusal(reason), true);
+for (const reply of [
+ TalerErrorCode.MERCHANT_POST_ORDERS_ID_PAY_EXCHANGE_LEGALLY_REFUSED,
+ TalerErrorCode.MERCHANT_POST_ORDERS_ID_PAY_EXCHANGE_TRANSACTION_LIMIT_VIOLATION,
+ "invalid-json",
+ "missing-code",
+ "unreadable-body",
+] as const) {
+ test(`merchant refusal ${reply} sends both exchanges' coins to /abort`, async (t) => {
+ t.mock.timers.enable({ apis: ["Date"], now: 150_000 });
+ const runner = await makeIdbRunner();
+ try {
+ const purchase = makeDownloadedPurchase(
+ "legal-refusal",
+ PurchaseStatus.PendingPaying,
+ );
+ const coins = ["accepted", "refused"].map(makeCoin);
+ coins[1].exchangeBaseUrl = "https://refused.test/";
+ purchase.payInfo = {
+ payCoinSelection: {
+ coinPubs: coins.map((coin) => coin.coinPub),
+ coinContributions: ["TESTKUDOS:1", "TESTKUDOS:1"],
+ },
+ totalPayCost: "TESTKUDOS:2",
+ };
+ await runner.runReadWriteTx(async (tx) => {
+ await upsertTestContractTerms(tx, purchase, "TESTKUDOS:2");
+ await tx.upsertPurchase(purchase);
+ for (const coin of coins) {
+ const details = makeExchangeDetails(
+ coin.exchangeBaseUrl,
+ coin.exchangeBaseUrl,
+ );
+ coin.exchangeMasterPub = details.masterPublicKey;
+ const denom = makeDenomination(
+ coin.exchangeBaseUrl,
+ coin.denomPubHash,
+ );
+ denom.exchangeMasterPub = coin.exchangeMasterPub;
+ denom.stampStart = timestampProtocolToDb({ t_s: 1 });
+ await tx.upsertExchangeDetails(details);
+ await tx.upsertExchange({
+ ...makeExchange(coin.exchangeBaseUrl),
+ detailsPointer: {
+ masterPublicKey: coin.exchangeMasterPub,
+ currency: denom.currency,
+ updateClock: purchase.timestamp,
+ },
+ });
+ await tx.upsertDenomination(denom);
+ await tx.upsertCoin({ ...coin, status: CoinStatus.Dormant });
+ }
+ });
+ const refusedUrls = [coins[1].exchangeBaseUrl];
+ const requests: string[] = [];
+ const wex = {
+ runWalletDbTx: runner.runReadWriteTx.bind(runner),
+ ws: {
+ networkAvailable: true,
+ depositPermissionCache: new Map(),
+ cacheDepositPermissions() {},
+ denomInfoCache: new Cache(10, Duration.fromSpec({ minutes: 1 })),
+ refreshCostCache: new Cache(10, Duration.fromSpec({ minutes: 1 })),
+ runSequentialized: (_locks: string[], run: () => Promise<unknown>) =>
+ run(),
+ },
+ cryptoApi: {
+ signDepositPermission: async (coin: DepositInfo) => ({
+ exchange_url: coin.exchangeBaseUrl,
+ coin_pub: coin.coinPub,
+ }),
+ },
+ taskScheduler: { resetTask() {}, startShepherdTask() {} },
+ http: {
+ fetch: async (
+ url: string,
+ options: { method: string; body: unknown },
+ ) => {
+ assert.equal(options.method, "POST");
+ const path = new URL(url).pathname;
+ requests.push(path);
+ const headers = new HeadersImpl();
+ headers.set("content-type", "application/json");
+ if (path === "/orders/order/pay") {
+ return {
+ status: 451,
+ headers,
+ requestUrl: url,
+ requestMethod: options.method,
+ json: async () => {
+ if (reply === "unreadable-body")
+ throw new Error("response body truncated");
+ if (reply === "invalid-json")
+ throw new SyntaxError("Invalid JSON");
+ if (reply === "missing-code") return {};
+ return { code: reply, exchange_base_urls: refusedUrls };
+ },
+ text: async () => {
+ if (reply === "unreadable-body")
+ throw new Error("response body truncated");
+ return reply === "invalid-json" ? "<html>" : "{}";
+ },
+ };
+ }
+ assert.equal(path, "/orders/order/abort");
+ assert.deepEqual(options.body, {
+ h_contract: purchase.download!.contractTermsHash,
+ coins: coins.map((coin) => ({
+ coin_pub: coin.coinPub,
+ exchange_url: coin.exchangeBaseUrl,
+ })),
+ });
+ return {
+ status: 502,
+ headers,
+ json: async () => ({
+ refunds: [
+ { type: "failure", exchange_status: 503 },
+ { type: "undeposited" },
+ ],
+ }),
+ };
+ },
+ },
+ } as unknown as WalletExecutionContext;
+ const run = () => processPurchase(wex, purchase.proposalId);
+ assert.equal((await run()).type, TaskRunResultType.Progress);
+ const stored = await runner.runReadWriteTx((tx) =>
+ tx.getPurchase(purchase.proposalId),
+ );
+ assert.ok(stored);
+ assert.equal(stored.purchaseStatus, PurchaseStatus.AbortingWithRefund);
+ assert.deepEqual(stored.payInfo, purchase.payInfo);
+ if (typeof reply === "number") {
+ assert.deepEqual(stored.failReason, {
+ code: reply,
+ exchangeBaseUrls: refusedUrls,
+ });
+ } else {
+ assert.equal(
+ stored.failReason?.code,
+ TalerErrorCode.WALLET_RECEIVED_MALFORMED_RESPONSE,
+ );
+ assert.equal(stored.failReason?.httpStatusCode, 451);
+ assert.ok(stored.failReason?.validationError);
+ }
+ assert.deepEqual(stored.abortReason, stored.failReason);
+ assert.equal((await run()).type, TaskRunResultType.Backoff);
+ assert.deepEqual(requests, ["/orders/order/pay", "/orders/order/abort"]);
+ } finally {
+ await runner.close();
+ }
+ });
+}
- const stored = await runner.runReadWriteTx(async (tx) => ({
- purchase: await tx.getPurchase(proposalId),
- retry: await tx.getOperationRetry(ctx.taskId),
- refreshGroups: await tx.listAllRefreshGroups(),
- }));
- assert.strictEqual(
- stored.purchase?.purchaseStatus,
- PurchaseStatus.SuspendedPaying,
- );
- assert.deepStrictEqual(stored.purchase?.payInfo, originalPayInfo);
- assert.deepStrictEqual(stored.retry?.lastError, reason);
- assert.strictEqual(stored.retry?.retryInfo.retryCounter, 0);
- assert.deepStrictEqual(stored.refreshGroups, []);
- assert.strictEqual(stoppedTaskId, ctx.taskId);
- } finally {
- await runner.close();
- }
-});
test("already-paid recovery retains the paid-by-other terminal state", () => {
assert.strictEqual(
diff --git a/packages/taler-wallet-core/src/pay-merchant.ts b/packages/taler-wallet-core/src/pay-merchant.ts
@@ -127,7 +127,6 @@ import {
} from "./coinSelection.js";
import {
constructTaskIdentifier,
- DbRetryInfo,
genericWaitForState,
getGenericRecordHandle,
LookupFullTransactionOpts,
@@ -642,47 +641,6 @@ export class PayMerchantTransactionContext implements TransactionContext {
});
}
- /**
- * Pause a payment after the merchant reports that an exchange cannot
- * process it for legal reasons.
- *
- * A 451 response is not evidence that the selected coins are unusable.
- * Refreshing or reselecting them here would prevent an idempotent retry of
- * the same deposit permissions once the merchant has resolved the issue.
- * Instead, retain the exact payInfo and record the refusal as the current
- * transaction error. The task remains stopped until the user explicitly
- * resumes (or aborts) the payment.
- */
- async suspendPayForLegalRefusal(reason: TalerErrorDetail): Promise<boolean> {
- const { wex } = this;
- return await wex.runWalletDbTx(async (tx) => {
- const [purchase, h] = await this.getRecordHandle(tx);
- if (!purchase) {
- return false;
- }
- const nextStatus = getPayMerchantSuspendTransition(
- purchase.purchaseStatus,
- );
- if (
- nextStatus !== PurchaseStatus.SuspendedPaying &&
- nextStatus !== PurchaseStatus.SuspendedPayingReplay
- ) {
- return false;
- }
- purchase.purchaseStatus = nextStatus;
- await tx.upsertOperationRetry({
- id: this.taskId,
- lastError: reason,
- retryInfo: DbRetryInfo.reset(),
- });
- await h.update(purchase, "legal-refusal-suspend");
- tx.scheduleOnCommit(() =>
- wex.taskScheduler.stopShepherdTask(this.taskId),
- );
- return true;
- });
- }
-
async failTransaction(
fromSt: PurchaseStatus,
reason?: TalerErrorDetail,
@@ -1431,6 +1389,15 @@ async function recoverPayFailureForCompleteOrder(
return TaskRunResult.progress();
}
+function isPayLegalRefusal(code: number): boolean {
+ return (
+ code ===
+ TalerErrorCode.MERCHANT_POST_ORDERS_ID_PAY_EXCHANGE_LEGALLY_REFUSED ||
+ code ===
+ TalerErrorCode.MERCHANT_POST_ORDERS_ID_PAY_EXCHANGE_TRANSACTION_LIMIT_VIOLATION
+ );
+}
+
async function recoverPayAfterStableFailure(
ctx: PayMerchantTransactionContext,
reason: TalerErrorDetail,
@@ -4214,30 +4181,20 @@ async function processPurchasePay(
}
case HttpStatusCode.UnavailableForLegalReasons: {
logger.warn(`exchange refused merchant payment for legal reasons`);
- if (
- resp.body.code ===
- TalerErrorCode.MERCHANT_POST_ORDERS_ID_PAY_EXCHANGE_LEGALLY_REFUSED ||
- resp.body.code ===
- TalerErrorCode.MERCHANT_POST_ORDERS_ID_PAY_EXCHANGE_TRANSACTION_LIMIT_VIOLATION
- ) {
- const legalReason: TalerErrorDetail = {
+ // Another exchange may already have accepted its deposits. Abort with
+ // the full original selection while the merchant can still refund them.
+ if (!("body" in resp))
+ return recoverPayAfterStableFailure(ctx, resp.detail!);
+ if (isPayLegalRefusal(resp.body.code)) {
+ return recoverPayAfterStableFailure(ctx, {
code: resp.body.code,
exchangeBaseUrls: resp.body.exchange_base_urls,
- };
- const suspended = await ctx.suspendPayForLegalRefusal(legalReason);
- return suspended
- ? TaskRunResult.cancelled()
- : TaskRunResult.finished();
+ });
}
- return repairPayAfterExchangeFailure(
- wex,
- ctx,
- resp.body.exchange_base_urls,
- {
- code: TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION,
- message: `merchant returned invalid legal-refusal error code ${resp.body.code}`,
- },
- );
+ return recoverPayAfterStableFailure(ctx, {
+ code: TalerErrorCode.WALLET_TRANSACTION_PROTOCOL_VIOLATION,
+ message: `merchant returned invalid legal-refusal error code ${resp.body.code}`,
+ });
}
case HttpStatusCode.Gone:
logger.warn(`pay transaction aborted, order expired`);