bank: Nostro reads the bank's callback, and the shop's bunq code is gone
All checks were successful
Deploy / build-deploy (push) Successful in 7m20s

The shadow run of 36a635f had Nostro's ReadCallback read a real
callback beside our own parser on 2026-11-25, for order CC-BCD155: the
same id, amount and reference, on the shop's own account. So the reader
takes over, and what this repo carried of bunq goes: the callback
parser, the payment-type table, the API client with its RSA signing,
`--pull-credits`, the mode that read the bank from the server with an
API key, and tools/register-bunq-webhook.sh.

The server now knows no bank. Catcrafts.Server-BankCallback.cpp is the
one unit that imports Nostro.Money: ReadBankCallback has a body read
and says what it comes to, CreditMethodFor says how a payment arrived.
Which bank it is is configuration: --banks= in project.cpp for what the
build can read, BANK_CALLBACK_BANK on the server for what arrives.

What changes for a running shop:

- The endpoint is configured with BANK_CALLBACK_PATH and
  BANK_CALLBACK_BANK; BUNQ_WEBHOOK_PATH is no longer read. Without the
  bank's name, or without TRANSFER_IBAN, the endpoint stays off and the
  startup log says so: one that answered 200 and credited nothing would
  look like working. Production's payments.env got both names before
  this was pushed.
- Only a payment on TRANSFER_IBAN is credited. A bank posts to whatever
  address any of its customers registered, so a callback about someone
  else's account can be the bank's own. Until now a payment in a
  callback was credited whichever account it was on.
- `via` says `internal` for a payment from another account at the bank
  itself, where it said `bunq`, and `card` where it would have said
  `MASTERCARD`. A kind without a word is still passed on as the bank
  wrote it, now only where that is a plain word.
- Every callback leaves one line in the log, `bank callback: credited
  ...` or `bank callback: nothing credited: <why>`, with nothing of the
  body in it beyond the credit.
- A line of the credits file may carry the bank's kind and the bank
  (`"bank":"bunq","kind":"EBA_SCT/SCT"`) in place of `method`, put into
  the ledger's words when the file is read. The pull script ships those
  and takes the bank's name from nostrod, so it holds no table of a
  bank's words either.

Also gone, with their last user: ParseAmountToMinor, PullCreditsInto
and the explicit -lcrypto (Crafter.Network names what it needs).

ShouldReadBankCallbacks replaces ShouldParseBunqPayments and
ShouldCompareCallbackReaders: what a callback comes to for each shape,
each method, the account and the sign, and that no note repeats
anything a body carried. ShouldReceiveBankCallbacks posts to the real
endpoint: an order settles from a callback, one from another account
quoting the same order does not pay for it, and a server without the
bank's name has no endpoint.

Built from scratch and run in a copy of this tree with crafter-build
6.4.1: the server and the wasm bundle build, and every suite passes but
ShouldServePostPages, which fails there for want of mirrored post media
and passed in CI on the commit before this. A dry run of the pull
script against nostrod gave 19 credits with their kinds.

Not tried: a real callback through the new handler, and `nostro
callbacks` against the registration that is in place, which was made
with the script this removes. deploy/README.md has the new setup.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Jorijn van der Graaf 2026-11-25 15:08:42 +01:00
commit 33ce8f45d8
Signed by: jorijnvdgraaf
GPG key ID: 2937E59CDCC1BCFB
24 changed files with 1218 additions and 2385 deletions

View file

@ -75,17 +75,15 @@ std::string gCssHref = "/styles.css";
PaymentRails gRails;
std::string gRedirectBase = "https://catcrafts.net";
// Where the bunq callback writes, and the secret path that authorises it.
// Both empty means the endpoint does not exist at all — an unconfigured
// Where the bank's callback writes, the secret path that authorises it, which
// bank's callbacks arrive there, and the account a payment has to be on. An
// empty path means the endpoint does not exist at all — an unconfigured
// webhook must not answer, or the shop would carry a public write-ish endpoint
// nobody asked for.
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;
std::string gCallbackBank;
std::string gCallbackIban;
// The bank-derived aggregates for /financials live in Catcrafts.Server-
// Financials.cpp, which owns their file. They are read through
@ -649,16 +647,20 @@ std::string NowRfc2822() {
// the POST/redirect/GET pattern, and it matters for a real form: a rendered
// POST response means reloading re-submits, and the back button re-posts. The
// redirect leaves the browser on a GET it can safely repeat.
// The bunq callback. See ParseBunqCallback for the security model; the short
// version is that bunq does NOT sign these, so this endpoint's only defences
// are the ones around it: a secret path segment, a source-IP allowlist in
// Caddy for bunq's published range, and the fact that no parcel leaves without
// a human. It therefore does the least it possibly can — decode one payment
// and append it to the credits file — and makes no settlement decision at all.
// The reconciler settles from that file exactly as it does from a pulled one,
// so a forged callback can at worst manufacture a credit line, never bypass
// the reference match or the covering-amount rule.
HTTPResponse HandleBunqCallback(const HTTPRequest& req) {
// The bank's callback. See ReadBankCallback in the interface for the security
// model; the short version is that a bank need not sign these and ours does
// not, so this endpoint's defences are the ones around it: a secret path
// segment, a source-IP allowlist in Caddy for the bank's published range, the
// check that a payment is on the shop's own account, and the fact that no
// parcel leaves without a human. It therefore does the least it possibly can —
// have one payment read and append it to the credits file — and makes no
// settlement decision at all. The reconciler settles from that file exactly as
// it does from a pulled one, so a forged callback can at worst manufacture a
// credit line, never bypass the reference match or the covering-amount rule.
//
// Every callback leaves exactly one line in the log, and none of them says
// anything the body carried beyond what a credit line already holds.
HTTPResponse HandleBankCallback(const HTTPRequest& req) {
HTTPResponse res;
res.headers["content-type"] = "text/plain; charset=utf-8";
// Never cache, never index, and say nothing useful in the body: this URL
@ -673,65 +675,32 @@ HTTPResponse HandleBunqCallback(const HTTPRequest& req) {
return res;
}
const std::optional<BankCredit> credit = ParseBunqCallback(req.body);
if (!credit) {
// A callback shape this cannot decode is NOT an error to shout about
// with a 4xx: bunq sends several notification categories, and only
// some carry a Payment. Answer 200 so bunq stops retrying something
// that will never decode, and log it so a genuinely new shape is
// visible rather than silently dropped.
std::println(std::cerr, "bunq callback: no usable payment in body ({} bytes)",
req.body.size());
res.status = "200";
res.body = "ok\n";
return res;
}
// Outgoing money cannot pay for an order, and the matcher ignores it
// anyway — so refuse to write the shop's own supplier payments into a file
// that lives on a public-facing host.
if (credit->amountMinor <= 0) {
res.status = "200";
res.body = "ok\n";
return res;
}
if (AppendCreditTo(gCreditsPath, *credit)) {
std::println(std::cerr, "bunq callback: credited {} via {} (id {})",
Money::FormatMinor(credit->amountMinor), credit->method,
credit->id);
}
// 200 even on a duplicate or a write we skipped: a duplicate IS success
// from bunq's side, and making it retry would achieve nothing.
// 200 whatever comes of it. A body that carries no payment for us is NOT
// an error to answer with a 4xx: a bank sends several kinds of event, and
// one it gets an error for it sends again, which achieves nothing. A
// duplicate IS success from the bank's side for the same reason.
res.status = "200";
res.body = "ok\n";
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<BankCredit> 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 (...) {
}
const BankCallbackResult read = ReadBankCallback(gCallbackBank, req.body, gCallbackIban);
if (!read.credit) {
// Said aloud, so that a shape the reader does not take, or a payment
// on an account that is not ours, is visible rather than silently
// dropped. The note holds nothing of the body.
std::println(std::cerr, "bank callback: nothing credited: {}", read.note);
return res;
}
if (AppendCreditTo(gCreditsPath, *read.credit)) {
std::println(std::cerr, "bank callback: credited {} via {} (id {})",
Money::FormatMinor(read.credit->amountMinor), read.credit->method,
read.credit->id);
} else {
std::println(std::cerr, "bank callback: nothing credited: the payment was "
"credited before, or the credits file could not be "
"written");
}
return res;
}
HTTPResponse HandleCheckout(const HTTPRequest& req, const Route& route) {
@ -1161,38 +1130,43 @@ void ConfigurePayments(PaymentRails rails, std::string redirectBase) {
if (!redirectBase.empty()) gRedirectBase = std::move(redirectBase);
}
void ConfigureBunqCallback(std::filesystem::path creditsPath, std::string secretPath) {
// Both or neither. A secret with nowhere to write, or a path to write with
// no secret guarding it, are each worse than not having the endpoint: the
// first answers requests it cannot act on, the second answers everyone.
void ConfigureBankCallback(std::filesystem::path creditsPath, std::string secretPath,
std::string bank, std::string ownIban) {
// All of it or none. A secret with nowhere to write, or a path to write
// with no secret guarding it, are each worse than not having the endpoint:
// the first answers requests it cannot act on, the second answers everyone.
if (creditsPath.empty() || secretPath.empty()) return;
// A short secret is not a secret. Refuse rather than serve a guessable
// write endpoint just because someone set the variable to "hook".
if (secretPath.size() < 24) {
std::println(std::cerr,
"bunq callback: BUNQ_WEBHOOK_PATH is too short to be secret "
"bank callback: BANK_CALLBACK_PATH is too short to be secret "
"({} chars, want 24+) — the endpoint is NOT enabled",
secretPath.size());
return;
}
// Which bank posts there decides how a body is read, and the account is
// what a payment has to be on to count. Without either the endpoint would
// answer the bank 200 and credit nothing, which looks like working.
if (bank.empty() || ownIban.empty()) {
std::println(std::cerr,
"bank callback: {} is not set — the endpoint is NOT enabled",
bank.empty() ? "BANK_CALLBACK_BANK (whose callbacks arrive there)"
: "TRANSFER_IBAN (the account a payment must be on)");
return;
}
if (secretPath.front() != '/') secretPath.insert(secretPath.begin(), '/');
gCreditsPath = std::move(creditsPath);
gWebhookPath = std::move(secretPath);
// Deliberately does NOT log the path: it would land in the journal, and
// from there in any log shipping or analytics that reads it.
std::println(std::cerr, "bunq callback: enabled on a secret path ({} chars)",
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.
gCallbackBank = std::move(bank);
gCallbackIban = std::move(ownIban);
// Deliberately does NOT log the path or the account: either would land in
// the journal, and from there in any log shipping or analytics that reads
// it. The bank's name is configuration and no secret.
std::println(std::cerr,
"bank callback shadow: on, Nostro's reader runs beside ours and "
"decides nothing (own account {})",
gShadowIban.empty() ? "not named" : "named");
"bank callback: enabled on a secret path ({} chars), reading {}'s "
"callbacks for the shop's own account",
gWebhookPath.size(), gCallbackBank);
}
bool CryptoPaymentAvailable() { return gRails.crypto != nullptr; }
@ -1411,7 +1385,7 @@ int Serve(std::uint16_t port) {
};
auto fallback = [](const HTTPRequest& req) -> HTTPResponse {
// The bunq callback, before anything else looks at the path. It is
// The bank's callback, before anything else looks at the path. It is
// matched here rather than added to the shared route table on purpose:
// ParseRoute is shared with the wasm frontend, and a secret URL has no
// business being compiled into a bundle served to browsers.
@ -1425,7 +1399,7 @@ int Serve(std::uint16_t port) {
// be an oracle: a GET returning 405 where every other unknown URL
// returns 404 confirms a guessed path is the right one, which is
// exactly the signal a secret-in-the-URL scheme cannot afford to give.
// bunq only ever POSTs, so nothing legitimate is lost.
// The bank only ever POSTs, so nothing legitimate is lost.
if (!gWebhookPath.empty() && req.method == "POST") {
const std::string_view path = PathWithoutQueryHTTP(req.path);
if (path.size() == gWebhookPath.size()) {
@ -1433,14 +1407,7 @@ int Serve(std::uint16_t port) {
for (std::size_t i = 0; i < path.size(); ++i) {
diff |= static_cast<unsigned char>(path[i] ^ gWebhookPath[i]);
}
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;
}
if (diff == 0) return HandleBankCallback(req);
}
}
// A POST to a product page is a checkout submission.