Commit c57e079d by PLN (Algolia)

devname: make doctor check the Linux chain and print the exact fixes

New checks: low ports (unprivileged-port sysctl or setcap on caddy), a
system caddy.service holding :80, linger, *.localhost resolving to
loopback through the system resolver (getaddrinfo), mkcert presence,
and the LAN face announcer. Each FAIL prints the command to run (apt,
pacman, dnf, brew, sysctl, setcap, systemctl); WARN lines cover the
optional parts and do not fail the exit code. Firewall hints for
socketfilterfw, ufw and firewalld are printed, never run.
parent b76c2eb3
...@@ -244,6 +244,18 @@ class Platform: ...@@ -244,6 +244,18 @@ class Platform:
def firewall_hints(self): def firewall_hints(self):
return [] return []
def low_ports(self, caddy):
return None # (ok, detail, fixes) where the OS gates :80/:443; None = nothing to check
def system_caddy(self):
return None # (state, fix) when an OS-managed caddy would hold :80 first
def linger(self):
return None # True/False where the agent's start-at-boot is a separate switch
def localhost_hint(self):
return "make the system resolver map *.localhost to 127.0.0.1/::1 (RFC 6761), or list the names in /etc/hosts"
def short_hostname(): def short_hostname():
"""This machine's first hostname label as a DNS-safe slug (XPS24 -> xps24); avahi announces it as <it>.local.""" """This machine's first hostname label as a DNS-safe slug (XPS24 -> xps24); avahi announces it as <it>.local."""
...@@ -276,6 +288,12 @@ class MacPlatform(Platform): ...@@ -276,6 +288,12 @@ class MacPlatform(Platform):
def announcer_problem(self): def announcer_problem(self):
return None if self.find_tool("dns-sd") else "dns-sd not found" return None if self.find_tool("dns-sd") else "dns-sd not found"
def low_ports(self, caddy):
return True, "macOS lets an unprivileged process bind :80/:443 on the wildcard address", []
def localhost_hint(self):
return "macOS resolves *.localhost natively; check /etc/hosts and any VPN or DNS profile overriding it"
def firewall_hints(self): def firewall_hints(self):
fw = "/usr/libexec/ApplicationFirewall/socketfilterfw" fw = "/usr/libexec/ApplicationFirewall/socketfilterfw"
caddy = os.path.realpath(CADDY) if CADDY else "$(readlink -f $(which caddy))" caddy = os.path.realpath(CADDY) if CADDY else "$(readlink -f $(which caddy))"
...@@ -510,6 +528,11 @@ WantedBy=default.target ...@@ -510,6 +528,11 @@ WantedBy=default.target
"--add-service=https --add-service=mdns && sudo firewall-cmd --reload") "--add-service=https --add-service=mdns && sudo firewall-cmd --reload")
return hints return hints
def localhost_hint(self):
return ("run systemd-resolved (it answers *.localhost itself; /etc/resolv.conf -> the 127.0.0.53 stub), "
"or add `myhostname` to the hosts: line of /etc/nsswitch.conf (sudo apt install libnss-myhostname "
"on Debian/Ubuntu if missing), or list the names in /etc/hosts")
def linger(self): def linger(self):
"""True/False: does the user manager (and so the agent) start at boot, before any login?""" """True/False: does the user manager (and so the agent) start at boot, before any login?"""
rc, out = run_out(["loginctl", "show-user", str(os.getuid()), "--property=Linger", "--value"]) rc, out = run_out(["loginctl", "show-user", str(os.getuid()), "--property=Linger", "--value"])
...@@ -1534,7 +1557,20 @@ def cmd_serve(a): ...@@ -1534,7 +1557,20 @@ def cmd_serve(a):
return caddy.wait() return caddy.wait()
def localhost_resolves(name="devname-doctor.localhost"):
"""(ok, addresses): does the system resolver (what curl, python and agents use) send *.localhost
to loopback? Browsers hard-wire .localhost themselves, so a working browser proves nothing here."""
try:
infos = socket.getaddrinfo(name, 80, type=socket.SOCK_STREAM)
except (socket.gaierror, UnicodeError):
return False, []
addrs = sorted({i[4][0].split("%")[0] for i in infos})
return bool(addrs) and all(ipaddress.ip_address(x).is_loopback for x in addrs), addrs
def cmd_doctor(a): def cmd_doctor(a):
"""PASS/FAIL lines decide the exit code; WARN lines are optional extras (LAN face, linger).
Every FAIL carries the exact command to fix it; doctor itself never changes anything."""
ok = True ok = True
def line(good, text): def line(good, text):
...@@ -1542,18 +1578,36 @@ def cmd_doctor(a): ...@@ -1542,18 +1578,36 @@ def cmd_doctor(a):
ok = ok and good ok = ok and good
print(("PASS " if good else "FAIL ") + text) print(("PASS " if good else "FAIL ") + text)
def warn(text):
print("WARN " + text)
def note(text): def note(text):
print(" " + text) print(" " + text)
note("platform: " + PLAT.describe()) note("platform: " + PLAT.describe())
line(bool(CADDY), f"caddy at {CADDY}" if CADDY else "caddy not found") line(bool(CADDY), f"caddy at {CADDY}" if CADDY else "caddy not found")
if not CADDY: if not CADDY:
note("fix: " + PLAT.install_hint("caddy")) note("fix: " + PLAT.install_hint("caddy"))
low = PLAT.low_ports(CADDY)
if low:
good, detail, fixes = low
line(good, "low ports: " + detail)
for f in fixes:
note("fix: " + f)
sc = PLAT.system_caddy()
if sc:
line(False, f"a system caddy.service is {sc[0]}: it takes :80 before devname's caddy can")
note("fix: " + sc[1])
running = PLAT.agent_running() running = PLAT.agent_running()
if running is None: if running is None:
note("no supervisor integration here: run `devname serve` under your init") note("no supervisor integration here: run `devname serve` under your init")
else: else:
line(running, f"{PLAT.supervisor} agent {PLAT.running_words[0] if running else PLAT.running_words[1]}" line(running, f"{PLAT.supervisor} agent {PLAT.running_words[0] if running else PLAT.running_words[1]}"
f" ({PLAT.agent_path()}; logs: {PLAT.log_hint()})") f" ({PLAT.agent_path()}; logs: {PLAT.log_hint()})")
if not running:
note("fix: devname agent install (preview first: devname agent install --print)")
lingering = PLAT.linger()
if lingering is False:
warn("agent starts at login, not at boot; for boot: loginctl enable-linger")
line(os.path.exists(ADMIN_SOCK), "caddy admin socket present") line(os.path.exists(ADMIN_SOCK), "caddy admin socket present")
try: try:
urllib.request.urlopen(urllib.request.Request("http://127.0.0.1/", headers={"Host": "doctor.invalid"}), timeout=3) urllib.request.urlopen(urllib.request.Request("http://127.0.0.1/", headers={"Host": "doctor.invalid"}), timeout=3)
...@@ -1572,17 +1626,33 @@ def cmd_doctor(a): ...@@ -1572,17 +1626,33 @@ def cmd_doctor(a):
except OSError: except OSError:
pass pass
line(code == 200, f"index page on {INDEX_HOST} (got {code})") line(code == 200, f"index page on {INDEX_HOST} (got {code})")
resolves, addrs = localhost_resolves()
line(resolves, "*.localhost resolves to loopback for curl/python/agents (getaddrinfo: "
+ (", ".join(addrs) or "no answer") + ")")
if not resolves:
note("fix: " + PLAT.localhost_hint())
if not MKCERT:
line(False, "mkcert not found (https off, http names still work)")
note("fix: " + PLAT.install_hint("mkcert"))
root = mkcert_caroot() root = mkcert_caroot()
line(bool(root) and os.path.exists(os.path.join(root, "rootCA.pem")), line(bool(root) and os.path.exists(os.path.join(root, "rootCA.pem")),
"mkcert root CA exists (https; trust it with `mkcert -install`)") "mkcert root CA exists (https; trust it once with `TRUST_STORES=system,nss mkcert -install`)")
line(have_https(), "https cert issued for the registered names") line(have_https(), "https cert issued for the registered names")
problem = PLAT.announcer_problem()
if problem:
warn(f"LAN face unavailable: {problem}; loopback names unaffected")
else:
note(f"LAN face names: <name>{LAN_SUFFIX}, gateway {GATEWAY_HOST}, ssh gate {HANDSHAKE_HOST}, "
f"address {lan_ip() or 'none (no private LAN address now)'}")
try: try:
with open(LAN_GATE) as fh: with open(LAN_GATE) as fh:
st = json.load(fh) st = json.load(fh)
age = int(time.time()) - st.get("checked", 0) age = int(time.time()) - st.get("checked", 0)
print(f" lan gate {'OPEN' if st.get('open') else 'closed'}, handshake {age}s ago ({st.get('detail', '')})") print(f" lan gate {'OPEN' if st.get('open') else 'closed'}, checked {age}s ago ({st.get('detail', '')})")
except (OSError, ValueError): except (OSError, ValueError):
print(" lan gate closed (announcer has not run yet)") print(" lan gate closed (announcer has not run yet)")
for h in PLAT.firewall_hints():
note("hint: " + h)
print(f"{len(load()['entries'])} names registered") print(f"{len(load()['entries'])} names registered")
return 0 if ok else 1 return 0 if ok else 1
......
...@@ -744,6 +744,68 @@ class PlatformTests(unittest.TestCase): ...@@ -744,6 +744,68 @@ class PlatformTests(unittest.TestCase):
ann.reconcile({"a.xps24.local"}, None) # lost the LAN: withdraw everything ann.reconcile({"a.xps24.local"}, None) # lost the LAN: withdraw everything
self.assertFalse(any(p.alive for p in started)) self.assertFalse(any(p.alive for p in started))
# doctor: every FAIL carries its exact fix; doctor itself runs no sudo and changes nothing
def doctor(self):
with mock.patch.object(self.dn.urllib.request, "urlopen", side_effect=OSError("refused")):
return self.cli("doctor")
def test_localhost_resolution_probe(self):
tcp = lambda ip: (socket.AF_INET6 if ":" in ip else socket.AF_INET, socket.SOCK_STREAM, 6, "", (ip, 80))
with mock.patch.object(self.dn.socket, "getaddrinfo", return_value=[tcp("127.0.0.1"), tcp("::1")]):
self.assertEqual(self.dn.localhost_resolves(), (True, ["127.0.0.1", "::1"]))
with mock.patch.object(self.dn.socket, "getaddrinfo", return_value=[tcp("127.0.0.1"), tcp("203.0.113.9")]):
self.assertFalse(self.dn.localhost_resolves()[0]) # a search-domain hijack must not pass
with mock.patch.object(self.dn.socket, "getaddrinfo", side_effect=socket.gaierror("no name")):
self.assertEqual(self.dn.localhost_resolves(), (False, []))
def test_linux_doctor_prints_every_fix(self):
run = FakeRun({("systemctl", "is-active", "caddy.service"): (0, "active"),
("systemctl", "--user", "is-active"): (3, "inactive"),
("loginctl", "show-user"): (0, "no")})
plat = self.linux(run, port_start="1024")
with mock.patch.object(self.dn, "file_has_bind_cap", return_value=False), \
mock.patch.object(self.dn, "localhost_resolves", return_value=(False, [])), \
mock.patch.object(self.dn, "MKCERT", None), \
mock.patch.object(plat, "announcer_problem", return_value="avahi-publish not found (x)"):
rc, out, _ = self.doctor()
self.assertEqual(rc, 1)
for want in ("platform: linux (ubuntu, debian family)",
"FAIL low ports", "sudo tee /etc/sysctl.d/60-devname-low-ports.conf", "sudo setcap",
"FAIL a system caddy.service is active", "fix: sudo systemctl disable --now caddy",
"FAIL systemd agent not active", "devname agent install --print",
"WARN agent starts at login", "loginctl enable-linger",
"FAIL *.localhost resolves", "systemd-resolved", "myhostname",
"FAIL mkcert not found", "libnss3-tools", "TRUST_STORES=system,nss",
"WARN LAN face unavailable: avahi-publish not found", "loopback names unaffected",
"hint: if ufw is active"):
self.assertIn(want, out)
self.assertFalse(any("sudo" in c for call in run.calls for c in call)) # printed, never run
def test_linux_doctor_passes_the_low_port_and_caddy_checks_when_set_up(self):
run = FakeRun({("systemctl", "is-active", "caddy.service"): (3, "inactive"),
("systemctl", "is-enabled", "caddy.service"): (1, "disabled"),
("systemctl", "--user", "is-active"): (0, "active"),
("loginctl", "show-user"): (0, "yes")})
plat = self.linux(run)
with mock.patch.object(plat, "announcer_problem", return_value=None), \
mock.patch.object(self.dn, "lan_ip", return_value="192.168.1.2"):
_, out, _ = self.doctor()
self.assertIn("PASS low ports: low ports open to users", out)
self.assertIn("PASS systemd agent active", out)
self.assertNotIn("system caddy", out)
self.assertNotIn("WARN agent starts at login", out)
self.assertIn(f"LAN face names: <name>{self.dn.LAN_SUFFIX}", out)
def test_mac_doctor_speaks_launchd_and_the_application_firewall(self):
plat = self.use(self.dn.MacPlatform(), FakeRun({("launchctl", "print"): (0, "")}))
with mock.patch.object(plat, "announcer_problem", return_value=None), \
mock.patch.object(self.dn, "lan_ip", return_value=None):
_, out, _ = self.doctor()
self.assertIn("PASS low ports: macOS lets an unprivileged process bind", out)
self.assertIn("PASS launchd agent loaded", out)
self.assertIn("socketfilterfw --add", out)
self.assertNotIn("WARN", out) # no linger concept, no system caddy probe on macOS
# any other Unix: no supervisor, a clear refusal # any other Unix: no supervisor, a clear refusal
def test_other_platform_refuses_agent_and_points_at_serve(self): def test_other_platform_refuses_agent_and_points_at_serve(self):
self.use(self.dn.Platform({})) self.use(self.dn.Platform({}))
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment