Skip to content
Repos

mologram

C++ 12.3 KB296 lines Opens in site

Directory Raw Download

// Daemon, RemoteService, framing, cache: real sockets, real threads, failure injection (races, killed peers, stale socket,
// full disk). SPEC 6.4, SEC-04, OPS-02, D-13.
#include <sys/resource.h>
#include <sys/socket.h>

#include <atomic>
#include <chrono>
#include <csignal>
#include <deque>
#include <filesystem>
#include <fstream>
#include <future>
#include <mutex>
#include <thread>

#include "tttest.hpp"
#include "mologram/Daemon.hpp"
#include "mologram/FakeTelegramService.hpp"
#include "mologram/MediaCache.hpp"
#include "mologram/RemoteService.hpp"
#include "mologram/Sha256.hpp"
#include "mologram/SocketUtil.hpp"

using namespace mologram;
namespace fs = std::filesystem;
using js::Object;
using js::Value;

namespace {

struct TempDir {
  std::string path;
  TempDir() {
    char t[] = "/tmp/mologram-test-XXXXXX";
    path = mkdtemp(t);
  }
  ~TempDir() { std::error_code ec; fs::remove_all(path, ec); }
  std::string sock() const { return path + "/d.sock"; }
};

template <class F>
bool waitFor(F pred, int ms = 8000) {
  auto end = std::chrono::steady_clock::now() + std::chrono::milliseconds(ms);
  while (std::chrono::steady_clock::now() < end) {
    if (pred()) return true;
    std::this_thread::sleep_for(std::chrono::milliseconds(2));
  }
  return pred();
}

struct Collector : IEventSink {
  std::mutex m;
  std::vector<Event> ev;
  void onEvent(const Event& e) override { std::lock_guard<std::mutex> g(m); ev.push_back(e); }
  int count(const std::string& n) { std::lock_guard<std::mutex> g(m); int c = 0; for (auto& e : ev) if (e.name == n) c++; return c; }
  std::vector<std::string> ids(const std::string& n) {
    std::lock_guard<std::mutex> g(m);
    std::vector<std::string> v;
    for (auto& e : ev) if (e.name == n) v.push_back(js::getStr(*e.data.find("message"), "id"));
    return v;
  }
};

struct Running {
  FakeTelegramService svc;
  Daemon daemon;
  std::thread th;
  explicit Running(const std::string& sock) : daemon(svc, sock) {}
  std::string start() {
    std::string err = daemon.start();
    if (err.empty()) th = std::thread([this]() { daemon.run(); });
    return err;
  }
  void stopAndJoin() { daemon.stop(); if (th.joinable()) th.join(); }
  ~Running() { stopAndJoin(); }
};

RpcResult callSync(ITelegramService& s, const std::string& m, Object p = {}) {
  auto pr = std::make_shared<std::promise<RpcResult>>();
  auto fu = pr->get_future();
  s.call(m, Value(std::move(p)), [pr](const RpcResult& r) { pr->set_value(r); });
  if (fu.wait_for(std::chrono::seconds(8)) != std::future_status::ready) return RpcResult::failure("test", "no reply");
  return fu.get();
}

}  // namespace

TEST_CASE("sha256 known vectors", "[daemon][unit]") {
  CHECK_EQ(Sha256::hexOf(""), std::string("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"));
  CHECK_EQ(Sha256::hexOf("abc"), std::string("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"));
  CHECK_EQ(Sha256::hexOf(std::string(1000, 'a')), std::string("41edece42d63e8d9bf515a9ba6932e1c20cbc9f5a5d134645adb5db1b9737ea3"));
}

TEST_CASE("frame reader handles byte-by-byte feeds, rejects garbage without any size cap", "[daemon][unit]") {
  Value v = Value(Object{{"hello", Value("w\xC3\xB6rld")}});
  std::string bytes = FrameCodec::encode(v);
  FrameReader r;
  Value out;
  for (size_t i = 0; i + 1 < bytes.size(); i++) { r.feed(&bytes[i], 1); CHECK(r.next(out) == FrameReader::Status::NeedMore); }
  r.feed(&bytes.back(), 1);
  REQUIRE(r.next(out) == FrameReader::Status::Frame);
  CHECK_EQ(js::getStr(out, "hello"), std::string("w\xC3\xB6rld"));
  FrameReader bad; bad.feed("XXXXjunk", 8);
  CHECK(bad.next(out) == FrameReader::Status::BadFrame);
  FrameReader partialBad; partialBad.feed("MLX", 3);
  CHECK(partialBad.next(out) == FrameReader::Status::BadFrame);
  // a huge declared length is simply "need more", not an allocation
  FrameReader huge; huge.feed("MLG1\xFF\xFF\xFF\xFF", 8);
  CHECK(huge.next(out) == FrameReader::Status::NeedMore);
}

