diff --git a/tools/testnet/.gitignore b/tools/testnet/.gitignore new file mode 100644 index 00000000..c20fbf27 --- /dev/null +++ b/tools/testnet/.gitignore @@ -0,0 +1,2 @@ +run/ +__pycache__/ diff --git a/tools/testnet/README.md b/tools/testnet/README.md new file mode 100644 index 00000000..d95c8dc3 --- /dev/null +++ b/tools/testnet/README.md @@ -0,0 +1,55 @@ +# testnet + +Starts a small linked bahamut network on 127.0.0.1 and runs client tests +against it. Requires only `python3` (3.6+), the `openssl` CLI and a built +`src/ircd`, so it works the same on Linux, macOS, or CI. + +``` +hub.test clients 16667, TLS clients 16697 + |-- leaf1.test plain link, flags HZ (clients 16668) + `-- leaf2.test TLS link, flags HSZ (clients 16669) +``` + +## Usage + +From the repository root, after `./configure && make`: + +```sh +tools/testnet/testnet.py test # start, run tests/, stop +tools/testnet/testnet.py test --pattern 'test_cap*' +tools/testnet/testnet.py test --keep # leave it running afterwards +tools/testnet/testnet.py up # start only, then connect your client +tools/testnet/testnet.py down +tools/testnet/testnet.py test --ircd /path/to/other/ircd +``` + +Configs, certificates and logs are written to `tools/testnet/run/` (ignored +by git). The oper login is `admin` / `operpass`. Each server's oper control +connection turns off connection throttling at startup, since every client +comes from 127.0.0.1. + +## Writing tests + +Add a `tests/test_*.py` file using `unittest` and the helpers in +`ircclient.py`: + +```python +import unittest + +from ircclient import Client, load_network + +class AwayNotifyTest(unittest.TestCase): + def test_example(self): + net = load_network() + c = Client(net["servers"][1]["port"]) # leaf1 + c.send("CAP REQ :away-notify") + c.expect(r" CAP \S+ ACK ") + c.register() +``` + +- `expect(regex)` consumes lines until one matches and returns it. +- `lines_until(regex)` returns every line it consumed. +- `wait_for_nick(nick)` waits until a user on another server is visible. + Use it before messaging them, because the NICK may still be propagating. +- `sync()` sends a PING and waits for the PONG, so every earlier reply has + arrived before you assert that something did *not* happen. diff --git a/tools/testnet/ircclient.py b/tools/testnet/ircclient.py new file mode 100644 index 00000000..0345f167 --- /dev/null +++ b/tools/testnet/ircclient.py @@ -0,0 +1,119 @@ +"""Minimal blocking IRC client for testnet tests (stdlib only).""" + +import itertools +import json +import os +import re +import socket +import ssl +import time + +HERE = os.path.dirname(os.path.abspath(__file__)) +DEFAULT_RUN_DIR = os.path.join(HERE, "run") + +_nick_counter = itertools.count(1) + + +def unique_nick(prefix="t"): + return "%s%d%d" % (prefix, os.getpid() % 1000, next(_nick_counter)) + + +def load_network(run_dir=None): + """Return the network description written by `testnet.py up`.""" + run_dir = run_dir or os.environ.get("TESTNET_DIR", DEFAULT_RUN_DIR) + with open(os.path.join(run_dir, "network.json")) as f: + return json.load(f) + + +class Client(object): + def __init__(self, port, tls=False, host="127.0.0.1", timeout=15): + self.timeout = timeout + sock = socket.create_connection((host, port), timeout=timeout) + if tls: + ctx = ssl.create_default_context() + ctx.check_hostname = False + ctx.verify_mode = ssl.CERT_NONE + sock = ctx.wrap_socket(sock) + self.sock = sock + self.buf = b"" + self.pending = [] # received, not yet consumed by expect() + self.seen = [] # every line received + self.nick = None + + def send(self, line): + self.sock.sendall((line + "\r\n").encode()) + + def _fill(self, deadline): + self.sock.settimeout(max(0.05, min(0.5, deadline - time.time()))) + try: + data = self.sock.recv(65536) + except (socket.timeout, ssl.SSLWantReadError): + return + if not data: + raise ConnectionError("connection closed; last lines: %r" + % self.seen[-10:]) + self.buf += data + while b"\n" in self.buf: + raw, self.buf = self.buf.split(b"\n", 1) + line = raw.rstrip(b"\r").decode("utf-8", "replace") + self.seen.append(line) + if line.startswith("PING "): + self.send("PONG " + line[5:]) + self.pending.append(line) + + def expect(self, pattern, timeout=None): + """Consume lines until one matches the regex; return that line.""" + rx = re.compile(pattern) + deadline = time.time() + (timeout or self.timeout) + while True: + while self.pending: + line = self.pending.pop(0) + if rx.search(line): + return line + if time.time() > deadline: + raise AssertionError("timed out waiting for %r; last lines: %r" + % (pattern, self.seen[-10:])) + self._fill(deadline) + + def lines_until(self, pattern, timeout=None): + """Like expect(), but return every consumed line (match last).""" + start = len(self.seen) - len(self.pending) + self.expect(pattern, timeout) + consumed = len(self.seen) - len(self.pending) + return self.seen[start:consumed] + + def register(self, nick=None, user="test"): + self.nick = nick or unique_nick() + self.send("NICK " + self.nick) + self.send("USER %s 0 * :testnet %s" % (user, self.nick)) + return self.lines_until(r" (376|422) ", timeout=60) + + def sync(self): + """Round-trip a PING so earlier replies have been received.""" + token = "sync%d" % next(_nick_counter) + self.send("PING :" + token) + self.expect(r"PONG .*%s" % token) + + def wait_for_nick(self, nick, timeout=30): + """Wait until nick is visible here (it may still be bursting in).""" + deadline = time.time() + timeout + while True: + self.send("WHOIS " + nick) + line = self.expect(r" (311|401) %s %s " % (self.nick, nick)) + if " 311 " in line: + self.expect(r" 318 ") + return + if time.time() > deadline: + raise AssertionError("%s never became visible" % nick) + time.sleep(0.5) + + def oper(self, net): + self.send("OPER %s %s" % (net["oper"]["name"], net["oper"]["password"])) + self.expect(r" 381 ") + + def close(self, message="bye"): + try: + self.send("QUIT :" + message) + except OSError: + pass + self.sock.close() diff --git a/tools/testnet/testnet.py b/tools/testnet/testnet.py new file mode 100755 index 00000000..a18929ff --- /dev/null +++ b/tools/testnet/testnet.py @@ -0,0 +1,272 @@ +#!/usr/bin/env python3 +"""Start a small local bahamut network and run tests against it. + + tools/testnet/testnet.py up # start hub + leaves, wait until linked + tools/testnet/testnet.py test # up (if needed), run tests/, down + tools/testnet/testnet.py down # stop every server + +Only needs python3, the openssl CLI and a built src/ircd. +""" + +import argparse +import json +import os +import shutil +import signal +import socket +import subprocess +import sys +import time +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +REPO = os.path.dirname(os.path.dirname(HERE)) +sys.path.insert(0, HERE) + +import ircclient # noqa: E402 + +LINK_PASS = "linkpass" +OPER = {"name": "admin", "password": "operpass"} + +# name, client port, server port, TLS server port, uplink (hub), link flags +SERVERS = [ + {"name": "hub.test", "port": 16667, "tls_port": 16697, + "sport": 17000, "tls_sport": 17001, "uplink": None}, + {"name": "leaf1.test", "port": 16668, "tls_port": 16698, + "sport": 17010, "tls_sport": 17011, + "uplink": {"port": 17000, "flags": "HZ"}}, # plain + zip + {"name": "leaf2.test", "port": 16669, "tls_port": 16699, + "sport": 17020, "tls_sport": 17021, + "uplink": {"port": 17001, "flags": "HSZ"}}, # TLS + zip +] + + +def server_conf(srv): + lines = [ + 'global { name %s; info "testnet %s"; ' + 'admin { "testnet"; "testnet"; "testnet"; }; };' % (srv["name"], srv["name"]), + 'options { network_name testnet; servtype hub; local_kline a@b; ' + 'network_kline a@b; services_name services.test; stats_name stats.test; ' + 'nshelpurl "http://localhost"; spamfilterurl "http://localhost"; };', + "port { port %d; bind 127.0.0.1; };" % srv["port"], + "port { port %d; bind 127.0.0.1; flags S; };" % srv["tls_port"], + "port { port %d; bind 127.0.0.1; };" % srv["sport"], + "port { port %d; bind 127.0.0.1; flags S; };" % srv["tls_sport"], + # T: exempt from connection throttling, tests reconnect quickly + "allow { host *@*; class users; flags T; };", + "class { name users; maxusers 500; pingfreq 90; maxsendq 100000; " + "maxclones 500:500; };", + "class { name servers; pingfreq 60; connfreq 5; maxsendq 5000000; " + "maxlinks 10; };", + "class { name opers; pingfreq 90; maxsendq 500000; };", + "oper { name %s; passwd %s; access OAaRD; host *@*; class opers; };" + % (OPER["name"], OPER["password"]), + ] + if srv["uplink"]: + lines.append( + "connect { name hub.test; host 127.0.0.1; apasswd %s; cpasswd %s; " + "port %d; flags %s; class servers; };" + % (LINK_PASS, LINK_PASS, srv["uplink"]["port"], srv["uplink"]["flags"])) + else: + for leaf in SERVERS[1:]: + lines.append( + "connect { name %s; host 127.0.0.1; apasswd %s; cpasswd %s; " + "flags Z; class servers; };" % (leaf["name"], LINK_PASS, LINK_PASS)) + return "\n".join(lines) + "\n" + + +def port_open(port): + try: + socket.create_connection(("127.0.0.1", port), timeout=1).close() + return True + except OSError: + return False + + +def server_pids(run_dir): + pids = [] + if not os.path.isdir(run_dir): + return pids + for name in sorted(os.listdir(run_dir)): + pidfile = os.path.join(run_dir, name, "testnet.pid") + if os.path.exists(pidfile): + with open(pidfile) as f: + pids.append(int(f.read().strip())) + return pids + + +def alive(pid): + try: + os.kill(pid, 0) + return True + except ProcessLookupError: + return False + + +def is_up(run_dir): + pids = server_pids(run_dir) + return len(pids) == len(SERVERS) and all(alive(p) for p in pids) + + +def control_client(port, timeout=60): + """Connect as an oper and turn off connection throttling. + + Every client and server link comes from 127.0.0.1, so the default + throttle (3 connections in 15s) would z-line the tests. Refused + connects don't count towards it, so retry until the server listens. + """ + deadline = time.time() + timeout + while True: + try: + c = ircclient.Client(port) + break + except ConnectionRefusedError: + if time.time() > deadline: + raise SystemExit("server on port %d never started" % port) + time.sleep(0.5) + c.register() + c.oper({"oper": OPER}) + c.send("SET THROTTLE ENABLE off") + c.expect(r"throttle ENABLE to OFF") + return c + + +def wait_linked(c, net, timeout): + deadline = time.time() + timeout + while time.time() < deadline: + c.send("LINKS") + lines = c.lines_until(r" 365 ") + found = {l.split()[3] for l in lines if " 364 " in l} + if all(s["name"] in found for s in net["servers"]): + return + time.sleep(1) + raise SystemExit("timed out waiting for servers to link") + + +def up(args): + if is_up(args.dir): + print("testnet already running in " + args.dir) + return + ircd = os.path.abspath(args.ircd) + if not os.access(ircd, os.X_OK): + raise SystemExit("ircd binary not found: %s (run make first)" % ircd) + if shutil.which("openssl") is None: + raise SystemExit("openssl CLI is required") + for srv in SERVERS: + if port_open(srv["port"]): + raise SystemExit("port %d is already in use" % srv["port"]) + + shutil.rmtree(args.dir, ignore_errors=True) + try: + start_servers(args, ircd) + except BaseException: + down(args) + raise + + +def start_servers(args, ircd): + os.makedirs(args.dir) + net = {"servers": [{"name": s["name"], "port": s["port"], + "tls_port": s["tls_port"]} for s in SERVERS], + "oper": OPER, "ircd": ircd} + with open(os.path.join(args.dir, "network.json"), "w") as f: + json.dump(net, f, indent=2) + + # the hub goes first so its throttle is off before the leaves link in + hub_control = None + for srv in SERVERS: + sdir = os.path.join(args.dir, srv["name"]) + os.makedirs(sdir) + with open(os.path.join(sdir, "ircd.conf"), "w") as f: + f.write(server_conf(srv)) + with open(os.path.join(sdir, "ircd.motd"), "w") as f: + f.write("testnet %s\n" % srv["name"]) + subprocess.check_call( + ["openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes", + "-keyout", "ircd.key", "-out", "ircd.crt", "-days", "30", + "-subj", "/CN=" + srv["name"]], + cwd=sdir, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + log = open(os.path.join(sdir, "testnet.log"), "w") + proc = subprocess.Popen([ircd, "-t"], cwd=sdir, stdin=subprocess.DEVNULL, + stdout=log, stderr=subprocess.STDOUT, + start_new_session=True) + with open(os.path.join(sdir, "testnet.pid"), "w") as f: + f.write("%d\n" % proc.pid) + c = control_client(srv["port"]) + if hub_control is None: + hub_control = c + else: + c.close() + + print("servers started, waiting for links...") + try: + wait_linked(hub_control, net, 180) + finally: + hub_control.close() + print("testnet up: " + ", ".join("%s:%d" % (s["name"], s["port"]) + for s in SERVERS)) + + +def down(args): + pids = server_pids(args.dir) + for name in os.listdir(args.dir) if os.path.isdir(args.dir) else []: + pidfile = os.path.join(args.dir, name, "testnet.pid") + if os.path.exists(pidfile): + os.unlink(pidfile) + for pid in pids: + try: + os.kill(pid, signal.SIGTERM) + except ProcessLookupError: + pass + deadline = time.time() + 10 + for pid in pids: + while time.time() < deadline: + try: + os.kill(pid, 0) + except ProcessLookupError: + break + time.sleep(0.2) + else: + try: + os.kill(pid, signal.SIGKILL) + except ProcessLookupError: + pass + if pids: + print("testnet down") + + +def test(args): + started = not is_up(args.dir) + os.environ["TESTNET_DIR"] = args.dir + try: + if started: + up(args) + loader = unittest.TestLoader() + suite = loader.discover(os.path.join(HERE, "tests"), + pattern=args.pattern, top_level_dir=HERE) + result = unittest.TextTestRunner(verbosity=2).run(suite) + finally: + if started and not args.keep: + down(args) + sys.exit(0 if result.wasSuccessful() else 1) + + +def main(): + p = argparse.ArgumentParser(description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + p.add_argument("command", choices=["up", "down", "test"]) + p.add_argument("--ircd", default=os.path.join(REPO, "src", "ircd"), + help="ircd binary to run (default: src/ircd)") + p.add_argument("--dir", default=ircclient.DEFAULT_RUN_DIR, + help="where server configs and logs are written") + p.add_argument("--pattern", default="test_*.py", + help="test file pattern for the test command") + p.add_argument("--keep", action="store_true", + help="leave the network running after test") + args = p.parse_args() + args.dir = os.path.abspath(args.dir) + {"up": up, "down": down, "test": test}[args.command](args) + + +if __name__ == "__main__": + main() diff --git a/tools/testnet/tests/__init__.py b/tools/testnet/tests/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tools/testnet/tests/test_cap.py b/tools/testnet/tests/test_cap.py new file mode 100644 index 00000000..47bf4878 --- /dev/null +++ b/tools/testnet/tests/test_cap.py @@ -0,0 +1,132 @@ +"""IRCv3 client capability negotiation (CAP LS/LIST/REQ/END).""" + +import unittest + +from ircclient import Client, load_network, unique_nick + + +class CapTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.net = load_network() + cls.port = cls.net["servers"][0]["port"] + probe = Client(cls.port) + try: + probe.register() + probe.send("CAP LS") + if " 421 " in probe.expect(r" (CAP|421) "): + raise unittest.SkipTest("server does not support CAP") + finally: + probe.close() + + def unregistered(self, *caps_cmds): + """Connect, send CAP commands, then NICK/USER without CAP END.""" + c = Client(self.port) + self.addCleanup(c.close) + c.nick = unique_nick("cap") + for cmd in caps_cmds: + c.send(cmd) + c.send("NICK " + c.nick) + c.send("USER test 0 * :cap test") + return c + + def cap_list(self, c): + c.send("CAP LIST") + return c.expect(r" CAP \S+ LIST ") + + def assert_not_registered(self, c): + self.cap_list(c) # round trip so a 001 would have arrived by now + self.assertFalse(any(" 001 " in l for l in c.seen)) + + def end_and_register(self, c): + c.send("CAP END") + c.expect(r" 001 %s " % c.nick, timeout=60) + + def test_ls_302_holds_registration_until_end(self): + c = self.unregistered("CAP LS 302") + line = c.expect(r" CAP \* LS ") + self.assertIn("cap-notify", line.split(" :", 1)[1].split()) + self.assert_not_registered(c) + self.end_and_register(c) + + def test_ls_302_enables_cap_notify_and_it_is_sticky(self): + c = self.unregistered("CAP LS 302") + self.assertTrue(self.cap_list(c).endswith(":cap-notify")) + c.send("CAP REQ :-cap-notify") + c.expect(r" CAP \S+ NAK :-cap-notify$") + self.end_and_register(c) + + def test_req_ack_and_disable(self): + c = self.unregistered("CAP LS") + c.expect(r" CAP \S+ LS ") + self.assertTrue(self.cap_list(c).endswith("LIST :")) + c.send("CAP REQ :cap-notify") + c.expect(r" CAP \S+ ACK :cap-notify$") + self.assertTrue(self.cap_list(c).endswith(":cap-notify")) + c.send("CAP REQ :-cap-notify") + c.expect(r" CAP \S+ ACK :-cap-notify$") + self.assertTrue(self.cap_list(c).endswith("LIST :")) + self.end_and_register(c) + + def test_req_with_unknown_cap_naks_whole_request(self): + c = self.unregistered("CAP LS") + c.send("CAP REQ :cap-notify no-such-cap") + c.expect(r" CAP \S+ NAK :cap-notify no-such-cap$") + self.assertTrue(self.cap_list(c).endswith("LIST :")) + self.end_and_register(c) + + def test_req_without_ls_holds_registration(self): + c = self.unregistered("CAP REQ :cap-notify") + c.expect(r" CAP \S+ ACK :cap-notify$") + self.assert_not_registered(c) + self.end_and_register(c) + + def test_list_302_has_no_values(self): + c = self.unregistered("CAP LS 302") + caps = self.cap_list(c).split(" :", 1)[1].split() + self.assertFalse([cap for cap in caps if "=" in cap]) + self.end_and_register(c) + + def test_req_only_spaces_is_rejected(self): + c = self.unregistered("CAP LS") + c.send("CAP REQ : ") + c.expect(r" 461 \S+ CAP ") + self.assertTrue(self.cap_list(c).endswith("LIST :")) + self.end_and_register(c) + + def test_req_too_long_to_ack_is_naked_on_token_boundary(self): + c = self.unregistered("CAP LS") + c.send("CAP REQ :" + " ".join(["cap-notify"] * 45)) + line = c.expect(r" CAP \S+ NAK :") + self.assertLessEqual(len(line), 510) + self.assertEqual({"cap-notify"}, set(line.split(" :", 1)[1].split())) + self.assertTrue(self.cap_list(c).endswith("LIST :")) + self.end_and_register(c) + + def test_invalid_and_missing_subcommand(self): + c = self.unregistered("CAP LS") + c.send("CAP FOO") + c.expect(r" 410 \S+ FOO ") + c.send("CAP") + c.expect(r" 461 \S+ CAP ") + self.end_and_register(c) + + def test_cap_after_registration(self): + c = Client(self.port) + self.addCleanup(c.close) + c.register() + c.send("CAP LS") + c.expect(r" CAP %s LS :" % c.nick) + c.send("CAP END") + c.sync() + self.assertEqual(1, sum(" 001 " in l for l in c.seen)) + + def test_client_without_cap_registers_normally(self): + c = Client(self.port) + self.addCleanup(c.close) + lines = c.register() + self.assertTrue(any(" 001 %s " % c.nick in l for l in lines)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/testnet/tests/test_link.py b/tools/testnet/tests/test_link.py new file mode 100644 index 00000000..6881d4af --- /dev/null +++ b/tools/testnet/tests/test_link.py @@ -0,0 +1,85 @@ +"""Server linking: bursts and propagation over plain+zip and TLS+zip links.""" + +import unittest + +from ircclient import Client, load_network, unique_nick + + +class LinkTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.net = load_network() + cls.hub, cls.leaf1, cls.leaf2 = [s["port"] for s in cls.net["servers"]] + + def client(self, port, tls=False): + c = Client(port, tls=tls) + c.register() + self.addCleanup(c.close) + return c + + def test_links_lists_every_server(self): + c = self.client(self.hub) + c.oper(self.net) + c.send("LINKS") + lines = c.lines_until(r" 365 ") + found = {l.split()[3] for l in lines if " 364 " in l} + for srv in self.net["servers"]: + self.assertIn(srv["name"], found) + + def test_privmsg_between_leaves(self): + a = self.client(self.leaf1) + b = self.client(self.leaf2) + a.wait_for_nick(b.nick) + a.send("PRIVMSG %s :hello across the hub" % b.nick) + b.expect(r"^:%s!\S+ PRIVMSG %s :hello across the hub" % (a.nick, b.nick)) + + def test_whois_remote_user(self): + a = self.client(self.hub) + b = self.client(self.leaf2) + a.wait_for_nick(b.nick) + a.send("WHOIS " + b.nick) + line = a.expect(r" 312 %s %s " % (a.nick, b.nick)) + self.assertIn("leaf2.test", line) + + def test_channel_join_topic_and_message(self): + chan = "#" + unique_nick("c") + a = self.client(self.leaf1) + b = self.client(self.leaf2) + a.send("JOIN " + chan) + a.expect(r" 366 ") + a.send("TOPIC %s :testnet topic" % chan) + a.expect(r" TOPIC %s :testnet topic" % chan) + b.wait_for_nick(a.nick) + b.send("JOIN " + chan) + joined = b.lines_until(r" 366 ") + a.expect(r"^:%s!\S+ JOIN :?%s" % (b.nick, chan)) + # a's JOIN and TOPIC may still be propagating when b joins + if not any(" 332 " in l and "testnet topic" in l for l in joined): + b.expect(r" TOPIC %s :testnet topic" % chan) + b.send("PRIVMSG %s :hi channel" % chan) + a.expect(r"^:%s!\S+ PRIVMSG %s :hi channel" % (b.nick, chan)) + + def test_nick_change_and_quit_propagate(self): + chan = "#" + unique_nick("c") + a = self.client(self.hub) + b = self.client(self.leaf1) + for c in (a, b): + c.send("JOIN " + chan) + c.expect(r" 366 ") + a.expect(r"^:%s!\S+ JOIN :?%s" % (b.nick, chan)) + newnick = unique_nick("n") + b.send("NICK " + newnick) + a.expect(r"^:%s!\S+ NICK :?%s" % (b.nick, newnick)) + b.nick = newnick + b.send("QUIT :leaving") + a.expect(r"^:%s!\S+ QUIT :" % newnick) + + def test_tls_client_port(self): + a = self.client(self.net["servers"][0]["tls_port"], tls=True) + b = self.client(self.leaf1) + a.wait_for_nick(b.nick) + a.send("PRIVMSG %s :hello over tls" % b.nick) + b.expect(r"^:%s!\S+ PRIVMSG %s :hello over tls" % (a.nick, b.nick)) + +if __name__ == "__main__": + unittest.main()