Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
0fba594
Exempt root from the Tor redirect too under --allow-root
onyks-os Nov 30, 2026
cea45a6
Fail closed when the session has no table fingerprint
onyks-os Nov 30, 2026
caee554
Keep the session when stop cannot remove its table
onyks-os Nov 30, 2026
a2d7ecc
Test that both tables get the same VPN transport exceptions
onyks-os Nov 30, 2026
69f0274
Stop writing watchdog_active and watchdog_pid to the lock
onyks-os Nov 30, 2026
b56c12a
Drop the pre-0.5 orphan recovery from start
onyks-os Nov 30, 2026
10c70d8
Merge remote-tracking branch 'origin/main' into fix/audit-findings
onyks-os Nov 30, 2026
00d9cba
Record the removals in the changelog and sync the docs site
onyks-os Nov 30, 2026
ac41603
Call ttp.ux directly instead of through state's re-exports
onyks-os Nov 30, 2026
8a5c458
Give restart start's options instead of a copy of them
onyks-os Nov 30, 2026
13f805b
Remove tor_control.verify_tor, which nothing called
onyks-os Nov 30, 2026
7114520
Delete _unit_state, DeliveryState and EXIT_UNVERIFIED
onyks-os Nov 30, 2026
b41facf
Drop re-exports and aliases that nothing uses
onyks-os Nov 30, 2026
747fb8a
Always map the DoH resolvers away instead of passing block_doh
onyks-os Nov 30, 2026
1802036
Resolve the Tor UID once and keep one list of Tor account names
onyks-os Nov 30, 2026
cdbfedd
Fold three near-copies into loops and one helper
onyks-os Nov 30, 2026
a488b18
Merge remote-tracking branch 'origin/main' into refactor/lean-audit
onyks-os Nov 30, 2026
a4c1054
Note the wider Tor account fallback in the changelog
onyks-os Nov 30, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
longer records `watchdog_active` and `watchdog_pid`, which nothing read:
`ttp watchdog status` asks systemd.

### Changed

- When the session lock does not say which UID Tor runs as, `ttp stop` and
`ttp start --external-daemon` look the account up among all four known
names (`debian-tor`, `toranon`, `tor`, `_tor`), the list that Tor detection
already used, instead of only `tor` and `debian-tor`.

### Fixed

- `ttp stop` deleted the session lock even when it could not remove the
Expand Down
7 changes: 7 additions & 0 deletions docs/web/release-notes/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
longer records `watchdog_active` and `watchdog_pid`, which nothing read:
`ttp watchdog status` asks systemd.

### Changed

- When the session lock does not say which UID Tor runs as, `ttp stop` and
`ttp start --external-daemon` look the account up among all four known
names (`debian-tor`, `toranon`, `tor`, `_tor`), the list that Tor detection
already used, instead of only `tor` and `debian-tor`.

### Fixed

- `ttp stop` deleted the session lock even when it could not remove the
Expand Down
4 changes: 2 additions & 2 deletions tests/leak/test_ip_leak.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

import pytest

# The production verifier, `ttp.tor_control.verify_tor`, makes five attempts
# The production verifier, `ttp.probe.verify_session`, makes five attempts
# across several endpoints with a three-second backoff. These tests used to make
# a single request to a single endpoint, which left them strictly less resilient
# than the code they exist to verify: one TLS handshake dropped by an exit node
Expand All @@ -26,7 +26,7 @@
# on `check.torproject.org`, on a commit whose identical tree had passed the same
# job eleven minutes earlier.
#
# The retry budget below deliberately mirrors verify_tor's. The endpoint list does
# The retry budget below deliberately mirrors verify_session's. The endpoint list does
# not: a leak test must not ask the code under test whether the code under test
# works.
_ATTEMPTS = 5
Expand Down
45 changes: 12 additions & 33 deletions tests/test_cli_start.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,10 @@

from ttp import state
from ttp.cli import app
from ttp.commands._common import EXIT_UNVERIFIED
from ttp.evidence import Verification, VerificationState
from ttp.evidence import ExitCode, Verification, VerificationState
from ttp.exceptions import DNSError, FirewallError, StateError, TorError
from ttp.runtime_records import RecordStore
from ttp.tor_detect import TOR_ACCOUNTS

runner = CliRunner()

