carlos / platform Public

scripts: chrony converge script for fixed boxes (G3 decision 5)

claude agent, operated by paul@keymail.dev ac7f2450fd383fe15f19f39bdcc62fadf1d33066 parent ae923d1
3 files changed, +328 −0
  • docs/region-ha-runbook.md +19 −0
  • scripts/region-ha-g3/chrony-fixed-box.sh +93 −0
  • scripts/region_ha_g3_chrony_test.py +216 −0

Intent

Human

<task-notification> <task-id>b3x86nmi6</task-id> <tool-use-id>toolu_018hr2PGFEhppqnRZ7iSoY2a</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/dc71bafb-7376-4e4b-a855-4d32f1eed771/tasks/b3x86nmi6.output</output-file> <status>completed</status> <summary>Background command "Wait for Task 3 fix round" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>a59a5ff0377ab3816</task-id> <tool-use-id>toolu_01WCZH2WY5PmQJHjWJNj6sSa</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/dc71bafb-7376-4e4b-a855-4d32f1eed771/tasks/a59a5ff0377ab3816.output</output-file> <status>completed</status> <summary>Agent "Opus task review of T3b" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Minor 1 (untested memwatch suspects wiring) is **ADDRESSED**. Deleting the wiring would now fail a test that runs in CI. - The wiring is now one line inside `admissionMetricsFromEnv` (group_metrics.go:61). It sits in the `a.group` branch after the empty-group check, so it is still group-only. `memwatchLoop` gets it through its existing constructor call, and the inline closure is gone. - If that line is deleted, `TestGroupMetricSuspectWiring` (internal/host/suspects_test.go) fails. `internal/host` runs under `go test ./...` in CI. The fix report shows this mutation failing. - The test drives a real `ExecBackend` through two refusals 11 minutes apart on a simulated clock, against a local stub server. It checks a count of 0 with no backend, 1 with the backend set, and 0 after clearing it. It also checks that a fixed box gets no callback. - No new Critical or Important issues in the fix diff. I re-ran nothing; this verdict comes from reading the diff and the fix report. I added a "Fix round 1" section to `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-g2-prep/.superpowers/sdd/2026-11-05-region-ha-g2-prep/task-3-review.md`.</result> <usage><subagent_tokens>150459</subagent_tokens><tool_uses>4</tool_uses><duration_ms>27271</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>a2c62c5a6a50042fb</task-id> <tool-use-id>toolu_01J6EoFE77F9zjTkFEaEqruR</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/dc71bafb-7376-4e4b-a855-4d32f1eed771/tasks/a2c62c5a6a50042fb.output</output-file> <status>completed</status> <summary>Agent "Census review region-ha-g2-t3" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>| unit-or-envelope | verdict | reason | |---|---|---| | `infra/modules/region-host/group_alarms.tf` `external` | APPROVE | It adds one group-only CloudWatch alarm on the existing ASG dimension that notifies the existing regional SNS topic. There are no IAM, queue, scaling or instance changes, which fits the recorded notification-only basis (group_alarms.tf:128-144). | | `infra/modules/region-host/tests/group_alarms.tftest.hcl` `external` | APPROVE | These are plan-only mock assertions for the new alarm: zero in fixed mode, its shape, its actions, notBreaching on missing data, and its namespace and dimension. Nothing is read at runtime (tftest.hcl:65, 222-225, 234-237, 243). | | `internal/host/agent.go` `runAgent` | APPROVE | `eb.Page = PageOperator` is the same sink that hadepartures_wiring.go:169 already set, and the finalizer page still needs the departures context (hatakeover.go:55). The atomic pointer only publishes `eb` to the metrics observer and is cleared on return. No new read site (agent.go:551-553). | | `internal/activator/hasamebox.go` `ExecBackend.sameBoxEmpty` | APPROVE | The new line only feeds the tracker with rt.Host and `lease.CurrentSelf().IID` after the refusal. `sameBoxProven` and the `false, err` answer are unchanged. `markAcquiredHere` only clears tracker state (hasamebox.go:72-74, 172-175). | | `internal/activator/hatakeover.go` `ExecBackend.reportTakeover` | APPROVE | A visitor refusal is noted and a confirmed termination clears the host. The refusal, the alarm, the departure-finalize page and the returned values are unchanged, and it reads only rt.Host and the classified iid (hatakeover.go:52-54, 70). | | envelope `infra/modules/region-host` | APPROVE | The only change is the alarm resource above. No IAM or other resource changes (group_alarms.tf:128-144). | | envelope `infra/modules/region-host/tests` | APPROVE | The only change is the mock assertions above (group_alarms.tftest.hcl). | | envelope `internal/activator` | APPROVE | The new hasuspectholder.go has four functions: `clock`, `clear`, `note` and `SuspectHolderHosts`. They touch only in-memory maps, `lease.LeaseTTL`, log lines and the injected `b.Page`. The struct field (backend_exec.go:402-403) and the two call sites reach nothing external and loosen no proof (hasuspectholder.go:39-128). | | envelope `internal/groupadmission` | APPROVE | It adds one int field, `SuspectHolderHosts`, to the Observation struct, with no logic (observation.go:9). | | envelope `internal/host` | APPROVE | `suspectsFrom` and `observe` read only the in-process backend's counter, and only in group mode. `groupMetricData` adds one Count datum to the existing PutMetricData path with no new authority or input (group_metrics.go:20-29, 61, 71-73, 199). | Overall: APPROVE all 5 units and 5 envelopes at tip 8940163b.</result> <usage><subagent_tokens>60170</subagent_tokens><tool_uses>7</tool_uses><duration_ms>44256</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>bhovovgwj</task-id> <tool-use-id>toolu_01UxPoJWWCrt7i7pgQfxi3Bv</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/dc71bafb-7376-4e4b-a855-4d32f1eed771/tasks/bhovovgwj.output</output-file> <status>completed</status> <summary>Background command "Ledger Task 3; wait for CI on fix tip" completed (exit code 0)</summary> </task-notification>

