This commit is contained in:
Jorijn van der Graaf 2026-11-01 18:35:23 +01:00
commit 1ea50c50bc
62 changed files with 9982 additions and 608 deletions

View file

@ -0,0 +1,403 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// The bunq connector against a fake bunq (tests/Support/FakeBunq.inc): connecting every kind of user, the protocol's
// checks (signatures, rate limits, session renewal, errors, a refused connection), accounts, the transaction sync,
// cards, OAuth, logging out, removing, and the connector's JSON, old and new.
#include "../../lib/json.hpp"
#include <stdlib.h>
#include <time.h>
import std;
import Nostro;
import Crafter.Network;
#include "../Support/Check.inc"
#include "../Support/FakeBunq.inc"
using namespace Nostro;
using Test::Check;
using Test::Equal;
using Test::Throws;
using json = nlohmann::json;
using Fault = Fake::Fault;
namespace {
constexpr std::uint16_t port = 47302;
// Nothing listens for nostro on HTTPS's own port here, which also makes a request's authority the host alone.
constexpr std::uint16_t closedPort = 443;
std::vector<std::string> AccountNames(const BunqConnector& connector) {
return connector.accounts | std::views::transform(&BunqAccount::name) | std::ranges::to<std::vector<std::string>>();
}
BunqAccount& AccountNamed(BunqConnector& connector, std::string_view name) {
return *std::ranges::find(connector.accounts, name, &BunqAccount::name);
}
void Connecting(Fake::Bunq& bunq) {
const std::uint64_t person = bunq.AddPerson("T. Tester", "key-person");
bunq.AddAccount(person, "NL69BUNQ2025123456", "Bank Account", 50000);
bunq.AddAccount(person, "NL17BUNQ2025654321", "Savings", 100, "MonetaryAccountSavings");
bunq.AddAccount(person, "NL45BUNQ2025111111", "Joint", 200, "MonetaryAccountJoint");
bunq.AddAccount(person, "NL91ABNA0417164300", "Elsewhere", 300, "MonetaryAccountExternal");
bunq.ChangeAccount(bunq.AddAccount(person, "NL02BUNQ2025222222", "Blocked", 400), {{"status", "BLOCKED"}});
bunq.ChangeAccount(bunq.AddAccount(person, "NL03BUNQ2025333333", "Closed", 0), {{"status", "CANCELLED"}});
bunq.ChangeAccount(bunq.AddAccount(person, "NL04BUNQ2025444444", "Dollars", 0), {{"currency", "USD"}});
bunq.ChangeAccount(bunq.AddAccount(person, "NL05BUNQ2025555555", "No balance", 0), {{"balance", nullptr}});
bunq.ChangeAccount(bunq.AddAccount(person, "NL06BUNQ2025666666", "No alias", 0), {{"alias", nullptr}});
{
std::lock_guard lock(bunq.mutex);
bunq.extraAccountItems = {json{{"Unknown", json{{"id", 1}}}}, json{{"A", json::object()}, {"B", json::object()}}, json(5)};
bunq.pageSize = 3;
}
BunqConnector& connector = BunqConnector::Create("key-person", "1.2.3.4, ,5.6.7.8 ", BunqEnvironment::Sandbox);
Equal(connector.name, std::string("T. Tester"), "a person's name is its display name");
Equal(std::format("{}", connector), std::string("T. Tester"), "a connector formats as its name");
Equal(connector.userType, std::string("UserPerson"), "the user type");
Equal(connector.id, person, "the user id");
Equal(connector.ownerId, person, "an API key's owner is its user");
Check(connector.environment == BunqEnvironment::Sandbox && !connector.IsOAuth(), "a sandbox API key connector");
Check(connector.sessionId != 0 && !connector.sessionToken.empty() && connector.serverPublicKey != nullptr, "a session and the server's key");
Check(AccountNames(connector) == std::vector<std::string>{"No alias", "No balance", "Blocked", "Elsewhere", "Joint", "Savings", "Bank Account"}, "open accounts of every kind, across pages, without closed or unknown-currency ones");
Equal(AccountNamed(connector, "Bank Account").bic, std::string("BUNQNL2A"), "a bunq IBAN gets bunq's BIC");
Equal(AccountNamed(connector, "Bank Account").balance, std::int64_t{50000}, "the balance");
Equal(AccountNamed(connector, "Savings").type, std::string("MonetaryAccountSavings"), "the account's kind");
Equal(AccountNamed(connector, "Elsewhere").bic, std::string(""), "an IBAN of another bank gets no BIC");
Equal(AccountNamed(connector, "No balance").balance, std::int64_t{0}, "no balance is zero");
Equal(AccountNamed(connector, "No alias").iban, std::string(""), "no IBAN alias is no IBAN");
Check(AccountNamed(connector, "Bank Account").connector == &connector, "an account points at its connector");
Equal(AccountNamed(connector, "Bank Account").Path(), std::format("/user/{}/monetary-account/{}", person, AccountNamed(connector, "Bank Account").id), "an account's API path");
Equal(AccountNamed(connector, "Bank Account").StorageKey(), std::format("bunq/sandbox/{}/{}", person, AccountNamed(connector, "Bank Account").id), "an account's storage key");
{
std::lock_guard lock(bunq.mutex);
Check(bunq.devices.at("key-person").at("permitted_ips") == json::array({"1.2.3.4", "5.6.7.8"}), "the allowed addresses, trimmed, without empty ones");
bunq.pageSize = 200;
}
for(const Fake::Logged& entry : bunq.Log()) {
Check(!entry.signed_ || entry.signatureValid, std::format("{} {} is signed with the installation's key", entry.method, entry.path));
}
Check(bunq.Count("POST", "/installation") == 1 && bunq.Log().front().signed_ == false, "the installation call is not signed");
// Adding the same user again replaces the connector and ends the old session, even when ending it fails.
const std::size_t logouts = bunq.Count("DELETE", "/session/");
BunqConnector& again = BunqConnector::Create("key-person", "", BunqEnvironment::Sandbox);
Equal(BunqConnector::connectors.size(), std::size_t{1}, "the same user replaces its connector");
Check(&again == &connector, "in place");
Equal(bunq.Count("DELETE", "/session/"), logouts + 1, "the old session is ended");
{
std::lock_guard lock(bunq.mutex);
Check(!bunq.devices.at("key-person").contains("permitted_ips"), "no addresses: the device is bound to the one it is added from");
}
bunq.Fail(Fault{.method = "DELETE", .path = "/session/", .status = 500, .body = "{}"});
BunqConnector::Create("key-person", "*", BunqEnvironment::Sandbox);
Equal(BunqConnector::connectors.size(), std::size_t{1}, "a failed logout of the old session does not stop the new one");
// Every kind of user, and the names bunq gives them.
bunq.AddUser("UserCompany", json{{"name", "Acme B.V."}, {"display_name", "Acme B.V."}}, "key-company");
Equal(BunqConnector::Create("key-company", "*", BunqEnvironment::Sandbox).userType, std::string("UserCompany"), "a company");
bunq.AddUser("UserPaymentServiceProvider", json{{"display_name", ""}, {"name", ""}, {"legal_name", "Legal Name"}}, "key-psp");
Equal(BunqConnector::Create("key-psp", "*", BunqEnvironment::Sandbox).name, std::string("Legal Name"), "the legal name when there is no display name or name");
bunq.AddUser("UserPerson", json{{"public_nick_name", "Nick"}}, "key-nick");
Equal(BunqConnector::Create("key-nick", "*", BunqEnvironment::Sandbox).name, std::string("Nick"), "the nick name last");
bunq.AddUser("UserPerson", json{{"display_name", 7}}, "key-nameless");
Equal(BunqConnector::Create("key-nameless", "*", BunqEnvironment::Sandbox).name, std::string(""), "no name at all");
bunq.Fail(Fault{.method = "POST", .path = "/session-server", .kind = Fault::Kind::SignedReply, .status = 200, .body = R"({"Response":[{"Id":{"id":1}},{"Token":{"token":"t"}},5,{"A":{},"B":{}}]})"});
Throws([] { BunqConnector::Create("key-person", "*", BunqEnvironment::Sandbox); }, "bunq session names no user", "a session without a user");
bunq.Fail(Fault{.method = "POST", .path = "/session-server", .kind = Fault::Kind::SignedReply, .status = 200, .body = R"({"Response":[{"Id":{"id":1}}]})"});
Throws([] { BunqConnector::Create("key-person", "*", BunqEnvironment::Sandbox); }, "bunq response has no 'Token' object", "a session without a token");
Throws<BunqError>([] { BunqConnector::Create("no such key", "*", BunqEnvironment::Sandbox); }, "User credentials are incorrect", "an unknown API key");
Check(BunqConnector::EnvironmentOfKey("sandbox_abc") == BunqEnvironment::Sandbox, "a sandbox key");
Check(BunqConnector::EnvironmentOfKey("abc") == BunqEnvironment::Production, "any other key is production");
}
void OAuth(Fake::Bunq& bunq) {
Equal(BunqConnector::OAuthAuthorizationUrl(BunqEnvironment::Production, "id x", "https://cb/?a=b", "s1"), std::string("https://oauth.bunq.com/auth?response_type=code&client_id=id%20x&redirect_uri=https%3A%2F%2Fcb%2F%3Fa%3Db&state=s1"), "the production authorization URL, encoded");
Equal(BunqConnector::OAuthAuthorizationUrl(BunqEnvironment::Sandbox, "id", "nostro://cb", "s2"), std::string("https://oauth.sandbox.bunq.com/auth?response_type=code&client_id=id&redirect_uri=nostro%3A%2F%2Fcb&state=s2"), "the sandbox one");
const std::uint64_t owner = bunq.AddPerson("O. Owner", "key-owner");
bunq.AddAccount(owner, "NL07BUNQ2025777777", "Shared", 1000);
const std::uint64_t grant = bunq.AddGrant(owner, "code-1", "token-1");
Equal(BunqConnector::OAuthExchangeCode(BunqEnvironment::Sandbox, bunq.clientId, bunq.clientSecret, "https://cb", "code-1"), std::string("token-1"), "a code gives its token");
Throws<BunqError>([&bunq] { BunqConnector::OAuthExchangeCode(BunqEnvironment::Production, bunq.clientId, bunq.clientSecret, "https://cb", "code-1"); }, "The authorization code is invalid or expired. (400)", "a code works once");
bunq.Fail(Fault{.method = "POST", .path = "/token", .kind = Fault::Kind::SignedReply, .status = 200, .body = R"({"token_type":"bearer"})"});
Throws<BunqError>([&bunq] { BunqConnector::OAuthExchangeCode(BunqEnvironment::Sandbox, bunq.clientId, bunq.clientSecret, "https://cb", "code-x"); }, "bunq OAuth token exchange", "an answer without a token");
BunqConnector& connector = BunqConnector::Create("token-1", "*", BunqEnvironment::Sandbox);
Check(connector.IsOAuth() && connector.userType == "UserApiKey", "an OAuth connection");
Equal(connector.id, grant, "its user id is the grant's own");
Equal(connector.ownerId, owner, "its owner is the user who granted access");
Equal(connector.name, std::string("O. Owner"), "and so is its name");
Check(AccountNames(connector) == std::vector<std::string>{"Shared"}, "the granted accounts");
// The same owner with an API key as well would list every account twice.
Throws([] { BunqConnector::Create("key-owner", "*", BunqEnvironment::Sandbox); }, "O. Owner is already connected through OAuth", "an API key for an owner connected through OAuth");
bunq.Fail(Fault{.method = "DELETE", .path = "/session/", .status = 500, .body = "{}"});
Throws([] { BunqConnector::Create("key-owner", "*", BunqEnvironment::Sandbox); }, "already connected through OAuth", "also when ending the refused session fails");
bunq.AddGrant(owner, "code-2", "token-2");
Equal(BunqConnector::Create("token-2", "*", BunqEnvironment::Sandbox).id, bunq.keys.at("token-2"), "a new grant for the owner replaces the old one");
// And the other way round: a grant for an owner connected with an API key.
const std::uint64_t keyed = bunq.AddPerson("K. Keyed", "key-keyed");
BunqConnector::Create("key-keyed", "*", BunqEnvironment::Sandbox);
bunq.AddGrant(keyed, "code-3", "token-3");
Throws([] { BunqConnector::Create("token-3", "*", BunqEnvironment::Sandbox); }, "K. Keyed is already connected with an API key", "a grant for an owner connected with an API key");
bunq.AddUser("UserApiKey", json{{"granted_by_user", json::object()}}, "token-empty");
BunqConnector& empty = BunqConnector::Create("token-empty", "*", BunqEnvironment::Sandbox);
Check(empty.name.empty() && empty.ownerId == empty.id, "a grant that names nobody");
}
void Protocol(Fake::Bunq& bunq, BunqConnector& connector) {
const std::string user = std::format("/user/{}", connector.id);
Check(connector.Get(user).contains("Response"), "a plain call");
Check(connector.Get(std::format("/v1{}", user)).contains("Response"), "a path that already has /v1, as pagination URLs do");
bunq.Fail(Fault{.method = "GET", .kind = Fault::Kind::Unsigned});
Throws([&] { connector.Get(user); }, "the response is not signed by bunq's server key", "an unsigned answer");
bunq.Fail(Fault{.method = "GET", .kind = Fault::Kind::BadSignature});
Throws([&] { connector.Get(user); }, "not signed by bunq's server key", "an answer signed by another key");
bunq.Fail(Fault{.method = "PUT", .kind = Fault::Kind::Reply, .status = 200, .body = "{}"});
Throws([&] { connector.Put(std::format("{}/card/1", user), json::object()); }, "not signed by bunq's server key; the request may have been carried out", "a write whose answer is not signed may have happened");
bunq.Fail(Fault{.method = "GET", .kind = Fault::Kind::SignedReply, .status = 200, .body = "not json"});
Throws([&] { connector.Get(user); }, "unreadable response", "an answer that is not JSON");
bunq.Fail(Fault{.method = "PUT", .kind = Fault::Kind::SignedReply, .status = 200, .body = "not json"});
Throws([&] { connector.Put(std::format("{}/card/1", user), json::object()); }, "may have been carried out", "an unreadable answer to a write");
bunq.Fail(Fault{.method = "DELETE", .kind = Fault::Kind::SignedReply, .status = 200, .body = ""});
Check(connector.Delete(std::format("{}/nothing", user)) == json::object(), "an empty answer is an empty object");
// A rate limit is waited out.
const std::size_t before = bunq.Count("GET", user);
bunq.Fail(Fault{.method = "GET", .status = 429, .body = R"({"Error":[{"error_description":"Too many requests."}]})"});
Check(connector.Get(user).contains("Response"), "a 429 is retried");
Equal(bunq.Count("GET", user), before + 2, "once");
// An ended session is opened again, once, and saved.
const std::string session = connector.sessionToken;
bunq.Fail(Fault{.method = "GET", .status = 401, .body = R"({"Error":[{"error_description":"Session expired."}]})"});
Check(connector.Get(user).contains("Response"), "a 401 opens a new session");
Check(connector.sessionToken != session, "with a new token");
Check(std::filesystem::exists(configPath / "connectors.json"), "which is saved");
bunq.ExpireSessions();
Check(connector.Get(user).contains("Response"), "a 403 Insufficient authentication. opens one too");
bunq.Fail(Fault{.method = "GET", .status = 403, .body = R"({"Error":[{"error_description":"Not allowed."}]})"});
Throws<BunqError>([&] { connector.Get(user); }, "Not allowed. (403)", "another 403 is an error");
bunq.Fail(Fault{.method = "GET", .status = 401, .body = "{}", .times = 2});
Throws<BunqError>([&] { connector.Get(user); }, "(401)", "a session is renewed once per call");
// Errors, and the ways bunq and its OAuth server describe them.
bunq.Fail(Fault{.method = "GET", .status = 500, .body = R"({"Error":[{"error_description":"one"},{"error_description":"two"},{"other":1}]})"});
Throws<BunqError>([&] { connector.Get(user); }, "bunq GET /user/", "a 5xx on a read");
bunq.Fail(Fault{.method = "GET", .status = 400, .body = R"({"Error":[{"error_description":"one"},{"error_description":"two"},{"other":1}]})"});
Throws<BunqError>([&] { connector.Get(user); }, ": one; two (400)", "every error description, joined");
bunq.Fail(Fault{.method = "GET", .status = 400, .body = R"({"error":"x","error_description":"y"})"});
Throws<BunqError>([&] { connector.Get(user); }, ": y (400)", "an OAuth-style description");
bunq.Fail(Fault{.method = "GET", .status = 400, .body = R"({"error":"x"})"});
Throws<BunqError>([&] { connector.Get(user); }, ": x (400)", "an OAuth-style error alone");
bunq.Fail(Fault{.method = "GET", .status = 400, .body = R"({"Error":"not a list"})"});
Throws<BunqError>([&] { connector.Get(user); }, R"({"Error":"not a list"} (400))", "an error body nostro cannot read is shown as it is");
bunq.Fail(Fault{.method = "GET", .status = 400, .body = "plain text"});
Throws<BunqError>([&] { connector.Get(user); }, ": plain text (400)", "an error that is not JSON");
bunq.Fail(Fault{.method = "GET", .status = 400, .body = ""});
Throws<BunqError>([&] { connector.Get(user); }, ": no details (400)", "an empty error");
bunq.Fail(Fault{.method = "PUT", .status = 502, .body = ""});
Throws<BunqError>([&] { connector.Put(std::format("{}/card/1", user), json::object()); }, "(502); the request may have been carried out", "a 5xx leaves a write's outcome open");
try {
connector.Get(std::format("{}/nothing", user));
} catch(const BunqError& e) {
Equal(e.status, std::uint16_t{404}, "a BunqError carries the status");
}
// A connection that cannot be made: a read says so as it is, a write that its outcome is unknown.
BunqConnector::RedirectTo(BunqEndpoint{.host = "127.0.0.1", .port = closedPort, .caPem = ""});
Throws([&] { connector.Get(user); }, "", "a read that cannot connect throws");
Throws([&] { connector.Post(std::format("{}/card", user), json::object()); }, "may have been carried out", "a write that cannot connect may have happened");
bunq.Redirect();
// List follows a listing's pages, adding count to a path with or without a query.
connector.List(std::format("{}/monetary-account?status=ACTIVE", user));
Equal(bunq.Log().back().path, std::format("{}/monetary-account?status=ACTIVE&count=200", user), "count is added to a path with a query");
bunq.Fail(Fault{.method = "GET", .kind = Fault::Kind::SignedReply, .status = 200, .body = R"({"Response":[{"A":{}}]})"});
Equal(connector.List(std::format("{}/card", user)).size(), std::size_t{1}, "a listing without pagination is one page");
}
void Transactions(Fake::Bunq& bunq, BunqConnector& connector) {
BunqAccount& account = AccountNamed(connector, "Bank Account");
const std::uint64_t id = account.id;
bunq.AddPayment(id, 10000, "Employer", "NL91ABNA0417164300", "salary", json{{"counterparty_alias", json{{"iban", "NL91ABNA0417164300"}, {"display_name", "Employer"}, {"swift_bic", "ABNANL2A"}}}});
bunq.AddPayment(id, -250, "Shop", "", "coffee", json{{"type", "MASTERCARD"}, {"counterparty_alias", json{{"iban", nullptr}, {"display_name", "Shop"}}}});
bunq.AddPayment(id, -1000, "Friend", "NL17BUNQ2025654321", "dinner");
bunq.AddPayment(id, -500, "", "", "", json{{"counterparty_alias", json{{"iban", nullptr}, {"label_user", json{{"display_name", "Label User"}}}}}});
bunq.AddPayment(id, 700, "Refund", "NL69BUNQ2025123456", "refund", json{{"sub_type", "REVERSAL"}});
{
std::lock_guard lock(bunq.mutex);
bunq.payments[id].insert(bunq.payments[id].begin() + 2, json{{"Other", json{{"id", 1}}}});
bunq.pageSize = 2;
}
connector.GetNewTransactions(account);
const std::vector<Transaction> first = account.FindTransactions(account.StorageKey(), {});
Equal(first.size(), std::size_t{5}, "the first sync stores the whole history, across pages, skipping what is not a payment");
Equal(first.at(0).kind, std::string("BUNQ/REVERSAL"), "the type and sub type");
Equal(first.at(1).name, std::string("Label User"), "the user's name when the account has none");
Equal(first.at(3).bic, std::string(""), "no IBAN, no BIC");
Equal(first.at(3).kind, std::string("MASTERCARD/PAYMENT"), "a card payment");
Equal(first.at(4).bic, std::string("ABNANL2A"), "a BIC bunq gives");
Equal(first.at(2).bic, std::string("BUNQNL2A"), "bunq's BIC for a bunq IBAN without one");
Equal(first.at(4).amount, std::int64_t{10000}, "the amount");
// A later sync reads only to the last stored payment; one at the very same time with a new id is new.
const std::size_t pages = bunq.Count("GET", std::format("/user/{}/monetary-account/{}/payment", connector.id, id));
const std::string last = bunq.AccountObject(id).at("id").dump();
bunq.AddPayment(id, -100, "Same time", "", "same", json{{"created", Fake::Time(4)}});
bunq.AddPayment(id, -200, "Newest", "", "new");
connector.GetNewTransactions();
const std::vector<Transaction> second = account.FindTransactions(account.StorageKey(), {});
Equal(second.size(), std::size_t{7}, "a later sync adds what is new");
Equal(bunq.Count("GET", std::format("/user/{}/monetary-account/{}/payment", connector.id, id)) - pages, std::size_t{2}, "and stops at what it has");
Check(last.size() > 0, "the account exists");
bunq.Fail(Fault{.method = "GET", .path = std::format("/user/{}/monetary-account/{}/payment", connector.id, id), .kind = Fault::Kind::SignedReply, .status = 200, .body = R"({"Response":[]})"});
connector.GetNewTransactions(account);
Equal(account.FindTransactions(account.StorageKey(), {}).size(), std::size_t{7}, "a page without pagination ends the sync");
std::lock_guard lock(bunq.mutex);
bunq.pageSize = 200;
}
void Cards(Fake::Bunq& bunq, BunqConnector& connector) {
const std::uint64_t active = bunq.AddCard(connector.id, "ACTIVE");
bunq.AddCard(connector.id, "DEACTIVATED", json{{"primary_account_numbers", json::array()}, {"label_monetary_account_current", nullptr}});
{
std::lock_guard lock(bunq.mutex);
bunq.cards[connector.id].push_back(json{{"A", json::object()}, {"B", json::object()}});
}
const std::vector<BunqCard> cards = connector.Cards();
Equal(cards.size(), std::size_t{2}, "the cards, without what is not one");
Equal(cards.at(0).lastFour, std::string("1234"), "the last four digits");
Equal(cards.at(0).iban, std::string("NL01BUNQ0000000001"), "the account it pays from");
Equal(cards.at(0).kind, std::string("CardDebit"), "the kind of card");
Check(cards.at(1).lastFour.empty() && cards.at(1).iban.empty(), "a card without numbers or account");
Equal(std::format("{}", cards.at(0)), std::format("{}\tACTIVE\tMASTERCARD_DEBIT\t**** 1234\tJ. Tester\tNostro\tNL01BUNQ0000000001\texpires 2030-11-30", active), "a card formats as one line");
Equal(connector.SetCardStatus(active, "DEACTIVATED").status, std::string("DEACTIVATED"), "freezing a card");
{
std::lock_guard lock(bunq.mutex);
bunq.cardsActivate = false;
}
Equal(connector.SetCardStatus(active, "ACTIVE").status, std::string("DEACTIVATED"), "the card as bunq keeps it");
bunq.Fail(Fault{.method = "PUT", .kind = Fault::Kind::SignedReply, .status = 200, .body = R"({"Response":[{"Id":{"id":1}}]})"});
Throws([&] { connector.SetCardStatus(active, "ACTIVE"); }, "bunq did not return the card it updated", "an answer without the card");
}
void Sessions(Fake::Bunq& bunq, BunqConnector& connector) {
Check(connector.TestConnector(), "a working connector");
connector.Logout();
Check(connector.sessionToken.empty(), "logging out forgets the session");
connector.Logout();
Check(connector.sessionToken.empty(), "logging out of a session that is gone is fine");
Check(connector.TestConnector(), "a call after logging out opens a new session");
bunq.Fail(Fault{.method = "DELETE", .path = "/session/", .status = 500, .body = "{}"});
Throws<BunqError>([&] { connector.Logout(); }, "(500)", "a logout bunq fails is an error");
{
std::lock_guard lock(bunq.mutex);
bunq.keys.erase("key-company");
}
bunq.ExpireSessions();
BunqConnector& revoked = *std::ranges::find(BunqConnector::connectors, std::string("Acme B.V."), &BunqConnector::name);
Check(!revoked.TestConnector(), "a connector whose key is revoked does not work");
}
// The connector's JSON, through connectors.json as nostro reads and writes it.
void Json(Fake::Bunq& bunq) {
const std::filesystem::path file = configPath / "connectors.json";
// Saved with a live session, so loading needs no renewal.
BunqConnector::connectors.at(0).TestConnector();
Connector::SaveConnectors();
std::ifstream in(file);
json saved = json::parse(in);
const json first = saved.at("bunq").at(0);
Check(first.at("environment") == "sandbox" && first.contains("serverPublicKey") && first.contains("ownerId") && first.contains("sessionId") && first.contains("userType"), "a connector is saved with its environment, server key, owner, session and user type");
// A connector saved before 2026-10-31, and one for production without a server key.
json legacy = first;
for(const std::string field : {"environment", "serverPublicKey", "sessionId", "userType", "ownerId"}) {
legacy.erase(field);
}
json production = first;
production["environment"] = "production";
production.erase("serverPublicKey");
{
std::ofstream out(file);
out << json{{"bunq", json::array({legacy, production})}}.dump();
}
const std::size_t fetched = bunq.Count("GET", "/installation");
Connector::LoadConnectors();
Equal(BunqConnector::connectors.size(), std::size_t{2}, "both load");
const BunqConnector& old = BunqConnector::connectors.at(0);
Check(old.environment == BunqEnvironment::Sandbox && old.ownerId == old.id && old.sessionId == 0 && old.userType.empty(), "an old connector is a sandbox one, owned by its user");
Check(old.serverPublicKey != nullptr && !old.accounts.empty(), "and fetches the server key before its first call");
Check(BunqConnector::connectors.at(1).environment == BunqEnvironment::Production, "the environment reads back");
Equal(bunq.Count("GET", "/installation"), fetched + 4, "each fetches the installation and its key once");
std::ifstream reread(file);
Check(json::parse(reread).at("bunq").at(0).contains("serverPublicKey"), "and the file has it after");
}
void Removing(Fake::Bunq& bunq) {
BunqConnector::connectors.clear();
bunq.AddAccount(bunq.AddPerson("First", "key-first"), "NL08BUNQ2025888888", "First account", 0);
bunq.AddAccount(bunq.AddPerson("Second", "key-second"), "NL09BUNQ2025999999", "Second account", 0);
BunqConnector& first = BunqConnector::Create("key-first", "*", BunqEnvironment::Sandbox);
BunqConnector::Create("key-second", "*", BunqEnvironment::Sandbox);
const std::filesystem::path stored = cachePath / "transactions" / first.StorageKey();
std::filesystem::create_directories(stored);
BunqConnector::Remove(first);
Equal(BunqConnector::connectors.size(), std::size_t{1}, "a connector is removed");
Check(!std::filesystem::exists(stored), "with its stored transactions");
Check(BunqConnector::connectors.front().accounts.front().connector == &BunqConnector::connectors.front(), "the others' accounts point at where their connector is now");
// Removed while this process has its table open, then added again: the account syncs into a new table on
// disk, not into the deleted one.
BunqConnector& second = BunqConnector::connectors.front();
second.GetNewTransactions();
const std::filesystem::path table = cachePath / "transactions" / second.accounts.front().StorageKey() / "Second account.cdb";
Check(std::filesystem::exists(table), "a synced account has its table");
BunqConnector::Remove(second);
Check(!std::filesystem::exists(table), "removing deletes it");
BunqConnector::Create("key-second", "*", BunqEnvironment::Sandbox).GetNewTransactions();
Check(std::filesystem::exists(table), "added again, it syncs into a new table");
BunqConnector stray;
Throws<std::invalid_argument>([&stray] { BunqConnector::Remove(stray); }, "not in BunqConnector::connectors", "a connector that is not listed");
}
}
int main() {
const Test::Directory directory("bunq");
configPath = directory.path / "config";
cachePath = directory.path / "cache";
setenv("TZ", "UTC", 1);
tzset();
// Before anything is redirected: bunq's own hosts.
Equal(BunqConnector::Endpoint(BunqEnvironment::Production).host, std::string("api.bunq.com"), "production's host");
Equal(BunqConnector::Endpoint(BunqEnvironment::Sandbox).host, std::string("public-api.sandbox.bunq.com"), "the sandbox's host");
Equal(BunqConnector::Endpoint(BunqEnvironment::Sandbox).port, std::uint16_t{443}, "on HTTPS's port");
Fake::Bunq bunq(port);
bunq.Redirect();
Equal(BunqConnector::Endpoint(BunqEnvironment::Production).port, port, "a redirect replaces every environment's endpoint");
Connecting(bunq);
OAuth(bunq);
BunqConnector& person = *std::ranges::find(BunqConnector::connectors, std::string("T. Tester"), &BunqConnector::name);
Protocol(bunq, person);
Transactions(bunq, person);
Cards(bunq, person);
Sessions(bunq, person);
Json(bunq);
Removing(bunq);
return Test::Result();
}