Expand Down Expand Up @@ -177,7 +177,7 @@ def ready(**kwargs):
patch("ttp.vpn.inspect_profile", side_effect=[profile, None if condition == "changed" else profile]),
patch("ttp.vpn_guard.retained", return_value=condition == "retained"),
patch("ttp.vpn_guard.install", side_effect=lambda *a: events.append("guard-verified")),
patch("ttp.firewall.apply_rules") as rules,
patch("ttp.firewall.apply_rules", return_value=100) as rules,
patch("ttp.state.write_lock") as lock,
patch("ttp.watchdog.start_watchdog"),
):
Expand Down Expand Up @@ -294,7 +294,7 @@ def test_start_tor_verification_fails(
`ttp restart && ...` walk onto a blocked network believing it had succeeded.
"""
result = runner.invoke(app, ["start"])
assert result.exit_code == EXIT_UNVERIFIED
assert result.exit_code == ExitCode.UNVERIFIED
assert "Tor Verification Inconclusive" in result.output
assert "does not prove" in result.output
assert "held fail-closed" not in result.output
Expand Down Expand Up @@ -329,7 +329,7 @@ def test_start_unverified_still_starts_the_watchdog(
as verification failed would have silently dropped `--watchdog`.
"""
result = runner.invoke(app, ["start", "--watchdog"])
assert result.exit_code == EXIT_UNVERIFIED
assert result.exit_code == ExitCode.UNVERIFIED
assert mock_watchdog.call_count == 1


Expand All @@ -353,7 +353,7 @@ def test_start_tor_unit_failure_leaves_the_host_in_cleartext(
"""
result = runner.invoke(app, ["start"])
assert result.exit_code == 1
assert result.exit_code != EXIT_UNVERIFIED
assert result.exit_code != ExitCode.UNVERIFIED
assert mock_nft_str.call_count == 0
assert mock_write.call_count == 0

Expand Down Expand Up @@ -415,7 +415,7 @@ def test_start_rolls_back_a_firewall_failure(
result = runner.invoke(app, ["start"])

assert result.exit_code == 1
assert result.exit_code != EXIT_UNVERIFIED
assert result.exit_code != ExitCode.UNVERIFIED
assert "Firewall Setup Failed" in result.output

assert mock_stop_tor.call_count == 1
Expand Down Expand Up @@ -592,35 +592,14 @@ def test_start_rollback_never_stops_a_tor_it_does_not_own(
# ---------------------------------------------------------------------------


@patch("ttp.firewall.apply_rules")
@patch("pwd.getpwnam", side_effect=KeyError("no such user"))
@patch("ttp.firewall.apply_rules", return_value=4242)
@patch("ttp.state.write_lock")
def test_start_records_an_unresolvable_tor_user_as_a_null_uid(
mock_write,
mock_pwnam,
mock_apply_rules,
mock_base_start,
):
"""An unresolvable Tor user is swallowed, and the lock says so explicitly.

`start` wraps the UID lookup in a bare `except Exception: pass`, so a Tor
user that does not resolve does not stop the session - it writes
`tor_uid: None` into the lock instead. That is not a dead end: `do_stop()`
treats a missing `tor_uid` as "work it out yourself" and falls back to
`get_uid_from_port(transport_port)`, then to `pwd.getpwnam` on "tor" and
"debian-tor" in turn (`ttp/commands/lifecycle.py:42-52`).

That fallback chain is reachable *only* through this `pass`, which means it
was reachable only through an uncovered line. Pinning the null here is what
makes the chain's own tests meaningful: if this silently started writing a
real UID, or crashing, the fallback would become unreachable code that
still has tests.
"""
def test_start_records_the_uid_the_firewall_exempted(mock_write, mock_apply_rules, mock_base_start):
"""The lock's tor_uid is the one the table exempts, resolved once by apply_rules."""
result = runner.invoke(app, ["start"])

assert result.exit_code == 0, result.output
assert mock_write.call_count == 1
assert mock_write.call_args.kwargs["tor_uid"] is None
assert mock_write.call_args.kwargs["tor_uid"] == 4242


@patch("ttp.watchdog.start_watchdog", side_effect=RuntimeError("fork failed"))
Expand Down Expand Up @@ -1052,7 +1031,7 @@ def test_start_external_daemon_happy_path_fallback_user(
assert result.exit_code == 0, result.output
assert "Tor daemon detected operating under UID: 110" in result.output

mock_pwnam.assert_any_call("tor")
mock_pwnam.assert_any_call(TOR_ACCOUNTS[0])


@patch("ttp.commands.start._is_port_listening_tcp", return_value=True)
Expand Down
6 changes: 3 additions & 3 deletions tests/test_cli_stop.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

from ttp.cli import app
from ttp.commands import lifecycle
from ttp.commands._common import EXIT_UNVERIFIED
from ttp.evidence import ExitCode

runner = CliRunner()

Expand Down Expand Up @@ -257,7 +257,7 @@ def test_restart_active_session(mock_read, mock_stop, mock_sleep, mock_start):
assert kwargs["no_ipv6"] is False


@patch("ttp.commands.stop_restart.start_command", side_effect=typer.Exit(code=EXIT_UNVERIFIED))
@patch("ttp.commands.stop_restart.start_command", side_effect=typer.Exit(code=ExitCode.UNVERIFIED))
@patch("time.sleep")
@patch("ttp.commands.stop_restart._do_stop")
@patch("ttp.state.read_lock", return_value={"pid": 1234})
Expand All @@ -272,7 +272,7 @@ def test_restart_propagates_the_unverified_exit_code(mock_read, mock_stop, mock_
code has to survive the wrapper rather than collapsing into 0 or 1.
"""
result = runner.invoke(app, ["restart"])
assert result.exit_code == EXIT_UNVERIFIED
assert result.exit_code == ExitCode.UNVERIFIED
assert mock_stop.call_count == 1


Expand Down
1 change: 0 additions & 1 deletion tests/test_edge_paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,6 @@ def test_a_missing_transport_binary_is_named_by_its_standard_path():
tor_user="toranon",
transport_port=9041,
dns_port=9054,
block_doh=False,
use_bridges=True,
bridges=["obfs4 192.0.2.1:443 AAAA cert=x iat-mode=0"],
ipv6_avail=False,
Expand Down
2 changes: 1 addition & 1 deletion tests/test_leak_retry.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ def test_the_retry_budget_is_not_silently_disarmed():

The two tests above would still pass with a budget of one if their fixtures
were adjusted to match, so the budget itself is asserted here: it exists to
mirror `ttp.tor_control.verify_tor`, which makes five attempts.
mirror `ttp.probe.verify_session`, which makes five attempts.
"""
assert leak_ip._ATTEMPTS >= 5
assert leak_ip._BACKOFF_SECONDS >= 1
6 changes: 1 addition & 5 deletions tests/test_netprobe.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@

from ttp import netprobe, tor_control

URL = tor_control.VERIFY_ENDPOINTS[0]
URL = netprobe.ENDPOINTS[0]


# The child: what it may hand back -------------------------------------------
Expand Down Expand Up @@ -133,10 +133,6 @@ def test_without_root_the_fetch_stays_in_process():
run.assert_not_called()


def test_the_child_and_the_parent_agree_on_the_endpoints():
assert tuple(tor_control.VERIFY_ENDPOINTS) == netprobe.ENDPOINTS


def test_the_child_reads_a_bounded_body_and_parses_it():
response = MagicMock()
response.__enter__.return_value = response
Expand Down
149 changes: 0 additions & 149 deletions tests/test_tor_control.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,56 +139,6 @@ def test_wait_for_bootstrap_timeout(mock_get_ctrl, mock_sleep):
tor_control.wait_for_bootstrap()


# verify_tor


@patch("ttp.tor_control.time.sleep")
@patch("ttp.tor_control.urllib.request.urlopen")
def test_verify_tor_success(mock_urlopen, mock_sleep):
"""verify_tor returns (True, IP) when the primary endpoint responds."""
mock_resp = MagicMock()
mock_resp.read.return_value = b'{"IsTor": true, "IP": "8.8.8.8"}'
mock_urlopen.return_value.__enter__.return_value = mock_resp

is_tor, ip = tor_control.verify_tor()
assert is_tor is True
assert ip == "8.8.8.8"


@patch("ttp.tor_control.time.sleep")
@patch("ttp.tor_control.urllib.request.urlopen")
def test_verify_tor_retries(mock_urlopen, mock_sleep):
"""verify_tor retries all endpoints across all attempts before giving up."""
mock_urlopen.side_effect = urllib.error.URLError("Timeout")

is_tor, ip = tor_control.verify_tor()

assert is_tor is False
assert ip == "unknown"
# 5 attempts x 3 endpoints = 15 calls
assert mock_urlopen.call_count == 15


@patch("ttp.tor_control.time.sleep")
@patch("ttp.tor_control.urllib.request.urlopen")
def test_verify_tor_fallback_endpoint(mock_urlopen, mock_sleep):
"""With the primary down for every attempt, the fallback's IP is reported, is_tor=False."""
mock_resp = MagicMock()
mock_resp.read.return_value = b'{"ip": "9.9.9.9"}'

def _urlopen(req, timeout):
host = urllib.parse.urlparse(req.full_url).hostname
if host == "check.torproject.org":
raise urllib.error.URLError("Primary down")
return MagicMock(__enter__=MagicMock(return_value=mock_resp))

mock_urlopen.side_effect = _urlopen

is_tor, ip = tor_control.verify_tor()
assert is_tor is False
assert ip == "9.9.9.9"


# request_new_circuit


Expand Down Expand Up @@ -272,92 +222,6 @@ def test_graceful_shutdown_signal_exception(mock_get_ctrl, mock_sleep):
# ---------------------------------------------------------------------------


@pytest.mark.parametrize("index", [1, 2], ids=["ipify", "ifconfig-me"])
def test_a_fallback_reflector_cannot_assert_is_tor(index: int) -> None:
"""A fallback that answers with an IsTor field must not raise the verdict.

The fallbacks are ordinary IP echo services with no Tor knowledge. Making
check.torproject.org unreachable is free for anyone on the path -- it is
also routinely rate-limited for Tor clients -- so field presence alone
must never decide this.
"""
responses = [None] * len(tor_control.VERIFY_ENDPOINTS)
responses[index] = {"IsTor": True, "IP": "203.0.113.66"}

def _fetch(endpoint: str):
return responses[tor_control.VERIFY_ENDPOINTS.index(endpoint)]

with (
patch.object(tor_control, "_fetch_endpoint", side_effect=_fetch),
patch("time.sleep"),
):
is_tor, ip = tor_control.verify_tor()

assert is_tor is False
assert ip != "203.0.113.66"


def test_the_authoritative_endpoint_is_still_believed() -> None:
with (
patch.object(tor_control, "_fetch_endpoint", return_value={"IsTor": True, "IP": "185.220.101.7"}),
patch("time.sleep"),
):
assert tor_control.verify_tor() == (True, "185.220.101.7")


def test_a_censored_network_is_unchanged() -> None:
"""With the authoritative endpoint down, an honest fallback still reports."""
responses = [None, {"ip": "198.51.100.9"}, None]

def _fetch(endpoint: str):
return responses[tor_control.VERIFY_ENDPOINTS.index(endpoint)]

with (
patch.object(tor_control, "_fetch_endpoint", side_effect=_fetch),
patch("time.sleep"),
):
assert tor_control.verify_tor() == (False, "198.51.100.9")


def test_one_slow_answer_from_the_authority_does_not_decide_the_verdict() -> None:
"""A fallback that answers first must not end the attempts.

check.torproject.org is routinely slow or rate-limited for Tor clients, and
the first request over a freshly built circuit is the slowest of all. If it
misses once, the reflector's answer was returned at once as "not Tor" and
the four remaining attempts never asked the authority again - so `ttp start`
reported "Traffic is NOT reaching Tor" through a running Tor exit.
"""
authority = iter([None, {"IsTor": True, "IP": "185.220.101.7"}])

def _fetch(endpoint: str):
if endpoint == tor_control.VERIFY_ENDPOINTS[0]:
return next(authority)
return {"ip": "185.220.101.7"}

with (
patch.object(tor_control, "_fetch_endpoint", side_effect=_fetch),
patch("time.sleep"),
):
assert tor_control.verify_tor() == (True, "185.220.101.7")


def test_a_later_valid_fallback_answer_replaces_an_earlier_malformed_one() -> None:
"""With the authority down throughout, report the address we did get, not "malformed"."""
fallback = iter([{"ip": "not-an-ip"}] + [{"ip": "198.51.100.9"}] * 4)

def _fetch(endpoint: str):
if endpoint == tor_control.VERIFY_ENDPOINTS[0]:
return None
return next(fallback)

with (
patch.object(tor_control, "_fetch_endpoint", side_effect=_fetch),
patch("time.sleep"),
):
assert tor_control.verify_tor() == (False, "198.51.100.9")


@pytest.mark.parametrize(
"hostile",
[
Expand Down Expand Up @@ -446,16 +310,3 @@ def test_request_new_circuit_wraps_a_controller_error() -> None:
):
with pytest.raises(TorError, match="Failed to request new circuit"):
tor_control.request_new_circuit()


def test_the_authoritative_endpoint_answering_without_istor_is_not_an_upgrade() -> None:
"""A trusted origin with an unexpected shape must not fall through.

Letting the loop continue would hand the verdict to a fallback reflector,
which is exactly what the origin binding exists to prevent.
"""
with (
patch.object(tor_control, "_fetch_endpoint", return_value={"IP": "185.220.101.7"}),
patch("time.sleep"),
):
assert tor_control.verify_tor() == (False, "185.220.101.7")
4 changes: 2 additions & 2 deletions tests/test_tor_detect.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,8 +215,8 @@ def test_detect_tor_user_custom_passwd(mock_run):
mock_run.return_value = MagicMock(returncode=1) # ps fails
with patch("ttp.tor_detect.Path.read_text") as mock_read:
mock_read.return_value = "my-custom-tor:x:110:110::/var/lib/tor:/bin/false\n"
# Since 'my-custom-tor' is not in _KNOWN_USERS, it fallbacks to 'tor'
# Unless we update _KNOWN_USERS or improve detection.
# Since 'my-custom-tor' is not in TOR_ACCOUNTS, it fallbacks to 'tor'
# Unless we update TOR_ACCOUNTS or improve detection.
assert _detect_tor_user() == "tor"


Expand Down
Loading