work: добавил фильтр по stadidisk.local. Теперь импротируются только те прокси, которые проксируются на nas (stadidisk.local)

This commit is contained in:
2026-10-29 22:36:00 +03:00
parent 9d9089ad50
commit 899e8092da
2 changed files with 63 additions and 37 deletions
+1
View File
@@ -6,6 +6,7 @@ wud.stadidisk.ru
[Settings] [Settings]
# Источник списка: list или caddyfile # Источник списка: list или caddyfile
domainsSource=caddyfile domainsSource=caddyfile
proxyTargetHost=stadidisk.local
#Путь к файлу с логином/паролем для авторизации #Путь к файлу с логином/паролем для авторизации
pathToCredentials=/etc/caddy-to-dsm/.secret pathToCredentials=/etc/caddy-to-dsm/.secret
+62 -37
View File
@@ -97,20 +97,20 @@ class ServiceFunctions:
password=password, password=password,
) )
def get_caddy_proxy_domains(self, proxy_target_host: str, ssh_host: str) -> list[str]:
"""
Получает домены из Caddyfile, у которых reverse_proxy
направлен на указанный upstream-хост.
"""
def get_caddy_proxy_domains(self,domain_suffix: str) -> list[str]: from urllib.parse import urlsplit
"""
Получает список reverse_proxy-доменов с Cudy
через SSH и caddy adapt.
"""
settings = self.load_config()
command = [ command = [
"ssh", "ssh",
"-T", "-T",
"-o", "BatchMode=yes", "-o", "BatchMode=yes",
"-o", "ConnectTimeout=5", "-o", "ConnectTimeout=5",
settings.ssh_host, ssh_host,
"/usr/bin/caddy adapt " "/usr/bin/caddy adapt "
"--config /etc/caddy/Caddyfile " "--config /etc/caddy/Caddyfile "
"--adapter caddyfile" "--adapter caddyfile"
@@ -131,65 +131,87 @@ class ServiceFunctions:
) from exc ) from exc
config = json.loads(result.stdout) config = json.loads(result.stdout)
target = proxy_target_host.strip().lower().rstrip(".")
servers = ( if not target:
config.get("apps", {}) raise ValueError("proxyTargetHost is empty")
.get("http", {})
.get("servers", {})
)
def has_reverse_proxy(node): def is_target_upstream(dial: str) -> bool:
if not isinstance(dial, str):
return False
address = dial.strip()
if address.startswith("tcp/"):
address = address[4:]
try:
parsed = urlsplit(
address if "://" in address
else "//" + address
)
hostname = (parsed.hostname or "").lower().rstrip(".")
except ValueError:
return False
return hostname == target
def has_target_proxy(node) -> bool:
if isinstance(node, dict): if isinstance(node, dict):
if node.get("handler") == "reverse_proxy": if node.get("handler") == "reverse_proxy":
return True for upstream in node.get("upstreams", []):
if is_target_upstream(
upstream.get("dial", "")
):
return True
return any( return any(
has_reverse_proxy(value) has_target_proxy(value)
for value in node.values() for value in node.values()
) )
if isinstance(node, list): if isinstance(node, list):
return any( return any(
has_reverse_proxy(item) has_target_proxy(item)
for item in node for item in node
) )
return False return False
suffix = domain_suffix.strip().lower().strip(".") servers = (
if not suffix: config.get("apps", {})
raise ValueError("domainSuffix is empty") .get("http", {})
.get("servers", {})
)
domains = set() domains = set()
for server in servers.values(): for server in servers.values():
for route in server.get("routes", []): for route in server.get("routes", []):
if not has_reverse_proxy( if not has_target_proxy(route.get("handle", [])):
route.get("handle", [])
):
continue continue
for matcher in route.get("match", []): for matcher in route.get("match", []):
for host in matcher.get("host", []): for host in matcher.get("host", []):
host = host.lower().rstrip(".") host = host.lower().rstrip(".")
if "*" in host: if "*" not in host:
continue
if (
host == suffix
or host.endswith("." + suffix)
):
domains.add(host) domains.add(host)
if not domains: if not domains:
raise RuntimeError( raise RuntimeError(
"No reverse_proxy domains found in Caddyfile" f"No reverse_proxy domains found for {target}"
) )
result_domains = sorted(domains) result_domains = sorted(domains)
logging.info("Caddy proxy domains: %s",", ".join(result_domains)) logging.info(
"Domains proxied to %s: %s",
target,
", ".join(result_domains)
)
return result_domains return result_domains
@@ -242,16 +264,19 @@ class ServiceFunctions:
# Выбираем источник списка доменов # Выбираем источник списка доменов
domains_source = config.get("Settings", "domainsSource", fallback="list").strip().lower() domains_source = config.get("Settings", "domainsSource", fallback="list").strip().lower()
ssh_host = config.get("Settings", "ssh_host").strip()
if domains_source == "caddyfile": if domains_source == "caddyfile":
domain_suffix = config.get( proxy_target_host = config.get(
"Settings", "Settings",
"domainSuffix", "proxyTargetHost",
fallback="stadidisk.local" fallback="stadidisk.local"
) )
domains = self.get_caddy_proxy_domains(domain_suffix) domains = self.get_caddy_proxy_domains(
proxy_target_host,
ssh_host
)
elif domains_source == "list": elif domains_source == "list":
@@ -281,8 +306,8 @@ class ServiceFunctions:
path_to_save_folder = Path(config.get("Settings", "pathToSaveFolder")), path_to_save_folder = Path(config.get("Settings", "pathToSaveFolder")),
nas_url = config.get("Settings", "urlNas"), nas_url = config.get("Settings", "urlNas"),
path_to_remote_ssh_cert=Path(config.get("Settings", "path_to_remote_ssh_cert")), path_to_remote_ssh_cert=Path(config.get("Settings", "path_to_remote_ssh_cert")),
is_load_cert_from_ssh=bool(config.get("Settings", "is_load_cert_from_ssh")), is_load_cert_from_ssh=config.getboolean("Settings", "is_load_cert_from_ssh"),
ssh_host=config.get("Settings", "ssh_host"), ssh_host=ssh_host,
path_to_copy_ssh_cert=Path(config.get("Settings", "path_to_copy_ssh_cert")) path_to_copy_ssh_cert=Path(config.get("Settings", "path_to_copy_ssh_cert"))
) )
return appl_settings return appl_settings