Attributed to this commit: 21.0 g CO₂e (2,598,163 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on region-ha-g2-prep, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/docs/region-ha-runbook.md b/docs/region-ha-runbook.md
index aa4b889b9..7a9895164 100644
--- a/docs/region-ha-runbook.md
+++ b/docs/region-ha-runbook.md
@@ -77,3 +77,22 @@ If the box role itself must read it, widen `ssm_parameter_arn` to include that o
1. Confirm in EC2 that the instance is terminated or is still running.
2. If it is a group member, terminate it in its group with `--no-should-decrement-desired-capacity`.
3. Never terminate a fixed box without a separate decision. Check its storage access and its agent first.
+
+## Install chrony on a fixed box
+
+Before G3 step 4 on the G3 card, install chrony on each named fixed box in an attended maintenance window. Use the reviewed `scripts/region-ha-g3/chrony-fixed-box.sh` through SSM as root, with approval for the named box. Group boxes already configure Amazon Time Sync at first boot.
+
+Run the script from the reviewed checkout or copy that exact script to the box:
+
+```sh
+bash scripts/region-ha-g3/chrony-fixed-box.sh
+bash scripts/region-ha-g3/chrony-fixed-box.sh --check
+```
+
+The install prints the package states before and after replacing `systemd-timesyncd` with `chrony`. It writes `server 169.254.169.123 prefer iburst minpoll 4 maxpoll 4` to `/etc/chrony/conf.d/carlos-fixed.conf`, enables chrony and restarts it. It leaves `carlos-edge` and `host.env` alone and does not reboot the box. You can run it again to restore the same configuration.
+
+Passing output includes a `^*` or `^+` source at `169.254.169.123`, a tracking CSV from `chronyc` running as `carlos` with the edge sandbox restrictions, and `Chrony checks passed.` The install also requires `chronyc waitsync 20 2` to succeed. Save the output with the G3 evidence. `--check` reads the package states, exact configuration and sources, then runs the tracking witness in a transient systemd unit. It does not install packages, write configuration or restart a service.
+
+If no matching source appears within 20 seconds, the script exits nonzero and leaves chrony installed. Synchronization or sandbox witness failures also stop the script. The rollback hint is `apt-get install systemd-timesyncd`; run it only if you decide to restore the previous time daemon. A failed check is not permission to continue to G3 step 4.
+
+For new fixed boxes, add the matching chrony setup to the deployment's host-init source and template. Do not apply that user_data change to running boxes, and never re-run user_data on a live box. A user_data change in the flagship root can stop and start the box. Keep this first-boot change separate from the attended convergence above.
diff --git a/scripts/region-ha-g3/chrony-fixed-box.sh b/scripts/region-ha-g3/chrony-fixed-box.sh
new file mode 100755
index 000000000..ff88bee3a
--- /dev/null
+++ b/scripts/region-ha-g3/chrony-fixed-box.sh
@@ -0,0 +1,93 @@
+#!/bin/bash
+set -euo pipefail
+
+# Operator-facing output, collected here for the copy pass.
+readonly PASS='Chrony checks passed.'
+readonly PREFLIGHT_FAILURE='Run as root on a fixed box with /etc/carlos present, with no arguments or only --check.'
+readonly CONFIG_FAILURE='Chrony configuration checks failed. Refuse symbolic links and require the fixed box configuration and installed chrony package.'
+readonly CLOCK_FAILURE='Chrony checks failed. Require an Amazon Time Sync source within 20 seconds and passing synchronization and sandbox checks.'
+readonly ROLLBACK='To restore the previous time daemon, run apt-get install systemd-timesyncd.'
+
+readonly CONF='/etc/chrony/conf.d/carlos-fixed.conf'
+readonly SOURCE='server 169.254.169.123 prefer iburst minpoll 4 maxpoll 4'
+check=false
+if (( $# == 1 )) && [[ $1 == --check ]]; then
+ check=true
+elif (( $# != 0 )); then
+ printf '%s\n' "$PREFLIGHT_FAILURE" >&2
+ exit 1
+fi
+if [[ $(id -u) != 0 || ! -d /etc/carlos ]]; then
+ printf '%s\n' "$PREFLIGHT_FAILURE" >&2
+ exit 1
+fi
+
+config_failure() {
+ printf '%s\n' "$CONFIG_FAILURE" >&2
+ exit 1
+}
+clock_failure() {
+ printf '%s\n' "$CLOCK_FAILURE" "$ROLLBACK" >&2
+ exit 1
+}
+check_paths() {
+ # Check parent directories too, including dangling destination links.
+ [[ ! -L /etc/chrony && ! -L /etc/chrony/conf.d && ! -L $CONF ]] || config_failure
+ [[ ! -e $CONF || -f $CONF ]] || config_failure
+}
+package_states() {
+ # An absent package is useful evidence before installation, not a fatal error.
+ dpkg-query -W -f='${binary:Package} ${Status}\n' chrony || true
+ dpkg-query -W -f='${binary:Package} ${Status}\n' systemd-timesyncd || true
+}
+
+check_paths
+states=$(package_states)
+printf '%s\n' "$states"
+if "$check"; then
+ [[ $states == *'chrony install ok installed'* ]] || config_failure
+ [[ -f $CONF ]] && cmp -s "$CONF" <(printf '%s\n' "$SOURCE") || config_failure
+ cat "$CONF"
+else
+ NEEDRESTART_MODE=l apt-get -y -q install chrony
+ package_states
+ check_paths
+ # mktemp uses the operator's on-disk TMPDIR, or /var/tmp when it is unset.
+ staging=$(mktemp "${TMPDIR:-/var/tmp}/carlos-chrony.XXXXXXXX")
+ trap 'rm -f -- "$staging"' EXIT
+ printf '%s\n' "$SOURCE" > "$staging"
+ install -o root -g root -m 0644 "$staging" "$CONF"
+ systemctl enable chrony.service
+ systemctl restart chrony.service
+fi
+
+# Match the group bootstrap's selected/candidate source rule. Cap slow chronyc
+# calls as well as the 20 one-second attempts so a stuck daemon cannot hang us.
+deadline=$((SECONDS + 20))
+synced=false
+for ((attempt = 0; attempt < 20; attempt++)); do
+ remaining=$((deadline - SECONDS))
+ (( remaining > 0 )) || break
+ limit=2
+ (( remaining >= limit )) || limit=$remaining
+ sources=$(timeout "$limit" chronyc -n sources) || sources=''
+ if awk '$1 ~ /^\^[*+]$/ && $2 == "169.254.169.123" { found=1 } END { exit !found }' <<< "$sources"; then
+ printf '%s\n' "$sources"
+ synced=true
+ break
+ fi
+ (( SECONDS < deadline )) || break
+ sleep 1
+done
+"$synced" || clock_failure
+if ! "$check"; then
+ chronyc waitsync 20 2 || clock_failure
+fi
+systemd-run --wait --pipe --quiet \
+ -p User=carlos \
+ -p NoNewPrivileges=yes \
+ -p ProtectSystem=strict \
+ -p RestrictAddressFamilies='AF_INET AF_INET6 AF_UNIX' \
+ -p SystemCallFilter=@system-service \
+ /usr/bin/chronyc -c tracking || clock_failure
+printf '%s\n' "$PASS"
diff --git a/scripts/region_ha_g3_chrony_test.py b/scripts/region_ha_g3_chrony_test.py
new file mode 100644
index 000000000..e23669536
--- /dev/null
+++ b/scripts/region_ha_g3_chrony_test.py
@@ -0,0 +1,216 @@
+"""Offline fixed-box convergence tests. Only copied scripts use fixture paths."""
+import json
+import os
+from pathlib import Path
+import re
+import subprocess
+import tempfile
+import unittest
+
+ROOT = Path(__file__).resolve().parent.parent
+SCRIPT = ROOT / 'scripts/region-ha-g3/chrony-fixed-box.sh'
+TEMPLATE = ROOT / 'infra/modules/region-host/group-init.sh.tftpl'
+CONF = 'server 169.254.169.123 prefer iburst minpoll 4 maxpoll 4\n'
+WITNESS = ['systemd-run', '--wait', '--pipe', '--quiet', '-p', 'User=carlos',
+ '-p', 'NoNewPrivileges=yes', '-p', 'ProtectSystem=strict',
+ '-p', 'RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX',
+ '-p', 'SystemCallFilter=@system-service', '/usr/bin/chronyc', '-c', 'tracking']
+SHIM = '''#!/usr/bin/python3
+import json, os, pathlib, shutil, sys
+name = pathlib.Path(sys.argv[0]).name
+args = sys.argv[1:]
+with open(os.environ['CALLS'], 'a') as log:
+ log.write(json.dumps([name] + args) + '\\n')
+if os.environ.get('FAIL_AT') == name + ' ' + ' '.join(args):
+ sys.exit(1)
+if name == 'id':
+ print(os.environ.get('TEST_UID', '0'))
+elif name == 'dpkg-query':
+ package = args[-1]
+ installed = pathlib.Path(os.environ['INSTALLED']).exists()
+ state = 'install ok installed' if installed or package == 'systemd-timesyncd' else 'unknown ok not-installed'
+ if installed and package == 'systemd-timesyncd':
+ state = 'deinstall ok config-files'
+ print(package + ' ' + state)
+elif name == 'apt-get':
+ assert os.environ.get('NEEDRESTART_MODE') == 'l'
+ pathlib.Path(os.environ['INSTALLED']).touch()
+elif name == 'chronyc' and args == ['-n', 'sources']:
+ print(os.environ.get('SOURCES', '^* 169.254.169.123 3 4 377 1 +0ns[+0ns] +/- 1ms'))
+elif name == 'systemd-run':
+ print('A9FEA97B,169.254.169.123,3,0,0.000001,0,0,0,0,0,0,0,Normal')
+elif name == 'install':
+ assert args[:6] == ['-o', 'root', '-g', 'root', '-m', '0644']
+ shutil.copyfile(args[6], args[7])
+ pathlib.Path(args[7]).chmod(0o644)
+'''
+
+
+class ChronyFixedBoxTests(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory(dir=os.environ.get('TMPDIR', str(Path.home() / '.cache')))
+ self.addCleanup(self.tmp.cleanup)
+ self.root = Path(self.tmp.name)
+ self.marker = self.root / 'etc/carlos'
+ self.marker.mkdir(parents=True)
+ self.conf = self.root / 'etc/chrony/conf.d/carlos-fixed.conf'
+ self.conf.parent.mkdir(parents=True)
+ self.bin = self.root / 'bin'
+ self.bin.mkdir()
+ for name in ('id', 'apt-get', 'dpkg-query', 'systemctl', 'chronyc', 'systemd-run', 'install', 'sleep'):
+ shim = self.bin / name
+ shim.write_text(SHIM)
+ shim.chmod(0o700)
+ self.log = self.root / 'calls'
+ self.installed = self.root / 'installed'
+ self.env = dict(os.environ, PATH=str(self.bin) + ':' + os.environ['PATH'],
+ CALLS=str(self.log), INSTALLED=str(self.installed), TMPDIR=str(self.root))
+
+ def run_script(self, *args, **env):
+ # No production override for root paths. Rewrite only a temporary copy.
+ source = SCRIPT.read_text().replace('/etc/carlos', str(self.marker))
+ source = source.replace('/etc/chrony', str(self.root / 'etc/chrony'))
+ result = subprocess.run(['bash', '-c', source, 'chrony-fixed-box.sh', *args],
+ env=dict(self.env, **env), capture_output=True, text=True, timeout=15)
+ calls = [json.loads(line) for line in self.log.read_text().splitlines()] if self.log.exists() else []
+ return result, calls
+
+ def ready(self):
+ self.installed.touch()
+ self.conf.write_text(CONF)
+
+ def test_happy_path_and_idempotence(self):
+ for _ in range(2):
+ self.log.unlink(missing_ok=True)
+ result, calls = self.run_script()
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(self.conf.read_text(), CONF)
+ self.assertEqual(self.conf.stat().st_mode & 0o777, 0o644)
+ self.assertEqual([c[0] for c in calls], ['id', 'dpkg-query', 'dpkg-query', 'apt-get',
+ 'dpkg-query', 'dpkg-query', 'install', 'systemctl', 'systemctl', 'chronyc',
+ 'chronyc', 'systemd-run'])
+ self.assertIn(['apt-get', '-y', '-q', 'install', 'chrony'], calls)
+ self.assertEqual(calls[7:11], [['systemctl', 'enable', 'chrony.service'],
+ ['systemctl', 'restart', 'chrony.service'], ['chronyc', '-n', 'sources'],
+ ['chronyc', 'waitsync', '20', '2']])
+ self.assertEqual(calls[-1], WITNESS)
+ self.assertEqual(calls[6][1:7], ['-o', 'root', '-g', 'root', '-m', '0644'])
+ self.assertFalse(Path(calls[6][-2]).exists(), 'staging file leaked')
+ self.assertIn('chrony unknown ok not-installed' if _ == 0 else 'chrony install ok installed', result.stdout)
+ self.assertIn('systemd-timesyncd deinstall ok config-files', result.stdout)
+ self.assertIn('A9FEA97B,169.254.169.123', result.stdout)
+ self.assertIn('Chrony checks passed.', result.stdout)
+
+ def test_check_only_reads(self):
+ self.ready()
+ before = self.conf.stat()
+ result, calls = self.run_script('--check')
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual([c[0] for c in calls], ['id', 'dpkg-query', 'dpkg-query', 'chronyc', 'systemd-run'])
+ self.assertEqual(calls[-1], WITNESS)
+ self.assertEqual(self.conf.stat().st_mtime_ns, before.st_mtime_ns)
+ self.assertEqual(self.conf.read_text(), CONF)
+
+ def test_non_root(self):
+ result, calls = self.run_script(TEST_UID='1000')
+ self.assertNotEqual(result.returncode, 0)
+ self.assertEqual(calls, [['id', '-u']])
+
+ def test_missing_marker(self):
+ self.marker.rmdir()
+ result, calls = self.run_script()
+ self.assertNotEqual(result.returncode, 0)
+ self.assertEqual(calls, [['id', '-u']])
+
+ def test_symlink_conf_and_parents(self):
+ target = self.root / 'target'
+ target.write_text('untouched\n')
+ for mode in ((), ('--check',)):
+ self.conf.symlink_to(target)
+ result, calls = self.run_script(*mode)
+ self.assertNotEqual(result.returncode, 0)
+ self.assertEqual(calls, [['id', '-u']])
+ self.assertEqual(target.read_text(), 'untouched\n')
+ self.conf.unlink()
+ self.log.unlink()
+ self.conf.symlink_to(self.root / 'absent')
+ result, calls = self.run_script()
+ self.assertNotEqual(result.returncode, 0)
+ self.assertEqual(calls, [['id', '-u']])
+ self.conf.unlink()
+ self.log.unlink()
+ self.conf.parent.rmdir()
+ self.conf.parent.symlink_to(self.root, target_is_directory=True)
+ result, calls = self.run_script()
+ self.assertNotEqual(result.returncode, 0)
+ self.assertEqual(calls, [['id', '-u']])
+
+ def test_no_source_stops_after_twenty_tries(self):
+ for source in ('', '^? 169.254.169.123', '^* 169.254.169.1234', '^* 192.0.2.1'):
+ with self.subTest(source=source):
+ self.log.unlink(missing_ok=True)
+ result, calls = self.run_script(SOURCES=source)
+ self.assertNotEqual(result.returncode, 0)
+ self.assertEqual(calls.count(['chronyc', '-n', 'sources']), 20)
+ self.assertEqual(calls.count(['sleep', '1']), 20)
+ self.assertNotIn(['chronyc', 'waitsync', '20', '2'], calls)
+ self.assertNotIn(WITNESS, calls)
+ self.assertTrue(self.installed.exists())
+ self.assertIn('20', result.stderr)
+ self.assertIn('apt-get install systemd-timesyncd', result.stderr)
+
+ def test_candidate_source_passes(self):
+ result, _ = self.run_script(SOURCES='^+ 169.254.169.123')
+ self.assertEqual(result.returncode, 0, result.stderr)
+
+ def test_check_refuses_missing_package_or_wrong_conf(self):
+ self.conf.write_text(CONF)
+ result, calls = self.run_script('--check')
+ self.assertNotEqual(result.returncode, 0)
+ self.assertNotIn('apt-get', [c[0] for c in calls])
+ self.ready()
+ for content in ('', CONF.replace('minpoll 4', 'minpoll 6'), CONF + 'pool example.invalid\n'):
+ self.conf.write_text(content)
+ result, calls = self.run_script('--check')
+ self.assertNotEqual(result.returncode, 0)
+ self.assertNotIn(WITNESS, calls)
+
+ def test_waitsync_and_sandbox_failures(self):
+ for failure in ('chronyc waitsync 20 2', ' '.join(WITNESS)):
+ with self.subTest(failure=failure):
+ self.log.unlink(missing_ok=True)
+ result, calls = self.run_script(FAIL_AT=failure)
+ self.assertNotEqual(result.returncode, 0)
+ self.assertNotIn('Chrony checks passed.', result.stdout)
+ self.assertIn('apt-get install systemd-timesyncd', result.stderr)
+ if failure.startswith('chronyc'):
+ self.assertNotIn(WITNESS, calls)
+
+ def test_mutation_commands_fail_closed(self):
+ for failure in ('apt-get -y -q install chrony', 'systemctl enable chrony.service',
+ 'systemctl restart chrony.service'):
+ self.log.unlink(missing_ok=True)
+ result, calls = self.run_script(FAIL_AT=failure)
+ self.assertNotEqual(result.returncode, 0)
+ self.assertNotIn(WITNESS, calls)
+ self.assertNotIn('Chrony checks passed.', result.stdout)
+
+ def test_unknown_arguments_refused(self):
+ for args in (('--typo',), ('--check', 'extra')):
+ result, calls = self.run_script(*args)
+ self.assertNotEqual(result.returncode, 0)
+ self.assertEqual(calls, [])
+
+ def test_conf_matches_group_template(self):
+ expected = re.search(r"'(?P<conf>server 169\.254\.169\.123[^']+)'", TEMPLATE.read_text()).group('conf')
+ actual = re.search(r"'(?P<conf>server 169\.254\.169\.123[^']+)'", SCRIPT.read_text()).group('conf')
+ self.assertEqual(actual, expected)
+
+ def test_forbidden_commands(self):
+ source = SCRIPT.read_text()
+ self.assertNotRegex(source, r'\b(?:reboot|kill)\b|systemctl\s+restart\s+carlos|host\.env')
+ self.assertNotRegex(source, '[\u2013\u2014]')
+
+
+if __name__ == '__main__':
+ unittest.main()