813 lines
50 KiB
C++
813 lines
50 KiB
C++
// 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();
|
||
}
|