Add Web 2 workspace and controlled deployment updates
This commit is contained in:
@@ -0,0 +1,194 @@
|
||||
"""Web settings and password verification, without desktop imports or disk reads."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
from dataclasses import dataclass, field
|
||||
import hashlib
|
||||
import hmac
|
||||
import ipaddress
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import secrets
|
||||
from typing import Mapping
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
|
||||
DEFAULT_DATA_DIR = Path(__file__).resolve().parents[1] / "local_state" / "ranch_web"
|
||||
DEFAULT_HOST = "127.0.0.1"
|
||||
DEFAULT_PORT = 8765
|
||||
COOKIE_NAME = "ranch_web_session"
|
||||
_HASH_PREFIX = "pbkdf2_sha256$"
|
||||
|
||||
|
||||
def is_loopback(host: str) -> bool:
|
||||
if host.lower() == "localhost":
|
||||
return True
|
||||
try:
|
||||
address = ipaddress.ip_address(host)
|
||||
if isinstance(address, ipaddress.IPv6Address) and address.ipv4_mapped:
|
||||
return address.ipv4_mapped.is_loopback
|
||||
return address.is_loopback
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def normalize_host(value: str) -> str:
|
||||
"""Accept a hostname / IP literal, never URLs, ports or wildcard patterns."""
|
||||
candidate = value.strip().lower()
|
||||
if candidate.startswith("[") and candidate.endswith("]"):
|
||||
candidate = candidate[1:-1]
|
||||
try:
|
||||
return str(ipaddress.ip_address(candidate))
|
||||
except ValueError:
|
||||
pass
|
||||
if len(candidate) > 253 or not re.fullmatch(
|
||||
r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*",
|
||||
candidate,
|
||||
):
|
||||
raise ValueError("允许的主机必须是明确的域名或 IP 地址,不能包含通配符或端口")
|
||||
return candidate
|
||||
|
||||
|
||||
def normalize_origin(value: str) -> str:
|
||||
parsed = urlsplit(value)
|
||||
if (
|
||||
parsed.scheme not in {"http", "https"}
|
||||
or not parsed.hostname
|
||||
or parsed.username is not None
|
||||
or parsed.password is not None
|
||||
or parsed.path not in {"", "/"}
|
||||
or parsed.query
|
||||
or parsed.fragment
|
||||
):
|
||||
raise ValueError("允许的来源必须是明确的 http 或 https 来源")
|
||||
host = normalize_host(parsed.hostname)
|
||||
try:
|
||||
port = parsed.port
|
||||
except ValueError:
|
||||
raise ValueError("允许的来源端口无效") from None
|
||||
if port is not None and not 1 <= port <= 65535:
|
||||
raise ValueError("允许的来源端口无效")
|
||||
authority = f"[{host}]" if ":" in host else host
|
||||
if port is not None and port != (443 if parsed.scheme == "https" else 80):
|
||||
authority += f":{port}"
|
||||
return f"{parsed.scheme}://{authority}"
|
||||
|
||||
|
||||
def _hash_parts(encoded: str) -> tuple[int, bytes, bytes]:
|
||||
try:
|
||||
algorithm, raw_iterations, salt, digest = encoded.split("$")
|
||||
iterations = int(raw_iterations)
|
||||
expected = base64.b64decode(digest, validate=True)
|
||||
if (
|
||||
algorithm != "pbkdf2_sha256"
|
||||
or not 100_000 <= iterations <= 2_000_000
|
||||
or not 8 <= len(salt) <= 128
|
||||
or len(expected) != 32
|
||||
):
|
||||
raise ValueError
|
||||
return iterations, salt.encode("utf-8"), expected
|
||||
except (ValueError, TypeError):
|
||||
raise ValueError("管理密码哈希格式无效") from None
|
||||
|
||||
|
||||
def hash_password(password: str, *, iterations: int = 600_000) -> str:
|
||||
if not password or len(password) > 1024 or not 100_000 <= iterations <= 2_000_000:
|
||||
raise ValueError("密码或哈希迭代次数无效")
|
||||
salt = secrets.token_hex(16)
|
||||
digest = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt.encode(), iterations)
|
||||
return f"{_HASH_PREFIX}{iterations}${salt}${base64.b64encode(digest).decode('ascii')}"
|
||||
|
||||
|
||||
def verify_password(password: str, configured: str) -> bool:
|
||||
if configured.startswith(_HASH_PREFIX):
|
||||
iterations, salt, expected = _hash_parts(configured)
|
||||
candidate = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, iterations)
|
||||
return hmac.compare_digest(candidate, expected)
|
||||
# Equal-length digests also permit non-ASCII passwords with compare_digest.
|
||||
return hmac.compare_digest(
|
||||
hashlib.sha256(password.encode("utf-8")).digest(),
|
||||
hashlib.sha256(configured.encode("utf-8")).digest(),
|
||||
)
|
||||
|
||||
|
||||
def _env_bool(value: str, name: str) -> bool:
|
||||
normalized = value.strip().lower()
|
||||
if normalized in {"1", "true", "yes", "on"}:
|
||||
return True
|
||||
if normalized in {"0", "false", "no", "off", ""}:
|
||||
return False
|
||||
raise ValueError(f"{name} 必须是布尔值")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class WebConfig:
|
||||
host: str = DEFAULT_HOST
|
||||
port: int = DEFAULT_PORT
|
||||
data_dir: Path = DEFAULT_DATA_DIR
|
||||
password: str = field(default="", repr=False)
|
||||
password_hash: str = field(default="", repr=False)
|
||||
allowed_hosts: tuple[str, ...] = ()
|
||||
allowed_origins: tuple[str, ...] = ()
|
||||
secure_cookie: bool = False
|
||||
session_ttl: int = 43_200
|
||||
max_body_bytes: int = 1_048_576
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
object.__setattr__(self, "host", normalize_host(self.host))
|
||||
object.__setattr__(self, "data_dir", Path(self.data_dir).expanduser().absolute())
|
||||
object.__setattr__(self, "allowed_hosts", tuple(normalize_host(h) for h in self.allowed_hosts))
|
||||
object.__setattr__(self, "allowed_origins", tuple(normalize_origin(o) for o in self.allowed_origins))
|
||||
if type(self.port) is not int or not 1 <= self.port <= 65535:
|
||||
raise ValueError("监听端口必须在 1–65535 之间")
|
||||
if type(self.session_ttl) is not int or not 60 <= self.session_ttl <= 2_592_000:
|
||||
raise ValueError("管理会话有效期必须在 60–2592000 秒之间")
|
||||
if type(self.max_body_bytes) is not int or not 1024 <= self.max_body_bytes <= 16_777_216:
|
||||
raise ValueError("请求正文上限必须在 1 KiB–16 MiB 之间")
|
||||
if self.password and self.password_hash:
|
||||
raise ValueError("管理密码和管理密码哈希只能配置一个")
|
||||
if self.password_hash:
|
||||
_hash_parts(self.password_hash)
|
||||
elif self.password.startswith(_HASH_PREFIX):
|
||||
_hash_parts(self.password)
|
||||
if not is_loopback(self.host) and not self.credential:
|
||||
raise ValueError("非本机绑定必须设置 RANCH_WEB_PASSWORD 或 RANCH_WEB_PASSWORD_HASH")
|
||||
# Public proxy hostnames must never silently enable the local password bypass.
|
||||
if not self.credential and any(not is_loopback(h) for h in self.allowed_hosts):
|
||||
raise ValueError("允许远程域名访问时必须设置 RANCH_WEB_PASSWORD 或 RANCH_WEB_PASSWORD_HASH")
|
||||
if not self.credential and any(not is_loopback(urlsplit(o).hostname or "") for o in self.allowed_origins):
|
||||
raise ValueError("允许远程来源访问时必须设置管理密码")
|
||||
|
||||
@property
|
||||
def credential(self) -> str:
|
||||
return self.password_hash or self.password
|
||||
|
||||
@property
|
||||
def access_mode(self) -> str:
|
||||
return "password" if self.credential else "local"
|
||||
|
||||
@property
|
||||
def trusted_hosts(self) -> frozenset[str]:
|
||||
hosts = {"localhost", "127.0.0.1", "::1", *self.allowed_hosts}
|
||||
if self.host not in {"0.0.0.0", "::"}:
|
||||
hosts.add(self.host)
|
||||
return frozenset(hosts)
|
||||
|
||||
@classmethod
|
||||
def from_env(cls, env: Mapping[str, str] | None = None, **overrides) -> WebConfig:
|
||||
values = os.environ if env is None else env
|
||||
settings = {
|
||||
"host": values.get("RANCH_WEB_HOST", DEFAULT_HOST),
|
||||
"port": int(values.get("RANCH_WEB_PORT", DEFAULT_PORT)),
|
||||
"data_dir": values.get("RANCH_WEB_DATA_DIR", DEFAULT_DATA_DIR),
|
||||
"password": values.get("RANCH_WEB_PASSWORD", ""),
|
||||
"password_hash": values.get("RANCH_WEB_PASSWORD_HASH", ""),
|
||||
"allowed_hosts": tuple(h.strip() for h in values.get("RANCH_WEB_ALLOWED_HOSTS", "").split(",") if h.strip()),
|
||||
"allowed_origins": tuple(o.strip() for o in values.get("RANCH_WEB_ALLOWED_ORIGINS", "").split(",") if o.strip()),
|
||||
"secure_cookie": _env_bool(values.get("RANCH_WEB_SECURE_COOKIE", ""), "RANCH_WEB_SECURE_COOKIE"),
|
||||
"session_ttl": int(values.get("RANCH_WEB_SESSION_TTL", 43_200)),
|
||||
"max_body_bytes": int(values.get("RANCH_WEB_MAX_BODY_BYTES", 1_048_576)),
|
||||
}
|
||||
settings.update(overrides)
|
||||
return cls(**settings)
|
||||
Reference in New Issue
Block a user