catcrafts.net/tests/ShouldMatchBankTransfers/main.cpp
Jorijn van der Graaf 3c61116531
bank: a payment is spent once
A payer could place several orders and send one transfer naming all of
them. Each order looked for its own reference, found it, and saw the
full amount, so every order settled on one payment: three EUR 5 orders
on a single EUR 5 credit, reproduced. The rail logged "settle this one
by hand" and settled each of them. The README called it a known
limitation; it was a way to pay once for several orders.

The rail now records which payment settled which order, by the bank's
id, in <credits>.claims, before it reports the order paid, and a claimed
payment is left out of every other order's sum. The record cannot live
in the credits file, which the pull replaces every hour. It is read back
at start. If it cannot be written the rail settles nothing and says why;
if it is there and cannot be read the rail does not start. A claims
file that ends mid-line gets its line break before the next claim, or
that claim would be lost at the next start and the payment free again.

It does not rest on what a description looks like, because the payer
writes it. The "also quotes another reference" flag stays as a pointer
in the log and decides nothing: a name followed by a date has the same
shape. A payer who really sends one transfer for two orders gets the
first settled and the other by hand, with one line in the journal.

One payment is also counted once however many lines of the credits file
carry its id. Two lines are not meant to happen and were reproduced all
the same (one callback delivered on two connections at once passed the
id check twice), and summed they settle an order on half its price. The
callback's look-then-append is now under a lock as well.

ShouldMatchBankTransfers drives the matcher and the rail itself across
a restart, a torn claims file, an unreadable one and a duplicated line;
ShouldSettleBankTransfers shows over HTTP that one of three orders
settles.

Found in the security review of 2026-11-26; the torn claims file and
the duplicate line by the adversarial review of the first fix.

Co-Authored-By: Claude Mythos 5.2 <noreply@anthropic.com>
2026-11-26 11:05:35 +01:00

421 lines
21 KiB
C++

