Nostro/tests/ShouldServeEveryUser/main.cpp
Jorijn van der Graaf 2e3739ff7a
fix: close what the security review before the first release found
A review of the tree and its history before they are published found no
key and no bank data in them. It did find these, each closed here.

The password dialog could be emptied (daemon). Shown(), which makes a
payee's name fit for polkit's dialog, let an & through. GNOME's older
agent (polkit-gnome) and MATE's put the message into Pango markup
unescaped, where a bare & fails to parse and leaves the dialog without
a message: paying "Tom & Jerry", or an order an app names so at
checkout, asked for the password and showed no amount and no payee.
Line and paragraph separators passed too. Shown() now shows & as +,
leaves out what draws nothing or places text (control and format
characters, the separators, what Unicode ignores by default, private
use) and makes any run of spaces one space. An address is held to it
instead of made fit: an e-mail address the dialog could not show
unchanged is refused before anyone is asked, since "a&b@..." shown as
"a+b@..." is somebody else's address.

A refused caller could look (daemon). A call that names an account, a
card, a request, a draft or a connector had it looked up, at the bank
where that takes it, before polkit was asked. So a caller polkit
refused was told whether it was there ("no account is called ..."),
and had the bank asked. Such a call now asks for View first
(HandleLookup), a call that only sees looks its account up after its
yes, and the connectors are read, which refreshes the accounts at the
bank, on the first yes instead of on the first call.

An app at checkout was told too much (checkout). The refusal of an
order's reference with another amount named the amount on record, and
a refusal by the bank carried the call it answered, whose path has the
user's and the account's ids at bunq. Neither does now.

A key typed by hand could be read off the screen (app). The line under
a key field showed how the key begins and its last four characters,
which is every character of it as it is typed. It shows how the key
begins and how long it is.

Every change asks for the password (packaging, app). Change, the
action for what changes something and pays nobody, passed without a
password in an active session, so any program of the user's could
cancel a scheduled payment, ask for money in their name or freeze a
card. It asks now (auth_self), a draft saved and a card frozen
included: only View passes as shipped, and loosening is an
administrator's rule, of which the README has an example. The app says
of every change where it is confirmed (AsksPassword is gone), and the
request form sends on its button as the pay form does: its review
sheet would be a second confirmation of what the dialog confirms.

What is built is what was tested (build). Crafter.Network, Crafter.DB
and Crafter.LintRules are named at the commits the tests ran against.
Crafter.Thread still follows its branch, which Crafter.Network's own
project file names, and so does Crafter.Network in the app's debug
build, where Crafter.Debug names it too and crafter-build refuses a
module built twice. lib/json.hpp was nlohmann/json's develop branch at
95e9a593 less its last newline, and called 3.12.0: it is that file
byte for byte now, and called what it is.

The published contract changes with this, before any release (design
rule 10): an e-mail address the dialog cannot show as it is is
refused, a call that looks something up needs View as well as its own
action, the checkout's errors say less, and the policy asks for the
password for Change. The XML, the policy and ShouldServeEveryUser,
which now holds the policy to its defaults, change together.

Reproduced and verified on the fake bus and the fake bunq. The new
checks of ShouldServeEveryUser fail on the worker of before (50 of
them: the & shown, the lookups answered, the bank asked) and pass now.
crafter-build test (17 tests), lint for the library, the app and the
fake system, and tests/coverage.sh (every line, function and region)
pass. Looked at on the made-up system, 360x760 dp at scale 2, dark, on
KDE Wayland: the key form with a key typed, the request form with its
wait and its result, a card frozen, and About. No picture in the
README shows a screen that changed.

Not tried: bunq's sandbox, a real polkit agent, the Flatpak builds.
The README's example rule ran against a stand-in for polkit's rule
engine only.

Co-Authored-By: Claude Mythos 5.2 <noreply@anthropic.com>
2026-11-19 16:09:48 +01:00

