// SPDX-License-Identifier: LGPL-3.0-only // SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® // The CLI (implementations/main.cpp), compiled into this test with its main renamed and run in-process, against // nostrod: this executable again, started as a process of its own (nostrod's main is compiled in too), on a fake // system bus (tests/Support/FakeBus.inc) and a fake bunq (tests/Support/FakeBunq.inc). Every command, with stdin fed in // and stdout and stderr read back. The OAuth state comes from RAND_bytes, which this test defines over OpenSSL's so it // can know the state to paste back. #include "../../lib/json.hpp" #include #include #include #include #include #include #include #include #include #include #include #include #include #include import std; import Nostro; import Crafter.Network; #define main NostroMain #include "../../implementations/main.cpp" #undef main #define main NostrodMain #include "../../implementations/nostrod.cpp" #undef main #include "../Support/Check.inc" #include "../Support/FakeBunq.inc" #include "../Support/FakeBus.inc" namespace { // The byte the next RAND_bytes call fills its buffer with, once. std::optional nextRandom; } extern "C" int RAND_bytes(unsigned char* buffer, int count) { if(nextRandom) { std::fill_n(buffer, count, *nextRandom); nextRandom.reset(); return 1; } static const auto real = reinterpret_cast(dlsym(RTLD_NEXT, "RAND_bytes")); return real(buffer, count); } using Test::Check; using Test::Equal; using json = nlohmann::json; using Fault = Fake::Fault; namespace fs = std::filesystem; namespace { constexpr std::uint16_t port = 47304; const std::string annIban = "NL23BUNQ2025123456"; const std::string savingsIban = "NL46BUNQ2025111111"; const std::string bobIban = "NL67BUNQ2025654321"; const std::string carolIban = "NL65BUNQ2025222222"; struct Outcome { std::int32_t code; std::string out; std::string err; }; fs::path outputs; std::string Slurp(const fs::path& file) { std::ifstream in(file, std::ios::binary); return std::string(std::istreambuf_iterator(in), std::istreambuf_iterator()); } // Runs `nostro ` with `input` on stdin, and returns its exit status and what it printed. Outcome Cli(std::vector args, std::string_view input = "") { args.insert(args.begin(), "nostro"); // main's arguments are C strings. // lint-disable-next-line no-char-pointer std::vector argv; for(std::string& arg : args) { argv.push_back(arg.data()); } argv.push_back(nullptr); std::istringstream in{std::string(input)}; std::streambuf* const original = std::cin.rdbuf(in.rdbuf()); std::cin.clear(); std::fflush(stdout); const std::int32_t savedOut = dup(STDOUT_FILENO); const std::int32_t savedErr = dup(STDERR_FILENO); const std::int32_t out = open((outputs / "out").c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0600); const std::int32_t err = open((outputs / "err").c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0600); dup2(out, STDOUT_FILENO); dup2(err, STDERR_FILENO); const std::int32_t code = NostroMain(static_cast(args.size()), argv.data()); std::fflush(stdout); dup2(savedOut, STDOUT_FILENO); dup2(savedErr, STDERR_FILENO); close(out); close(err); close(savedOut); close(savedErr); std::cin.rdbuf(original); return Outcome{code, Slurp(outputs / "out"), Slurp(outputs / "err")}; } // `nostro ` succeeds and prints `part`. void Works(std::vector args, std::string_view part, std::string_view input = "", std::source_location where = std::source_location::current()) { const std::string command = std::format("nostro {}", args | std::views::join_with(' ') | std::ranges::to()); const Outcome outcome = Cli(std::move(args), input); Test::Check(outcome.code == 0, std::format("{} exits 0, not {}: {}", command, outcome.code, outcome.err), where); Test::Check(outcome.out.contains(part), std::format("{} prints '{}', not:\n{}", command, part, outcome.out), where); } // `nostro ` fails and says `part` on stderr. void Fails(std::vector args, std::string_view part, std::string_view input = "", std::source_location where = std::source_location::current()) { const std::string command = std::format("nostro {}", args | std::views::join_with(' ') | std::ranges::to()); const Outcome outcome = Cli(std::move(args), input); Test::Check(outcome.code == 1, std::format("{} exits 1, not {}", command, outcome.code), where); Test::Check(outcome.err.contains(part), std::format("{} says '{}', not:\n{}", command, part, outcome.err), where); } // The first number in what a command printed after `after`, such as an id. std::string IdAfter(std::string_view text, std::string_view after) { const std::size_t at = text.find(after); std::string id; for(std::size_t i = at == std::string_view::npos ? text.size() : at + after.size(); i < text.size() && text[i] >= '0' && text[i] <= '9'; i++) { id += text[i]; } return id; } void Basics() { const Outcome none = Cli({}); Check(none.code == 1 && none.out.contains("usage:"), "no command prints the usage and fails"); Works({"help"}, "usage:"); Works({"--help"}, "usage:"); const Outcome unknown = Cli({"frobnicate"}); Check(unknown.code == 1 && unknown.err.contains("unknown command 'frobnicate'") && unknown.err.contains("usage:"), "an unknown command"); Fails({"accounts", "--limit"}, "--limit needs a value"); Works({"connectors"}, ""); Works({"accounts"}, ""); } void Connecting(Fake::Bunq& bunq) { // The key comes from the prompt, here stdin, never from the command line. Works({"connectors", "add", "bunq", "--sandbox"}, "added Ann (sandbox, 2 accounts)", "key-ann\n"); Works({"connectors", "add", "bunq", "*"}, "added Bob (production, 1 accounts)", "key-bob\n"); Fails({"connectors", "add", "bunq"}, "nothing given for 'bunq API key: '"); Fails({"connectors", "add"}, "connector type not provided"); Fails({"connectors", "add", "unknown"}, "unknown connector type 'unknown'"); Fails({"connectors", "frob"}, "unknown connectors command 'frob'"); // OAuth: the address the browser lands on is pasted back, and its state must be this run's. const std::string state(32, '1'); const std::string redirect = "http://127.0.0.1/cb"; Fails({"connectors", "add", "bunq-oauth", bunq.clientId}, "redirect uri not provided"); Fails({"connectors", "add", "bunq-oauth", bunq.clientId, redirect, "--sandbox"}, "no address given", "fake-secret\n"); Fails({"connectors", "add", "bunq-oauth", bunq.clientId, redirect, "--sandbox"}, "bunq did not authorize: access_denied No", std::format("fake-secret\n{}?error=access_denied&error_description=No\n", redirect)); Fails({"connectors", "add", "bunq-oauth", bunq.clientId, redirect, "--sandbox"}, "bunq did not authorize: access_denied", std::format("fake-secret\n{}?error=access_denied\n", redirect)); Fails({"connectors", "add", "bunq-oauth", bunq.clientId, redirect, "--sandbox"}, "has no code= in it", std::format("fake-secret\n{}?state={}\n", redirect, state)); Fails({"connectors", "add", "bunq-oauth", bunq.clientId, redirect, "--sandbox"}, "its state differs", std::format("fake-secret\n{}?code=code-cli&state=other\n", redirect)); nextRandom = 0x11; const Outcome added = Cli({"connectors", "add", "bunq-oauth", bunq.clientId, redirect, "--sandbox"}, std::format("fake-secret\n{}?code=code-cli&state={}\n", redirect, state)); Check(added.code == 0 && added.out.contains("added Carol through OAuth (sandbox, 1 accounts)"), std::format("an OAuth connection: {}", added.err)); Check(added.out.contains(std::format("https://oauth.sandbox.bunq.com/auth?response_type=code&client_id={}&redirect_uri=http%3A%2F%2F127.0.0.1%2Fcb&state={}", bunq.clientId, state)), "the address to approve at"); Works({"connectors"}, "1\tAnn\tbunq\tsandbox\tapi key\tok"); Works({"connectors"}, "2\tBob\tbunq\tproduction\tapi key\tok"); Works({"connectors"}, "3\tCarol\tbunq\tsandbox\toauth\tok"); Works({"accounts"}, std::format("Ann\tbunq\n\tSavings\tBUNQNL2A {}\t€1.00\n\tMain\tBUNQNL2A {}\t€1000.00", savingsIban, annIban)); } void History(Fake::Bunq& bunq, std::uint64_t main) { bunq.AddPayment(main, -250, "Cafe", "", "coffee"); bunq.AddPayment(main, -1000, "Grocer", "", "food"); Works({"transactions", annIban}, "-€10.00\tGrocer\t\tfood"); Works({"transactions", annIban, "--search", "COFFEE", "--amount", "-250", "--from", "2026-10-01", "--to", "2026-10-01", "--limit", "5"}, "-€2.50\tCafe\t\tcoffee"); const Outcome late = Cli({"transactions", annIban, "--to", "2026-10-01 09:00"}); Check(late.code == 0 && late.out.empty(), "a time of day is when the range ends"); Fails({"transactions", annIban, "--limit", "x"}, "limit 'x' is not a whole number"); Fails({"transactions", annIban, "--from", "soon"}, "is not a date"); Fails({"transactions", "Main"}, "2 accounts are called 'Main': use the IBAN"); Fails({"transactions", "Nope"}, "no account is called or has IBAN 'Nope'"); Fails({"transactions"}, "account not provided"); } void Paying(Fake::Bunq& bunq) { Works({"send", annIban, std::string(bobIban), "Bob", "1250", "lunch"}, "sent €12.50 to Bob (payment "); Works({"send", "Savings", std::string(annIban), "Ann", "100"}, "sent €1.00 to Ann"); Fails({"send", annIban, std::string(bobIban), "Bob", "12.50"}, "give it in the smallest unit, 1250 for 12.50"); Fails({"send", annIban, std::string(bobIban), "Bob", "12,50"}, "give it in the smallest unit"); Fails({"send", annIban, std::string(bobIban), "Bob", "lots"}, "amount 'lots' is not a whole number"); bunq.Fail(Fault{.method = "POST", .path = "/user/", .status = 400, .body = R"({"Error":[{"error_description":"Not enough money."}]})"}); const Outcome refused = Cli({"send", annIban, std::string(bobIban), "Bob", "100"}); Check(refused.code == 1 && refused.err.contains("Not enough money.") && !refused.err.contains("OAuth"), "bunq's refusal, as it is"); bunq.Fail(Fault{.method = "POST", .path = "/user/", .status = 403, .body = R"({"Error":[{"error_description":"Not allowed for this user."}]})"}); Fails({"send", std::string(carolIban), std::string(bobIban), "Bob", "100"}, "added through OAuth, which can only pay your own accounts"); Works({"draft", annIban, std::string(bobIban), "Bob", "200", "to accept"}, "drafted €2.00 to Bob (draft "); const std::string draft = IdAfter(Cli({"drafts", annIban}).out, ""); Works({"drafts", annIban}, "PENDING\tAnn"); Works({"drafts", annIban, "accept", draft}, std::format("accepted draft {}", draft)); Works({"draft", annIban, std::string(bobIban), "Bob", "300"}, "drafted €3.00"); Works({"drafts", annIban, "reject", IdAfter(Cli({"drafts", annIban}).out, "")}, "rejected draft"); Fails({"drafts", annIban, "accept"}, "draft id not provided"); Works({"schedule", annIban, std::string(bobIban), "Bob", "300", "2027-01-01", "monthly", "rent", "--every", "2", "--until", "2027-12-31"}, "scheduled €3.00 to Bob (schedule "); Works({"schedule", annIban, std::string(bobIban), "Bob", "400", "2027-01-01 08:00", "Weekly"}, "scheduled €4.00"); Fails({"schedule", annIban, std::string(bobIban), "Bob", "400", "2027-01-01", "fortnightly"}, "'FORTNIGHTLY' is not a schedule"); Fails({"schedule", annIban, std::string(bobIban), "Bob", "400", "2027-01-01", "daily", "--every", "-1"}, "--every '-1' is not a whole number"); Works({"scheduled", annIban}, "every 2 months from"); const std::string schedule = IdAfter(Cli({"scheduled", annIban}).out, ""); Works({"scheduled", annIban, "cancel", schedule}, std::format("cancelled schedule {}", schedule)); } void Requesting() { Works({"request", std::string(bobIban), annIban, "Ann", "500", "pay me back"}, "PENDING\tAnn"); Works({"requests", std::string(bobIban)}, "€5.00\tpay me back\thttps://bunq.me/"); Works({"incoming", annIban}, "PENDING\tINTERNAL\tBob"); const std::string incoming = IdAfter(Cli({"incoming", annIban}).out, ""); Works({"incoming", annIban, "accept", incoming}, std::format("paid request {}", incoming)); Works({"request", std::string(bobIban), annIban, "Ann", "600", "again"}, "PENDING"); Works({"incoming", annIban, "reject", IdAfter(Cli({"incoming", annIban}).out, "")}, "rejected request"); Works({"request", std::string(bobIban), annIban, "Ann", "700"}, "PENDING"); const std::string request = IdAfter(Cli({"requests", std::string(bobIban)}).out, ""); Works({"requests", std::string(bobIban), "revoke", request}, std::format("revoked request {}", request)); Fails({"requests", std::string(bobIban), "revoke", "x"}, "request id 'x' is not a whole number"); } void Cards(Fake::Bunq& bunq, std::uint64_t ann) { const std::string card = std::to_string(bunq.AddCard(ann, "ACTIVE")); Works({"cards"}, std::format("Ann\tbunq\n\t{}\tACTIVE", card)); Works({"cards", "freeze", card}, std::format("card {} is now DEACTIVATED", card)); { std::lock_guard lock(bunq.mutex); bunq.cardsActivate = false; } Fails({"cards", "unfreeze", card}, std::format("bunq kept card {} DEACTIVATED (its order status is VIRTUAL_DELIVERY)", card)); Works({"cards", "lost", card}, std::format("card {} is now LOST", card)); Fails({"cards", "melt", card}, "unknown card action 'melt'"); Fails({"cards", "freeze", "1"}, "no card has id 1"); Fails({"cards", "freeze"}, "card id not provided"); } void Checkouts() { Works({"checkout", "account"}, "no account pays at checkout: `nostro checkout account ` chooses one"); Works({"checkout", "account", annIban}, std::format("checkouts pay from Main\tBUNQNL2A {}\t€", annIban)); Works({"checkout", "account"}, std::format("Main\tBUNQNL2A {}", annIban)); Fails({"checkout", "account", std::string(carolIban)}, "is reached through OAuth, which pays only your own accounts"); Fails({"checkout", "accounts"}, "unknown checkout command 'accounts'"); Fails({"checkout"}, "checkout command not provided"); } void Removing(Fake::Bunq& bunq) { bunq.AddAccount(bunq.AddPerson("Ann", "key-ann2"), "NL84BUNQ2025333333", "Other", 0); Works({"connectors", "add", "bunq"}, "added Ann (production", "key-ann2\n"); Fails({"connectors", "remove", "Ann"}, "2 connectors are called 'Ann': use the number"); Fails({"connectors", "remove", "Nobody"}, "no connector is called or numbered 'Nobody'"); Works({"connectors", "remove", "4"}, "removed Ann"); { std::lock_guard lock(bunq.mutex); bunq.keys.erase("key-bob"); } bunq.ExpireSessions(); Works({"connectors"}, "2\tBob\tbunq\tproduction\tapi key\tfailing"); const Outcome listed = Cli({"accounts"}); Check(listed.code == 0 && listed.err.contains("bunq connector 'Bob' is unavailable"), std::format("a connector that does not work is a note: {}", listed.err)); Works({"connectors", "remove", "Bob"}, "removed Bob"); bunq.Fail(Fault{.method = "DELETE", .path = "/session/", .status = 500, .body = "{}"}); const Outcome forced = Cli({"connectors", "remove", "Carol"}); Check(forced.code == 0 && forced.out.contains("removed Carol") && forced.err.contains("could not log out, forgetting the connector anyway"), std::format("a connector that cannot log out is removed anyway: {}", forced.err)); const Outcome left = Cli({"connectors"}); Check(left.out.contains("1\tAnn") && !left.out.contains("Bob") && !left.out.contains("Carol"), "what is left"); } } // main's signature is C's. // lint-disable-next-line no-char-pointer int main(int argc, char* argv[]) { // nostrod, and each of its workers, is this executable again. if(Fake::IsNostrod()) { Fake::Bunq::RedirectFromEnvironment(); return NostrodMain(argc, argv); } const Test::Directory directory("cli"); outputs = directory.path; setenv("TZ", "UTC", 1); tzset(); // What nostrod reads from the environment is set before any thread starts. Fake::Bunq::ExportRedirect(port, directory.path / "bunq.pem"); setenv("DBUS_SYSTEM_BUS_ADDRESS", Fake::Bus::Address(directory.path / "bus").c_str(), 1); Fake::Bus bus(directory.path / "bus"); { std::lock_guard lock(bus.mutex); bus.logindNames[bus.clientUid] = "tester"; } Fake::Bunq bunq(port); const std::uint64_t ann = bunq.AddPerson("Ann", "key-ann"); const std::uint64_t annMain = bunq.AddAccount(ann, annIban, "Main", 100000); bunq.AddAccount(ann, savingsIban, "Savings", 100); bunq.AddAccount(bunq.AddPerson("Bob", "key-bob"), bobIban, "Main", 0); const std::uint64_t carol = bunq.AddPerson("Carol", "key-carol"); bunq.AddAccount(carol, carolIban, "Shared", 500); bunq.AddGrant(carol, "code-cli", "token-carol"); const pid_t nostrod = Fake::StartNostrod({"--state", (directory.path / "state").string()}); Check(bus.WaitForName("net.catcrafts.Nostro1"), "nostrod is on the bus"); Basics(); Connecting(bunq); History(bunq, annMain); Paying(bunq); Requesting(); Cards(bunq, ann); Checkouts(); Removing(bunq); bus.Disconnect("net.catcrafts.Nostro1"); Equal(Fake::Wait(nostrod), 0, "nostrod ends when the bus goes"); Check(bus.WaitForName("net.catcrafts.Nostro1.Checkout", false), "and its checkout with it"); return Test::Result(); }