Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions .github/scripts/fork-fleet-walls-wsl2.test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down
15 changes: 11 additions & 4 deletions .github/scripts/fork-fleet-walls.test.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
of every walls file in fork-fleet-walls/; the contract each must pass on fake machines from its <os>.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 <this>. 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
Expand Down Expand Up @@ -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)
Expand All @@ -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=()):
Expand Down
15 changes: 8 additions & 7 deletions .github/scripts/fork-fleet-walls/wsl2
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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:
Expand Down
46 changes: 38 additions & 8 deletions .github/scripts/fork-fleet.test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 <this>. 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
Expand Down Expand Up @@ -1490,14 +1490,14 @@ 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:
text = f.read()
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
Expand Down Expand Up @@ -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']
Expand Down Expand Up @@ -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."""

Expand Down
4 changes: 3 additions & 1 deletion fork-kit/desk/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
16 changes: 13 additions & 3 deletions fork-kit/desk/sbin/desk-install
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down Expand Up @@ -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()
Expand All @@ -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):
Expand Down
Loading
Loading