feat: add configurable PID1-owned DoH forwarding

Default managed SOCKS hostname DNS to verified HTTPS with literal-IP bootstrap and no plaintext fallback. Supervise the loopback forwarder with private anchored readiness and preserve foreign markers. Include configuration, deployment, documentation and offline checks.

Co-authored-by: GPT-6 <gpt-6@openai.com>
This commit is contained in:
ZeusinaandGPT-6 Bot committed 2026-10-13 14:32:58 +03:00
1 parent ea886e5bc8
commit 367d956ae3
20 files changed
+2383 -37

No files matched your search

+8 -1
View File
@@ -6,5 +6,12 @@ ZAPRET_AUTOTUNE_VIDEO_ID=dQw4w9WgXcQ
# Missing/empty selects automatic YouTube inventory: primary + two public samples.
# Nonempty JSON overrides it: 1..5 unique 11-character VideoIDs (not signed URLs).
# ZAPRET_AUTOTUNE_GOOGLEVIDEO_VIDEO_IDS='["dQw4w9WgXcQ","aqz-KE-bpKQ","jNQXAC9IVRw"]'
# Optional target ss-server native DNS; empty retains the base resolver behavior.
# Encrypted target DNS for both SOCKS hostname traffic and managed checks.
ZAPRET_AUTOTUNE_DNS_MODE=doh
ZAPRET_AUTOTUNE_DOH_URL=https://dns.google/dns-query
# Empty selects Google bootstrap only for the exact default URL above.
# Custom provider: change URL AND supply its literal bootstrap IPs (comma-separated).
ZAPRET_AUTOTUNE_DOH_BOOTSTRAP_IPS=
ZAPRET_AUTOTUNE_DOH_TIMEOUT_SEC=5
# Explicit native mode only; ignored in doh mode. Never an automatic fallback.
SS_DNS_SERVER=
+43 -11
View File
@@ -202,14 +202,35 @@ asset checks cover sampled thumbnail/avatar routes, not the whole thumbnail pool
The current service/adaptive hardware acceptance gate is **pending**; the old
clean-run PASS below does not qualify these new modes.
Optional `SS_DNS_SERVER` is an unbracketed literal IPv4/IPv6 address only (for
example `8.8.8.8` or `2001:4860:4860::8888`); empty preserves existing resolver
behavior. No domain, port, zone, control characters or option strings are
accepted. Validation runs before service launch and reports opaque `configerror`
without echoing input. DNS applies only to this target's native `ss-server`.
The image build checks installed `ss-server -h` for native `-d <addr>` support;
the validated nonsecret address is passed as a separate `-d` argv value, not
eval or an assumed JSON key. Passwords still go only to private JSON configs.
**Managed DNS defaults to DoH**, independently of service/YouTube mode. PID 1
starts the stdlib Go forwarder on container loopback `127.0.0.1:5353` (UDP and
TCP), validates its private PID readiness acknowledgement, then starts ss-server
with `-d 127.0.0.1:5353`. No DNS port is published. Both client hostname traffic
and managed checks share this encrypted resolver path; it works for arbitrary
services, not only YouTube. HTTPS uses normal certificate verification, direct
literal-IP bootstrap and a socket mark excluding live/probe NFQUEUE rules;
there is no recursive SOCKS resolution or plaintext fallback. Endpoint errors
return SERVFAIL while the forwarder stays alive, rather than switching DNS modes.
The private `.env` controls `ZAPRET_AUTOTUNE_DNS_MODE=doh|native`,
`ZAPRET_AUTOTUNE_DOH_URL` (default `https://dns.google/dns-query`),
`ZAPRET_AUTOTUNE_DOH_BOOTSTRAP_IPS` (missing/empty selects `8.8.8.8,8.8.4.4`
**only for the exact default Google URL**; otherwise explicit 1–4 literal
IPs, comma-separated without spaces), and `ZAPRET_AUTOTUNE_DOH_TIMEOUT_SEC`
(default `5`, integer 1–30). Changing provider requires changing **both** URL
and bootstrap IPs. Compose/example leave bootstrap empty, so changing only the
URL cannot silently reuse Google bootstrap. URL must use HTTPS/443 with a path, without userinfo, query
or fragment. A path can contain a private provider token: do not print it.
Validation reports opaque errors before any services start. The subprocess
gets provider configuration through env, never endpoint argv/logging.
Only explicit `ZAPRET_AUTOTUNE_DNS_MODE=native` restores the old resolver
behavior, with no forwarder child. In that mode optional `SS_DNS_SERVER` accepts
only an unbracketed literal IPv4/IPv6 address; empty retains the base resolver.
It is ignored in DoH mode and is **not** a fallback. Native DNS can be plaintext.
The pinned ss-server's native `-d <addr>` is used, not an assumed JSON key;
passwords still go only to private JSON configs. No extra capability is added;
Compose sets container-local `ip_unprivileged_port_start=0` for port 5353.
Managed probes use `socks5h://127.0.0.1:1080`: Player, metadata, image,
media, recovery and warmup hostnames go through the owned SS listener rather than
curl's local DNS. Older private `socks5` overrides are validated and canonicalized
@@ -217,8 +238,13 @@ internally; credentials and unowned endpoints remain forbidden. Public legacy
discovery and root checker local `--resolve` pinning are unchanged.
This corrects a DNS path bypass, not a proven cause of earlier peer certificate
failures, and does not fix/prove all thumbnail routes. It is **not full asset
availability proof**. No DoH bridge, permanent Google IP pins or global host DNS
changes are supplied. PID 1 remains the sole startup/recovery owner.
availability proof**. No permanent service IP pins or global host DNS changes
are supplied. Clients must request remote DNS (browser SOCKS5 remote DNS or
`curl --socks5-hostname 127.0.0.1:11082` when that is the chosen host port).
Client-local resolution and IP-literal requests bypass this hostname DNS path;
the bridge does not encrypt unrelated container processes' DNS. The new DoH
integration still needs remote runtime acceptance; earlier clean-run PASS does
not qualify it. PID 1 remains the sole startup/recovery owner.
Compose has no automatic restart. PID 1 restarts the entire owned runtime only
for technical failures, with three starts per rolling six hours (including initial
@@ -283,7 +309,13 @@ Any startup command failure/timeout exits 78, never the retry code 75. These
bounds do not shorten the monitor's 90-minute bootstrap/recovery scan budget.
SIGTERM/SIGINT cancels and waits for the monitor before stopping target-local
zapret and Shadowsocks children. Nonretry monitor fatal exits stop the
zapret and Shadowsocks children, then terminates/joins DNS within five seconds
and removes only its anchored, validated readiness inode. PID 1 retains private
directory/file descriptors through child death, including SIGKILL. Preexisting,
replaced or symlink readiness evidence is preserved and fails closed rather
than being deleted for a restart. DNS remains available throughout rollback and
SS shutdown. A DNS child crash participates in the existing technical retry
budget; upstream outages do not kill that child. Nonretry monitor fatal exits stop the
entrypoint; technical exits and Shadowsocks failures restart from private configs
only after safe cleanup. Legacy monitor health is YouTube Player API status
through the owned SOCKS, not video playback/SABR; legacy GGC candidates are scoped
+46 -1
View File
@@ -32,7 +32,7 @@ with tempfile.TemporaryDirectory(prefix='target-config-') as tmp:
('example.org', False), ('8.8.8.8\n', False), ('-d 8.8.8.8', False)):
for path in private.iterdir():
path.unlink()
result = subprocess.run(['sh', str(entry)], env=dict(base, SS_DNS_SERVER=dns),
result = subprocess.run(['sh', str(entry)], env=dict(base, ZAPRET_AUTOTUNE_DNS_MODE='native', SS_DNS_SERVER=dns),
capture_output=True, timeout=5)
assert result.returncode == (0 if valid else 64), result.stderr
assert not result.stdout and base['SS_PASSWORD'].encode() not in result.stderr
@@ -43,6 +43,24 @@ with tempfile.TemporaryDirectory(prefix='target-config-') as tmp:
path = private / (name + '.json')
assert path.stat().st_mode & 0o777 == 0o600
assert json.loads(path.read_text())['password'] == base['SS_PASSWORD']
for overrides, valid in (({}, True), ({'SS_DNS_SERVER': 'ignored.example'}, True),
({'ZAPRET_AUTOTUNE_DOH_BOOTSTRAP_IPS': ''}, True),
({'ZAPRET_AUTOTUNE_DNS_MODE': ''}, False),
({'ZAPRET_AUTOTUNE_DOH_URL': 'http://secret.invalid/token'}, False),
({'ZAPRET_AUTOTUNE_DOH_URL': 'https://secret.invalid/token'}, False),
({'ZAPRET_AUTOTUNE_DOH_URL': 'https://secret.invalid/token',
'ZAPRET_AUTOTUNE_DOH_BOOTSTRAP_IPS': ''}, False),
({'ZAPRET_AUTOTUNE_DOH_URL': 'https://secret.invalid/token',
'ZAPRET_AUTOTUNE_DOH_BOOTSTRAP_IPS': '192.0.2.1'}, True),
({'ZAPRET_AUTOTUNE_DOH_TIMEOUT_SEC': '31'}, False)):
for path in private.iterdir():
path.unlink()
result = subprocess.run(['sh', str(entry)], env=dict(base, **overrides), capture_output=True, timeout=5)
assert result.returncode == (0 if valid else 64), result.stderr
assert b'secret.invalid' not in result.stderr and b'token' not in result.stderr
assert base['SS_PASSWORD'].encode() not in result.stdout + result.stderr
if not valid:
assert not list(private.iterdir())
# Render privately, never print the config/password; config does not deploy.
compose_env = {k: v for k, v in base.items() if not k.startswith('ZAPRET_AUTOTUNE_')}
factory_cases = []
@@ -74,9 +92,36 @@ with tempfile.TemporaryDirectory(prefix='target-config-') as tmp:
assert settings['ZAPRET_AUTOTUNE_GOOGLEVIDEO_MODE'] == mode
assert settings['ZAPRET_AUTOTUNE_GOOGLEVIDEO_VIDEO_IDS'] == overrides.get('ZAPRET_AUTOTUNE_GOOGLEVIDEO_VIDEO_IDS', '')
assert settings['SS_DNS_SERVER'] == overrides.get('SS_DNS_SERVER', '')
assert settings['ZAPRET_AUTOTUNE_DNS_MODE'] == 'doh'
assert settings['ZAPRET_AUTOTUNE_DOH_URL'] == 'https://dns.google/dns-query'
assert settings['ZAPRET_AUTOTUNE_DOH_BOOTSTRAP_IPS'] == ''
assert settings['ZAPRET_AUTOTUNE_DOH_TIMEOUT_SEC'] == '5'
assert settings['ZAPRET_AUTOTUNE_SOCKS_PROXY'] == 'socks5h://127.0.0.1:1080'
factory_cases.append({'environment': {k: v for k, v in settings.items()
if k.startswith('ZAPRET_AUTOTUNE_')}, 'ids': ids})
# Validate the actual rendered DNS environment, not an invented equivalent.
# Compose must not inject Google bootstrap into a custom-provider request.
for service in ('0', '1'):
for provider in ({}, {'ZAPRET_AUTOTUNE_DOH_URL': 'https://secret.invalid/token'}):
for bootstrap in ({}, {'ZAPRET_AUTOTUNE_DOH_BOOTSTRAP_IPS': ''},
{'ZAPRET_AUTOTUNE_DOH_BOOTSTRAP_IPS': '192.0.2.1'}):
overrides = dict(provider, **bootstrap, ZAPRET_AUTOTUNE_YOUTUBE_SERVICE=service)
result = subprocess.run(['docker', 'compose', '--env-file', '/dev/null', '-f',
str(ROOT / 'deploy/managed-target/compose.yaml'),
'config', '--format', 'json'], env=dict(compose_env, **overrides),
capture_output=True, timeout=10)
assert result.returncode == 0, 'Compose config failed (output suppressed)'
settings = json.loads(result.stdout)['services']['target']['environment']
assert settings['ZAPRET_AUTOTUNE_DOH_BOOTSTRAP_IPS'] == bootstrap.get('ZAPRET_AUTOTUNE_DOH_BOOTSTRAP_IPS', '')
for path in private.iterdir():
path.unlink()
validated = subprocess.run(['sh', str(entry)], env=dict(env, **settings), capture_output=True, timeout=5)
valid = not provider or bool(bootstrap.get('ZAPRET_AUTOTUNE_DOH_BOOTSTRAP_IPS'))
assert validated.returncode == (0 if valid else 64), 'Rendered DNS config validation failed'
assert b'secret.invalid' not in validated.stderr and b'token' not in validated.stderr
assert base['SS_PASSWORD'].encode() not in validated.stdout + validated.stderr
if not valid:
assert not list(private.iterdir()), 'Invalid DNS config created service configs'
# Only sanitized fixture settings cross into Go; never persist the password.
fixture = root / 'compose-factory.json'
fixture.write_text(json.dumps(factory_cases))
+15 -1
View File
@@ -23,6 +23,10 @@ assert " create_host_path: false\n" in compose
assert "SS_PASSWORD: ${SS_PASSWORD:?Set SS_PASSWORD in the deployment environment}" in compose
for setting in (
'SS_DNS_SERVER: ${SS_DNS_SERVER-}',
'ZAPRET_AUTOTUNE_DNS_MODE: ${ZAPRET_AUTOTUNE_DNS_MODE-doh}',
'ZAPRET_AUTOTUNE_DOH_URL: ${ZAPRET_AUTOTUNE_DOH_URL-https://dns.google/dns-query}',
'ZAPRET_AUTOTUNE_DOH_BOOTSTRAP_IPS: ${ZAPRET_AUTOTUNE_DOH_BOOTSTRAP_IPS-}',
'ZAPRET_AUTOTUNE_DOH_TIMEOUT_SEC: ${ZAPRET_AUTOTUNE_DOH_TIMEOUT_SEC-5}',
'ZAPRET_AUTOTUNE_YOUTUBE_SERVICE: ${ZAPRET_AUTOTUNE_YOUTUBE_SERVICE-0}',
'ZAPRET_AUTOTUNE_GOOGLEVIDEO_MODE: ${ZAPRET_AUTOTUNE_GOOGLEVIDEO_MODE-cold}',
'ZAPRET_AUTOTUNE_VIDEO_ID: ${ZAPRET_AUTOTUNE_VIDEO_ID-dQw4w9WgXcQ}',
@@ -30,7 +34,17 @@ for setting in (
):
assert setting in compose, setting
assert entrypoint.index('target-config-check || exit 64') < entrypoint.index('cat > "$config_dir/server.json"')
assert 'set -- "$@" -d "$SS_DNS_SERVER"' in entrypoint
assert 'set -- "$@" -d "$dns_address"' in entrypoint
assert entrypoint.index('start_dns || return $?') < entrypoint.index('set -- ss-server')
assert 'dns-forwarder readiness-check "$dns_pid"' in entrypoint
assert 'dns-forwarder readiness-cleanup "$dns_pid"' in entrypoint
assert 'exec 8<"$config_dir"' in entrypoint
assert 'exec 9<"$config_dir/dns-ready"' in entrypoint
assert 'rm -f "$config_dir/dns-ready"' not in entrypoint
assert 'while dns_alive && kill -0 "$server_pid"' in entrypoint
assert entrypoint.index('bounded_wait "$pid" 5') < entrypoint.index('bounded_wait "$dns_pid" 5')
assert '5353' not in compose
assert 'net.ipv4.ip_unprivileged_port_start: "0"' in compose
assert 'eval ' not in entrypoint
assert "secrets:" not in compose
assert "ss_password=${SS_PASSWORD-}" in entrypoint
+140 -6
View File
@@ -4,6 +4,7 @@ Only a temporary COPY of the entrypoint is redirected to fake executables;
production has no test switches, real network probes, or accelerated timers.
"""
import ctypes
import atexit
import os
from pathlib import Path
import shutil
@@ -13,6 +14,15 @@ import time
ROOT = Path(__file__).resolve().parents[2]
# Real readiness CLI checks root ownership. Use an isolated user namespace for
# offline fixtures when invoked as an ordinary user; no host-root requirement.
if os.geteuid() != 0:
os.execvp('unshare', ['unshare', '-Ur', 'python3', str(Path(__file__).resolve())])
CLI_TMP = tempfile.TemporaryDirectory(prefix='dns-readiness-cli-')
atexit.register(CLI_TMP.cleanup)
DNS_CLI = Path(CLI_TMP.name) / 'autotune'
subprocess.run(['go', 'build', '-o', str(DNS_CLI), './cmd/zapret-autotune'],
cwd=ROOT, env=dict(os.environ, GOPROXY='off', GOTOOLCHAIN='local'), check=True)
FAKE = r'''#!/usr/bin/env python3
import ctypes, os, pathlib, signal, subprocess, sys, time
root = pathlib.Path(os.environ['FIXTURE'])
@@ -27,7 +37,11 @@ def increment(key):
path.write_text(str(n))
return n
def linger(code=0):
signal.signal(signal.SIGTERM, lambda *_: sys.exit(code))
def stop(*_):
if os.environ.get('ZAPRET_AUTOTUNE_DNS_MODE', 'doh') == 'doh' and scenario not in ('dns-death', 'dns-killed', 'dns-replace', 'dns-replace-symlink', 'dns-prestart'):
os.kill(int((root / 'dns-pid').read_text()), 0)
sys.exit(code)
signal.signal(signal.SIGTERM, stop)
while True:
time.sleep(.01)
def assert_workers_gone():
@@ -74,8 +88,12 @@ if name in ('ss-server', 'ss-local'):
f.write(str(os.getpid()) + '\n')
assert 'SS_PASSWORD' not in os.environ
assert sys.argv[1] == '-c'
dns = os.environ.get('SS_DNS_SERVER', '') if name == 'ss-server' else ''
dns = ('127.0.0.1:5353' if os.environ.get('ZAPRET_AUTOTUNE_DNS_MODE', 'doh') == 'doh'
else os.environ.get('SS_DNS_SERVER', '')) if name == 'ss-server' else ''
assert sys.argv[3:] == (['-d', dns] if dns else [])
if dns == '127.0.0.1:5353':
assert (root / 'private' / 'dns-ready').read_text().strip() == (root / 'dns-pid').read_text()
os.kill(int((root / 'dns-pid').read_text()), 0)
assert (pathlib.Path(sys.argv[2]).stat().st_mode & 0o777) == 0o600
log(name)
if name == 'ss-local' and scenario in ('ss', 'mixed', 'joinfail') and increment('ss_runs') == 1:
@@ -96,6 +114,71 @@ if name == 'zapret2':
assert name == 'autotune'
if sys.argv[1:] == ['target-config-check']:
sys.exit(0)
if sys.argv[1] == 'dns-forwarder':
if sys.argv[2] in ('readiness-check', 'readiness-cleanup'):
# exec preserves PID1's actual inherited anchors; no simulated unlink.
os.execv(os.environ['DNS_CLI'], [os.environ['DNS_CLI'], *sys.argv[1:]])
mode = os.environ.get('ZAPRET_AUTOTUNE_DNS_MODE', 'doh')
if sys.argv[2] == 'mode':
print(mode)
sys.exit(0)
if sys.argv[2] == 'address':
print('127.0.0.1:5353' if mode == 'doh' else os.environ.get('SS_DNS_SERVER', ''))
sys.exit(0)
assert sys.argv[2:] == ['serve'] and mode == 'doh'
assert 'SS_PASSWORD' not in os.environ
with (root / 'children').open('a') as f:
f.write(str(os.getpid()) + '\n')
(root / 'dns-pid').write_text(str(os.getpid()))
log('dns-start')
if scenario == 'dns-early':
sys.exit(1)
ready = root / 'private' / 'dns-ready'
owned = None
if scenario == 'dns-preack-foreign':
ready.write_text('foreign evidence\n')
sys.exit(1)
if scenario not in ('dns-noack', 'dns-term', 'dns-int'):
with ready.open('x') as f:
os.chmod(ready, 0o600)
f.write(str(os.getpid() + (1 if scenario == 'dns-wrongack' else 0)) + '\n')
owned = ready.stat()
if scenario == 'dns-permissions':
ready.chmod(0o644)
if scenario == 'dns-symlink':
payload = ready.with_name('dns-payload')
ready.rename(payload)
ready.symlink_to(payload)
log('dns-ready')
def stop_dns(*_):
assert not (root / 'prepared').exists(), 'DNS stopped before restoration'
# SS children have been joined, not merely signalled.
for pid in (root / 'children').read_text().splitlines():
if int(pid) != os.getpid():
assert not pathlib.Path('/proc/' + pid).exists(), ('DNS stopped before child join', pid)
log('dns-stop')
if ready.exists() and not ready.is_symlink() and owned and os.path.samestat(owned, ready.stat()):
ready.unlink()
sys.exit(0)
signal.signal(signal.SIGTERM, stop_dns)
if scenario in ('dns-term', 'dns-int'):
os.kill(os.getppid(), signal.SIGTERM if scenario == 'dns-term' else signal.SIGINT)
if scenario in ('dns-death', 'dns-killed', 'dns-replace', 'dns-replace-symlink') and increment('dns_runs') == 1:
while not (root / 'monitor_runs').exists():
time.sleep(.01)
if scenario.startswith('dns-replace'):
# Retain old inode so a replacement cannot reuse its number.
ready.rename(ready.with_name('retired-ready'))
payload = ready.with_name('foreign-ready')
payload.write_text('foreign evidence\n')
payload.chmod(0o600)
if scenario == 'dns-replace-symlink':
ready.symlink_to(payload)
else:
payload.rename(ready)
os.kill(os.getpid(), signal.SIGKILL)
while True:
time.sleep(.01)
command = sys.argv[2]
if command == 'init':
log('init')
@@ -107,6 +190,9 @@ elif command == 'reconcile':
assert_workers_gone()
if scenario == 'prestartfail':
sys.exit(78)
if scenario == 'dns-prestart':
os.kill(int((root / 'dns-pid').read_text()), signal.SIGKILL)
time.sleep(.03)
if scenario in ('unknown', 'unknown75') and n == 2:
sys.exit(78)
(root / 'prepared').unlink(missing_ok=True)
@@ -116,6 +202,11 @@ elif command == 'monitor':
n = increment('monitor_runs')
log('monitor ' + str(n))
assert os.getsid(0) == os.getpid(), 'monitor not in its own verified session'
if scenario in ('dns-death', 'dns-killed', 'dns-replace', 'dns-replace-symlink') and n == 1:
linger()
if scenario == 'dns-outage':
# Upstream SERVFAIL is modelled by a live DNS child, not child failure.
assert (root / 'dns-pid').exists()
if n == 1 and scenario == 'orphans':
subprocess.Popen([str(root / 'bin' / 'blockcheck')], preexec_fn=os.setpgrp)
while not (root / 'workers').exists() or len((root / 'workers').read_text().splitlines()) != 2:
@@ -144,7 +235,7 @@ elif command == 'monitor':
'''
def run(scenario, expected, dns=''):
def run(scenario, expected, dns='', mode='native'):
with tempfile.TemporaryDirectory(prefix='supervision-') as tmp:
root = Path(tmp)
binary = root / 'bin'
@@ -156,6 +247,11 @@ def run(scenario, expected, dns=''):
(binary / name).symlink_to(fake)
configs = root / 'private'
configs.mkdir()
if scenario.startswith('dns-stale'):
if scenario == 'dns-stale-symlink':
(configs / 'dns-ready').symlink_to(configs / 'missing')
else:
(configs / 'dns-ready').write_text('foreign evidence\n')
text = (ROOT / 'managed-target-entrypoint.sh').read_text()
helper = ROOT / 'managed-target-supervision.sh'
if scenario == 'ackfail':
@@ -170,7 +266,11 @@ def run(scenario, expected, dns=''):
entry.write_text(text)
env = dict(os.environ, PATH=f'{binary}:{os.environ["PATH"]}', FIXTURE=tmp,
SCENARIO=scenario, SS_PASSWORD='ab' * 32, SS_DNS_SERVER=dns,
ZAPRET_CONFIG=str(root / 'config'))
ZAPRET_CONFIG=str(root / 'config'), DNS_CLI=str(DNS_CLI))
if mode is None:
env.pop('ZAPRET_AUTOTUNE_DNS_MODE', None)
else:
env['ZAPRET_AUTOTUNE_DNS_MODE'] = mode
peer = None
if scenario == 'orphans':
# Local fixture is not PID 1. Adopt orphan workers here so the test
@@ -186,10 +286,10 @@ def run(scenario, expected, dns=''):
if peer:
peer.terminate()
peer.wait(timeout=2)
events = (root / 'events').read_text().splitlines()
events = (root / 'events').read_text().splitlines() if (root / 'events').exists() else []
assert result.returncode == expected, (scenario, result.returncode, result.stderr, events)
assert b'ab' * 32 not in result.stdout + result.stderr
for pid in (root / 'children').read_text().splitlines():
for pid in ((root / 'children').read_text().splitlines() if (root / 'children').exists() else []):
assert not Path(f'/proc/{pid}').exists(), (scenario, 'child not joined', pid)
if scenario == 'orphans':
for pid in (root / 'workers').read_text().splitlines():
@@ -205,6 +305,16 @@ def run(scenario, expected, dns=''):
for i, event in enumerate(events):
if event in ('start', 'stop'):
assert events[i - 1] == 'reconcile', (scenario, events)
foreign = scenario in ('dns-symlink', 'dns-preack-foreign', 'dns-replace', 'dns-replace-symlink', 'dns-stale', 'dns-stale-symlink')
if foreign:
ready = configs / 'dns-ready'
assert ready.exists() or ready.is_symlink(), (scenario, 'foreign readiness deleted')
if scenario != 'dns-stale-symlink' and scenario != 'dns-symlink':
assert ready.read_text() == 'foreign evidence\n', (scenario, 'foreign bytes changed')
else:
assert not (configs / 'dns-ready').exists(), (scenario, 'stale DNS readiness')
if mode == 'native':
assert 'dns-start' not in events
return events
@@ -233,6 +343,30 @@ for dns in ('8.8.8.8', '2001:4860:4860::8888'):
events = run('fatal64', 64, dns)
assert events.count('ss-server') == 1 and events.count('ss-local') == 1
for scenario in ('dns-outage', 'technical', 'ss', 'cancel', 'dns-death', 'dns-killed'):
events = run(scenario, 0, dns='8.8.8.8', mode=None)
assert events.index('dns-ready') < events.index('ss-server')
assert events.index('dns-ready') < events.index('ss-local')
if scenario not in ('dns-death', 'dns-killed'):
assert events.count('dns-start') == events.count('dns-stop')
assert events.index('stop') < events.index('dns-stop')
if scenario == 'dns-outage':
assert events.count('start') == 1 and 'cooldown 15' not in events
for scenario, code in (('dns-early', 78), ('dns-noack', 78), ('dns-wrongack', 78),
('dns-permissions', 78), ('dns-symlink', 78), ('dns-prestart', 78)):
events = run(scenario, code, mode='doh')
assert not any(e.startswith('monitor ') for e in events)
if scenario != 'dns-prestart':
assert 'ss-server' not in events and 'ss-local' not in events
for scenario in ('dns-stale', 'dns-stale-symlink', 'dns-preack-foreign', 'dns-replace', 'dns-replace-symlink'):
events = run(scenario, 78, mode='doh')
assert events.count('dns-start') <= 1 and 'cooldown 15' not in events
if scenario.startswith('dns-stale'):
assert not events
for scenario in ('dns-term', 'dns-int'):
events = run(scenario, 0, mode='doh')
assert events == ['dns-start', 'dns-stop'], events
def check_watchdog_traps(shell):
"""Same bounded_wait from normal flow, plain EXIT, and TERM -> EXIT traps."""
+6
View File
@@ -13,6 +13,10 @@ services:
environment:
SS_PASSWORD: ${SS_PASSWORD:?Set SS_PASSWORD in the deployment environment}
SS_DNS_SERVER: ${SS_DNS_SERVER-}
ZAPRET_AUTOTUNE_DNS_MODE: ${ZAPRET_AUTOTUNE_DNS_MODE-doh}
ZAPRET_AUTOTUNE_DOH_URL: ${ZAPRET_AUTOTUNE_DOH_URL-https://dns.google/dns-query}
ZAPRET_AUTOTUNE_DOH_BOOTSTRAP_IPS: ${ZAPRET_AUTOTUNE_DOH_BOOTSTRAP_IPS-}
ZAPRET_AUTOTUNE_DOH_TIMEOUT_SEC: ${ZAPRET_AUTOTUNE_DOH_TIMEOUT_SEC-5}
ZAPRET_AUTOTUNE_YOUTUBE_SERVICE: ${ZAPRET_AUTOTUNE_YOUTUBE_SERVICE-0}
ZAPRET_AUTOTUNE_GOOGLEVIDEO_MODE: ${ZAPRET_AUTOTUNE_GOOGLEVIDEO_MODE-cold}
ZAPRET_AUTOTUNE_VIDEO_ID: ${ZAPRET_AUTOTUNE_VIDEO_ID-dQw4w9WgXcQ}
@@ -38,6 +42,8 @@ services:
networks: [target]
restart: "no"
stop_grace_period: 240s
sysctls:
net.ipv4.ip_unprivileged_port_start: "0"
networks:
target:
driver: bridge