cli MVP
This commit is contained in:
parent
367c19386c
commit
1ea50c50bc
62 changed files with 9982 additions and 608 deletions
106
tests/ShouldHandleMoneyAndText/main.cpp
Normal file
106
tests/ShouldHandleMoneyAndText/main.cpp
Normal file
|
|
@ -0,0 +1,106 @@
|
|||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
// Currencies and amounts (Nostro:Currency) and the text helpers (Nostro:Utils): every parse with what it refuses,
|
||||
// every format, and the local-time helpers with a fixed time zone so the expectations hold anywhere.
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <time.h>
|
||||
|
||||
import std;
|
||||
import Nostro;
|
||||
|
||||
#include "../Support/Check.inc"
|
||||
|
||||
using namespace Nostro;
|
||||
using Test::Check;
|
||||
using Test::Equal;
|
||||
using Test::Throws;
|
||||
|
||||
namespace {
|
||||
void Currencies() {
|
||||
Check(GetCurrency("EUR") == Currency::Euro, "EUR is the euro");
|
||||
Check(GetCurrency("eur") == Currency::Euro, "eur is the euro");
|
||||
Throws([] { GetCurrency("USD"); }, "unsupported currency 'USD'", "an unknown currency is refused");
|
||||
Equal(GetCurrencyCode(Currency::Euro), std::string_view("EUR"), "code");
|
||||
Equal(GetCurrencySymbol(Currency::Euro), std::string_view("€"), "symbol");
|
||||
Equal(GetCurrencyDecimals(Currency::Euro), std::uint8_t{2}, "decimals");
|
||||
Equal(std::format("{}", Currency::Euro), std::string("€"), "a currency formats as its symbol");
|
||||
}
|
||||
|
||||
void Amounts() {
|
||||
Equal(ParseAmount("12.50", Currency::Euro), std::int64_t{1250}, "a whole amount with cents");
|
||||
Equal(ParseAmount("12", Currency::Euro), std::int64_t{1200}, "an amount without a fraction");
|
||||
Equal(ParseAmount("12.5", Currency::Euro), std::int64_t{1250}, "a fraction shorter than the decimals");
|
||||
Equal(ParseAmount("-0.05", Currency::Euro), std::int64_t{-5}, "a negative amount");
|
||||
for(const std::string_view bad : {"", ".5", "-", "1.234", "1a.00", "1.0x", "+1"}) {
|
||||
Throws([bad] { ParseAmount(bad, Currency::Euro); }, "malformed amount", std::format("'{}' is refused", bad));
|
||||
}
|
||||
|
||||
Equal(FormatAmount(1250, Currency::Euro), std::string("12.50"), "cents format with a point");
|
||||
Equal(FormatAmount(5, Currency::Euro), std::string("0.05"), "less than a unit gets its leading zeros");
|
||||
Equal(FormatAmount(0, Currency::Euro), std::string("0.00"), "zero");
|
||||
Equal(FormatAmount(-5, Currency::Euro), std::string("-0.05"), "a negative amount");
|
||||
Equal(FormatAmount(std::numeric_limits<std::int64_t>::min(), Currency::Euro), std::string("-92233720368547758.08"), "the most negative amount");
|
||||
Equal(FormatMoney(-102, Currency::Euro), std::string("-€1.02"), "money puts the sign before the symbol");
|
||||
Equal(FormatMoney(102, Currency::Euro), std::string("€1.02"), "and no sign when positive");
|
||||
}
|
||||
|
||||
void Escaping() {
|
||||
Equal(EscB("a\"b\\c\nd\re\tf\x01g"), std::string("a\\\"b\\\\c\\nd\\re\\tf\\u0001g"), "JSON escaping of every kind of character");
|
||||
}
|
||||
|
||||
void Timestamps() {
|
||||
using namespace std::chrono;
|
||||
const system_clock::time_point time = sys_days(year(2026) / 10 / 31) + hours(12) + minutes(34) + seconds(56) + microseconds(123456);
|
||||
Check(ParseTimestamp("2026-10-31 12:34:56.123456") == time, "a timestamp with microseconds");
|
||||
Check(ParseTimestamp("2026-10-31 12:34:56.1") == time - microseconds(23456), "a short fraction counts in tenths");
|
||||
Check(ParseTimestamp("2026-10-31 12:34:56") == time - microseconds(123456), "a timestamp without a fraction");
|
||||
for(const std::string_view bad : {"2026-10-31", "2026/10-31 12:34:56", "2026-10/31 12:34:56", "2026-10-31T12:34:56", "2026-10-31 12-34:56", "2026-10-31 12:34-56", "20x6-10-31 12:34:56", "2026-10-31 12:34:56.", "2026-10-31 12:34:56.1234567", "2026-10-31 12:34:56x1", "2026-02-30 12:34:56", "2026-10-31 12:34:5x"}) {
|
||||
Throws([bad] { ParseTimestamp(bad); }, "malformed timestamp", std::format("'{}' is refused", bad));
|
||||
}
|
||||
Equal(FormatTimestamp(time), std::string("2026-10-31 12:34:56.123456"), "FormatTimestamp is ParseTimestamp's inverse");
|
||||
}
|
||||
|
||||
void LocalTime() {
|
||||
// Amsterdam: the clocks went back on 2026-10-25, so that day lasted 25 hours.
|
||||
setenv("TZ", "Europe/Amsterdam", 1);
|
||||
tzset();
|
||||
using namespace std::chrono;
|
||||
Check(ParseLocalDate("2026-10-31") == sys_days(year(2026) / 10 / 30) + hours(23), "a date is local midnight");
|
||||
Check(ParseLocalDate("2026-10-31 09:30") == sys_days(year(2026) / 10 / 31) + hours(8) + minutes(30), "a date and time is local");
|
||||
Check(ParseLocalDate("2026-10-25", 1) - ParseLocalDate("2026-10-25") == hours(25), "a day of the clock change counts by the calendar");
|
||||
Check(ParseLocalDate("2026-10-31", 1) == ParseLocalDate("2026-11-01"), "a day on crosses the month");
|
||||
for(const std::string_view bad : {"2026-10-3", "2026/10/31", "2026-10-31T09:30", "2026-10-31 09-30", "2026-1x-31", "2026-02-30", "2026-10-31 24:00", "2026-10-31 23:60"}) {
|
||||
Throws([bad] { ParseLocalDate(bad); }, "is not a date", std::format("'{}' is refused", bad));
|
||||
}
|
||||
Equal(FormatLocalTime(sys_days(year(2026) / 10 / 31) + hours(8) + minutes(30)), std::string("2026-10-31 09:30"), "local time format");
|
||||
}
|
||||
|
||||
void Urls() {
|
||||
Equal(UrlEncode("a-b_c.d~e f/g?h=i&j"), std::string("a-b_c.d~e%20f%2Fg%3Fh%3Di%26j"), "everything but the unreserved characters is encoded");
|
||||
Equal(UrlEncode("é"), std::string("%C3%A9"), "bytes above 0x7F are encoded one by one");
|
||||
Equal(UrlDecode("a%20b+c%2Fd%2f"), std::string("a b c/d/"), "percent escapes and a plus decode");
|
||||
Equal(UrlDecode("100%"), std::string("100%"), "a bare percent stays");
|
||||
Equal(UrlDecode("%zz%2"), std::string("%zz%2"), "an escape without two hex digits stays");
|
||||
Equal(UrlDecode("%Aa"), std::string("\xaa"), "hex digits of either case");
|
||||
|
||||
const std::string_view url = "https://example.com/cb?code=a%2Bb&state=x+y&empty=&flag#state=fragment";
|
||||
Equal(QueryParameter(url, "code").value_or("none"), std::string("a+b"), "a parameter is decoded");
|
||||
Equal(QueryParameter(url, "state").value_or("none"), std::string("x y"), "the fragment is not part of the query");
|
||||
Equal(QueryParameter(url, "empty").value_or("none"), std::string(""), "an empty value");
|
||||
Equal(QueryParameter(url, "flag").value_or("none"), std::string(""), "a name without a value");
|
||||
Check(!QueryParameter(url, "missing"), "a parameter that is not there");
|
||||
Check(!QueryParameter("https://example.com/cb", "code"), "a URL without a query");
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
Currencies();
|
||||
Amounts();
|
||||
Escaping();
|
||||
Timestamps();
|
||||
LocalTime();
|
||||
Urls();
|
||||
return Test::Result();
|
||||
}
|
||||
123
tests/ShouldKeepFilesPrivate/main.cpp
Normal file
123
tests/ShouldKeepFilesPrivate/main.cpp
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
// The file layer (Nostro:File): where the config and cache live, private files and what CreatePrivateFile refuses,
|
||||
// and ReadSecret from a pipe and from a terminal, where it must not echo.
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/stat.h>
|
||||
#include <termios.h>
|
||||
#include <unistd.h>
|
||||
|
||||
import std;
|
||||
import Nostro;
|
||||
|
||||
#include "../Support/Check.inc"
|
||||
|
||||
using namespace Nostro;
|
||||
using Test::Check;
|
||||
using Test::Equal;
|
||||
using Test::Throws;
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
namespace {
|
||||
void Paths() {
|
||||
const std::string home = std::getenv("HOME") ? std::string(std::getenv("HOME")) : std::string();
|
||||
setenv("XDG_CONFIG_HOME", "/xdg/config", 1);
|
||||
setenv("XDG_CACHE_HOME", "/xdg/cache", 1);
|
||||
Equal(GetConfigPath().string(), std::string("/xdg/config/.config/nostro"), "the config path under XDG_CONFIG_HOME");
|
||||
Equal(GetCachePath().string(), std::string("/xdg/cache/nostro"), "the cache path under XDG_CACHE_HOME");
|
||||
unsetenv("XDG_CONFIG_HOME");
|
||||
unsetenv("XDG_CACHE_HOME");
|
||||
setenv("HOME", "/home/tester", 1);
|
||||
Equal(GetConfigPath().string(), std::string("/home/tester/.config/nostro"), "the config path under HOME");
|
||||
Equal(GetCachePath().string(), std::string("/home/tester/.cache/nostro"), "the cache path under HOME");
|
||||
unsetenv("HOME");
|
||||
Throws([] { GetConfigPath(); }, "XDG_CONFIG_HOME and HOME not set", "no config path without either variable");
|
||||
Throws([] { GetCachePath(); }, "XDG_CACHE_HOME and HOME not set", "no cache path without either variable");
|
||||
setenv("HOME", home.c_str(), 1);
|
||||
}
|
||||
|
||||
std::uint32_t Mode(const fs::path& path) {
|
||||
struct stat info{};
|
||||
stat(path.c_str(), &info);
|
||||
return info.st_mode & 0777;
|
||||
}
|
||||
|
||||
void PrivateFiles(const fs::path& root) {
|
||||
const fs::path file = root / "a" / "b" / "secret.json";
|
||||
CreatePrivateFile(file);
|
||||
Check(fs::is_regular_file(file), "the file is made, with the directories above it");
|
||||
Equal(Mode(file), std::uint32_t{0600}, "the file is private");
|
||||
Equal(Mode(file.parent_path()), std::uint32_t{0700}, "and so is its directory");
|
||||
CreatePrivateFile(file);
|
||||
Check(fs::is_regular_file(file), "making it again changes nothing");
|
||||
|
||||
// Neither the directory nor the file can be made inside a directory that is not writable.
|
||||
const fs::path locked = root / "locked";
|
||||
fs::create_directory(locked);
|
||||
chmod(locked.c_str(), 0500);
|
||||
Throws<std::system_error>([&locked] { CreatePrivateFile(locked / "inner" / "file"); }, "cannot create", "a directory that cannot be made");
|
||||
Throws<std::system_error>([&locked] { CreatePrivateFile(locked / "file"); }, "cannot create", "a file that cannot be made");
|
||||
chmod(locked.c_str(), 0700);
|
||||
}
|
||||
|
||||
// Runs ReadSecret with `input` behind std::cin and something that is no terminal as stdin.
|
||||
std::string SecretFrom(std::string_view input) {
|
||||
std::istringstream in{std::string(input)};
|
||||
std::streambuf* const original = std::cin.rdbuf(in.rdbuf());
|
||||
std::string secret;
|
||||
try {
|
||||
secret = ReadSecret("Key: ");
|
||||
} catch(...) {
|
||||
std::cin.rdbuf(original);
|
||||
throw;
|
||||
}
|
||||
std::cin.rdbuf(original);
|
||||
return secret;
|
||||
}
|
||||
|
||||
void Secrets() {
|
||||
const std::int32_t saved = dup(STDIN_FILENO);
|
||||
const std::int32_t null = open("/dev/null", O_RDONLY);
|
||||
dup2(null, STDIN_FILENO);
|
||||
Equal(SecretFrom(" my key \r\n"), std::string("my key"), "a secret is trimmed");
|
||||
Equal(SecretFrom(" \t \n"), std::string(""), "a line of spaces is no secret");
|
||||
Throws([] { SecretFrom(""); }, "nothing given for 'Key: '", "stdin ending before a line");
|
||||
|
||||
// On a terminal the typing is not echoed while it is read, and echoing is back afterwards.
|
||||
const std::int32_t master = posix_openpt(O_RDWR | O_NOCTTY);
|
||||
grantpt(master);
|
||||
unlockpt(master);
|
||||
std::array<char, 128> name{};
|
||||
ptsname_r(master, name.data(), name.size());
|
||||
const std::int32_t terminal = open(name.data(), O_RDWR | O_NOCTTY);
|
||||
dup2(terminal, STDIN_FILENO);
|
||||
clearerr(stdin);
|
||||
std::cin.clear();
|
||||
const std::string typed = "typed secret\n";
|
||||
write(master, typed.data(), typed.size());
|
||||
Equal(ReadSecret("Key: "), std::string("typed secret"), "a secret typed on a terminal");
|
||||
termios after{};
|
||||
tcgetattr(STDIN_FILENO, &after);
|
||||
Check((after.c_lflag & ECHO) != 0, "echoing is back on after reading");
|
||||
|
||||
dup2(saved, STDIN_FILENO);
|
||||
close(terminal);
|
||||
close(master);
|
||||
close(null);
|
||||
close(saved);
|
||||
clearerr(stdin);
|
||||
std::cin.clear();
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
const Test::Directory directory("files");
|
||||
Paths();
|
||||
PrivateFiles(directory.path);
|
||||
Secrets();
|
||||
return Test::Result();
|
||||
}
|
||||
251
tests/ShouldMoveMoney/main.cpp
Normal file
251
tests/ShouldMoveMoney/main.cpp
Normal file
|
|
@ -0,0 +1,251 @@
|
|||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
// Moving money through the bunq connector, against a fake bunq (tests/Support/FakeBunq.inc): counterparties and what
|
||||
// they refuse, payments, draft payments, scheduled payments, requests both ways, and how each lists and formats.
|
||||
|
||||
#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 namespace std::chrono;
|
||||
using Test::Check;
|
||||
using Test::Equal;
|
||||
using Test::Throws;
|
||||
using json = nlohmann::json;
|
||||
using Fault = Fake::Fault;
|
||||
|
||||
namespace {
|
||||
constexpr std::uint16_t port = 47303;
|
||||
constexpr std::string_view payerIban = "NL23BUNQ2025123456";
|
||||
constexpr std::string_view payeeIban = "NL67BUNQ2025654321";
|
||||
|
||||
json LastBody(Fake::Bunq& bunq, std::string_view method) {
|
||||
const std::vector<Fake::Logged> log = bunq.Log();
|
||||
const auto last = std::ranges::find_if(log.rbegin(), log.rend(), [method](const Fake::Logged& entry) { return entry.method == method; });
|
||||
return json::parse(last->body);
|
||||
}
|
||||
|
||||
void Counterparties() {
|
||||
const BunqCounterparty email = BunqCounterparty::Parse(" someone@example.com ", "Someone");
|
||||
Check(email.type == "EMAIL" && email.value == "someone@example.com" && email.name == "Someone", "an e-mail address, trimmed");
|
||||
const BunqCounterparty phone = BunqCounterparty::Parse("+31 6-1234 (5678)", "");
|
||||
Check(phone.type == "PHONE_NUMBER" && phone.value == "+31612345678", "a phone number without its spaces, dashes and brackets");
|
||||
Throws<std::invalid_argument>([] { BunqCounterparty::Parse("+31x6", ""); }, "is not a phone number", "a phone number with a letter");
|
||||
Throws<std::invalid_argument>([] { BunqCounterparty::Parse("+3161", ""); }, "is not a phone number", "a phone number too short");
|
||||
const BunqCounterparty iban = BunqCounterparty::Parse(" nl23 bunq 2025 1234 56 ", "Payer");
|
||||
Check(iban.type == "IBAN" && iban.value == payerIban, "an IBAN, upper case and without spaces");
|
||||
for(const std::string_view bad : {"NL23BUNQ2025123457", "NL23BUNQ", "1L23BUNQ2025123456", "N123BUNQ2025123456", "NLX3BUNQ2025123456", "NL2XBUNQ2025123456", "NL23BUNQ2025-23456", "NL23BUNQ20251234561234567890123456"}) {
|
||||
Throws<std::invalid_argument>([bad] { BunqCounterparty::Parse(bad, ""); }, "is not a valid IBAN", std::format("'{}' is refused", bad));
|
||||
}
|
||||
}
|
||||
|
||||
void Payments(Fake::Bunq& bunq, BunqAccount& payer, BunqAccount& payee) {
|
||||
const std::uint64_t id = payer.Send(payeeIban, "Payee", 1250, Currency::Euro, "lunch \"together\"");
|
||||
Check(id != 0, "a payment gets an id");
|
||||
const json sent = LastBody(bunq, "POST");
|
||||
Check(sent.at("amount") == json{{"value", "12.50"}, {"currency", "EUR"}}, "the amount goes as a decimal string");
|
||||
Check(sent.at("counterparty_alias") == json{{"type", "IBAN"}, {"value", payeeIban}, {"name", "Payee"}}, "the counterparty, with its name");
|
||||
Equal(sent.at("description").get<std::string>(), std::string("lunch \"together\""), "the description, quotes and all");
|
||||
Check(bunq.Log().back().signed_ && bunq.Log().back().signatureValid, "a signed payment");
|
||||
payee.connector->GetNewTransactions(payee);
|
||||
Equal(payee.FindTransactions(payee.StorageKey(), {}).at(0).amount, std::int64_t{1250}, "the payee gets it");
|
||||
|
||||
payer.Send("someone@example.com", "", 100, Currency::Euro, "");
|
||||
Check(!LastBody(bunq, "POST").at("counterparty_alias").contains("name"), "no name, no name field");
|
||||
Throws<std::invalid_argument>([&payer] { payer.Send(payeeIban, "Payee", 0, Currency::Euro, ""); }, "more than zero", "nothing to send");
|
||||
Throws<std::invalid_argument>([&payer] { payer.Send(payeeIban, "Payee", -5, Currency::Euro, ""); }, "more than zero", "a negative amount");
|
||||
}
|
||||
|
||||
void Drafts(Fake::Bunq& bunq, BunqAccount& payer) {
|
||||
const std::uint64_t accepted = payer.Draft(payeeIban, "Payee", 200, Currency::Euro, "to accept");
|
||||
const std::uint64_t rejected = payer.Draft(payeeIban, "Payee", 300, Currency::Euro, "to reject");
|
||||
Check(LastBody(bunq, "POST").at("number_of_required_accepts") == 1, "one accept makes a draft a payment");
|
||||
std::vector<BunqDraftPayment> drafts = payer.DraftPayments();
|
||||
Equal(drafts.size(), std::size_t{2}, "both drafts list");
|
||||
Check(drafts.at(0).id == rejected && drafts.at(0).status == "PENDING" && drafts.at(0).createdBy == "Payer", "newest first, pending, with who made it");
|
||||
Check(drafts.at(0).entries.size() == 1 && drafts.at(0).entries.at(0).amount == 300 && drafts.at(0).entries.at(0).counterparty.iban == payeeIban, "its entry");
|
||||
Equal(std::format("{}", drafts.at(0)), std::format("{}\tPENDING\tPayer\n\tPayee {}\t€3.00\tto reject", rejected, payeeIban), "a draft formats with a line per entry");
|
||||
|
||||
const std::size_t paid = bunq.Count("POST", "/");
|
||||
const BunqDraftPayment shown = payer.DraftPayment(accepted);
|
||||
Check(shown.id == accepted && shown.entries.at(0).amount == 200 && !shown.updated.empty(), "one draft, as bunq has it, with when it last changed");
|
||||
payer.RespondToDraftPayment(shown, true);
|
||||
Check(LastBody(bunq, "PUT").at("status") == "ACCEPTED" && LastBody(bunq, "PUT").at("previous_updated_timestamp") == shown.updated, "accepting names the draft as it was shown");
|
||||
payer.RespondToDraftPayment(payer.DraftPayment(rejected), false);
|
||||
Equal(LastBody(bunq, "PUT").at("status").get<std::string>(), std::string("REJECTED"), "rejecting");
|
||||
drafts = payer.DraftPayments();
|
||||
Check(drafts.at(0).status == "REJECTED" && drafts.at(1).status == "ACCEPTED", "the drafts' new states");
|
||||
Equal(bunq.Count("POST", "/"), paid, "a response is a PUT, not a new payment");
|
||||
|
||||
// A draft bunq lists without an updated time, a creator or entries.
|
||||
{
|
||||
std::lock_guard lock(bunq.mutex);
|
||||
json& draft = bunq.drafts[payer.id].at(0).at("DraftPayment");
|
||||
draft.erase("updated");
|
||||
bunq.drafts[payer.id].push_back(json{{"DraftPayment", json{{"id", 1}, {"status", "PENDING"}, {"entries", "none"}}}});
|
||||
bunq.drafts[payer.id].push_back(json{{"DraftPayment", json{{"id", 3}, {"status", "PENDING"}, {"entries", json::array({json{{"amount", Fake::Amount(250)}, {"counterparty_alias", json{{"display_name", "Positive"}}}}})}}}});
|
||||
bunq.drafts[payer.id].push_back(json{{"SomethingElse", json{{"id", 2}}}});
|
||||
}
|
||||
payer.RespondToDraftPayment(payer.DraftPayment(rejected), false);
|
||||
Check(!LastBody(bunq, "PUT").contains("previous_updated_timestamp"), "a draft without an updated time is answered without one");
|
||||
drafts = payer.DraftPayments();
|
||||
Equal(drafts.size(), std::size_t{4}, "an object that is no draft is skipped");
|
||||
Check(drafts.at(2).createdBy.empty() && drafts.at(2).entries.empty(), "a draft without a creator or entries");
|
||||
Check(drafts.at(3).entries.at(0).amount == 250, "an entry bunq lists as positive stays positive");
|
||||
|
||||
// A draft that changed after it was shown is refused, not accepted unseen.
|
||||
const BunqDraftPayment before = payer.DraftPayment(payer.Draft(payeeIban, "Payee", 400, Currency::Euro, "to change"));
|
||||
{
|
||||
std::lock_guard lock(bunq.mutex);
|
||||
json& draft = bunq.drafts[payer.id].at(0).at("DraftPayment");
|
||||
draft.at("entries").at(0)["amount"] = Fake::Amount(-40000);
|
||||
draft["updated"] = Fake::Time(999);
|
||||
}
|
||||
Throws<BunqError>([&payer, &before] { payer.RespondToDraftPayment(before, true); }, "changed in the meantime", "accepting a draft that changed since it was shown");
|
||||
}
|
||||
|
||||
void Schedules(Fake::Bunq& bunq, BunqAccount& payer) {
|
||||
const system_clock::time_point start = sys_days(year(2027) / 1 / 1);
|
||||
const std::uint64_t monthly = payer.Schedule(payeeIban, "Payee", 300, Currency::Euro, "rent", BunqSchedule{.start = start, .end = start + days(365), .unit = "MONTHLY", .every = 1});
|
||||
const json body = LastBody(bunq, "POST");
|
||||
Check(body.at("schedule") == json{{"time_start", "2027-01-01 00:00:00.000000"}, {"time_end", "2028-01-01 00:00:00.000000"}, {"recurrence_unit", "MONTHLY"}, {"recurrence_size", 1}}, "the schedule in UTC");
|
||||
Check(body.at("payment").at("amount") == json{{"value", "3.00"}, {"currency", "EUR"}}, "the payment it makes");
|
||||
const std::uint64_t weekly = payer.Schedule(payeeIban, "Payee", 400, Currency::Euro, "allowance", BunqSchedule{.start = start, .unit = "WEEKLY", .every = 2});
|
||||
Check(!LastBody(bunq, "POST").at("schedule").contains("time_end"), "no end, no end time");
|
||||
Throws<std::invalid_argument>([&] { payer.Schedule(payeeIban, "Payee", 1, Currency::Euro, "", BunqSchedule{.start = start, .unit = "FORTNIGHTLY"}); }, "is not a schedule", "an unknown recurrence");
|
||||
Throws<std::invalid_argument>([&] { payer.Schedule(payeeIban, "Payee", 1, Currency::Euro, "", BunqSchedule{.start = start, .unit = "DAILY", .every = 0}); }, "at least every 1", "every 0");
|
||||
|
||||
std::vector<BunqScheduledPayment> scheduled = payer.ScheduledPayments();
|
||||
Equal(scheduled.size(), std::size_t{2}, "both schedules list");
|
||||
Check(scheduled.at(0).id == weekly && scheduled.at(0).amount == 400 && scheduled.at(0).schedule.unit == "WEEKLY" && scheduled.at(0).schedule.every == 2 && !scheduled.at(0).schedule.end, "the weekly one, its amount positive");
|
||||
Check(scheduled.at(1).id == monthly && scheduled.at(1).schedule.end == start + days(365) && scheduled.at(1).schedule.next == start && scheduled.at(1).schedule.status == "ACTIVE", "the monthly one, with its end and next run");
|
||||
{
|
||||
std::lock_guard lock(bunq.mutex);
|
||||
bunq.scheduledName = "SchedulePayment";
|
||||
bunq.schedules[payer.id].push_back(json{{"ScheduledPayment", json{{"id", 3}, {"payment", json{{"amount", Fake::Amount(100)}, {"counterparty_alias", json{{"display_name", "Old"}}}}}, {"schedule", json{{"time_start", "2026-01-01 00:00:00"}, {"recurrence_unit", "ONCE"}, {"status", "FINISHED"}}}}}});
|
||||
}
|
||||
scheduled = payer.ScheduledPayments();
|
||||
Equal(scheduled.size(), std::size_t{3}, "listed under the spec's name too");
|
||||
Check(scheduled.back().schedule.status == "FINISHED" && !scheduled.back().schedule.next && scheduled.back().schedule.every == 1, "a status inside the schedule, no next run, every 1 by default");
|
||||
Equal(scheduled.back().amount, std::int64_t{100}, "an amount bunq lists as positive stays positive");
|
||||
|
||||
payer.CancelScheduledPayment(weekly);
|
||||
Equal(payer.ScheduledPayments().size(), std::size_t{2}, "a cancelled schedule is gone");
|
||||
}
|
||||
|
||||
void Requests(Fake::Bunq& bunq, BunqAccount& payer, BunqAccount& payee) {
|
||||
const BunqPaymentRequest asked = payee.Request(payerIban, "Payer", 500, Currency::Euro, "pay me back");
|
||||
Check(asked.status == "PENDING" && asked.amount == 500 && !asked.amountPaid && asked.shareUrl.starts_with("https://bunq.me/"), "a request, with a bunq.me link");
|
||||
Check(LastBody(bunq, "POST").at("allow_bunqme") == true, "bunq.me is allowed");
|
||||
std::vector<BunqIncomingRequest> incoming = payer.IncomingRequests();
|
||||
Equal(incoming.size(), std::size_t{1}, "the payer sees it");
|
||||
Check(incoming.at(0).type == "INTERNAL" && incoming.at(0).status == "PENDING" && incoming.at(0).counterparty.iban == payeeIban, "who asks, and how");
|
||||
const BunqIncomingRequest one = payer.IncomingRequest(incoming.at(0).id);
|
||||
Check(one.id == incoming.at(0).id && one.amount == 500 && one.counterparty.iban == payeeIban, "one request, as bunq has it");
|
||||
payer.RespondToRequest(incoming.at(0), true);
|
||||
Check(LastBody(bunq, "PUT").at("amount_responded") == json{{"value", "5.00"}, {"currency", "EUR"}}, "accepting pays the amount asked");
|
||||
const BunqPaymentRequest paid = payee.Requests().at(0);
|
||||
Check(paid.status == "ACCEPTED" && paid.amountPaid == 500, "the asker sees it paid");
|
||||
|
||||
payee.Request(payerIban, "Payer", 600, Currency::Euro, "again");
|
||||
payer.RespondToRequest(payer.IncomingRequests().at(0), false);
|
||||
Equal(LastBody(bunq, "PUT"), json{{"status", "REJECTED"}}, "rejecting");
|
||||
const BunqPaymentRequest revoked = payee.Request(payerIban, "Payer", 700, Currency::Euro, "never mind");
|
||||
payee.RevokeRequest(revoked.id);
|
||||
Equal(LastBody(bunq, "PUT"), json{{"status", "REVOKED"}}, "revoking");
|
||||
const std::vector<BunqPaymentRequest> requests = payee.Requests();
|
||||
Check(requests.at(0).status == "REVOKED" && requests.at(1).status == "REJECTED", "the requests' states");
|
||||
|
||||
// A request whose amount changes after it was shown is paid as shown.
|
||||
payee.Request(payerIban, "Payer", 1000, Currency::Euro, "changes");
|
||||
const BunqIncomingRequest shown = payer.IncomingRequests().at(0);
|
||||
{
|
||||
std::lock_guard lock(bunq.mutex);
|
||||
bunq.responses[payer.id].at(0).at("RequestResponse")["amount_inquired"] = Fake::Amount(99900);
|
||||
}
|
||||
payer.RespondToRequest(shown, true);
|
||||
Check(LastBody(bunq, "PUT").at("amount_responded") == json{{"value", "10.00"}, {"currency", "EUR"}}, "accepting pays the amount shown, not the one asked since");
|
||||
|
||||
// A request that was made but cannot be read back is still the request it is, and says so in a note.
|
||||
std::vector<std::string> notes;
|
||||
const std::function<void(std::string_view)> stderrSink = noteSink;
|
||||
noteSink = [¬es](std::string_view note) { notes.emplace_back(note); };
|
||||
bunq.Fail(Fault{.method = "GET", .path = std::format("/user/{}/monetary-account/{}/request-inquiry/", payee.connector->id, payee.id), .status = 500, .body = "{}"});
|
||||
const BunqPaymentRequest unread = payee.Request(payerIban, "Payer", 800, Currency::Euro, "unread");
|
||||
noteSink = stderrSink;
|
||||
Check(unread.id != 0 && unread.status == "PENDING" && unread.counterparty.iban == payerIban && unread.shareUrl.empty(), "made, pending, without a link");
|
||||
Check(notes.size() == 1 && notes.at(0).contains("was made, but reading it back failed"), "the failed read-back goes to the note sink");
|
||||
bunq.Fail(Fault{.method = "GET", .path = std::format("/user/{}/monetary-account/{}/request-inquiry/", payee.connector->id, payee.id), .status = 500, .body = "{}"});
|
||||
Check(payee.Request("someone@example.com", "Someone", 900, Currency::Euro, "").counterparty.iban.empty(), "one asked by e-mail has no IBAN");
|
||||
Throws<std::invalid_argument>([&payee] { payee.Request(payerIban, "Payer", 0, Currency::Euro, ""); }, "more than zero", "asking for nothing");
|
||||
|
||||
{
|
||||
std::lock_guard lock(bunq.mutex);
|
||||
bunq.inquiries[payee.id].push_back(json{{"RequestInquiry", json{{"id", 1}, {"amount_inquired", Fake::Amount(100)}, {"counterparty_alias", json::object()}}}});
|
||||
bunq.inquiries[payee.id].push_back(json{{"Other", json{{"id", 2}}}});
|
||||
}
|
||||
const BunqPaymentRequest bare = payee.Requests().back();
|
||||
Check(bare.created == system_clock::time_point() && bare.status.empty(), "a request without a time or status");
|
||||
}
|
||||
|
||||
void Formats() {
|
||||
const system_clock::time_point at = sys_days(year(2026) / 10 / 31) + hours(9);
|
||||
Equal(std::format("{}", BunqLabel{"Name", "NL01"}), std::string("Name NL01"), "a label with an IBAN");
|
||||
Equal(std::format("{}", BunqLabel{"Name", ""}), std::string("Name"), "a label without one");
|
||||
|
||||
BunqPaymentRequest request{.id = 1, .status = "ACCEPTED", .counterparty = {"Payer", ""}, .currency = Currency::Euro, .amount = 500, .amountPaid = 500, .description = "pay", .created = at, .shareUrl = ""};
|
||||
Equal(std::format("{}", request), std::string("1\t2026-10-31 09:00\tACCEPTED\tPayer\t€5.00\tpay"), "a request paid in full");
|
||||
request.amountPaid = 400;
|
||||
request.shareUrl = "https://bunq.me/x";
|
||||
Equal(std::format("{}", request), std::string("1\t2026-10-31 09:00\tACCEPTED\tPayer\t€5.00 (paid €4.00)\tpay\thttps://bunq.me/x"), "a request paid in part, with its link");
|
||||
|
||||
const BunqIncomingRequest incoming{.id = 2, .status = "PENDING", .type = "DIRECT_DEBIT", .counterparty = {"Utility", "NL02"}, .currency = Currency::Euro, .amount = 3000, .description = "energy", .created = at};
|
||||
Equal(std::format("{}", incoming), std::string("2\t2026-10-31 09:00\tPENDING\tDIRECT_DEBIT\tUtility NL02\t€30.00\tenergy"), "an incoming request");
|
||||
|
||||
BunqScheduledPayment scheduled{.id = 3, .counterparty = {"Landlord", ""}, .currency = Currency::Euro, .amount = 90000, .description = "rent", .schedule = BunqSchedule{.start = at, .end = std::nullopt, .unit = "ONCE", .every = 1, .status = "ACTIVE", .next = at}};
|
||||
Equal(std::format("{}", scheduled), std::string("3\tACTIVE\tonce on 2026-10-31 09:00, next 2026-10-31 09:00\tLandlord\t€900.00\trent"), "a payment scheduled once");
|
||||
scheduled.schedule.unit = "MONTHLY";
|
||||
scheduled.schedule.end = at + days(1);
|
||||
scheduled.schedule.status = "FINISHED";
|
||||
Equal(std::format("{}", scheduled), std::string("3\tFINISHED\tmonthly from 2026-10-31 09:00 until 2026-11-01 09:00\tLandlord\t€900.00\trent"), "a finished monthly one, without its next run");
|
||||
for(const auto& [unit, words] : std::map<std::string, std::string>{{"HOURLY", "every 3 hours"}, {"DAILY", "every 3 days"}, {"WEEKLY", "every 3 weeks"}, {"MONTHLY", "every 3 months"}, {"YEARLY", "every 3 years"}}) {
|
||||
scheduled.schedule.unit = unit;
|
||||
scheduled.schedule.every = 3;
|
||||
Check(std::format("{}", scheduled).contains(words), std::format("{} every 3 is '{}'", unit, words));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
const Test::Directory directory("money");
|
||||
configPath = directory.path / "config";
|
||||
cachePath = directory.path / "cache";
|
||||
setenv("TZ", "UTC", 1);
|
||||
tzset();
|
||||
|
||||
Fake::Bunq bunq(port);
|
||||
bunq.Redirect();
|
||||
bunq.AddAccount(bunq.AddPerson("Payer", "key-payer"), payerIban, "Payer", 100000);
|
||||
bunq.AddAccount(bunq.AddPerson("Payee", "key-payee"), payeeIban, "Payee", 0);
|
||||
BunqConnector::Create("key-payer", "*", BunqEnvironment::Sandbox);
|
||||
BunqConnector::Create("key-payee", "*", BunqEnvironment::Sandbox);
|
||||
BunqAccount& payer = BunqConnector::connectors.at(0).accounts.at(0);
|
||||
BunqAccount& payee = BunqConnector::connectors.at(1).accounts.at(0);
|
||||
|
||||
Counterparties();
|
||||
Payments(bunq, payer, payee);
|
||||
Drafts(bunq, payer);
|
||||
Schedules(bunq, payer);
|
||||
Requests(bunq, payer, payee);
|
||||
Formats();
|
||||
return Test::Result();
|
||||
}
|
||||
336
tests/ShouldRunCommands/main.cpp
Normal file
336
tests/ShouldRunCommands/main.cpp
Normal file
|
|
@ -0,0 +1,336 @@
|
|||
// 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 <dlfcn.h>
|
||||
#include <fcntl.h>
|
||||
#include <poll.h>
|
||||
#include <spawn.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/resource.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/un.h>
|
||||
#include <sys/wait.h>
|
||||
#include <systemd/sd-bus.h>
|
||||
#include <systemd/sd-id128.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
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<std::uint8_t> 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<int (*)(unsigned char*, int)>(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<char>(in), std::istreambuf_iterator<char>());
|
||||
}
|
||||
|
||||
// Runs `nostro <args>` with `input` on stdin, and returns its exit status and what it printed.
|
||||
Outcome Cli(std::vector<std::string> 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<char*> 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<std::int32_t>(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 <args>` succeeds and prints `part`.
|
||||
void Works(std::vector<std::string> 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<std::string>());
|
||||
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 <args>` fails and says `part` on stderr.
|
||||
void Fails(std::vector<std::string> 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<std::string>());
|
||||
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 <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();
|
||||
}
|
||||
178
tests/ShouldSaveConnectors/main.cpp
Normal file
178
tests/ShouldSaveConnectors/main.cpp
Normal file
|
|
@ -0,0 +1,178 @@
|
|||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
// connectors.json and its lock (Nostro:Connector), against a fake bunq (tests/Support/FakeBunq.inc): loading what is
|
||||
// there, what is not and what is broken, saving through a synced rename, and every way the lock and the save can fail.
|
||||
// A failing flock or fsync cannot be had on demand, so this test defines its own, which the linker takes over libc's:
|
||||
// they do what the test scripts, and call libc's when there is no script.
|
||||
|
||||
#include "../../lib/json.hpp"
|
||||
#include <dlfcn.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <signal.h>
|
||||
#include <sys/file.h>
|
||||
#include <sys/resource.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
import std;
|
||||
import Nostro;
|
||||
import Crafter.Network;
|
||||
|
||||
#include "../Support/Check.inc"
|
||||
#include "../Support/FakeBunq.inc"
|
||||
|
||||
namespace {
|
||||
// What the next calls answer, with the errno they leave, before libc's own calls take over again.
|
||||
std::deque<std::pair<std::int32_t, std::int32_t>> flockScript;
|
||||
std::deque<std::pair<std::int32_t, std::int32_t>> fsyncScript;
|
||||
}
|
||||
|
||||
extern "C" int flock(int fd, int operation) {
|
||||
if(!flockScript.empty()) {
|
||||
const auto [result, error] = flockScript.front();
|
||||
flockScript.pop_front();
|
||||
errno = error;
|
||||
return result;
|
||||
}
|
||||
static const auto real = reinterpret_cast<int (*)(int, int)>(dlsym(RTLD_NEXT, "flock"));
|
||||
return real(fd, operation);
|
||||
}
|
||||
|
||||
extern "C" int fsync(int fd) {
|
||||
if(!fsyncScript.empty()) {
|
||||
const auto [result, error] = fsyncScript.front();
|
||||
fsyncScript.pop_front();
|
||||
errno = error;
|
||||
return result;
|
||||
}
|
||||
static const auto real = reinterpret_cast<int (*)(int)>(dlsym(RTLD_NEXT, "fsync"));
|
||||
return real(fd);
|
||||
}
|
||||
|
||||
using namespace Nostro;
|
||||
using Test::Check;
|
||||
using Test::Equal;
|
||||
using Test::Throws;
|
||||
using json = nlohmann::json;
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
namespace {
|
||||
constexpr std::uint16_t port = 47301;
|
||||
|
||||
std::string Read(const fs::path& file) {
|
||||
std::ifstream in(file, std::ios::binary);
|
||||
return std::string(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
|
||||
}
|
||||
|
||||
void Write(const fs::path& file, std::string_view text) {
|
||||
std::ofstream out(file, std::ios::binary);
|
||||
out << text;
|
||||
}
|
||||
|
||||
void Locking() {
|
||||
const fs::path lock = configPath / "connectors.lock";
|
||||
fs::create_directories(lock);
|
||||
Throws<std::system_error>([] { Connector::LoadConnectors(); }, "cannot open", "a lock file that cannot be opened");
|
||||
fs::remove(lock);
|
||||
|
||||
flockScript = {{-1, ENOLCK}};
|
||||
Throws<std::system_error>([] { Connector::LoadConnectors(); }, "cannot lock", "a lock that fails");
|
||||
flockScript = {{-1, EWOULDBLOCK}, {-1, EINTR}, {-1, ENOLCK}};
|
||||
Throws<std::system_error>([] { Connector::LoadConnectors(); }, "cannot lock", "a wait for the lock that fails");
|
||||
Check(flockScript.empty(), "the wait goes on after a signal");
|
||||
|
||||
// Held by another process, then free: nostro waits, through a signal, and goes on.
|
||||
flockScript = {{-1, EWOULDBLOCK}, {-1, EINTR}, {0, 0}};
|
||||
Connector::LoadConnectors();
|
||||
Check(flockScript.empty(), "the lock is taken after waiting");
|
||||
Check(BunqConnector::connectors.empty(), "no file is no connectors");
|
||||
Connector::LoadConnectors();
|
||||
Check(flockScript.empty(), "and kept: the next load does not lock again");
|
||||
}
|
||||
|
||||
void Loading(Fake::Bunq& bunq) {
|
||||
const fs::path file = configPath / "connectors.json";
|
||||
Write(file, "{ not json");
|
||||
Throws<std::runtime_error>([] { Connector::LoadConnectors(); }, "is not valid JSON", "a broken file");
|
||||
// Broken inside a key: the error says where, never what the file holds there.
|
||||
Write(file, R"({"bunq": [{"privateKey": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADAN)");
|
||||
std::string cutShort;
|
||||
try {
|
||||
Connector::LoadConnectors();
|
||||
} catch(const std::runtime_error& e) {
|
||||
cutShort = e.what();
|
||||
}
|
||||
Check(cutShort.contains("breaks at byte") && !cutShort.contains("MIIE") && !cutShort.contains("PRIVATE"), std::format("a key cut short is not quoted: {}", cutShort));
|
||||
Write(file, "{}");
|
||||
Connector::LoadConnectors();
|
||||
Check(BunqConnector::connectors.empty(), "a file without bunq's key has no bunq connectors");
|
||||
|
||||
bunq.AddAccount(bunq.AddPerson("Saver", "key-saver"), "NL23BUNQ2025123456", "Savings", 100);
|
||||
BunqConnector::Create("key-saver", "*", BunqEnvironment::Sandbox);
|
||||
Connector::SaveConnectors();
|
||||
struct stat info{};
|
||||
stat(file.c_str(), &info);
|
||||
Equal(info.st_mode & 0777, std::uint32_t{0600}, "the file is private");
|
||||
Check(!fs::exists(configPath / std::format("connectors.json.tmp-{}", getpid())), "no temporary file is left");
|
||||
|
||||
// A connector whose key bunq no longer knows loads without accounts, beside one that works.
|
||||
json saved = json::parse(Read(file));
|
||||
json broken = saved.at("bunq").at(0);
|
||||
broken["apiKey"] = "revoked";
|
||||
broken["sessionToken"] = "ended";
|
||||
saved.at("bunq").push_back(broken);
|
||||
Write(file, saved.dump());
|
||||
BunqConnector::connectors.clear();
|
||||
Connector::LoadConnectors();
|
||||
Equal(BunqConnector::connectors.size(), std::size_t{2}, "both connectors load");
|
||||
Equal(BunqConnector::connectors.at(0).accounts.size(), std::size_t{1}, "the working one has its account");
|
||||
Check(BunqConnector::connectors.at(1).accounts.empty(), "the broken one has none, and the load goes on");
|
||||
BunqConnector::connectors.pop_back();
|
||||
Connector::SaveConnectors();
|
||||
}
|
||||
|
||||
void Saving() {
|
||||
const fs::path file = configPath / "connectors.json";
|
||||
const std::string before = Read(file);
|
||||
const fs::path temporary = configPath / std::format("connectors.json.tmp-{}", getpid());
|
||||
|
||||
fs::create_directories(temporary);
|
||||
Throws<std::system_error>([] { Connector::SaveConnectors(); }, "cannot open", "a temporary file that cannot be opened");
|
||||
fs::remove(temporary);
|
||||
|
||||
// A file size limit makes the write fail part way.
|
||||
signal(SIGXFSZ, SIG_IGN);
|
||||
rlimit limit{};
|
||||
getrlimit(RLIMIT_FSIZE, &limit);
|
||||
const rlimit small{.rlim_cur = 16, .rlim_max = limit.rlim_max};
|
||||
setrlimit(RLIMIT_FSIZE, &small);
|
||||
Throws<std::system_error>([] { Connector::SaveConnectors(); }, "cannot write", "a write that fails");
|
||||
setrlimit(RLIMIT_FSIZE, &limit);
|
||||
Check(!fs::exists(temporary), "a failed write leaves no temporary file");
|
||||
|
||||
fsyncScript = {{-1, EIO}};
|
||||
Throws<std::system_error>([] { Connector::SaveConnectors(); }, "cannot sync", "a sync that fails");
|
||||
Check(!fs::exists(temporary), "nor does a failed sync");
|
||||
Equal(Read(file), before, "and the old file is as it was");
|
||||
|
||||
Connector::SaveConnectors();
|
||||
Check(Read(file) == before, "a save that works writes the same");
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
const Test::Directory directory("connectors");
|
||||
configPath = directory.path / "config";
|
||||
cachePath = directory.path / "cache";
|
||||
fs::create_directories(configPath);
|
||||
|
||||
Fake::Bunq bunq(port);
|
||||
bunq.Redirect();
|
||||
|
||||
Locking();
|
||||
Loading(bunq);
|
||||
Saving();
|
||||
return Test::Result();
|
||||
}
|
||||
813
tests/ShouldServeEveryUser/main.cpp
Normal file
813
tests/ShouldServeEveryUser/main.cpp
Normal file
|
|
@ -0,0 +1,813 @@
|
|||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
// nostrod on a fake system bus (tests/Support/FakeBus.inc) in front of a fake bunq (tests/Support/FakeBunq.inc): the
|
||||
// daemon and its workers are this executable again (nostrod's main is compiled in), every call goes through
|
||||
// Nostro::Client or Nostro::Checkout, and the bus plays each user by the uid it gives a connection. Users kept apart, a
|
||||
// uid handed to a new user, every polkit answer and what the dialog is told, calls that wait on each other or do not,
|
||||
// checkouts and their retries, workers that die, idle exits, and how each error reaches the client.
|
||||
|
||||
#include "../../lib/json.hpp"
|
||||
#include <poll.h>
|
||||
#include <signal.h>
|
||||
#include <spawn.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/resource.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/un.h>
|
||||
#include <sys/wait.h>
|
||||
#include <systemd/sd-bus.h>
|
||||
#include <systemd/sd-id128.h>
|
||||
#include <unistd.h>
|
||||
|
||||
import std;
|
||||
import Nostro;
|
||||
import Nostro.Checkout;
|
||||
import Crafter.Network;
|
||||
|
||||
#define main NostrodMain
|
||||
#include "../../implementations/nostrod.cpp"
|
||||
#undef main
|
||||
|
||||
#include "../Support/Check.inc"
|
||||
#include "../Support/FakeBunq.inc"
|
||||
#include "../Support/FakeBus.inc"
|
||||
|
||||
using namespace Nostro;
|
||||
using Test::Check;
|
||||
using Test::Equal;
|
||||
using Test::Throws;
|
||||
using json = nlohmann::json;
|
||||
using Fault = Fake::Fault;
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
namespace {
|
||||
constexpr std::uint16_t port = 47305;
|
||||
constexpr std::uint32_t aliceUid = 4242;
|
||||
constexpr std::uint32_t bobUid = 4343;
|
||||
constexpr std::string_view name = "net.catcrafts.Nostro1";
|
||||
constexpr std::string_view checkoutName = "net.catcrafts.Nostro1.Checkout";
|
||||
const std::string aliceMain = "NL23BUNQ2025123456";
|
||||
const std::string aliceOther = "NL46BUNQ2025111111";
|
||||
const std::string closingIban = "NL09BUNQ2025999999";
|
||||
const std::string lateIban = "NL08BUNQ2025888888";
|
||||
const std::string bobIban = "NL67BUNQ2025654321";
|
||||
const std::string carolIban = "NL65BUNQ2025222222";
|
||||
const std::string daveIban = "NL84BUNQ2025333333";
|
||||
const std::string briefIban = "NL06BUNQ2025444444";
|
||||
const std::string shopIban = "NL91ABNA0417164300";
|
||||
|
||||
// The users and accounts at the fake bunq.
|
||||
struct Bank {
|
||||
std::uint64_t alice = 0;
|
||||
std::uint64_t aliceMainId = 0;
|
||||
std::uint64_t closingId = 0;
|
||||
};
|
||||
|
||||
struct Failure {
|
||||
std::string name;
|
||||
std::string message;
|
||||
};
|
||||
|
||||
// How `call` failed: the D-Bus name of nostrod's error, "exception" for any other, "none" when it did not fail.
|
||||
template<typename Call>
|
||||
Failure FailureOf(Call&& call) {
|
||||
try {
|
||||
call();
|
||||
} catch(const DaemonError& e) {
|
||||
return Failure{e.name, e.what()};
|
||||
} catch(const Checkout::Error& e) {
|
||||
return Failure{e.name, e.what()};
|
||||
} catch(const std::exception& e) {
|
||||
return Failure{"exception", e.what()};
|
||||
}
|
||||
return Failure{"none", ""};
|
||||
}
|
||||
|
||||
// A client for user `uid`: the fake bus gives each new connection the uid it is set to.
|
||||
Client As(Fake::Bus& bus, std::uint32_t uid) {
|
||||
{
|
||||
std::lock_guard lock(bus.mutex);
|
||||
bus.clientUid = uid;
|
||||
}
|
||||
return Client::System();
|
||||
}
|
||||
|
||||
void SetPolkit(Fake::Bus& bus, Fake::Polkit outcome, std::string_view action = {}) {
|
||||
std::lock_guard lock(bus.mutex);
|
||||
if(action.empty()) {
|
||||
bus.polkit = outcome;
|
||||
bus.polkitByAction.clear();
|
||||
} else {
|
||||
bus.polkitByAction[std::string(action)] = outcome;
|
||||
}
|
||||
}
|
||||
|
||||
std::string Summary(Fake::Bus& bus) {
|
||||
const Fake::PolkitCheck check = bus.LastCheck();
|
||||
return check.details.contains("summary") ? check.details.at("summary") : std::string();
|
||||
}
|
||||
|
||||
std::string Slurp(const fs::path& file) {
|
||||
std::ifstream in(file);
|
||||
return std::string(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
|
||||
}
|
||||
|
||||
// Stops every worker, as systemd stops a service, and waits until nostrod has seen them go.
|
||||
void KillWorkers(Fake::Bus& bus, pid_t nostrod) {
|
||||
for(const pid_t pid : bus.Peers()) {
|
||||
if(pid != nostrod) {
|
||||
kill(pid, SIGTERM);
|
||||
}
|
||||
}
|
||||
for(std::size_t i = 0; i < 300 && std::ranges::any_of(bus.Peers(), [nostrod](pid_t pid) { return pid != nostrod; }); i++) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
||||
}
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(300));
|
||||
}
|
||||
|
||||
// A call made by hand, as alice, for what Client never sends; the name of the error it got, or empty when it worked.
|
||||
template<typename Build>
|
||||
std::string Raw(Fake::Bus& bus, std::string_view destination, std::string_view interface, std::string_view member, bool interactive, Build&& build) {
|
||||
{
|
||||
std::lock_guard lock(bus.mutex);
|
||||
bus.clientUid = aliceUid;
|
||||
}
|
||||
sd_bus* raw = nullptr;
|
||||
sd_bus_open_system(&raw);
|
||||
sd_bus_set_allow_interactive_authorization(raw, interactive ? 1 : 0);
|
||||
sd_bus_message* call = nullptr;
|
||||
sd_bus_message_new_method_call(raw, &call, std::string(destination).c_str(), "/net/catcrafts/Nostro1", std::string(interface).c_str(), std::string(member).c_str());
|
||||
build(call);
|
||||
sd_bus_error error = SD_BUS_ERROR_NULL;
|
||||
sd_bus_message* reply = nullptr;
|
||||
const std::int32_t result = sd_bus_call(raw, call, 0, &error, &reply);
|
||||
const std::string failed = result < 0 ? std::string(error.name) : std::string();
|
||||
sd_bus_error_free(&error);
|
||||
sd_bus_message_unref(reply);
|
||||
sd_bus_message_unref(call);
|
||||
sd_bus_flush_close_unref(raw);
|
||||
return failed;
|
||||
}
|
||||
|
||||
// The element of interface `interface` in an introspection document, empty when it has none, with the whitespace
|
||||
// between and inside tags brought down to what XML needs, so the published file and nostrod's own document compare.
|
||||
std::string Interface(std::string_view xml, std::string_view interface) {
|
||||
const std::size_t start = xml.find(std::format("<interface name=\"{}\">", interface));
|
||||
if(start == std::string_view::npos) {
|
||||
return {};
|
||||
}
|
||||
const std::string_view element = xml.substr(start, xml.find("</interface>", start) - start);
|
||||
std::string out;
|
||||
bool space = false;
|
||||
for(const char c : element) {
|
||||
if(c == ' ' || c == '\n' || c == '\t') {
|
||||
space = true;
|
||||
continue;
|
||||
}
|
||||
if(space && !out.empty() && out.back() != '>' && c != '<' && c != '/') {
|
||||
out += ' ';
|
||||
}
|
||||
space = false;
|
||||
out += c;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// The introspection document of nostrod's object under `destination`, asked as alice.
|
||||
std::string Introspect(Fake::Bus& bus, std::string_view destination) {
|
||||
{
|
||||
std::lock_guard lock(bus.mutex);
|
||||
bus.clientUid = aliceUid;
|
||||
}
|
||||
sd_bus* raw = nullptr;
|
||||
sd_bus_open_system(&raw);
|
||||
sd_bus_error error = SD_BUS_ERROR_NULL;
|
||||
sd_bus_message* reply = nullptr;
|
||||
sd_bus_call_method(raw, std::string(destination).c_str(), "/net/catcrafts/Nostro1", "org.freedesktop.DBus.Introspectable", "Introspect", &error, &reply, "");
|
||||
// sd-bus hands strings out as C strings.
|
||||
// lint-disable-next-line no-char-pointer
|
||||
const char* document = nullptr;
|
||||
sd_bus_message_read(reply, "s", &document);
|
||||
std::string served(document ? document : "");
|
||||
sd_bus_error_free(&error);
|
||||
sd_bus_message_unref(reply);
|
||||
sd_bus_flush_close_unref(raw);
|
||||
return served;
|
||||
}
|
||||
|
||||
// The published contract: packaging/dbus/net.catcrafts.Nostro1.xml and net.catcrafts.Nostro1.Checkout.xml are the
|
||||
// interfaces nostrod serves, each under its own name alone, and the polkit policy declares every action nostrod asks
|
||||
// about and no other, each owned by the user nostrod runs as, with a dialog that uses no detail nostrod does not set.
|
||||
void Contract(Fake::Bus& bus) {
|
||||
const std::string served = Introspect(bus, name);
|
||||
Check(Interface(served, name) == Interface(Slurp("packaging/dbus/net.catcrafts.Nostro1.xml"), name), std::format("packaging/dbus/net.catcrafts.Nostro1.xml is the interface nostrod serves, which is:\n{}", served));
|
||||
const std::string checkout = Introspect(bus, checkoutName);
|
||||
Check(Interface(checkout, checkoutName) == Interface(Slurp("packaging/dbus/net.catcrafts.Nostro1.Checkout.xml"), checkoutName), std::format("packaging/dbus/net.catcrafts.Nostro1.Checkout.xml is the checkout nostrod serves, which is:\n{}", checkout));
|
||||
// An app allowed to talk to the checkout's name reaches nothing else through it.
|
||||
Check(Interface(served, checkoutName).empty() && Interface(checkout, name).empty(), "each name serves its own interface alone");
|
||||
Check(!Raw(bus, checkoutName, name, "Connectors", true, [](sd_bus_message*) {}).empty(), "the checkout's name answers no other method");
|
||||
const std::string payHere = Raw(bus, name, checkoutName, "Pay", true, [](sd_bus_message* call) {
|
||||
sd_bus_message_append(call, "ssxssa{sv}", shopIban.c_str(), "Shop", std::int64_t{100}, "EUR", "1", 0u);
|
||||
});
|
||||
Check(!payHere.empty(), "and the other name pays no checkout");
|
||||
|
||||
const std::string policy = Slurp("packaging/system/net.catcrafts.Nostro1.policy");
|
||||
std::vector<std::string> declared;
|
||||
for(std::size_t at = policy.find("<action id=\""); at != std::string::npos; at = policy.find("<action id=\"", at + 1)) {
|
||||
const std::string_view action = std::string_view(policy).substr(at, policy.find("</action>", at) - at);
|
||||
const std::size_t id = action.find('"') + 1;
|
||||
declared.emplace_back(action.substr(id, action.find('"', id) - id));
|
||||
Check(action.contains("<annotate key=\"org.freedesktop.policykit.owner\">unix-user:nostro</annotate>"), std::format("{} is owned by the user nostrod runs as", declared.back()));
|
||||
for(std::size_t key = action.find("$("); key != std::string_view::npos; key = action.find("$(", key + 1)) {
|
||||
Check(action.substr(key).starts_with("$(summary)"), std::format("{} shows only details nostrod sets", declared.back()));
|
||||
}
|
||||
}
|
||||
const std::vector<std::string> asked = {std::string(Bus::actionView), std::string(Bus::actionChange), std::string(Bus::actionPay), std::string(Bus::actionUnfreezeCard), std::string(Bus::actionBlockCard), std::string(Bus::actionConnectors), std::string(Bus::actionCheckout)};
|
||||
Check(std::ranges::is_permutation(declared, asked), "the policy declares the actions nostrod asks about, and no other");
|
||||
}
|
||||
|
||||
void NotRunning(Fake::Bus& bus) {
|
||||
Throws<std::runtime_error>([&bus] { As(bus, aliceUid).Connectors(); }, "nostrod is not running", "a call without nostrod on the bus says so");
|
||||
}
|
||||
|
||||
void Arguments(const fs::path& state) {
|
||||
Equal(Fake::Wait(Fake::StartNostrod({"--state", state.string()})), 1, "a second nostrod cannot own the name, and ends");
|
||||
Equal(Fake::Wait(Fake::StartNostrod({"--idle"}, {"XDG_DATA_HOME"})), 1, "an option without its value");
|
||||
Equal(Fake::Wait(Fake::StartNostrod({"--idle", "soon"}, {"XDG_DATA_HOME", "HOME"})), 1, "a time that is no number");
|
||||
Equal(Fake::Wait(Fake::StartNostrod({"--frob"})), 1, "an unknown argument");
|
||||
}
|
||||
|
||||
void Users(Fake::Bus& bus, const fs::path& state) {
|
||||
Client alice = As(bus, aliceUid);
|
||||
Check(alice.Connectors().empty(), "a new user has no connectors");
|
||||
const AddedConnector added = alice.AddBunq("key-alice", "*", "");
|
||||
Check(added.name == "Alice" && added.environment == "production" && added.accounts == 3, "a connector, its environment from the key");
|
||||
const Fake::PolkitCheck check = bus.LastCheck();
|
||||
Check(check.action == "net.catcrafts.Nostro1.Connectors" && check.details.at("environment") == "production" && check.flags == 1, "adding one is the Connectors action, and the dialog may ask");
|
||||
Equal(check.details.at("summary"), std::string("add a bunq connector (production)"), "what the dialog says");
|
||||
Check(check.subject.starts_with(":1."), "polkit is asked about the caller's own connection");
|
||||
|
||||
Client bob = As(bus, bobUid);
|
||||
Check(bob.Connectors().empty(), "another user sees none of them");
|
||||
Equal(bob.AddBunq("key-bob", "", "sandbox").environment, std::string("sandbox"), "an environment named by the caller");
|
||||
Equal(alice.Connectors().size(), std::size_t{1}, "each user sees their own connectors");
|
||||
Equal(bob.Connectors().at(0).name, std::string("Bob"), "and only those");
|
||||
Equal(Slurp(state / "users" / std::to_string(aliceUid) / "owner"), std::string("alice\n"), "a user's directory says whose it is");
|
||||
Equal(Slurp(state / "users" / std::to_string(bobUid) / "owner"), std::string("bob\n"), "the other's too");
|
||||
Check(fs::exists(state / "users" / std::to_string(aliceUid) / "connectors.json") && fs::exists(state / "users" / std::to_string(bobUid) / "connectors.json"), "each has their connectors in their own directory");
|
||||
}
|
||||
|
||||
void Prompts(Fake::Bus& bus, Fake::Bunq& bunq, const Bank& bank) {
|
||||
Client alice = As(bus, aliceUid);
|
||||
const Created sent = alice.Send(aliceMain, bobIban, "Bob", 1250, "lunch");
|
||||
Check(sent.id != 0 && sent.currency == Currency::Euro, "a payment, and the currency its amount was in");
|
||||
Fake::PolkitCheck check = bus.LastCheck();
|
||||
Equal(check.action, std::string("net.catcrafts.Nostro1.Pay"), "paying is the Pay action");
|
||||
Equal(check.details.at("summary"), std::format("pay €12.50 to {} (Bob) from {} (Main)", bobIban, aliceMain), "the dialog names the amount, the payee and the account");
|
||||
Check(check.details.at("amount_minor") == "1250" && check.details.at("currency") == "EUR" && check.details.at("counterparty") == bobIban && check.details.at("account_iban") == aliceMain && check.details.at("environment") == "production", "and gives polkit rules the details to test");
|
||||
alice.Send(aliceMain, bobIban, "", 100, "");
|
||||
Equal(Summary(bus), std::format("pay €1.00 to {} from {} (Main)", bobIban, aliceMain), "a payee without a name is its IBAN");
|
||||
|
||||
// What a caller writes is made fit for the dialog: no control, invisible or direction characters, nothing for
|
||||
// markup or for polkit's $(…), at most 64 characters.
|
||||
const std::string nasty = std::format("B\x01o\x7F" "b\xC2\x85\xE2\x80\x8B\xE2\x80\xAE\xE2\x81\xA6\xEF\xBB\xBF<i>$(amount_minor)</i>\xF0\x9F\x98\x80x{}", std::string(70, 'y'));
|
||||
alice.Send(aliceMain, "x@y", nasty, 100, "");
|
||||
Equal(Summary(bus), std::format("pay €1.00 to x@y (Bob‹i›$ (amount_minor)‹/i›😀x{}…) from {} (Main)", std::string(37, 'y'), aliceMain), "a name made safe to show");
|
||||
// D-Bus carries UTF-8 alone, so text that is not cannot even be sent.
|
||||
Throws<std::invalid_argument>([&alice] { alice.Send(aliceMain, bobIban, "\xFF", 100, ""); }, "not UTF-8", "a name that is not UTF-8");
|
||||
|
||||
alice.Accounts();
|
||||
Check(bus.LastCheck().action == "net.catcrafts.Nostro1.View" && Summary(bus) == "see your accounts and balances", "listing is the View action");
|
||||
alice.Transactions(aliceMain, {});
|
||||
Equal(Summary(bus), std::string("see your transactions"), "so are the transactions");
|
||||
|
||||
alice.Request(aliceMain, bobIban, "Bob", 500, "back");
|
||||
Check(bus.LastCheck().action == "net.catcrafts.Nostro1.Change" && Summary(bus) == std::format("ask {} (Bob) for €5.00 into {} (Main)", bobIban, aliceMain), "asking for money is a Change");
|
||||
const std::uint64_t asked = alice.Requests(aliceMain).at(0).id;
|
||||
alice.RevokeRequest(aliceMain, asked);
|
||||
Equal(Summary(bus), std::format("revoke request {} of {} (Main)", asked, aliceMain), "revoking one");
|
||||
|
||||
Client bob = As(bus, bobUid);
|
||||
bob.Request(bobIban, aliceMain, "Alice", 700, "rent");
|
||||
const BunqIncomingRequest owed = alice.IncomingRequests(aliceMain).at(0);
|
||||
alice.RespondToRequest(aliceMain, owed.id, true);
|
||||
Check(bus.LastCheck().action == "net.catcrafts.Nostro1.Pay" && Summary(bus) == std::format("pay €7.00 to {} ({}) from {} (Main), as asked in request {}", owed.counterparty.iban, owed.counterparty.name, aliceMain, owed.id), "accepting a request is a payment, shown as asked");
|
||||
bob.Request(bobIban, aliceMain, "Alice", 800, "more");
|
||||
const BunqIncomingRequest refused = alice.IncomingRequests(aliceMain).at(0);
|
||||
alice.RespondToRequest(aliceMain, refused.id, false);
|
||||
Check(bus.LastCheck().action == "net.catcrafts.Nostro1.Change" && Summary(bus) == std::format("reject request {} from {} ({})", refused.id, refused.counterparty.iban, refused.counterparty.name), "rejecting one is a Change");
|
||||
|
||||
const std::chrono::system_clock::time_point start = std::chrono::sys_days(std::chrono::year(2027) / 1 / 1);
|
||||
alice.Schedule(aliceMain, bobIban, "Bob", 300, "rent", BunqSchedule{.start = start, .end = start + std::chrono::days(364), .unit = "MONTHLY", .every = 1});
|
||||
Check(bus.LastCheck().action == "net.catcrafts.Nostro1.Pay" && Summary(bus) == std::format("schedule €3.00 to {} (Bob) from {} (Main), monthly from 2027-01-01 00:00 UTC until 2027-12-31 00:00 UTC", bobIban, aliceMain), "a schedule is a payment, with when it runs");
|
||||
alice.Schedule(aliceMain, bobIban, "Bob", 300, "", BunqSchedule{.start = start, .unit = "ONCE"});
|
||||
Check(Summary(bus).ends_with(", once on 2027-01-01 00:00 UTC"), "one that runs once");
|
||||
const std::uint64_t scheduled = alice.ScheduledPayments(aliceMain).at(0).id;
|
||||
alice.CancelScheduledPayment(aliceMain, scheduled);
|
||||
Equal(Summary(bus), std::format("cancel scheduled payment {} of {} (Main)", scheduled, aliceMain), "cancelling one");
|
||||
|
||||
alice.Draft(aliceMain, bobIban, "Bob", 200, "");
|
||||
Equal(Summary(bus), std::format("make a draft payment of €2.00 to {} (Bob) from {} (Main), paid once someone accepts it", bobIban, aliceMain), "a draft");
|
||||
const BunqDraftPayment draft = alice.DraftPayments(aliceMain).at(0);
|
||||
alice.RespondToDraftPayment(aliceMain, draft.id, true);
|
||||
Check(bus.LastCheck().action == "net.catcrafts.Nostro1.Pay" && Summary(bus) == std::format("pay €2.00 to {} ({}) from {} (Main), as drafted in draft payment {}", draft.entries.at(0).counterparty.iban, draft.entries.at(0).counterparty.name, aliceMain, draft.id), "accepting a draft is a payment");
|
||||
{
|
||||
std::lock_guard lock(bunq.mutex);
|
||||
json entries = json::array();
|
||||
for(const std::string_view payee : {"One", "Two", "Three", "Four"}) {
|
||||
entries.push_back(json{{"amount", Fake::Amount(-100)}, {"counterparty_alias", json{{"display_name", payee}, {"iban", bobIban}}}, {"pointer", json{{"type", "IBAN"}, {"value", bobIban}, {"name", payee}}}, {"description", ""}});
|
||||
}
|
||||
bunq.drafts[bank.aliceMainId].push_back(json{{"DraftPayment", json{{"id", 900001}, {"status", "PENDING"}, {"entries", entries}}}});
|
||||
bunq.drafts[bank.aliceMainId].push_back(json{{"DraftPayment", json{{"id", 900002}, {"status", "PENDING"}, {"entries", json::array()}}}});
|
||||
bunq.drafts[bank.aliceMainId].push_back(json{{"DraftPayment", json{{"id", 900003}, {"status", "PENDING"}, {"entries", json::array({json{{"amount", Fake::Amount(-250)}, {"counterparty_alias", json{{"iban", bobIban}}}}, json{{"amount", Fake::Amount(-50)}, {"counterparty_alias", json{{"display_name", "Mail"}}}}})}}}});
|
||||
}
|
||||
alice.RespondToDraftPayment(aliceMain, 900001, true);
|
||||
Equal(Summary(bus), std::format("pay €4.00 to {0} (One), {0} (Two), {0} (Three) and 1 more from {1} (Main), as drafted in draft payment 900001", bobIban, aliceMain), "a draft to many payees names three");
|
||||
alice.RespondToDraftPayment(aliceMain, 900002, false);
|
||||
Equal(Summary(bus), std::string("reject draft payment 900002 of €0.00 to no one"), "a draft to nobody");
|
||||
alice.RespondToDraftPayment(aliceMain, 900003, false);
|
||||
Equal(Summary(bus), std::format("reject draft payment 900003 of €3.00 to {}, Mail", bobIban), "payees known by IBAN or by name alone");
|
||||
|
||||
const std::uint64_t card = bunq.AddCard(bank.alice, "ACTIVE");
|
||||
Check(!alice.Cards().empty() && Summary(bus) == "see your cards", "the cards");
|
||||
alice.SetCardStatus(card, "DEACTIVATED");
|
||||
Check(bus.LastCheck().action == "net.catcrafts.Nostro1.Change" && Summary(bus) == "freeze card **** 1234", "freezing a card is a Change");
|
||||
alice.SetCardStatus(card, "ACTIVE");
|
||||
Check(bus.LastCheck().action == "net.catcrafts.Nostro1.UnfreezeCard" && Summary(bus) == "unfreeze card **** 1234", "unfreezing one has an action of its own");
|
||||
alice.SetCardStatus(card, "STOLEN");
|
||||
Check(bus.LastCheck().action == "net.catcrafts.Nostro1.BlockCard" && Summary(bus) == "report card **** 1234 stolen, which blocks it for good", "and so does blocking one for good");
|
||||
}
|
||||
|
||||
void Outcomes(Fake::Bus& bus) {
|
||||
Client alice = As(bus, aliceUid);
|
||||
SetPolkit(bus, Fake::Polkit::Deny);
|
||||
const Failure denied = FailureOf([&alice] { alice.Accounts(); });
|
||||
Check(denied.name == SD_BUS_ERROR_ACCESS_DENIED && denied.message.contains("does not allow net.catcrafts.Nostro1.View"), std::format("a refusal by policy: {}", denied.message));
|
||||
SetPolkit(bus, Fake::Polkit::Dismiss);
|
||||
Equal(FailureOf([&alice] { alice.Send(aliceMain, bobIban, "Bob", 100, ""); }).name, std::string(Bus::errorCancelled), "a dialog closed without a password");
|
||||
SetPolkit(bus, Fake::Polkit::Absent);
|
||||
const Failure absent = FailureOf([&alice] { alice.Accounts(); });
|
||||
Check(absent.name == SD_BUS_ERROR_ACCESS_DENIED && absent.message.contains("polkit did not decide"), "no polkit is no");
|
||||
SetPolkit(bus, Fake::Polkit::Silent);
|
||||
const Failure silent = FailureOf([&alice] { alice.Connectors(); });
|
||||
Check(silent.name == SD_BUS_ERROR_ACCESS_DENIED && silent.message.contains("polkit did not decide"), "nor is no answer");
|
||||
const std::string cancellation = bus.LastCheck().cancellation;
|
||||
bool cancelled = false;
|
||||
for(std::size_t i = 0; i < 100 && !cancelled; i++) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
||||
std::lock_guard lock(bus.mutex);
|
||||
cancelled = std::ranges::contains(bus.cancelled, cancellation);
|
||||
}
|
||||
Check(cancelled, "and the dialog of a check given up on is cancelled");
|
||||
|
||||
// A call that may not ask for a password is told it would need one.
|
||||
SetPolkit(bus, Fake::Polkit::Password);
|
||||
Check(!alice.Connectors().empty(), "a password asked for, and given");
|
||||
Equal(Raw(bus, name, name, "Connectors", false, [](sd_bus_message*) {}), std::string(SD_BUS_ERROR_INTERACTIVE_AUTHORIZATION_REQUIRED), "a call that does not allow a dialog");
|
||||
|
||||
// A client that stops waiting.
|
||||
SetPolkit(bus, Fake::Polkit::Silent);
|
||||
Client quick = As(bus, aliceUid);
|
||||
Client hurried = Client::System(std::chrono::seconds(1));
|
||||
const Failure lost = FailureOf([&hurried] { hurried.Send(aliceMain, bobIban, "Bob", 100, ""); });
|
||||
Check(lost.name == "exception" && lost.message.contains("may have been carried out"), std::format("a payment without an answer may have been made: {}", lost.message));
|
||||
Equal(FailureOf([&hurried] { hurried.Connectors(); }).name, std::string(SD_BUS_ERROR_TIMEOUT), "a listing without an answer is only that");
|
||||
SetPolkit(bus, Fake::Polkit::Allow);
|
||||
Check(!quick.Connectors().empty(), "and the next call is answered");
|
||||
}
|
||||
|
||||
void Concurrency(Fake::Bus& bus, Fake::Bunq& bunq, const Bank& bank) {
|
||||
Client alice = As(bus, aliceUid);
|
||||
Client again = As(bus, aliceUid);
|
||||
SetPolkit(bus, Fake::Polkit::Slow, Bus::actionPay);
|
||||
std::thread paying([&alice] { alice.Send(aliceMain, bobIban, "Bob", 100, ""); });
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(200));
|
||||
const std::chrono::steady_clock::time_point asked = std::chrono::steady_clock::now();
|
||||
again.Connectors();
|
||||
Check(std::chrono::steady_clock::now() - asked < std::chrono::milliseconds(700), "a dialog left open holds up no other call");
|
||||
paying.join();
|
||||
|
||||
// Gone while the dialog was open: the connector, then an account.
|
||||
again.AddBunq("key-dave", "*", "");
|
||||
std::string gone;
|
||||
std::thread toDave([&alice, &gone] {
|
||||
try {
|
||||
alice.Send(daveIban, bobIban, "Bob", 100, "");
|
||||
} catch(const std::invalid_argument& e) {
|
||||
gone = e.what();
|
||||
}
|
||||
});
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(200));
|
||||
again.RemoveConnector("Dave");
|
||||
Equal(Summary(bus), std::string("remove the bunq connector 'Dave' and its stored transactions"), "removing a connector");
|
||||
toDave.join();
|
||||
Check(gone.contains("that connector is no longer there"), std::format("a payment whose connector went: {}", gone));
|
||||
|
||||
std::thread fromClosing([&alice, &gone] {
|
||||
try {
|
||||
alice.Send(closingIban, bobIban, "Bob", 100, "");
|
||||
} catch(const std::invalid_argument& e) {
|
||||
gone = e.what();
|
||||
}
|
||||
});
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(200));
|
||||
bunq.ChangeAccount(bank.closingId, json{{"status", "CANCELLED"}});
|
||||
again.Accounts();
|
||||
fromClosing.join();
|
||||
Check(gone.contains("that account is no longer there"), std::format("a payment whose account closed: {}", gone));
|
||||
SetPolkit(bus, Fake::Polkit::Allow);
|
||||
}
|
||||
|
||||
void Errors(Fake::Bus& bus, Fake::Bunq& bunq, const Bank& bank, const fs::path& state) {
|
||||
Client alice = As(bus, aliceUid);
|
||||
Throws<std::invalid_argument>([&alice] { alice.Send(aliceMain, "NL00BUNQ0000000000", "X", 100, ""); }, "is not a valid IBAN", "a payee refused before anything is asked");
|
||||
Throws<std::invalid_argument>([&alice] { alice.Send(aliceMain, bobIban, "Bob", 0, ""); }, "more than zero", "nothing to pay");
|
||||
Throws<std::invalid_argument>([&alice] { alice.Send("Main", bobIban, "Bob", 100, ""); }, "2 accounts are called 'Main': use the IBAN", "two accounts of one name");
|
||||
Throws<std::invalid_argument>([&alice] { alice.Transactions("Nope", {}); }, "no account is called or has IBAN 'Nope'", "an account nobody has");
|
||||
bunq.AddAccount(bank.alice, lateIban, "Late", 0);
|
||||
Check(alice.Transactions(lateIban, {}).empty(), "an account opened since is found on a second look");
|
||||
Throws<std::invalid_argument>([&alice] { alice.AddBunq("key", "*", "moon"); }, "unknown environment 'moon'", "an environment that is none");
|
||||
Throws<std::invalid_argument>([&alice] { alice.SetCardStatus(1, "MELTED"); }, "unknown card status 'MELTED'", "a card status that is none");
|
||||
Throws<std::invalid_argument>([&alice] { alice.SetCardStatus(1, "LOST"); }, "no card has id 1", "a card nobody has");
|
||||
|
||||
bunq.Fail(Fault{.method = "POST", .path = "/user/", .status = 400, .body = R"({"Error":[{"error_description":"Not enough money."}]})"});
|
||||
const Failure refused = FailureOf([&alice] { alice.Send(aliceMain, bobIban, "Bob", 100, ""); });
|
||||
Check(refused.name == Bus::errorBank && refused.message.contains("Not enough money."), "bunq's refusal, as bunq said it");
|
||||
const AddedConnector carol = alice.AddBunqOAuth("production", bunq.clientId, bunq.clientSecret, "http://127.0.0.1/cb", "code-carol");
|
||||
Check(carol.name == "Carol" && Summary(bus) == "add a bunq connector through OAuth (production)", "a connector through OAuth");
|
||||
bunq.Fail(Fault{.method = "POST", .path = "/user/", .status = 403, .body = R"({"Error":[{"error_description":"Not allowed for this user."}]})"});
|
||||
Equal(FailureOf([&alice] { alice.Send(carolIban, bobIban, "Bob", 100, ""); }).name, std::string(Bus::errorOAuthCannotPay), "an OAuth connector paying someone else");
|
||||
|
||||
// A user whose connectors.json cannot be read hears so, without what it holds.
|
||||
const fs::path eve = state / "users" / "4444";
|
||||
fs::create_directories(eve);
|
||||
std::ofstream(eve / "owner") << "eve\n";
|
||||
std::ofstream(eve / "connectors.json") << R"({"bunq": [{"privateKey": "-----BEGIN PRIVATE KEY-----\nMIIE)";
|
||||
{
|
||||
std::lock_guard lock(bus.mutex);
|
||||
bus.logindNames[4444] = "eve";
|
||||
}
|
||||
const Failure unreadable = FailureOf([&bus] { As(bus, 4444).Connectors(); });
|
||||
Check(unreadable.name == Bus::errorFailed && unreadable.message.contains("is not valid JSON") && !unreadable.message.contains("MIIE"), std::format("an unreadable connectors.json: {}", unreadable.message));
|
||||
|
||||
const Failure stranger = FailureOf([&bus] { As(bus, 4545).Connectors(); });
|
||||
Check(stranger.name == SD_BUS_ERROR_ACCESS_DENIED && stranger.message.contains("logind knows no user 4545"), "a uid without a login session");
|
||||
{
|
||||
std::lock_guard lock(bus.mutex);
|
||||
bus.omitUid = true;
|
||||
}
|
||||
const Failure nameless = FailureOf([&alice] { alice.Connectors(); });
|
||||
Check(nameless.name == SD_BUS_ERROR_ACCESS_DENIED && nameless.message.contains("did not say which user"), "a caller the bus cannot name");
|
||||
{
|
||||
std::lock_guard lock(bus.mutex);
|
||||
bus.omitUid = false;
|
||||
}
|
||||
|
||||
// What Client never sends: an optional value of two, and a query key nostrod does not know, which it skips.
|
||||
const std::string twoEnds = Raw(bus, name, name, "Schedule", true, [](sd_bus_message* call) {
|
||||
sd_bus_message_append(call, "sssxs", aliceMain.c_str(), bobIban.c_str(), "Bob", std::int64_t{100}, "");
|
||||
sd_bus_message_open_container(call, 'r', "xaxsusax");
|
||||
sd_bus_message_append(call, "xaxsusax", std::int64_t{0}, 2, std::int64_t{1}, std::int64_t{2}, "ONCE", 1u, "", 0);
|
||||
sd_bus_message_close_container(call);
|
||||
});
|
||||
Equal(twoEnds, std::string(Bus::errorFailed), "a schedule with two ends");
|
||||
const std::string unknown = Raw(bus, name, name, "Transactions", true, [](sd_bus_message* call) {
|
||||
sd_bus_message_append(call, "sa{sv}", aliceMain.c_str(), 1, "colour", "s", "blue");
|
||||
});
|
||||
Equal(unknown, std::string(), "a query key nostrod does not know");
|
||||
}
|
||||
|
||||
// A stand-in for nostrod's checkout, for answers nostrod never gives, chosen by the order's reference: "extra", a
|
||||
// result the client does not know; "shape", an answer of another shape; "odd", an error of another name; "bare", an
|
||||
// error without a message; anything else, no answer at all. A plain object rather than a vtable, whose answers sd-bus would hold to its signature.
|
||||
class FakeCheckout {
|
||||
public:
|
||||
FakeCheckout() {
|
||||
sd_bus_open_system(&bus);
|
||||
sd_bus_add_object(bus, nullptr, "/net/catcrafts/Nostro1", OnCall, nullptr);
|
||||
sd_bus_request_name(bus, "net.catcrafts.Nostro1.Checkout", 0);
|
||||
thread = std::thread([this] {
|
||||
while(!stop) {
|
||||
while(sd_bus_process(bus, nullptr) > 0) {
|
||||
}
|
||||
sd_bus_wait(bus, 20000);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
FakeCheckout(const FakeCheckout&) = delete;
|
||||
FakeCheckout& operator=(const FakeCheckout&) = delete;
|
||||
|
||||
~FakeCheckout() {
|
||||
stop = true;
|
||||
thread.join();
|
||||
sd_bus_flush_close_unref(bus);
|
||||
}
|
||||
|
||||
private:
|
||||
static std::int32_t OnCall(sd_bus_message* call, void*, sd_bus_error*) {
|
||||
if(!sd_bus_message_is_method_call(call, "net.catcrafts.Nostro1.Checkout", "Pay")) {
|
||||
return 0;
|
||||
}
|
||||
sd_bus_message_skip(call, "ssxs");
|
||||
// sd-bus hands strings out as C strings.
|
||||
// lint-disable-next-line no-char-pointer
|
||||
const char* reference = nullptr;
|
||||
sd_bus_message_read_basic(call, 's', &reference);
|
||||
const std::string_view kind(reference);
|
||||
if(kind == "extra") {
|
||||
return sd_bus_reply_method_return(call, "ta{sv}", std::uint64_t{7}, 2u, "colour", "s", "blue", "repeated", "b", 1);
|
||||
}
|
||||
if(kind == "shape") {
|
||||
return sd_bus_reply_method_return(call, "s", "nonsense");
|
||||
}
|
||||
if(kind == "odd") {
|
||||
return sd_bus_reply_method_errorf(call, "org.example.Odd", "an error of another name");
|
||||
}
|
||||
if(kind == "bare") {
|
||||
const sd_bus_error bare = {"org.example.Bare", nullptr, 0};
|
||||
return sd_bus_reply_method_error(call, &bare);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
sd_bus* bus = nullptr;
|
||||
std::thread thread;
|
||||
std::atomic<bool> stop{false};
|
||||
};
|
||||
|
||||
// Nostro.Checkout's own side: with no nostro on the bus, and against a stand-in for nostrod's checkout.
|
||||
void CheckoutClient(Fake::Bus& bus) {
|
||||
Checkout::Order order{.payeeIban = shopIban, .payeeName = "Shop", .amount = 1250, .reference = "1"};
|
||||
const Failure missing = FailureOf([&order] { Checkout::Pay(order); });
|
||||
Check(missing.name == SD_BUS_ERROR_SERVICE_UNKNOWN && missing.message.contains("nostro is not installed"), std::format("a checkout without nostro: {}", missing.message));
|
||||
Throws<std::invalid_argument>([] { Checkout::Pay({.payeeIban = "\xFF", .amount = 1, .reference = "1"}); }, "not UTF-8", "an order that is not UTF-8");
|
||||
|
||||
const auto pay = [&order](std::string_view reference, std::chrono::seconds timeout) {
|
||||
order.reference = std::string(reference);
|
||||
return Checkout::Pay(order, timeout);
|
||||
};
|
||||
{
|
||||
const FakeCheckout stand;
|
||||
Check(bus.WaitForName(checkoutName), "a stand-in for nostrod's checkout");
|
||||
const Checkout::Paid extra = pay("extra", std::chrono::seconds(20));
|
||||
Check(extra.paymentId == 7 && extra.repeated, "results the client does not know are skipped");
|
||||
Throws<std::system_error>([&pay] { pay("shape", std::chrono::seconds(20)); }, "cannot read nostrod's answer", "an answer of another shape");
|
||||
const Failure odd = FailureOf([&pay] { pay("odd", std::chrono::seconds(20)); });
|
||||
Check(odd.name == "org.example.Odd" && odd.message == "an error of another name", "an error of another name, as it came");
|
||||
const Failure bare = FailureOf([&pay] { pay("bare", std::chrono::seconds(20)); });
|
||||
Check(bare.name == "org.example.Bare" && bare.message.empty(), "and one without a message");
|
||||
const Failure late = FailureOf([&pay] { pay("silent", std::chrono::seconds(1)); });
|
||||
Check(late.name == SD_BUS_ERROR_TIMEOUT && late.message.contains("the order may have been paid"), std::format("no answer in time: {}", late.message));
|
||||
}
|
||||
Check(bus.WaitForName(checkoutName, false), "and the stand-in gone");
|
||||
}
|
||||
|
||||
// nostrod's side of a checkout: the account that pays, the prompt, the record that answers a retry, and every way an
|
||||
// order is refused.
|
||||
void Checkouts(Fake::Bus& bus, Fake::Bunq& bunq, const Bank& bank) {
|
||||
Client alice = As(bus, aliceUid);
|
||||
const auto pay = [&bus](const Checkout::Order& order) {
|
||||
{
|
||||
std::lock_guard lock(bus.mutex);
|
||||
bus.clientUid = aliceUid;
|
||||
}
|
||||
return Checkout::Pay(order);
|
||||
};
|
||||
const auto checks = [&bus](std::string_view reference) {
|
||||
std::lock_guard lock(bus.mutex);
|
||||
return std::ranges::count_if(bus.checks, [reference](const Fake::PolkitCheck& check) { return check.details.contains("reference") && check.details.at("reference") == reference; });
|
||||
};
|
||||
const std::string payments = std::format("/user/{}/monetary-account/{}/payment", bank.alice, bank.aliceMainId);
|
||||
const Checkout::Order order{.payeeIban = shopIban, .payeeName = "Shop", .amount = 1250, .reference = "order-1"};
|
||||
|
||||
Check(!alice.DefaultCheckoutAccount().has_value() && Summary(bus) == "see which account pays at checkout", "no account pays at checkout until one is chosen");
|
||||
Throws<Checkout::NoCheckoutAccount>([&pay, &order] { pay(order); }, "no account is chosen to pay checkouts from", "a checkout before an account is chosen");
|
||||
Throws<std::invalid_argument>([&alice] { alice.SetDefaultCheckoutAccount(carolIban); }, "is reached through OAuth, which pays only your own accounts", "an account that could pay no shop");
|
||||
const Account chosen = alice.SetDefaultCheckoutAccount(aliceMain);
|
||||
Check(chosen.iban == aliceMain && chosen.name == "Main", "an account chosen, and shown");
|
||||
Check(bus.LastCheck().action == "net.catcrafts.Nostro1.Connectors" && Summary(bus) == std::format("let apps ask you to pay from {} (Main) at checkout", aliceMain), "choosing it is a change to the connections");
|
||||
Equal(alice.DefaultCheckoutAccount().value_or(Account{}).iban, aliceMain, "the account checkouts pay from");
|
||||
|
||||
const std::size_t before = bunq.Count("POST", payments);
|
||||
const Checkout::Paid paid = pay(order);
|
||||
Check(paid.paymentId != 0 && !paid.repeated, "an order paid");
|
||||
const Fake::PolkitCheck check = bus.LastCheck();
|
||||
Equal(check.action, std::string("net.catcrafts.Nostro1.Checkout"), "paying at checkout is an action of its own");
|
||||
Equal(check.details.at("summary"), std::format("pay €12.50 to {} (Shop) from {} (Main), as an app asks at checkout, reference order-1", shopIban, aliceMain), "the dialog shows the order, and the account that pays it");
|
||||
Check(check.details.at("reference") == "order-1" && check.details.at("amount_minor") == "1250" && check.details.at("account_iban") == aliceMain && check.details.at("counterparty") == shopIban, "and gives polkit rules the details");
|
||||
Equal(bunq.Count("POST", payments), before + 1, "one payment");
|
||||
|
||||
const Checkout::Paid again = pay(order);
|
||||
Check(again.paymentId == paid.paymentId && again.repeated, "the same order again answers with its payment");
|
||||
Check(checks("order-1") == 1 && bunq.Count("POST", payments) == before + 1, "without asking, or paying, again");
|
||||
|
||||
const auto refused = [&pay](Checkout::Order changed, std::string_view part, std::string_view what) {
|
||||
const Failure failure = FailureOf([&pay, &changed] { pay(changed); });
|
||||
Check(failure.name == Checkout::errorInvalidArgument && failure.message.contains(part), std::format("{}: {}", what, failure.message));
|
||||
};
|
||||
Checkout::Order changed = order;
|
||||
changed.amount = 1300;
|
||||
refused(changed, "reference order-1 to NL91ABNA0417164300 is an order of €12.50, not of €13.00", "a reference paid for another amount");
|
||||
changed = order;
|
||||
changed.payeeIban = "shop@example.com";
|
||||
refused(changed, "checkout pays an IBAN, and 'shop@example.com' is none", "a payee that is no IBAN");
|
||||
changed.payeeIban = "NL00BUNQ0000000000";
|
||||
refused(changed, "is not a valid IBAN", "an IBAN with a typo");
|
||||
changed = order;
|
||||
changed.amount = 0;
|
||||
refused(changed, "more than zero", "nothing to pay");
|
||||
changed = order;
|
||||
changed.currency = "USD";
|
||||
refused(changed, "unsupported currency 'USD'", "a currency nostro does not pay in");
|
||||
changed = order;
|
||||
changed.reference = "";
|
||||
refused(changed, "an order needs a reference", "an order without a reference");
|
||||
|
||||
// bunq refusing it before doing anything: the order was not paid, and is paid when asked again.
|
||||
Checkout::Order refusedOrder = order;
|
||||
refusedOrder.reference = "order-2";
|
||||
bunq.Fail(Fault{.method = "POST", .path = "/user/", .status = 400, .body = R"({"Error":[{"error_description":"Not enough money."}]})"});
|
||||
const Failure poor = FailureOf([&pay, &refusedOrder] { pay(refusedOrder); });
|
||||
Check(poor.name == Checkout::errorBank && poor.message.contains("Not enough money."), "bunq's refusal");
|
||||
Check(!pay(refusedOrder).repeated, "and the order paid when asked again");
|
||||
|
||||
// bunq's answer lost: the order may have been paid, and is not paid again.
|
||||
Checkout::Order lostOrder = order;
|
||||
lostOrder.reference = "order-3";
|
||||
bunq.Fail(Fault{.method = "POST", .path = "/user/", .status = 500, .body = R"({"Error":[{"error_description":"Hiccup."}]})"});
|
||||
const Failure hiccup = FailureOf([&pay, &lostOrder] { pay(lostOrder); });
|
||||
Check(hiccup.name == Checkout::errorBank && hiccup.message.contains("may have been carried out"), std::format("an answer that may hide a payment: {}", hiccup.message));
|
||||
const Failure lost = FailureOf([&pay, &lostOrder] { pay(lostOrder); });
|
||||
Check(lost.name == Checkout::errorFailed && lost.message.contains("order order-3 to NL91ABNA0417164300 may have been paid already") && !lost.message.contains(aliceMain), std::format("such an order asked again, without the account: {}", lost.message));
|
||||
|
||||
Checkout::Order unconfirmed = order;
|
||||
unconfirmed.reference = "order-4";
|
||||
SetPolkit(bus, Fake::Polkit::Dismiss, Bus::actionCheckout);
|
||||
Throws<Checkout::Cancelled>([&pay, &unconfirmed] { pay(unconfirmed); }, "you did not authenticate", "an order the user did not confirm");
|
||||
|
||||
// Asked again while the user is still at the prompt: the second call waits for the first, and gets its answer.
|
||||
SetPolkit(bus, Fake::Polkit::Slow, Bus::actionCheckout);
|
||||
Checkout::Paid first;
|
||||
std::thread paying([&pay, &unconfirmed, &first] { first = pay(unconfirmed); });
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(300));
|
||||
changed = unconfirmed;
|
||||
changed.amount = 99;
|
||||
refused(changed, "is an order of €12.50, not of €0.99", "another amount while the order is being paid");
|
||||
const Checkout::Paid waited = pay(unconfirmed);
|
||||
paying.join();
|
||||
Check(first.paymentId != 0 && waited.paymentId == first.paymentId && !first.repeated && waited.repeated, "a retry while the first call is at the prompt gets the first call's payment");
|
||||
Equal(checks("order-4"), std::ptrdiff_t{2}, "and the user is asked once for it, after the dismissed dialog");
|
||||
|
||||
SetPolkit(bus, Fake::Polkit::Silent, Bus::actionCheckout);
|
||||
Checkout::Order unanswered = order;
|
||||
unanswered.reference = "order-5";
|
||||
Failure gaveUp;
|
||||
std::thread asking([&pay, &unanswered, &gaveUp] { gaveUp = FailureOf([&pay, &unanswered] { pay(unanswered); }); });
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(300));
|
||||
const Failure alsoGaveUp = FailureOf([&pay, &unanswered] { pay(unanswered); });
|
||||
asking.join();
|
||||
Check(gaveUp.name == SD_BUS_ERROR_ACCESS_DENIED && alsoGaveUp.name == gaveUp.name && alsoGaveUp.message == gaveUp.message, "and the first call's refusal, when it is refused");
|
||||
SetPolkit(bus, Fake::Polkit::Allow);
|
||||
|
||||
// An account chosen and since closed pays no checkout.
|
||||
const std::uint64_t brief = bunq.AddAccount(bank.alice, briefIban, "Brief", 1000);
|
||||
Equal(alice.SetDefaultCheckoutAccount(briefIban).iban, briefIban, "an account opened since");
|
||||
bunq.ChangeAccount(brief, json{{"status", "CANCELLED"}});
|
||||
alice.Accounts();
|
||||
Check(!alice.DefaultCheckoutAccount().has_value(), "a closed account pays at checkout no more");
|
||||
Checkout::Order orphan = order;
|
||||
orphan.reference = "order-6";
|
||||
Throws<Checkout::NoCheckoutAccount>([&pay, &orphan] { pay(orphan); }, "or it is gone", "nor does a checkout pay from it");
|
||||
alice.SetDefaultCheckoutAccount(aliceMain);
|
||||
}
|
||||
|
||||
void Workers(Fake::Bus& bus, pid_t nostrod) {
|
||||
// A worker dying with a call under way: the caller hears it may have been carried out.
|
||||
Client alice = As(bus, aliceUid);
|
||||
SetPolkit(bus, Fake::Polkit::Silent, Bus::actionPay);
|
||||
Failure lost;
|
||||
std::thread paying([&alice, &lost] { lost = FailureOf([&alice] { alice.Send(aliceMain, bobIban, "Bob", 100, ""); }); });
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(300));
|
||||
KillWorkers(bus, nostrod);
|
||||
paying.join();
|
||||
Check(lost.name == Bus::errorFailed && lost.message.contains("stopped before it answered"), std::format("a call whose worker died: {}", lost.message));
|
||||
SetPolkit(bus, Fake::Polkit::Allow);
|
||||
Equal(As(bus, aliceUid).Connectors().size(), std::size_t{2}, "the next call starts a worker again, which reads the connectors again");
|
||||
|
||||
// A uid that logind gives another name now: the directory stays the first user's.
|
||||
{
|
||||
std::lock_guard lock(bus.mutex);
|
||||
bus.logindNames[aliceUid] = "mallory";
|
||||
}
|
||||
KillWorkers(bus, nostrod);
|
||||
const Failure reused = FailureOf([&bus] { As(bus, aliceUid).Connectors(); });
|
||||
Check(reused.name == SD_BUS_ERROR_ACCESS_DENIED && reused.message.contains("holds the bank connections of 'alice'"), std::format("a uid handed to someone else: {}", reused.message));
|
||||
{
|
||||
std::lock_guard lock(bus.mutex);
|
||||
bus.logindNames[aliceUid] = "alice";
|
||||
}
|
||||
KillWorkers(bus, nostrod);
|
||||
Check(!As(bus, aliceUid).Connectors().empty(), "served again once the name is the one it was");
|
||||
}
|
||||
|
||||
void Notes(Fake::Bus& bus, Fake::Bunq& bunq) {
|
||||
Client bob = As(bus, bobUid);
|
||||
{
|
||||
std::lock_guard lock(bunq.mutex);
|
||||
bunq.keys.erase("key-bob");
|
||||
}
|
||||
bunq.ExpireSessions();
|
||||
bob.Accounts();
|
||||
const std::vector<std::string> notes = bob.TakeNotes();
|
||||
// The worker was started again for this call: its first read of the connectors notes it, and so does the refresh.
|
||||
Check(!notes.empty() && std::ranges::all_of(notes, [](const std::string& note) { return note.contains("bunq connector 'Bob' is unavailable"); }), "a connector that cannot be reached comes back as a note");
|
||||
Check(bob.TakeNotes().empty(), "taken once");
|
||||
}
|
||||
|
||||
void SpawnFailure(Fake::Bus& bus, const fs::path& state) {
|
||||
const pid_t limited = Fake::StartNostrod({"--state", state.string()});
|
||||
Check(bus.WaitForName(name), "a nostrod that will run out of descriptors, then of processes");
|
||||
// Descriptors 0 to 2 are taken, so no new one fits under 3; poll still takes one at a time.
|
||||
const rlim_t files = Fake::Limit(limited, RLIMIT_NOFILE, 3);
|
||||
const Failure noSocket = FailureOf([&bus] { As(bus, aliceUid).Connectors(); });
|
||||
Check(noSocket.name == Bus::errorFailed && noSocket.message.contains("cannot make a socket for a worker"), std::format("no descriptor for a worker's socket: {}", noSocket.message));
|
||||
Fake::Limit(limited, RLIMIT_NOFILE, files);
|
||||
const rlim_t processes = Fake::Limit(limited, RLIMIT_NPROC, 0);
|
||||
const Failure failed = FailureOf([&bus] { As(bus, aliceUid).Connectors(); });
|
||||
Check(failed.name == Bus::errorFailed && failed.message.contains("cannot start a worker"), std::format("a worker that cannot be started: {}", failed.message));
|
||||
Fake::Limit(limited, RLIMIT_NPROC, processes);
|
||||
bus.Disconnect(name);
|
||||
Equal(Fake::Wait(limited), 0, "it ends with the bus");
|
||||
Check(bus.WaitForName(name, false) && bus.WaitForName(checkoutName, false), "and lets go of its names");
|
||||
}
|
||||
|
||||
void Idle(Fake::Bus& bus, const fs::path& state) {
|
||||
const pid_t idle = Fake::StartNostrod({"--state", state.string(), "--idle", "1", "--prompt-timeout", "3"});
|
||||
Check(bus.WaitForName(name), "a nostrod that idles after a second");
|
||||
Client alice = As(bus, aliceUid);
|
||||
Check(!alice.Connectors().empty(), "it starts a worker");
|
||||
// The worker and the front both pass an idle second while a dialog is open, and wait for it.
|
||||
SetPolkit(bus, Fake::Polkit::Silent, Bus::actionView);
|
||||
Equal(FailureOf([&alice] { alice.Accounts(); }).name, std::string(SD_BUS_ERROR_ACCESS_DENIED), "a dialog nobody answers");
|
||||
SetPolkit(bus, Fake::Polkit::Allow);
|
||||
Equal(Fake::Wait(idle), 0, "then the idle worker ends, and nostrod after it");
|
||||
}
|
||||
}
|
||||
|
||||
// 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("daemon");
|
||||
const fs::path state = directory.path / "state";
|
||||
// What nostrod reads from the environment is set before any thread starts.
|
||||
setenv("XDG_DATA_HOME", (directory.path / "data").c_str(), 1);
|
||||
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 = {{aliceUid, "alice"}, {bobUid, "bob"}};
|
||||
}
|
||||
|
||||
Fake::Bunq bunq(port);
|
||||
Bank bank;
|
||||
bank.alice = bunq.AddPerson("Alice", "key-alice");
|
||||
bank.aliceMainId = bunq.AddAccount(bank.alice, aliceMain, "Main", 100000);
|
||||
bunq.AddAccount(bank.alice, aliceOther, "Main", 500);
|
||||
bank.closingId = bunq.AddAccount(bank.alice, closingIban, "Closing", 100);
|
||||
bunq.AddAccount(bunq.AddPerson("Bob", "key-bob"), bobIban, "Bob's", 0);
|
||||
const std::uint64_t carol = bunq.AddPerson("Carol", "key-carol");
|
||||
bunq.AddAccount(carol, carolIban, "Shared", 500);
|
||||
bunq.AddGrant(carol, "code-carol", "token-carol");
|
||||
bunq.AddAccount(bunq.AddPerson("Dave", "key-dave"), daveIban, "Dave's", 100);
|
||||
|
||||
NotRunning(bus);
|
||||
CheckoutClient(bus);
|
||||
const pid_t nostrod = Fake::StartNostrod({"--state", state.string(), "--idle", "60", "--prompt-timeout", "2"});
|
||||
Check(bus.WaitForName(name), "nostrod owns its name");
|
||||
Contract(bus);
|
||||
Arguments(state);
|
||||
Users(bus, state);
|
||||
Prompts(bus, bunq, bank);
|
||||
Outcomes(bus);
|
||||
Concurrency(bus, bunq, bank);
|
||||
Errors(bus, bunq, bank, state);
|
||||
Checkouts(bus, bunq, bank);
|
||||
Workers(bus, nostrod);
|
||||
Notes(bus, bunq);
|
||||
bus.Disconnect(name);
|
||||
Equal(Fake::Wait(nostrod), 0, "nostrod ends when the bus goes, after its workers");
|
||||
Check(bus.WaitForName(name, false) && bus.WaitForName(checkoutName, false), "and lets go of its names");
|
||||
|
||||
SpawnFailure(bus, state);
|
||||
Idle(bus, state);
|
||||
return Test::Result();
|
||||
}
|
||||
53
tests/ShouldSignAndVerify/main.cpp
Normal file
53
tests/ShouldSignAndVerify/main.cpp
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
// The OpenSSL helpers (Nostro:Crypto): keys made, written and read back, signatures made and checked, including every
|
||||
// way a signature can fail to verify, and the error checks every OpenSSL call goes through.
|
||||
|
||||
import std;
|
||||
import Nostro;
|
||||
|
||||
#include "../Support/Check.inc"
|
||||
|
||||
using namespace Nostro;
|
||||
using Test::Check;
|
||||
using Test::Equal;
|
||||
using Test::Throws;
|
||||
|
||||
int main() {
|
||||
const auto [made, publicPem] = Crypto::CreateKey();
|
||||
const Crypto::Key key = Crypto::OwnKey(made);
|
||||
const Crypto::Key other = Crypto::OwnKey(std::get<0>(Crypto::CreateKey()));
|
||||
Check(publicPem.starts_with("-----BEGIN PUBLIC KEY-----"), "CreateKey gives the public half in PEM");
|
||||
|
||||
const std::string privatePem = Crypto::PrivateKeyToPem(key.get());
|
||||
const Crypto::Key reread = Crypto::OwnKey(Crypto::LoadKeyFromPem(privatePem));
|
||||
const Crypto::Key publicKey = Crypto::OwnKey(Crypto::LoadPublicKeyFromPem(publicPem));
|
||||
Equal(Crypto::PublicKeyToPem(publicKey.get()), publicPem, "a public key reads back as it was written");
|
||||
Equal(Crypto::PublicKeyToPem(reread.get()), publicPem, "a private key reads back to the same pair");
|
||||
Throws([] { Crypto::LoadKeyFromPem("not a key"); }, "openssl error", "garbage is not a private key");
|
||||
Throws([] { Crypto::LoadPublicKeyFromPem("not a key"); }, "openssl error", "garbage is not a public key");
|
||||
|
||||
const std::string body = R"({"amount":{"value":"12.50","currency":"EUR"}})";
|
||||
const std::string signature = Crypto::SignBody(key.get(), body);
|
||||
Check(Crypto::VerifyBody(publicKey.get(), body, signature), "a signature verifies against its key");
|
||||
Check(Crypto::VerifyBody(reread.get(), body, Crypto::SignBody(reread.get(), body)), "and so does one from the key read back");
|
||||
Check(!Crypto::VerifyBody(publicKey.get(), std::format("{} ", body), signature), "a changed body does not verify");
|
||||
Check(!Crypto::VerifyBody(other.get(), body, signature), "another key does not verify");
|
||||
Check(!Crypto::VerifyBody(publicKey.get(), body, ""), "an empty signature does not verify");
|
||||
Check(!Crypto::VerifyBody(publicKey.get(), body, signature.substr(1)), "a signature that is not whole base64 does not verify");
|
||||
Check(!Crypto::VerifyBody(publicKey.get(), body, "!!!!"), "a signature with characters outside base64 does not verify");
|
||||
Check(!Crypto::VerifyBody(publicKey.get(), body, "QUI="), "one byte of padding decodes, and does not verify");
|
||||
Check(!Crypto::VerifyBody(publicKey.get(), body, "QQ=="), "two bytes of padding decode, and do not verify");
|
||||
|
||||
Equal(Crypto::RandomHex(16).size(), std::size_t{32}, "16 random bytes are 32 hex digits");
|
||||
Check(Crypto::RandomHex(8) != Crypto::RandomHex(8), "random bytes differ");
|
||||
Check(std::ranges::all_of(Crypto::RandomHex(32), [](char c) { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'); }), "lower-case hex");
|
||||
|
||||
Equal(Crypto::ThrowOnOpenssl(std::int64_t{1}), std::int64_t{1}, "a positive status passes");
|
||||
Throws([] { Crypto::ThrowOnOpenssl(std::int64_t{0}); }, "openssl error", "zero is a failure");
|
||||
std::int32_t value = 7;
|
||||
Check(Crypto::ThrowOnOpenssl(&value) == &value, "a pointer passes");
|
||||
Throws([] { Crypto::ThrowOnOpenssl(static_cast<std::int32_t*>(nullptr)); }, "openssl error", "a null pointer is a failure");
|
||||
return Test::Result();
|
||||
}
|
||||
100
tests/ShouldStoreTransactions/main.cpp
Normal file
100
tests/ShouldStoreTransactions/main.cpp
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
// The transaction store (Nostro:Account): what a sync stores and what it drops as already stored, the queries, the
|
||||
// table's file name, a version 1 table migrating on its first open, and how transactions and accounts format.
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <time.h>
|
||||
|
||||
import std;
|
||||
import Nostro;
|
||||
import Crafter.DB;
|
||||
|
||||
#include "../Support/Check.inc"
|
||||
|
||||
using namespace Nostro;
|
||||
using namespace std::chrono;
|
||||
using Test::Check;
|
||||
using Test::Equal;
|
||||
|
||||
namespace {
|
||||
// Transaction version 1 as nostro wrote it; the same members give the same fingerprint, so it writes a real old table.
|
||||
struct OldTransaction {
|
||||
std::string name;
|
||||
std::string bic;
|
||||
std::string iban;
|
||||
std::string description;
|
||||
Currency currency;
|
||||
std::int64_t amount;
|
||||
system_clock::time_point timePoint;
|
||||
static constexpr std::uint32_t version = 1;
|
||||
static constexpr auto orderedBy = &OldTransaction::timePoint;
|
||||
};
|
||||
|
||||
const system_clock::time_point start = sys_days(year(2026) / 10 / 1) + hours(10);
|
||||
|
||||
Transaction Made(std::string_view name, std::int32_t minute, std::string_view id, std::int64_t amount = -100, std::string_view description = "groceries", std::string_view iban = "NL02BUNQ0000000002") {
|
||||
return Transaction{std::string(name), "BUNQNL2A", std::string(iban), std::string(description), Currency::Euro, amount, start + minutes(minute), std::string(id), "BUNQ/PAYMENT"};
|
||||
}
|
||||
|
||||
std::vector<std::string> Names(const std::vector<Transaction>& rows) {
|
||||
return rows | std::views::transform(&Transaction::name) | std::ranges::to<std::vector<std::string>>();
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
const Test::Directory directory("transactions");
|
||||
cachePath = directory.path;
|
||||
setenv("TZ", "UTC", 1);
|
||||
tzset();
|
||||
|
||||
const Account account{"Main/Spending", "BUNQNL2A", "NL01BUNQ0000000001", Currency::Euro, -1250};
|
||||
Equal(std::format("{}", account), std::string("Main/Spending\tBUNQNL2A NL01BUNQ0000000001\t-€12.50"), "an account formats as name, BIC and IBAN, balance");
|
||||
|
||||
const std::string key = "test/sandbox/1/2";
|
||||
Check(account.GetLastTransactionTime(key) == system_clock::time_point::min(), "a new table has no last transaction");
|
||||
|
||||
Account store = account;
|
||||
store.SaveTransactions(key, {Made("Bob", 1, "1"), Made("Alice", 0, "0")});
|
||||
Check(store.GetLastTransactionTime(key) == start + minutes(1), "rows arrive in any order and are stored sorted");
|
||||
Check(std::filesystem::exists(directory.path / "transactions" / key / "Main_Spending.cdb"), "a '/' in the account name becomes '_' in the file name");
|
||||
|
||||
// At the last stored timestamp only a new id is new; a row without an id there cannot be told apart.
|
||||
store.SaveTransactions(key, {Made("Bob again", 1, "1"), Made("Carol", 1, "2", -250, "rent", "NL03BUNQ0000000003"), Made("Nobody", 1, ""), Made("Old", 0, "9"), Made("Dave", 2, "3", 5000, "salary")});
|
||||
Equal(Names(store.FindTransactions(key, {})).size(), std::size_t{4}, "a sync that overlaps the last one stores only what is new");
|
||||
Check(Names(store.FindTransactions(key, {})) == std::vector<std::string>{"Dave", "Carol", "Bob", "Alice"}, "newest first, and the later of two at one time first");
|
||||
|
||||
Check(Names(store.FindTransactions(key, {.search = "CAROL"})) == std::vector<std::string>{"Carol"}, "search matches the name, whatever its case");
|
||||
Check(Names(store.FindTransactions(key, {.search = "Salary"})) == std::vector<std::string>{"Dave"}, "search matches the description");
|
||||
Check(Names(store.FindTransactions(key, {.search = "nl03"})) == std::vector<std::string>{"Carol"}, "search matches the IBAN");
|
||||
Check(Names(store.FindTransactions(key, {.amount = -100})) == std::vector<std::string>{"Bob", "Alice"}, "an exact amount");
|
||||
Check(Names(store.FindTransactions(key, {.from = start + minutes(1), .to = start + minutes(1)})) == std::vector<std::string>{"Carol", "Bob"}, "an inclusive time range");
|
||||
Check(Names(store.FindTransactions(key, {.limit = 1})) == std::vector<std::string>{"Dave"}, "at most `limit`");
|
||||
Check(store.FindTransactions(key, {.search = "nothing like it"}).empty(), "a search that matches nothing");
|
||||
|
||||
const Transaction alice = store.FindTransactions(key, {.search = "alice"}).at(0);
|
||||
Equal(alice.id, std::string("0"), "the bank's id is stored");
|
||||
Equal(alice.kind, std::string("BUNQ/PAYMENT"), "and its classification");
|
||||
Equal(std::format("{}", alice), std::string("2026-10-01 10:00\t-€1.00\tAlice\tNL02BUNQ0000000002\tgroceries"), "a transaction formats as one line");
|
||||
|
||||
// A table written by version 1 migrates when it is first opened, and its rows come back without id or kind.
|
||||
const std::filesystem::path oldFile = directory.path / "transactions" / "test" / "v1" / "Old.cdb";
|
||||
{
|
||||
Crafter::DB::Table<OldTransaction> old(oldFile);
|
||||
const std::array rows = {
|
||||
OldTransaction{"First", "", "NL04", "old", Currency::Euro, 100, start},
|
||||
OldTransaction{"Second", "", "NL05", "old", Currency::Euro, 200, start + minutes(5)},
|
||||
};
|
||||
old.Append(std::span<const OldTransaction>(rows));
|
||||
old.Close();
|
||||
}
|
||||
Account migrated{"Old", "", "", Currency::Euro, 0};
|
||||
const std::vector<Transaction> rows = migrated.FindTransactions("test/v1", {});
|
||||
Check(Names(rows) == std::vector<std::string>{"Second", "First"}, "a version 1 table reads after its migration");
|
||||
Check(rows.size() == 2 && rows[0].id.empty() && rows[0].kind.empty(), "migrated rows have no id or kind");
|
||||
Check(std::filesystem::exists(std::format("{}.v1.bak", oldFile.string())), "the migration keeps the old file");
|
||||
migrated.SaveTransactions("test/v1", {Made("Second", 5, "55"), Made("Third", 6, "66")});
|
||||
Check(Names(migrated.FindTransactions("test/v1", {})) == std::vector<std::string>{"Third", "Second", "First"}, "a migrated row at the last timestamp is not stored again under an id");
|
||||
return Test::Result();
|
||||
}
|
||||
403
tests/ShouldTalkToBunq/main.cpp
Normal file
403
tests/ShouldTalkToBunq/main.cpp
Normal 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();
|
||||
}
|
||||
67
tests/Support/Check.inc
Normal file
67
tests/Support/Check.inc
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
// What every test checks with, included after `import std;`. A failed check prints where and why and makes the test
|
||||
// exit 1; the test goes on, so one run lists every failure.
|
||||
|
||||
namespace Test {
|
||||
std::int32_t failures = 0;
|
||||
|
||||
void Check(bool condition, std::string_view what, std::source_location where = std::source_location::current()) {
|
||||
if(!condition) {
|
||||
std::println("FAIL {}:{}: {}", where.file_name(), where.line(), what);
|
||||
failures++;
|
||||
}
|
||||
}
|
||||
|
||||
template<typename Actual, typename Expected>
|
||||
void Equal(const Actual& actual, const Expected& expected, std::string_view what, std::source_location where = std::source_location::current()) {
|
||||
if(!(actual == expected)) {
|
||||
std::println("FAIL {}:{}: {}: expected '{}', got '{}'", where.file_name(), where.line(), what, expected, actual);
|
||||
failures++;
|
||||
}
|
||||
}
|
||||
|
||||
// `code` throws an E whose what() contains `part`.
|
||||
template<typename E = std::exception, typename Code>
|
||||
void Throws(Code&& code, std::string_view part, std::string_view what, std::source_location where = std::source_location::current()) {
|
||||
try {
|
||||
code();
|
||||
} catch(const E& e) {
|
||||
if(!std::string_view(e.what()).contains(part)) {
|
||||
std::println("FAIL {}:{}: {}: the error '{}' does not say '{}'", where.file_name(), where.line(), what, e.what(), part);
|
||||
failures++;
|
||||
}
|
||||
return;
|
||||
} catch(...) {
|
||||
std::println("FAIL {}:{}: {}: threw something else", where.file_name(), where.line(), what);
|
||||
failures++;
|
||||
return;
|
||||
}
|
||||
std::println("FAIL {}:{}: {}: did not throw", where.file_name(), where.line(), what);
|
||||
failures++;
|
||||
}
|
||||
|
||||
std::int32_t Result() {
|
||||
if(failures == 0) {
|
||||
std::println("all checks passed");
|
||||
return 0;
|
||||
}
|
||||
std::println("{} check(s) failed", failures);
|
||||
return 1;
|
||||
}
|
||||
|
||||
// A fresh directory for one test's files, deleted with everything in it when the test ends.
|
||||
struct Directory {
|
||||
std::filesystem::path path;
|
||||
|
||||
explicit Directory(std::string_view name) : path(std::filesystem::temp_directory_path() / std::format("nostro-{}-{}", name, std::random_device()())) {
|
||||
std::filesystem::create_directories(path);
|
||||
}
|
||||
|
||||
~Directory() {
|
||||
std::error_code ignored;
|
||||
std::filesystem::remove_all(path, ignored);
|
||||
}
|
||||
};
|
||||
}
|
||||
694
tests/Support/FakeBunq.inc
Normal file
694
tests/Support/FakeBunq.inc
Normal file
|
|
@ -0,0 +1,694 @@
|
|||
// 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<std::string>(), 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::string scheduledName = "ScheduledPayment";
|
||||
bool cardsActivate = true; // false: PUT card ACTIVE leaves the card as it is, as the sandbox does
|
||||
|
||||
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<std::string, Installation> installations; // by token
|
||||
std::map<std::string, Session> sessions; // by token
|
||||
std::map<std::string, std::uint64_t> keys; // API key or OAuth token: the user it opens a session for
|
||||
std::map<std::string, json> devices; // API key: the device-server body that registered it
|
||||
std::map<std::uint64_t, std::pair<std::string, json>> users; // id: the object's type and the object
|
||||
std::map<std::uint64_t, std::pair<std::string, json>> accounts; // id: the object's type and the object
|
||||
std::vector<json> extraAccountItems; // listed first, as they are
|
||||
std::map<std::uint64_t, std::vector<json>> payments; // account id: items, newest first
|
||||
std::map<std::uint64_t, std::vector<json>> inquiries; // account id: RequestInquiry items, newest first
|
||||
std::map<std::uint64_t, std::vector<json>> responses; // account id: RequestResponse items, newest first
|
||||
std::map<std::uint64_t, std::vector<json>> schedules; // account id: items, newest first
|
||||
std::map<std::uint64_t, std::vector<json>> drafts; // account id: DraftPayment items, newest first
|
||||
std::map<std::uint64_t, std::vector<json>> cards; // user id: card items
|
||||
std::map<std::string, std::string> codes; // OAuth authorization code: the token it gives
|
||||
std::string clientId = "fake-client";
|
||||
std::string clientSecret = "fake-secret";
|
||||
std::vector<Fault> faults;
|
||||
std::vector<Logged> 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, "<port> <file with this process's certificate>", 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<char>(file), std::istreambuf_iterator<char>())});
|
||||
}
|
||||
|
||||
// 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},
|
||||
{"order_status", "VIRTUAL_DELIVERY"},
|
||||
{"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<Logged> 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::size_t>(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<std::uint64_t>::max();
|
||||
}
|
||||
return item.begin().value().at("id").get<std::uint64_t>();
|
||||
}
|
||||
|
||||
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<std::string>();
|
||||
}
|
||||
}
|
||||
// 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<std::uint64_t> 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>() : std::string(), description, json::object());
|
||||
if(pointer.value("type", "") == "IBAN") {
|
||||
if(const std::optional<std::uint64_t> to = AccountOfIban(pointer.at("value").get<std::string>())) {
|
||||
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<json>& items, std::string_view path, std::string_view query) {
|
||||
const std::string count = Param(query, "count");
|
||||
const std::size_t limit = std::min<std::size_t>(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<std::uint64_t>::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<std::uint64_t>::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<json>& items, std::string_view type, std::uint64_t id) {
|
||||
for(json& item : items) {
|
||||
if(item.contains(type) && item.at(type).at("id").get<std::uint64_t>() == id) {
|
||||
return &item.at(type);
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
std::pair<std::uint16_t, json> Route(const std::string& method, const std::vector<std::string>& part, const std::string& path, const std::string& query, const json& body, const std::string& authentication) {
|
||||
const auto is = [&part](std::initializer_list<std::string_view> 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<std::string>()};
|
||||
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<json> 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<std::uint64_t>();
|
||||
}
|
||||
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();
|
||||
if(card.at("id").get<std::uint64_t>() == number(3)) {
|
||||
const std::string status = body.at("status").get<std::string>();
|
||||
if(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<std::uint64_t> payer = AccountOfIban(pointer.at("value").get<std::string>())) {
|
||||
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<std::string>();
|
||||
(*response)["status"] = status;
|
||||
json* inquiry = response->contains("inquiry") ? FindItem(inquiries[response->at("inquiry").at("account").get<std::uint64_t>()], "RequestInquiry", response->at("inquiry").at("id").get<std::uint64_t>()) : 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<json> 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<std::string>();
|
||||
(*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<json> Older(const std::vector<json>& items, std::string_view query) {
|
||||
return Param(query, "older_id").empty() ? items : std::vector<json>();
|
||||
}
|
||||
|
||||
Crafter::HTTPResponse Reply(std::uint16_t status, const std::string& body, std::optional<std::reference_wrapper<const Nostro::Crypto::Key>> signer) {
|
||||
std::unordered_map<std::string, std::string> 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) {
|
||||
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> 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<std::string> 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);
|
||||
}
|
||||
};
|
||||
}
|
||||
458
tests/Support/FakeBus.inc
Normal file
458
tests/Support/FakeBus.inc
Normal file
|
|
@ -0,0 +1,458 @@
|
|||
// SPDX-License-Identifier: LGPL-3.0-only
|
||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
// A system bus for tests, included after <systemd/sd-bus.h>, <systemd/sd-id128.h>, <poll.h>, <spawn.h>,
|
||||
// <sys/resource.h>, <sys/socket.h>, <sys/un.h>, <sys/wait.h>, <unistd.h> and `import std;`. It listens on a unix socket and stands in
|
||||
// for the bus driver, for logind and for polkit; every other call goes to the connection that owns the name it is sent
|
||||
// to, from the caller's unique name, and every answer back to whoever it is for. Each connection has a uid: one from
|
||||
// this test's own process gets Bus::clientUid as it is when the connection is made, so a test plays a user by setting
|
||||
// it before Client::System(); one from another process (nostrod, its workers) keeps its own. Point sd-bus at it by
|
||||
// setting DBUS_SYSTEM_BUS_ADDRESS to Address() before any thread starts, so before the Bus itself.
|
||||
|
||||
namespace Fake {
|
||||
// What polkit answers a check with.
|
||||
enum class Polkit : std::uint8_t {
|
||||
Allow, // authorized
|
||||
Password, // needs the user's password: authorized when the call lets a dialog ask for it, a challenge if not
|
||||
Deny, // refused by policy (polkit.result=no)
|
||||
Dismiss, // the dialog was closed: not authorized, polkit.result=auth_self, which is how Plasma's agent answers
|
||||
Absent, // no polkit on the bus: ServiceUnknown, without a message
|
||||
Silent, // never answers
|
||||
Slow, // authorized, a second later
|
||||
};
|
||||
|
||||
// One CheckAuthorization as polkit got it.
|
||||
struct PolkitCheck {
|
||||
std::string subject;
|
||||
std::string action;
|
||||
std::map<std::string, std::string> details;
|
||||
std::uint32_t flags = 0;
|
||||
std::string cancellation;
|
||||
};
|
||||
|
||||
class Bus {
|
||||
public:
|
||||
// Lock this around anything a test reads or changes while the bus runs.
|
||||
std::mutex mutex;
|
||||
std::uint32_t clientUid = 4242;
|
||||
std::map<std::uint32_t, std::string> logindNames;
|
||||
Polkit polkit = Polkit::Allow;
|
||||
std::map<std::string, Polkit, std::less<>> polkitByAction;
|
||||
std::vector<PolkitCheck> checks;
|
||||
std::vector<std::string> cancelled;
|
||||
// Credentials without the uid, as no bus sends them.
|
||||
bool omitUid = false;
|
||||
|
||||
explicit Bus(std::filesystem::path path) : path(std::move(path)) {
|
||||
listener = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
|
||||
sockaddr_un address{};
|
||||
address.sun_family = AF_UNIX;
|
||||
std::strncpy(address.sun_path, this->path.c_str(), sizeof(address.sun_path) - 1);
|
||||
if(bind(listener, reinterpret_cast<sockaddr*>(&address), sizeof(address)) != 0 || listen(listener, 64) != 0) {
|
||||
throw std::runtime_error(std::format("the fake bus cannot listen on {}", this->path.string()));
|
||||
}
|
||||
thread = std::thread([this] { Run(); });
|
||||
}
|
||||
|
||||
Bus(const Bus&) = delete;
|
||||
Bus& operator=(const Bus&) = delete;
|
||||
|
||||
~Bus() {
|
||||
stop = true;
|
||||
thread.join();
|
||||
close(listener);
|
||||
std::filesystem::remove(path);
|
||||
}
|
||||
|
||||
static std::string Address(const std::filesystem::path& path) {
|
||||
return std::format("unix:path={}", path.string());
|
||||
}
|
||||
|
||||
// Waits until `name` is owned, or not: false when `owned` is not reached within `timeout`.
|
||||
bool WaitForName(std::string_view name, bool owned = true, std::chrono::milliseconds timeout = std::chrono::seconds(20)) {
|
||||
const std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now() + timeout;
|
||||
while(std::chrono::steady_clock::now() < end) {
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
if(names.contains(name) == owned) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Ends the connection that owns `name`, as when the bus goes away under it.
|
||||
void Disconnect(std::string_view name) {
|
||||
std::lock_guard lock(mutex);
|
||||
dropping.emplace_back(name);
|
||||
}
|
||||
|
||||
// The other processes connected now: nostrod, and its workers.
|
||||
std::vector<pid_t> Peers() {
|
||||
std::lock_guard lock(mutex);
|
||||
std::vector<pid_t> peers;
|
||||
for(const Connection& connection : connections) {
|
||||
if(!connection.dead && connection.pid != getpid()) {
|
||||
peers.push_back(connection.pid);
|
||||
}
|
||||
}
|
||||
return peers;
|
||||
}
|
||||
|
||||
// The last check polkit got, or an empty one.
|
||||
PolkitCheck LastCheck() {
|
||||
std::lock_guard lock(mutex);
|
||||
return checks.empty() ? PolkitCheck() : checks.back();
|
||||
}
|
||||
|
||||
private:
|
||||
struct Connection {
|
||||
sd_bus* bus = nullptr;
|
||||
std::string unique;
|
||||
std::uint32_t uid = 0;
|
||||
pid_t pid = 0;
|
||||
bool dead = false;
|
||||
};
|
||||
|
||||
// An answer kept for later (Polkit::Slow).
|
||||
struct Later {
|
||||
std::chrono::steady_clock::time_point at;
|
||||
std::size_t connection = 0;
|
||||
sd_bus_message* call = nullptr;
|
||||
};
|
||||
|
||||
std::filesystem::path path;
|
||||
std::int32_t listener = -1;
|
||||
std::thread thread;
|
||||
std::atomic<bool> stop{false};
|
||||
std::vector<Connection> connections;
|
||||
std::map<std::string, std::size_t, std::less<>> names;
|
||||
std::vector<std::string> dropping;
|
||||
std::vector<Later> later;
|
||||
std::uint32_t nextUnique = 1;
|
||||
|
||||
// sd-bus hands strings out as C strings.
|
||||
// lint-disable-next-line no-char-pointer
|
||||
static std::string Text(const char* text) {
|
||||
return text ? std::string(text) : std::string();
|
||||
}
|
||||
|
||||
static std::string ReadString(sd_bus_message* message) {
|
||||
// lint-disable-next-line no-char-pointer
|
||||
const char* value = nullptr;
|
||||
sd_bus_message_read_basic(message, 's', &value);
|
||||
return Text(value);
|
||||
}
|
||||
|
||||
void Run() {
|
||||
while(!stop) {
|
||||
std::vector<pollfd> fds;
|
||||
{
|
||||
std::lock_guard lock(mutex);
|
||||
for(const std::string& name : std::exchange(dropping, {})) {
|
||||
if(const auto owner = names.find(name); owner != names.end()) {
|
||||
Drop(owner->second);
|
||||
}
|
||||
}
|
||||
AnswerLater();
|
||||
fds.push_back(pollfd{listener, POLLIN, 0});
|
||||
for(const Connection& connection : connections) {
|
||||
fds.push_back(pollfd{connection.dead ? -1 : sd_bus_get_fd(connection.bus), static_cast<std::int16_t>(connection.dead ? 0 : sd_bus_get_events(connection.bus)), 0});
|
||||
}
|
||||
}
|
||||
poll(fds.data(), fds.size(), 10);
|
||||
std::lock_guard lock(mutex);
|
||||
if((fds[0].revents & POLLIN) != 0) {
|
||||
Accept();
|
||||
}
|
||||
for(std::size_t i = 0; i < connections.size(); i++) {
|
||||
while(!connections[i].dead) {
|
||||
sd_bus_message* message = nullptr;
|
||||
const std::int32_t result = sd_bus_process(connections[i].bus, &message);
|
||||
if(result < 0) {
|
||||
Drop(i);
|
||||
break;
|
||||
}
|
||||
if(message) {
|
||||
Route(i, message);
|
||||
sd_bus_message_unref(message);
|
||||
}
|
||||
if(result == 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
std::lock_guard lock(mutex);
|
||||
for(Later& answer : later) {
|
||||
sd_bus_message_unref(answer.call);
|
||||
}
|
||||
for(std::size_t i = 0; i < connections.size(); i++) {
|
||||
Drop(i);
|
||||
}
|
||||
}
|
||||
|
||||
void Drop(std::size_t i) {
|
||||
if(connections[i].dead) {
|
||||
return;
|
||||
}
|
||||
connections[i].dead = true;
|
||||
sd_bus_flush_close_unref(connections[i].bus);
|
||||
connections[i].bus = nullptr;
|
||||
std::erase_if(names, [i](const auto& owner) { return owner.second == i; });
|
||||
}
|
||||
|
||||
void Accept() {
|
||||
const std::int32_t fd = accept4(listener, nullptr, nullptr, SOCK_CLOEXEC | SOCK_NONBLOCK);
|
||||
if(fd < 0) {
|
||||
return;
|
||||
}
|
||||
ucred peer{};
|
||||
socklen_t size = sizeof(peer);
|
||||
getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &peer, &size);
|
||||
Connection connection;
|
||||
connection.pid = peer.pid;
|
||||
connection.uid = peer.pid == getpid() ? clientUid : peer.uid;
|
||||
sd_bus_new(&connection.bus);
|
||||
sd_bus_set_fd(connection.bus, fd, fd);
|
||||
sd_id128_t id{};
|
||||
sd_id128_randomize(&id);
|
||||
sd_bus_set_server(connection.bus, 1, id);
|
||||
sd_bus_start(connection.bus);
|
||||
connections.push_back(connection);
|
||||
}
|
||||
|
||||
std::optional<std::size_t> Owner(std::string_view name) {
|
||||
if(name.starts_with(':')) {
|
||||
for(std::size_t i = 0; i < connections.size(); i++) {
|
||||
if(!connections[i].dead && connections[i].unique == name) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
const auto owner = names.find(name);
|
||||
return owner == names.end() ? std::nullopt : std::optional<std::size_t>(owner->second);
|
||||
}
|
||||
|
||||
template<typename... Args>
|
||||
void Reply(std::size_t to, sd_bus_message* call, std::string_view types, Args... args) {
|
||||
sd_bus_message* reply = nullptr;
|
||||
sd_bus_message_new_method_return(call, &reply);
|
||||
if(!types.empty()) {
|
||||
sd_bus_message_append(reply, std::string(types).c_str(), args...);
|
||||
}
|
||||
sd_bus_send(connections[to].bus, reply, nullptr);
|
||||
sd_bus_message_unref(reply);
|
||||
}
|
||||
|
||||
void Fail(std::size_t to, sd_bus_message* call, std::string_view name, const std::optional<std::string>& message) {
|
||||
sd_bus_message* reply = nullptr;
|
||||
const std::string errorName(name);
|
||||
const sd_bus_error error = {errorName.c_str(), message ? message->c_str() : nullptr, 0};
|
||||
sd_bus_message_new_method_error(call, &reply, &error);
|
||||
sd_bus_send(connections[to].bus, reply, nullptr);
|
||||
sd_bus_message_unref(reply);
|
||||
}
|
||||
|
||||
void Route(std::size_t from, sd_bus_message* message) {
|
||||
std::uint8_t type = 0;
|
||||
sd_bus_message_get_type(message, &type);
|
||||
const std::string destination = Text(sd_bus_message_get_destination(message));
|
||||
if(type == SD_BUS_MESSAGE_METHOD_CALL && destination == "org.freedesktop.DBus") {
|
||||
Driver(from, message);
|
||||
} else if(type == SD_BUS_MESSAGE_METHOD_CALL && destination == "org.freedesktop.login1") {
|
||||
Logind(from, message);
|
||||
} else if(type == SD_BUS_MESSAGE_METHOD_CALL && destination == "org.freedesktop.PolicyKit1") {
|
||||
PolicyKit(from, message);
|
||||
} else if(const std::optional<std::size_t> to = Owner(destination)) {
|
||||
if(type == SD_BUS_MESSAGE_METHOD_CALL) {
|
||||
// A call goes on from the caller's unique name, with its own cookie, so the answer finds it again.
|
||||
std::uint64_t cookie = 0;
|
||||
sd_bus_message_get_cookie(message, &cookie);
|
||||
sd_bus_message* copy = nullptr;
|
||||
sd_bus_message_new_method_call(connections[*to].bus, ©, destination.c_str(), sd_bus_message_get_path(message), sd_bus_message_get_interface(message), sd_bus_message_get_member(message));
|
||||
sd_bus_message_rewind(message, 1);
|
||||
sd_bus_message_copy(copy, message, 1);
|
||||
sd_bus_message_set_sender(copy, connections[from].unique.c_str());
|
||||
sd_bus_message_set_allow_interactive_authorization(copy, sd_bus_message_get_allow_interactive_authorization(message));
|
||||
sd_bus_message_seal(copy, cookie, 0);
|
||||
sd_bus_send(connections[*to].bus, copy, nullptr);
|
||||
sd_bus_message_unref(copy);
|
||||
} else {
|
||||
sd_bus_send(connections[*to].bus, message, nullptr);
|
||||
}
|
||||
} else if(type == SD_BUS_MESSAGE_METHOD_CALL) {
|
||||
Fail(from, message, SD_BUS_ERROR_SERVICE_UNKNOWN, std::format("The name {} was not provided by any .service files", destination));
|
||||
}
|
||||
}
|
||||
|
||||
void Driver(std::size_t from, sd_bus_message* call) {
|
||||
const std::string member = Text(sd_bus_message_get_member(call));
|
||||
if(member == "Hello") {
|
||||
connections[from].unique = std::format(":1.{}", nextUnique++);
|
||||
Reply(from, call, "s", connections[from].unique.c_str());
|
||||
} else if(member == "RequestName") {
|
||||
const std::string name = ReadString(call);
|
||||
const std::optional<std::size_t> owner = Owner(name);
|
||||
if(owner && *owner != from) {
|
||||
Reply(from, call, "u", 3u);
|
||||
return;
|
||||
}
|
||||
names[name] = from;
|
||||
Reply(from, call, "u", 1u);
|
||||
} else if(member == "GetConnectionUnixUser" || member == "GetConnectionCredentials") {
|
||||
const std::optional<std::size_t> owner = Owner(ReadString(call));
|
||||
const std::uint32_t uid = owner ? connections[*owner].uid : 0;
|
||||
const std::uint32_t pid = owner ? static_cast<std::uint32_t>(connections[*owner].pid) : 0;
|
||||
if(member == "GetConnectionUnixUser") {
|
||||
Reply(from, call, "u", uid);
|
||||
} else if(omitUid) {
|
||||
Reply(from, call, "a{sv}", 1, "ProcessID", "u", pid);
|
||||
} else {
|
||||
Reply(from, call, "a{sv}", 2, "UnixUserID", "u", uid, "ProcessID", "u", pid);
|
||||
}
|
||||
} else {
|
||||
// AddMatch, RemoveMatch, ReleaseName: done.
|
||||
Reply(from, call, "");
|
||||
}
|
||||
}
|
||||
|
||||
void Logind(std::size_t from, sd_bus_message* call) {
|
||||
const std::string member = Text(sd_bus_message_get_member(call));
|
||||
constexpr std::string_view prefix = "/org/freedesktop/login1/user/_";
|
||||
if(member == "GetUser") {
|
||||
std::uint32_t uid = 0;
|
||||
sd_bus_message_read_basic(call, 'u', &uid);
|
||||
if(!logindNames.contains(uid)) {
|
||||
Fail(from, call, "org.freedesktop.login1.NoSuchUser", std::format("No user {} known or logged in", uid));
|
||||
return;
|
||||
}
|
||||
Reply(from, call, "o", std::format("{}{}", prefix, uid).c_str());
|
||||
} else {
|
||||
// Properties.Get(interface, "Name") on a user's object.
|
||||
const std::string userPath = Text(sd_bus_message_get_path(call));
|
||||
std::uint32_t uid = 0;
|
||||
std::from_chars(userPath.data() + prefix.size(), userPath.data() + userPath.size(), uid);
|
||||
Reply(from, call, "v", "s", logindNames.at(uid).c_str());
|
||||
}
|
||||
}
|
||||
|
||||
void PolicyKit(std::size_t from, sd_bus_message* call) {
|
||||
if(Text(sd_bus_message_get_member(call)) == "CancelCheckAuthorization") {
|
||||
cancelled.push_back(ReadString(call));
|
||||
Reply(from, call, "");
|
||||
return;
|
||||
}
|
||||
PolkitCheck check;
|
||||
sd_bus_message_enter_container(call, 'r', "sa{sv}");
|
||||
ReadString(call);
|
||||
sd_bus_message_enter_container(call, 'a', "{sv}");
|
||||
while(sd_bus_message_enter_container(call, 'e', "sv") > 0) {
|
||||
ReadString(call);
|
||||
sd_bus_message_enter_container(call, 'v', "s");
|
||||
check.subject = ReadString(call);
|
||||
sd_bus_message_exit_container(call);
|
||||
sd_bus_message_exit_container(call);
|
||||
}
|
||||
sd_bus_message_exit_container(call);
|
||||
sd_bus_message_exit_container(call);
|
||||
check.action = ReadString(call);
|
||||
sd_bus_message_enter_container(call, 'a', "{ss}");
|
||||
while(sd_bus_message_enter_container(call, 'e', "ss") > 0) {
|
||||
std::string key = ReadString(call);
|
||||
check.details[std::move(key)] = ReadString(call);
|
||||
sd_bus_message_exit_container(call);
|
||||
}
|
||||
sd_bus_message_exit_container(call);
|
||||
sd_bus_message_read_basic(call, 'u', &check.flags);
|
||||
check.cancellation = ReadString(call);
|
||||
checks.push_back(check);
|
||||
|
||||
const auto chosen = polkitByAction.find(check.action);
|
||||
const Polkit outcome = chosen == polkitByAction.end() ? polkit : chosen->second;
|
||||
const bool prompt = (check.flags & 1) != 0;
|
||||
if(outcome == Polkit::Allow || (outcome == Polkit::Password && prompt)) {
|
||||
Reply(from, call, "(bba{ss})", 1, 0, 1, "polkit.result", "auth_self");
|
||||
} else if(outcome == Polkit::Password) {
|
||||
Reply(from, call, "(bba{ss})", 0, 1, 1, "polkit.result", "auth_self");
|
||||
} else if(outcome == Polkit::Deny) {
|
||||
Reply(from, call, "(bba{ss})", 0, 0, 1, "polkit.result", "no");
|
||||
} else if(outcome == Polkit::Dismiss) {
|
||||
Reply(from, call, "(bba{ss})", 0, 0, 1, "polkit.result", "auth_self");
|
||||
} else if(outcome == Polkit::Absent) {
|
||||
Fail(from, call, SD_BUS_ERROR_SERVICE_UNKNOWN, std::nullopt);
|
||||
} else if(outcome == Polkit::Slow) {
|
||||
later.push_back(Later{std::chrono::steady_clock::now() + std::chrono::seconds(1), from, sd_bus_message_ref(call)});
|
||||
}
|
||||
}
|
||||
|
||||
void AnswerLater() {
|
||||
const std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
|
||||
std::erase_if(later, [this, now](const Later& answer) {
|
||||
if(answer.at > now) {
|
||||
return false;
|
||||
}
|
||||
if(!connections[answer.connection].dead) {
|
||||
Reply(answer.connection, answer.call, "(bba{ss})", 1, 0, 1, "polkit.result", "auth_self");
|
||||
}
|
||||
sd_bus_message_unref(answer.call);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Whether this process is nostrod, or one of its workers, started by a test from its own executable.
|
||||
inline bool IsNostrod() {
|
||||
return std::getenv("NOSTRO_TEST_ROLE") != nullptr;
|
||||
}
|
||||
|
||||
// Starts this test's own executable as nostrod with `args`: its main runs nostrod's main when IsNostrod(). The
|
||||
// variables in `unset` are left out of its environment.
|
||||
inline pid_t StartNostrod(std::vector<std::string> args, std::vector<std::string_view> unset = {}) {
|
||||
args.insert(args.begin(), "nostrod");
|
||||
// posix_spawn takes C strings.
|
||||
// lint-disable-next-line no-char-pointer
|
||||
std::vector<char*> argv;
|
||||
for(std::string& arg : args) {
|
||||
argv.push_back(arg.data());
|
||||
}
|
||||
argv.push_back(nullptr);
|
||||
std::vector<std::string> variables;
|
||||
for(std::size_t i = 0; environ[i]; i++) {
|
||||
const std::string_view variable(environ[i]);
|
||||
if(std::ranges::none_of(unset, [variable](std::string_view name) { return variable.starts_with(std::format("{}=", name)); })) {
|
||||
variables.emplace_back(variable);
|
||||
}
|
||||
}
|
||||
variables.emplace_back("NOSTRO_TEST_ROLE=nostrod");
|
||||
// lint-disable-next-line no-char-pointer
|
||||
std::vector<char*> envp;
|
||||
for(std::string& variable : variables) {
|
||||
envp.push_back(variable.data());
|
||||
}
|
||||
envp.push_back(nullptr);
|
||||
pid_t pid = -1;
|
||||
posix_spawn(&pid, "/proc/self/exe", nullptr, nullptr, argv.data(), envp.data());
|
||||
return pid;
|
||||
}
|
||||
|
||||
// Sets the soft limit of `resource` for process `pid`, to see what it does when it reaches it, and returns the soft
|
||||
// limit it had. The hard limit stays, so the old one can be set again.
|
||||
inline rlim_t Limit(pid_t pid, decltype(RLIMIT_NOFILE) resource, rlim_t soft) {
|
||||
rlimit old{};
|
||||
prlimit(pid, resource, nullptr, &old);
|
||||
const rlimit limit{.rlim_cur = soft, .rlim_max = old.rlim_max};
|
||||
prlimit(pid, resource, &limit, nullptr);
|
||||
return old.rlim_cur;
|
||||
}
|
||||
|
||||
// Waits for a process this test started, and returns how it ended: its exit status, or 128 and the signal.
|
||||
inline std::int32_t Wait(pid_t pid) {
|
||||
std::int32_t status = 0;
|
||||
waitpid(pid, &status, 0);
|
||||
return WIFEXITED(status) ? WEXITSTATUS(status) : 128 + WTERMSIG(status);
|
||||
}
|
||||
}
|
||||
42
tests/coverage.sh
Executable file
42
tests/coverage.sh
Executable file
|
|
@ -0,0 +1,42 @@
|
|||
#!/bin/sh
|
||||
# SPDX-License-Identifier: LGPL-3.0-only
|
||||
# SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
# Runs the tests built with clang's source-based coverage and reports it for nostro's own sources, then lists every
|
||||
# line no test ran. Needs crafter-build, llvm-profdata, llvm-cov and llvm-readelf on PATH. A toolchain without compiler-rt's profile
|
||||
# runtime takes its libclang_rt.profile archive as the first argument. Leaves the profiles and the annotated sources in
|
||||
# build/coverage/.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
out=build/coverage
|
||||
rm -rf "$out"
|
||||
mkdir -p "$out"
|
||||
|
||||
if [ $# -gt 0 ]; then
|
||||
LLVM_PROFILE_FILE="$PWD/$out/%p.profraw" crafter-build test --banks=bunq --coverage "--profile-runtime=$1"
|
||||
else
|
||||
LLVM_PROFILE_FILE="$PWD/$out/%p.profraw" crafter-build test --banks=bunq --coverage
|
||||
fi
|
||||
llvm-profdata merge -sparse "$out"/*.profraw -o "$out/nostro.profdata"
|
||||
|
||||
# Each test's newest build with coverage mappings in it: a plain build can be newer, and a test whose sources did not
|
||||
# change is not linked again.
|
||||
set --
|
||||
for test in tests/Should*/; do
|
||||
name=$(basename "$test")
|
||||
for binary in $(ls -t bin/"$name"-*/"$name"); do
|
||||
if llvm-readelf -S "$binary" | grep -q __llvm_covfun; then
|
||||
if [ $# -eq 0 ]; then
|
||||
set -- "$binary"
|
||||
else
|
||||
set -- "$@" -object "$binary"
|
||||
fi
|
||||
break
|
||||
fi
|
||||
done
|
||||
done
|
||||
|
||||
ignore='(lib/json\.hpp|/tests/|/Crafter\.|/app/|/usr/)'
|
||||
llvm-cov report "$@" -instr-profile="$out/nostro.profdata" -ignore-filename-regex="$ignore"
|
||||
llvm-cov show "$@" -instr-profile="$out/nostro.profdata" -ignore-filename-regex="$ignore" -format=text > "$out/sources.txt"
|
||||
awk '/^\/.*:$/ { file = $0 } /^ *[0-9]+\| *0\|/ { split($0, part, "|"); gsub(/ /, "", part[1]); print "not run: " file part[1] }' "$out/sources.txt"
|
||||
Loading…
Reference in a new issue