v0.43.1
This commit is contained in:
1 parent
5b6d4a7903
commit
4d1087e357
160 files changed
+2407
-1933
No files matched your search
@@ -28,7 +28,6 @@ UNSUPPORTED_PSEUDO_ELEMENTS = re.compile(r'::(?:-webkit-[\w-]+|-moz-[\w-]+|backd
|
||||
WORD_PATTERN = re.compile(r'(?<![\w-])[a-zA-Z_][\w-]*(?![\w-])')
|
||||
VENDOR_SELECTOR = re.compile(r'::?-(webkit|moz|ms|o)-[\w-]+')
|
||||
|
||||
|
||||
def panel_sources() -> list[Path]:
|
||||
if __package__:
|
||||
from .build.panel_css import source_files
|
||||
@@ -36,7 +35,6 @@ def panel_sources() -> list[Path]:
|
||||
from build.panel_css import source_files
|
||||
return source_files(ROOT)
|
||||
|
||||
|
||||
def embedded_javascript_sources() -> list[Path]:
|
||||
paths = set()
|
||||
for parent in (ROOT / 'src').rglob('*.rs'):
|
||||
@@ -46,7 +44,6 @@ def embedded_javascript_sources() -> list[Path]:
|
||||
paths.add(path)
|
||||
return sorted(paths)
|
||||
|
||||
|
||||
def structural_inventory(paths: list[Path]) -> dict:
|
||||
"""Report repetitions in their actual conditional scope; never reorder CSS."""
|
||||
selectors = defaultdict(list)
|
||||
@@ -99,7 +96,6 @@ def structural_inventory(paths: list[Path]) -> dict:
|
||||
families = [tuple(sorted({family for selector in entry['selectors']
|
||||
for family in VENDOR_SELECTOR.findall(selector)}))
|
||||
for entry in entries]
|
||||
# Vendor pseudo-element families legitimately repeat one rule body.
|
||||
vendor_only = (any(families) and all(len(family) <= 1 for family in families)
|
||||
and len(families) == len(set(families)))
|
||||
repeated_bodies.append({'scope': list(scope), 'rules': entries,
|
||||
@@ -116,10 +112,7 @@ def structural_inventory(paths: list[Path]) -> dict:
|
||||
'parse_errors': parse_errors,
|
||||
}
|
||||
|
||||
|
||||
def source_words(scope: str) -> set[str]:
|
||||
# Rust's include_str! lists are the asset entry points; an abandoned JS file
|
||||
# beside a bundle must not make its obsolete selectors appear live.
|
||||
paths = embedded_javascript_sources() + list(WEB.rglob('*.html'))
|
||||
if scope == 'panel':
|
||||
paths += list(WEB.rglob('*.json')) + list((ROOT / 'src').rglob('*.rs'))
|
||||
@@ -130,7 +123,6 @@ def source_words(scope: str) -> set[str]:
|
||||
words.update(WORD_PATTERN.findall(path.read_text(encoding='utf-8', errors='replace')))
|
||||
return words
|
||||
|
||||
|
||||
def selector_parts(tokens: list) -> list[str]:
|
||||
parts: list[list] = [[]]
|
||||
for tok in tokens:
|
||||
@@ -140,7 +132,6 @@ def selector_parts(tokens: list) -> list[str]:
|
||||
parts[-1].append(tok)
|
||||
return [tinycss2.serialize(part).strip() for part in parts if tinycss2.serialize(part).strip()]
|
||||
|
||||
|
||||
def rules(stylesheet: str):
|
||||
def walk(items):
|
||||
for item in items:
|
||||
@@ -150,7 +141,6 @@ def rules(stylesheet: str):
|
||||
yield from walk(tinycss2.parse_rule_list(item.content, skip_whitespace=True, skip_comments=True))
|
||||
return list(walk(tinycss2.parse_stylesheet(stylesheet, skip_whitespace=True, skip_comments=True)))
|
||||
|
||||
|
||||
def token_refs(node) -> list[tuple[str, str]]:
|
||||
if isinstance(node, css_parser.ClassSelector):
|
||||
return [('class', node.class_name)]
|
||||
@@ -168,10 +158,7 @@ def token_refs(node) -> list[tuple[str, str]]:
|
||||
out.extend(token_refs(child))
|
||||
return out
|
||||
|
||||
|
||||
def possibly_matches(node, words: set[str]) -> bool:
|
||||
# Only positive class/id requirements identify review candidates. Runtime
|
||||
# interpolation still requires manual inspection before removing a rule.
|
||||
if isinstance(node, css_parser.ClassSelector):
|
||||
return node.class_name in words
|
||||
if isinstance(node, css_parser.IDSelector):
|
||||
@@ -192,10 +179,8 @@ def possibly_matches(node, words: set[str]) -> bool:
|
||||
return possibly_matches(node.parsed_tree, words)
|
||||
if isinstance(node, css_parser.RelativeSelector):
|
||||
return possibly_matches(node.selector, words)
|
||||
# Pseudo-classes, type selectors, vendor syntax and other unknowns: KEEP.
|
||||
return True
|
||||
|
||||
|
||||
def audit_file(path: Path, words: set[str], scope: str) -> dict:
|
||||
raw = path.read_text(encoding='utf-8')
|
||||
entries = []
|
||||
@@ -210,13 +195,10 @@ def audit_file(path: Path, words: set[str], scope: str) -> dict:
|
||||
references = set().union(*(set(token_refs(item)) for item in parsed))
|
||||
all_classes.update(word for typ, word in references if typ == 'class')
|
||||
dead = bool(parsed) and not any(possibly_matches(item, words) for item in parsed)
|
||||
# docs.css targets classes emitted by the third-party Swagger UI bundle.
|
||||
external = scope == 'docs' and '.swagger-ui' in selector
|
||||
if external:
|
||||
dead = False
|
||||
missing = sorted({f'{typ}:{word}' for typ, word in references if word not in words})
|
||||
# Retain the historical JSON key for older audit consumers;
|
||||
# "dead" is a candidate flag, never proof of runtime absence.
|
||||
parts.append({'selector': selector, 'dead': dead, 'review_required': dead, 'missing_tokens': missing,
|
||||
'external': external})
|
||||
except css_parser.SelectorError as exc:
|
||||
@@ -234,7 +216,6 @@ def audit_file(path: Path, words: set[str], scope: str) -> dict:
|
||||
'unparsed': unknown, 'entries': entries,
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
cli = argparse.ArgumentParser(description=__doc__)
|
||||
cli.add_argument('--json', type=Path, help='Write complete selector audit JSON to this file')
|
||||
@@ -270,6 +251,5 @@ def main():
|
||||
if args.strict and failures:
|
||||
raise SystemExit('Panel CSS structure check failed: ' + ', '.join(failures))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -35,7 +35,6 @@ PY
|
||||
VERSION="$(python3 scripts/version.py)"
|
||||
printf 'Validating RustProxy %s\n' "$VERSION"
|
||||
|
||||
# Project-owned source/layout validation.
|
||||
python3 scripts/preflight.py
|
||||
python3 scripts/build/panel_css.py --check
|
||||
|
||||
@@ -44,15 +43,12 @@ if [[ ! -f Cargo.lock ]]; then
|
||||
cargo generate-lockfile
|
||||
fi
|
||||
|
||||
# Rust quality gates.
|
||||
cargo fmt --all -- --check
|
||||
cargo check --locked --all-targets
|
||||
cargo test --locked --all-targets
|
||||
cargo clippy --locked --all-targets -- -D warnings
|
||||
cargo build --release --locked
|
||||
|
||||
# The Docker discovery agent is shipped with the source tree, but is a separate Go module.
|
||||
# Set CHECK_DOCKER_AGENT=0 when intentionally validating only the Rust binary.
|
||||
if [[ -f "$ROOT/docker-agent/go.mod" && "${CHECK_DOCKER_AGENT:-1}" != "0" ]]; then
|
||||
command -v go >/dev/null 2>&1 || fail "Go is required to validate docker-agent (or set CHECK_DOCKER_AGENT=0)"
|
||||
(
|
||||
|
||||
@@ -20,7 +20,6 @@ WHITESPACE = " \t\n\r\f"
|
||||
HEX = "0123456789abcdefABCDEF"
|
||||
DELIMITERS = frozenset("{};")
|
||||
|
||||
|
||||
def _escape_end(text: str, start: int) -> int:
|
||||
end = start + 1
|
||||
if end == len(text):
|
||||
@@ -36,7 +35,6 @@ def _escape_end(text: str, start: int) -> int:
|
||||
return end
|
||||
return end + (2 if text[end:end + 2] == "\r\n" else 1)
|
||||
|
||||
|
||||
def _string_end(text: str, start: int) -> int:
|
||||
end = start + 1
|
||||
while end < len(text):
|
||||
@@ -50,17 +48,13 @@ def _string_end(text: str, start: int) -> int:
|
||||
end += 1
|
||||
raise ValueError("Unterminated CSS string")
|
||||
|
||||
|
||||
def _comment_end(text: str, start: int) -> int:
|
||||
end = text.find("*/", start + 2)
|
||||
if end < 0:
|
||||
raise ValueError("Unterminated CSS comment")
|
||||
return end + 2
|
||||
|
||||
|
||||
def _group_end(text: str, start: int) -> int:
|
||||
# Do not rewrite anything in functions or attribute selectors. This also
|
||||
# protects unquoted data URLs and whitespace required by calc()/CSS escapes.
|
||||
closing = ")" if text[start] == "(" else "]"
|
||||
is_url = (text[start] == "(" and text[max(0, start - 3):start].lower() == "url"
|
||||
and (start < 4 or not (text[start - 4].isalnum() or text[start - 4] in "_-")))
|
||||
@@ -79,11 +73,9 @@ def _group_end(text: str, start: int) -> int:
|
||||
elif text[end] in ")]" and not is_url:
|
||||
raise ValueError("Mismatched CSS delimiter")
|
||||
else:
|
||||
# In an unquoted url(), /* and square brackets are literal data.
|
||||
end += 1
|
||||
raise ValueError(f"Unterminated CSS {text[start]} group")
|
||||
|
||||
|
||||
def minify(text: str) -> str:
|
||||
"""Conservatively compact a stylesheet without reordering its CSS tokens."""
|
||||
tokens: list[tuple[str, str]] = []
|
||||
@@ -119,8 +111,6 @@ def minify(text: str) -> str:
|
||||
if depth:
|
||||
raise ValueError("Unterminated CSS rule")
|
||||
|
||||
# Source modules must stay independent of runtime imports and encoding
|
||||
# declarations; all are UTF-8 and are delivered as one embedded response.
|
||||
for index, token in enumerate(tokens):
|
||||
if token != ("plain", "@"):
|
||||
continue
|
||||
@@ -152,8 +142,6 @@ def minify(text: str) -> str:
|
||||
if (before and after and before[0] != "space" and after[0] != "space"
|
||||
and not (before[0] == "plain" and before[1] in DELIMITERS)
|
||||
and not (after[0] == "plain" and after[1] in DELIMITERS)):
|
||||
# Retain a token boundary: e.g. --value:foo/**/bar must never
|
||||
# become the single identifier foobar. No guessed whitespace.
|
||||
compact.append(("protected", "/**/"))
|
||||
continue
|
||||
if kind == "space" and compact and compact[-1][0] == "space":
|
||||
@@ -173,7 +161,6 @@ def minify(text: str) -> str:
|
||||
output.append(value)
|
||||
return "".join(output)
|
||||
|
||||
|
||||
def source_files(root: Path = ROOT) -> list[Path]:
|
||||
directory = root / CSS_DIRECTORY
|
||||
manifest = directory / "manifest.json"
|
||||
@@ -199,7 +186,6 @@ def source_files(root: Path = ROOT) -> list[Path]:
|
||||
raise ValueError(f"CSS source must be a regular, non-symlink file: {path.name}")
|
||||
return paths
|
||||
|
||||
|
||||
def bundle(root: Path = ROOT) -> tuple[str, list[Path], int]:
|
||||
paths = source_files(root)
|
||||
parts: list[str] = []
|
||||
@@ -213,7 +199,6 @@ def bundle(root: Path = ROOT) -> tuple[str, list[Path], int]:
|
||||
raise ValueError(f"{path.name}: {error}") from error
|
||||
return "\n".join(parts) + "\n", paths, source_bytes
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--root", type=Path, default=ROOT)
|
||||
@@ -234,8 +219,6 @@ def main() -> int:
|
||||
if args.cargo:
|
||||
watched = [root / CSS_DIRECTORY, root / CSS_DIRECTORY / "manifest.json", *paths]
|
||||
if args.out_dir is not None:
|
||||
# Cargo must rerun the generator when its cached output is
|
||||
# removed even if every source module is unchanged.
|
||||
watched.append(args.out_dir.resolve() / "panel-style.css")
|
||||
for path in watched:
|
||||
if any(char in str(path) for char in "\r\n\0"):
|
||||
@@ -249,6 +232,5 @@ def main() -> int:
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -37,11 +37,9 @@ HELP = ("Install Python 3.10+ and allow HTTPS access to github.com/codeload.gith
|
||||
"or set SWAGGER_UI_DOWNLOAD_URL=file:///absolute/path/swagger-ui-5.33.1.zip "
|
||||
"to a reviewed copy of the same tag archive. See docs/INSTALL.md.")
|
||||
|
||||
|
||||
class AssetError(ValueError):
|
||||
"""A controlled, actionable source/archive error (never an implicit fallback)."""
|
||||
|
||||
|
||||
def source_value(value: str | None) -> str | Path:
|
||||
"""Unset/empty means the pin, never the adapter's historical default."""
|
||||
if value is None or not value.strip():
|
||||
@@ -56,7 +54,6 @@ def source_value(value: str | None) -> str | Path:
|
||||
if (parts.scheme != "file" or parts.netloc not in ("", "localhost")
|
||||
or parts.query or parts.fragment):
|
||||
raise ValueError()
|
||||
# url2pathname decodes percent escapes (including spaces) on this platform.
|
||||
path = Path(url2pathname(parts.path))
|
||||
if not path.is_absolute() or any(c in str(path) for c in "\r\n\0"):
|
||||
raise ValueError()
|
||||
@@ -64,7 +61,6 @@ def source_value(value: str | None) -> str | Path:
|
||||
except (ValueError, OSError):
|
||||
raise AssetError("Swagger source must be the pinned HTTPS URL or an absolute file:// URL.") from None
|
||||
|
||||
|
||||
def expected_digest(value: str | None) -> str | None:
|
||||
if value is None or not value.strip():
|
||||
return None
|
||||
@@ -73,7 +69,6 @@ def expected_digest(value: str | None) -> str | None:
|
||||
raise AssetError("SWAGGER_UI_ARCHIVE_SHA256 must contain exactly 64 hexadecimal digits.")
|
||||
return value
|
||||
|
||||
|
||||
class HttpsRedirects(HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
target = urlsplit(newurl)
|
||||
@@ -82,7 +77,6 @@ class HttpsRedirects(HTTPRedirectHandler):
|
||||
raise AssetError("Swagger download refused an unexpected redirect.")
|
||||
return super().redirect_request(req, fp, code, msg, headers, newurl)
|
||||
|
||||
|
||||
def download(destination: Path) -> None:
|
||||
"""Download with a few retries; github.com occasionally times out or returns a gateway error."""
|
||||
last: Exception | None = None
|
||||
@@ -92,7 +86,7 @@ def download(destination: Path) -> None:
|
||||
return
|
||||
except AssetError:
|
||||
raise
|
||||
except (OSError, ValueError) as error: # URLError/HTTPError/timeouts are OSError subclasses
|
||||
except (OSError, ValueError) as error:
|
||||
last = error
|
||||
if attempt < 3:
|
||||
delay = (3, 6, 12)[attempt]
|
||||
@@ -100,7 +94,6 @@ def download(destination: Path) -> None:
|
||||
time.sleep(delay)
|
||||
raise AssetError(f"Swagger download failed after 4 attempts: {last}")
|
||||
|
||||
|
||||
def _download_once(destination: Path) -> None:
|
||||
"""TLS verification uses Python's default trust store; never executes a shell."""
|
||||
started = time.monotonic()
|
||||
@@ -120,7 +113,6 @@ def _download_once(destination: Path) -> None:
|
||||
raise AssetError("Swagger download exceeded the size or time limit.")
|
||||
output.write(block)
|
||||
|
||||
|
||||
def read_assets(path: Path, checksum: str | None) -> tuple[dict[str, bytes], str]:
|
||||
if not path.is_file() or not 0 < path.stat().st_size <= MAX_ARCHIVE:
|
||||
raise AssetError("Swagger archive must be a nonempty regular file of at most 64 MiB.")
|
||||
@@ -148,7 +140,6 @@ def read_assets(path: Path, checksum: str | None) -> tuple[dict[str, bytes], str
|
||||
mode = (info.external_attr >> 16) & 0o170000
|
||||
if info.is_dir() or mode not in (0, 0o100000) or not 0 < info.file_size <= limit:
|
||||
raise AssetError(f"Swagger archive member is not a bounded regular file: {name}.")
|
||||
# Bounded read as well as metadata validation; CRC checked by ZipFile.
|
||||
with archive.open(info) as stream:
|
||||
data = stream.read(limit + 1)
|
||||
if not 0 < len(data) <= limit or len(data) != info.file_size:
|
||||
@@ -168,10 +159,9 @@ def read_assets(path: Path, checksum: str | None) -> tuple[dict[str, bytes], str
|
||||
assets["licenses.txt"] = b"Swagger UI " + VERSION.encode() + b"\n\n" + b"\n\n".join(licenses)
|
||||
return assets, digest
|
||||
|
||||
|
||||
def atomic_write(path: Path, data: bytes) -> None:
|
||||
if path.is_file() and path.read_bytes() == data:
|
||||
return # Preserve mtime for Cargo's rerun-if-changed tracking.
|
||||
return
|
||||
fd, name = tempfile.mkstemp(prefix=".swagger-", dir=path.parent)
|
||||
temporary = Path(name)
|
||||
try:
|
||||
@@ -181,7 +171,6 @@ def atomic_write(path: Path, data: bytes) -> None:
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def cached_archives(out_dir: Path, cache: Path) -> list[Path]:
|
||||
"""Previously downloaded copies of the pinned archive.
|
||||
|
||||
@@ -203,7 +192,6 @@ def cached_archives(out_dir: Path, cache: Path) -> list[Path]:
|
||||
candidates.extend(siblings)
|
||||
return [item for item in dict.fromkeys(candidates) if item != cache and item.is_file()]
|
||||
|
||||
|
||||
def remember_archive(out_dir: Path, cache: Path) -> None:
|
||||
"""Best-effort copy of a validated archive into the shared cache directory."""
|
||||
parents = out_dir.parents
|
||||
@@ -216,7 +204,6 @@ def remember_archive(out_dir: Path, cache: Path) -> None:
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def read_vendored() -> tuple[dict[str, bytes], str, Path] | None:
|
||||
"""Assets vendored in third_party/ (official swagger-ui-dist files); verified against SHA256SUMS.
|
||||
|
||||
@@ -250,7 +237,6 @@ def read_vendored() -> tuple[dict[str, bytes], str, Path] | None:
|
||||
"licenses.txt": b"Swagger UI " + VERSION.encode() + b"\n\n" + b"\n\n".join(licenses)}
|
||||
return assets, hashlib.sha256(manifest.read_bytes()).hexdigest(), manifest
|
||||
|
||||
|
||||
def prepare(out_dir: Path, source: str | Path, checksum: str | None = None,
|
||||
*, offline: bool = False) -> list[Path]:
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
@@ -288,7 +274,7 @@ def prepare(out_dir: Path, source: str | Path, checksum: str | None = None,
|
||||
try:
|
||||
download(temporary)
|
||||
assets, digest = read_assets(temporary, checksum)
|
||||
os.replace(temporary, cache) # Cache only an already-validated archive.
|
||||
os.replace(temporary, cache)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
remember_archive(out_dir, cache)
|
||||
@@ -307,11 +293,9 @@ def prepare(out_dir: Path, source: str | Path, checksum: str | None = None,
|
||||
}
|
||||
receipt_path = destination / "source.json"
|
||||
atomic_write(receipt_path, (json.dumps(receipt, indent=2, sort_keys=True) + "\n").encode())
|
||||
# Watch both a supplied symlink and its resolved target, plus cached/generated files.
|
||||
inputs = [archive.absolute(), archive.resolve(), *outputs, receipt_path]
|
||||
return list(dict.fromkeys(inputs))
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--out-dir", required=True, type=Path)
|
||||
@@ -335,6 +319,5 @@ def main() -> int:
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -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()
|
||||
@@ -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
|
||||
'''
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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()
|
||||
@@ -11,13 +11,8 @@ from pathlib import Path
|
||||
|
||||
WEB = Path(__file__).resolve().parents[1] / "src/admin/web"
|
||||
ROOT = WEB / "cf_page"
|
||||
# Use the exact dashboard brand mark: r / p with the same span structure,
|
||||
# typography, dimensions and border styles as css/20-shell.css.
|
||||
LOGO = '<span class="brand-mark" aria-label="RustProxy">r<span>/</span>p</span>'
|
||||
|
||||
# Code, title, explanation, advice, RustProxy status label, origin status label,
|
||||
# RustProxy indicator, origin indicator. Indicators describe this request only;
|
||||
# they must never claim to have checked the upstream's health.
|
||||
STATUSES = [
|
||||
(200, "Service ready", "RustProxy received and handled the request.", "No further action is required for this response.", "Working", "Not checked", "ok", "unknown"),
|
||||
(400, "Bad request", "The request was malformed or could not be understood.", "Check the request and try again.", "Request rejected", "Not contacted", "error", "unknown"),
|
||||
@@ -85,7 +80,6 @@ ICONS = {
|
||||
"origin": '''<svg viewBox="0 0 120 106" aria-hidden="true" focusable="false"><rect x="22" y="13" width="76" height="27" rx="4" fill="#aaa"/><rect x="22" y="46" width="76" height="27" rx="4" fill="#aaa"/><circle cx="34" cy="27" r="4" fill="#f1f1f1"/><circle cx="34" cy="60" r="4" fill="#f1f1f1"/><path d="M48 27h38M48 60h38" stroke="#d9d9d9" stroke-width="4" stroke-linecap="round"/><path d="M60 73v14m-21 0h42" stroke="#aaa" stroke-width="7" stroke-linecap="round"/></svg>''',
|
||||
}
|
||||
|
||||
|
||||
def node(icon: str, location: str, title: str, state: str, indicator: str) -> str:
|
||||
indicator_glyph = {"ok": "✓", "error": "×", "unknown": "–"}[indicator]
|
||||
return (
|
||||
@@ -95,7 +89,6 @@ def node(icon: str, location: str, title: str, state: str, indicator: str) -> st
|
||||
f'<p class="state {indicator}">{escape(state)}</p></div>'
|
||||
)
|
||||
|
||||
|
||||
def make_page(code: int | None, title: str, happened: str, advice: str, gateway: str, origin: str,
|
||||
gateway_indicator: str, origin_indicator: str, *, variant: str = "status") -> str:
|
||||
arrow = '<div class="connector" aria-hidden="true"><svg viewBox="0 0 100 30"><path d="M8 15h84m-74-10L8 15l10 10M82 5l10 10-10 10"/></svg></div>'
|
||||
@@ -133,7 +126,6 @@ def make_page(code: int | None, title: str, happened: str, advice: str, gateway:
|
||||
</html>
|
||||
'''
|
||||
|
||||
|
||||
VARIANTS = [
|
||||
("welcome", "Congratulations! RustProxy is running.",
|
||||
"RustProxy is installed and serving this page. This does not verify an upstream application.",
|
||||
@@ -145,7 +137,6 @@ VARIANTS = [
|
||||
"Page served", "Not checked", "ok", "unknown"),
|
||||
]
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ROOT.mkdir(parents=True, exist_ok=True)
|
||||
for entry in STATUSES:
|
||||
@@ -155,6 +146,5 @@ def main() -> None:
|
||||
(ROOT / f"{variant}.html").write_text(make_page(None, *entry, variant=variant), encoding="utf-8")
|
||||
print(f"Generated {len(STATUSES) + len(VARIANTS)} offline RustProxy-branded pages")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -2,8 +2,8 @@
|
||||
"""Migrate Nginx Proxy Manager proxy hosts from SQLite into RustProxy."""
|
||||
from __future__ import annotations
|
||||
|
||||
from migrate_npm_core import * # stable migration/model API
|
||||
from migrate_npm_api import * # stable administration API helpers
|
||||
from migrate_npm_core import *
|
||||
from migrate_npm_api import *
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
@@ -69,7 +69,5 @@ def main() -> None:
|
||||
except (MigrationError, OSError, sqlite3.Error) as error:
|
||||
parser.exit(1, f"Migration failed: {error}\n")
|
||||
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -15,7 +15,7 @@ class RustProxyClient:
|
||||
handlers: list[Any] = [urllib.request.HTTPCookieProcessor(jar)]
|
||||
if parsed.scheme == "https":
|
||||
if insecure_tls:
|
||||
context = ssl._create_unverified_context() # Explicit operator opt-in for local/self-signed admin TLS.
|
||||
context = ssl._create_unverified_context()
|
||||
else:
|
||||
context = ssl.create_default_context(cafile=str(ca_file) if ca_file else None)
|
||||
handlers.append(urllib.request.HTTPSHandler(context=context))
|
||||
@@ -71,8 +71,6 @@ class RustProxyClient:
|
||||
raise MigrationError("unexpected RustProxy PUT /api/config response")
|
||||
return value
|
||||
|
||||
|
||||
|
||||
def write_private_json(path: Path, value: dict[str, Any]) -> None:
|
||||
path = path.expanduser()
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
@@ -103,7 +101,6 @@ def split_ids(values: list[str] | None) -> list[str] | None:
|
||||
out.append(item)
|
||||
return out
|
||||
|
||||
|
||||
def print_report(decisions: list[Decision]) -> None:
|
||||
imported = sum(1 for d in decisions if d.action == "import")
|
||||
skipped = sum(1 for d in decisions if d.action == "skip")
|
||||
@@ -120,5 +117,3 @@ def print_report(decisions: list[Decision]) -> None:
|
||||
print(" reason: " + decision.reason)
|
||||
for warning in decision.warnings or []:
|
||||
print(" warning: " + warning)
|
||||
|
||||
|
||||
@@ -31,11 +31,9 @@ import urllib.request
|
||||
|
||||
MAX_CONFIG_BYTES = 2_097_152
|
||||
|
||||
|
||||
class MigrationError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class NpmProxyHost:
|
||||
id: int
|
||||
@@ -55,7 +53,6 @@ class NpmProxyHost:
|
||||
block_exploits: bool
|
||||
meta: dict[str, Any]
|
||||
|
||||
|
||||
@dataclass
|
||||
class Decision:
|
||||
npm_id: int
|
||||
@@ -66,7 +63,6 @@ class Decision:
|
||||
warnings: list[str] | None = None
|
||||
reason: str | None = None
|
||||
|
||||
|
||||
def json_value(raw: Any, fallback: Any) -> Any:
|
||||
if raw is None or raw == "":
|
||||
return fallback
|
||||
@@ -77,13 +73,11 @@ def json_value(raw: Any, fallback: Any) -> Any:
|
||||
except (TypeError, json.JSONDecodeError):
|
||||
return fallback
|
||||
|
||||
|
||||
def bool_value(raw: Any) -> bool:
|
||||
if isinstance(raw, str):
|
||||
return raw.strip().lower() in {"1", "true", "yes", "on"}
|
||||
return bool(raw)
|
||||
|
||||
|
||||
def normalize_host_pattern(value: str) -> str:
|
||||
value = value.strip().lower().rstrip(".")
|
||||
wildcard = value.startswith("*.")
|
||||
@@ -100,11 +94,9 @@ def normalize_host_pattern(value: str) -> str:
|
||||
raise MigrationError(f"hostname must be ASCII/punycode: {value!r}")
|
||||
return ("*." if wildcard else "") + base
|
||||
|
||||
|
||||
def sql_columns(connection: sqlite3.Connection, table: str) -> set[str]:
|
||||
return {str(row[1]) for row in connection.execute(f"PRAGMA table_info({table})")}
|
||||
|
||||
|
||||
def load_npm_hosts(database: Path) -> list[NpmProxyHost]:
|
||||
if database.is_symlink() or not database.is_file():
|
||||
raise MigrationError(f"NPM SQLite database not found or unsafe: {database}")
|
||||
@@ -172,7 +164,6 @@ def load_npm_hosts(database: Path) -> list[NpmProxyHost]:
|
||||
))
|
||||
return result
|
||||
|
||||
|
||||
def backend_url(item: NpmProxyHost) -> str:
|
||||
if item.forward_scheme not in {"http", "https"}:
|
||||
raise MigrationError(f"unsupported upstream scheme {item.forward_scheme!r}")
|
||||
@@ -193,13 +184,11 @@ def backend_url(item: NpmProxyHost) -> str:
|
||||
rendered = host
|
||||
return f"{item.forward_scheme}://{rendered}:{item.forward_port}"
|
||||
|
||||
|
||||
def slug(value: str) -> str:
|
||||
value = value.lower().replace("*.", "wildcard-")
|
||||
value = re.sub(r"[^a-z0-9_-]+", "-", value).strip("-_")
|
||||
return value[:40] or "host"
|
||||
|
||||
|
||||
def unique_id(base: str, used: set[str]) -> str:
|
||||
base = re.sub(r"[^A-Za-z0-9_-]+", "-", base)[:64].strip("-_") or "npm"
|
||||
candidate = base
|
||||
@@ -211,7 +200,6 @@ def unique_id(base: str, used: set[str]) -> str:
|
||||
used.add(candidate)
|
||||
return candidate
|
||||
|
||||
|
||||
def listener_inventory(config: dict[str, Any]) -> tuple[list[str], list[str]]:
|
||||
http_ids: list[str] = []
|
||||
https_ids: list[str] = []
|
||||
@@ -225,7 +213,6 @@ def listener_inventory(config: dict[str, Any]) -> tuple[list[str], list[str]]:
|
||||
(https_ids if binding.get("tls") else http_ids).append(listener_id)
|
||||
return http_ids, https_ids
|
||||
|
||||
|
||||
def selected_tls_ports(config: dict[str, Any], listener_ids: list[str]) -> set[int]:
|
||||
selected = set(listener_ids)
|
||||
ports: set[int] = set()
|
||||
@@ -247,7 +234,6 @@ def selected_tls_ports(config: dict[str, Any], listener_ids: list[str]) -> set[i
|
||||
ports.add(port)
|
||||
return ports
|
||||
|
||||
|
||||
def existing_host_owners(config: dict[str, Any]) -> dict[str, str]:
|
||||
result: dict[str, str] = {}
|
||||
for vhost in config.get("vhosts") or []:
|
||||
@@ -263,7 +249,6 @@ def existing_host_owners(config: dict[str, Any]) -> dict[str, str]:
|
||||
pass
|
||||
return result
|
||||
|
||||
|
||||
def warnings_for(item: NpmProxyHost, tls_verify: bool) -> list[str]:
|
||||
warnings: list[str] = []
|
||||
if item.access_list_id:
|
||||
@@ -284,7 +269,6 @@ def warnings_for(item: NpmProxyHost, tls_verify: bool) -> list[str]:
|
||||
warnings.append("NPM meta.nginx_err is set; review the source host before cutover")
|
||||
return warnings
|
||||
|
||||
|
||||
def build_migration(
|
||||
npm_hosts: list[NpmProxyHost],
|
||||
config: dict[str, Any],
|
||||
@@ -399,5 +383,3 @@ def build_migration(
|
||||
owners[host] = vid
|
||||
decisions.append(Decision(item.id, "import", normalized, backend=origin, rustproxy_ids=created_ids, warnings=warnings))
|
||||
return new_config, decisions
|
||||
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[1])
|
||||
@@ -17,6 +16,5 @@ def main() -> None:
|
||||
if missing:
|
||||
parser.exit(2, f"Source preflight failed: missing {', '.join(missing)}\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -37,18 +37,14 @@ PROVIDER_FIELDS = {
|
||||
"rfc2136": {"dns_server", "dns_port", "key_name", "key_secret", "key_algorithm", "sign_query"},
|
||||
}
|
||||
|
||||
|
||||
def credential(value: object) -> str:
|
||||
# API keys are ASCII tokens; reject anything that could inject INI content.
|
||||
if not isinstance(value, str) or not re.fullmatch(r"[A-Za-z0-9_./+\-=]{8,4096}", value):
|
||||
raise AcmeError("acme.invalid_api_credential")
|
||||
return value
|
||||
|
||||
|
||||
class AcmeError(Exception):
|
||||
"""Messages contain fixed diagnostics, never provider output or input secrets."""
|
||||
|
||||
|
||||
def domain(value: object, wildcard: bool = True, single_label: bool = False) -> str:
|
||||
if not isinstance(value, str) or not value.isascii() or len(value) > 253:
|
||||
raise AcmeError("acme.invalid_domain")
|
||||
@@ -62,7 +58,6 @@ def domain(value: object, wildcard: bool = True, single_label: bool = False) ->
|
||||
return value
|
||||
raise AcmeError("acme.dns_names_only")
|
||||
|
||||
|
||||
def validate(raw: object) -> dict:
|
||||
if not isinstance(raw, dict):
|
||||
raise AcmeError("acme.invalid_request")
|
||||
@@ -132,14 +127,12 @@ def validate(raw: object) -> dict:
|
||||
raise AcmeError("acme.invalid_sign_query")
|
||||
return value
|
||||
|
||||
|
||||
def private_directory(path: Path) -> None:
|
||||
path.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
info = path.lstat()
|
||||
if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.geteuid() or info.st_mode & 0o077:
|
||||
raise AcmeError("acme.unsafe_directory")
|
||||
|
||||
|
||||
def write_new(path: Path, data: bytes) -> None:
|
||||
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0), 0o600)
|
||||
with os.fdopen(fd, "wb") as stream:
|
||||
@@ -147,7 +140,6 @@ def write_new(path: Path, data: bytes) -> None:
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
|
||||
|
||||
def credentials(value: dict) -> bytes:
|
||||
if value["provider"] == "http01":
|
||||
return b""
|
||||
@@ -163,7 +155,6 @@ def credentials(value: dict) -> bytes:
|
||||
}
|
||||
return "".join(f"dns_rfc2136_{k} = {v}\n" for k, v in lines.items()).encode("ascii")
|
||||
|
||||
|
||||
def certbot_prefix(executable: str | None = None) -> list[str]:
|
||||
if executable:
|
||||
return [executable]
|
||||
@@ -175,7 +166,6 @@ def certbot_prefix(executable: str | None = None) -> list[str]:
|
||||
return [discovered]
|
||||
raise AcmeError("acme.certbot_not_installed")
|
||||
|
||||
|
||||
def certbot_command(value: dict, work: Path, credential_file: Path, command_prefix: list[str]) -> list[str]:
|
||||
args = [*command_prefix, "certonly", "--non-interactive", "--agree-tos", "--no-eff-email",
|
||||
"--email", value["email"], "--server", DIRECTORIES[value["environment"]],
|
||||
@@ -193,9 +183,7 @@ def certbot_command(value: dict, work: Path, credential_file: Path, command_pref
|
||||
args += ["-d", name]
|
||||
return args
|
||||
|
||||
|
||||
def read_generated(work: Path, name: str) -> bytes:
|
||||
# Resolve live symlinks only inside Certbot's archive.
|
||||
archive = (work / "config" / "archive").resolve(strict=True)
|
||||
path = (work / "config" / "live" / "rustproxy" / name).resolve(strict=True)
|
||||
if not path.is_relative_to(archive):
|
||||
@@ -210,7 +198,6 @@ def read_generated(work: Path, name: str) -> bytes:
|
||||
raise AcmeError("acme.invalid_pem")
|
||||
return data
|
||||
|
||||
|
||||
def issue(raw: dict, certificate_directory: Path, executable: str | None = None) -> dict:
|
||||
value = validate(raw)
|
||||
command_prefix = certbot_prefix(executable)
|
||||
@@ -218,7 +205,6 @@ def issue(raw: dict, certificate_directory: Path, executable: str | None = None)
|
||||
private_directory(certificate_directory)
|
||||
root = certificate_directory / "acme"
|
||||
private_directory(root)
|
||||
# Each profile has isolated CA accounts, credentials and lineages.
|
||||
suffix = "" if value["provider"] == "rfc2136" else "-" + value["provider"]
|
||||
work = root / (value["environment"] + "-" + value["certificate_id"] + suffix)
|
||||
private_directory(work)
|
||||
@@ -233,7 +219,6 @@ def issue(raw: dict, certificate_directory: Path, executable: str | None = None)
|
||||
raise AcmeError("acme.profile_busy") from None
|
||||
for folder in ["config", "work", "logs"]:
|
||||
private_directory(work / folder)
|
||||
# Secret Store credentials exist as a plaintext file only while Certbot runs.
|
||||
credential_file = work / (value["provider"] + ".ini")
|
||||
if value["provider"] == "http01":
|
||||
webroot = certificate_directory / "acme-http01"
|
||||
@@ -260,7 +245,6 @@ def issue(raw: dict, certificate_directory: Path, executable: str | None = None)
|
||||
credential_file.unlink(missing_ok=True)
|
||||
cert = read_generated(work, "fullchain.pem")
|
||||
key = read_generated(work, "privkey.pem")
|
||||
# Work on immutable copies so the active certificate never changes mid-run.
|
||||
stem = "acme-" + uuid.uuid4().hex
|
||||
cert_path = certificate_directory / (stem + ".pem")
|
||||
key_path = certificate_directory / (stem + ".key")
|
||||
@@ -277,13 +261,10 @@ def issue(raw: dict, certificate_directory: Path, executable: str | None = None)
|
||||
"domains": value["domains"], "cert_file": cert_path.name, "key_file": key_path.name,
|
||||
"staged": True}
|
||||
|
||||
|
||||
|
||||
def profile_directory(certificate_directory: Path, provider: str, environment: str, certificate_id: str) -> Path:
|
||||
suffix = "" if provider == "rfc2136" else "-" + provider
|
||||
return certificate_directory / "acme" / (environment + "-" + certificate_id + suffix)
|
||||
|
||||
|
||||
def read_private(path: Path, limit: int = MAX_INPUT) -> bytes:
|
||||
fd = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
|
||||
with os.fdopen(fd, "rb") as stream:
|
||||
@@ -295,7 +276,6 @@ def read_private(path: Path, limit: int = MAX_INPUT) -> bytes:
|
||||
raise AcmeError("acme.unsafe_profile")
|
||||
return data
|
||||
|
||||
|
||||
def certificate_dates(pem: bytes, executable: str | None = None) -> dict:
|
||||
"""Read validity without exposing subject/PEM data or requiring a new Python package."""
|
||||
executable = executable or shutil.which("openssl")
|
||||
@@ -310,7 +290,6 @@ def certificate_dates(pem: bytes, executable: str | None = None) -> dict:
|
||||
dates = {}
|
||||
for line in result.stdout.decode("ascii").splitlines():
|
||||
name, text = line.split("=", 1)
|
||||
# OpenSSL's English ASN.1 date print format; LC_ALL is fixed above.
|
||||
value = datetime.datetime.strptime(text.strip(), "%b %d %H:%M:%S %Y GMT").replace(tzinfo=datetime.timezone.utc)
|
||||
dates[name] = int(value.timestamp())
|
||||
if dates["notAfter"] <= dates["notBefore"]:
|
||||
@@ -319,7 +298,6 @@ def certificate_dates(pem: bytes, executable: str | None = None) -> dict:
|
||||
except (ValueError, KeyError, UnicodeError, subprocess.TimeoutExpired):
|
||||
raise AcmeError("acme.certificate_dates_invalid") from None
|
||||
|
||||
|
||||
def renewal_request(raw: object) -> dict:
|
||||
if not isinstance(raw, dict) or set(raw) - {"action", "certificate_id", "provider", "environment", "cert_file", "key_file", "dry_run", "force", "credential_ini_b64"}:
|
||||
raise AcmeError("acme.invalid_renewal_request")
|
||||
@@ -350,7 +328,6 @@ def renewal_request(raw: object) -> dict:
|
||||
value.pop("credential_ini_b64", None)
|
||||
return value
|
||||
|
||||
|
||||
def renew(raw: dict, certificate_directory: Path, executable: str | None = None) -> dict:
|
||||
"""Renew ONE existing, consented lineage; never create a profile.
|
||||
|
||||
@@ -365,7 +342,6 @@ def renew(raw: dict, certificate_directory: Path, executable: str | None = None)
|
||||
certificate_directory = certificate_directory.absolute()
|
||||
private_directory(certificate_directory)
|
||||
work = profile_directory(certificate_directory, value["provider"], value["environment"], value["certificate_id"])
|
||||
# Do not create missing profile paths during renewal.
|
||||
for path in [certificate_directory / "acme", work, work / "config", work / "work", work / "logs"]:
|
||||
if not path.exists():
|
||||
raise AcmeError("acme.renewal_profile_missing")
|
||||
@@ -389,7 +365,6 @@ def renew(raw: dict, certificate_directory: Path, executable: str | None = None)
|
||||
if not isinstance(names, list) or not 1 <= len(names) <= 16:
|
||||
raise AcmeError("acme.invalid_domains")
|
||||
names = [domain(n, wildcard=value["provider"] != "http01") for n in names]
|
||||
# Credentials are recreated only for the duration of this invocation.
|
||||
read_private(work / "config" / "renewal" / "rustproxy.conf", 65536)
|
||||
credential_file = work / (value["provider"] + ".ini")
|
||||
if value["provider"] != "http01":
|
||||
@@ -402,7 +377,6 @@ def renew(raw: dict, certificate_directory: Path, executable: str | None = None)
|
||||
try:
|
||||
installed_cert = read_private(certificate_directory / value["cert_file"], MAX_PEM)
|
||||
installed_key = read_private(certificate_directory / value["key_file"], MAX_PEM)
|
||||
# Check dependencies/installed PEM before invoking a CA operation.
|
||||
old_dates = certificate_dates(installed_cert)
|
||||
args = [*command_prefix, "renew", "--cert-name", "rustproxy", "--non-interactive",
|
||||
"--no-random-sleep-on-renew", "--no-directory-hooks",
|
||||
@@ -434,7 +408,6 @@ def renew(raw: dict, certificate_directory: Path, executable: str | None = None)
|
||||
return output
|
||||
if dates["not_after_unix"] < old_dates["not_after_unix"]:
|
||||
raise AcmeError("acme.renewal_older_certificate")
|
||||
# Content-addressed staging keeps retries idempotent.
|
||||
stem = "acme-" + hashlib.sha256(cert + b"\0" + key).hexdigest()[:48]
|
||||
paths = [(certificate_directory / (stem + ".pem"), cert), (certificate_directory / (stem + ".key"), key)]
|
||||
if len(list(certificate_directory.glob("acme-*.key"))) >= 1024 and not paths[1][0].exists():
|
||||
@@ -468,11 +441,9 @@ def main() -> None:
|
||||
result = renew(value, args.cert_dir) if isinstance(value, dict) and value.get("action") == "renew" else issue(value, args.cert_dir)
|
||||
print(json.dumps(result))
|
||||
except (AcmeError, OSError, ValueError) as error:
|
||||
# OSError/JSON errors can contain paths/input. Do not serialize them.
|
||||
message = str(error) if isinstance(error, AcmeError) else "acme.local_io_or_json_error"
|
||||
print(json.dumps({"error": message}))
|
||||
raise SystemExit(1) from None
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compatibility entry point; all issuance uses acme_provider."""
|
||||
from acme_provider import * # noqa: F403
|
||||
from acme_provider import *
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,6 +1,4 @@
|
||||
#!/usr/bin/env bash
|
||||
# Start two TCP and two UDP mock backends for RustProxy Stream tests.
|
||||
# Usage: ./start_stream_backends.sh [bind-host]
|
||||
set -euo pipefail
|
||||
|
||||
DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
|
||||
@@ -37,7 +35,6 @@ printf 'UDP: %s:9201 (udp-a), %s:9202 (udp-b)\n' "$HOST" "$HOST"
|
||||
printf 'UDP health probe: PING => PONG\n'
|
||||
printf 'Stop: Ctrl+C\n\n'
|
||||
|
||||
# Stop the group if any backend exits unexpectedly (e.g., port conflict).
|
||||
wait -n "${pids[@]}"
|
||||
echo 'A backend stopped; stopping all mock backends.' >&2
|
||||
exit 1
|
||||
@@ -4,12 +4,10 @@ from pathlib import Path
|
||||
import sys
|
||||
import tomllib
|
||||
|
||||
|
||||
def project_version(root: Path | None = None) -> str:
|
||||
manifest = (root or Path(__file__).resolve().parents[1]) / "Cargo.toml"
|
||||
data = tomllib.loads(manifest.read_text(encoding="utf-8"))
|
||||
return data["package"]["version"]
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(project_version(Path(sys.argv[1]) if len(sys.argv) > 1 else None))
|
||||
Reference in new issue
Block a user