The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Add reversible Fedora login setup for existing accounts (#804)
Deeb5b0d30e36bf
diff --git a/os/DEVELOPMENT.md b/os/DEVELOPMENT.mdindex 9da6f0463..7d88d1508 100644--- a/os/DEVELOPMENT.md+++ b/os/DEVELOPMENT.md@@ -665,6 +665,68 @@ tests that older image, not product changes in the newer test checkout.Apple firmware provisioning, physical drivers, platform installation and Fedoraupdate/recovery integration remain separate work before releasing this port.+### Explicit Fedora login setup++The private session RPM includes `harness-session-setup`, implemented separately+in `fedora_session.py`. Installing the RPM remains passive. On an existing Fedora+Asahi Minimal system, an administrator may install Fedora's `greetd` package and+explicitly select an existing account with `enable --user USER --autologin`.+The account must already have a usable recovery password and sudo permission to+disable setup. The helper never creates accounts or edits their homes/profiles.++Fedora's greetd package supplies PAM session setup, logind integration and its+conditional SELinux policy. Its standard display-manager alias and graphical+target handle tty1 ordering/conflicts. Harness adds one configuration, one service+drop-in and one selected-user sudoers rule for the two exact Wi-Fi form commands.+`visudo` validates that rule before activation. A durable receipt precedes changes;+failure rolls them back, `disable` restores the exact previous target, and edited+managed files are preserved for explicit conflict resolution. Enable and disable+never start, stop or restart the current session; they affect the next boot.+Other ttys and vendor login configuration remain intact.++The Fedora 44 aarch64 `greetd-0.10.3-6.fc44` RPM has 1,355,071 bytes of regular-file+payload (443,637 bytes downloaded); its matching SELinux package adds 10,359 bytes+of payload (20,682 bytes downloaded). This is a PAM login daemon and text greeter,+without another desktop environment. These measurements exclude already-shared+Fedora dependencies and filesystem allocation; record the actual dependency+transaction in native validation. The upstream source RPM and artifact hashes+belong in the ignored validation receipt. Fedora's normal policy supplies the+session's authenticated fallback and runtime directory instead of copying the+VM fixture's empty-password/profile autostart into an existing installation.++Run the focused portable contracts with:++```sh+python3 -m unittest discover -s os/tests -p 'test_fedora_session.py'+python3 -m unittest discover -s os/tests -p 'test_fedora_package.py'+```++These exercise temporary-root transactions, account prerequisites, conflicting+and edited configuration, interruption recovery and the passive RPM payload.+They do not establish actual PAM authentication, SELinux enforcement or graphical+boot. Those require the separate native Fedora VM sequence and ultimately real+Apple hardware. With an exact-source immutable fixture, the private login driver+normalizes only its disposable clone, installs signed Fedora login/SELinux+packages, and requires enforcing policy after a cold boot:++```sh+python3 os/tests/fedora_session_vm.py \+ --fixture /path/to/harness-arm-session-fixture \+ --fixture-source FULL_IMAGE_PRODUCER_SHA \+ --output os/test-results/fedora-session-login+```++It records the setup source separately from the image/runtime, tests QMP virtual+keyboard password login and sudo, next-boot autologin, the two exact Wi-Fi forms,+authenticated recovery and disable back to the prior console. It does not relax+SELinux enforcement to pass. The candidate helper is overlaid onto the existing+RPM fixture; the portable payload check separately covers its package exposure.++The setup does not touch Apple partitioning, ESP/m1n1/U-Boot/GRUB,+firmware, kernels or Asahi's speaker-safety configuration. Fedora/Asahi remains+responsible for base-system updates and recovery; Super+u remains the verified+per-user runtime update path described above.+### Native runtime updates in the ARM fixtureThe **Harness OS private runtime update fixtures** workflow builds native x86 anddiff --git a/os/fedora_session.py b/os/fedora_session.pynew file mode 100644index 000000000..3ea4d1d89--- /dev/null+++ b/os/fedora_session.py@@ -0,0 +1,363 @@+#!/usr/bin/python3+"""Explicit, reversible console login setup for the private Fedora session RPM."""+import argparse+import contextlib+import datetime+import fcntl+import json+import os+from pathlib import Path+import platform+import re+import stat+import subprocess+import tempfile+++STATE = 'var/lib/harness-os/session-setup.json'+CONFIG = 'etc/greetd/harness.toml'+DROPIN = 'etc/systemd/system/greetd.service.d/90-harness.conf'+SUDOERS = 'etc/sudoers.d/harness-session-network'+ALIAS = 'etc/systemd/system/display-manager.service'+TARGET = 'etc/systemd/system/default.target'+PATHS = (CONFIG, DROPIN, SUDOERS, ALIAS, TARGET)+USERNAME = re.compile(r'[A-Za-z_][A-Za-z0-9_.-]{0,31}')+++class SetupError(RuntimeError):+ pass+++def regular(text, mode=0o644):+ return {'kind': 'file', 'text': text, 'mode': mode}+++def link(target):+ return {'kind': 'link', 'target': target}+++class Setup:+ def __init__(self, root=Path('/')):+ self.root = root++ def path(self, name):+ path = self.root / name+ # Never follow an administrator's redirected configuration directory.+ for parent in path.parents:+ if parent == self.root:+ break+ if parent.is_symlink():+ raise SetupError('Refusing a symlink configuration directory: ' + str(parent))+ if parent.exists():+ info = parent.stat()+ if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.geteuid() or info.st_mode & 0o022:+ raise SetupError('Configuration directory is not securely owned: ' + str(parent))+ return path++ def snapshot(self, name):+ path = self.path(name)+ try:+ info = path.lstat()+ except FileNotFoundError:+ return None+ if info.st_uid != os.geteuid():+ raise SetupError('Configuration has a different owner: ' + str(path))+ if stat.S_ISLNK(info.st_mode):+ return link(os.readlink(path))+ if stat.S_ISREG(info.st_mode):+ return regular(path.read_text(), stat.S_IMODE(info.st_mode))+ raise SetupError('Refusing a special configuration file: ' + str(path))++ def run(self, *command, check=True):+ result = subprocess.run(command, stdin=subprocess.DEVNULL, text=True,+ capture_output=True, timeout=20)+ if check and result.returncode:+ raise SetupError(command[0] + ' failed: ' + (result.stderr or result.stdout).strip()[-500:])+ return result.stdout.strip()++ def sync_directory(self, path):+ descriptor = os.open(path, os.O_RDONLY | os.O_DIRECTORY)+ try:+ os.fsync(descriptor)+ finally:+ os.close(descriptor)++ def write(self, name, entry, replace=False):+ path = self.path(name)+ path.parent.mkdir(parents=True, exist_ok=True)+ descriptor, temporary = tempfile.mkstemp(prefix='.harness-setup-', dir=path.parent)+ try:+ if entry['kind'] == 'link':+ os.close(descriptor)+ os.unlink(temporary)+ os.symlink(entry['target'], temporary)+ else:+ with os.fdopen(descriptor, 'w') as stream:+ os.fchmod(stream.fileno(), entry['mode'])+ stream.write(entry['text'])+ stream.flush()+ os.fsync(stream.fileno())+ if name == SUDOERS:+ self.run('/usr/sbin/visudo', '-c', '-f', temporary)+ if replace:+ os.replace(temporary, path)+ else:+ os.link(temporary, path, follow_symlinks=False)+ self.sync_directory(path.parent)+ finally:+ if os.path.lexists(temporary):+ os.unlink(temporary)++ def save(self, state):+ previous = self.snapshot(STATE)+ if previous is not None and (previous['kind'] != 'file' or previous['mode'] != 0o600):+ raise SetupError('The setup receipt must be a private regular file.')+ self.write(STATE, regular(json.dumps(state, indent=2) + '\n', 0o600), replace=True)++ def load(self):+ entry = self.snapshot(STATE)+ if entry is None:+ return None+ if entry['kind'] != 'file' or entry['mode'] != 0o600:+ raise SetupError('The setup receipt must be a private regular file.')+ state = json.loads(entry['text'])+ if (state.get('schema') != 1 or state.get('phase') not in {'enabling', 'enabled', 'disabling'} or+ not USERNAME.fullmatch(str(state.get('user', ''))) or+ set(state.get('files', {})) != set(PATHS)):+ raise SetupError('Unrecognized setup receipt; preserve it for recovery.')+ expected = self.plan(state['user'], state['files'][TARGET]['before'], state['previous_target'],+ state['files'][ALIAS]['before'])+ if state['files'] != expected or state.get('created_dirs') != [+ name for name in state.get('created_dirs', []) if name in {+ 'etc/systemd/system/greetd.service.d', 'var/lib/harness-os'}]:+ raise SetupError('Setup receipt has unexpected file changes; preserve it for recovery.')+ return state++ @contextlib.contextmanager+ def locked(self):+ path = self.path('run/harness-session-setup.lock')+ descriptor = os.open(path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)+ try:+ info = os.fstat(descriptor)+ if not stat.S_ISREG(info.st_mode) or info.st_uid != os.geteuid() or info.st_mode & 0o077:+ raise SetupError('The setup lock is not securely owned.')+ try:+ fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)+ except BlockingIOError as error:+ raise SetupError('Another session setup is running.') from error+ yield+ finally:+ os.close(descriptor)++ def account(self, user):+ if not USERNAME.fullmatch(user):+ raise SetupError('Choose an existing local account with a conventional login name.')+ accounts = [line.split(':') for line in self.path('etc/passwd').read_text().splitlines()]+ account = next((row for row in accounts if len(row) == 7 and row[0] == user), None)+ limits = self.path('etc/login.defs').read_text()+ minimum = re.search(r'^\s*UID_MIN\s+(\d+)', limits, re.MULTILINE)+ if not account or int(account[2]) < max(1, int(minimum[1]) if minimum else 1000):+ raise SetupError('Choose an existing, non-root local user account.')+ shells = self.path('etc/shells').read_text().splitlines()+ home = self.root / account[5].lstrip('/')+ shell = self.root / account[6].lstrip('/')+ if (not account[5].startswith('/') or not home.is_dir() or home.stat().st_uid != int(account[2]) or+ account[6] not in shells or Path(account[6]).name in {'false', 'nologin'} or+ not os.access(shell, os.X_OK)):+ raise SetupError('The selected account needs its existing home and an enabled login shell.')+ shadows = [line.split(':') for line in self.path('etc/shadow').read_text().splitlines()]+ shadow = next((row for row in shadows if len(row) == 9 and row[0] == user), None)+ today = (datetime.date.today() - datetime.date(1970, 1, 1)).days+ if (not shadow or not shadow[1] or shadow[1][0] in '!*' or not shadow[2] or int(shadow[2]) == 0 or+ not re.fullmatch(r'\$[^$\s:]+\$[^:\s]{10,}|[./0-9A-Za-z]{13}', shadow[1]) or+ (shadow[7] and int(shadow[7]) >= 0 and int(shadow[7]) <= today) or+ (shadow[4] and int(shadow[4]) >= 0 and int(shadow[2]) + int(shadow[4]) <= today)):+ raise SetupError('The selected account needs a usable, unexpired password for recovery login.')+ # Query existing policy as root; do not authenticate or grant administrative access.+ self.run('/usr/bin/sudo', '-n', '-l', '-U', user, '--', '/usr/bin/harness-session-setup', 'disable')+ return int(account[2])++ def preflight(self, user):+ release = self.path('etc/os-release').read_text()+ if (platform.machine() != 'aarch64' or not re.search(r'^ID=[\"\']?fedora[\"\']?$', release, re.MULTILINE) or+ json.loads(self.path('usr/share/harness-os/runtime.json').read_text()).get('system_profile') != 'fedora'):+ raise SetupError('This setup is only for the native Fedora ARM session package.')+ for binary in ('usr/bin/greetd', 'usr/bin/agreety', 'usr/bin/harness-session', 'usr/sbin/visudo'):+ if not os.access(self.root / binary, os.X_OK):+ raise SetupError('Install Fedora\'s greetd and sudo packages before enabling the session.')+ self.run('/usr/bin/rpm', '-V', 'greetd')+ # Bound the files systemctl enable may create to the vendor alias we record.+ unit = self.path('usr/lib/systemd/system/greetd.service').read_text()+ install = re.search(r'^\[Install\]\s*\n(.*?)(?=^\[|\Z)', unit, re.MULTILINE | re.DOTALL)+ settings = [line.strip() for line in install[1].splitlines()+ if line.strip() and not line.lstrip().startswith(('#', ';'))] if install else []+ if settings != ['Alias=display-manager.service']:+ raise SetupError('The installed greetd enablement policy differs; review it before setup.')+ if self.path('sys/fs/selinux/enforce').exists():+ self.run('/usr/bin/rpm', '-q', 'greetd-selinux')+ self.run('/usr/sbin/visudo', '-c')+ for service in ('greetd.service', 'display-manager.service'):+ if self.run('/usr/bin/systemctl', 'is-active', service, check=False) not in {'inactive', 'failed'}:+ raise SetupError('An existing login manager is active; keep its configuration.')+ alias_before = self.snapshot(ALIAS)+ enabled = self.run('/usr/bin/systemctl', 'is-enabled', 'greetd.service', check=False)+ if not ((enabled == 'disabled' and alias_before is None) or+ (enabled == 'enabled' and alias_before == link('/usr/lib/systemd/system/greetd.service'))):+ raise SetupError('greetd has a different enablement or mask; keep its configuration.')+ for prefix in ('etc', 'run', 'usr/lib'):+ for name in ('greetd.service', 'display-manager.service'):+ if prefix == 'etc' and name == 'display-manager.service' and alias_before is not None:+ continue # Fedora's pristine package preset is retained on disable.+ if ((prefix != 'usr/lib' or name == 'display-manager.service') and+ self.snapshot(prefix + '/systemd/system/' + name) is not None):+ raise SetupError('An existing login-manager override or alias is present.')+ overrides = self.path(prefix + '/systemd/system/greetd.service.d')+ if overrides.exists() and any(overrides.iterdir()):+ raise SetupError('An existing greetd override is present.')+ if self.run('/usr/bin/systemctl', 'is-enabled', '[email protected]', check=False).startswith('masked'):+ raise SetupError('The recovery console on tty2 is masked.')+ previous_target = self.run('/usr/bin/systemctl', 'get-default')+ if previous_target not in {'multi-user.target', 'graphical.target'}:+ raise SetupError('Keep the existing custom boot target.')+ before = self.snapshot(TARGET)+ if before is not None and before not in [link('/' + directory + '/' + previous_target)+ for directory in ('usr/lib/systemd/system', 'lib/systemd/system')]:+ raise SetupError('Keep the existing custom default-target configuration.')+ files = self.plan(user, before, previous_target, alias_before)+ for name, change in files.items():+ if self.snapshot(name) != change['before']:+ raise SetupError('Configuration already exists: /' + name)+ return self.account(user), previous_target, files++ def plan(self, user, target_before, previous_target, alias_before=None):+ if previous_target not in {'multi-user.target', 'graphical.target'}:+ raise SetupError('Unrecognized original target in setup receipt.')+ if target_before is not None and target_before not in [+ link('/' + directory + '/' + previous_target)+ for directory in ('usr/lib/systemd/system', 'lib/systemd/system')]:+ raise SetupError('Unrecognized original target link in setup receipt.')+ if alias_before not in (None, link('/usr/lib/systemd/system/greetd.service')):+ raise SetupError('Unrecognized original login-manager alias in setup receipt.')+ config = ('[terminal]\nvt = 1\n\n[general]\nsource_profile = false\n\n'+ '[default_session]\ncommand = "/usr/bin/agreety --cmd /usr/bin/harness-session"\n'+ 'user = "greetd"\n\n[initial_session]\ncommand = "/usr/bin/harness-session"\n'+ 'user = ' + json.dumps(user) + '\n')+ sudoers = ('# Managed by harness-session-setup; only the existing network form.\n' + user ++ ' ALL=(root) NOPASSWD: /usr/bin/python3 /usr/lib/harness-os/network.py, '+ '/usr/bin/python3 /usr/lib/harness-os/network.py --first-use\n')+ files = {name: {'before': None, 'after': entry} for name, entry in [+ (CONFIG, regular(config)),+ (DROPIN, regular('[Service]\nExecStart=\nExecStart=/usr/bin/greetd --config /etc/greetd/harness.toml\n')),+ (SUDOERS, regular(sudoers, 0o440)),+ (ALIAS, link('/usr/lib/systemd/system/greetd.service')),+ ]}+ files[TARGET] = {'before': target_before, 'after': target_before if previous_target == 'graphical.target'+ else link('/usr/lib/systemd/system/graphical.target')}+ files[ALIAS]['before'] = alias_before+ return files++ def verify(self, state, partial=False):+ for name, change in state['files'].items():+ current = self.snapshot(name)+ permitted = [change['after']]+ if partial:+ permitted.append(change['before'])+ if name == TARGET:+ # Recover an interrupted systemctl replacement of the old link.+ permitted.append(None)+ if current not in permitted:+ raise SetupError('Managed configuration changed; preserve it and the receipt: /' + name)++ def rollback(self, state):+ self.verify(state, partial=True)+ for name in reversed(PATHS):+ change = state['files'][name]+ if self.snapshot(name) == change['before']:+ continue+ if change['before'] is None:+ self.path(name).unlink()+ self.sync_directory(self.path(name).parent)+ else:+ self.write(name, change['before'], replace=True)+ self.path(STATE).unlink()+ self.sync_directory(self.path(STATE).parent)+ for name in reversed(state['created_dirs']):+ try:+ self.path(name).rmdir()+ except OSError:+ pass # Never remove another component's files.++ def enable(self, user):+ existing = self.load()+ if existing:+ if existing['phase'] != 'enabled':+ raise SetupError('A previous setup was interrupted. Run harness-session-setup disable to restore it.')+ if existing['user'] != user:+ raise SetupError('Disable the existing setup before selecting a different account.')+ self.verify(existing)+ if self.account(user) != existing['uid']:+ raise SetupError('The selected account identity has changed; disable the existing setup.')+ return 'Harness login is already enabled for ' + user + '.'+ uid, target, files = self.preflight(user)+ state = {'schema': 1, 'phase': 'enabling', 'user': user, 'uid': uid,+ 'previous_target': target, 'files': files,+ 'created_dirs': [name for name in ('var/lib/harness-os', 'etc/systemd/system/greetd.service.d')+ if not self.path(name).exists()]}+ self.save(state) # Durable before any login policy changes.+ try:+ for name in (CONFIG, DROPIN, SUDOERS):+ self.write(name, files[name]['after'])+ if self.path('sys/fs/selinux/enforce').exists():+ self.run('/usr/sbin/restorecon', str(self.path(name)))+ # Use Fedora's unit Install policy. Neither command starts/stops a service.+ self.run('/usr/bin/systemctl', '--no-reload', 'enable', 'greetd.service')+ if target != 'graphical.target':+ self.run('/usr/bin/systemctl', '--no-reload', 'set-default', 'graphical.target')+ self.verify(state)+ state['phase'] = 'enabled'+ self.save(state)+ except BaseException:+ self.rollback(state)+ raise+ return 'Harness login is enabled for ' + user + ' on the next boot. The running session is unchanged.'++ def disable(self):+ state = self.load()+ if not state:+ return 'Harness login is not enabled by this setup.'+ self.verify(state, partial=state['phase'] != 'enabled')+ state['phase'] = 'disabling'+ self.save(state)+ self.rollback(state)+ return 'The previous login setup is restored for the next boot. The running session is unchanged.'++ def status(self):+ state = self.load()+ if not state:+ return 'Harness login is not enabled by this setup.'+ self.verify(state, partial=state['phase'] != 'enabled')+ return json.dumps({key: state[key] for key in ('phase', 'user', 'uid', 'previous_target')}, indent=2)+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ commands = parser.add_subparsers(dest='command', required=True)+ enable = commands.add_parser('enable', help='Enable next-boot login for an existing local account.')+ enable.add_argument('--user', required=True)+ enable.add_argument('--autologin', action='store_true', required=True,+ help='Deliberately allow this account to log in without a password at boot.')+ commands.add_parser('disable', help='Restore the previous login setup on the next boot.')+ commands.add_parser('status')+ args = parser.parse_args()+ if os.geteuid() != 0:+ parser.error('Run this setup through sudo.')+ setup = Setup()+ try:+ with setup.locked():+ print(setup.enable(args.user) if args.command == 'enable' else getattr(setup, args.command)())+ except (SetupError, OSError, ValueError, KeyError, subprocess.SubprocessError) as error:+ parser.exit(1, str(error) + '\n')+++if __name__ == '__main__':+ main()diff --git a/os/packaging/fedora/AGENTS.md b/os/packaging/fedora/AGENTS.mdindex 5c1d5708d..b9ef38576 100644--- a/os/packaging/fedora/AGENTS.md+++ b/os/packaging/fedora/AGENTS.md@@ -22,12 +22,19 @@ and running agents. Read `guide.md` and the shipped TUI reference before advisinlater session; they must not kill the running agents or enable a second updater.- `harness-session` starts the session explicitly from a logged-in local console.Installing the package does not create users, change passwords or enable- autologin. The full image's provisioning is a separate responsibility.+ autologin. The private `harness-session-setup enable --user USER --autologin`+ path explicitly selects an existing local account and Fedora's greetd/PAM+ login stack for the next boot. Read the setup section in `guide.md` first.+ Preserve its recovery receipt, existing account authentication and SELinux+ policy. `harness-session-setup disable` restores the previous login policy;+ disable before removing the session RPM. Never overwrite conflicting settings.## Network, tools and diagnosis- Fedora's NetworkManager owns networking. `hn-os wifi` opens the root-owned- network form through sudo; passwords stay in its masked input.+ network form through sudo; passwords stay in its masked input. Explicit login+ setup grants only that form's two exact commands to the selected user. Do not+ add a global wheel grant or arbitrary sudo/polkit permission.- PipeWire owns audio. Clipboard tools are `wl-copy` and `wl-paste`.- Chromium is optional and remains sandboxed. Install ordinary task dependenciesthrough Fedora's package manager; keep existing security policy enabled.diff --git a/os/packaging/fedora/guide.md b/os/packaging/fedora/guide.mdindex 5f6c7fc89..9325f56b1 100644--- a/os/packaging/fedora/guide.md+++ b/os/packaging/fedora/guide.md@@ -36,3 +36,50 @@ base system; do not describe a private VM as physically tested hardware support.Use `hn-browser URL` when a browser helps. Chromium is optional and sandboxed.Use `hn-os wifi` for networking and keep passwords in its masked form. Packageinstallation does not change accounts, start a session or replace system policy.++## Private Fedora login setup++This development path starts from an existing Fedora Asahi Remix Minimal install+made with [Asahi's installer](https://asahilinux.org/fedora/). It does not install+Fedora or establish physical Mac support. Fedora/Asahi continues to own the boot+chain, firmware, kernel, device trees, audio safety, base updates and recovery.+Keep macOS and Apple recovery available; do not use the PC installer on this path.++Install the verified private session RPM, then install Fedora's `greetd` package+with `sudo dnf install greetd`. Fedora supplies its PAM configuration and, on a+system with the targeted SELinux policy, its matching `greetd-selinux` dependency.+Keep those policies enabled and unchanged. Chromium and the default agent remain+separate prerequisites for their respective session features.++Choose an existing local account with a usable password and existing permission+to run setup through sudo. First verify its password login and sudo from another+console, such as Ctrl+Alt+F2. Then explicitly enable next-boot autologin:++```sh+sudo harness-session-setup enable --user EXISTING_USER --autologin+sudo harness-session-setup status+```++This allows console access to that account after Fedora boots. Existing disk+encryption remains separate. The command does not create users, change passwords,+edit home directories or shell profiles, or interrupt the current session. It+uses Fedora's greetd service, display-manager alias and graphical target. It+refuses conflicting login configuration and saves the previous target. The+initial login happens once per boot; signing out returns to password login.++The selected account receives permission for only the two fixed invocations of+the root-owned Harness Wi-Fi form, including first use. No other sudo permission,+NetworkManager setting, DNS policy or audio configuration is changed.++To restore the previous login setup, use an authenticated console:++```sh+sudo harness-session-setup disable+```++The change takes effect at the next boot. This also removes the selected account's+managed Wi-Fi permission. The package itself remains installed. Disable before+removing the session RPM. If setup was interrupted, the same command restores the+recorded state. If an administrator edited a managed file, setup preserves it and+stops; inspect the named file and `/var/lib/harness-os/session-setup.json` before+resolving the difference. Never discard that receipt to force a reconfiguration.diff --git a/os/packaging/fedora/harness-os-session.spec b/os/packaging/fedora/harness-os-session.specindex 56bfb40ce..a784d4510 100644--- a/os/packaging/fedora/harness-os-session.spec+++ b/os/packaging/fedora/harness-os-session.spec@@ -24,6 +24,8 @@ The minimal Harness OS session and verified native ARM runtime. This is acomponent for a future Fedora/Asahi Harness image. It does not provision accounts,start services, install a boot chain, or implement Fedora system recovery.Chromium and the image's default agent are supplied separately when needed.+The optional harness-session-setup command uses Fedora's separately installed+greetd package for explicit, reversible next-boot login with an existing account.%prep%setup -q -c -Tdiff --git a/os/tests/fedora_session_vm.py b/os/tests/fedora_session_vm.pynew file mode 100644index 000000000..5bc560fb7--- /dev/null+++ b/os/tests/fedora_session_vm.py@@ -0,0 +1,413 @@+#!/usr/bin/env python3+"""Exercise explicit Fedora login setup on a private, enforcing ARM VM clone.++The image/runtime producer remains separate from this setup/observer source.+Only the disposable guest is provisioned. Never use this fixture on hardware.+"""+import argparse+import hashlib+import json+from pathlib import Path+import shlex+import shutil+import subprocess+import tempfile+import time++from arm_boot import digest+from arm_session import ROOT, SessionVM, failure_evidence, fixture_identity+from session_vm import put+++PASSWORD = 'private-login-42' # Public fixture credential, never a person's password.+HELPER = ROOT / 'os/fedora_session.py'+PROTECTED = '''import hashlib,json,pathlib,sys+names=['/etc/passwd','/etc/shadow','/etc/group','/etc/gshadow','/etc/sudoers',+ '/etc/greetd/config.toml','/etc/pam.d/greetd','/etc/pam.d/greetd-greeter',+ '/etc/selinux/config','/etc/NetworkManager/conf.d','/etc/pipewire','/etc/wireplumber',+ '/etc/sudoers.d','/home/me/.bash_profile','/home/me/.bashrc','/home/me/.profile',+ '/home/me/projects/login-preservation/proof.txt']+excluded={'/etc/sudoers.d/harness-session-network'}+files={}+for name in ['/home/me','/home/me/projects','/home/me/.config','/home/me/.config/systemd',+ '/home/me/.config/systemd/user']:+ s=pathlib.Path(name).stat()+ files[name]={'mode':s.st_mode&0o7777,'uid':s.st_uid,'gid':s.st_gid}+for name in names:+ p=pathlib.Path(name)+ for item in sorted(p.rglob('*')) if p.is_dir() else [p]:+ if str(item) in excluded: continue+ if item.is_symlink(): files[str(item)]={'link':str(item.readlink())}+ elif item.is_file():+ s=item.stat()+ files[str(item)]={'sha256':hashlib.sha256(item.read_bytes()).hexdigest(),+ 'mode':s.st_mode&0o7777,'uid':s.st_uid,'gid':s.st_gid}+ elif not item.exists(): files[str(item)]={'absent':True}+record=pathlib.Path('/var/lib/harness-test/login-preserved.json')+if sys.argv[1]=='record': record.write_text(json.dumps(files,sort_keys=True)+'\\n')+else: assert files==json.loads(record.read_text()), 'An existing account/project/policy changed'+print(json.dumps(files,sort_keys=True))+'''++LOGIN_PROBE = '''import json,os,pathlib,re,subprocess+assert subprocess.check_output(['getenforce'],text=True).strip()=='Enforcing'+pid=int(subprocess.check_output(['pgrep','-u','1000','-x','labwc'],text=True).strip())+proc=pathlib.Path('/proc')/str(pid)+assert proc.stat().st_uid==1000+env=dict(entry.split('=',1) for entry in (proc/'environ').read_text().split('\\0') if '=' in entry)+assert env['XDG_RUNTIME_DIR']=='/run/user/1000'+assert env['DBUS_SESSION_BUS_ADDRESS']=='unix:path=/run/user/1000/bus'+assert env['XDG_SESSION_TYPE']=='wayland'+sid=re.search(r'session-([^/]+)\\.scope',(proc/'cgroup').read_text())[1]+properties=dict(line.split('=',1) for line in subprocess.check_output(+ ['loginctl','show-session',sid],text=True).splitlines() if '=' in line)+assert all(properties.get(k)==v for k,v in {'User':'1000','Name':'me','Service':'greetd',+ 'Seat':'seat0','VTNr':'1','Remote':'no','Class':'user'}.items()), properties+assert pathlib.Path('/run/user/1000/bus').is_socket()+result={'pid':pid,'session':sid,'properties':properties,'environment':{k:env[k] for k in+ ['XDG_RUNTIME_DIR','DBUS_SESSION_BUS_ADDRESS','XDG_SESSION_TYPE']},+ 'selinux_context':(proc/'attr/current').read_text().strip()}+pathlib.Path('/tmp/harness-login-probe.json').write_text(json.dumps(result,indent=2)+'\\n')+'''++HANDOFF_PROBE = '''import hashlib,json,os,pathlib,re,shlex,subprocess,sys+out=pathlib.Path('/var/lib/harness-test')+stage=sys.argv[1]+result={'processes':[], 'files':{}, 'process_tree':subprocess.check_output(+ ['ps','-eo','pid,ppid,uid,stat,comm'],text=True)}+for name in ['/usr/bin/hn','/usr/bin/hn-os','/usr/bin/harness','/usr/bin/opencode',+ '/usr/lib/harness/hn','/usr/lib/harness/harness-tui','/usr/lib/harness/cli.mjs',+ '/usr/lib/harness-os/onboarding.py','/usr/lib/harness-os/runtime-path',+ '/home/me/.local/state/harness-os/onboarded']:+ p=pathlib.Path(name)+ result['files'][name]={'exists':p.exists(),'resolved':str(p.resolve())}+ if p.is_file():+ result['files'][name].update(sha256=hashlib.sha256(p.read_bytes()).hexdigest(),uid=p.stat().st_uid)+for proc in pathlib.Path('/proc').iterdir():+ if not proc.name.isdigit(): continue+ try:+ argv=(proc/'cmdline').read_text().strip('\\0').split('\\0')+ if not any(arg in ['/usr/lib/harness-os/onboarding.py','/usr/lib/harness-os/network.py',+ '/usr/lib/harness/cli.mjs','/usr/lib/harness/hn','/usr/bin/opencode'] for arg in argv): continue+ env=dict(item.split('=',1) for item in (proc/'environ').read_text().split('\\0') if '=' in item)+ record={'pid':int(proc.name),'uid':proc.stat().st_uid,'argv':argv,'exe':str((proc/'exe').readlink()),+ 'stdin':str((proc/'fd/0').readlink()),'cgroup':(proc/'cgroup').read_text(),+ 'environment':{k:env[k] for k in ['HOME','PATH','TMUX','TMUX_PANE','HARNESS_TUI_BIN',+ 'HARNESS_CLI','HARNESS_CLI_ARGS','HARNESS_OS','XDG_RUNTIME_DIR'] if k in env}}+ result['processes'].append(record)+ if stage=='before' and '/usr/lib/harness-os/onboarding.py' in argv:+ assert record['uid']==1000 and re.fullmatch(r'%[0-9]+',env['TMUX_PANE'])+ socket=pathlib.Path(env['TMUX'].split(',')[0])+ assert socket.is_socket() and socket.stat().st_uid==1000+ output='/home/me/.local/state/harness-os/login-welcome-output.log'+ base=['runuser','-u','me','--','tmux','-S',str(socket)]+ pane=subprocess.check_output(base+['display-message','-p','-t',env['TMUX_PANE'],+ '#{pane_pid} #{pane_pipe}'],text=True).split()+ assert len(pane)==2 and pane[1]=='0', ('Unexpected first-use pane',pane)+ ancestors=[proc.name]+ while ancestors[-1]!=pane[0] and len(ancestors)<8:+ ancestors.append(re.search(r'^PPid:\\s+(\\d+)',+ (pathlib.Path('/proc')/ancestors[-1]/'status').read_text(),re.M)[1])+ assert ancestors[-1]==pane[0], ('First-use process is outside its tmux pane',ancestors,pane)+ exited='printf "%s\\\\n" "pane=#{pane_id} status=#{pane_dead_status} signal=#{pane_dead_signal}" > '+output+'.exit'+ subprocess.run(base+['set-hook','-p','-t',env['TMUX_PANE'],'pane-exited',+ 'run-shell '+shlex.quote(exited)],check=True,timeout=10)+ subprocess.run(base+['pipe-pane','-t',env['TMUX_PANE'],'cat > '+output],check=True,timeout=10)+ result['observed_pane']={'socket':str(socket),'pane':env['TMUX_PANE'],+ 'process_ancestry':ancestors,'output':output}+ except (FileNotFoundError,ProcessLookupError): pass+if stage=='before': assert 'observed_pane' in result, 'No exact first-use pane to observe'+exited=pathlib.Path('/home/me/.local/state/harness-os/login-welcome-output.log.exit')+result['pane_exit']=exited.read_text() if exited.exists() else None+(out/('handoff-'+stage+'.json')).write_text(json.dumps(result,indent=2)+'\\n')+'''+++def handoff_evidence(machine, stage):+ machine.command('python3 /usr/local/lib/harness-test/login-handoff.py ' + stage, timeout=30)+ (machine.folder / ('handoff-' + stage + '.json')).write_bytes(+ machine.read_file('/var/lib/harness-test/handoff-' + stage + '.json'))+ if stage != 'before':+ (machine.folder / 'welcome-output.log').write_bytes(+ machine.read_file('/home/me/.local/state/harness-os/login-welcome-output.log'))+++def home_directory_evidence(machine, name, require_owned=False):+ paths = '/home/me /home/me/projects /home/me/.config /home/me/.config/systemd /home/me/.config/systemd/user'+ text, _ = machine.command("stat -c '%n uid=%u gid=%g mode=%a type=%F' " + paths ++ '; ls -Zd ' + paths, check=False)+ (machine.folder / (name + '-home-directories.txt')).write_text(text)+ if require_owned:+ machine.user('for p in ' + paths + '; do test -O "$p" && test -w "$p" || exit 1; done')+++def wait_root(machine, condition, seconds=30):+ machine.command('for n in $(seq 1 ' + str(seconds * 2) + '); do if ' + condition ++ '; then exit 0; fi; sleep .5; done; exit 1', timeout=seconds + 10)+++def typed(machine, command):+ machine.type_probe(command)+ machine.keys('ret')+++def console_login(machine, tty, name, wrong=False, graphical=False):+ machine.keys('ctrl', 'alt', 'f' + str(tty))+ machine.frame(name + '-login', 'login:')+ typed(machine, 'me')+ machine.frame(name + '-password', 'password:')+ if wrong:+ typed(machine, 'incorrect-fixture-password')+ machine.frame(name + '-rejected', 'incorrect', 30)+ # Both login(1) and agreety return to the username prompt after failure.+ machine.frame(name + '-retry', 'login:')+ typed(machine, 'me')+ machine.frame(name + '-retry-password', 'password:')+ typed(machine, PASSWORD)+ if not graphical:+ machine.frame(name + '-shell', 'me@harness')+ marker = '/tmp/' + name + '-authenticated'+ typed(machine, 'touch ' + marker)+ wait_root(machine, 'test -f ' + marker + ' && test "$(stat -c %u ' + marker + ')" = 1000')+++def sudo_setup(machine, action):+ typed(machine, 'sudo -k')+ command = 'sudo harness-session-setup ' + action+ if action == 'enable':+ command += ' --user me --autologin'+ typed(machine, command)+ machine.frame(action + '-sudo-authentication', 'password for me')+ typed(machine, PASSWORD)+ condition = ('grep -q ' + shlex.quote('"phase": "enabled"') + ' /var/lib/harness-os/session-setup.json'+ if action == 'enable' else 'test ! -e /var/lib/harness-os/session-setup.json')+ wait_root(machine, condition)+ machine.frame(action + '-complete', 'next boot')+++def inventory(machine, destination):+ machine.command("rpm -qa --qf '%{NAME}\\t%{VERSION}-%{RELEASE}\\t%{ARCH}\\t%{SIZE}\\n' | sort > " + destination)+ return machine.read_file(destination).decode()+++def diagnostics(machine, name):+ if not machine:+ return+ try:+ text, _ = machine.command('getenforce; systemctl status greetd getty@tty1 getty@tty2 --no-pager; '+ 'loginctl list-sessions; ls -lZ /etc/greetd /etc/sudoers.d; '+ 'journalctl -b -u greetd -u getty@tty1 -u getty@tty2 --no-pager; '+ 'journalctl -b _UID=1000 --no-pager; '+ 'journalctl -b -k --no-pager | tail -n 160', timeout=30, check=False)+ (machine.folder / (name + '-login-diagnostics.txt')).write_text(text)+ except (OSError, RuntimeError, TimeoutError) as error:+ (machine.folder / (name + '-diagnostic-error.txt')).write_text(str(error))+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--fixture', type=Path, required=True)+ parser.add_argument('--fixture-source', required=True)+ parser.add_argument('--output', type=Path, required=True)+ args = parser.parse_args()+ source = subprocess.check_output(['git', '-C', str(ROOT), 'rev-parse', 'HEAD'], text=True).strip()+ if subprocess.check_output(['git', '-C', str(ROOT), 'status', '--porcelain'], text=True).strip():+ parser.error('Commit the exact setup/observer source before native acceptance.')+ fixture = args.fixture.resolve()+ image = fixture_identity(fixture, args.fixture_source)+ output = args.output.resolve()+ output.mkdir(parents=True, exist_ok=False)+ if shutil.disk_usage(output).free < image['raw_disk']['bytes'] + 2 * 1024**3:+ parser.error('Keep at least the private disk size plus 2 GiB free before this VM.')+ result = {'status': 'running', 'started_at': time.time(), 'test_source_commit': source,+ 'image_source_commit': args.fixture_source, 'runtime': image['package']['runtime'],+ 'image_manifest_sha256': digest(fixture / 'manifest.json'),+ 'helper_sha256': digest(HELPER), 'scope': 'Explicit Fedora login setup on enforcing 16 KiB ARM VM',+ 'checks': [], 'normalization': [], 'boots': [],+ 'limitations': ['Private fixture and public test credential; never install or publish this disk',+ 'Candidate setup helper is overlaid; the immutable RPM/runtime producer remains separate',+ 'No Apple boot/firmware/graphics/audio, physical installation or base-update/recovery acceptance']}+ machine = None+ with tempfile.TemporaryDirectory(prefix='harness-fedora-login-') as temporary:+ disk = Path(temporary) / 'guest.raw'+ try:+ subprocess.run(['zstd', '-d', '--sparse', str(fixture / 'guest.raw.zst'), '-o', str(disk)],+ check=True, timeout=180)+ assert disk.stat().st_size == image['raw_disk']['bytes'] and digest(disk) == image['raw_disk']['sha256']++ def boot(name, offline=False, allow_relabel=False):+ nonlocal machine+ if machine:+ diagnostics(machine, 'completed')+ result['boots'][-1]['shutdown'] = machine.poweroff()+ machine.close()+ machine = SessionVM(output / name, disk, fixture / 'Image')+ result['boots'].append({'name': name, 'started_at': time.time()})+ try:+ machine.start(offline=offline)+ except RuntimeError:+ # Fedora's initial policy install requests one full relabel+ # and reboot before a login console can become available.+ # QEMU -no-reboot exits for that request; retain and verify+ # the actual guest reset before starting the next cold boot.+ serial = (machine.folder / 'serial.log').read_text(errors='replace')+ if (not allow_relabel or 'selinux-autorelabel.service' not in serial or+ 'Relabeling / ' not in serial or 'reboot: Restarting system' not in serial):+ raise+ exit_code = machine.process.wait(timeout=15)+ events = []+ while line := machine.qmp_file.readline():+ events.append(json.loads(line))+ assert exit_code == 0 and any(event.get('event') == 'SHUTDOWN' and+ event.get('data', {}).get('guest') is True and+ event['data'].get('reason') == 'guest-reset' for event in events), 'Missing completed Fedora relabel reboot'+ result['boots'][-1]['relabel_reboot'] = {'exit_code': exit_code, 'events': events}+ (machine.folder / 'relabel-reboot.json').write_text(json.dumps(result['boots'][-1], indent=2) + '\n')+ machine.close()+ machine = SessionVM(output / (name + '-after-relabel'), disk, fixture / 'Image')+ result['boots'].append({'name': name + '-after-relabel', 'started_at': time.time()})+ machine.start(offline=offline) # A second relabel/reboot is a failure.+ result['boots'][-1]['accelerator'] = machine.accelerator++ boot('01-private-normalization', offline=True)+ # Stop only this fixture's passwordless login before enabling its NIC.+ machine.command('systemctl stop [email protected]; loginctl terminate-user me', check=False)+ wait_root(machine, '! pgrep -u 1000 -x labwc >/dev/null')+ machine.monitor('set_link', name='hnnet', up=True)+ wait_root(machine, 'nmcli -t -f STATE general | grep -qx connected', 60)+ package_before = inventory(machine, '/tmp/packages-before.tsv')+ manager = 'manager=$(command -v dnf5 || command -v microdnf); "$manager"'+ text, _ = machine.command(manager + ' install -y --setopt=install_weak_deps=False --setopt=gpgcheck=True '+ 'selinux-policy-targeted policycoreutils libselinux-utils', timeout=600)+ (output / 'normalization-policy-install.log').write_text(text)+ policy_before = inventory(machine, '/tmp/packages-policy.tsv')+ text, _ = machine.command(manager + ' install -y --setopt=install_weak_deps=False --setopt=gpgcheck=True greetd', timeout=600)+ (output / 'greetd-install.log').write_text(text)+ package_after = inventory(machine, '/tmp/packages-after.tsv')+ for name, data in [('before', package_before), ('policy', policy_before), ('after', package_after)]:+ (output / ('packages-' + name + '.tsv')).write_text(data)+ prior = {line.split('\t')[0]: line for line in policy_before.splitlines()}+ added = [line for line in package_after.splitlines() if line.split('\t')[0] not in prior]+ result['greetd_transaction'] = {'added_packages': added,+ 'installed_bytes': sum(int(line.split('\t')[3]) for line in added)}+ machine.command('rpm -V greetd && rpm -q greetd-selinux && test -f /etc/selinux/targeted/contexts/files/file_contexts')+ # Verify the known fixture before removing just its private shortcuts.+ for local, guest in [('os/root/etc/profile.d/harness-os.sh', '/etc/profile.d/harness-os.sh'),+ ('os/root/etc/sudoers.d/20-harness-network', '/etc/sudoers.d/20-harness-network')]:+ expected = subprocess.check_output(['git', '-C', str(ROOT), 'show', args.fixture_source + ':' + local])+ assert machine.read_file(guest) == expected, 'Private fixture source changed: ' + guest+ machine.command('rm -- ' + shlex.quote(guest))+ autologin = '/etc/systemd/system/[email protected]/autologin.conf'+ expected = ('[Service]\nExecStart=\nExecStart=-/sbin/agetty --autologin me --noclear %I $TERM\n').encode()+ assert machine.read_file(autologin) == expected+ machine.command('rm -- ' + autologin)+ machine.command('printf %s ' + shlex.quote('me:' + PASSWORD + '\n') + ' | chpasswd')+ machine.command('test ! -e /home/me/.local/state/harness-os/onboarded')+ home_directory_evidence(machine, 'before-fixture')+ # Root install -d assigns only its leaf ownership: intermediate+ # .config can become root-owned and break the real first-use agent.+ # All private home fixtures must be created by the existing user.+ machine.user('mkdir -p ~/projects/login-preservation ~/.config/systemd/user && '+ 'ln -s /dev/null ~/.config/systemd/user/harness-update.timer && '+ 'printf %s existing-private-project > ~/projects/login-preservation/proof.txt')+ home_directory_evidence(machine, 'after-fixture', require_owned=True)+ put(machine, '/usr/lib/harness-os/fedora_session.py', HELPER.read_text())+ put(machine, '/usr/local/lib/harness-test/login-protected.py', PROTECTED)+ put(machine, '/usr/local/lib/harness-test/login-handoff.py', HANDOFF_PROBE)+ machine.command('install -d /var/lib/harness-test')+ machine.command('chmod 755 /usr/lib/harness-os/fedora_session.py && '+ 'ln -s ../lib/harness-os/fedora_session.py /usr/bin/harness-session-setup')+ assert hashlib.sha256(machine.read_file('/usr/lib/harness-os/fedora_session.py')).hexdigest() == result['helper_sha256']+ # Label the private ext4 root even if its container base had no active LSM.+ machine.command('test "$(sed -n \'s/^SELINUX=//p\' /etc/selinux/config)" = enforcing && '+ 'setfiles -F -e /proc -e /sys -e /dev -e /run '+ '/etc/selinux/targeted/contexts/files/file_contexts /', timeout=300)+ result['normalization'] = ['Installed signed Fedora targeted policy/tools and greetd; package deltas retained',+ 'Removed only source-verified private profile, tty1 autologin and global-wheel network grant',+ 'Assigned existing private me account a test password; masked only its update timer',+ 'Added preservation project and exact-source helper/symlink; labeled only the private ext4 root']++ boot('02-enforcing-console', allow_relabel=True)+ machine.command('test "$(getenforce)" = Enforcing && test "$(systemctl get-default)" = multi-user.target && '+ '! systemctl is-active --quiet greetd && ! pgrep -u 1000 -x labwc >/dev/null')+ home_directory_evidence(machine, 'enforcing', require_owned=True)+ console_login(machine, 1, 'baseline-console')+ machine.command('python3 /usr/local/lib/harness-test/login-protected.py record')+ (output / 'protected-baseline.json').write_bytes(machine.read_file('/var/lib/harness-test/login-preserved.json'))+ sudo_setup(machine, 'enable')+ machine.command('python3 /usr/local/lib/harness-test/login-protected.py compare && '+ '! systemctl is-active --quiet greetd && ! pgrep -u 1000 -x labwc >/dev/null')+ result['setup_receipt'] = json.loads(machine.read_file('/var/lib/harness-os/session-setup.json'))+ result['checks'].append('An actual password console and sudo enable setup without starting a session or changing existing account/project/platform policy')++ boot('03-enforcing-harness', offline=True)+ machine.wait_user('systemctl --user is-active --quiet hn-screen && hn capture-pane -p | grep -q "Connect to Wi-Fi"', 150)+ machine.frame('01-passwordless-wifi', 'Connect to Wi-Fi', absent=['password for me'])+ put(machine, '/tmp/harness-login-probe.py', LOGIN_PROBE)+ machine.command('python3 /tmp/harness-login-probe.py && pgrep -u 0 -f "^/usr/bin/python3 /usr/lib/harness-os/network.py --first-use$"')+ result['login'] = json.loads(machine.read_file('/tmp/harness-login-probe.json'))+ machine.keyboard('login-offline')+ machine.user('sudo -K')+ text, status = machine.user('sudo -n /usr/bin/true', check=False)+ assert status != 0 and 'password' in text.lower(), 'Setup granted unrelated passwordless sudo'+ text, status = machine.user('sudo -n /usr/bin/python3 /usr/lib/harness-os/network.py --unexpected', check=False)+ assert status != 0 and 'password' in text.lower(), 'Network rule accepted extra arguments'+ handoff_evidence(machine, 'before')+ machine.monitor('set_link', name='hnnet', up=True)+ try:+ machine.wait_user('test -f ~/.local/state/harness-os/onboarded && pgrep -u 1000 -x opencode >/dev/null', 150)+ finally:+ handoff_evidence(machine, 'after')+ machine.frame('02-connected-workspace', ['OpenCode', 'Ask anything'], 90)+ machine.keys('meta_l', 'w')+ machine.frame('03-wifi-form', 'Wi-Fi', absent=['password for me'])+ wait_root(machine, 'pgrep -u 0 -f "^/usr/bin/python3 /usr/lib/harness-os/network.py$" >/dev/null')+ machine.keys('esc')+ result['checks'].append('Enforcing greetd/PAM login creates the correct seat/user bus; offline first-use and regular Wi-Fi form run passwordlessly only through the exact selected-user rules; configured link reaches the workspace')++ console_login(machine, 2, 'recovery-console', wrong=True)+ machine.keys('ctrl', 'alt', 'f1')+ machine.command('loginctl terminate-session ' + shlex.quote(result['login']['session']))+ console_login(machine, 1, 'greetd-fallback', wrong=True, graphical=True)+ machine.wait_user('systemctl --user is-active --quiet hn-screen', 90)+ machine.command('python3 /tmp/harness-login-probe.py')+ machine.keyboard('after-authentication')+ result['checks'].append('tty2 password recovery and greetd logout fallback both reject a wrong password and accept the existing account password using QMP virtual keyboard input')+ machine.command('pgrep -u 1000 -x labwc > /tmp/harness-login-compositor-before')+ before = machine.read_file('/tmp/harness-login-compositor-before')+ machine.keys('ctrl', 'alt', 'f2')+ sudo_setup(machine, 'disable')+ machine.command('pgrep -u 1000 -x labwc > /tmp/harness-login-compositor-after')+ assert before == machine.read_file('/tmp/harness-login-compositor-after'), 'Disable interrupted the graphical session'+ machine.command('python3 /usr/local/lib/harness-test/login-protected.py compare && '+ 'test "$(systemctl get-default)" = multi-user.target && '+ 'test ! -e /etc/sudoers.d/harness-session-network && test ! -e /etc/greetd/harness.toml')+ machine.keys('ctrl', 'alt', 'f1')+ machine.keyboard('after-disable')+ result['checks'].append('Authenticated disable restores exact prior policy and target while the running graphical session still accepts keyboard input')++ boot('04-restored-console')+ machine.command('test "$(getenforce)" = Enforcing && test "$(systemctl get-default)" = multi-user.target && '+ '! systemctl is-active --quiet greetd && ! pgrep -u 1000 -x labwc >/dev/null && '+ 'python3 /usr/local/lib/harness-test/login-protected.py compare && rpm -V harness-os-session')+ console_login(machine, 1, 'restored-console')+ runtime = json.loads(machine.read_file('/usr/share/harness-os/runtime.json'))+ assert runtime == image['package']['runtime'], 'Setup changed the immutable runtime provenance'+ result['checks'].append('Final cold boot returns to enforcing Fedora password console with existing account/project and packaged runtime unchanged')+ diagnostics(machine, 'completed')+ result['boots'][-1]['shutdown'] = machine.poweroff()+ result['status'] = 'passed'+ except BaseException as error:+ result.update(status='failed', error=str(error))+ diagnostics(machine, 'failure')+ failure_evidence(machine)+ raise+ finally:+ if machine:+ machine.close()+ result['finished_at'] = time.time()+ (output / 'receipt.json').write_text(json.dumps(result, indent=2) + '\n')+++if __name__ == '__main__':+ main()diff --git a/os/tests/test_fedora_package.py b/os/tests/test_fedora_package.pyindex db70d1ef1..3d3606aea 100644--- a/os/tests/test_fedora_package.py+++ b/os/tests/test_fedora_package.py@@ -65,6 +65,8 @@ class FedoraPayload(unittest.TestCase):self.assertIn('usr/lib/harness-os/live_update.py', result['files'])self.assertIn('usr/lib/systemd/user/harness-update.timer', result['files'])self.assertEqual(result['symlinks']['usr/bin/harness-session'], '../lib/harness-os/session')+ self.assertEqual(result['symlinks']['usr/bin/harness-session-setup'], '../lib/harness-os/fedora_session.py')+ self.assertIn('usr/lib/harness-os/fedora_session.py', result['files'])self.assertIn('W-u', (destination / 'usr/share/harness-os/labwc/rc.xml').read_text())self.assertNotIn('W-i', (destination / 'usr/share/harness-os/labwc/rc.xml').read_text())self.assertNotIn('harness-install', (destination / 'usr/lib/systemd/user/harness-os.target').read_text())diff --git a/os/tests/test_fedora_session.py b/os/tests/test_fedora_session.pynew file mode 100644index 000000000..1e81cf97a--- /dev/null+++ b/os/tests/test_fedora_session.py@@ -0,0 +1,257 @@+"""Portable setup transaction checks; real Fedora PAM/login belongs to the VM."""+import importlib.util+import errno+import json+import os+from pathlib import Path+import subprocess+import sys+import tempfile+import unittest+from unittest.mock import patch++SOURCE = Path(__file__).resolve().parents[1] / 'fedora_session.py'+spec = importlib.util.spec_from_file_location('fedora_session', SOURCE)+session = importlib.util.module_from_spec(spec)+spec.loader.exec_module(session)+++class Fixture(session.Setup):+ """Only emulate external Fedora tools; exercise all actual file operations."""+ def __init__(self, root):+ super().__init__(root)+ self.commands = []+ self.fail = None+ self.default = 'multi-user.target'++ def run(self, *command, check=True):+ self.commands.append(command)+ if self.fail and self.fail in command:+ raise session.SetupError('Injected external command failure: ' + self.fail)+ if 'visudo' in command[0] and '-f' in command:+ text = Path(command[-1]).read_text()+ assert text == self.plan('owner', None, 'multi-user.target')[session.SUDOERS]['after']['text']+ if command[0].endswith('systemctl'):+ if 'is-active' in command:+ return 'inactive'+ if 'is-enabled' in command:+ return ('enabled' if command[-1] == 'greetd.service' and+ self.snapshot(session.ALIAS) == session.link('/usr/lib/systemd/system/greetd.service')+ else 'disabled')+ if 'get-default' in command:+ return self.default+ if 'enable' in command:+ if not self.path(session.ALIAS).is_symlink():+ self.path(session.ALIAS).symlink_to('/usr/lib/systemd/system/greetd.service')+ if 'set-default' in command:+ path = self.path(session.TARGET)+ if path.is_symlink():+ path.unlink()+ path.symlink_to('/usr/lib/systemd/system/graphical.target')+ return ''+++class FedoraSession(unittest.TestCase):+ def setUp(self):+ temporary = tempfile.TemporaryDirectory()+ self.addCleanup(temporary.cleanup)+ self.root = Path(temporary.name)+ self.setup = Fixture(self.root)+ self.uid = os.geteuid() or 1000+ self.put('etc/os-release', 'ID=fedora\n')+ self.put('usr/share/harness-os/runtime.json', '{"system_profile":"fedora"}\n')+ self.put('etc/passwd', f'root:x:0:0:root:/root:/bin/bash\nowner:x:{self.uid}:1000:Owner:/home/owner:/bin/bash\n')+ self.put('etc/shadow', 'owner:$6$fixture$existing-password-hash:20000:0:99999:7:::\n', 0o600)+ self.put('etc/login.defs', 'UID_MIN 100\n')+ self.put('etc/shells', '/bin/bash\n')+ self.put('etc/greetd/config.toml', '# Fedora vendor config remains byte-for-byte intact\n')+ self.put('etc/pam.d/greetd', 'session include system-auth\n')+ self.put('etc/sudoers.d/existing', '# Existing administrative policy\n', 0o440)+ self.put('usr/lib/systemd/system/greetd.service', '[Unit]\[email protected]\n[Install]\nAlias=display-manager.service\n')+ for name in ('usr/bin/greetd', 'usr/bin/agreety', 'usr/bin/harness-session', 'usr/sbin/visudo', 'bin/bash'):+ self.put(name, '#!/bin/sh\nexit 0\n', 0o755)+ self.put('home/owner/.profile', 'export EXISTING=keep\n')+ self.put('home/owner/projects/project.py', 'print("existing project")\n')+ if os.geteuid() == 0:+ os.chown(self.root / 'home/owner', self.uid, 1000)+ (self.root / 'etc/systemd/system').mkdir(parents=True)+ (self.root / 'var/lib').mkdir(parents=True)+ (self.root / 'run').mkdir()+ self.setup.path(session.TARGET).symlink_to('/usr/lib/systemd/system/multi-user.target')+ self.protected = self.snapshot_protected()+ patcher = patch.object(session.platform, 'machine', return_value='aarch64')+ patcher.start()+ self.addCleanup(patcher.stop)++ def put(self, name, text, mode=0o644):+ path = self.root / name+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(text)+ path.chmod(mode)++ def snapshot_protected(self):+ return {name: (self.root / name).read_bytes() for name in (+ 'etc/passwd', 'etc/shadow', 'etc/pam.d/greetd', 'etc/greetd/config.toml',+ 'etc/sudoers.d/existing', 'home/owner/.profile', 'home/owner/projects/project.py')}++ def assert_original(self):+ self.assertEqual(self.setup.snapshot(session.TARGET), session.link('/usr/lib/systemd/system/multi-user.target'))+ self.assertFalse(self.setup.path(session.STATE).exists())+ for name in session.PATHS[:-1]:+ self.assertIsNone(self.setup.snapshot(name))+ self.assertEqual(self.snapshot_protected(), self.protected)++ def test_enable_disable_restores_exact_state_without_starting_services(self):+ self.setup.enable('owner')+ state = self.setup.load()+ self.assertEqual(state['phase'], 'enabled')+ self.assertEqual(state['uid'], self.uid)+ self.assertEqual(self.snapshot_protected(), self.protected)+ self.assertEqual(self.setup.snapshot(session.SUDOERS)['mode'], 0o440)+ self.assertEqual(self.setup.snapshot(session.TARGET), session.link('/usr/lib/systemd/system/graphical.target'))+ self.assertIn('source_profile = false', self.setup.path(session.CONFIG).read_text())+ self.assertIn(('/usr/bin/systemctl', '--no-reload', 'enable', 'greetd.service'), self.setup.commands)+ self.assertIn(('/usr/bin/systemctl', '--no-reload', 'set-default', 'graphical.target'), self.setup.commands)+ self.assertFalse(any(word in {'start', 'stop', 'restart', 'isolate'} for cmd in self.setup.commands for word in cmd))+ self.setup.disable()+ self.assert_original()++ def test_idempotent_enable_checks_identity_and_does_not_rewrite(self):+ self.setup.enable('owner')+ before = {name: self.setup.path(name).lstat().st_mtime_ns for name in session.PATHS}+ self.assertIn('already enabled', self.setup.enable('owner'))+ self.assertEqual(before, {name: self.setup.path(name).lstat().st_mtime_ns for name in session.PATHS})+ with self.assertRaisesRegex(session.SetupError, 'different account'):+ self.setup.enable('another')+ self.setup.disable()+ self.assertIn('not enabled', self.setup.disable())++ def test_existing_graphical_default_is_not_rewritten(self):+ self.setup.default = 'graphical.target'+ self.setup.path(session.TARGET).unlink()+ # With no /etc override, Fedora owns the vendor default target.+ self.setup.enable('owner')+ self.assertIsNone(self.setup.snapshot(session.TARGET))+ self.assertFalse(any('set-default' in command for command in self.setup.commands))+ self.setup.disable()+ self.assertIsNone(self.setup.snapshot(session.TARGET))++ def test_pristine_vendor_preset_alias_survives_enable_and_disable(self):+ previous = session.link('/usr/lib/systemd/system/greetd.service')+ self.setup.path(session.ALIAS).symlink_to(previous['target'])+ self.setup.enable('owner')+ self.assertEqual(self.setup.load()['files'][session.ALIAS], {'before': previous, 'after': previous})+ self.setup.disable()+ self.assertEqual(self.setup.snapshot(session.ALIAS), previous)+ self.setup.path(session.ALIAS).unlink()+ self.assert_original()++ def test_missing_autologin_flag_is_rejected_before_host_access(self):+ result = subprocess.run([sys.executable, str(SOURCE), 'enable', '--user', 'owner'], capture_output=True, text=True)+ self.assertEqual(result.returncode, 2)+ self.assertIn('--autologin', result.stderr)++ def test_accounts_need_recovery_authentication_and_existing_sudo(self):+ for user in ('root', 'missing', 'owner,ALL', 'owner\nroot'):+ with self.subTest(user=user), self.assertRaises(session.SetupError):+ self.setup.enable(user)+ self.assert_original()+ for password in ('', '!', '*', '!$6$locked$existing-password-hash', 'x'):+ self.put('etc/shadow', f'owner:{password}:20000:0:99999:7:::\n', 0o600)+ with self.subTest(password=password), self.assertRaisesRegex(session.SetupError, 'password'):+ self.setup.enable('owner')+ self.assertFalse(self.setup.path(session.STATE).exists())+ self.put('etc/shadow', self.protected['etc/shadow'].decode(), 0o600)+ self.setup.fail = 'disable'+ with self.assertRaisesRegex(session.SetupError, 'external command failure'):+ self.setup.enable('owner')+ self.assert_original()++ def test_conflicting_configuration_is_never_overwritten(self):+ for name in (session.CONFIG, session.DROPIN, session.SUDOERS, session.ALIAS):+ self.put(name, 'existing admin configuration\n')+ with self.subTest(path=name), self.assertRaises(session.SetupError):+ self.setup.enable('owner')+ self.assertEqual(self.setup.path(name).read_text(), 'existing admin configuration\n')+ self.setup.path(name).unlink()+ self.assert_original()++ def test_foreign_service_install_policy_is_rejected_before_changes(self):+ self.put('usr/lib/systemd/system/greetd.service', '[Install]\nAlias=display-manager.service\nWantedBy=another.target\n')+ with self.assertRaisesRegex(session.SetupError, 'enablement policy differs'):+ self.setup.enable('owner')+ self.assert_original()++ def test_tampering_refuses_disable_before_any_managed_file_changes(self):+ self.setup.enable('owner')+ self.setup.path(session.SUDOERS).chmod(0o640)+ self.setup.path(session.SUDOERS).write_text('# administrator edited this policy\n')+ self.setup.path(session.SUDOERS).chmod(0o440)+ before = {name: self.setup.snapshot(name) for name in session.PATHS}+ with self.assertRaisesRegex(session.SetupError, 'configuration changed'):+ self.setup.disable()+ self.assertEqual(before, {name: self.setup.snapshot(name) for name in session.PATHS})+ self.assertEqual(self.setup.load()['phase'], 'enabled')++ def test_failure_validating_rule_or_enabling_login_rolls_back(self):+ for failing in ('-f', 'enable', 'set-default'):+ self.setup.fail = failing+ with self.subTest(failing=failing), self.assertRaisesRegex(session.SetupError, 'external command failure'):+ self.setup.enable('owner')+ self.assert_original()++ def test_no_space_committing_configuration_restores_prior_files(self):+ original_link = os.link+ def no_space(source, destination, **kwargs):+ if destination == self.setup.path(session.SUDOERS):+ raise OSError(errno.ENOSPC, 'No space left on device')+ return original_link(source, destination, **kwargs)+ with patch.object(session.os, 'link', side_effect=no_space):+ with self.assertRaises(OSError) as failure:+ self.setup.enable('owner')+ self.assertEqual(failure.exception.errno, errno.ENOSPC)+ self.assert_original()++ def test_interrupted_enable_and_disable_are_recoverable(self):+ self.setup.enable('owner')+ state = self.setup.load()+ state['phase'] = 'enabling'+ self.setup.save(state)+ self.setup.path(session.SUDOERS).unlink()+ self.setup.path(session.TARGET).unlink()+ with self.assertRaisesRegex(session.SetupError, 'interrupted'):+ self.setup.enable('owner')+ self.setup.disable()+ self.assert_original()+ self.setup.enable('owner')+ state = self.setup.load()+ state['phase'] = 'disabling'+ self.setup.save(state)+ self.setup.path(session.ALIAS).unlink()+ self.setup.disable()+ self.assert_original()++ def test_symlink_configuration_directory_and_receipt_are_refused(self):+ redirected = self.root / 'redirected'+ redirected.mkdir()+ directory = self.root / 'etc/systemd/system/greetd.service.d'+ directory.symlink_to(redirected)+ with self.assertRaisesRegex(session.SetupError, 'symlink configuration directory'):+ self.setup.enable('owner')+ self.assertEqual(list(redirected.iterdir()), [])+ directory.unlink()+ self.setup.path(session.STATE).parent.mkdir()+ self.setup.path(session.STATE).symlink_to(self.root / 'etc/shadow')+ with self.assertRaisesRegex(session.SetupError, 'private regular file'):+ self.setup.disable()+ self.assertEqual(self.snapshot_protected(), self.protected)++ def test_concurrent_setup_cannot_write_over_receipt(self):+ with self.setup.locked():+ with self.assertRaisesRegex(session.SetupError, 'Another session setup'):+ with self.setup.locked():+ self.fail('second setup acquired lock')+++if __name__ == '__main__':+ unittest.main()diff --git a/os/tools/fedora_payload.py b/os/tools/fedora_payload.pyindex c64531a2a..20d07f4df 100644--- a/os/tools/fedora_payload.py+++ b/os/tools/fedora_payload.py@@ -1,7 +1,7 @@"""The Fedora session payload, shared by RPM packaging and private VM checks.-This is one component of a future Harness OS image. Account setup, platform-packages, boot, networking policy and base-system recovery belong to that image.+This is one component of a future Harness OS image. Platform packages, boot and+base-system recovery belong to Fedora/Asahi. Login setup is a separate opt-in."""import hashlibimport json@@ -61,7 +61,7 @@ def stage(source, runtime, destination, commit, runtime_commit):shutil.copyfile(source / 'os/root' / name, target)for local, name in [*[('os/' + name + '.py', 'usr/lib/harness-os/' + name + '.py') for name in- ['onboarding', 'network', 'projects', 'hardware', 'live_update']],+ ['onboarding', 'network', 'projects', 'hardware', 'live_update', 'fedora_session']],('os/tools/hn-os', 'usr/bin/hn-os'),('tui/README.md', 'usr/share/harness-os/guide/tui.md'),('docs/naming-system.md', 'usr/share/harness-os/guide/naming.md'),@@ -78,6 +78,7 @@ def stage(source, runtime, destination, commit, runtime_commit):shutil.copyfile(runtime / local, library / target)(library / 'hn').symlink_to('harness-tui')(destination / 'usr/bin/harness-session').symlink_to('../lib/harness-os/session')+ (destination / 'usr/bin/harness-session-setup').symlink_to('../lib/harness-os/fedora_session.py')info.update(system_profile='fedora', package_source_commit=commit,files={p.name: {'bytes': p.stat().st_size, 'sha256': digest(p)}for p in library.iterdir() if not p.is_symlink()})