diff --git a/.github/scripts/fork-fleet-walls-wsl2.test.py b/.github/scripts/fork-fleet-walls-wsl2.test.py index be74684ad08d..40bd59d9a587 100755 --- a/.github/scripts/fork-fleet-walls-wsl2.test.py +++ b/.github/scripts/fork-fleet-walls-wsl2.test.py @@ -512,8 +512,10 @@ def test_the_pin_is_the_launchers(self): # change the launcher, read it again, def test_one_pin_in_the_linux_file(self): """Issue #365 item 2: the launcher is pinned once, in the linux walls file. wsl2 has no copy of its own (no LAUNCHER_SHA256 at all, so the two cannot drift) and checks the launcher against the pin of the linux file it - loaded. A linux file that pins another launcher, or none (one from before the pin, #327: walls files of two - releases), and the launcher cannot be told: sockets FAILs as job-units does, never a pass.""" + loaded. A linux file that pins another launcher, or this linux file with its pin line taken out, and the + launcher cannot be told: sockets FAILs as job-units does, never a pass. (A real linux file from before the pin, + #327, has no launcher_shipped either, so there job-units passes and sockets alone FAILs: still exit 1. Issue + #408 item 5 corrects the #390 claim that job-units fails there too.)""" self.assertNotRegex(slurp(os.path.join(FOLDER, 'wsl2')), r'LAUNCHER_SHA256\s*=') self.assertFalse(hasattr(wsl2, 'LAUNCHER_SHA256')) m = walls_with(self, self.fake()) diff --git a/.github/scripts/fork-fleet-walls.test.py b/.github/scripts/fork-fleet-walls.test.py index 23e904d93c8a..afc52d865e14 100644 --- a/.github/scripts/fork-fleet-walls.test.py +++ b/.github/scripts/fork-fleet-walls.test.py @@ -3,7 +3,7 @@ of every walls file in fork-fleet-walls/; the contract each must pass on fake machines from its .fixture.json is in fork-fleet-walls-contract.test.py, which uses this file's helpers. A new walls file (and its fixture) is tested without a change to either file. Run: python3 . Linux only.""" -import ast, base64, contextlib, hashlib, importlib.machinery, importlib.util, io, json, os, re, shutil, signal, stat, subprocess, sys, tempfile, unittest +import ast, base64, contextlib, errno, hashlib, importlib.machinery, importlib.util, io, json, os, re, shutil, signal, stat, subprocess, sys, tempfile, unittest from unittest import mock sys.dont_write_bytecode = True @@ -1274,7 +1274,7 @@ def test_linux_launcher_shipped_refuses_an_unsafe_launcher_itself(self): this uid's alone (launcher_safe on what it opened), or no plain file (a FIFO: opened without blocking), before it reads it; ask() refuses the same later, so this tests launcher_shipped alone. A safe copy of the launcher passes; a safe one with other bytes does not. Issue #365 item 4: a call that blocks (the FIFO opened without - O_NONBLOCK) fails in no_wait's time, never hangs the run.""" + O_NONBLOCK) fails in no_wait's time, never hangs the run, and never passes as a refusal (issue #408 item 2).""" m = fw_linux() folder = os.path.join(self.tmp, 'kit') os.makedirs(folder, mode=0o755) @@ -1297,10 +1297,17 @@ def test_linux_launcher_shipped_refuses_an_unsafe_launcher_itself(self): os.chmod(writable, 0o775) fifo = os.path.join(folder, 'fifo.sh') os.mkfifo(fifo, 0o755) - for path, error in ((link, OSError), (writable, ValueError), (fifo, ValueError)): + # Each refusal by its own message (issue #408 item 2, the #390 security lens's M7b): a Waited reworded into a + # ValueError (a FIFO opened without O_NONBLOCK, behind a wrapper) is not launcher_safe's refusal. + with self.subTest('link.sh'): + m.LAUNCHER = link + with no_wait(), self.assertRaises(OSError) as got: + m.launcher_shipped() + self.assertEqual(got.exception.errno, errno.ELOOP) # O_NOFOLLOW's own refusal + for path in (writable, fifo): with self.subTest(os.path.basename(path)): m.LAUNCHER = path - with no_wait(), self.assertRaises(error): + with no_wait(), self.assertRaisesRegex(ValueError, 'is a link, or not owned by uid'): m.launcher_shipped() def job_units(self, change, links=()): diff --git a/.github/scripts/fork-fleet-walls/wsl2 b/.github/scripts/fork-fleet-walls/wsl2 index a889d5b54cfe..9d27407a7c6b 100755 --- a/.github/scripts/fork-fleet-walls/wsl2 +++ b/.github/scripts/fork-fleet-walls/wsl2 @@ -7,10 +7,11 @@ launcher beside this folder says with `fork-fleet-launch.sh paths`: Windows' dri /mnt/wsl and /usr/lib/wsl are outside it, so no job sees them), job-units and etc-secrets. A wall the linux file gains is a wall here too. The launcher is one file: the one the linux walls ask (`paths`) is the one whose job units' properties are read here (unit_props: sandbox(), job_fs() and start()'s systemd-run, every form of -p), and it must be -as safe as they want it. It must also be the launcher this file was checked against (the linux file's -LAUNCHER_SHA256, the one pin: this file has no copy of its own): no reading of bash can follow every way a changed -launcher could hand systemd-run more (eval, a helper, printf -v, source, a quote), so any other launcher cannot be -told. On top, what only WSL2 has: +as safe as they want it. It must also be the launcher the linux file next to this one was checked against (its +LAUNCHER_SHA256, the one pin: this file has no copy of its own, so it is tied to the launcher only through that +file, and the installer puts the linux file in last: no partial install leaves an older wsl2 file under a newer pin): +no reading of bash can follow every way a changed launcher could hand systemd-run more (eval, a helper, printf -v, +source, a quote), so any other launcher cannot be told. On top, what only WSL2 has: - interop: WSL runs Windows programs from the distro (a binfmt_misc handler run by /init), as the Windows user, outside every Linux wall. It must be off now, and stay off: in /etc/wsl.conf, and masked for systemd-binfmt, which registers WSL's handler again at boot. Any handler that runs Windows programs counts, whatever its name; @@ -442,9 +443,9 @@ def merged(values): def launcher_props(): """The job units' properties (unit_props) of the launcher the linux walls ask what jobs see (LINUX.LAUNCHER, beside this folder: the one the pool runs, also under FORK_FLEET_LAUNCH_CONF), checked as they check it, on the - open file itself, if it is the launcher this file was checked against: the linux file's LAUNCHER_SHA256, the one - pin of the kit (issue #365 item 2). A linux file without it (one from before the pin) or with another: cannot - tell.""" + open file itself, if it is the launcher the linux file was checked against: its LAUNCHER_SHA256, the one pin of + the kit (issue #365 item 2), which the installer puts in after this file (issue #408 item 1). A linux file + without it (one from before the pin) or with another: cannot tell.""" path = LINUX.LAUNCHER fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | getattr(os, 'O_CLOEXEC', 0)) # a FIFO: no wait try: diff --git a/.github/scripts/fork-fleet.test.py b/.github/scripts/fork-fleet.test.py index 7af3db88b0fd..85c42f45fb93 100644 --- a/.github/scripts/fork-fleet.test.py +++ b/.github/scripts/fork-fleet.test.py @@ -2,7 +2,7 @@ """Tests of fork-fleet.py, fork-fleet-launch.sh and fork-fleet-hook.sh, and of their wiring in fork-tests.yml, fork-fleet.yml and fork-release.yml. Run: python3 . Linux only (the gate and launcher tests run real processes).""" import copy, datetime, http.client, importlib.util, io, json, os, pwd, re, shutil, signal, socket, stat, subprocess, sys -import tempfile, time +import ast, glob, tempfile, time import unittest, urllib.error, urllib.parse from contextlib import redirect_stdout from functools import partial @@ -1490,7 +1490,6 @@ def test_an_unknown_pool_is_refused_before_anything_else(self): ff.main(['dispatch', '--pool', 'nope', '--token-file', '/nonexistent', '--once'], env={}) -@unittest.skipUnless(sys.platform.startswith('linux') and os.geteuid() != 0, 'Linux, not as root') def walls_probe(): """check-net's walls' probe, the Python code the launcher runs in the unit (its WALLS).""" with open(LAUNCH) as f: @@ -1498,6 +1497,7 @@ def walls_probe(): return text.split("read -r -d '' WALLS <<'EOF' || true\n", 1)[1].split('\nEOF\n', 1)[0] +@unittest.skipUnless(sys.platform.startswith('linux') and os.geteuid() != 0, 'Linux, not as root') class Launcher(unittest.TestCase): """fork-fleet-launch.sh with a fake systemd-run, systemctl, chown, pgrep, setpriv, ip, nft, iptables and id (it runs here as this user, not root; LauncherAsRoot runs the real ones). The fake systemd-run records each unit it @@ -1801,17 +1801,27 @@ def test_the_jobs_resolv_conf_on_either_kind_of_host(self): readlink says where this host's /etc/resolv.conf leads). A plain file: the jobs' file is bound at /etc/resolv.conf, a mount point of its own, with no link there. A link (systemd-resolved's, into /run): the jobs' file is bound at its target, and the unit's root links /etc/resolv.conf to it, as no whole /etc brings - that link any more (issue #243). The host's kind changed between two starts (a WSL distro told to stop making - its link): each root is made anew, with no link left from before. A target that is no plain path: refused - before any unit starts.""" + that link any more (issue #243). The host's kind changed between two starts of one unit name (a WSL distro + told to stop making its link, or told to make it again): the root is made anew, with no link left from before + and the new one made. Issue #408 item 3: one name for every start, so the starts share a root. The first unit + has ended and its copy is gone, but its root is still there and the unit is still loaded (so no prune takes + the root): job_fs itself must make it anew. A target that is no plain path: refused before any unit + starts.""" self.write('rec/resolv-target', '/run/x y/resolv.conf\n', 0o644) self.refused('/etc/resolv.conf leads to /run/x y/resolv.conf: not a plain file path') resolv = os.path.realpath(self.path('resolv.conf')) listed = {p: os.readlink(p) for p in job_paths() if os.path.islink(p)} - for name, target in (('fleet-vm-t3code-11', '/run/systemd/resolve/stub-resolv.conf'), - ('fleet-vm-t3code-12', '/etc/resolv.conf')): - with self.subTest(target): + name = self.NAME + for n, target in enumerate(('/run/systemd/resolve/stub-resolv.conf', '/etc/resolv.conf', + '/run/systemd/resolve/stub-resolv.conf')): + with self.subTest(n=n, target=target): self.write('rec/resolv-target', target + '\n', 0o644) + if n: + # Still loaded (once, as the last start's user: the other slot's user is free), so prune + # keeps its root; its copy gone, so start does not refuse the name. + shutil.rmtree(self.path(f'var/runners/{name}')) + self.write('rec/units', f'fork-fleet-{name}.service loaded failed failed x\n', 0o644) + self.assertTrue(os.path.isdir(self.path(f'run/{name}.root'))) self.start(name) args = self.rec_text('systemd-run').splitlines() props = [args[i + 1] for i, a in enumerate(args) if a == '-p'] @@ -4686,6 +4696,26 @@ def test_a_missing_or_broken_config_fails_red_and_puts_out_nothing(self): self.assertIn('runners={"plugins":["self-hosted","proj-build"]', written) +class TestFiles(unittest.TestCase): + def test_no_skip_decorator_on_a_helper(self): + """Issue #408 item 6: a unittest skip decorator on a module-level helper (walls_probe had LauncherAsRoot's + opposite, "not as root") turns every call of it into a skip, so a root test that calls it never ran, and + the class it was meant for (Launcher) lost its guard. Skips go on test classes and test methods only, in + every test file of the fork's scripts and kits.""" + repo = os.path.dirname(os.path.dirname(HERE)) + files = sorted({*glob.glob(os.path.join(HERE, '*.test.py')), + *glob.glob(os.path.join(repo, 'fork-kit', '**', '*.test.py'), recursive=True)}) + self.assertIn(os.path.abspath(__file__), files) + bad = [] + for path in files: + with open(path, encoding='utf-8') as f: + tree = ast.parse(f.read(), path) + bad += [f'{os.path.relpath(path, repo)}: {n.name}' for n in tree.body + if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)) + and any('skip' in ast.unparse(d) for d in n.decorator_list)] + self.assertEqual(bad, []) + + class OldBugs(unittest.TestCase): """Bugs of a project's own router, kept as tests of this one.""" diff --git a/fork-kit/desk/README.md b/fork-kit/desk/README.md index 9f7373ba7e99..8ad34a1c7f55 100644 --- a/fork-kit/desk/README.md +++ b/fork-kit/desk/README.md @@ -153,7 +153,9 @@ parts run in the tests on a fake root. config choice is saved, so a run stopped between saving the choice and the swap fails `check` until the next run. - **Stopped half-way:** the next install ends it. A new release is staged in `/opt/fork-fleet/.kit-stage-*` and checked first (gate loads with the fleet config, the pool is in it, `bash -n`, the walls know this OS); a release - that fails is never installed. Files are renamed in one by one while the agent and the refresh timer are stopped; + that fails is never installed. Files are renamed in one by one while the agent and the refresh timer are stopped, + the walls file that pins the launcher (`fork-fleet-walls/linux`) last: a stop before it leaves the old pin, so + a new launcher fails the walls until the next run ends the swap, and no older walls file meets a newer pin. `SOURCE` is written last, so `check` reports a half-done swap. Users are recorded in `/etc/fork-fleet/desk-kit.json` before they are made, so uninstall removes them even after a stop. diff --git a/fork-kit/desk/sbin/desk-install b/fork-kit/desk/sbin/desk-install index 8d5ef53d16e8..5496df606aa7 100755 --- a/fork-kit/desk/sbin/desk-install +++ b/fork-kit/desk/sbin/desk-install @@ -40,6 +40,10 @@ FILES = {'fork-fleet-launch.sh': '.github/scripts/fork-fleet-launch.sh', 'machine_file.py': 'fork-kit/common/machine_file.py', 'README.md': 'fork-kit/desk/README.md', 'free_contract.py': 'fork-kit/common/free_contract.py', 'free-memory': 'fork-kit/common/free/memory'} WALLS = '.github/scripts/fork-fleet-walls' # copied whole: every OS's walls file and fixture +# The one file that pins the launcher (its LAUNCHER_SHA256; the other walls files read that pin). swap() renames it in +# last, so a run stopped half-way never pairs a new pin with walls or a launcher of the old release: any launcher +# change then fails on the old pin until the next run ends the swap (issue #408 item 1). +PIN_HOLDER = 'fork-fleet-walls/linux' SUBDIRS = ('units', 'fork-fleet-walls') # the folders the manifest makes inside /opt/fork-fleet UNITS = {'fork-fleet-desk-agent.service': '.github/scripts/fork-fleet-desk-agent.service', 't3code-fleet-refresh.service': '.github/scripts/fork-fleet-refresh.service', @@ -367,14 +371,15 @@ def read_manifest(): def swap(tmp, manifest, sha, before_change): """Each changed file renamed into /opt/fork-fleet (the agent stopped meanwhile, so no verb runs from half-old, half-new files, and the refresh and seed timers and services stopped too: they run its files); files of the old - release that are gone, removed. Unchanged files (same text, mode and owner root) are left as they are; one whose - mode or owner was changed is replaced by the staged copy. True when anything changed.""" + release that are gone, removed (before the pin holder goes in). Unchanged files (same text, mode and owner root) are left as they are; one whose + mode or owner was changed is replaced by the staged copy; the launcher's pin holder (PIN_HOLDER) last. True when + anything changed.""" def same(rel): with contextlib.suppress(OSError): st = os.lstat(p(f'{OPT}/{rel}')) return (stat.S_ISREG(st.st_mode) and st.st_uid == ROOT_UID and stat.S_IMODE(st.st_mode) == file_mode(rel) and sha256(p(f'{OPT}/{rel}')) == manifest[rel]) - changed = [rel for rel in sorted(manifest) if not same(rel)] + changed = sorted((rel for rel in manifest if not same(rel)), key=lambda rel: (rel == PIN_HOLDER, rel)) gone = sorted(set(read_manifest()) - set(manifest)) if changed or gone: before_change() @@ -384,6 +389,11 @@ def swap(tmp, manifest, sha, before_change): os.makedirs(p(f'{OPT}/{d}'), mode=0o755, exist_ok=True) os.chmod(p(f'{OPT}/{d}'), 0o755) for rel in changed: + if rel == PIN_HOLDER: + # files of the old release that are gone, out before the new pin: none is judged by a pin it never saw + for old in gone: + with contextlib.suppress(FileNotFoundError): + os.unlink(p(f'{OPT}/{old}')) os.replace(os.path.join(tmp, rel), p(f'{OPT}/{rel}')) for rel in gone: with contextlib.suppress(FileNotFoundError): diff --git a/fork-kit/desk/tests/install.test.py b/fork-kit/desk/tests/install.test.py index 93c36c419af1..9ce381ca9e1f 100644 --- a/fork-kit/desk/tests/install.test.py +++ b/fork-kit/desk/tests/install.test.py @@ -4,7 +4,7 @@ python3 -I -B fork-kit/desk/tests/install.test.py """ -import contextlib, datetime, fcntl, importlib.machinery, importlib.util, io, json, os, shutil, stat, subprocess +import contextlib, datetime, fcntl, importlib.machinery, importlib.util, io, json, os, re, shutil, stat, subprocess import sys, tempfile, types, unittest, unittest.mock KIT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) @@ -349,6 +349,75 @@ def test_upgrade_replaces_changed_files_and_removes_gone_ones(self): self.assertLess(calls.index(stop), calls.index('systemctl restart fork-fleet-desk-agent.service')) self.assertEqual(json.loads(self.read('/etc/fork-fleet/desk-kit.json'))['sha'], SHA2) + def test_the_launcher_pin_goes_in_last_so_a_stopped_swap_never_pairs_a_new_pin_with_old_walls(self): + """Issue #408 item 1 (the #390 lenses): the walls pin the launcher in one file (PIN_HOLDER, the linux walls; + the wsl2 walls read that pin). A run stopped between any two renames of an upgrade never leaves the new pin + beside an older launcher, dispatcher or walls file (each would then be judged by a pin it was never checked + against), `check`'s install line fails meanwhile, and the next run ends the swap. Also stopped before the first rename.""" + self.assertEqual(self.install()[0], 0) + changed = {'.github/scripts/fork-fleet-launch.sh': STUBS['.github/scripts/fork-fleet-launch.sh'] + '# new\n', + '.github/scripts/fork-fleet-walls.py': STUBS['.github/scripts/fork-fleet-walls.py'] + '# new\n', + '.github/scripts/fork-fleet-walls/linux': '#!/bin/sh\n# new\n', + '.github/scripts/fork-fleet-walls/wsl2': '#!/bin/sh\n# new\n'} + new = self.release('release2', changed) + news = {f'/opt/fork-fleet/{rel}': slurp(os.path.join(new, src)) for rel, src in + [*[(r, s) for r, s in self.m.FILES.items() if s in changed], + *[(f'fork-fleet-walls/{n}', f'{self.m.WALLS}/{n}') for n in ('linux', 'wsl2')]]} + pin = '/opt/fork-fleet/' + self.m.PIN_HOLDER + self.assertIn(pin, news) + real, after = os.replace, [] + + def stopped_after(n): + def spy(a, b, *k, **kw): + if '/.kit-stage-' in str(a): + if len(after) == n: + raise SystemExit(f'stopped after {n} renames') + after.append(b) + return real(a, b, *k, **kw) + return spy + for n in range(len(news)): + with self.subTest(stopped_after=n): + after.clear() + with unittest.mock.patch.object(self.m.os, 'replace', stopped_after(n)): + self.assertIn('stopped after', str(self.install(sha=SHA2, source=new)[0])) + self.assertEqual(len(after), n) + now = {path: self.read(path) == text for path, text in news.items()} + self.assertFalse(now[pin], f'the pin was renamed in while {[p for p, v in now.items() if not v]} ' + 'were still old') + self.assertTrue(self.m.installed_problems()) # check's install line fails meanwhile + code, _, err = self.install(sha=SHA2, source=new) # runs again: ends the swap + self.assertEqual(code, 0, err) + self.assertEqual({path: self.read(path) for path in news}, news) + self.assertEqual(self.m.installed_problems(), []) + code, _, err = self.install() # back to the old release for the next stop + self.assertEqual(code, 0, err) + + def test_files_a_release_removes_are_gone_before_the_new_pin_goes_in(self): + """#579 lenses: a run stopped just before the pin holder's rename has already removed the files the new + release drops, so no old walls file is left beside the new pin; the next run ends the swap.""" + self.assertEqual(self.install()[0], 0) + new = self.release('release2', {'.github/scripts/fork-fleet-walls/wsl2': None, + '.github/scripts/fork-fleet-walls/wsl2.fixture.json': None, + '.github/scripts/fork-fleet-walls/linux': '#!/bin/sh\n# new\n'}) + gone = self.path('/opt/fork-fleet/fork-fleet-walls/wsl2') + self.assertTrue(os.path.exists(gone)) + pin, real, seen = self.path('/opt/fork-fleet/' + self.m.PIN_HOLDER), os.replace, [] + + def spy(a, b, *k, **kw): + if str(b) == pin and '/.kit-stage-' in str(a): + seen.append(os.path.exists(gone)) + raise SystemExit('stopped before the pin') + return real(a, b, *k, **kw) + with unittest.mock.patch.object(self.m.os, 'replace', spy): + self.assertIn('stopped before the pin', str(self.install(sha=SHA2, source=new)[0])) + self.assertEqual(seen, [False]) + self.assertFalse(os.path.exists(gone)) + code, _, err = self.install(sha=SHA2, source=new) # runs again: ends the swap + self.assertEqual(code, 0, err) + self.assertIn('# new', self.read('/opt/fork-fleet/' + self.m.PIN_HOLDER)) + self.assertFalse(os.path.exists(gone)) + self.assertEqual(self.m.installed_problems(), []) + def test_project_fleet_config_is_used_and_kept(self): project = os.path.join(self.tmp, 'project.json') self.write(project, json.dumps({'pools': [{'name': 'desktop'}], 'project': True})) @@ -1090,6 +1159,15 @@ def test_every_file_the_kit_installs_is_in_this_repository(self): self.assertTrue(os.path.exists(os.path.join(REPO, src)), src) self.assertTrue(os.listdir(os.path.join(REPO, m.WALLS))) + def test_the_pin_holder_is_the_one_walls_file_that_pins_the_launcher(self): + """Issue #408 item 1: swap() renames PIN_HOLDER last; that only helps while it is the walls file that holds + the launcher's pin, and the only one.""" + m = load() + folder = os.path.join(REPO, m.WALLS) + pins = [f'fork-fleet-walls/{n}' for n in sorted(os.listdir(folder)) + if re.search(r'^LAUNCHER_SHA256\s*=', slurp(os.path.join(folder, n)), re.M)] + self.assertEqual(pins, [m.PIN_HOLDER]) + def test_bootstrap_checks_its_arguments_before_anything(self): boot = os.path.join(KIT, 'bootstrap.sh') self.assertEqual(subprocess.run(['sh', '-n', boot]).returncode, 0)