commit ea0d0ead885ee0f69325787580d6007aaf821ce1
parent 3b3ec074bbfe9cbd3568884210bc0f38917c0883
Author: Florian Dold <dold@taler.net>
Date: Wed, 25 Nov 2026 22:48:39 +0100
wallet-core: validate transaction scope before reading history
Issue: https://bugs.taler.net/n/8437
Diffstat:
3 files changed, 195 insertions(+), 91 deletions(-)
diff --git a/packages/taler-harness/src/integrationtests/test-currency-scope-separation.ts b/packages/taler-harness/src/integrationtests/test-currency-scope-separation.ts
@@ -20,8 +20,10 @@
import {
Duration,
ScopeType,
+ TalerErrorCode,
TalerMerchantInstanceHttpClient,
- j2s,
+ TransactionsRequest,
+ TransactionType,
succeedOrThrow,
} from "@gnu-taler/taler-util";
import { WalletApiOperation } from "@gnu-taler/taler-wallet-core";
@@ -77,6 +79,33 @@ export async function runCurrencyScopeSeparationTest(t: GlobalTestState) {
console.log("setup done!");
+ async function assertAuditorScopeRejected() {
+ const scopeInfo = {
+ type: ScopeType.Auditor as const,
+ currency: "TESTKUDOS",
+ url: "https://auditor.example/",
+ };
+ for (const request of [
+ () =>
+ walletClient.call(WalletApiOperation.GetTransactions, { scopeInfo }),
+ () =>
+ walletClient.call(WalletApiOperation.GetTransactionsV2, { scopeInfo }),
+ () =>
+ walletClient.call(WalletApiOperation.GetTransactionsV2, {
+ scopeInfo,
+ limit: 0,
+ }),
+ ]) {
+ const err = await t.assertThrowsTalerErrorAsync(request);
+ t.assertDeepEqual(
+ err.errorDetail.code,
+ TalerErrorCode.WALLET_CORE_API_BAD_REQUEST,
+ );
+ t.assertDeepEqual(err.errorDetail.parameter, "scopeInfo");
+ }
+ }
+ await assertAuditorScopeRejected();
+
// Withdraw digital cash into the wallet.
const w1 = await withdrawViaBankV4(t, {
@@ -95,9 +124,7 @@ export async function runCurrencyScopeSeparationTest(t: GlobalTestState) {
await w1.withdrawalFinishedCond;
await w2.withdrawalFinishedCond;
-
- const bal = await walletClient.call(WalletApiOperation.GetBalances, {});
- console.log(j2s(bal));
+ await assertAuditorScopeRejected();
const payRes = await makeTestPaymentV2(t, {
merchant,
@@ -127,33 +154,89 @@ export async function runCurrencyScopeSeparationTest(t: GlobalTestState) {
await walletClient.call(WalletApiOperation.TestingWaitTransactionsFinal, {});
- const txns1 = await walletClient.call(WalletApiOperation.GetTransactionsV2, {
- scopeInfo: {
- type: ScopeType.Exchange,
- currency: "TESTKUDOS",
- url: exchangeOne.baseUrl,
+ const payment = await walletClient.call(
+ WalletApiOperation.GetTransactionById,
+ {
+ transactionId: payRes.transactionId,
},
- });
-
- console.log(`txns1: ${j2s(txns1)}`);
+ );
+ t.assertTrue(payment.type === TransactionType.Payment);
+ t.assertDeepEqual(payment.refunds.length, 1);
+ const refundId = payment.refunds[0].transactionId;
- const txns2 = await walletClient.call(WalletApiOperation.GetTransactionsV2, {
- scopeInfo: {
- type: ScopeType.Exchange,
- currency: "TESTKUDOS",
- url: exchangeTwo.baseUrl,
- },
+ // A free payment spends no coins, so it has no recorded funding exchange.
+ // It must remain visible in either TESTKUDOS balance's history (#8435).
+ const freePayment = await makeTestPaymentV2(t, {
+ merchant,
+ merchantAdminAccessToken: adminAccessToken,
+ walletClient,
+ order: { amount: "TESTKUDOS:0", summary: "Free item" },
});
+ await walletClient.call(WalletApiOperation.TestingWaitTransactionsFinal, {});
- console.log(`txns2: ${j2s(txns2)}`);
+ const scopeOne = {
+ type: ScopeType.Exchange as const,
+ currency: "TESTKUDOS",
+ url: exchangeOne.baseUrl,
+ };
+ const scopeTwo = { ...scopeOne, url: exchangeTwo.baseUrl };
+ async function assertHistory(
+ request: Pick<TransactionsRequest, "scopeInfo" | "filterByState">,
+ expectedIds: string[],
+ ) {
+ for (const operation of [
+ WalletApiOperation.GetTransactions,
+ WalletApiOperation.GetTransactionsV2,
+ ] as const) {
+ const { transactions } = await walletClient.call(operation, request);
+ t.assertDeepEqual(
+ transactions.map((tx) => tx.transactionId),
+ expectedIds,
+ );
+ }
+ }
+ await assertHistory({ scopeInfo: scopeOne }, [
+ w1.transactionId,
+ payRes.transactionId,
+ refundId,
+ freePayment.transactionId,
+ ]);
+ await assertHistory({ scopeInfo: scopeTwo }, [
+ w2.transactionId,
+ freePayment.transactionId,
+ ]);
+ await assertHistory(
+ { scopeInfo: { type: ScopeType.Global, currency: "TESTKUDOS" } },
+ [
+ w1.transactionId,
+ w2.transactionId,
+ payRes.transactionId,
+ refundId,
+ freePayment.transactionId,
+ ],
+ );
+ await assertHistory({ scopeInfo: { ...scopeOne, currency: "OTHER" } }, []);
- t.assertDeepEqual(
- txns1.transactions.map((x) => x.type),
- ["withdrawal", "payment", "refund"],
+ // Leave this withdrawal waiting for a bank transfer.
+ const pending = await walletClient.call(
+ WalletApiOperation.AcceptManualWithdrawal,
+ { exchangeBaseUrl: exchangeTwo.baseUrl, amount: "TESTKUDOS:5" },
);
+ await assertHistory({ scopeInfo: scopeOne, filterByState: "nonfinal" }, []);
+ await assertHistory({ scopeInfo: scopeTwo, filterByState: "nonfinal" }, [
+ pending.transactionId,
+ ]);
+
+ // Paging backwards skips the pending withdrawal and the more recent
+ // payment and refund from the first exchange to fill the two slots.
+ const page = await walletClient.call(WalletApiOperation.GetTransactionsV2, {
+ scopeInfo: scopeTwo,
+ filterByState: "final",
+ limit: -2,
+ });
t.assertDeepEqual(
- txns2.transactions.map((x) => x.type),
- ["withdrawal"],
+ page.transactions.map((tx) => tx.transactionId),
+ [freePayment.transactionId, w2.transactionId],
);
}
diff --git a/packages/taler-wallet-core/src/transactions.test.ts b/packages/taler-wallet-core/src/transactions.test.ts
@@ -22,7 +22,7 @@ import {
ParsedTransactionIdentifier,
parseTransactionIdentifier,
resolveTransactionReference,
- shouldSkipCurrency,
+ makeTransactionScopeFilter,
} from "./transactions.js";
import type { WalletWithdrawalGroup } from "./db/records.js";
import type { WalletDbTransaction } from "./db/transaction.js";
@@ -134,27 +134,56 @@ test("an unknown or ambiguous bank withdrawal reference is not resolved", async
});
test("legacy exchange scope conservatively matches transactions by URL", () => {
- const request = {
+ const matches = makeTransactionScopeFilter({
scopeInfo: {
- type: ScopeType.ExchangeLegacyKeys as const,
+ type: ScopeType.ExchangeLegacyKeys,
currency: "TESTKUDOS",
url: "https://exchange/",
masterPub: "superseded-key",
},
- };
+ });
assert.equal(
- shouldSkipCurrency(request, "TESTKUDOS", ["https://exchange/"]),
- false,
+ matches("TESTKUDOS", ["https://exchange/"]),
+ true,
"the matching URL must be included regardless of the master key",
);
assert.equal(
- shouldSkipCurrency(request, "TESTKUDOS", ["https://other-exchange/"]),
- true,
+ matches("TESTKUDOS", ["https://other-exchange/"]),
+ false,
"a different URL must still be excluded",
);
assert.equal(
- shouldSkipCurrency(request, "OTHER", ["https://exchange/"]),
- true,
+ matches("OTHER", ["https://exchange/"]),
+ false,
"a different currency must still be excluded",
);
});
+
+test("an exchange scope matches any funding exchange or an unknown funding exchange", () => {
+ const first = "https://first.example/";
+ const second = "https://second.example/";
+ const matches = makeTransactionScopeFilter({
+ scopeInfo: {
+ type: ScopeType.Exchange,
+ currency: "TESTKUDOS",
+ url: second,
+ },
+ });
+ assert.equal(matches("TESTKUDOS", [first, second]), true);
+ assert.equal(matches("TESTKUDOS", [first]), false);
+ assert.equal(matches("TESTKUDOS", []), true);
+ assert.equal(matches("OTHER", []), false);
+});
+
+test("scopeInfo takes precedence over the currency-only history filter", () => {
+ const currencyOnly = makeTransactionScopeFilter({ currency: "testkudos" });
+ assert.equal(currencyOnly("TESTKUDOS", []), true);
+ assert.equal(currencyOnly("OTHER", []), false);
+
+ const scoped = makeTransactionScopeFilter({
+ currency: "testkudos",
+ scopeInfo: { type: ScopeType.Global, currency: "other" },
+ });
+ assert.equal(scoped("TESTKUDOS", []), false);
+ assert.equal(scoped("OTHER", []), true);
+});
diff --git a/packages/taler-wallet-core/src/transactions.ts b/packages/taler-wallet-core/src/transactions.ts
@@ -80,53 +80,41 @@ import { WalletDbTransaction } from "./db/transaction.js";
const logger = new Logger("taler-wallet-core:transactions.ts");
-export function shouldSkipCurrency(
- transactionsRequest:
- | TransactionsRequest
- | GetTransactionsV2Request
- | undefined,
+type TransactionScopeFilter = (
currency: string,
- exchangesInTransaction: string[],
-): boolean {
- if (transactionsRequest?.scopeInfo) {
- const sameCurrency = Amounts.isSameCurrency(
- currency,
- transactionsRequest.scopeInfo.currency,
- );
- switch (transactionsRequest.scopeInfo.type) {
- case ScopeType.Global: {
- return !sameCurrency;
- }
- case ScopeType.Exchange:
- case ScopeType.ExchangeLegacyKeys: {
- // Transaction metadata only records the exchange URL. Treat every
- // key set served at that URL as a conservative match. This can
- // return false positives after a key rotation, but never hides older
- // transactions whose exact key set was not recorded.
- return (
- !sameCurrency ||
- (exchangesInTransaction.length > 0 &&
- !exchangesInTransaction.includes(transactionsRequest.scopeInfo.url))
- );
- }
- case ScopeType.Auditor: {
- // same currency and same auditor
- throw TalerError.fromDetail(
- TalerErrorCode.WALLET_CORE_API_BAD_REQUEST,
- { parameter: "scopeInfo" },
- "filtering transactions by auditor scope is not implemented",
- );
- }
- default:
- assertUnreachable(transactionsRequest.scopeInfo);
+ exchanges: string[],
+) => boolean;
+
+/** Resolve and validate the requested scope before inspecting any history. */
+export function makeTransactionScopeFilter(
+ request?: Pick<TransactionsRequest, "scopeInfo" | "currency">,
+): TransactionScopeFilter {
+ const scope = request?.scopeInfo;
+ switch (scope?.type) {
+ case undefined: {
+ const currency = request?.currency;
+ return currency
+ ? (txCurrency) => Amounts.isSameCurrency(currency, txCurrency)
+ : () => true;
}
+ case ScopeType.Global:
+ return (currency) => Amounts.isSameCurrency(scope.currency, currency);
+ case ScopeType.Exchange:
+ case ScopeType.ExchangeLegacyKeys:
+ // History may lack funding exchanges and only records their URLs,
+ // so a key rotation must not hide transactions at the same URL.
+ return (currency, exchanges) =>
+ Amounts.isSameCurrency(scope.currency, currency) &&
+ (exchanges.length === 0 || exchanges.includes(scope.url));
+ case ScopeType.Auditor:
+ throw TalerError.fromDetail(
+ TalerErrorCode.WALLET_CORE_API_BAD_REQUEST,
+ { parameter: "scopeInfo" },
+ "filtering transactions by auditor scope is not implemented",
+ );
+ default:
+ assertUnreachable(scope);
}
- if (transactionsRequest?.currency) {
- return (
- transactionsRequest.currency.toLowerCase() !== currency.toLowerCase()
- );
- }
- return false;
}
/**
@@ -355,10 +343,6 @@ function checkFilterIncludes(
req: GetTransactionsV2Request | undefined,
mtx: WalletTransactionMeta,
): boolean {
- if (shouldSkipCurrency(req, mtx.currency, mtx.exchanges)) {
- return false;
- }
-
const parsedTx = parseTransactionIdentifier(mtx.transactionId);
if (
parsedTx?.tag === TransactionType.Refresh &&
@@ -424,6 +408,7 @@ async function addFiltered(
wex: WalletExecutionContext,
tx: WalletDbTransaction,
req: GetTransactionsV2Request | undefined,
+ matchesScope: TransactionScopeFilter,
target: Transaction[],
source: WalletTransactionMeta[],
): Promise<number> {
@@ -435,7 +420,10 @@ async function addFiltered(
if (req?.limit != null && target.length >= Math.abs(req.limit)) {
break;
}
- if (checkFilterIncludes(req, mtx)) {
+ if (
+ matchesScope(mtx.currency, mtx.exchanges) &&
+ checkFilterIncludes(req, mtx)
+ ) {
const ctx = await getContextForTransaction(wex, mtx.transactionId);
const txDetails = await ctx.lookupFullTransaction(tx);
// FIXME: This means that in some cases we can return fewer transactions
@@ -547,6 +535,7 @@ export async function getTransactionsV2(
// Other requests are more difficult to implement
// in a performant way due to IndexedDB limitations.
+ const matchesScope = makeTransactionScopeFilter(transactionsRequest);
const resultTransactions: Transaction[] = [];
await wex.runWalletDbTx(async (tx) => {
@@ -564,7 +553,14 @@ export async function getTransactionsV2(
const res = await tx.listTransactionMetaByStatus({
onlyActive: false,
});
- await addFiltered(wex, tx, transactionsRequest, resultTransactions, res);
+ await addFiltered(
+ wex,
+ tx,
+ transactionsRequest,
+ matchesScope,
+ resultTransactions,
+ res,
+ );
} else {
if (limit === 0) {
return;
@@ -585,6 +581,7 @@ export async function getTransactionsV2(
wex,
tx,
transactionsRequest,
+ matchesScope,
resultTransactions,
page,
);
@@ -614,6 +611,7 @@ export async function getTransactions(
wex: WalletExecutionContext,
transactionsRequest?: TransactionsRequest,
): Promise<TransactionsResponse> {
+ const matchesScope = makeTransactionScopeFilter(transactionsRequest);
const transactions: Transaction[] = [];
const onlyActive = transactionsRequest?.filterByState === "nonfinal";
@@ -626,13 +624,7 @@ export async function getTransactions(
allMetaTransactions.map((x) => x.transactionId),
);
for (const metaTx of allMetaTransactions) {
- if (
- shouldSkipCurrency(
- transactionsRequest,
- metaTx.currency,
- metaTx.exchanges,
- )
- ) {
+ if (!matchesScope(metaTx.currency, metaTx.exchanges)) {
continue;
}