Files
CaddyToDSM/service_functions.py

521 lines
18 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import json
import shutil
from structs import CertInfo, DSMCredentials,ApplSettings
from pathlib import Path
from dataclasses import asdict
import logging
from configparser import ConfigParser
from caddy_worker import CaddyWorker
import subprocess
class ServiceFunctions:
def save_cert_info(self, cert_info: CertInfo, path_to_save_folder: Path):
"""
Сохраняет информацию о сертификате в JSON-файл.
JSON используется для последующего сравнения сертификата Caddy
с ранее загруженным в DSM сертификатом.
Args:
cert_info: Информация о сертификате Caddy.
path_to_save_folder: Папка для хранения информации
о сертификатах.
Returns:
Path: Путь к папке с сохранённой информацией сертификата.
"""
data = asdict(cert_info)
save_dir = path_to_save_folder / cert_info.dir_caddy_cert.name
save_dir.mkdir(parents=True, exist_ok=True)
data["expires_at"] = cert_info.expires_at.isoformat()
data["path_to_key"] = str(cert_info.path_to_key)
data["dir_caddy_cert"] = str(cert_info.dir_caddy_cert)
(save_dir / cert_info.dir_caddy_cert.name).write_text(
json.dumps(data, indent=4, ensure_ascii=False),
encoding="utf-8"
)
return save_dir
@staticmethod
def get_login_pass_from_file(path_to_file: Path):
"""
Читает данные для авторизации в DSM из файла.
Файл должен содержать параметры:
username=<логин>
password=<пароль>
Args:
path_to_file: Путь к файлу с учётными данными.
Returns:
DSMCredentials: Логин и пароль для авторизации.
None: Если файл не найден, не читается или отсутствует
логин либо пароль.
"""
if not path_to_file.is_file():
logging.error(f"Secret file not found: {path_to_file}")
return None
try:
lines = path_to_file.read_text(encoding="utf-8").splitlines()
except OSError as e:
logging.error(f"Cannot read secret file {path_to_file}: {e}")
return None
secret = {}
for line in lines:
line = line.strip()
if not line or "=" not in line:
continue
key, value = line.split("=", 1)
secret[key.strip()] = value.strip()
user_name = secret.get("username")
password = secret.get("password")
if not user_name:
logging.error("user_name is not specified in secret")
return None
if not password:
logging.error("password is not specified in secret")
return None
return DSMCredentials(
user_name=user_name,
password=password,
)
def get_caddy_proxy_domains(self, proxy_target_host: str, ssh_host: str) -> list[str]:
"""
Получает домены из Caddyfile, у которых reverse_proxy
направлен на указанный upstream-хост.
"""
from urllib.parse import urlsplit
command = [
"ssh",
"-T",
"-o", "BatchMode=yes",
"-o", "ConnectTimeout=5",
ssh_host,
"/usr/bin/caddy adapt "
"--config /etc/caddy/Caddyfile "
"--adapter caddyfile"
]
try:
result = subprocess.run(
command,
capture_output=True,
text=True,
timeout=30,
check=True
)
except (subprocess.CalledProcessError,
subprocess.TimeoutExpired) as exc:
raise RuntimeError(
"Failed to read Caddyfile from Cudy"
) from exc
config = json.loads(result.stdout)
target = proxy_target_host.strip().lower().rstrip(".")
if not target:
raise ValueError("proxyTargetHost is empty")
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 node.get("handler") == "reverse_proxy":
for upstream in node.get("upstreams", []):
if is_target_upstream(
upstream.get("dial", "")
):
return True
return any(
has_target_proxy(value)
for value in node.values()
)
if isinstance(node, list):
return any(
has_target_proxy(item)
for item in node
)
return False
servers = (
config.get("apps", {})
.get("http", {})
.get("servers", {})
)
domains = set()
for server in servers.values():
for route in server.get("routes", []):
if not has_target_proxy(route.get("handle", [])):
continue
for matcher in route.get("match", []):
for host in matcher.get("host", []):
host = host.lower().rstrip(".")
if "*" not in host:
domains.add(host)
if not domains:
raise RuntimeError(
f"No reverse_proxy domains found for {target}"
)
result_domains = sorted(domains)
logging.info(
"Domains proxied to %s: %s",
target,
", ".join(result_domains)
)
return result_domains
def load_config(self):
"""
Загружает настройки приложения из файла config.conf.
Читает список доменов и основные параметры приложения:
пути к сертификатам, файлу учётных данных, папке хранения
данных и URL DSM.
Returns:
ApplSettings: Настройки приложения.
Raises:
FileNotFoundError: Если файл config.conf не найден.
"""
config_path = Path("/etc/caddy-to-dsm/config.conf")
if not config_path.is_file():
logging.error(f"Config file not found: {config_path}")
raise FileNotFoundError(f"Config file not found: {config_path}")
config = ConfigParser(allow_no_value=True)
config.read(config_path, encoding="utf-8")
required_settings = [
"pathToCredentials",
"pathToCaddyCert",
"pathToSaveFolder",
"urlNas",
"path_to_remote_ssh_cert",
"is_load_cert_from_ssh",
"ssh_host",
"path_to_copy_ssh_cert"
]
if not config.has_section("Settings"):
raise ValueError("Missing [Settings] section")
for setting in required_settings:
if not config.has_option("Settings", setting):
raise ValueError(
f"Missing setting '{setting}' in [Settings]"
)
# Выбираем источник списка доменов
domains_source = config.get("Settings", "domainsSource", fallback="list").strip().lower()
ssh_host = config.get("Settings", "ssh_host").strip()
if domains_source == "caddyfile":
proxy_target_host = config.get(
"Settings",
"proxyTargetHost",
fallback="stadidisk.local"
)
domains = self.get_caddy_proxy_domains(
proxy_target_host,
ssh_host
)
elif domains_source == "list":
if not config.has_section("ListDomains"):
raise ValueError(
"Missing [ListDomains] section"
)
domains = list(
config["ListDomains"].keys()
)
else:
raise ValueError(
f"Unknown domainsSource: {domains_source}"
)
if not domains:
raise RuntimeError(
"Domain list is empty, synchronization aborted"
)
appl_settings = ApplSettings(
list_domains = domains,
path_to_caddy_cert = Path(config.get("Settings", "pathToCaddyCert")),
credentials = Path(config.get("Settings", "pathToCredentials")),
path_to_save_folder = Path(config.get("Settings", "pathToSaveFolder")),
nas_url = config.get("Settings", "urlNas"),
path_to_remote_ssh_cert=Path(config.get("Settings", "path_to_remote_ssh_cert")),
is_load_cert_from_ssh=config.getboolean("Settings", "is_load_cert_from_ssh"),
ssh_host=ssh_host,
path_to_copy_ssh_cert=Path(config.get("Settings", "path_to_copy_ssh_cert"))
)
return appl_settings
def search_caddy_cert(self, path_to_caddy_cert: Path, list_domains: list):
"""
Ищет папки сертификатов для настроенных доменов Caddy.
Args:
path_to_caddy_cert: Путь к папке с сертификатами Caddy.
list_domains: Список доменов из конфигурации.
Returns:
list: Список доменов, для которых найдена папка сертификата.
None: Если папка Caddy не существует или список доменов пуст.
"""
update_certs = []
if not path_to_caddy_cert.is_dir():
logging.error(f"Caddy cert folder <{path_to_caddy_cert}> not found")
return None
if not list_domains:
logging.error(f"List Domains is empty")
return None
for domain in list_domains:
folder = path_to_caddy_cert / domain
if folder.is_dir():
update_certs.append(domain)
else:
logging.warning(f"Cert <{domain}> not found in Caddy Folder")
return update_certs
@staticmethod
def remove_unnecessary_dsm_certs(path_to_dsm_certs_data: Path, list_domains: list):
"""
Удаляет локальные данные сертификатов неиспользуемых доменов.
Сравнивает существующие папки с сертификатами со списком доменов
из конфигурации и удаляет папки доменов, которых больше нет
в настройках.
Args:
path_to_dsm_certs_data: Путь к папке с сохранёнными данными
сертификатов.
list_domains: Список актуальных доменов из конфигурации.
Returns:
bool: True, если проверка и удаление завершились успешно.
False, если произошла ошибка.
"""
if not path_to_dsm_certs_data.is_dir():
logging.error(f"DSM cert folder <{path_to_dsm_certs_data}> not found")
return False
if not list_domains:
logging.error(f"List Domains is empty")
return False
for folder in path_to_dsm_certs_data.iterdir():
if not folder.is_dir():
continue
if folder.name not in list_domains:
logging.info(
f"Removing unnecessary DSM certificate: {folder.name}"
)
try:
shutil.rmtree(folder)
except OSError as e:
logging.error(
f"Cannot remove folder {folder}: {e}"
)
return False
return True
def check_update_certs(self, path_to_dsm_certs_data: Path, path_to_caddy_certs: Path, candidates_update_certs: list):
"""
Определяет сертификаты Caddy, которые необходимо обновить в DSM.
Для каждого домена сравнивает SHA-256 отпечаток текущего
сертификата Caddy с отпечатком, сохранённым после предыдущего
обновления.
Args:
path_to_dsm_certs_data: Путь к локальным данным сертификатов,
загруженных в DSM.
path_to_caddy_certs: Путь к сертификатам Caddy.
candidates_update_certs: Список доменов, для которых найдены
сертификаты Caddy.
Returns:
list: Список доменов, сертификаты которых требуют обновления.
"""
if not path_to_dsm_certs_data.is_dir():
logging.error(f"Path to certs dir not found: {path_to_dsm_certs_data}")
return []
if not candidates_update_certs:
logging.error(f"List Update is empty: {candidates_update_certs}")
return []
need_update_certs = []
for cert in candidates_update_certs:
cert_folder = path_to_dsm_certs_data / cert
if not cert_folder.is_dir():
need_update_certs.append(cert)
continue
path_to_caddy_cert = CaddyWorker.search_cert_caddy(path_to_caddy_certs, cert)
if path_to_caddy_cert is None:
logging.error(f"Caddy cert not found: {cert}")
continue
caddy_cert_info = CaddyWorker.get_cert_info(path_to_caddy_cert)
if caddy_cert_info is None:
logging.error(f"Unable to read Caddy certificate: {cert}")
continue
#Информация о сертификате который загружен в DSM
dsm_cert_info = cert_folder / cert
if dsm_cert_info.is_file() is False:
logging.error(f"Cert not found: {dsm_cert_info}")
continue
try:
with open(dsm_cert_info, "r", encoding="utf-8") as file:
data_dsm_cert = json.load(file)
except (OSError, json.JSONDecodeError) as e:
logging.error(
f"Cannot read DSM certificate info {dsm_cert_info}: {e}"
)
continue
domain_name = data_dsm_cert.get("domain_name")
fingerprint = data_dsm_cert.get("fingerprint")
if not domain_name or not fingerprint:
logging.error(
f"Invalid certificate info file: {dsm_cert_info}"
)
continue
if domain_name != caddy_cert_info.domain_name:
logging.info(
f"Cert DSM: {data_dsm_cert['domain_name']} "
f"is not located in the caddy cert "
f"{caddy_cert_info.domain_name} folder"
)
continue
if fingerprint != caddy_cert_info.fingerprint:
need_update_certs.append(cert)
logging.info(f"Cert: {cert} added to update")
else:
logging.info(f"Cert: {cert} does not require update")
return need_update_certs
@staticmethod
def remove_tmp_certificates(path_to_save_folder: Path, domain: str) -> bool:
"""
Удаляет временные файлы сертификата после завершения операции.
Удаляется папка tmp конкретного домена, содержащая PEM-файлы,
подготовленные для импорта в DSM.
Args:
path_to_save_folder: Основная папка для хранения данных
сертификатов.
domain: Домен, для которого удаляются временные файлы.
Returns:
bool: True, если временная папка удалена или уже отсутствует.
False, если удалить папку не удалось.
"""
tmp_dir = path_to_save_folder / domain / "tmp"
if not tmp_dir.is_dir():
logging.info(f"Temporary certificate folder not found: {tmp_dir}")
return True
try:
shutil.rmtree(tmp_dir)
logging.info(f"Temporary certificate folder removed: {tmp_dir}")
return True
except OSError as e:
logging.error(
f"Cannot remove temporary certificate folder {tmp_dir}: {e}"
)
return False