from service_functions import ServiceFunctions from structs import DSMAuthInfo, DSMInfo import logging import requests class DSMWorker: AUTH_API = "SYNO.API.Auth" AUTH_VERSION = "7" AUTH_METHOD_LOGIN = "login" AUTH_FORMAT_SID = "sid" AUTH_ENABLE_SYNO_TOKEN = "yes" CERT_API = "SYNO.Core.Certificate.CRT" CERT_VERSION = "1" CERT_METHOD_LIST = "list" CERT_IMPORT_API = "SYNO.Core.Certificate" CERT_IMPORT_VERSION = "1" CERT_IMPORT_METHOD = "import" def __init__(self, dsm_url: str): self.dsm_url = dsm_url.rstrip("/") self.sid: str | None = None self.token: str | None = None def auth_in_DSM(self, path_to_secret) -> DSMAuthInfo | None: dsm_cred = ServiceFunctions.get_login_pass_from_file(path_to_secret) url = f"{self.dsm_url}/webapi/entry.cgi" auth_params = { "api": self.AUTH_API, "version": self.AUTH_VERSION, "method": self.AUTH_METHOD_LOGIN, "account": dsm_cred.user_name, "passwd": dsm_cred.password, "format": self.AUTH_FORMAT_SID, "enable_syno_token": self.AUTH_ENABLE_SYNO_TOKEN, } try: response = requests.post( url, data=auth_params, timeout=10, verify=False, ) response.raise_for_status() except requests.RequestException as e: logging.error(f"Cannot connect to DSM: {e}") return None try: result = response.json() except ValueError as e: logging.error(f"DSM returned invalid JSON: {e}") return None if not result.get("success"): error = result.get("error", {}) logging.error( f"DSM authentication failed: " f"code={error.get('code')}" ) return None data = result.get("data", {}) sid = data.get("sid") token = data.get("synotoken") if not sid: logging.error("DSM did not return SID") return None if not token: logging.error("DSM did not return SynoToken") return None self.sid = sid self.token = token logging.info("Successfully authenticated in DSM") return DSMAuthInfo( sid=sid, token=token, ) def get_list_certs(self): if not self.sid or not self.token: logging.error("DSM authentication required") return None url = f"{self.dsm_url}/webapi/entry.cgi" params = { "api": self.CERT_API, "version": self.CERT_VERSION, "method": self.CERT_METHOD_LIST, "_sid": self.sid, } headers = { "X-SYNO-TOKEN": self.token, } try: response = requests.post( url, headers=headers, data=params, timeout=10, verify=False, ) response.raise_for_status() except requests.RequestException as e: logging.error(f"Cannot get certificate list from DSM: {e}") return None try: result = response.json() except ValueError as e: logging.error(f"DSM returned invalid JSON: {e}") return None if not result.get("success"): error = result.get("error", {}) logging.error( f"Cannot get certificate list from DSM: " f"code={error.get('code')}" ) return None return result.get("data") def import_cert(self, dsm_info: DSMInfo) -> bool: if not self.sid or not self.token: logging.error("DSM authentication required") return False if not dsm_info.private_key_path.is_file(): logging.error( f"Private key not found: {dsm_info.private_key_path}" ) return False if not dsm_info.certificate_pem_path.is_file(): logging.error( f"Certificate not found: {dsm_info.certificate_pem_path}" ) return False if not dsm_info.path_to_fullchain.is_file(): logging.error( f"Fullchain certificate not found: " f"{dsm_info.path_to_fullchain}" ) return False certificates_json = self.get_list_certs() if certificates_json is None: logging.error("Unable to get certificate list from DSM") return False certificates = certificates_json.get("certificates", []) cert_id = "" is_default = False # Поиск сертификата в списке for certificate in certificates: if certificate.get("desc") != dsm_info.certificate_name: continue cert_id = certificate.get("id", "") is_default = certificate.get("is_default", False) logging.info( f"Found existing certificate: " f"{dsm_info.certificate_name}, id={cert_id}" ) break url = f"{self.dsm_url}/webapi/entry.cgi" params = { "api": self.CERT_IMPORT_API, "version": self.CERT_IMPORT_VERSION, "method": self.CERT_IMPORT_METHOD, "SynoToken": self.token, "_sid": self.sid, } data = { "id": "", "desc": dsm_info.certificate_name, } if is_default: data["as_default"] = "true" try: with open(dsm_info.private_key_path, "rb") as key_file, \ open(dsm_info.certificate_pem_path, "rb") as cert_file, \ open(dsm_info.path_to_fullchain, "rb") as fullchain_file: files = { "key": ("private.key", key_file), "cert": ("cert.pem", cert_file), "inter_cert": ("inter_cert.pem", fullchain_file), "id": (None, cert_id), "desc": (None, dsm_info.certificate_name), } response = requests.post( url, params=params, data=data, files=files, timeout=30, verify=False, ) except OSError as e: logging.error(f"Cannot open certificate files: {e}") return False except requests.RequestException as e: logging.error(f"Certificate import request failed: {e}") return False try: result = response.json() except ValueError as e: logging.error(f"DSM returned invalid JSON: {e}") return False if not result.get("success"): error = result.get("error", {}) logging.error( f"Certificate import failed: " f"code={error.get('code')}" ) return False logging.info( f"Certificate successfully imported: " f"{dsm_info.certificate_name}" ) return True