testsAndMisc/python_pkg/focus_policy/tests/test_main.py
Krzysztof kuhy Rudnicki e3d5e1dd18 Serve the blocklist over DoT and hand the policy to the app as an asset
Two gaps stopped the unrooted path working end to end. The phone had no way to
read the focus policy, and the blocklist was only reachable as a hosts file or
over plain UDP/53 on the LAN -- while the rooted enforcer actively rejected
every DoT connection, so a self-hosted resolver could not have worked even if
one existed.

focus_owner now loads a generated policy.json instead of hardcoding anything,
so config.sh stays the single source of truth across Python, shell and Kotlin.
The committed asset is rendered with --redact-home and a test fails if home
coordinates ever appear in it. An unknown schema_version is rejected outright:
silently accepting a newer schema means enforcing a policy the app has misread,
and a misread allowlist is one that blocks the dialer.

dns_enforcer.sh rejected ALL port 853 traffic and pinned Private DNS off, every
20 seconds. That is right when DoT is a bypass channel and exactly wrong when
DoT is the enforcement channel, which is what an unrooted phone needs -- it has
no hosts file to fall back to. With DNS_TRUSTED_DOT_HOST set it now ACCEPTs the
trusted resolver before the blanket REJECT, and pins Private DNS to that
hostname so the user cannot pick an unfiltered one. Rule order is load-bearing:
iptables takes the first match, so an ACCEPT appended after the REJECT would
never be reached. expected_rule_count() counts the new rules, because a
mismatch there makes chain_intact() rebuild the chain every 20s -- a silent
fork storm that also drops the connection each time. With the variable empty
the behaviour is byte-identical, so the rooted phone is untouched until this is
deployed.

setup_dot_resolver.sh terminates DoT with stunnel rather than Caddy: DoT is a
raw TLS stream and stock caddy:2.8 has no layer4 module, so using Caddy would
have meant an xcaddy rebuild of a container serving five live sites. It reuses
the certificate Caddy already renews, so nothing competes for port 80. It binds
to the WireGuard address, not 0.0.0.0 -- a public DoT endpoint is an open
resolver, and over the existing tunnel it needs no port-forward, no firewall
rule and no rate limiting. Verified: example.com resolves, pornhub.com returns
0.0.0.0, TLS 1.3 against the LE cert, and both the LAN and public addresses
refuse.

The Device Owner checklist is planning only. Checking the device rather than
the config settled the one open risk: Google Wallet is not installed and no NFC
payment default is set, so the unconfirmable tap-to-pay question does not apply
here. The same check found that Aegis, MS Authenticator, Oracle IDM and PKO IKO
are absent -- they are in config.sh's whitelist, which describes the rooted
phone, not this one.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AwepyL5Lxs5QKbKkMpxxxL
2026-08-05 09:36:11 +02:00

111 lines
3.4 KiB
Python

"""Tests for the policy-export command line entry point."""
from __future__ import annotations
import json
from typing import TYPE_CHECKING
import pytest
from python_pkg.focus_policy.__main__ import build_parser, main
if TYPE_CHECKING:
from pathlib import Path
MINIMAL_CONFIG = """
export RADIUS=150
export NIGHT_CURFEW_ENABLED=1
export NIGHT_CURFEW_START="2300"
export NIGHT_CURFEW_END="0500"
export LAUNCHER_PACKAGE="com.launcher"
export WHITELIST="
com.launcher
pl.mbank
"
export NIGHT_WHITELIST="
pl.mbank
"
export SYSTEM_NEVER_DISABLE="
com.android.settings
"
"""
SECRETS = "export HOME_LAT=52.2297\nexport HOME_LON=21.0122\n"
@pytest.fixture
def config(tmp_path: Path) -> Path:
"""Write a minimal config plus secrets, returning the config path."""
(tmp_path / "config.sh").write_text(MINIMAL_CONFIG, encoding="utf-8")
(tmp_path / "config_secrets.sh").write_text(SECRETS, encoding="utf-8")
return tmp_path / "config.sh"
def test_parser_requires_config() -> None:
"""--config is mandatory; without it argparse exits."""
with pytest.raises(SystemExit):
build_parser().parse_args([])
def test_writes_policy_to_stdout(
config: Path,
capsys: pytest.CaptureFixture[str],
) -> None:
"""With no --output the rendered policy goes to stdout."""
assert main(["--config", str(config)]) == 0
payload = json.loads(capsys.readouterr().out)
assert payload["schema_version"] == 1
assert payload["home"]["latitude"] == pytest.approx(52.2297)
def test_writes_policy_to_file(config: Path, tmp_path: Path) -> None:
"""--output writes the document, creating parent directories."""
out = tmp_path / "nested" / "policy.json"
assert main(["--config", str(config), "--output", str(out)]) == 0
assert json.loads(out.read_text(encoding="utf-8"))["schema_version"] == 1
def test_redact_home_removes_coordinates(
config: Path,
capsys: pytest.CaptureFixture[str],
) -> None:
"""--redact-home blanks the coordinates but keeps the radius.
This is the flag the committed asset is generated with, so that the
repository never records where the user lives.
"""
assert main(["--config", str(config), "--redact-home"]) == 0
payload = json.loads(capsys.readouterr().out)
assert payload["home"]["latitude"] is None
assert payload["home"]["longitude"] is None
assert payload["home"]["radius_m"] == pytest.approx(150.0)
def test_explicit_secrets_path(config: Path, tmp_path: Path) -> None:
"""--secrets overrides the default sibling lookup."""
other = tmp_path / "other.sh"
other.write_text("export HOME_LAT=1.0\nexport HOME_LON=2.0\n", encoding="utf-8")
assert main(["--config", str(config), "--secrets", str(other)]) == 0
def test_placeholder_coordinates_exit_nonzero(
config: Path,
capsys: pytest.CaptureFixture[str],
) -> None:
"""The shipped placeholder is a hard error, not a silent default."""
config.with_name("config_secrets.sh").write_text(
"export HOME_LAT=REDACTED_LAT\nexport HOME_LON=REDACTED_LON\n",
encoding="utf-8",
)
assert main(["--config", str(config)]) == 1
assert "placeholder" in capsys.readouterr().err
def test_missing_config_exits_nonzero(
tmp_path: Path,
capsys: pytest.CaptureFixture[str],
) -> None:
"""An unreadable config reports the OS error rather than traceback."""
assert main(["--config", str(tmp_path / "absent.sh")]) == 1
assert "error:" in capsys.readouterr().err