// SPDX-License-Identifier: LGPL-3.0-only // SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® // A bunq for tests, included after `#include "../../lib/json.hpp"`, `import std;`, `import Nostro;` and // `import Crafter.Network;`. It serves HTTPS on 127.0.0.1 with Crafter.Network's self-signed certificate, // answers the calls nostro makes from a small state of its own, signs every success with its own key as bunq does, // checks the client's signatures, and fails on request. Point nostro at it with Fake::Bunq::Redirect(). namespace Fake { using json = nlohmann::json; // bunq's clock: every object made moves it on a minute, from 2026-10-01 10:00 UTC. std::string Time(std::uint32_t minutes) { return Nostro::FormatTimestamp(Nostro::ParseTimestamp("2026-10-01 10:00:00") + std::chrono::minutes(minutes)); } // A value of `query` ("a=1&b=2"), decoded. std::string Param(std::string_view query, std::string_view name) { return Nostro::QueryParameter(std::format("?{}", query), name).value_or(""); } std::int64_t Minor(const json& amount) { return Nostro::ParseAmount(amount.at("value").get(), Nostro::Currency::Euro); } json Amount(std::int64_t minor) { return json{{"value", Nostro::FormatAmount(minor, Nostro::Currency::Euro)}, {"currency", "EUR"}}; } // What the server does instead of answering, for the next `times` requests that match. struct Fault { enum class Kind : std::uint8_t { Reply, // `status` and `body`, unsigned, as bunq sends an error SignedReply, // `status` and `body`, signed: a success bunq would not send Unsigned, // the real answer without its signature BadSignature, // the real answer signed with another key }; std::string method; // empty matches every method std::string path; // a prefix of the path below /v1, without the query; empty matches every path Kind kind = Kind::Reply; std::uint16_t status = 500; std::string body; std::uint32_t times = 1; }; // One request as the server saw it. struct Logged { std::string method; std::string path; // below /v1, with the query std::string body; bool signed_ = false; // carried an X-Bunq-Client-Signature bool signatureValid = false; // which verified against the installation's key }; class Bunq { public: // The server answers on threads of its own: lock this around anything a test reads or changes while nostro // could be calling. std::mutex mutex; std::uint16_t port; Nostro::Crypto::Key key; // signs every success Nostro::Crypto::Key otherKey; // signs for BadSignature std::string publicKeyPem; std::uint64_t nextId = 1000; std::uint32_t clock = 0; std::size_t pageSize = 200; // a listing sends at most this many per page, whatever its count asks std::chrono::milliseconds latency{0}; // how long every answer takes: a real bank is a network away std::string scheduledName = "ScheduledPayment"; bool cardsActivate = true; // false: PUT card ACTIVE leaves the card as it is, as bunq does for one that was never activated struct Installation { std::uint64_t id; std::string clientKeyPem; }; struct Session { std::uint64_t id; std::string key; // the API key or OAuth token the session was opened with std::string installation; // its installation token }; std::map installations; // by token std::map sessions; // by token std::map keys; // API key or OAuth token: the user it opens a session for std::map devices; // API key: the device-server body that registered it std::map> users; // id: the object's type and the object std::map> accounts; // id: the object's type and the object std::vector extraAccountItems; // listed first, as they are std::map> payments; // account id: items, newest first std::map> inquiries; // account id: RequestInquiry items, newest first std::map> responses; // account id: RequestResponse items, newest first std::map> schedules; // account id: items, newest first std::map> drafts; // account id: DraftPayment items, newest first std::map> cards; // user id: card items std::map codes; // OAuth authorization code: the token it gives std::string clientId = "fake-client"; std::string clientSecret = "fake-secret"; std::vector faults; std::vector log; explicit Bunq(std::uint16_t port) : port(port), key(Nostro::Crypto::OwnKey(std::get<0>(Nostro::Crypto::CreateKey()))), otherKey(Nostro::Crypto::OwnKey(std::get<0>(Nostro::Crypto::CreateKey()))), publicKeyPem(Nostro::Crypto::PublicKeyToPem(key.get())), listener(port, {}, [this](const Crafter::HTTPRequest& request) { return Answer(request); }, Crafter::TLSServerCredentials{.selfSigned = true}) { } // Sends nostro's bunq calls here. void Redirect() const { Nostro::BunqConnector::RedirectTo(Nostro::BunqEndpoint{.host = "127.0.0.1", .port = port, .caPem = Crafter::GetSelfSignedCertificatePem().certificate}); } // Points the processes this test starts (nostrod and its workers) at the bunq it will run on `port`: in // NOSTRO_TEST_BUNQ, " ", read by RedirectFromEnvironment(). Called // before any thread starts, as it sets the environment. static void ExportRedirect(std::uint16_t port, const std::filesystem::path& certificate) { std::ofstream(certificate) << Crafter::GetSelfSignedCertificatePem().certificate; setenv("NOSTRO_TEST_BUNQ", std::format("{} {}", port, certificate.string()).c_str(), 1); } // In a process the test started: sends nostro to the test's bunq, as ExportRedirect() said. static void RedirectFromEnvironment() { std::istringstream variable(std::getenv("NOSTRO_TEST_BUNQ")); std::uint16_t port = 0; std::string certificate; variable >> port >> certificate; std::ifstream file(certificate); Nostro::BunqConnector::RedirectTo(Nostro::BunqEndpoint{.host = "127.0.0.1", .port = port, .caPem = std::string(std::istreambuf_iterator(file), std::istreambuf_iterator())}); } // A user, its API key, and nothing else; `object` is what bunq says about it ("id" is filled in). std::uint64_t AddUser(std::string_view type, json object, std::string_view apiKey) { std::lock_guard lock(mutex); const std::uint64_t id = nextId++; object["id"] = id; users[id] = {std::string(type), std::move(object)}; if(!apiKey.empty()) { keys[std::string(apiKey)] = id; } return id; } std::uint64_t AddPerson(std::string_view name, std::string_view apiKey) { return AddUser("UserPerson", json{{"display_name", name}, {"public_nick_name", name}}, apiKey); } // An OAuth grant of `granted`'s accounts: a UserApiKey of its own, and the code that gives its token. std::uint64_t AddGrant(std::uint64_t granted, std::string_view code, std::string_view token) { json grantedObject; { std::lock_guard lock(mutex); grantedObject = json{{users.at(granted).first, users.at(granted).second}}; codes[std::string(code)] = std::string(token); } return AddUser("UserApiKey", json{{"requested_by_user", json{{"UserPerson", json{{"id", 1}, {"display_name", "Nostro"}}}}}, {"granted_by_user", grantedObject}}, token); } std::uint64_t AddAccount(std::uint64_t user, std::string_view iban, std::string_view description, std::int64_t balance, std::string_view type = "MonetaryAccountBank") { std::lock_guard lock(mutex); const std::uint64_t id = nextId++; accounts[id] = {std::string(type), json{ {"id", id}, {"user_id", user}, {"description", description}, {"currency", "EUR"}, {"status", "ACTIVE"}, {"balance", Amount(balance)}, {"alias", json::array({json{{"type", "PHONE_NUMBER"}, {"value", "+31600000000"}}, json{{"type", "IBAN"}, {"value", iban}, {"name", description}}})}, }}; return id; } // A payment as bunq lists it, on `account`; `extra` overrides or adds fields. std::uint64_t AddPayment(std::uint64_t account, std::int64_t amount, std::string_view counterparty, std::string_view iban, std::string_view description, json extra = json::object()) { std::lock_guard lock(mutex); return AddPaymentLocked(account, amount, counterparty, iban, description, std::move(extra)); } std::uint64_t AddCard(std::uint64_t user, std::string_view status, json extra = json::object()) { std::lock_guard lock(mutex); const std::uint64_t id = nextId++; json card = { {"id", id}, {"status", status}, // Plastic the user has and activated, unless `extra` says otherwise: a virtual card is VIRTUAL_DELIVERY, and // bunq has one as DEACTIVATED however it stands. {"order_status", "DELIVERED_TO_CUSTOMER"}, {"product_type", "MASTERCARD_DEBIT"}, {"name_on_card", "J. Tester"}, {"second_line", "Nostro"}, {"expiry_date", "2030-11-30"}, {"primary_account_numbers", json::array({json{{"four_digit", "1234"}}})}, {"label_monetary_account_current", json{{"iban", "NL01BUNQ0000000001"}}}, }; card.update(extra); cards[user].push_back(json{{"CardDebit", card}}); return id; } void Fail(Fault fault) { std::lock_guard lock(mutex); faults.push_back(std::move(fault)); } std::vector Log() { std::lock_guard lock(mutex); return log; } std::size_t Count(std::string_view method, std::string_view pathPrefix) { std::lock_guard lock(mutex); return static_cast(std::ranges::count_if(log, [method, pathPrefix](const Logged& entry) { return entry.method == method && entry.path.starts_with(pathPrefix); })); } // Ends every session, as an expiry would. void ExpireSessions() { std::lock_guard lock(mutex); sessions.clear(); } json AccountObject(std::uint64_t id) { std::lock_guard lock(mutex); return accounts.at(id).second; } void ChangeAccount(std::uint64_t id, const json& changes) { std::lock_guard lock(mutex); accounts.at(id).second.update(changes); } private: // Last, so the rest is ready when it starts accepting. Crafter::ListenerAsyncHTTP1 listener; json Error(std::string_view description) { return json{{"Error", json::array({json{{"error_description", description}, {"error_description_translated", description}}})}}; } static json Response(json items) { return json{{"Response", std::move(items)}}; } static json Id(std::uint64_t id) { return Response(json::array({json{{"Id", json{{"id", id}}}}})); } static std::uint64_t ItemId(const json& item) { if(!item.is_object() || item.size() != 1 || !item.begin().value().is_object() || !item.begin().value().contains("id")) { return std::numeric_limits::max(); } return item.begin().value().at("id").get(); } json Label(std::uint64_t account) { const json& object = accounts.at(account).second; std::string iban; for(const json& alias : object.value("alias", json::array())) { if(alias.value("type", "") == "IBAN") { iban = alias.at("value").get(); } } // bunq shows an account by its holder's name, as it did "Sugar Daddy" in the sandbox. const std::uint64_t user = object.value("user_id", std::uint64_t{0}); const std::string holder = users.contains(user) ? users.at(user).second.value("display_name", "") : std::string(); return json{{"iban", iban}, {"display_name", holder.empty() ? object.value("description", "") : holder}, {"label_user", json{{"display_name", holder}}}}; } std::optional AccountOfIban(std::string_view iban) { for(const auto& [id, account] : accounts) { for(const json& alias : account.second.value("alias", json::array())) { if(alias.value("type", "") == "IBAN" && alias.value("value", "") == iban) { return id; } } } return std::nullopt; } // What a payment's counterparty looks like in a listing. json CounterpartyLabel(const json& pointer) { if(pointer.value("type", "") == "IBAN") { return json{{"iban", pointer.at("value")}, {"display_name", pointer.value("name", "")}}; } return json{{"iban", nullptr}, {"display_name", pointer.value("name", "")}, {"label_user", json{{"display_name", pointer.value("name", "")}}}}; } std::uint64_t AddPaymentLocked(std::uint64_t account, std::int64_t amount, std::string_view counterparty, std::string_view iban, std::string_view description, json extra) { const std::uint64_t id = nextId++; json payment = { {"id", id}, {"created", Time(clock++)}, {"monetary_account_id", account}, {"amount", Amount(amount)}, {"counterparty_alias", json{{"iban", iban.empty() ? json(nullptr) : json(iban)}, {"display_name", counterparty}}}, {"description", description}, {"type", "BUNQ"}, {"sub_type", "PAYMENT"}, }; payment.update(extra); payments[account].insert(payments[account].begin(), json{{"Payment", payment}}); json& balance = accounts.at(account).second["balance"]; if(balance.is_object()) { balance = Amount(Minor(balance) + amount); } return id; } // Moves money out of `from` to whoever `pointer` names, and into their account when it is one of ours. std::uint64_t Pay(std::uint64_t from, const json& amount, const json& pointer, std::string_view description) { const std::int64_t minor = Minor(amount); const json label = CounterpartyLabel(pointer); const std::uint64_t id = AddPaymentLocked(from, -minor, label.value("display_name", ""), label.at("iban").is_string() ? label.at("iban").get() : std::string(), description, json::object()); if(pointer.value("type", "") == "IBAN") { if(const std::optional to = AccountOfIban(pointer.at("value").get())) { const json payer = Label(from); AddPaymentLocked(*to, minor, payer.value("display_name", ""), payer.value("iban", ""), description, json::object()); } } return id; } // A listing page of `items` (newest first) by bunq's count and older_id. json Page(const std::vector& items, std::string_view path, std::string_view query) { const std::string count = Param(query, "count"); const std::size_t limit = std::min(count.empty() ? 10 : std::stoul(count), pageSize); const std::string older = Param(query, "older_id"); const std::uint64_t olderId = older.empty() ? std::numeric_limits::max() : std::stoull(older); json page = json::array(); std::uint64_t last = 0; bool more = false; for(const json& item : items) { const std::uint64_t id = ItemId(item); if(id != std::numeric_limits::max() && id >= olderId) { continue; } if(page.size() == limit) { more = true; break; } page.push_back(item); last = id; } return json{ {"Response", page}, {"Pagination", json{ {"future_url", std::format("/v1{}?newer_id={}", path, last)}, {"newer_url", nullptr}, {"older_url", more ? json(std::format("/v1{}?count={}&older_id={}", path, count.empty() ? "10" : count, last)) : json(nullptr)}, }}, }; } json* FindItem(std::vector& items, std::string_view type, std::uint64_t id) { for(json& item : items) { if(item.contains(type) && item.at(type).at("id").get() == id) { return &item.at(type); } } return nullptr; } std::pair Route(const std::string& method, const std::vector& part, const std::string& path, const std::string& query, const json& body, const std::string& authentication) { const auto is = [&part](std::initializer_list pattern) { if(part.size() != pattern.size()) { return false; } std::size_t i = 0; for(const std::string_view expected : pattern) { if(expected != "*" && part[i] != expected) { return false; } i++; } return true; }; const auto number = [&part](std::size_t i) { return std::stoull(part[i]); }; if(method == "POST" && is({"installation"})) { const std::string token = Nostro::Crypto::RandomHex(16); const std::uint64_t id = nextId++; installations[token] = Installation{id, body.at("client_public_key").get()}; return {200, Response(json::array({json{{"Id", json{{"id", id}}}}, json{{"Token", json{{"id", id}, {"token", token}}}}, json{{"ServerPublicKey", json{{"server_public_key", publicKeyPem}}}}}))}; } if(method == "POST" && is({"token"})) { if(Param(query, "grant_type") != "authorization_code") { return {400, json{{"error", "invalid_request"}, {"error_description", "Missing required GET parameter \"grant_type\"."}}}; } const auto code = codes.find(Param(query, "code")); if(code == codes.end() || Param(query, "client_id") != clientId || Param(query, "client_secret") != clientSecret) { return {400, json{{"error", "invalid_grant"}, {"error_description", "The authorization code is invalid or expired."}}}; } const std::string token = code->second; codes.erase(code); return {200, json{{"access_token", token}, {"token_type", "bearer"}, {"state", ""}}}; } if(is({"device-server"}) || is({"session-server"})) { if(!installations.contains(authentication)) { return {401, Error("Insufficient authorisation.")}; } const std::string secret = body.value("secret", ""); if(!keys.contains(secret)) { return {400, Error("User credentials are incorrect. Incorrect API key or IP address.")}; } if(is({"device-server"})) { devices[secret] = body; return {200, Id(nextId++)}; } const std::uint64_t user = keys.at(secret); const std::string token = Nostro::Crypto::RandomHex(16); const std::uint64_t id = nextId++; sessions[token] = Session{id, secret, authentication}; return {200, Response(json::array({json{{"Id", json{{"id", id}}}}, json{{"Token", json{{"id", id}, {"token", token}}}}, json{{users.at(user).first, users.at(user).second}}}))}; } // Everything else needs a session, for the user in its path. const auto session = sessions.find(authentication); if(session == sessions.end()) { return {403, Error("Insufficient authentication.")}; } const std::uint64_t self = keys.at(session->second.key); if(method == "GET" && is({"installation"})) { return {200, Response(json::array({json{{"Id", json{{"id", installations.at(session->second.installation).id}}}}}))}; } if(method == "GET" && is({"installation", "*", "server-public-key"})) { return {200, Response(json::array({json{{"ServerPublicKey", json{{"server_public_key", publicKeyPem}}}}}))}; } if(method == "DELETE" && is({"session", "*"})) { sessions.erase(session); return {200, Response(json::array())}; } if(part.size() < 2 || part[0] != "user" || number(1) != self) { return {403, Error("Insufficient authentication.")}; } if(method == "GET" && is({"user", "*"})) { return {200, Response(json::array({json{{users.at(self).first, users.at(self).second}}}))}; } if(method == "GET" && is({"user", "*", "monetary-account"})) { std::vector items = Older(extraAccountItems, query); // An OAuth grant lists the accounts of the user who granted it; one that names nobody lists none. std::uint64_t granted = self; if(users.at(self).first == "UserApiKey") { const json& grantedBy = users.at(self).second.at("granted_by_user"); granted = grantedBy.empty() ? 0 : grantedBy.begin().value().at("id").get(); } for(auto account = accounts.rbegin(); account != accounts.rend(); account++) { const std::uint64_t owner = account->second.second.value("user_id", std::uint64_t{0}); if(owner == granted) { items.push_back(json{{account->second.first, account->second.second}}); } } return {200, Page(items, path, query)}; } if(method == "GET" && is({"user", "*", "card"})) { return {200, Page(cards[self], path, query)}; } if(method == "PUT" && is({"user", "*", "card", "*"})) { for(json& item : cards[self]) { json& card = item.begin().value(); // By its id, which what a test put among the cards to be skipped has none of. if(card.value("id", std::uint64_t{0}) == number(3)) { const std::string status = body.at("status").get(); // As bunq does: a virtual card asked to freeze or to unfreeze is left as it is and answered // without an error. Reporting it lost or stolen takes, as for any card. const bool ignored = card.value("order_status", std::string()) == "VIRTUAL_DELIVERY" && (status == "ACTIVE" || status == "DEACTIVATED"); if(!ignored && (status != "ACTIVE" || cardsActivate)) { card["status"] = status; } return {200, Response(json::array({item}))}; } } return {404, Error("Card not found.")}; } if(part.size() < 5 || part[2] != "monetary-account" || !accounts.contains(number(3))) { return {404, Error("Not found.")}; } const std::uint64_t account = number(3); const std::string what = part[4]; if(what == "payment" && part.size() == 5) { if(method == "GET") { return {200, Page(payments[account], path, query)}; } return {200, Id(Pay(account, body.at("amount"), body.at("counterparty_alias"), body.value("description", "")))}; } if(what == "request-inquiry") { if(part.size() == 5 && method == "GET") { return {200, Page(inquiries[account], path, query)}; } if(part.size() == 5) { const std::uint64_t id = nextId++; const json& pointer = body.at("counterparty_alias"); json inquiry = { {"id", id}, {"created", Time(clock++)}, {"status", "PENDING"}, {"amount_inquired", body.at("amount_inquired")}, {"amount_responded", nullptr}, {"counterparty_alias", CounterpartyLabel(pointer)}, {"description", body.value("description", "")}, {"bunqme_share_url", body.value("allow_bunqme", false) ? json(std::format("https://bunq.me/t/{}", id)) : json(nullptr)}, }; inquiries[account].insert(inquiries[account].begin(), json{{"RequestInquiry", inquiry}}); if(pointer.value("type", "") == "IBAN") { if(const std::optional payer = AccountOfIban(pointer.at("value").get())) { json response = { {"id", nextId++}, {"created", inquiry.at("created")}, {"status", "PENDING"}, {"type", "INTERNAL"}, {"amount_inquired", body.at("amount_inquired")}, {"counterparty_alias", Label(account)}, {"description", body.value("description", "")}, {"inquiry", json{{"account", account}, {"id", id}}}, }; responses[*payer].insert(responses[*payer].begin(), json{{"RequestResponse", response}}); } } return {200, Id(id)}; } json* inquiry = FindItem(inquiries[account], "RequestInquiry", number(5)); if(!inquiry) { return {404, Error("Request not found.")}; } if(method == "GET") { return {200, Response(json::array({json{{"RequestInquiry", *inquiry}}}))}; } (*inquiry)["status"] = body.at("status"); return {200, Id(number(5))}; } if(what == "request-response") { if(part.size() == 5) { return {200, Page(responses[account], path, query)}; } json* response = FindItem(responses[account], "RequestResponse", number(5)); if(!response) { return {404, Error("Request not found.")}; } if(method == "GET") { return {200, Response(json::array({json{{"RequestResponse", *response}}}))}; } const std::string status = body.at("status").get(); (*response)["status"] = status; json* inquiry = response->contains("inquiry") ? FindItem(inquiries[response->at("inquiry").at("account").get()], "RequestInquiry", response->at("inquiry").at("id").get()) : nullptr; if(inquiry) { (*inquiry)["status"] = status; } if(status == "ACCEPTED") { const json requester = response->at("counterparty_alias"); Pay(account, body.at("amount_responded"), json{{"type", "IBAN"}, {"value", requester.at("iban")}, {"name", requester.value("display_name", "")}}, response->value("description", "")); if(inquiry) { (*inquiry)["amount_responded"] = body.at("amount_responded"); } } return {200, Id(number(5))}; } if(what == "schedule-payment") { if(part.size() == 5 && method == "GET") { std::vector items; for(const json& item : schedules[account]) { items.push_back(json{{scheduledName, item.begin().value()}}); } return {200, Page(items, path, query)}; } if(part.size() == 5) { const std::uint64_t id = nextId++; const json& payment = body.at("payment"); json schedule = body.at("schedule"); schedule["time_next"] = schedule.at("time_start"); json scheduled = { {"id", id}, {"status", "ACTIVE"}, {"payment", json{{"amount", Amount(-Minor(payment.at("amount")))}, {"counterparty_alias", CounterpartyLabel(payment.at("counterparty_alias"))}, {"description", payment.value("description", "")}}}, {"schedule", schedule}, }; schedules[account].insert(schedules[account].begin(), json{{"ScheduledPayment", scheduled}}); return {200, Id(id)}; } std::erase_if(schedules[account], [id = number(5)](const json& item) { return ItemId(item) == id; }); return {200, Response(json::array())}; } if(what == "draft-payment") { if(part.size() == 5 && method == "GET") { return {200, Page(drafts[account], path, query)}; } if(part.size() == 5) { const std::uint64_t id = nextId++; json entries = json::array(); for(const json& entry : body.at("entries")) { entries.push_back(json{{"amount", Amount(-Minor(entry.at("amount")))}, {"counterparty_alias", CounterpartyLabel(entry.at("counterparty_alias"))}, {"pointer", entry.at("counterparty_alias")}, {"description", entry.value("description", "")}}); } const std::string now = Time(clock++); json draft = {{"id", id}, {"created", now}, {"updated", now}, {"status", "PENDING"}, {"user_alias_created", json{{"display_name", users.at(self).second.value("display_name", "")}}}, {"entries", entries}}; drafts[account].insert(drafts[account].begin(), json{{"DraftPayment", draft}}); return {200, Id(id)}; } json* draft = FindItem(drafts[account], "DraftPayment", number(5)); if(!draft) { return {404, Error("Draft not found.")}; } if(method == "GET") { return {200, Response(json::array({json{{"DraftPayment", *draft}}}))}; } if(body.contains("previous_updated_timestamp") && body.at("previous_updated_timestamp") != draft->value("updated", "")) { return {400, Error("The draft payment was changed in the meantime.")}; } const std::string status = body.at("status").get(); (*draft)["status"] = status; (*draft)["updated"] = Time(clock++); if(status == "ACCEPTED") { for(const json& entry : draft->at("entries")) { Pay(account, Amount(-Minor(entry.at("amount"))), entry.at("pointer"), entry.value("description", "")); } } return {200, Id(number(5))}; } return {404, Error("Not found.")}; } // The extra account items, on the first page only. std::vector Older(const std::vector& items, std::string_view query) { return Param(query, "older_id").empty() ? items : std::vector(); } Crafter::HTTPResponse Reply(std::uint16_t status, const std::string& body, std::optional> signer) { std::unordered_map headers = {{"Content-Type", "application/json"}}; if(signer) { headers["X-Bunq-Server-Signature"] = Nostro::Crypto::SignBody(signer->get().get(), body); } return Crafter::CreateResponseHTTP(std::to_string(status), headers, body); } Crafter::HTTPResponse Answer(const Crafter::HTTPRequest& request) { // The bank's own time, before the lock: whoever reads or changes the bank meanwhile is not kept waiting. std::chrono::milliseconds wait{0}; { std::lock_guard lock(mutex); wait = latency; } if(wait.count() > 0) { std::this_thread::sleep_for(wait); } std::lock_guard lock(mutex); std::string path = request.path.substr(0, request.path.find('?')); const std::string query = request.path.contains('?') ? request.path.substr(request.path.find('?') + 1) : std::string(); if(path.starts_with("/v1")) { path = path.substr(3); } const auto header = [&request](const std::string& name) { const auto found = request.headers.find(name); return found == request.headers.end() ? std::string() : found->second; }; const std::string authentication = header("x-bunq-client-authentication"); Logged entry{request.method, query.empty() ? path : std::format("{}?{}", path, query), request.body, false, false}; const std::string signature = header("x-bunq-client-signature"); if(!signature.empty()) { entry.signed_ = true; const std::string installation = installations.contains(authentication) ? authentication : (sessions.contains(authentication) ? sessions.at(authentication).installation : std::string()); if(installations.contains(installation)) { const Nostro::Crypto::Key client = Nostro::Crypto::OwnKey(Nostro::Crypto::LoadPublicKeyFromPem(installations.at(installation).clientKeyPem)); entry.signatureValid = Nostro::Crypto::VerifyBody(client.get(), request.body, signature); } } log.push_back(entry); // A session and a payment need a valid signature, as at bunq. if((path == "/session-server" || (request.method == "POST" && path.ends_with("/payment"))) && !entry.signatureValid) { return Reply(466, Error("Request signature required.").dump(), std::nullopt); } std::optional fault; for(auto it = faults.begin(); it != faults.end(); it++) { if((it->method.empty() || it->method == request.method) && (it->path.empty() || path.starts_with(it->path))) { fault = *it; if(--it->times == 0) { faults.erase(it); } break; } } if(fault && fault->kind == Fault::Kind::Reply) { return Reply(fault->status, fault->body, std::nullopt); } if(fault && fault->kind == Fault::Kind::SignedReply) { return Reply(fault->status, fault->body, std::cref(key)); } std::vector part; for(const auto piece : std::views::split(std::string_view(path).substr(1), '/')) { part.emplace_back(std::string_view(piece.begin(), piece.end())); } const json body = request.body.empty() ? json::object() : json::parse(request.body, nullptr, false); const auto [status, answer] = Route(request.method, part, path, query, body, authentication); const bool success = status >= 200 && status < 300; if(fault && fault->kind == Fault::Kind::Unsigned) { return Reply(status, answer.dump(), std::nullopt); } if(fault && fault->kind == Fault::Kind::BadSignature) { return Reply(status, answer.dump(), std::cref(otherKey)); } return Reply(status, answer.dump(), success ? std::optional(std::cref(key)) : std::nullopt); } }; }