diff --git a/.github/fork-ci-tests.txt b/.github/fork-ci-tests.txt index 5c78d1d2ed531..1a61bf4e03b03 100644 --- a/.github/fork-ci-tests.txt +++ b/.github/fork-ci-tests.txt @@ -7,6 +7,7 @@ # is a note; one that was present and then deleted fails. .github/scripts/fork-ci-tests.test.cjs .github/scripts/fork-contracts.test.py +.github/scripts/fork-fleet-desk-key.test.py .github/scripts/fork-fleet-desk.test.py .github/scripts/fork-fleet.test.py .github/scripts/fork-gate-trust-docs.test.py diff --git a/.github/fork-fleet-desk-key.md b/.github/fork-fleet-desk-key.md new file mode 100644 index 0000000000000..b8a1dcaeb2ddc --- /dev/null +++ b/.github/fork-fleet-desk-key.md @@ -0,0 +1,83 @@ +# Desk link key tool (`desk-key`) + +Fork only. `.github/scripts/fork-fleet-desk-key.py` runs on the always-on host. It keeps the +`authorized_keys` lines of the desk link: one line per desk pool, which lets that pool's desktop +log in only to run the desk link's `serve` for its own pool (row D2, `fork-fleet-desk.py`). The +fleet runbook is `.github/fork-fleet.md`. + +``` +desk-key = sudo -u fleet-desk -H /usr/bin/python3 -I /opt/fork-fleet/fork-fleet-desk-key.py --config /opt/fork-fleet/fork-fleet.json [--user NAME] + +desk-key add POOL < desktop-key.pub # add POOL's line (one ssh-ed25519 public key on stdin) +desk-key status [POOL] # POOL's line, or every desk pool's and every retired pool's +desk-key remove POOL # remove POOL's line, also after POOL left the fleet config +``` + +The line it writes, and the only kind it removes: + +``` +restrict,command="/usr/bin/python3 -I /opt/fork-fleet/fork-fleet-desk.py serve POOL" ssh-ed25519 AAAA... fork-fleet-desk:POOL +``` + +Every other byte of the file stays as it was. Lines are split at `\n` only, as sshd splits +them. A line that names `fork-fleet-desk:POOL` but that the tool cannot read as one of its own +(for example one with a lone `\r` or another control byte in it, or a login line whose comment +contains a desk line) is shown by `status` and `remove` and never changed: edit it by hand. + +## Exit codes + +| Code | Meaning | +| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| 0 | done; `status`: every line is the exact line this version writes | +| 1 | `status` or `remove` found a problem: a wrong line (run `remove`, then `add`), a line of a retired pool (run `remove POOL`), or a line naming a pool that the tool cannot read (edit it by hand) | +| 2 | refused, nothing changed: bad input, unknown pool, wrong user, unsafe file, bad config, bad usage | +| 3 | `status`: a desk pool has no line (and nothing else is wrong) | +| 4 | error: an unexpected failure (for example a full disk); the file is the old one or the new one, never half | + +## The desk-link user + +The key goes into the `authorized_keys` of one dedicated, unprivileged user (default +`fleet-desk`), never root's. The tool runs as that user and refuses: + +- root, and any user other than `--user`; +- a user in an admin group: `root`, `sudo`, `wheel`, `admin`, `adm`, `docker`, `lxd`, `libvirt`, + `systemd-journal` (primary or supplementary); +- a system account (uid 999 or below) unless its name is the default `fleet-desk`, so a daemon's + account (for example a database's) never gets the link; a user with another name needs a uid of + 1000 or more; +- a `$HOME` that is not the user's home in the password database (sshd reads that one; use + `sudo -H`); +- a `~/.ssh`, `authorized_keys` or home (when it makes `~/.ssh`) that the user does not own, that + is a symlink, or that group or others can write (sshd's StrictModes would ignore the file). + +## Retiring a desktop + +Take its pool out of the fleet config, then run `desk-key remove POOL`. `status` without a pool +reports any line left for a pool the config no longer has: "key for retired pool POOL still +allows a login: run desk-key remove POOL" (exit 1). + +## What the setup (D8) must guarantee + +The tool cannot check these from the desk-link user's side. The setup row (D8) makes them true +and its PASS/FAIL check proves them: + +1. **The user and its password field.** The desk-link user is a system user with only its own + group: no `sudo`, `wheel`, `adm`, `docker` or `systemd-journal`, and no sudoers rule. Its shell + is `/bin/sh` (sshd runs the forced command through it, so `nologin` would close the link). Its + password field is `*`: not empty, and not `!` either, because with `UsePAM no` OpenSSH treats a + `!` account as locked and refuses even the key. Its home and `~/.ssh` are owned by it and are + not group- or world-writable. +2. **sshd settings for that user.** A `Match User ` block with + `AuthenticationMethods publickey`, `DisableForwarding yes`, `PermitTTY no`, `PermitTunnel no`, + `PermitUserRC no`, `AllowAgentForwarding no`, `X11Forwarding no`. `PermitUserEnvironment` + stays `no`. No `PermitRootLogin` change. If `AllowUsers` or `AllowGroups` is set, the user is + added to it. The check runs `sshd -T -C user=...,host=...,addr=...` and checks that + `authorizedkeysfile` is `.ssh/authorized_keys` and that those values hold. +3. **The /run folder.** `/run/fork-fleet-desk` is made by tmpfiles, owned by the desk-link user, + mode 0710 with the socket group, and the desk link's `launch` accepts that owner. +4. **Root-owned install files.** `/opt/fork-fleet`, `fork-fleet-desk.py` and this tool are owned + by root and not writable by the desk-link user; `/usr/bin/python3` exists (the forced command + names it by its full path). +5. **A key used for nothing else.** The desktop's link key is made only for the link and kept by + root on the desktop. The check confirms, as root and read-only, that its fingerprint is in no + other `authorized_keys` on the host (root's, an admin's). diff --git a/.github/fork-fleet.md b/.github/fork-fleet.md index 2ff3bf2ff44d6..78eaa1c8a8ba0 100644 --- a/.github/fork-fleet.md +++ b/.github/fork-fleet.md @@ -487,11 +487,11 @@ echo 'd /run/fork-fleet-desk 0710 fleet-desk fleet-desk -' > /etc/tmpfiles.d/for systemd-tmpfiles --create /etc/tmpfiles.d/fork-fleet-desk.conf # Per desk pool: the desktop's public key, as the desk-link user, with the key tool fork-fleet-desk-key.py # (row D4 of the desktop-pool design; install it beside the others). -sudo -u fleet-desk -H python3 -I /opt/fork-fleet/fork-fleet-desk-key.py add POOL < desk-POOL.pub +sudo -u fleet-desk -H /usr/bin/python3 -I /opt/fork-fleet/fork-fleet-desk-key.py --config /opt/fork-fleet/fork-fleet.json add POOL < desk-POOL.pub ``` The line it writes (and the only kind of line that user's key file holds) is -`restrict,command="python3 -I /opt/fork-fleet/fork-fleet-desk.py serve POOL" ssh-ed25519 AAAA... fork-fleet-desk:POOL` +`restrict,command="/usr/bin/python3 -I /opt/fork-fleet/fork-fleet-desk.py serve POOL" ssh-ed25519 AAAA... fork-fleet-desk:POOL` in `~fleet-desk/.ssh/authorized_keys`. The pool's launch command in the project's fleet config is `"launch": ["python3", "-I", "/opt/fork-fleet/fork-fleet-desk.py", "launch", "POOL"]`. diff --git a/.github/scripts/fork-fleet-desk-key.py b/.github/scripts/fork-fleet-desk-key.py new file mode 100755 index 0000000000000..44e8d48a667f3 --- /dev/null +++ b/.github/scripts/fork-fleet-desk-key.py @@ -0,0 +1,406 @@ +#!/usr/bin/env python3 +"""Fork only: the desk link's key tool, on the always-on host. Doc: .github/fork-fleet-desk-key.md. + +Desk agents log in as one dedicated, unprivileged desk-link user (USER, or --user), never as root. Run this as that +user (`sudo -u fleet-desk -H /usr/bin/python3 -I ...`). It refuses root; any other user; a user in an admin group +(ADMIN_GROUPS); a system account (uid below 1000) other than the default name; a $HOME that is not the user's home +in the password database (sshd reads that one); and a ~/.ssh, authorized_keys or (to make ~/.ssh) home that user does +not own. The user needs a shell that can run a command (sshd runs the forced command through it, so nologin would +close the link); `restrict` and the forced command are what limit it. + +Each desk pool (a pool of fork-fleet.json whose launch runs DESK `launch` for itself) has at most one line in that +user's ~/.ssh/authorized_keys: its desktop's ed25519 key, `restrict` (no pty, no forwarding of any kind) and forced +to SERVE POOL. This tool writes and removes only those lines, which end in the comment `fork-fleet-desk:POOL`; +every other byte of the file stays as it was. Lines are split at \\n only, as sshd does. + + desk-key [--config FILE] [--user NAME] add POOL < KEY.pub + Adds POOL's line for the one ssh-ed25519 public key on stdin (its comment is dropped). Already there: nothing + changes. Refused, file untouched: not exactly one valid ed25519 public key; a pool that is not a desk pool; + POOL already has another line (both are shown: `remove` first); the key is on any other line (sshd uses the + first line a key matches, so that line would decide what the key may do). + desk-key [--config FILE] [--user NAME] status [POOL] + POOL's line, or each desk pool's, and every line of a pool the config no longer has (a retired pool). + desk-key [--config FILE] [--user NAME] remove POOL + Removes POOL's lines, also when POOL has left the config (a retired desktop). None: nothing changes. +(desk-key = /usr/bin/python3 -I fork-fleet-desk-key.py) + +Writes go to a temporary file in ~/.ssh with the file's mode (a new file: 0600), then a rename, under a lock on +~/.ssh; a file another program changed meanwhile is left alone (run again). A symlinked ~/.ssh or authorized_keys +is refused. Standard library, POSIX. +""" +import argparse, base64, fcntl, glob, grp, hashlib, importlib.util, os, pwd, re, stat, struct, sys, tempfile + +sys.dont_write_bytecode = True +HERE = os.path.dirname(os.path.abspath(__file__)) +_spec = importlib.util.spec_from_file_location('fork_fleet', os.path.join(HERE, 'fork-fleet.py')) +ff = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(ff) + +# The desk link's program and its forced command: .github/scripts/fork-fleet-desk.py (row D2) owns both. Change +# them only together with that file; `status` then shows every old line as wrong. An absolute interpreter: sshd's +# PATH for the forced command is not this tool's to trust. +PYTHON = '/usr/bin/python3' +DESK = '/opt/fork-fleet/fork-fleet-desk.py' +SERVE = f'{PYTHON} -I {DESK} serve' +USER = 'fleet-desk' # the desk-link user's default name (D2's serve runs as it too) +ADMIN_GROUPS = frozenset(('root', 'sudo', 'wheel', 'admin', 'adm', 'docker', 'lxd', 'libvirt', 'systemd-journal')) +SYSTEM_UID_MAX = 999 # a uid at or below this is a system account: only USER may be one +KEY_TYPE = 'ssh-ed25519' +MARK = 'fork-fleet-desk:' +TMP = '.authorized_keys.desk-key.' +MAX_KEY = 16384 +B64 = re.compile(r'[A-Za-z0-9+/]+={0,2}') +TYPE_WORD = re.compile(r'(ssh|ecdsa|sk)-[a-z0-9@.-]+') # a key type in the comment: a second key on the line +CTRL = re.compile(r'[\x00-\x08\x0a-\x1f\x7f]') # control bytes but tab: sshd and this tool may disagree +LINE = re.compile(rb'[^\n]*\n|[^\n]+') # sshd splits at \n only; a lone \r stays in its line + +# Exit codes (also in --help and the doc). +OK, PROBLEM, REFUSED, MISSING, ERROR = 0, 1, 2, 3, 4 +CODES = f'''exit codes: + {OK} done; status: every line is the exact line this version writes + {PROBLEM} status or remove found a problem: a wrong line (run remove, then add), a line of a retired pool (run + remove POOL), or a line naming a pool that this tool cannot read (edit it by hand) + {REFUSED} refused, nothing changed: bad input, unknown pool, wrong user, unsafe file, bad config, bad usage + {MISSING} status: a desk pool has no line (and nothing else is wrong) + {ERROR} error: an unexpected failure (for example a full disk); the file is the old one or the new one, never half +''' + + +class Refused(Exception): + pass + + +def desk_pools(cfg): + """Names of the pools whose launch command runs the desk program's `launch` for that pool.""" + out = [] + for p in cfg['pools']: + cmd = p.get('launch') or [] + if any(os.path.basename(x) == os.path.basename(DESK) and cmd[i + 1:i + 3] == ['launch', p['name']] + for i, x in enumerate(cmd)): + out.append(p['name']) + return out + + +def parse_key(raw): + """The base64 blob of the one ssh-ed25519 public key in `raw` (bytes). Never echoes the input.""" + if len(raw) > MAX_KEY: + raise Refused('the key is too long for one public key') + text = raw.decode('ascii', 'replace') + if 'PRIVATE KEY' in text: + raise Refused('that is a private key: give the .pub file, and make a new key pair if it was shared') + text = text[:-1] if text.endswith('\n') else text + text = text[:-1] if text.endswith('\r') else text + if not text.strip() or any(ord(c) < 32 or ord(c) == 127 for c in text.replace('\t', ' ')) or '�' in text: + raise Refused('give exactly one public key on one line') + fields = text.split() + if len(fields) < 2 or fields[0] != KEY_TYPE or any(TYPE_WORD.fullmatch(w) for w in fields[2:]): + raise Refused(f'give one {KEY_TYPE} public key ("{KEY_TYPE} AAAA... comment"), no options in front') + blob = fields[1] + try: + data = base64.b64decode(blob, validate=True) if B64.fullmatch(blob) else b'' + except ValueError: + data = b'' + kind = KEY_TYPE.encode() + if (len(data) != 4 + len(kind) + 4 + 32 or base64.b64encode(data).decode() != blob + or data[:4 + len(kind) + 4] != struct.pack('>I', len(kind)) + kind + struct.pack('>I', 32)): + raise Refused(f'that is not a valid {KEY_TYPE} public key') + return blob + + +def group_names(pw): + out = set() + for gid in os.getgrouplist(pw.pw_name, pw.pw_gid): + try: + out.add(grp.getgrgid(gid).gr_name) + except KeyError: + pass + return out + + +def check_user(name): + """The desk-link user's home (from the password database), or Refused.""" + euid = os.geteuid() + if euid == 0: + raise Refused(f'never as root: the desk link key goes to the desk-link user ({name}): sudo -u {name} -H ...') + try: + pw = pwd.getpwuid(euid) + except KeyError: + pw = None + if pw is None or pw.pw_name != name: + raise Refused(f'run this as the desk-link user {name!r}, not {pw and pw.pw_name!r}: sudo -u {name} -H ...') + if euid <= SYSTEM_UID_MAX and name != USER: + raise Refused(f'{name} is a system account (uid {euid}): of those, only the default desk-link user {USER} ' + 'may hold the link (doc: the desk-link user)') + admin = sorted(group_names(pw) & ADMIN_GROUPS) + if admin: + raise Refused(f'{name} is in the admin group(s) {", ".join(admin)}: the desk link needs its own ' + 'unprivileged user') + home = os.environ.get('HOME') + if home and os.path.realpath(home) != os.path.realpath(pw.pw_dir): + raise Refused(f'HOME is {home}, but sshd reads {name}\'s home {pw.pw_dir}: run with sudo -u {name} -H') + return pw.pw_dir + + +def owned(path, what): + if os.stat(path, follow_symlinks=False).st_uid != os.geteuid(): + raise Refused(f'{path} ({what}) does not belong to this user') + + +def strict(path, what): + if os.stat(path, follow_symlinks=False).st_mode & 0o022: + raise Refused(f'{path} ({what}) is writable by group or others: sshd (StrictModes) would not use it') + + +def line_for(pool, blob): + return f'restrict,command="{SERVE} {pool}" {KEY_TYPE} {blob} {MARK}{pool}' + + +def fingerprint(blob): + return 'SHA256:' + base64.b64encode(hashlib.sha256(base64.b64decode(blob)).digest()).decode().rstrip('=') + + +def text_of(line): + t = line.decode('utf-8', 'surrogateescape') + t = t[:-1] if t.endswith('\n') else t + return t[:-1] if t.endswith('\r') else t + + +def active(line): + t = text_of(line).strip() + return bool(t) and not t.startswith('#') + + +def fields(line): + """(options, key type, blob, comment) as sshd reads the line; None for a blank or # line, or one with a control + byte inside (sshd and this tool could read that one differently, so it is never one of this tool's lines).""" + t = text_of(line).lstrip(' \t') + if not t or t.startswith('#') or CTRL.search(t): + return None + opts = '' + if not TYPE_WORD.fullmatch(re.split(r'[ \t]', t, maxsplit=1)[0]): # options first: they end at a space outside "" + quoted, i = False, 0 + while i < len(t) and (quoted or t[i] not in ' \t'): + if t[i] == '\\' and t[i + 1:i + 2] == '"': + i += 1 + elif t[i] == '"': + quoted = not quoted + i += 1 + opts, t = t[:i], t[i:].lstrip(' \t') + parts = re.split(r'[ \t]+', t, maxsplit=2) + if len(parts) < 2: + return None + return opts, parts[0], parts[1], (parts[2] if len(parts) > 2 else '').rstrip(' \t') + + +def mark_of(line): + """The pool of a desk line (key type ssh-ed25519, comment exactly fork-fleet-desk:POOL), or None.""" + f = fields(line) + name = f[3][len(MARK):] if f and f[1] == KEY_TYPE and f[3].startswith(MARK) else None + return name if name and ff.POOL.fullmatch(name) else None + + +def marked(line, pool): + return mark_of(line) == pool + + +def blob_of(line): + """The key blob of a desk line, or None.""" + f = fields(line) + return f[2] if f and mark_of(line) else None + + +def names(line, pool=None): + """True when an active line names fork-fleet-desk:POOL (any pool when None) without being a desk line.""" + pat = re.escape(MARK + pool) + r'(?![a-z0-9_-])' if pool else re.escape(MARK) + return active(line) and mark_of(line) is None and re.search(pat, text_of(line)) is not None + + +def elsewhere(lines, blob, pool): + return [ln for ln in lines if active(ln) and blob in text_of(ln).split() and not marked(ln, pool)] + + +class Keys: + """~/.ssh/authorized_keys of the home `home`, locked while open.""" + + def __init__(self, home, make): + self.dir = os.path.join(home, '.ssh') + self.path = os.path.join(self.dir, 'authorized_keys') + if make and not os.path.lexists(self.dir): + owned(os.path.realpath(home), 'home') + try: + os.mkdir(self.dir, 0o700) + except FileExistsError: # another run made it meanwhile: the checks below apply to it as to any + pass + if os.path.islink(self.dir) or os.path.lexists(self.dir) and not os.path.isdir(self.dir): + raise Refused(f'{self.dir} is a symlink or not a directory') + if os.path.isdir(self.dir): + owned(self.dir, '~/.ssh') + strict(self.dir, '~/.ssh') + self.fd = os.open(self.dir, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) if os.path.isdir(self.dir) else None + try: + if self.fd is not None: + fcntl.flock(self.fd, fcntl.LOCK_EX) + self.st, self.raw = self.read() + except BaseException: + self.close() + raise + + def read(self): + if self.fd is None or not os.path.lexists(self.path): + return None, b'' + st = os.lstat(self.path) + if not stat.S_ISREG(st.st_mode): + raise Refused(f'{self.path} is a symlink or not a regular file') + owned(self.path, 'authorized_keys') + strict(self.path, 'authorized_keys') + fd = os.open(self.path, os.O_RDONLY | os.O_NOFOLLOW) + with os.fdopen(fd, 'rb') as f: + return st, f.read() + + def lines(self): + return LINE.findall(self.raw) + + def write(self, data): + # Under the lock, every temp file there is from an earlier run that stopped half-way: remove it. Anything + # else with that name (a directory: never made by this tool) is skipped, so it can never block a write. + for old in glob.glob(os.path.join(glob.escape(self.dir), TMP + '*')): + try: + if not stat.S_ISDIR(os.lstat(old).st_mode): + os.unlink(old) + except FileNotFoundError: + pass + fd, tmp = tempfile.mkstemp(prefix=TMP, dir=self.dir) + try: + os.fchmod(fd, stat.S_IMODE(self.st.st_mode) if self.st else 0o600) + with os.fdopen(fd, 'wb') as f: + f.write(data) + f.flush() + os.fsync(f.fileno()) + if self.read()[1] != self.raw: + raise Refused(f'{self.path} changed while this ran: nothing written, run again') + os.replace(tmp, self.path) + os.fsync(self.fd) + except BaseException: + if os.path.lexists(tmp): + os.unlink(tmp) + raise + + def close(self): + if self.fd is not None: + os.close(self.fd) + + +def add(keys, pool, blob): + want = line_for(pool, blob) + lines = keys.lines() + mine = [ln for ln in lines if marked(ln, pool)] + other = elsewhere(lines, blob, pool) + if [text_of(ln) for ln in mine] == [want] and not other: + print(f'desk-key: {pool}: already there ({fingerprint(blob)})') + return OK + if other: + raise Refused('this key is already on another line, which sshd would use for it:' + + ''.join(f'\n {text_of(ln)}' for ln in other)) + if mine: + shown = ''.join(f'\n has: {text_of(ln)}' for ln in mine) + raise Refused(f'{pool} already has a line (remove it first):{shown}\n want: {want}') + end = b'' if not keys.raw or keys.raw.endswith(b'\n') else b'\n' + keys.write(keys.raw + end + want.encode() + b'\n') + print(f'desk-key: {pool}: added ({fingerprint(blob)})') + return OK + + +def unreadable(lines, pool=None): + """Lines that name a desk pool but are not desk lines this tool can manage: shown, never touched.""" + odd = [ln for ln in lines if names(ln, pool)] + for ln in odd: + print(f'desk-key: a line names {MARK}{pool or "..."} but is not one this tool can read or remove; ' + f'edit it by hand:\n {text_of(ln)!r}') + return odd + + +def remove(keys, pool): + lines = keys.lines() + keep = [ln for ln in lines if not marked(ln, pool)] + if len(keep) == len(lines): + print(f'desk-key: {pool}: no line, nothing to remove') + else: + keys.write(b''.join(keep)) + print(f'desk-key: {pool}: removed {len(lines) - len(keep)} line(s)') + return PROBLEM if unreadable(lines, pool) else OK + + +def status(keys, pools, known, only=None): + codes = [OK] + lines = keys.lines() + for pool in pools: + mine = [ln for ln in lines if marked(ln, pool)] + blob = blob_of(mine[0]) if len(mine) == 1 else None + if pool not in known: + if mine: + print(f'desk-key: key for retired pool {pool} still allows a login: run desk-key remove {pool}' + + ''.join(f'\n {text_of(ln)}' for ln in mine)) + codes.append(PROBLEM) + elif not mine: + print(f'desk-key: {pool}: no line') + codes.append(MISSING) + elif blob and text_of(mine[0]) == line_for(pool, blob) and not elsewhere(lines, blob, pool): + print(f'desk-key: {pool}: ok ({fingerprint(blob)})') + else: + why = 'two or more lines' if len(mine) > 1 else 'not the line this version writes, or its key is on ' \ + 'another line too' + print(f'desk-key: {pool}: wrong ({why}); remove, then add:' + ''.join(f'\n {text_of(ln)}' for ln in mine)) + codes.append(PROBLEM) + if unreadable(lines, only): + codes.append(PROBLEM) + return PROBLEM if PROBLEM in codes else max(codes) + + +def main(argv=None, stdin=None): + ap = argparse.ArgumentParser(prog='desk-key', description=__doc__.split('\n\n', 1)[1], + epilog=CODES, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument('--config', default=ff.CONFIG) + ap.add_argument('--user', default=USER, help=f'the desk-link user this must run as (default {USER})') + ap.add_argument('verb', choices=('add', 'status', 'remove')) + ap.add_argument('pool', nargs='?') + args = ap.parse_args(argv) # bad usage: exit 2, as any refusal + keys = None + try: + if args.pool is None and args.verb != 'status': + raise Refused(f'{args.verb} needs a POOL') + if args.pool is not None and not ff.POOL.fullmatch(args.pool): + raise Refused(f'{args.pool[:40]!r} is not a pool name') + try: + known = desk_pools(ff.load(args.config)) + except (OSError, ValueError) as e: + raise Refused(f'no valid fleet config: {e}') from None + if args.verb == 'add' and args.pool not in known: + raise Refused(f'{args.pool!r} is not a desk pool of {args.config} ' + f'(desk pools: {", ".join(known) or "none"})') + blob = parse_key((stdin or sys.stdin.buffer).read(MAX_KEY + 1)) if args.verb == 'add' else None + keys = Keys(check_user(args.user), make=args.verb == 'add') + if args.pool is not None and args.pool not in known and not any( + marked(ln, args.pool) or names(ln, args.pool) for ln in keys.lines()): + raise Refused(f'{args.pool!r} is not a desk pool of {args.config} and has no line ' + f'(desk pools: {", ".join(known) or "none"})') + if args.verb == 'add': + return add(keys, args.pool, blob) + if args.verb == 'remove': + return remove(keys, args.pool) + retired = sorted({mark_of(ln) for ln in keys.lines() if mark_of(ln)} - set(known)) + if not (args.pool or known or retired): + print(f'desk-key: no desk pools in {args.config}') + return status(keys, [args.pool] if args.pool else known + retired, known, args.pool) + except Refused as e: + print(f'desk-key: refused: {e}', file=sys.stderr) + return REFUSED + except Exception as e: # noqa: BLE001 - one plain line and its own exit code, not a traceback + print(f'desk-key: error: {type(e).__name__}: {e}', file=sys.stderr) + return ERROR + finally: + if keys: + keys.close() + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/.github/scripts/fork-fleet-desk-key.test.py b/.github/scripts/fork-fleet-desk-key.test.py new file mode 100644 index 0000000000000..9ee61a0527b2a --- /dev/null +++ b/.github/scripts/fork-fleet-desk-key.test.py @@ -0,0 +1,489 @@ +#!/usr/bin/env python3 +"""Tests of fork-fleet-desk-key.py: a temporary HOME and fleet config only. Run: python3 . POSIX.""" +import base64, contextlib, fcntl, glob, importlib.util, io, json, os, pwd, re, shlex, shutil, struct, subprocess +import sys, tempfile, unittest +from contextlib import redirect_stderr, redirect_stdout +from unittest import mock + +sys.dont_write_bytecode = True +HERE = os.path.dirname(os.path.abspath(__file__)) +TOOL = os.path.join(HERE, 'fork-fleet-desk-key.py') +_spec = importlib.util.spec_from_file_location('desk_key', TOOL) +dk = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(dk) + + +def blob(seed, kind=b'ssh-ed25519', size=32): + data = struct.pack('>I', len(kind)) + kind + struct.pack('>I', size) + bytes([seed]) * size + return base64.b64encode(data).decode() + + +K1, K2 = blob(1), blob(2) +PUB1 = f'ssh-ed25519 {K1} someone@desktop\n'.encode() +ME = pwd.getpwuid(os.geteuid()).pw_name +PRIVATE = b'-----BEGIN OPENSSH PRIVATE KEY-----\nc2VjcmV0LW1hcmtlcg==\n-----END OPENSSH PRIVATE KEY-----\n' +OK, PROBLEM, REFUSED, MISSING, ERROR = 0, 1, 2, 3, 4 +# The tool as a test user: this user, whose password-database home is the temporary HOME, in no admin group, and not +# held to the system-account rule (CI users are often in docker or adm, or have a low uid). Those checks have their +# own tests below, run in process. +RUN = r''' +import importlib.util, os, pwd, sys +sys.dont_write_bytecode = True +tool, home = sys.argv[1], sys.argv[2] +spec = importlib.util.spec_from_file_location('desk_key', tool) +dk = importlib.util.module_from_spec(spec) +spec.loader.exec_module(dk) +real = pwd.getpwuid +pwd.getpwuid = lambda uid: (lambda e: pwd.struct_passwd((e.pw_name, e.pw_passwd, e.pw_uid, e.pw_gid, e.pw_gecos, home, + e.pw_shell)))(real(uid)) +os.getgrouplist = lambda name, gid: [] +dk.SYSTEM_UID_MAX = -1 +sys.exit(dk.main(sys.argv[3:])) +''' + + +def desk(name): + return {'name': name, 'label': f'fleet-{name}-example', 'slots': 1, 'waits': False, + 'beacon': f'FLEET_{name.upper()}', + 'launch': ['python3', '-I', '/opt/fork-fleet/fork-fleet-desk.py', 'launch', name]} + + +class DeskKey(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.mkdtemp() + self.home = os.path.join(self.tmp, 'home') + os.mkdir(self.home) + cfg = dk.ff.load() + cfg['pools'] = cfg['pools'] + [desk('desk'), desk('desk2')] + self.config = os.path.join(self.tmp, 'fleet.json') + with open(self.config, 'w') as f: + json.dump(cfg, f) + self.ssh = os.path.join(self.home, '.ssh') + self.keys = os.path.join(self.ssh, 'authorized_keys') + + def tearDown(self): + shutil.rmtree(self.tmp) + + def env(self): + return {'HOME': self.home, 'PATH': os.environ.get('PATH', '/usr/bin:/bin'), 'LC_ALL': 'C'} + + def cmd(self, *args): + return [sys.executable, '-I', '-c', RUN, TOOL, self.home, '--config', self.config, '--user', ME, *args] + + def run_tool(self, *args, stdin=b''): + p = subprocess.run(self.cmd(*args), input=stdin, env=self.env(), capture_output=True, timeout=60) + return p.returncode, p.stdout.decode() + p.stderr.decode() + + def put(self, data, mode=0o600): + os.makedirs(self.ssh, mode=0o700, exist_ok=True) + with open(self.keys, 'wb') as f: + f.write(data) + os.chmod(self.keys, mode) + + def content(self): + with open(self.keys, 'rb') as f: + return f.read() + + def snap(self): + st = os.lstat(self.keys) + return self.content(), st.st_ino, st.st_mtime_ns, st.st_mode + + def test_add_to_empty_home_then_again_then_remove(self): + self.assertEqual(self.run_tool('add', 'desk', stdin=PUB1)[0], 0) + line = 'restrict,command="/usr/bin/python3 -I /opt/fork-fleet/fork-fleet-desk.py serve desk" ' \ + f'ssh-ed25519 {K1} fork-fleet-desk:desk\n' + self.assertEqual(self.content(), line.encode()) + self.assertEqual(os.stat(self.ssh).st_mode & 0o777, 0o700) + self.assertEqual(os.stat(self.keys).st_mode & 0o777, 0o600) + before = self.snap() + code, out = self.run_tool('add', 'desk', stdin=PUB1) + self.assertEqual((code, self.snap()), (0, before), out) + self.assertIn('already there', out) + self.assertEqual(self.run_tool('status', 'desk')[0], 0) + self.assertEqual(self.run_tool('remove', 'desk')[0], 0) + self.assertEqual(self.content(), b'') + before = self.snap() + self.assertEqual(self.run_tool('remove', 'desk')[0], 0) + self.assertEqual(self.snap(), before) + self.assertEqual(self.run_tool('status', 'desk')[0], MISSING) + + def test_other_lines_stay_byte_for_byte_and_mode_kept(self): + for start in (b'# mine\r\nssh-rsa AAAAB3 me@laptop\r\n\xff\xfe odd bytes\n\n', + f'from="10.0.0.1" ssh-ed25519 {K2} other\nno newline at the end'.encode()): + with self.subTest(start=start): + self.put(start, 0o640) + self.assertEqual(self.run_tool('add', 'desk', stdin=PUB1)[0], 0) + got = self.content() + end = b'' if start.endswith(b'\n') else b'\n' + self.assertTrue(got.startswith(start + end), got) + self.assertEqual(got.count(b'\n'), start.count(b'\n') + len(end) + 1) + self.assertEqual(os.stat(self.keys).st_mode & 0o777, 0o640) + self.assertEqual(os.stat(self.keys).st_uid, os.getuid()) + self.assertEqual(self.run_tool('remove', 'desk')[0], 0) + self.assertEqual(self.content(), start + end) + + def test_refuses_anything_but_one_valid_ed25519_public_key(self): + self.put(b'# untouched\n') + before = self.snap() + bad = { + 'empty': b'', 'blank': b'\n', + 'two keys': PUB1 + PUB1, + 'two keys, one line': f'ssh-ed25519 {K1} ssh-ed25519 {K2}\n'.encode(), + 'a control byte': f'ssh-ed25519 {K1} x'.encode() + b'\x00', + 'rsa': f'ssh-rsa {blob(1, b"ssh-rsa")} x\n'.encode(), + 'type and blob disagree': f'ssh-ed25519 {blob(1, b"ssh-rsa")}\n'.encode(), + 'options in front': f'command="sh" ssh-ed25519 {K1}\n'.encode(), + 'bad base64': b'ssh-ed25519 AAAA!!!!\n', + 'short key': f'ssh-ed25519 {blob(1, size=31)}\n'.encode(), + 'trailing bytes': f'ssh-ed25519 {base64.b64encode(base64.b64decode(K1) + b"x").decode()}\n'.encode(), + 'extra padding': f'ssh-ed25519 {K1}==\n'.encode(), + 'non-ascii': f'ssh-ed25519 {K1} caf\u00e9\n'.encode(), + 'type only': b'ssh-ed25519\n', + 'too long': b'ssh-ed25519 ' + b'A' * 20000 + b'\n', + 'private key': PRIVATE, + } + for name, key in bad.items(): + with self.subTest(name): + code, out = self.run_tool('add', 'desk', stdin=key) + self.assertEqual(code, REFUSED, out) + self.assertEqual(self.snap(), before) + self.assertNotIn('c2VjcmV0LW1hcmtlcg', out) + self.assertIn('private key', self.run_tool('add', 'desk', stdin=PRIVATE)[1]) + + def test_refuses_a_pool_it_does_not_know(self): + for pool in ('nope', 'vm', 'pc', '../desk', 'desk "x"'): + with self.subTest(pool): + code, out = self.run_tool('add', pool, stdin=PUB1) + self.assertEqual(code, REFUSED, out) + self.assertFalse(os.path.lexists(self.ssh)) + code, out = self.run_tool('remove', pool) + self.assertEqual(code, REFUSED, out) + self.assertEqual(self.run_tool('status', pool)[0], REFUSED) + self.assertFalse(os.path.lexists(self.ssh)) + if not dk.ff.POOL.fullmatch(pool): # not even a pool name: refused before anything is read + self.assertIn('is not a pool name', out) + + def test_one_line_per_pool_and_one_line_per_key(self): + self.assertEqual(self.run_tool('add', 'desk', stdin=PUB1)[0], 0) + before = self.snap() + code, out = self.run_tool('add', 'desk', stdin=f'ssh-ed25519 {K2}\n'.encode()) + self.assertEqual(code, REFUSED) + self.assertIn(K1, out) + self.assertIn(K2, out) + code, out = self.run_tool('add', 'desk2', stdin=PUB1) # the same key for a second pool: sshd uses the first + self.assertEqual((code, self.snap()), (REFUSED, before), out) + self.put(f'ssh-ed25519 {K2} a plain login line\n'.encode()) + before = self.snap() + code, out = self.run_tool('add', 'desk', stdin=f'ssh-ed25519 {K2}\n'.encode()) + self.assertEqual((code, self.snap()), (REFUSED, before), out) + self.assertIn('another line', out) + + def test_remove_and_status_touch_only_their_pool(self): + self.put(b'ssh-rsa AAAAB3 me\n') + self.assertEqual(self.run_tool('add', 'desk', stdin=PUB1)[0], 0) + self.assertEqual(self.run_tool('add', 'desk2', stdin=f'ssh-ed25519 {K2}\n'.encode())[0], 0) + self.assertEqual(self.run_tool('status')[0], 0) + self.assertEqual(self.run_tool('remove', 'desk')[0], 0) + self.assertEqual(self.content(), b'ssh-rsa AAAAB3 me\n' + dk.line_for('desk2', K2).encode() + b'\n') + self.assertEqual(self.run_tool('status')[0], MISSING) + self.assertEqual(self.run_tool('status', 'desk2')[0], 0) + + def test_status_finds_wrong_lines(self): + stale = f'restrict,command="python3 -I /old/fork-fleet-desk.py serve desk" ssh-ed25519 {K1} ' \ + 'fork-fleet-desk:desk\n' + good = dk.line_for('desk', K1) + '\n' + for name, data in (('old command', stale), ('two lines', good + good), ('no restrict', good[len('restrict,'):]), + ('key also elsewhere', good + f'ssh-ed25519 {K1} me\n'), + ('no options at all', f'ssh-ed25519 {K1} fork-fleet-desk:desk\n')): + with self.subTest(name): + self.put(data.encode()) + code, out = self.run_tool('status', 'desk') + self.assertEqual(code, PROBLEM, out) + self.assertIn('wrong', out) + self.assertEqual(self.run_tool('add', 'desk', stdin=PUB1)[0], REFUSED) + self.put(f'# x\nssh-ed25519 {K1} fork-fleet-desk:desk\n'.encode()) # an unrestricted line with the mark + self.assertEqual(self.run_tool('remove', 'desk')[0], OK) + self.assertEqual(self.content(), b'# x\n') + self.put('# fork-fleet-desk:desk\n'.encode()) # a comment line is no line + self.assertEqual(self.run_tool('status', 'desk')[0], MISSING) + + def test_refuses_symlinks(self): + real = os.path.join(self.tmp, 'real') + with open(real, 'wb') as f: + f.write(b'# elsewhere\n') + os.makedirs(self.ssh, 0o700) + os.symlink(real, self.keys) + for args, stdin in ((('add', 'desk'), PUB1), (('remove', 'desk'), b''), (('status', 'desk'), b'')): + code, out = self.run_tool(*args, stdin=stdin) + self.assertEqual((code, 'is a symlink' in out), (REFUSED, True), out) + self.assertTrue(os.path.islink(self.keys)) + os.unlink(self.keys) + os.rmdir(self.ssh) + os.mkdir(os.path.join(self.tmp, 'dot-ssh')) + os.symlink(os.path.join(self.tmp, 'dot-ssh'), self.ssh) + code, out = self.run_tool('add', 'desk', stdin=PUB1) + self.assertEqual((code, 'is a symlink' in out), (REFUSED, True), out) + self.assertEqual(os.listdir(os.path.join(self.tmp, 'dot-ssh')), []) + with open(real, 'rb') as f: + self.assertEqual(f.read(), b'# elsewhere\n') + + def test_only_as_the_desk_link_user_and_never_as_root(self): + self.assertIn('never as root', self.in_process('--user', 'root', 'add', 'desk', stdin=PUB1, euid=0)[1]) + code, out = self.in_process('add', 'desk', stdin=PUB1, euid=os.geteuid()) # default user name + self.assertEqual((code, dk.USER in out), (REFUSED, True), out) + self.assertEqual(self.run_tool('--user', ME + 'x', 'status')[0], REFUSED) + self.assertFalse(os.path.lexists(self.ssh)) + other = next((u for u in pwd.getpwall() if u.pw_uid not in (0, os.geteuid())), None) + if other is None: + self.skipTest('no second user') + for made in (False, True): # HOME (to make ~/.ssh), then ~/.ssh, of another user: refused + if made: + self.put(b'# mine\n') + code, out = self.in_process('--user', other.pw_name, 'add', 'desk', stdin=PUB1, euid=other.pw_uid) + self.assertEqual((code, 'does not belong' in out), (REFUSED, True), out) + self.assertEqual(self.content(), b'# mine\n') + + @contextlib.contextmanager + def account(self, home=None, groups=(), system_max=-1): + """What RUN fakes, in process: the password-database home, the groups (names), the system-account limit.""" + real = pwd.getpwuid + + def getpwuid(uid): + e = real(uid) + return pwd.struct_passwd((e.pw_name, e.pw_passwd, e.pw_uid, e.pw_gid, e.pw_gecos, home or self.home, + e.pw_shell)) + gids = {90000 + i: name for i, name in enumerate(groups)} + with mock.patch.object(dk.pwd, 'getpwuid', getpwuid), \ + mock.patch.object(dk.os, 'getgrouplist', return_value=list(gids)), \ + mock.patch.object(dk.grp, 'getgrgid', side_effect=lambda g: mock.Mock(gr_name=gids[g])), \ + mock.patch.object(dk, 'SYSTEM_UID_MAX', system_max): + yield + + def in_process(self, *argv, stdin=b'', euid=None, **account): + out = io.StringIO() + argv = argv if '--user' in argv or euid is not None else ('--user', ME) + argv + with mock.patch.dict(os.environ, {'HOME': self.home}), redirect_stdout(out), redirect_stderr(out), \ + mock.patch.object(dk.os, 'geteuid', return_value=os.geteuid() if euid is None else euid), \ + self.account(**account): + return dk.main(['--config', self.config, *argv], io.BytesIO(stdin)), out.getvalue() + + def test_stopped_half_way_leaves_the_old_file(self): + self.put(b'# old\n', 0o644) + before = self.snap() + with mock.patch.object(dk.os, 'replace', side_effect=OSError('cut')): + self.assertEqual(self.in_process('add', 'desk', stdin=PUB1)[0], ERROR) + self.assertEqual(self.snap(), before) + self.assertEqual(sorted(os.listdir(self.ssh)), ['authorized_keys']) + leftover = os.path.join(self.ssh, dk.TMP + 'x') # from a run that was killed before its rename + with open(leftover, 'wb') as f: + f.write(b'half') + self.assertEqual(self.run_tool('add', 'desk', stdin=PUB1)[0], 0) + self.assertFalse(os.path.lexists(leftover)) + + def test_file_changed_meanwhile_is_left_alone(self): + self.put(b'# before\n') + real_mkstemp = dk.tempfile.mkstemp + + def someone_writes(*a, **kw): + self.put(b'# written by someone else\n') + return real_mkstemp(*a, **kw) + with mock.patch.object(dk.tempfile, 'mkstemp', side_effect=someone_writes): + code, out = self.in_process('add', 'desk', stdin=PUB1) + self.assertEqual(code, REFUSED, out) + self.assertIn('changed while this ran', out) + self.assertEqual(self.content(), b'# written by someone else\n') + self.assertEqual(sorted(os.listdir(self.ssh)), ['authorized_keys']) + + @unittest.skipUnless(shutil.which('ssh-keygen'), 'no ssh-keygen') + def test_openssh_reads_the_line_and_agrees_on_the_fingerprint(self): + key = os.path.join(self.tmp, 'id') + subprocess.run(['ssh-keygen', '-q', '-t', 'ed25519', '-N', '', '-C', 'x', '-f', key], check=True) + with open(key + '.pub', 'rb') as f: + self.assertEqual(self.run_tool('add', 'desk', stdin=f.read())[0], 0) + got = subprocess.run(['ssh-keygen', '-l', '-E', 'sha256', '-f', self.keys], capture_output=True, text=True) + self.assertEqual(got.returncode, 0, got.stderr) + self.assertIn(self.run_tool('status', 'desk')[1].split('(')[1].rstrip(')\n'), got.stdout) + + def without(self, name): + with open(self.config) as f: + cfg = json.load(f) + cfg['pools'] = [p for p in cfg['pools'] if p['name'] != name] + with open(self.config, 'w') as f: + json.dump(cfg, f) + + def test_a_retired_pool_line_is_shown_and_removable(self): + self.put(b'ssh-rsa AAAAB3 me\n') + self.assertEqual(self.run_tool('add', 'desk', stdin=PUB1)[0], 0) + self.assertEqual(self.run_tool('add', 'desk2', stdin=f'ssh-ed25519 {K2}\n'.encode())[0], 0) + self.without('desk') # the desktop is retired: its pool leaves the config first + for args in (('status',), ('status', 'desk')): + code, out = self.run_tool(*args) + self.assertEqual(code, PROBLEM, out) + self.assertIn('key for retired pool desk still allows a login: run desk-key remove desk', out) + code, out = self.run_tool('add', 'desk3', stdin=PUB1) # not a desk pool: refused before anything is read + self.assertEqual(code, REFUSED, out) + before = self.snap() + self.assertEqual(self.run_tool('add', 'desk2', stdin=PUB1)[0], REFUSED) # the key is still on a line + self.assertEqual(self.snap(), before) + code, out = self.run_tool('remove', 'desk') + self.assertEqual(code, OK, out) + self.assertEqual(self.content(), b'ssh-rsa AAAAB3 me\n' + dk.line_for('desk2', K2).encode() + b'\n') + self.assertEqual(self.run_tool('status')[0], OK) + self.assertEqual(self.run_tool('remove', 'desk')[0], REFUSED) # no line and no pool: a typo, say so + self.assertEqual(self.run_tool('status', 'desk')[0], REFUSED) + + def test_lines_split_at_newline_only_as_sshd_does(self): + tail = f'ssh-ed25519 {K2} tail' + for name, raw, status_code in ( + ('desk line, then a lone CR and a key in its comment', + f'{dk.line_for("desk", K1)}\r{tail}\n', PROBLEM), + ('a login line whose comment runs on into a desk line', + f'ssh-rsa AAAAB3 me\r{dk.line_for("desk", K1)}\n', PROBLEM), + ('the same with a space: one ssh-rsa line to sshd', + f'ssh-rsa AAAAB3 me {dk.line_for("desk", K1)}\n', PROBLEM), + ('a CR inside the options', + dk.line_for('desk', K1).replace(',command', '\r,command') + '\n', PROBLEM)): + with self.subTest(name): + self.put(raw.encode()) + before = self.snap() + code, out = self.run_tool('status', 'desk') + self.assertEqual(code, status_code, out) + self.assertIn('edit it by hand', out) + code, out = self.run_tool('remove', 'desk') + self.assertEqual(code, PROBLEM, out) + self.assertEqual(self.snap(), before) # never cut: no tail can become a key line of its own + self.assertFalse(any(ln.lstrip().startswith(b'ssh-ed25519') for ln in self.content().split(b'\n'))) + self.put(f'# x\r\n{dk.line_for("desk", K1)}\r\nssh-rsa AAAAB3 me\r\n'.encode()) # CRLF: a normal file + self.assertEqual(self.run_tool('status', 'desk')[0], OK) + self.assertEqual(self.run_tool('remove', 'desk')[0], OK) + self.assertEqual(self.content(), b'# x\r\nssh-rsa AAAAB3 me\r\n') + + def test_exit_codes_are_distinct_and_documented(self): + p = subprocess.run([sys.executable, '-I', TOOL, '--help'], capture_output=True, text=True, timeout=60) + self.assertEqual(p.returncode, 0, p.stderr) + for code in (OK, PROBLEM, REFUSED, MISSING, ERROR): + self.assertRegex(p.stdout, rf'\n {code} \w') + doc = os.path.join(os.path.dirname(HERE), 'fork-fleet-desk-key.md') + with open(doc, encoding='utf-8') as f: + text = f.read() + for code in (OK, PROBLEM, REFUSED, MISSING, ERROR): + self.assertRegex(text, rf'\n\| {code} +\|') + self.assertEqual((OK, PROBLEM, REFUSED, MISSING, ERROR), (dk.OK, dk.PROBLEM, dk.REFUSED, dk.MISSING, dk.ERROR)) + self.assertEqual(self.run_tool('add', 'desk', stdin=b'junk\n')[0], REFUSED) + self.assertEqual(self.run_tool('status', 'desk')[0], MISSING) + self.put(((dk.line_for('desk', K1) + '\n') * 2).encode()) + self.assertEqual(self.run_tool('status', 'desk')[0], PROBLEM) + self.assertEqual(self.run_tool('--user', ME + 'x', 'status', 'desk')[0], REFUSED) + self.assertEqual(self.run_tool('frobnicate')[0], REFUSED) # bad usage + with mock.patch.object(dk.os, 'fsync', side_effect=OSError(28, 'No space left on device')): + self.assertEqual(self.in_process('remove', 'desk')[0], ERROR) + + def test_a_second_run_waits_for_the_lock(self): + self.put(b'# start\n') + fd = os.open(self.ssh, os.O_RDONLY | os.O_DIRECTORY) + try: + fcntl.flock(fd, fcntl.LOCK_EX) # another desk-key run holds ~/.ssh + p = subprocess.Popen(self.cmd('add', 'desk'), stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, env=self.env()) + p.stdin.write(PUB1) + p.stdin.close() + with self.assertRaises(subprocess.TimeoutExpired, msg='add did not wait for the lock on ~/.ssh'): + p.wait(timeout=3) + self.put(b'# start\n# the other run\n') # what the lock holder writes before it lets go + finally: + os.close(fd) + out = p.stdout.read() + p.stdout.close() + self.assertEqual(p.wait(timeout=60), OK, out) + self.assertEqual(self.content(), b'# start\n# the other run\n' + dk.line_for('desk', K1).encode() + b'\n') + + def test_two_adds_at_once_on_an_empty_home(self): + real_mkdir = os.mkdir + + def the_other_run_made_it_first(path, mode=0o777): + real_mkdir(path, 0o700) + raise FileExistsError(17, 'File exists', path) + with mock.patch.object(dk.os, 'mkdir', side_effect=the_other_run_made_it_first): + code, out = self.in_process('add', 'desk', stdin=PUB1) + self.assertEqual(code, OK, out) + self.assertEqual(self.content(), dk.line_for('desk', K1).encode() + b'\n') + os.unlink(self.keys) + os.rmdir(self.ssh) + os.symlink(self.tmp, self.ssh) # what the other "run" made is still checked: a symlink + with mock.patch.object(dk.os.path, 'lexists', side_effect=lambda p: p != self.ssh and os.path.exists(p)), \ + mock.patch.object(dk.os, 'mkdir', side_effect=FileExistsError(17, 'File exists')): + code, out = self.in_process('add', 'desk', stdin=PUB1) + self.assertEqual((code, 'is a symlink' in out), (REFUSED, True), out) + + def test_the_home_sshd_reads_admins_and_system_accounts(self): + elsewhere = os.path.join(self.tmp, 'real-home') + os.mkdir(elsewhere) + code, out = self.in_process('add', 'desk', stdin=PUB1, home=elsewhere) # $HOME is not the user's home + self.assertEqual((code, 'sshd reads' in out), (REFUSED, True), out) + for group in ('sudo', 'wheel', 'adm', 'docker'): + code, out = self.in_process('add', 'desk', stdin=PUB1, groups=('users', group)) + self.assertEqual((code, 'admin group' in out), (REFUSED, True), out) + code, out = self.in_process('add', 'desk', stdin=PUB1, system_max=10 ** 9) # a system uid, not USER + self.assertEqual((code, 'system account' in out), (REFUSED, True), out) + self.assertFalse(os.path.lexists(self.ssh)) + with mock.patch.object(dk, 'USER', ME): # the default name may be a system account + code, out = self.in_process('add', 'desk', stdin=PUB1, system_max=10 ** 9, groups=('users',)) + self.assertEqual(code, OK, out) + + def test_unsafe_modes_and_leftovers(self): + self.put(b'# x\n', 0o620) + self.assertEqual(self.run_tool('add', 'desk', stdin=PUB1)[0], REFUSED) # sshd would not read it + os.chmod(self.keys, 0o600) + os.chmod(self.ssh, 0o770) + self.assertEqual(self.run_tool('add', 'desk', stdin=PUB1)[0], REFUSED) + os.chmod(self.ssh, 0o700) + self.assertEqual(self.content(), b'# x\n') + junk = os.path.join(self.ssh, dk.TMP + 'made-by-hand') + os.mkdir(junk) # not this tool's: skipped, never in the way + stale = os.path.join(self.ssh, dk.TMP + 'stale') + with open(stale, 'wb') as f: + f.write(b'half') + os.utime(stale, (1, 1)) # from a run long gone + self.assertEqual(self.run_tool('add', 'desk', stdin=PUB1)[0], OK) + self.assertEqual((os.path.isdir(junk), os.path.lexists(stale)), (True, False)) + + def test_serve_takes_the_forced_command_of_every_pool_name(self): + """The contract with the desk link (row D2): its program is DESK's file and `serve` takes SERVE POOL.""" + desk = os.path.join(HERE, os.path.basename(dk.DESK)) + if not os.path.exists(desk): + mine = {os.path.basename(TOOL), os.path.basename(__file__)} + d2 = [os.path.basename(p) for p in glob.glob(os.path.join(HERE, 'fork-fleet-desk*')) + if os.path.basename(p) not in mine] + runbook = os.path.join(os.path.dirname(HERE), 'fork-fleet.md') + with open(runbook, encoding='utf-8') as f: + d2 += ['fork-fleet.md'] * ('# The desk link' in f.read()) + self.assertEqual(d2, [], f'the desk link (row D2) is here, but {os.path.basename(dk.DESK)} is not: ' + 'point DESK and SERVE at its program') + self.skipTest('the desk link (row D2) is not here yet') + spec = importlib.util.spec_from_file_location('fork_fleet_desk', desk) + d2 = importlib.util.module_from_spec(spec) + spec.loader.exec_module(d2) # its own constants, not its comments + for name in ('FORCED', 'INSTALLED', 'USER'): + self.assertTrue(hasattr(d2, name), f'the desk link (row D2) no longer defines {name}') + self.assertEqual((dk.SERVE, dk.DESK, dk.USER), (d2.FORCED, d2.INSTALLED, d2.USER), + 'the key tool and the desk link (row D2) name a different forced command, program or user') + self.assertIn(f'command="{d2.FORCED} desk" ', dk.line_for('desk', K1)) + argv = shlex.split(dk.line_for('desk', K1).split('"')[1]) + self.assertEqual(argv[:4], [dk.PYTHON, '-I', dk.DESK, 'serve']) + run = os.path.join(self.tmp, 'run') + os.mkdir(run, 0o700) + + def serve(*args): + p = subprocess.run([sys.executable, '-I', desk, *args], stdin=subprocess.DEVNULL, capture_output=True, + text=True, timeout=60, env={**self.env(), 'FORK_FLEET_DESK_DIR': run}) + return p.returncode, re.sub(rf'(?