from service_functions import ServiceFunctions from structs import DSMAuthInfo, DSMInfo import logging import requests import json 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" CERT_SERVICE_API = "SYNO.Core.Certificate.Service" CERT_SERVICE_VERSION = "1" CERT_SERVICE_METHOD_SET = "set" 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) -> DSMInfo: if not self.sid or not self.token: logging.error("DSM authentication required") return None if not dsm_info.private_key_path.is_file(): logging.error( f"Private key not found: {dsm_info.private_key_path}" ) return None if not dsm_info.certificate_pem_path.is_file(): logging.error( f"Certificate not found: {dsm_info.certificate_pem_path}" ) return None if not dsm_info.path_to_fullchain.is_file(): logging.error( f"Fullchain certificate not found: " f"{dsm_info.path_to_fullchain}" ) return None certificates_json = self.get_list_certs() if certificates_json is None: logging.error("Unable to get certificate list from DSM") return None 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 None except requests.RequestException as e: logging.error(f"Certificate import request failed: {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"Certificate import failed: " f"code={error.get('code')}" ) return None logging.info( f"Certificate successfully imported: " f"{dsm_info.certificate_name}" ) dsm_info.dsm_id_cert = result["data"].get("id") return dsm_info def get_list_services(self, list_certs): services = [] if not list_certs: logging.error( "list_certs is empty, cannot get list of services", ) return None certificates = list_certs.get("certificates") if not isinstance(certificates, list): logging.error( "Invalid certificates: expected list, got %s", type(certificates).__name__, ) return None for certificate in certificates: for service in certificate.get("services", []): services.append({ "service": service, "old_id": certificate["id"], "id": None, }) return services def set_cert_on_service(self, list_services, 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 find_service = None for service in list_services: if dsm_info.certificate_name == service["service"].get("display_name"): find_service = service break if find_service is None: logging.error( f"Service not found in: {dsm_info.certificate_name}" ) return False if not dsm_info.dsm_id_cert: logging.error("DSM certificate ID is required") return False if find_service["old_id"] == dsm_info.dsm_id_cert: logging.info( f"Certificate already set for service: " f"{dsm_info.certificate_name}" ) return True find_service["id"] = dsm_info.dsm_id_cert settings = [find_service] url = f"{self.dsm_url}/webapi/entry.cgi" params = { "api": self.CERT_SERVICE_API, "version": self.CERT_SERVICE_VERSION, "method": self.CERT_SERVICE_METHOD_SET, "SynoToken": self.token, "_sid": self.sid, } data = { "settings": json.dumps(settings), } try: response = requests.post( url, params=params, data=data, timeout=30, verify=False, ) except requests.RequestException as e: logging.error(f"Certificate request 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 service set failed: " f"code={error.get('code')}" ) return False logging.info( f"Certificate successfully set service: " f"{dsm_info.certificate_name}" ) return True def logout_dsm(self) -> bool: if not self.sid: logging.info("DSM session is not active") return True url = f"{self.dsm_url}/webapi/entry.cgi" params = { "api": self.AUTH_API, "version": self.AUTH_VERSION, "method": "logout", "_sid": self.sid, } try: response = requests.get( url, params=params, timeout=30, verify=False, ) response.raise_for_status() except requests.RequestException as e: logging.error(f"DSM logout 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"DSM logout failed: code={error.get('code')}" ) return False self.sid = None self.token = None logging.info("DSM session successfully closed") return True