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

-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
'''