diff --git a/deploy/README.md b/deploy/README.md index c39072a..ebd728a 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -510,6 +510,45 @@ key after the home address changed), the pull fails and its unit says so, but nothing tells the shop. Settlement then rests on the webhook alone, so a failing `catcrafts-credits` unit is worth noticing. +#### The callback shadow (temporary, since 2026-11-25) + +The webhook's parser (`ParseBunqCallback`) is to be replaced by Nostro's +`ReadCallback`, so that this repo stops carrying bunq's wire format. That +reader is stricter than ours and had never been run on a callback bunq really +sent, while ours has settled real payments since 2026-08. So for now both run: +ours decides exactly as before, and Nostro's reads the same body afterwards and +logs what it made of it. It cannot change the answer or the credit, and it +turns on by itself wherever `BUNQ_WEBHOOK_PATH` is set. + +Read the result on the server, after any payment in or out of the account: + +```sh +journalctl -u catcrafts-server | grep 'bank callback shadow' +``` + +- `AGREE in method=sepa account=ours event=transactions`: both readers read + the same id, amount and reference. This line on a real incoming transfer is + what the test is for. +- `AGREE … method ours=MASTERCARD nostro=card …`: still agreement. Only the + name for how the money arrived differs, which is expected for card payments. +- `account=other`: the payment is on another account than `TRANSFER_IBAN`. Our + parser never looked at that, and the replacement must. +- `DIFFER nostro refused what ours reads as a payment: `: Nostro's + reader would have dropped a payment ours credited. The sentence names the + check that failed, and that is a fix for Nostro, not for this repo. +- `DIFFER id=… amount=… reference=…`: both read a payment and not the same one. + +The line carries no payment data: no id, no amount, no name and no reference. +`ShouldCompareCallbackReaders` pins the verdicts and +`ShouldReceiveBankCallbacks` the endpoint, including that a payment Nostro's +reader refuses is credited all the same. + +When real payments read `AGREE`, the reader takes over, and the shadow goes +together with `ParseBunqCallback` +(`server/implementations/Catcrafts.Server-CallbackShadow.cpp` and its call in +`Catcrafts.Server-Http.cpp`). Nostro's module is built in through +`project.cpp`, named at the commit of its 1.1.0 release. + #### The old reader: `--pull-credits` `catcrafts-server --pull-credits` is this repo's own bunq client. It onboards diff --git a/project.cpp b/project.cpp index df9ebab..8f7293c 100644 --- a/project.cpp +++ b/project.cpp @@ -94,7 +94,7 @@ static Configuration* SharedLibrary(std::span args) { // Same `static unique_ptr` convention as SharedLibrary, and the same warning: // cfg.dependencies holds a raw pointer, so the Configuration must outlive // CrafterBuildProject. -static Configuration* ServerCore(std::span args, Configuration* network) { +static Configuration* ServerCore(std::span args, Configuration* network, Configuration* money) { static auto core = std::make_unique(); // Same idempotence rule as SharedLibrary — see the warning there. if (!core->name.empty()) return core.get(); @@ -103,12 +103,12 @@ static Configuration* ServerCore(std::span args, Configu core->outputName = "Catcrafts.ServerCore"; ApplyStandardArgs(*core, args); core->type = ConfigurationType::LibraryStatic; - core->dependencies = { SharedLibrary(args), network }; + core->dependencies = { SharedLibrary(args), network, money }; std::array ifaces = { "server/interfaces/Catcrafts.Server", }; - std::array impls = { + std::array impls = { "server/implementations/Catcrafts.Server-Http", "server/implementations/Catcrafts.Server-Orders", "server/implementations/Catcrafts.Server-Rails", @@ -116,6 +116,7 @@ static Configuration* ServerCore(std::span args, Configu "server/implementations/Catcrafts.Server-Eurc", "server/implementations/Catcrafts.Server-Transfer", "server/implementations/Catcrafts.Server-Bunq", + "server/implementations/Catcrafts.Server-CallbackShadow", "server/implementations/Catcrafts.Server-Shipping", "server/implementations/Catcrafts.Server-Mail", "server/implementations/Catcrafts.Server-Financials", @@ -179,7 +180,33 @@ extern "C" Configuration CrafterBuildProject(std::span a .args = netArgs, }); - Configuration* core = ServerCore(args, network); + // Nostro.Money: the part of Nostro (the bank library this shop's own + // bunq code is being replaced by) that reads what a bank posts to a + // callback's address. `--product=money` is that module alone: it holds + // no credential and brings no Crafter.Network, Crafter.DB or OpenSSL + // of its own, which is why it can sit in this server at all. Nostro's + // full library pins Crafter.Network at a commit and without QUIC, and + // loading it here would stop the build on two builds of one module. + // + // Named at the commit of the 1.1.0 release, not at a branch. This is + // code that reads claims about money, so what is built is what was + // read, and moving it forward is a change to this line. + // + // Its args are this build's own minus `--product=`: Nostro reads that + // flag too, and `server` is no product of its. + std::vector moneyArgs; + for (std::string_view a : args) { + if (!a.starts_with("--product=")) moneyArgs.emplace_back(a); + } + moneyArgs.emplace_back("--product=money"); + moneyArgs.emplace_back("--banks=bunq"); + Configuration* money = GitProject({ + .source = { .url = "https://forgejo.catcrafts.net/Catcrafts/Nostro.git", + .commit = "5d02cc6b96d43092204e8c32fb46bc0e98192945" }, + .args = moneyArgs, + }); + + Configuration* core = ServerCore(args, network, money); Configuration* shared = SharedLibrary(args); Configuration cfg; @@ -236,6 +263,7 @@ extern "C" Configuration CrafterBuildProject(std::span a cfg.AddTest("ShouldIssueEurcAddresses").Dependencies({ core, shared }); cfg.AddTest("ShouldMatchBankTransfers").Dependencies({ core, shared }); cfg.AddTest("ShouldParseBunqPayments").Dependencies({ core, shared }); + cfg.AddTest("ShouldCompareCallbackReaders").Dependencies({ core, shared }); // ── black-box suites (the tools/e2e.sh port) ────────────────── // Each spawns the REAL binary — depending on &cfg is what builds it @@ -284,6 +312,16 @@ extern "C" Configuration CrafterBuildProject(std::span a .Dependencies({ &cfg, shared, network }).Args({ serverBin }) .Timeout(std::chrono::seconds(180)); + // The callback endpoint itself, over real HTTP: what the bank posts is + // credited by our own parser exactly as before, an order settles from + // it, and the shadow run of Nostro's reader beside it says what it + // made of the same body without being able to change any of that. + // No secret and no network, like the suite above. It waits out the + // reconciler once. + cfg.AddTest("ShouldReceiveBankCallbacks", harness) + .Dependencies({ &cfg, shared, network }).Args({ serverBin }) + .Timeout(std::chrono::seconds(180)); + // ── live-provider suite ─────────────────────────────────────── // The EURC rail settling an actual on-chain transfer on a testnet: a // MANDATORY deploy gate in CI (the workflow supplies diff --git a/server/implementations/Catcrafts.Server-CallbackShadow.cpp b/server/implementations/Catcrafts.Server-CallbackShadow.cpp new file mode 100644 index 0000000..1e16859 --- /dev/null +++ b/server/implementations/Catcrafts.Server-CallbackShadow.cpp @@ -0,0 +1,179 @@ +/* +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. +*/ + +// The callback shadow: what Nostro's reader makes of a bank callback, set +// beside what this shop's own parser made of it. TEMPORARY, and it decides +// nothing. The interface (ShadowCallbackVerdict) says why it exists and when +// it goes. +// +// This is the one unit that imports Nostro.Money. Everything it takes from +// there is read here and turned into this shop's own words before it leaves, +// so nothing else in the server knows the module is there. +// +// The rule every line below is written to: NOTHING OF THE BODY COMES OUT. The +// verdict is built from fixed words, from whether two values are equal, and +// from the few words a bank has for a category or a type of payment, each +// checked to be such a word before it is printed. An id, an amount, a name, an +// IBAN or a description is compared and never quoted. + +module; +module Catcrafts.Server; + +import std; +import Catcrafts.Shared; +import Nostro.Money; + +namespace Catcrafts::Server { + +namespace { + +// A word that is safe to print whoever wrote the body: letters, digits and +// the three marks a bank's own word or ours is made with, and not many of +// them. Anything else is not printed at all. Nostro already holds a bank's +// category to capitals, digits and underscores; this does not lean on that. +std::string Word(std::string_view s) { + constexpr std::size_t most = 48; + if (s.empty() || s.size() > most) return "?"; + for (const char c : s) { + const bool plain = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') + || (c >= '0' && c <= '9') || c == '_' || c == ':' + || c == '-'; + if (!plain) return "?"; + } + return std::string(s); +} + +// The sentence Nostro refused a body with. By its contract that sentence is +// Nostro's own and holds nothing of the body, which is what makes it the one +// piece of text here that is passed on. Still held to printable ASCII and a +// length, so a contract that was broken cannot put a control character or a +// page of text into the journal. +std::string Sentence(std::string_view s) { + constexpr std::size_t most = 200; + std::string out; + out.reserve(std::min(s.size(), most)); + for (const char c : s.substr(0, most)) { + out += (c >= 0x20 && c < 0x7F) ? c : '?'; + } + return out; +} + +// IBANs compared as the rest of the server compares them: spacing and case +// are how a person wrote one down, not part of it. +std::string FoldIban(std::string_view s) { + std::string out; + out.reserve(s.size()); + for (const char c : s) { + if (c == ' ' || c == '\t') continue; + out += static_cast(c >= 'a' && c <= 'z' ? c - 'a' + 'A' : c); + } + return out; +} + +// Nostro's answer to how a payment arrived, in the ledger's `via` words, so +// it can be set beside what BunqMethodFor said. Empty for Unknown: the caller +// then falls back to the bank's own word, as BunqMethodFor does. +std::string_view ViaOf(Nostro::PaymentMethod method) { + switch (method) { + case Nostro::PaymentMethod::CreditTransfer: return "sepa"; + case Nostro::PaymentMethod::DirectDebit: return "directdebit"; + case Nostro::PaymentMethod::Card: return "card"; + case Nostro::PaymentMethod::Ideal: return "ideal"; + case Nostro::PaymentMethod::Internal: return "bunq"; + case Nostro::PaymentMethod::Swift: return "swift"; + case Nostro::PaymentMethod::Unknown: break; + } + return {}; +} + +// The `via` word Nostro's reading leads to for a payment of this kind. +std::string NostroVia(std::string_view bank, std::string_view kind) { + Nostro::PaymentMethod method = Nostro::PaymentMethod::Unknown; + try { + method = Nostro::PaymentMethodOf(bank, kind); + } catch (...) { + return "?"; + } + if (const std::string_view via = ViaOf(method); !via.empty()) { + return std::string(via); + } + // A kind Nostro's table has not. A kind is "/", and the + // type alone is what BunqMethodFor passes through for one IT does not + // know, with "bank" where the bank sent none. + const std::string_view type = kind.substr(0, kind.find('/')); + return type.empty() ? std::string("bank") : std::string(type); +} + +std::string_view Same(bool same) { return same ? "same" : "DIFFERENT"; } + +} // namespace + +std::string ShadowCallbackVerdict(std::string_view bank, std::string_view body, + const std::optional& ours, + std::string_view ownIban) { + try { + Nostro::CallbackEvent event; + try { + event = Nostro::ReadCallback(bank, body); + } catch (const std::runtime_error& e) { + // What Nostro promises to throw, and the only thing whose words + // are passed on. + const std::string why = Sentence(e.what()); + return ours + ? std::format("DIFFER nostro refused what ours reads as a payment: {}", why) + : std::format("AGREE neither reads a payment (nostro: {})", why); + } catch (...) { + // Anything else is not in its contract, and its words could be + // the body's: a JSON library quotes what it choked on. + return "DIFFER nostro threw something other than it promises"; + } + + const std::string eventWord = Word(event.event); + if (!event.transaction) { + return ours + ? std::format("DIFFER nostro reads no payment in it (event={}), ours does", + eventWord) + : std::format("AGREE no payment in it (event={})", eventWord); + } + + const Nostro::Transaction& theirs = *event.transaction; + const std::string_view direction = + theirs.amount > 0 ? "in" : theirs.amount < 0 ? "out" : "zero"; + const std::string_view account = + ownIban.empty() ? "unknown" + : FoldIban(event.account) == FoldIban(ownIban) ? "ours" : "other"; + + if (!ours) { + return std::format( + "DIFFER nostro reads a payment, ours does not ({} account={} event={})", + direction, account, eventWord); + } + + const std::string theirVia = NostroVia(bank, theirs.kind); + const std::string method = theirVia == ours->method + ? std::format("method={}", Word(theirVia)) + : std::format("method ours={} nostro={}", Word(ours->method), Word(theirVia)); + const std::string rest = std::format("{} {} account={} event={}", direction, + method, account, eventWord); + + const bool sameId = theirs.id == ours->id; + const bool sameAmount = theirs.amount == ours->amountMinor; + const bool sameReference = theirs.description == ours->reference; + if (sameId && sameAmount && sameReference) { + return std::format("AGREE {}", rest); + } + return std::format("DIFFER id={} amount={} reference={} {}", Same(sameId), + Same(sameAmount), Same(sameReference), rest); + } catch (...) { + // Out of memory while building a line, in practice. The comparison + // must never be the thing that fails a callback. + return "FAILED the comparison itself threw"; + } +} + +} // namespace Catcrafts::Server diff --git a/server/implementations/Catcrafts.Server-Http.cpp b/server/implementations/Catcrafts.Server-Http.cpp index 34f7184..47baa03 100644 --- a/server/implementations/Catcrafts.Server-Http.cpp +++ b/server/implementations/Catcrafts.Server-Http.cpp @@ -82,6 +82,11 @@ std::string gRedirectBase = "https://catcrafts.net"; std::filesystem::path gCreditsPath; std::string gWebhookPath; +// The callback shadow (temporary, see ShadowCallbackVerdict): off until +// ConfigureCallbackShadow says which account is the shop's own. +bool gCallbackShadow = false; +std::string gShadowIban; + // The bank-derived aggregates for /financials live in Catcrafts.Server- // Financials.cpp, which owns their file. They are read through // CurrentFinancials() per request rather than cached: unlike the content @@ -703,6 +708,32 @@ HTTPResponse HandleBunqCallback(const HTTPRequest& req) { return res; } +// The shadow run (temporary, see ShadowCallbackVerdict): what Nostro's reader +// makes of the body HandleBunqCallback has just dealt with, logged beside what +// ours made of it. +// +// It is called AFTER the handler has returned its answer and written its +// credit, on purpose. The handler above is not touched by it and cannot be +// changed by it: the body is parsed a second time here rather than handed +// over, so that the code which settles money stays exactly the code that has +// been settling it. If this ever took the process down, the credit would be on +// disk already, and the bank's retry of a callback it got no answer to is +// refused as a duplicate by the id. +void ShadowBunqCallback(const HTTPRequest& req) { + if (!gCallbackShadow) return; + try { + const std::optional ours = ParseBunqCallback(req.body); + std::println(std::cerr, "bank callback shadow: {}", + ShadowCallbackVerdict("bunq", req.body, ours, gShadowIban)); + } catch (...) { + // Nothing here may fail a callback that was already answered. + try { + std::println(std::cerr, "bank callback shadow: FAILED before a verdict"); + } catch (...) { + } + } +} + HTTPResponse HandleCheckout(const HTTPRequest& req, const Route& route) { HTTPResponse res; @@ -1153,6 +1184,17 @@ void ConfigureBunqCallback(std::filesystem::path creditsPath, std::string secret gWebhookPath.size()); } +void ConfigureCallbackShadow(std::string ownIban) { + gShadowIban = std::move(ownIban); + gCallbackShadow = true; + // The account is not printed: whether one was named is what a reader of + // the log needs, to know what "account=unknown" on a verdict means. + std::println(std::cerr, + "bank callback shadow: on, Nostro's reader runs beside ours and " + "decides nothing (own account {})", + gShadowIban.empty() ? "not named" : "named"); +} + bool CryptoPaymentAvailable() { return gRails.crypto != nullptr; } bool BankPaymentAvailable() { return gRails.bank != nullptr; } @@ -1391,7 +1433,14 @@ int Serve(std::uint16_t port) { for (std::size_t i = 0; i < path.size(); ++i) { diff |= static_cast(path[i] ^ gWebhookPath[i]); } - if (diff == 0) return HandleBunqCallback(req); + if (diff == 0) { + // Ours decides, and has finished deciding, before the + // shadow looks at the same body. The answer is already + // made and is returned as it is. + HTTPResponse answer = HandleBunqCallback(req); + ShadowBunqCallback(req); + return answer; + } } } // A POST to a product page is a checkout submission. diff --git a/server/implementations/main.cpp b/server/implementations/main.cpp index b639e4a..2c02f73 100644 --- a/server/implementations/main.cpp +++ b/server/implementations/main.cpp @@ -446,6 +446,13 @@ int main(int argc, char** argv) { // is configured. if (const char* v = std::getenv("BUNQ_WEBHOOK_PATH"); v && *v) { Server::ConfigureBunqCallback(transferCreditsPath, v); + // The shadow run of Nostro's callback reader beside ours + // (temporary, see ShadowCallbackVerdict). It needs no setting of + // its own, so the test starts with the deploy that carries it, and + // it decides nothing. TRANSFER_IBAN is the account it reports a + // payment as being on or not on. + const char* iban = std::getenv("TRANSFER_IBAN"); + Server::ConfigureCallbackShadow(iban ? iban : ""); } // Invoice signing: the GPG key uid/fingerprint; GNUPGHOME decides the diff --git a/server/interfaces/Catcrafts.Server.cppm b/server/interfaces/Catcrafts.Server.cppm index f1a7601..e6b4948 100644 --- a/server/interfaces/Catcrafts.Server.cppm +++ b/server/interfaces/Catcrafts.Server.cppm @@ -639,6 +639,54 @@ export namespace Catcrafts::Server { void ConfigureBunqCallback(std::filesystem::path creditsPath, std::string secretPath); + // ── the callback shadow (temporary, since 2026-11-25) ───────────── + // + // A second reading of every bank callback, by Nostro's ReadCallback (the + // module Nostro.Money of https://forgejo.catcrafts.net/Catcrafts/Nostro, + // at its 1.1.0 release), set beside what ParseBunqCallback made of the + // same body. It decides NOTHING: the handler has answered and written its + // credit before this runs, and all that comes out is one log line. + // + // Why it exists: ParseBunqCallback is to be replaced by that reader, so + // that this repo stops carrying bunq's wire format. The reader is + // stricter. It wants a time, a counterparty and the account's own IBAN + // where ours reads four members, and when this was written nobody had run + // it on a callback bunq really sent: its shape came from a sample in + // bunq's SDK dated 2017. Ours has settled real payments since 2026-08. So + // the two run side by side until the log shows the reader agreeing on + // real payments. Then it takes over, and this goes together with + // ParseBunqCallback. + // + // The line carries no payment data, on purpose: no id, no amount, no name + // and no reference, only whether the two readings match and a few fixed + // words. A callback's body holds the payer's name and IBAN, which the + // privacy notice says this shop does not copy out of the bank, and it may + // repeat the address it was sent to, which is a secret. + // + // AGREE in method=sepa account=ours event=transactions + // AGREE out method ours=MASTERCARD nostro=card account=other event=transactions + // DIFFER nostro refused what ours reads as a payment: + // DIFFER id=same amount=DIFFERENT reference=same in method=sepa … + // + // AGREE means the id, the amount and the reference are the same, which is + // everything settlement rests on. The method is reported beside it and is + // allowed to differ: Nostro calls bunq's MASTERCARD a card payment, where + // ours passes a type it does not know through as bunq wrote it. `account` + // says whether the payment is on `ownIban`, which ours never looked at. + // + // `ours` is what ParseBunqCallback made of the same body, `bank` what a + // Nostro connector to the bank is called ("bunq"), and `ownIban` the + // account the shop is paid into; empty reports the account as unknown. + // Whatever the reading or the comparison throws is caught and becomes the + // verdict, in words that are not the body's. + std::string ShadowCallbackVerdict(std::string_view bank, std::string_view body, + const std::optional& ours, + std::string_view ownIban); + + // Turn the shadow on for the callback endpoint, naming the shop's own + // account. Without this call the endpoint behaves exactly as it did. + void ConfigureCallbackShadow(std::string ownIban); + // One pull: read the account and append every credit not already in the // file to it, newest last. Returns the number appended, or nullopt if the // bank could not be reached. This is what `--pull-credits` runs, and it is diff --git a/tests/ShouldCompareCallbackReaders/main.cpp b/tests/ShouldCompareCallbackReaders/main.cpp new file mode 100644 index 0000000..08f2036 --- /dev/null +++ b/tests/ShouldCompareCallbackReaders/main.cpp @@ -0,0 +1,269 @@ +/* +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. +*/ + +// The callback shadow's verdict: what Nostro's reader makes of a bank callback +// beside what our own parser made of it (ShadowCallbackVerdict). Temporary, +// like the shadow itself. +// +// Three things are held here, and the third is the one that must not regress: +// +// * AGREE is said when, and only when, the id, the amount and the reference +// are the same in both readings. Those are what settlement rests on. +// * Each way the two can part is said in words that tell them apart: Nostro +// refusing a body ours reads, reading none where ours does, reading one +// where ours does not, and reading another value. +// * NOTHING OF THE BODY COMES OUT. The verdict goes to the server's log, and +// a callback holds the payer's name and IBAN and may repeat the secret +// address it was posted to. Every verdict this suite produces is searched +// for the values its bodies carry. +// +// The bodies are made up. Their shape is bunq's own sample of a MUTATION +// callback (bunq/sdk_python, tests/assets/NotificationUrlJsons/Mutation.json), +// which is also what Nostro's reader was written against. Whether bunq still +// writes one like it is exactly what the shadow is in production to find out, +// and no suite can. + +import std; +import Catcrafts.Shared; +import Catcrafts.Server; + +using namespace Catcrafts; + +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); +} + +// Not real accounts, and not the shop's: see ShouldSettleBankTransfers. +constexpr std::string_view kOwnIban = "NL00TEST0123456789"; +constexpr std::string_view kOtherIban = "NL00OTHR0000000002"; + +// Every value below that a verdict must never repeat. +constexpr std::string_view kSecrets[] = { + "SECRETMARK", "CC-2B6457", "4155999", "570", "24.95", "NL00", "Payer", + "shop.invalid", "bad type", +}; + +struct Sent { + std::string_view id = "4155999"; + std::string_view type = "EBA_SCT"; + std::string_view description = "CC-2B6457"; + std::string_view value = "570.43"; + std::string_view account = kOwnIban; // the payment's own side +}; + +// A callback as bunq's sample has one: the envelope with the address it was +// sent to, and a Payment with both sides on it. +std::string Callback(const Sent& s) { + return std::format(R"({{ + "NotificationUrl": {{ + "target_url": "https://shop.invalid/hooks/SECRETMARK", + "category": "MUTATION", + "event_type": "MUTATION_CREATED", + "object": {{"Payment": {{ + "id": {}, + "created": "2026-11-25 10:15:30.498520", + "updated": "2026-11-25 10:15:30.498520", + "monetary_account_id": 42, + "amount": {{"currency": "EUR", "value": "{}"}}, + "description": "{}", + "type": "{}", + "alias": {{"iban": "{}", "display_name": "SECRETMARK Shop", "country": "NL"}}, + "counterparty_alias": {{"iban": "NL00PAYR0000000001", + "display_name": "SECRETMARK Payer", "country": "NL"}} + }}}} + }} + }})", s.id, s.value, s.description, s.type, s.account); +} + +// The four members our own parser reads, and nothing else: the shape this +// repo's suites have always used for a callback, which Nostro's reader +// refuses for what it lacks. +constexpr std::string_view kReduced = R"({ + "NotificationUrl": { + "category": "MUTATION", + "object": {"Payment": { + "id": 4155999, + "type": "EBA_SCT", + "description": "CC-2B6457", + "amount": {"currency": "EUR", "value": "570.43"} + }} + } +})"; + +std::vector verdicts; + +// The verdict on `body`, with our own parser's reading of the same body, as +// the server calls it. +std::string Verdict(std::string_view body, std::string_view ownIban = kOwnIban, + std::string_view bank = "bunq") { + const std::optional ours = Server::ParseBunqCallback(body); + verdicts.push_back(Server::ShadowCallbackVerdict(bank, body, ours, ownIban)); + return verdicts.back(); +} + +void Equal(const std::string& got, std::string_view want, std::string_view what) { + Check(got == want, what, got); +} + +void Has(const std::string& got, std::string_view part, std::string_view what) { + Check(got.find(part) != std::string::npos, what, got); +} + +} // namespace + +int main() { + // ── the two readings agree ──────────────────────────────────────── + Equal(Verdict(Callback({})), + "AGREE in method=sepa account=ours event=transactions", + "an incoming transfer on the shop's account reads the same both ways"); + Equal(Verdict(Callback({}), "nl00 test 0123 4567 89"), + "AGREE in method=sepa account=ours event=transactions", + "the shop's IBAN is compared as a person wrote it down"); + Equal(Verdict(Callback({ .account = kOtherIban })), + "AGREE in method=sepa account=other event=transactions", + "a payment on another account is said to be on another account"); + Equal(Verdict(Callback({}), ""), + "AGREE in method=sepa account=unknown event=transactions", + "with no account named, whose it is on is not guessed"); + Equal(Verdict(Callback({ .value = "-24.95" })), + "AGREE out method=sepa account=ours event=transactions", + "money going out keeps its sign in both readings"); + + // ── the method, which may differ without the readings differing ─── + Equal(Verdict(Callback({ .type = "IDEAL" })), + "AGREE in method=ideal account=ours event=transactions", "iDEAL"); + Equal(Verdict(Callback({ .type = "BUNQ" })), + "AGREE in method=bunq account=ours event=transactions", + "between two bunq accounts"); + Equal(Verdict(Callback({ .type = "MASTERCARD", .value = "-24.95" })), + "AGREE out method ours=MASTERCARD nostro=card account=ours event=transactions", + "a card payment, which ours passes through and Nostro names, is still AGREE"); + Equal(Verdict(Callback({ .type = "ADYEN" })), + "AGREE in method=ADYEN account=ours event=transactions", + "a type neither table has is the bank's own word in both"); + Equal(Verdict(Callback({ .type = "" })), + "AGREE in method=bank account=ours event=transactions", + "no type at all is 'bank' in both"); + { + const std::string v = Verdict(Callback({ .type = "bad type!" })); + Has(v, "method=?", "a type that is no bank's word is not printed"); + Has(v, "AGREE in ", "and the readings still agree"); + } + + // ── Nostro refuses what ours reads ──────────────────────────────── + // + // The outcome the shadow is in production to rule out, or to find. + { + const std::string v = Verdict(kReduced); + Has(v, "DIFFER nostro refused what ours reads as a payment: ", + "the four members ours reads are not enough for Nostro's reader"); + } + { + const std::string v = Verdict(Callback({ .account = "" })); + Has(v, "DIFFER nostro refused what ours reads as a payment: ", + "a payment that does not say which account it is on is refused"); + Has(v, "which account", "and the refusal says that is why"); + } + { + // Past what Nostro reads at all, with a payment ours still decodes. + std::string big = Callback({}); + const std::size_t at = big.find("\"category\""); + big.insert(at, std::format("\"padding\": \"{}\", ", std::string(70000, 'x'))); + const std::string v = Verdict(big); + Has(v, "DIFFER nostro refused what ours reads as a payment: ", + "a body past Nostro's limit is refused"); + Check(v.size() < 400, "and the verdict stays one line's worth", v); + } + Has(Verdict(Callback({}), kOwnIban, "nobank"), + "DIFFER nostro refused what ours reads as a payment: ", + "a bank Nostro was not built with reads nothing"); + + // ── one reads a payment where the other reads none ──────────────── + { + // Two things under `object`: ours looks for the Payment among them, + // Nostro takes a callback to be about one thing. + std::string two(kReduced); + const std::size_t at = two.rfind("}}"); + two.insert(at + 1, R"(, "Other": {})"); + Equal(Verdict(two), + "DIFFER nostro reads no payment in it (event=transactions), ours does", + "a second object beside the payment"); + } + { + verdicts.push_back(Server::ShadowCallbackVerdict("bunq", Callback({}), + std::nullopt, kOwnIban)); + Equal(verdicts.back(), + "DIFFER nostro reads a payment, ours does not (in account=ours event=transactions)", + "a payment only Nostro reads"); + } + + // ── both read a payment, and not the same one ───────────────────── + { + const std::string body = Callback({}); + const std::optional ours = Server::ParseBunqCallback(body); + Check(ours.has_value(), "our parser reads the sample's shape"); + if (ours) { + Server::BankCredit other = *ours; + other.amountMinor += 1; + verdicts.push_back(Server::ShadowCallbackVerdict("bunq", body, other, kOwnIban)); + Equal(verdicts.back(), + "DIFFER id=same amount=DIFFERENT reference=same in method=sepa " + "account=ours event=transactions", + "another amount"); + other = *ours; + other.id = "1"; + verdicts.push_back(Server::ShadowCallbackVerdict("bunq", body, other, kOwnIban)); + Has(verdicts.back(), "DIFFER id=DIFFERENT amount=same reference=same ", + "another id"); + other = *ours; + other.reference = "something else"; + verdicts.push_back(Server::ShadowCallbackVerdict("bunq", body, other, kOwnIban)); + Has(verdicts.back(), "DIFFER id=same amount=same reference=DIFFERENT ", + "another reference"); + } + } + + // ── neither reads a payment ─────────────────────────────────────── + for (const std::string_view none : { std::string_view(""), std::string_view("not json"), + std::string_view("SECRETMARK"), + std::string_view(R"({"SECRETMARK": 1})"), + std::string_view(R"({"NotificationUrl": {}})") }) { + Has(Verdict(none), "AGREE neither reads a payment (nostro: ", + std::format("a body that is no callback: '{}'", none.substr(0, 16))); + } + Equal(Verdict(R"({"NotificationUrl": {"category": "REQUEST", + "event_type": "REQUEST_INQUIRY_CREATED", + "object": {"RequestInquiry": {"id": 7}}}})"), + "AGREE no payment in it (event=bunq:REQUEST)", + "a callback about something that is no payment"); + + // ── and none of it says anything a body carried ─────────────────── + Check(verdicts.size() >= 25, "the verdicts above were all collected", + std::format("{}", verdicts.size())); + for (const std::string& v : verdicts) { + for (const std::string_view secret : kSecrets) { + Check(v.find(secret) == std::string::npos, + std::format("a verdict repeats '{}' from a body", secret), v); + } + Check(v.find('\n') == std::string::npos, "a verdict is one line", v); + } + + if (failures != 0) { + std::println(std::cerr, "{} check(s) failed", failures); + return 1; + } + std::println("ShouldCompareCallbackReaders: all checks passed"); + return 0; +} diff --git a/tests/ShouldReceiveBankCallbacks/main.cpp b/tests/ShouldReceiveBankCallbacks/main.cpp new file mode 100644 index 0000000..6060f6b --- /dev/null +++ b/tests/ShouldReceiveBankCallbacks/main.cpp @@ -0,0 +1,272 @@ +/* +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. +*/ + +// The bank's callback endpoint, over real HTTP, with the shadow run of +// Nostro's reader attached to it (see ShadowCallbackVerdict in the server's +// interface). The endpoint is how a transfer settles within seconds in +// production, and until this suite it was only ever exercised there. +// +// What it holds, in the order that matters: +// +// * OUR PARSER STILL DECIDES, ALONE. A payment it reads is credited whatever +// Nostro's reader makes of the same body, including when that reader +// refuses it. The shadow is in production to find out whether it would +// refuse real callbacks, so the one thing it must not be able to do is +// turn a refusal into a missed payment. +// * An order settles from a callback, end to end: the body the bank posts, +// the credit, the reconciler, the paid page. +// * The shadow says what it found, once per callback, in the server's log. +// * That log says nothing a callback carried: not the payer, not the +// reference, and not the address, which is the endpoint's only secret. +// +// No secret and no network: the suite plays the bank by posting to the +// endpoint, as ShouldSettleBankTransfers plays it by writing the credits file. +// The bodies are made up, in the shape of bunq's own sample of a callback. + +import std; +import Crafter.Network; +import Catcrafts.E2eHarness; + +using namespace Catcrafts::E2e; +namespace fs = std::filesystem; + +namespace { + +// Not real accounts, and not the shop's: see ShouldSettleBankTransfers. +constexpr std::string_view kIban = "NL00TEST0123456789"; +constexpr std::string_view kOtherIban = "NL00OTHR0000000002"; +constexpr std::string_view kBeneficiary = "Catcrafts E2E, not a real account"; + +// The secret address. Long enough for the server to take it for one. +constexpr std::string_view kHook = "/hooks/bank/e2e-HOOKSECRET-0123456789abcdef"; + +// What a PAID donation page says: see ShouldSettleBankTransfers for why this +// copy, and not a badge, is the signal. +constexpr std::string_view kPaidCopy = "Your donation funds"; + +constexpr std::string_view kShadow = "bank callback shadow: "; + +struct Sent { + std::string_view id; + std::string_view value; + std::string_view description = "PAYERNOTE thanks"; + std::string_view type = "EBA_SCT"; + std::string_view account = kIban; // the payment's own side +}; + +// A callback as bunq's sample has one: the envelope with the address it was +// sent to, and a Payment with both sides on it. +std::string Callback(const Sent& s) { + return std::format(R"({{ + "NotificationUrl": {{ + "target_url": "https://shop.invalid{}", + "category": "MUTATION", + "event_type": "MUTATION_CREATED", + "object": {{"Payment": {{ + "id": {}, + "created": "2026-11-25 10:15:30.498520", + "updated": "2026-11-25 10:15:30.498520", + "monetary_account_id": 42, + "amount": {{"currency": "EUR", "value": "{}"}}, + "description": "{}", + "type": "{}", + "alias": {{"iban": "{}", "display_name": "PAYEENAME", "country": "NL"}}, + "counterparty_alias": {{"iban": "NL00PAYR0000000001", + "display_name": "PAYERNAME", "country": "NL"}} + }}}} + }} + }})", kHook, s.id, s.value, s.description, s.type, s.account); +} + +// The four members our own parser reads and nothing else, which Nostro's +// reader refuses for what it lacks. +std::string Reduced(std::string_view id, std::string_view value) { + return std::format(R"({{"NotificationUrl": {{"category": "MUTATION", + "object": {{"Payment": {{"id": {}, "type": "EBA_SCT", + "description": "PAYERNOTE reduced", + "amount": {{"currency": "EUR", "value": "{}"}}}}}}}}}})", id, value); +} + +std::string TokenOf(const Crafter::HTTPResponse& res) { + const auto loc = res.headers.find("location"); + if (loc == res.headers.end()) return {}; + const std::string& url = loc->second; + const std::size_t at = url.rfind('/'); + return at == std::string::npos ? std::string{} : url.substr(at + 1); +} + +// The order reference ("CC-XXXXXX") out of the ledger's newest order event. +std::string NewestReference(const TestServer& srv) { + const std::string text = srv.OrdersText(); + const std::string key = "\"ref\":\""; + std::string found; + for (std::size_t at = text.find(key); at != std::string::npos; + at = text.find(key, at + 1)) { + const std::size_t start = at + key.size(); + const std::size_t end = text.find('"', start); + if (end == std::string::npos) break; + found = text.substr(start, end - start); + } + return found; +} + +} // namespace + +int main(int argc, char** argv) { + if (argc < 2) { + std::println(std::cerr, "usage: ShouldReceiveBankCallbacks "); + return 2; + } + + ServerOptions options; + // The REAL transfer rail in the bank slot, settling from the credits file + // the callback endpoint writes. The crypto slot is off. + options.extraArgs = { "--rail=transfer", "--crypto-rail=off" }; + options.env = { + { "TRANSFER_IBAN", std::string(kIban) }, + { "TRANSFER_BENEFICIARY", std::string(kBeneficiary) }, + { "TRANSFER_POLL_SECONDS", "1" }, + { "BUNQ_WEBHOOK_PATH", std::string(kHook) }, + // A developer's shell may carry the real key, and with one the rail + // would read the real bank instead of the credits file. Never here. + { "BUNQ_API_KEY", "" }, + }; + TestServer srv(argv[1], 8223, options); + + const fs::path credits(srv.Orders().string() + ".transfer-credits.jsonl"); + const fs::path log = srv.Work() / "server.log"; + const auto Credited = [&](std::string_view id) { + return CountOccurrences(ReadFile(credits), std::format("\"id\":\"{}\"", id)); + }; + const auto Logged = [&](std::string_view line) { + return CountOccurrences(ReadFile(log), line); + }; + const auto Send = [&](std::string body) { + return srv.Post(std::string(kHook), std::move(body), "application/json").status; + }; + + Check(Logged("bank callback shadow: on") == 1 && Logged("own account named") == 1, + "the shadow says at startup that it is on, and that it knows the account", + ReadFile(log)); + + // ── the endpoint is the secret address, and only for a POST ─────── + srv.CheckStatus(std::string(kHook), "404"); + { + std::string near(kHook); + near.back() = near.back() == 'f' ? 'e' : 'f'; + const std::string status = + srv.Post(near, Callback({ .id = "9000099", .value = "5.00" }), + "application/json").status; + Check(status != "200", "an address one character off is not the endpoint", status); + Check(Credited("9000099") == 0, "and what is posted there credits nothing"); + Check(Logged(kShadow) == 1, "nor does the shadow look at it"); // the startup line + } + + // ── a payment both readers read ─────────────────────────────────── + Check(Send(Callback({ .id = "9000001", .value = "5.00" })) == "200", + "a callback is answered 200"); + Check(Credited("9000001") == 1, "and its payment is credited", ReadFile(credits)); + { + const std::string text = ReadFile(credits); + Check(text.find("\"amount_minor\":500") != std::string::npos + && text.find("\"method\":\"sepa\"") != std::string::npos, + "with its amount and how it arrived", text); + } + Check(Logged("bank callback shadow: AGREE in method=sepa account=ours " + "event=transactions") == 1, + "the shadow says Nostro's reader read the same payment", ReadFile(log)); + + // The bank retries, and a retry must not count twice. The shadow looks at + // each one: it compares readings, it keeps no books. + Check(Send(Callback({ .id = "9000001", .value = "5.00" })) == "200", + "the same callback again is answered 200 as well"); + Check(Credited("9000001") == 1, "and is credited once", ReadFile(credits)); + Check(Logged("bank callback shadow: AGREE in method=sepa account=ours " + "event=transactions") == 2, + "the shadow compares the retry too", ReadFile(log)); + + // ── a payment Nostro's reader refuses: ours decides, alone ──────── + Check(Send(Reduced("9000002", "3.00")) == "200", + "a callback Nostro's reader refuses is answered 200"); + Check(Credited("9000002") == 1, + "and is CREDITED all the same: the shadow has no say", ReadFile(credits)); + Check(Logged("bank callback shadow: DIFFER nostro refused what ours reads " + "as a payment: ") == 1, + "the shadow says that Nostro's reader would have refused it", ReadFile(log)); + + // ── money going out ─────────────────────────────────────────────── + Check(Send(Callback({ .id = "9000003", .value = "-24.95", .type = "MASTERCARD" })) + == "200", + "a callback about an outgoing card payment is answered 200"); + Check(Credited("9000003") == 0, "and credits nothing", ReadFile(credits)); + Check(Logged("bank callback shadow: AGREE out method ours=MASTERCARD nostro=card " + "account=ours event=transactions") == 1, + "the shadow reads it the same, and names the method each reader gives", + ReadFile(log)); + + // ── a payment on another account ────────────────────────────────── + // + // Only the shadow's word is held here. Our parser never looked at which + // account a payment is on, and what the endpoint does with one on another + // account is for the change that replaces the parser to decide and pin. + Check(Send(Callback({ .id = "9000004", .value = "5.00", .account = kOtherIban })) + == "200", + "a callback about another account is answered 200"); + Check(Logged("bank callback shadow: AGREE in method=sepa account=other " + "event=transactions") == 1, + "the shadow says the payment is not on the shop's account", ReadFile(log)); + + // ── what is no callback ─────────────────────────────────────────── + Check(Send("not a callback PAYERNOTE") == "200", + "a body that is no callback is answered 200, so the bank stops retrying"); + Check(Logged("bank callback shadow: AGREE neither reads a payment") == 1, + "and neither reader reads a payment in it", ReadFile(log)); + + // ── an order settles from a callback, end to end ────────────────── + { + const auto res = srv.Post("/shop/donation", "amount=7.00"); + Check(res.status == "303", "a donation on the transfer rail is accepted", + res.status); + const std::string token = TokenOf(res); + const std::string reference = NewestReference(srv); + Check(!token.empty() && !reference.empty(), "and has a page and a reference"); + if (token.empty() || reference.empty()) return Finish(); + const std::string path = "/order/" + token; + srv.BodyHas(path, "awaiting payment", "the order starts out unpaid"); + + const std::string note = std::format("betaling {} bedankt", reference); + Check(Send(Callback({ .id = "9000010", .value = "7.00", .description = note })) + == "200", + "the bank's callback for it is answered 200"); + const std::string body = srv.WaitForBody(path, kPaidCopy, 120); + Check(body.find(kPaidCopy) != std::string::npos, + "and the order is paid, from the callback alone"); + Check(Logged("bank callback shadow: AGREE in method=sepa account=ours " + "event=transactions") == 3, + "with the shadow agreeing on that payment too", ReadFile(log)); + } + + // ── one verdict a callback, and nothing a callback carried ──────── + { + const std::string text = ReadFile(log); + // Seven callbacks reached the endpoint, and the startup line makes eight. + Check(CountOccurrences(text, kShadow) == 8, + "the shadow spoke once for each callback", text); + for (const std::string_view secret : + { kHook, std::string_view("HOOKSECRET"), std::string_view("PAYERNAME"), + std::string_view("PAYEENAME"), std::string_view("PAYERNOTE"), + std::string_view("NL00PAYR"), kIban, kOtherIban, + std::string_view("shop.invalid") }) { + Check(text.find(secret) == std::string::npos, + std::format("the server's log repeats '{}' from a callback", secret), + text); + } + } + + return Finish(); +}