This commit is contained in:
Mateusz Gruszczyński committed 2026-11-28 17:36:53 +01:00
1 parent 5b6d4a7903
commit 4d1087e357
160 files changed
+2407 -1933

No files matched your search

+2 -4
View File
@@ -2,8 +2,8 @@
"""Install/update a local release binary on Linux/systemd. No builds."""
from __future__ import annotations
from deploy_core import * # stable public helper surface used by release checks
from deploy_runtime import * # stable install/update helper surface
from deploy_core import *
from deploy_runtime import *
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
@@ -75,7 +75,5 @@ def main() -> None:
except (OSError, ValueError, RuntimeError, subprocess.SubprocessError, KeyError) as error:
parser.exit(1, f'Deployment failed: {error}\n')
if __name__ == '__main__':
main()
-32
View File
@@ -45,15 +45,12 @@ GEOIP_MAX_BYTES = 256 * 1024 * 1024
GEOIP_FETCH_ATTEMPTS = 4
GEOIP_RETRY_DELAYS = (3, 6, 12)
class GeoipUnavailable(RuntimeError):
"""The GeoIP CSV download failed after retries; the deployment itself can continue."""
def run(args: list[str], **kwargs) -> subprocess.CompletedProcess:
return subprocess.run(args, check=True, stdin=subprocess.DEVNULL, **kwargs)
def safe_path(raw: str) -> Path:
if not re.fullmatch(r'/[A-Za-z0-9_./-]+', raw) or '..' in raw.split('/') or raw in ('/', '/etc', '/var', '/opt', '/usr', '/var/lib'):
raise ValueError('Use a dedicated absolute path with no spaces, traversal or shell characters.')
@@ -63,7 +60,6 @@ def safe_path(raw: str) -> Path:
raise ValueError(f'Symlinked installation/data path is not allowed: {part}')
return p
def address(raw: str, loopback: bool = False, allow_remote: bool = False) -> str:
if raw.startswith('['):
host, port = raw[1:].split(']:', 1)
@@ -76,14 +72,10 @@ def address(raw: str, loopback: bool = False, allow_remote: bool = False) -> str
raise ValueError('Administration must use loopback unless remote administration is explicitly accepted.')
return f'[{ip}]:{int(port)}' if ip.version == 6 else f'{ip}:{int(port)}'
def listener_ip(raw: str) -> ipaddress.IPv4Address | ipaddress.IPv6Address:
host = raw[1:].split(']:', 1)[0] if raw.startswith('[') else raw.rsplit(':', 1)[0]
return ipaddress.ip_address(host)
def admin_address(raw: str, allow_remote: bool = False) -> tuple[str, bool]:
value = address(raw)
ip = listener_ip(value)
@@ -99,7 +91,6 @@ def digest(path: Path) -> str:
result.update(block)
return result.hexdigest()
def _fetch_https_once(url: str, max_bytes: int) -> bytes:
if urllib.parse.urlparse(url).scheme != 'https':
raise ValueError('GeoIP downloads require HTTPS.')
@@ -120,7 +111,6 @@ def _fetch_https_once(url: str, max_bytes: int) -> bytes:
raise ValueError('GeoIP download exceeded the configured safety limit.')
return bytes(result)
def fetch_https(url: str, max_bytes: int) -> bytes:
"""Download with retries; transient gateway/network failures (502/503/504, timeouts) are retried."""
last: BaseException | None = None
@@ -139,7 +129,6 @@ def fetch_https(url: str, max_bytes: int) -> bytes:
time.sleep(delay)
raise GeoipUnavailable(f'GeoIP download from {url} failed: {last}')
def acquire_geoip_update_lock(data: Path, uid: int | None = None, gid: int | None = None) -> int:
"""Serialize installer/manual GeoIP refresh with the in-process worker."""
path = data / '.geoip-update.lock'
@@ -157,7 +146,6 @@ def acquire_geoip_update_lock(data: Path, uid: int | None = None, gid: int | Non
os.close(fd)
raise
def release_geoip_update_lock(fd: int | None) -> None:
if fd is None:
return
@@ -166,7 +154,6 @@ def release_geoip_update_lock(fd: int | None) -> None:
finally:
os.close(fd)
def validate_geoip_csv(name: str, payload: bytes) -> None:
"""Reject truncated/error payloads before a GeoIP CSV is published."""
family = 4 if name == 'user-country-ipv4.csv' else 6
@@ -200,7 +187,6 @@ def validate_geoip_csv(name: str, payload: bytes) -> None:
if rows == 0:
raise ValueError(f'GeoIP {name} does not contain any address ranges.')
def geoip_file_digest(path: Path) -> str | None:
try:
st = path.lstat()
@@ -210,7 +196,6 @@ def geoip_file_digest(path: Path) -> str | None:
return None
return digest(path)
def prepare_geoip_update(data: Path, prefix: Path) -> tuple[Path | None, list[str]]:
"""Download and validate current GeoIP CSVs before service downtime.
@@ -243,7 +228,6 @@ def prepare_geoip_update(data: Path, prefix: Path) -> tuple[Path | None, list[st
shutil.rmtree(staging, ignore_errors=True)
raise
def copy_private(source: Path, target: Path, mode: int = 0o600) -> None:
temporary = target.with_name(target.name + '.' + uuid.uuid4().hex + '.tmp')
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, mode)
@@ -260,7 +244,6 @@ def copy_private(source: Path, target: Path, mode: int = 0o600) -> None:
finally:
temporary.unlink(missing_ok=True)
def apply_geoip_update(data: Path, staging: Path | None, names: list[str], uid: int, gid: int) -> None:
if not names:
return
@@ -279,10 +262,7 @@ def apply_geoip_update(data: Path, staging: Path | None, names: list[str], uid:
os.chown(target, uid, gid)
print('GeoIP database updated: ' + ', '.join(names))
def download_geoip(data: Path, uid: int, gid: int) -> None:
# First install has no code-prefix staging transaction. Validate each direct
# payload before publishing it atomically into the private data directory.
directory = data / 'geoip'
if directory.exists() and directory.is_symlink():
raise ValueError('GeoIP directory cannot be a symlink.')
@@ -296,7 +276,6 @@ def download_geoip(data: Path, uid: int, gid: int) -> None:
write_private(target, payload, 0o600)
os.chown(target, uid, gid)
def write_private(path: Path, value: bytes, mode: int = 0o600) -> None:
temporary = path.with_name(path.name + '.' + uuid.uuid4().hex + '.tmp')
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, mode)
@@ -312,7 +291,6 @@ def write_private(path: Path, value: bytes, mode: int = 0o600) -> None:
finally:
temporary.unlink(missing_ok=True)
def shell_path_profile(prefix: Path) -> bytes:
binary_dir = prefix / 'current'
return (
@@ -323,13 +301,10 @@ def shell_path_profile(prefix: Path) -> bytes:
'esac\n'
).encode()
def install_shell_path(prefix: Path) -> None:
write_private(SHELL_PATH_PROFILE, shell_path_profile(prefix), 0o644)
def logrotate_config(user: str, group: str) -> bytes:
# User/group are validated system account names, never interpolated from a request.
for value in (user, group):
if not re.fullmatch(r'[a-z_][a-z0-9_-]*\$?', value):
raise ValueError('Unsafe service account for logrotate configuration.')
@@ -340,12 +315,10 @@ def logrotate_config(user: str, group: str) -> bytes:
f' su {user} {group}\n'
'}\n').encode()
def install_logrotate(record: dict) -> None:
"""Keep logrotate in sync with the actual managed service account."""
write_private(LOGROTATE_PATH, logrotate_config(record['user'], record['group']), 0o644)
def check_shell_path(prefix: Path) -> bool:
expected = shell_path_profile(prefix)
try:
@@ -361,7 +334,6 @@ def check_shell_path(prefix: Path) -> bool:
)
return valid
def read_record(prefix: Path) -> dict:
path = prefix / 'install.json'
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
@@ -381,12 +353,10 @@ def read_record(prefix: Path) -> dict:
value['remote_admin'] = remote_admin
return value
def validate_user(name: str) -> None:
if not re.fullmatch(r'[a-z_][a-z0-9_-]{0,30}', name) or name in ('root', 'nobody'):
raise ValueError('Use a dedicated non-root service account.')
def service_unit(record: dict) -> str:
prefix, data, user = record['prefix'], record['data_dir'], record['user']
args = f'{prefix}/current/rust-proxy --data-dir {data} --admin-listen {record["admin"]} serve'
@@ -441,5 +411,3 @@ LockPersonality=true
[Install]
WantedBy=multi-user.target
'''
+2 -27
View File
@@ -1,7 +1,7 @@
"""Runtime install/update operations for deploy.py."""
from __future__ import annotations
from deploy_core import * # re-exported internal deployment primitives
from deploy_core import *
ACME_RUNTIME_NAMES = frozenset({'acme-python', 'acme-python.installing', 'acme-python.virtualenv-bootstrap'})
RUNTIME_STATE_NAMES = frozenset({'.geoip-update.lock'})
@@ -117,13 +117,11 @@ def restore_managed_acme_runtime(failed: Path, restored: Path) -> None:
except OSError:
shutil.copytree(source, target, symlinks=True)
def chown_tree(path: Path, uid: int, gid: int) -> None:
os.chown(path, uid, gid)
for child in path.rglob('*'):
os.chown(child, uid, gid, follow_symlinks=False)
def ensure_service_data_access(data: Path, account) -> None:
"""Repair the managed data-root metadata and verify service-user traversal.
@@ -153,7 +151,6 @@ def ensure_service_data_access(data: Path, account) -> None:
'check execute/search permissions on its parent directories (for example with namei -l).'
)
def switch(prefix: Path, release: str) -> None:
if not re.fullmatch(r'[A-Za-z0-9_.-]+', release) or '..' in release:
raise ValueError('Invalid release name.')
@@ -161,7 +158,6 @@ def switch(prefix: Path, release: str) -> None:
os.symlink('releases/' + release, temporary)
os.replace(temporary, prefix / 'current')
def running_release_matches(record: dict) -> bool:
"""Check the actual systemd process executable without publishing a version API.
@@ -181,7 +177,6 @@ def running_release_matches(record: dict) -> bool:
except (OSError, ValueError, KeyError, subprocess.SubprocessError):
return False
def admin_health_endpoint(record: dict) -> tuple[str, bool, str]:
"""Resolve the active persisted administration listener and scheme.
@@ -211,7 +206,6 @@ def admin_health_endpoint(record: dict) -> tuple[str, bool, str]:
if isinstance(values, list):
allowed_hosts = [str(value).strip() for value in values if str(value).strip()]
except (OSError, sqlite3.Error, ValueError, TypeError, json.JSONDecodeError):
# Fall back to the startup listener for old or uninitialized databases.
pass
host, port = (raw[1:].split(']:') if raw.startswith('[') else raw.rsplit(':', 1))
@@ -226,13 +220,11 @@ def admin_health_endpoint(record: dict) -> tuple[str, bool, str]:
connect_raw = f'[{connect_host}]:{port}' if ':' in connect_host else f'{connect_host}:{port}'
return connect_raw, tls, authority
def healthy(record: dict, version: str, attempts: int = 30) -> bool:
raw, tls, health_host = admin_health_endpoint(record)
host, port = (raw[1:].split(']:') if raw.startswith('[') else raw.rsplit(':', 1))
for _ in range(attempts):
if tls:
# Local liveness probe only; the admin certificate may be self-signed.
conn = http.client.HTTPSConnection(host, int(port), timeout=2, context=ssl._create_unverified_context())
else:
conn = http.client.HTTPConnection(host, int(port), timeout=2)
@@ -251,7 +243,6 @@ def healthy(record: dict, version: str, attempts: int = 30) -> bool:
time.sleep(1)
return False
def stage(binary: Path, prefix: Path, user: str, sha: str) -> tuple[str, str]:
release = 'build-' + sha[:24]
releases = prefix / 'releases'; releases.mkdir(mode=0o755, exist_ok=True); os.chmod(releases, 0o755)
@@ -265,16 +256,13 @@ def stage(binary: Path, prefix: Path, user: str, sha: str) -> tuple[str, str]:
shutil.rmtree(directory); raise
if directory.is_symlink() or (directory / 'rust-proxy').is_symlink() or digest(directory / 'rust-proxy') != sha:
raise ValueError('Staged binary checksum mismatch.')
# Never execute the supplied binary as root, even for its version banner.
result = run(['runuser', '-u', user, '--', str(directory / 'rust-proxy'), '--version'], capture_output=True, text=True, timeout=15)
matched = re.fullmatch(r'(?:rust-proxy|RustProxy) (\d+\.\d+\.\d+(?:[-+][\w.-]+)?)\s*', result.stdout)
if not matched:
raise ValueError('Binary did not return a RustProxy version.')
return release, matched[1]
def backup_stopped(record: dict, prefix: Path) -> Path:
# Service stop must happen before this call: ACME files and SQLite form one backup.
data = Path(record['data_dir'])
lock_fd = os.open(data / 'process.lock', os.O_WRONLY | os.O_CREAT | os.O_NOFOLLOW, 0o600)
try:
@@ -290,7 +278,6 @@ def backup_stopped(record: dict, prefix: Path) -> Path:
finally:
os.close(lock_fd)
def restore_service_unit(backup: Path) -> None:
saved = backup / 'rustproxy.service'
if saved.exists():
@@ -299,7 +286,6 @@ def restore_service_unit(backup: Path) -> None:
UNIT_PATH.unlink(missing_ok=True)
run(['systemctl', 'daemon-reload'])
def reset_saved_config(data: Path) -> None:
"""Development-only reset of desired config while preserving auth/certs/audit data."""
database = data / 'config.sqlite3'
@@ -316,7 +302,6 @@ def reset_saved_config(data: Path) -> None:
connection.close()
print('Stored vhost/settings configuration cleared; account, certificates and other private data were preserved.')
def service_failure_details() -> str:
chunks: list[str] = []
commands = (
@@ -333,7 +318,6 @@ def service_failure_details() -> str:
pass
return '\n'.join(chunks)[-8000:]
def stop_for_managed_update(data: Path) -> None:
"""Ask RustProxy 0.14.0+ to force hot cache into the enabled cold tier before exit.
@@ -349,26 +333,21 @@ def stop_for_managed_update(data: Path) -> None:
finally:
marker.unlink(missing_ok=True)
def update(record: dict, binary: Path, sha: str, start: bool, refresh_geoip: bool = False, reset_config: bool = False) -> dict:
prefix = Path(record['prefix']); data = Path(record['data_dir']); account = pwd.getpwnam(record['user'])
geoip_lock_fd: int | None = None
geoip_stage: Path | None = None
try:
# Repair missing or stale installer-owned shell setup on upgrades.
install_shell_path(prefix)
check_shell_path(prefix)
# Repair stale ownership before stopping the running service.
ensure_service_data_access(data, account)
release, version = stage(binary, prefix, record['user'], sha)
geoip_names: list[str] = []
if refresh_geoip:
# Shared lock with the runtime worker prevents concurrent upgrades.
geoip_lock_fd = acquire_geoip_update_lock(data, account.pw_uid, account.pw_gid)
try:
geoip_stage, geoip_names = prepare_geoip_update(data, prefix)
except GeoipUnavailable as error:
# GeoIP is refreshed best-effort: the update must not be blocked by a flaky download.
print(f'WARNING: GeoIP refresh skipped, keeping the installed country data: {error}', file=sys.stderr)
geoip_stage, geoip_names = None, []
active = subprocess.run(['systemctl', 'is-active', '--quiet', SERVICE], check=False, stdout=subprocess.DEVNULL).returncode == 0
@@ -399,7 +378,7 @@ def update(record: dict, binary: Path, sha: str, start: bool, refresh_geoip: boo
print('New release diagnostics:\n' + details, file=sys.stderr)
stop_for_managed_update(data)
failed = data.with_name(data.name + '.failed-' + uuid.uuid4().hex[:12])
data.rename(failed) # keep the failed generation for diagnosis; do not delete it
data.rename(failed)
copy_data(backup / 'data', data)
restore_managed_acme_runtime(failed, data)
chown_tree(data, account.pw_uid, account.pw_gid)
@@ -420,7 +399,6 @@ def update(record: dict, binary: Path, sha: str, start: bool, refresh_geoip: boo
shutil.rmtree(geoip_stage, ignore_errors=True)
release_geoip_update_lock(geoip_lock_fd)
def install(record: dict, binary: Path, sha: str, start: bool, install_geoip: bool = False) -> dict:
import grp
prefix = Path(record['prefix']); data = Path(record['data_dir'])
@@ -448,7 +426,6 @@ def install(record: dict, binary: Path, sha: str, start: bool, install_geoip: bo
switch(prefix, release)
install_shell_path(prefix)
install_logrotate(record)
# Record is written even if initial startup fails, so an update can repair it.
write_private(prefix / 'install.json', json.dumps(record, indent=2).encode())
write_private(UNIT_PATH, service_unit(record).encode(), 0o644)
run(['systemctl', 'daemon-reload']); run(['systemctl', 'enable', SERVICE])
@@ -458,5 +435,3 @@ def install(record: dict, binary: Path, sha: str, start: bool, install_geoip: bo
run(['systemctl', 'stop', SERVICE])
raise RuntimeError('Installed but startup failed. Data was retained; inspect journalctl -u rustproxy.')
return record
-6
View File
@@ -16,7 +16,6 @@ MANAGED = ["build.rs", "langs", "deploy", "debian", "grafana", "make_zip.py", "s
"README.md", "LICENSE", "CHANGELOG.md", "AGENTS.md", "SHA256SUMS",
".env.example", ".gitignore"]
def upgrade(source: Path, target: Path, *, stopped: bool, data_dir: Path | None = None) -> Path:
source = source.resolve()
if target.is_symlink():
@@ -62,8 +61,6 @@ def upgrade(source: Path, target: Path, *, stopped: bool, data_dir: Path | None
installed.append(name)
shutil.copytree(new, old)
if name == "langs" and (backup / name).is_dir():
# Preserve additional site language packs; bundled packs are
# updated, with their previous bytes retained in the backup.
for pack in (backup / name).glob("*.json"):
if pack.is_symlink():
raise ValueError("Language packs must not be symlinks.")
@@ -72,7 +69,6 @@ def upgrade(source: Path, target: Path, *, stopped: bool, data_dir: Path | None
elif new.is_file():
installed.append(name)
shutil.copy2(new, old)
# Obsolete renewal sidecar: validate, record the manifest, then remove it last.
runtime_data = (data_dir or (target / "data")).resolve()
certs_dir = runtime_data / "certs"
if certs_dir.is_symlink():
@@ -99,7 +95,6 @@ def upgrade(source: Path, target: Path, *, stopped: bool, data_dir: Path | None
for stream in locks:
stream.close()
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("target", type=Path)
@@ -116,6 +111,5 @@ def main() -> None:
print("Preserved data, .env, .git, target and other unmanaged files. No database migration was run.")
print(f"Next: cd {args.target}; ./dev.sh test; ./dev.sh")
if __name__ == "__main__":
main()