TEST_CASE("remote calls round trip and events reach every attached client", "[daemon][integration]") {
  TempDir d; Running run(d.sock());
  REQUIRE(run.start().empty());
  RemoteService a(d.sock()), b(d.sock()); Collector ca, cb;
  a.addSink(&ca); b.addSink(&cb);
  a.start(); b.start();
  REQUIRE(a.waitConnected(nullptr)); REQUIRE(b.waitConnected(nullptr));
  RpcResult hello = callSync(a, "hello");
  REQUIRE(hello.ok);
  CHECK_EQ(js::getInt(hello.value, "proto_version"), 1);
  RpcResult sent = callSync(a, "messages.send", {{"peer", Value("user:100")}, {"text", Value("hi")}});
  REQUIRE(sent.ok);
  CHECK(waitFor([&] { return ca.count("message.new") == 1 && cb.count("message.new") == 1; }));
  RpcResult bad = callSync(b, "messages.send", {{"peer", Value("user:100")}});
  CHECK_EQ(bad.error.code, std::string(ErrorCode::BadParams));
  CHECK_EQ(callSync(b, "no.such").error.code, std::string(ErrorCode::UnknownMethod));
}

TEST_CASE("burst of 1000 events arrives complete and in order at two clients", "[daemon][integration]") {
  TempDir d; Running run(d.sock());
  REQUIRE(run.start().empty());
  RemoteService a(d.sock()), b(d.sock()); Collector ca, cb;
  a.addSink(&ca); b.addSink(&cb); a.start(); b.start();
  REQUIRE(a.waitConnected(nullptr)); REQUIRE(b.waitConnected(nullptr));
  REQUIRE(waitFor([&] { return run.daemon.attached() == 2; }));
  std::vector<std::string> sentIds;
  for (int i = 0; i < 1000; i++) sentIds.push_back(std::to_string(run.svc.simulateIncoming({PeerKind::User, 101}, "m" + std::to_string(i)).id));
  CHECK(waitFor([&] { return ca.count("message.new") == 1000 && cb.count("message.new") == 1000; }));
  CHECK(ca.ids("message.new") == sentIds);
  CHECK(cb.ids("message.new") == sentIds);
}

TEST_CASE("bad magic and bad version are rejected, answered and counted", "[daemon][integration]") {
  TempDir d; Running run(d.sock());
  REQUIRE(run.start().empty());
  {
    int e; Fd c = SocketUtil::connectUnix(d.sock(), e); REQUIRE(c.valid());
    SocketUtil::writeAll(c.get(), "NOPE0000", 8);
    char buf[512]; ssize_t n = ::recv(c.get(), buf, sizeof(buf), 0);
    CHECK(n > 0);
    CHECK(waitFor([&] { return run.daemon.stats().rejectedFrames.load() == 1; }));
  }
  {
    int e; Fd c = SocketUtil::connectUnix(d.sock(), e); REQUIRE(c.valid());
    Object o; o["v"] = Value(2); o["id"] = js::id(1); o["m"] = Value("hello"); o["p"] = Value(Object{});
    std::string f = FrameCodec::encode(Value(std::move(o)));
    SocketUtil::writeAll(c.get(), f.data(), f.size());
    char buf[1024]; ssize_t n = ::recv(c.get(), buf, sizeof(buf), 0);
    REQUIRE(n > 8);
    CHECK(std::string(buf + 8, (size_t)n - 8).find("bad_version") != std::string::npos);
    CHECK(waitFor([&] { return run.daemon.stats().badVersion.load() == 1; }));
  }
  CHECK_EQ((int)run.svc.rejectedCalls(), 0);
}

TEST_CASE("a killed UI process does not disturb the daemon or other clients", "[daemon][integration]") {
  TempDir d; Running run(d.sock());
  REQUIRE(run.start().empty());
  {
    int e; Fd c = SocketUtil::connectUnix(d.sock(), e); REQUIRE(c.valid());
    for (int i = 0; i < 20; i++) {
      std::string f = FrameCodec::encode(Wire::request(i + 1, "dialogs.list", Value(Object{})));
      SocketUtil::writeAll(c.get(), f.data(), f.size());
    }
    // closes with unread replies pending: abrupt death
  }
  RemoteService b(d.sock()); b.start();
  REQUIRE(b.waitConnected(nullptr));
  CHECK(callSync(b, "dialogs.folders").ok);
  CHECK(waitFor([&] { return run.daemon.attached() == 1; }));
}

TEST_CASE("stale socket file is detected and replaced; a live daemon and a second lock holder are refused", "[daemon][integration]") {
  TempDir d;
  {
    std::string err; Fd l = SocketUtil::listenUnix(d.sock(), err); REQUIRE(l.valid());
  }  // listener closed, socket file stays: stale
  REQUIRE(fs::exists(d.sock()));
  Running run(d.sock());
  CHECK(run.start().empty());
  CHECK_EQ((int)run.daemon.stats().staleSocketsRemoved.load(), 1);
  FakeTelegramService other;
  Daemon second(other, d.sock());
  std::string err = second.start();
  CHECK(err.find("lock") != std::string::npos);
}