/*
catcrafts.net
Copyright (C) 2026 Catcrafts
The source code of this website is made available for viewing purposes only.
No permission is granted to copy, modify, distribute, or create derivative works.
*/
// MatchCredits: the decision that releases goods on the bank-transfer rail.
//
// Everything here is a case a real payer or a real bank actually produces. The
// reference travels through a human retyping it and a bank reformatting the
// field, so the interesting failures are all cosmetic-looking: a lower-case
// reference, a space inserted every four characters, the structured RF form
// quoted instead of the short one. Each of those arriving as "unpaid" would be
// money sitting in the account against an order the shop thinks was abandoned.
//
// The other half is refusing to over-match. A matcher that credits an order
// from money that was not for it is worse than one that misses: it ships goods
// nobody paid for.
import std;
import Catcrafts.Shared;
import Catcrafts.Server;
using namespace Catcrafts;
using Server::BankCredit;
namespace {
int failures = 0;
void Check(bool ok, std::string_view what, std::string_view got = {}) {
if (ok) return;
++failures;
std::println(std::cerr, "FAIL: {}{}{}", what,
got.empty() ? "" : " got: ", got);
}
BankCredit Credit(std::string reference, std::int64_t amountMinor,
std::string method = "sepa", std::string id = "p1") {
BankCredit c;
c.id = std::move(id);
c.reference = std::move(reference);
c.amountMinor = amountMinor;
c.method = std::move(method);
return c;
}
// The braced lists below land in a vector on purpose. MatchCredits takes a
// span, and the libc++ 23 inside the Crafter.Build 2.1.0 Flatpak (what CI
// builds with) has no span(initializer_list) constructor; libc++ 22 had one
// under C++26, which is the only reason the lists ever compiled.
Server::TransferMatch Match(std::vector<BankCredit> credits, std::string_view reference) {
return Server::MatchCredits(credits, reference);
}
std::int64_t PaidFor(std::vector<BankCredit> credits, std::string_view reference) {
return Match(std::move(credits), reference).paidMinor;
}
// ── the rail itself, without a server around it ───────────────────────
//
// MatchCredits is pure; what it is given is not. The rail keeps the claims in
// a file, reads them back when it starts, and writes one before it reports an
// order paid. Those three are where "a payment is spent once" can fail while
// every check on the matcher still passes, so they are driven here through
// the rail's own interface: a fixed list of credits standing in for the
// bank, a scratch directory standing in for /var/lib/catcrafts, and a NEW
// rail object wherever production would have restarted.
namespace fs = std::filesystem;
class FixedCredits final : public Server::CreditSource {
public:
explicit FixedCredits(std::vector<BankCredit> credits) : credits_(std::move(credits)) {}
std::optional<std::vector<BankCredit>> Recent() override { return credits_; }
std::string_view Name() const override { return "fixed"; }
private:
std::vector<BankCredit> credits_;
};
std::unique_ptr<Server::PaymentRail> Rail(const fs::path& creditsPath,
std::vector<BankCredit> credits) {
Server::RailConfig cfg;
cfg.mode = "transfer";
cfg.transferIban = "NL00TEST0123456789";
cfg.transferBeneficiary = "Not a real account";
cfg.transferCreditsPath = creditsPath;
cfg.transferPollSeconds = 1;
return Server::MakeTransferRail(cfg, std::make_unique<FixedCredits>(std::move(credits)));
}
// Whether the rail reports the order with this reference paid. The deadline
// in the id is far in the future, so an unpaid order reads as pending here
// and never as lapsed.
bool Settles(Server::PaymentRail& rail, std::string_view reference, std::int64_t minor) {
const auto status = rail.CheckPaid(std::format("{}@4102444800", reference), minor);
return status && status->state == Server::PayState::Paid;
}
std::string Slurp(const fs::path& p) {
std::ifstream in(p, std::ios::binary);
return std::string(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
}
void TheRailRemembersWhatWasSpent(const fs::path& work) {
const std::vector<BankCredit> oneForTwo = {
Credit("CC-AAAAAA CC-BBBBBB", 500, "sepa", "pay-1") };
// Across a restart. The first rail settles one order and is destroyed;
// the second is what a deploy leaves running, with nothing in memory.
// The same credit is still in the file the bank fills, naming the other
// order, and it must stay spent.
{
const fs::path credits = work / "restart.jsonl";
{
auto rail = Rail(credits, oneForTwo);
Check(rail != nullptr, "rail: it starts with no claims file at all");
if (!rail) return;
Check(Settles(*rail, "CC-AAAAAA", 500), "rail: the first order settles");
Check(!Settles(*rail, "CC-BBBBBB", 500),
"rail: the same payment does not settle the second");
}
auto again = Rail(credits, oneForTwo);
Check(again != nullptr, "rail: it starts again on the claims it wrote");
if (!again) return;
Check(!Settles(*again, "CC-BBBBBB", 500),
"rail: after a restart the payment is still spent");
Check(Settles(*again, "CC-AAAAAA", 500),
"rail: and the order it was spent on still finds it");
const std::string claims = Slurp(fs::path(credits.string() + ".claims"));
Check(std::ranges::count(claims, '\n') == 1,
"rail: settling the same order again writes no second claim", claims);
}
// A claims file that stops mid-line: a write cut short by a full disk, or
// a crash. The next claim used to be written straight onto the end of the
// broken line, where the next start could not read it, and the payment
// was free to settle a second order one restart later (found in review,
// reproduced end to end).
{
const fs::path credits = work / "torn.jsonl";
const fs::path claimsFile(credits.string() + ".claims");
{
std::ofstream out(claimsFile, std::ios::binary);
out << R"({"credit":"earlier-payment","refer)"; // and no line break
}
{
auto rail = Rail(credits, oneForTwo);
Check(rail != nullptr, "torn: the rail starts on a claims file cut short");
if (!rail) return;
Check(Settles(*rail, "CC-AAAAAA", 500), "torn: an order settles");
}
auto again = Rail(credits, oneForTwo);
if (!again) return;
Check(!Settles(*again, "CC-BBBBBB", 500),
"torn: the claim written after a broken line survives the restart",
Slurp(claimsFile));
}
// A claims file that is there and cannot be read is a rail that cannot
// know what was spent. It must not run and treat every payment as fresh.
// A directory in the file's place stands in for "unreadable" here: file
// permissions would not stop this suite when it runs as root, as in CI.
{
const fs::path credits = work / "unreadable.jsonl";
fs::create_directories(fs::path(credits.string() + ".claims"));
Check(Rail(credits, oneForTwo) == nullptr,
"rail: it refuses to start on a claims file it cannot read");
}
// One payment listed twice. Not meant to happen and reproduced in review
// all the same (one callback delivered on two connections at once). A
// payer who sent half the price must not find the order settled by it.
{
const fs::path credits = work / "twice.jsonl";
auto rail = Rail(credits, {
Credit("CC-CCCCCC", 500, "sepa", "pay-7"),
Credit("CC-CCCCCC", 500, "sepa", "pay-7") });
if (!rail) return;
Check(!Settles(*rail, "CC-CCCCCC", 1000),
"rail: half the price listed twice does not settle the order");
Check(Settles(*rail, "CC-CCCCCC", 500),
"rail: and still pays for what it is worth");
}
}
} // namespace
int main() {
const std::string ref = "CC-2B6457";
// ── the forms a payer actually quotes ─────────────────────────────
Check(PaidFor({ Credit("CC-2B6457 catcrafts.net", 5000) }, ref) == 5000,
"the reference exactly as we printed it");
Check(PaidFor({ Credit("cc2b6457", 5000) }, ref) == 5000,
"lower case and no hyphen");
Check(PaidFor({ Credit("RF70CC2B6457", 5000) }, ref) == 5000,
"the structured RF form, whose body IS the reference");
Check(PaidFor({ Credit("CC 2B 64 57", 5000) }, ref) == 5000,
"a bank grouping the field into pairs");
Check(PaidFor({ Credit("Payment for order CC-2B6457, thanks!", 5000) }, ref) == 5000,
"the reference buried in a sentence");
Check(PaidFor({ Credit("betaling cc/2b/6457", 5000) }, ref) == 5000,
"separators a payer invented");
// ── refusing to over-match ────────────────────────────────────────
Check(PaidFor({ Credit("CC-2B6458", 5000) }, ref) == 0,
"one character different is a different order");
Check(PaidFor({ Credit("no reference at all", 5000) }, ref) == 0,
"a transfer with no reference pays for nothing");
Check(PaidFor({ Credit("", 5000) }, ref) == 0,
"an empty remittance field pays for nothing");
// The needle guard: an empty or near-empty reference must not match every
// credit on the account. This is the difference between one order settling
// and the whole ledger settling from a single payment.
Check(PaidFor({ Credit("anything", 5000), Credit("something", 900) }, "") == 0,
"an empty reference matches nothing");
Check(PaidFor({ Credit("anything", 5000) }, "CC") == 0,
"a too-short reference matches nothing");
// Outgoing money must never pay for an order. A refund we sent quotes the
// very reference of the order it refunds, so counting signed amounts
// blindly would let a refund settle the thing it reversed.
Check(PaidFor({ Credit("CC-2B6457 refund", -5000) }, ref) == 0,
"an outgoing payment quoting the reference is not income");
Check(PaidFor({ Credit("CC-2B6457", 5000), Credit("CC-2B6457 refund", -2000) },
ref) == 5000,
"a later refund does not reduce what arrived");
// ── partials accumulate ───────────────────────────────────────────
// The buyer is told to send the difference to the same IBAN with the same
// reference, so two credits for one order is a supported path and not an
// anomaly. Summing is what makes that instruction true.
Check(PaidFor({ Credit("CC-2B6457", 3000, "sepa", "a"),
Credit("CC-2B6457", 2000, "sepa", "b") }, ref) == 5000,
"two credits for one order are summed");
{
const Server::TransferMatch m = Match(
{ Credit("CC-2B6457", 3000, "sepa", "a"),
Credit("CC-2B6457", 2000, "sepa", "b") }, ref);
Check(m.count == 2, "the count reports how many credits carried it",
std::format("{}", m.count));
}
// ── the method reaches the ledger ─────────────────────────────────
// The `via` column decides whether an order is safe to ship: a plain SEPA
// transfer is final, and anything with a dispute window is not.
{
const Server::TransferMatch m =
Match({ Credit("CC-2B6457", 5000, "ideal") }, ref);
Check(m.method == "ideal", "the settling method is carried out", m.method);
}
// ── other orders' money is left alone ────────────────────────────
Check(PaidFor({ Credit("CC-AAAAAA", 90000), Credit("CC-2B6457", 5000),
Credit("CC-BBBBBB", 12345) }, ref) == 5000,
"only the credits quoting THIS reference are counted");
// ── the ambiguity tripwire ───────────────────────────────────────
// One transfer quoting two orders cannot be attributed by a per-order
// matcher: both orders see the full amount. The flag is advisory and
// decides nothing (a reference shape is also what a name followed by a
// date looks like); it is there so the log can point at the settlement.
// What keeps both orders from settling on the same money is the next
// section.
{
const Server::TransferMatch m =
Match({ Credit("CC-2B6457 and CC-AAAAAA", 10000) }, ref);
Check(m.ambiguous,
"a credit quoting a second order reference is flagged ambiguous");
const Server::TransferMatch clean =
Match({ Credit("CC-2B6457 thanks", 10000) }, ref);
Check(!clean.ambiguous, "an ordinary credit is not flagged");
}
// ── money is spent once ──────────────────────────────────────────
//
// The trick this closes: place three orders, then send ONE transfer whose
// text names all three. Each order looks for its own reference, finds it,
// and sees the full amount, so with nothing recording that the money was
// used, all three settle on a single payment. The flag above cannot stop
// that (it is a guess about text a stranger wrote). The claim does: a
// payment that settled one order pays for no other.
{
const std::vector<BankCredit> credits = {
Credit("CC-2B6457 CC-AAAAAA CC-BBBBBB", 5000, "sepa", "pay-1") };
// Unspent, every order it names sees the money. That much is right:
// which of them it pays for is decided by which settles first.
const Server::TransferMatch first = Server::MatchCredits(credits, ref);
Check(first.paidMinor == 5000, "an unspent payment counts for an order it names");
Check(Server::MatchCredits(credits, "CC-AAAAAA").paidMinor == 5000,
"and, until one of them settles, for the others it names too");
Check(first.credits == std::vector<std::string>{ "pay-1" },
"the match names the payment to claim, by the bank's id");
Check(first.spentElsewhere == 0, "nothing is reported spent before a claim");
const std::vector<Server::CreditClaim> claims = { { "pay-1", "CC-2B6457" } };
const Server::TransferMatch other =
Server::MatchCredits(credits, "CC-AAAAAA", claims);
Check(other.paidMinor == 0 && other.count == 0,
"a payment that settled one order pays for no other",
std::format("{}", other.paidMinor));
Check(other.spentElsewhere == 1,
"and the match says the money was there and is spent");
Check(other.credits.empty(), "a spent payment is not offered for a second claim");
Check(Server::MatchCredits(credits, "CC-BBBBBB", claims).paidMinor == 0,
"nor for a third order");
// The order that holds the claim must still find its own money: a
// settlement that was claimed and then never reached the ledger is
// completed from exactly this.
const Server::TransferMatch own = Server::MatchCredits(credits, ref, claims);
Check(own.paidMinor == 5000 && own.spentElsewhere == 0,
"the order that claimed a payment still counts it");
const std::vector<Server::CreditClaim> spelled = { { "pay-1", "cc 2b6457" } };
Check(Server::MatchCredits(credits, ref, spelled).paidMinor == 5000,
"however the claim spells that order's reference");
Check(Server::MatchCredits(credits, "CC-AAAAAA", spelled).paidMinor == 0,
"and it still shuts the other orders out");
}
// A claim is on ONE PAYMENT, not on a reference. Another payment for the
// same order is untouched by it, which is what keeps "send the rest the
// same way" true for an order that shared its first transfer.
{
const std::vector<BankCredit> credits = {
Credit("CC-AAAAAA and CC-2B6457", 3000, "sepa", "pay-1"),
Credit("CC-AAAAAA", 2000, "ideal", "pay-2") };
const std::vector<Server::CreditClaim> claims = { { "pay-1", "CC-2B6457" } };
const Server::TransferMatch m =
Server::MatchCredits(credits, "CC-AAAAAA", claims);
Check(m.paidMinor == 2000 && m.count == 1,
"only the spent payment is left out of the sum",
std::format("{} in {}", m.paidMinor, m.count));
Check(m.spentElsewhere == 1, "the spent one is counted as spent");
Check(m.credits == std::vector<std::string>{ "pay-2" },
"only the payment still unspent is offered for a claim");
Check(m.method == "ideal", "the method is that of a payment that counted", m.method);
}
// A claim for a payment the account no longer shows changes nothing: the
// pull replaces the credits file every hour and old payments leave it.
{
const std::vector<BankCredit> credits = {
Credit("CC-2B6457", 5000, "sepa", "pay-9") };
const std::vector<Server::CreditClaim> claims = { { "long-gone", "CC-ZZZZZZ" } };
Check(Server::MatchCredits(credits, ref, claims).paidMinor == 5000,
"a claim on some other payment does not touch this one");
}
// A line written by hand may carry no id. It is still one payment, and
// has to be claimable like one, or the hand-written escape hatch would be
// the one place the old trick still worked.
{
const std::vector<BankCredit> credits = {
Credit("CC-2B6457 CC-AAAAAA", 5000, "sepa", "") };
const Server::TransferMatch first = Server::MatchCredits(credits, ref);
Check(first.credits.size() == 1 && !first.credits[0].empty(),
"a credit with no id still has a key to be claimed under");
if (first.credits.size() == 1) {
const std::vector<Server::CreditClaim> claims = {
{ first.credits[0], "CC-2B6457" } };
Check(Server::MatchCredits(credits, "CC-AAAAAA", claims).paidMinor == 0,
"and is spent once like any other");
Check(Server::MatchCredits(credits, ref, claims).paidMinor == 5000,
"while its own order still counts it");
}
}
// ── one payment is counted once ──────────────────────────────────
//
// Two lines with the same bank id are one payment. Summed, they double
// the money against the reference, which settles a half-paid order.
{
const Server::TransferMatch twice = Match(
{ Credit("CC-2B6457", 2500, "sepa", "pay-1"),
Credit("CC-2B6457", 2500, "sepa", "pay-1") }, ref);
Check(twice.paidMinor == 2500 && twice.count == 1,
"a payment listed twice is counted once",
std::format("{} in {}", twice.paidMinor, twice.count));
Check(twice.duplicates == 1, "and the second line is reported as a duplicate");
Check(twice.credits == std::vector<std::string>{ "pay-1" },
"it is still one payment to claim");
// Different ids are different payments, however alike they look:
// this is the top-up the order page asks for.
Check(PaidFor({ Credit("CC-2B6457", 2500, "sepa", "pay-1"),
Credit("CC-2B6457", 2500, "sepa", "pay-2") }, ref) == 5000,
"two payments of the same amount are both counted");
// And with no id there is nothing to tell two lines apart by, so a
// hand-written pair is taken as two payments, as it always was.
Check(PaidFor({ Credit("CC-2B6457", 2500, "sepa", ""),
Credit("CC-2B6457", 2500, "sepa", "") }, ref) == 5000,
"two lines without an id are each counted");
}
// ── the rail: claims on disk, across restarts ────────────────────
{
std::error_code ec;
const fs::path work = fs::temp_directory_path(ec)
/ std::format("catcrafts-transfer-{}", Server::NewOrderToken());
fs::create_directories(work, ec);
if (ec) {
std::println(std::cerr, "could not create {}: {}", work.string(), ec.message());
return 1;
}
TheRailRemembersWhatWasSpent(work);
fs::remove_all(work, ec);
}
// An empty account is a clean zero rather than anything alarming: it is
// simply the state of every order between checkout and payment.
Check(PaidFor({}, ref) == 0, "no credits at all is zero, not an error");
if (failures != 0) {
std::println(std::cerr, "{} check(s) failed", failures);
return 1;
}
std::println("ShouldMatchBankTransfers: all checks passed");
return 0;
}