946 lines
63 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 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();
}
// How often polkit was asked about something that takes a password as shipped: everything but seeing, which a
// call that names an account or a card asks about first, and which an active session has without a dialog.
std::size_t Asked(Fake::Bus& bus) {
std::lock_guard lock(bus.mutex);
return static_cast<std::size_t>(std::ranges::count_if(bus.checks, [](const Fake::PolkitCheck& check) { return check.action != Bus::actionView; }));
}
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,
// and each but seeing asking for the user's password as it is shipped.
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()));
// Secure as shipped: in the user's own session only seeing passes without their password, everything else
// asks for it every time, and nothing passes from anywhere else. Loosening that is an administrator's rule.
const std::string_view inSession = declared.back() == Bus::actionView ? "<allow_active>yes</allow_active>" : "<allow_active>auth_self</allow_active>";
Check(action.contains(inSession) && action.contains("<allow_inactive>auth_self</allow_inactive>") && action.contains("<allow_any>auth_self</allow_any>"), std::format("{} asks for the user's password as shipped, unless it only looks, and keeps no authorization", 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");
// An API key says itself which environment it is of. One the caller names is held to that, before anyone is
// asked and before the key goes anywhere: a real key is not shown to the sandbox.
const auto prompted = [&bus] {
std::lock_guard lock(bus.mutex);
return bus.checks.size();
};
const std::size_t prompts = prompted();
Throws<std::invalid_argument>([&bob] { bob.AddBunq("key-bob", "", "sandbox"); }, "that API key is a production key, not a sandbox one", "a key that is not a sandbox key is not sent to the sandbox");
Throws<std::invalid_argument>([&bob] { bob.AddBunq("sandbox_key-bob", "", "production"); }, "that API key is a sandbox key, not a production one", "nor a sandbox key taken for a real one");
Check(prompted() == prompts && bob.Connectors().empty(), "nobody is asked for a password for either, and nothing is connected");
Equal(bob.AddBunq("key-bob", "", "production").environment, std::string("production"), "an environment named by the caller, which the key is of");
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(36, 'y'), aliceMain), "a name made safe to show");
// An agent that reads its message as markup shows nothing of one with a bare & in it, the amount included.
alice.Send(aliceMain, bobIban, "Tom & Jerry", 100, "");
Equal(Summary(bus), std::format("pay €1.00 to {} (Tom + Jerry) from {} (Main)", bobIban, aliceMain), "an & is shown as a +");
// Nothing starts a line of its own or leaves a gap: an em space first, then a soft hyphen, an Arabic letter
// mark, a space, a no-break space and a blank Braille pattern, a line and a paragraph separator, a tag, a
// private-use character and a variation selector, and two spaces last.
alice.Send(aliceMain, bobIban, "\xE2\x80\x83 Ann\xC2\xAD\xD8\x9C \xC2\xA0\xE2\xA0\x80Lee\xE2\x80\xA8\xE2\x80\xA9\xF3\xA0\x81\x81\xEE\x80\x80\xEF\xB8\x8F ", 100, "");
Equal(Summary(bus), std::format("pay €1.00 to {} (Ann Lee) from {} (Main)", bobIban, aliceMain), "what draws nothing is left out, and spaces of any kind are one space between words");
// 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");
// An address decides where the money goes, so the dialog shows it whole and as it is, or nobody is asked: one
// with an & would read as one with a +, which is another address.
const std::size_t passwords = Asked(bus);
const std::string addressRefused = "the password dialog would not show that address as it is";
Throws<std::invalid_argument>([&alice] { alice.Send(aliceMain, "tom&jerry@example.com", "Tom", 100, ""); }, addressRefused, "an address with an &");
Throws<std::invalid_argument>([&alice] { alice.Request(aliceMain, "tom\xE2\x80\x8Bjerry@example.com", "Tom", 100, ""); }, addressRefused, "one with a character that draws nothing");
Throws<std::invalid_argument>([&alice] { alice.Draft(aliceMain, std::format("{}@example.com", std::string(250, 'a')), "Tom", 100, ""); }, addressRefused, "one longer than an address gets");
Throws<std::invalid_argument>([&alice, start = std::chrono::sys_days(std::chrono::year(2027) / 1 / 1)] { alice.Schedule(aliceMain, "<tom@example.com>", "Tom", 100, "", BunqSchedule{.start = start, .unit = "ONCE"}); }, addressRefused, "one in angle brackets");
Equal(Asked(bus), passwords, "and nobody is asked for a password for any of them");
const std::string longAddress = std::format("{}@example.com", std::string(70, 'a'));
alice.Send(aliceMain, longAddress, "Tom", 100, "");
Check(Summary(bus) == std::format("pay €1.00 to {} (Tom) from {} (Main)", longAddress, aliceMain) && bus.LastCheck().details.at("counterparty") == longAddress, "an address longer than a name may be is shown whole, and given to rules whole");
alice.Accounts();
Check(bus.LastCheck().action == "net.catcrafts.Nostro1.View" && Summary(bus) == "see your accounts and balances", "listing is the View action");
const std::size_t listed = alice.Transactions(aliceMain, {}).size();
Equal(Summary(bus), std::string("see your transactions"), "so are the transactions");
// From what nostrod has stored alone: the bank is not asked, so what it has had since is not among it.
bunq.AddPayment(bank.aliceMainId, 4200, "Carol", "NL65BUNQ2025222222", "since the last look");
const std::size_t calls = bunq.Count("GET", "/user/");
Equal(alice.Transactions(aliceMain, {.stored = true}).size(), listed, "a question about what is stored is answered from it");
Check(bunq.Count("GET", "/user/") == calls && Summary(bus) == "see your transactions", "without a call to the bank, and after the same check");
Equal(alice.Transactions(aliceMain, {.search = "since the last look", .stored = true}).size(), std::size_t{0}, "so a payment the bank has had since is not found there");
Check(alice.Transactions(aliceMain, {.search = "since the last look"}).size() == 1 && bunq.Count("GET", "/user/") == calls + 1, "any other question asks the bank first, and finds it");
Equal(alice.Transactions(aliceMain, {.search = "since the last look", .stored = true}).size(), std::size_t{1}, "after which it is stored");
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");
// A virtual card is not frozen or unfrozen: bunq would leave it as it is and answer as if it had been done. It
// is refused before anyone is asked for a password, and bunq is not asked to change anything.
const std::uint64_t number = bunq.AddCard(bank.alice, "DEACTIVATED", json{{"order_status", "VIRTUAL_DELIVERY"}, {"primary_account_numbers", json::array({json{{"four_digit", "4321"}}})}});
const std::size_t prompts = Asked(bus);
const std::size_t changes = bunq.Count("PUT", "/user/");
for(const std::string_view status : {"DEACTIVATED", "ACTIVE"}) {
Throws<std::invalid_argument>([&alice, number, status] { alice.SetCardStatus(number, status); }, std::format("card {} is a virtual card, which bunq does not freeze or unfreeze when asked", number), "a virtual card is not frozen or unfrozen");
}
Check(Asked(bus) == prompts && bunq.Count("PUT", "/user/") == changes, "nobody is asked for a password for it, and bunq is not asked");
Equal(alice.SetCardStatus(number, "LOST").status, std::string("LOST"), "it is reported lost like any card");
Check(bus.LastCheck().action == "net.catcrafts.Nostro1.BlockCard" && Summary(bus) == "report card **** 4321 lost, which blocks it for good", "which blocks it for good, after the password for that");
}
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");
}
// What a call names is looked up for a caller who may see the user's accounts, and for no other: one polkit
// refuses that is told nothing of what is there, and has the bank asked nothing.
void Lookups(Fake::Bus& bus, Fake::Bunq& bunq, pid_t nostrod) {
Client alice = As(bus, aliceUid);
const std::string_view accounts = "see your accounts and balances";
const BunqSchedule once{.start = std::chrono::sys_days(std::chrono::year(2027) / 1 / 1), .unit = "ONCE"};
// Each call, with something that is there or something that is not, and what polkit is asked to let it see.
const std::vector<std::tuple<std::string_view, std::function<void()>, std::string_view>> calls = {
{"a payment from an account nobody has", [&alice] { alice.Send("Nope", bobIban, "Bob", 100, ""); }, accounts},
{"a payment from an account there is", [&alice] { alice.Send(aliceMain, bobIban, "Bob", 100, ""); }, accounts},
{"a schedule", [&alice, &once] { alice.Schedule("Nope", bobIban, "Bob", 100, "", once); }, accounts},
{"a request for money", [&alice] { alice.Request("Nope", bobIban, "Bob", 100, ""); }, accounts},
{"a draft", [&alice] { alice.Draft("Nope", bobIban, "Bob", 100, ""); }, accounts},
{"revoking a request", [&alice] { alice.RevokeRequest("Nope", 1); }, accounts},
{"cancelling a schedule", [&alice] { alice.CancelScheduledPayment(aliceMain, 1); }, accounts},
{"answering a request", [&alice] { alice.RespondToRequest(aliceMain, 1, true); }, "see your incoming requests for money"},
{"answering a draft", [&alice] { alice.RespondToDraftPayment(aliceMain, 1, false); }, "see your draft payments"},
{"a card's status", [&alice] { alice.SetCardStatus(1, "LOST"); }, "see your cards"},
{"the account that pays at checkout", [&alice] { alice.SetDefaultCheckoutAccount("Nope"); }, accounts},
{"removing a connector", [&alice] { alice.RemoveConnector("Nobody"); }, "see your bank connectors"},
{"the transactions of an account nobody has", [&alice] { alice.Transactions("Nope", {}); }, "see your transactions"},
{"a listing of one", [&alice] { alice.Requests("Nope"); }, "see your requests for money"},
};
SetPolkit(bus, Fake::Polkit::Deny, Bus::actionView);
const std::size_t prompts = Asked(bus);
const std::size_t questions = bunq.Count("GET", "/user/");
for(const auto& [what, call, seen] : calls) {
const Failure refused = FailureOf(call);
Check(refused.name == SD_BUS_ERROR_ACCESS_DENIED && refused.message.contains("does not allow net.catcrafts.Nostro1.View"), std::format("{}, asked by a caller who may not see the accounts: {}", what, refused.message));
Check(bus.LastCheck().action == Bus::actionView && Summary(bus) == seen, std::format("{}: polkit is asked whether the caller may {}", what, seen));
}
Equal(Asked(bus), prompts, "nobody is asked for a password for any of it");
Equal(bunq.Count("GET", "/user/"), questions, "and the bank is asked nothing");
// Where seeing the accounts takes a password, a call that looks something up asks for it first.
SetPolkit(bus, Fake::Polkit::Dismiss, Bus::actionView);
Equal(FailureOf([&alice] { alice.Send(aliceMain, bobIban, "Bob", 100, ""); }).name, std::string(Bus::errorCancelled), "a password to look, not given");
SetPolkit(bus, Fake::Polkit::Password, Bus::actionView);
const std::string unasked = Raw(bus, name, name, "Send", false, [](sd_bus_message* call) {
sd_bus_message_append(call, "sssxs", aliceMain.c_str(), bobIban.c_str(), "Bob", std::int64_t{100}, "");
});
Equal(unasked, std::string(SD_BUS_ERROR_INTERACTIVE_AUTHORIZATION_REQUIRED), "or one the call did not let nostrod ask for");
Equal(Asked(bus), prompts, "and still nobody is asked about the payment itself");
Check(alice.Send(aliceMain, bobIban, "Bob", 100, "").id != 0, "given, the call goes on");
const std::pair<std::string, std::string> lastTwo = [&bus] {
std::lock_guard lock(bus.mutex);
return std::pair(bus.checks.at(bus.checks.size() - 2).action, bus.checks.back().action);
}();
Check(lastTwo.first == Bus::actionView && lastTwo.second == Bus::actionPay, "and asks twice: to look, and then to pay");
// A worker just started reads the user's connectors, which asks the bank, for the first caller polkit says
// yes to, and for none before.
KillWorkers(bus, nostrod);
SetPolkit(bus, Fake::Polkit::Deny, Bus::actionView);
const std::size_t before = bunq.Count("GET", "/user/");
Equal(FailureOf([&bus] { As(bus, aliceUid).Accounts(); }).name, std::string(SD_BUS_ERROR_ACCESS_DENIED), "a caller a new worker refuses");
Equal(bunq.Count("GET", "/user/"), before, "has the bank asked nothing either");
SetPolkit(bus, Fake::Polkit::Allow);
Check(!As(bus, aliceUid).Connectors().empty() && bunq.Count("GET", "/user/") > before, "the first caller polkit lets in has the connectors read");
}
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 another amount than €13.00", "a reference paid for another amount");
// Which amount it was paid for is not said: whoever knows an order's payee and reference could ask for it.
const Failure other = FailureOf([&pay, &changed] { pay(changed); });
Check(!other.message.contains("12.50") && !other.message.contains("1250"), std::format("and not for which amount: {}", other.message));
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("bunq: Not enough money. (400)"), std::format("bunq's refusal: {}", poor.message));
// The app is told what the bank said, and not which call it said it to: that names the user and the account.
const auto namesNoAccount = [](const Failure& failure) {
return !failure.message.contains("/user/") && !failure.message.contains("monetary-account") && !failure.message.contains(aliceMain);
};
Check(namesNoAccount(poor), std::format("without the user or the account at the bank: {}", poor.message));
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") && namesNoAccount(hiccup), std::format("an answer that may hide a payment, also without the account: {}", 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 another amount than €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);
Lookups(bus, bunq, nostrod);
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();
}