TEST_CASE("daemon death fails pending calls with disconnected and the client reconnects when it returns", "[daemon][integration]") {
  TempDir d;
  auto run = std::make_unique<Running>(d.sock());
  REQUIRE(run->start().empty());
  RemoteService a(d.sock()); Collector c; a.addSink(&c); a.start();
  REQUIRE(a.waitConnected(nullptr));
  CHECK(callSync(a, "dialogs.folders").ok);
  run.reset();  // daemon killed
  CHECK(waitFor([&] { return !a.connected(); }));
  CHECK_EQ(callSync(a, "dialogs.folders").error.code, std::string(ErrorCode::Disconnected));
  auto again = std::make_unique<Running>(d.sock());
  REQUIRE(again->start().empty());
  CHECK(waitFor([&] { return a.connected(); }, 10000));
  CHECK(callSync(a, "dialogs.folders").ok);
  CHECK(a.reconnects() >= 2);
  CHECK(c.count("connection.state") >= 3);
}

namespace {
struct DeferredFake : FakeTelegramService {
  std::mutex qm; std::deque<std::function<void()>> q;
  void execute(std::function<void()> job) override { std::lock_guard<std::mutex> g(qm); q.push_back(std::move(job)); }
  void drain() { for (;;) { std::function<void()> j; { std::lock_guard<std::mutex> g(qm); if (q.empty()) return; j = q.front(); q.pop_front(); } j(); } }
  size_t queued() { std::lock_guard<std::mutex> g(qm); return q.size(); }
};
}  // namespace

TEST_CASE("cancel travels over the wire and the request ends cancelled", "[daemon][integration]") {
  TempDir d; DeferredFake svc; Daemon daemon(svc, d.sock());
  REQUIRE(daemon.start().empty());
  std::thread th([&] { daemon.run(); });
  RemoteService a(d.sock()); a.start();
  REQUIRE(a.waitConnected(nullptr));
  auto pr = std::make_shared<std::promise<RpcResult>>(); auto fu = pr->get_future();
  RequestId id = a.call("dialogs.folders", Value(Object{}), [pr](const RpcResult& r) { pr->set_value(r); });
  REQUIRE(waitFor([&] { return svc.queued() == 1; }));
  a.cancel(id);
  std::this_thread::sleep_for(std::chrono::milliseconds(100));  // let the cancel frame reach the daemon
  svc.drain();
  REQUIRE(fu.wait_for(std::chrono::seconds(8)) == std::future_status::ready);
  CHECK_EQ(fu.get().error.code, std::string(ErrorCode::Cancelled));
  daemon.stop(); th.join();
}

TEST_CASE("media cache stores, verifies, rejects tampering, survives a full disk", "[daemon][cache][integration]") {
  TempDir d; MediaCache cache(d.path + "/cache");
  std::string err;
  std::string p = cache.put("tok:1", "hello bytes", err);
  REQUIRE(!p.empty());
  CHECK(cache.get("tok:1").has_value());
  CHECK(!cache.get("tok:missing").has_value());
  { std::ofstream t(p, std::ios::binary | std::ios::trunc); t << "tampered"; }
  CHECK(!cache.get("tok:1").has_value());
  CHECK_EQ((int)cache.rejected(), 1);
  // full disk: a file size limit makes write() fail with EFBIG, a real failure injection
  std::signal(SIGXFSZ, SIG_IGN);
  rlimit old; getrlimit(RLIMIT_FSIZE, &old);
  rlimit small = old; small.rlim_cur = 100;
  setrlimit(RLIMIT_FSIZE, &small);
  std::string err2;
  std::string p2 = cache.put("tok:big", std::string(100000, 'x'), err2);
  setrlimit(RLIMIT_FSIZE, &old);
  CHECK(p2.empty());
  CHECK(!err2.empty());
  CHECK(!cache.get("tok:big").has_value());
}

TEST_CASE("daemon stops when the last UI process leaves unless told to stay", "[daemon][integration]") {
  TempDir d; FakeTelegramService svc; Daemon daemon(svc, d.sock());
  daemon.setStopWhenEmpty(true);
  REQUIRE(daemon.start().empty());
  std::atomic<bool> returned{false};
  std::thread th([&] { daemon.run(); returned = true; });
  {
    RemoteService a(d.sock()); a.start();
    REQUIRE(a.waitConnected(nullptr));
    CHECK(callSync(a, "hello").ok);
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
    CHECK(!returned.load());  // still attached
  }
  CHECK(waitFor([&] { return returned.load(); }));
  th.join();
}

TEST_CASE("a connect-and-leave probe does not make the daemon stop (launcher race)", "[daemon][integration]") {
  TempDir d; FakeTelegramService svc; Daemon daemon(svc, d.sock());
  daemon.setStopWhenEmpty(true);
  REQUIRE(daemon.start().empty());
  std::atomic<bool> returned{false};
  std::thread th([&] { daemon.run(); returned = true; });
  for (int i = 0; i < 5; i++) { int e; Fd probe = SocketUtil::connectUnix(d.sock(), e); REQUIRE(probe.valid()); }
  std::this_thread::sleep_for(std::chrono::milliseconds(200));
  CHECK(!returned.load());
  RemoteService a(d.sock()); a.start();
  REQUIRE(a.waitConnected(nullptr));
  CHECK(callSync(a, "hello").ok);
  daemon.stop(); th.join();
}
38.1ms