|
| 1 | +import asyncio |
| 2 | +import logging |
| 3 | +from pathlib import Path |
| 4 | +import shutil |
| 5 | + |
| 6 | +import certifi |
| 7 | +from homeassistant.core import HomeAssistant |
| 8 | + |
| 9 | + |
| 10 | +_LOGGER = logging.getLogger(__name__) |
| 11 | + |
| 12 | + |
| 13 | +# Heavily based on https://github.com/Athozs/hass-additional-ca/blob/c9499d39a4b4d7175336d1d31c4e1b6d9bd6932f/custom_components/additional_ca/__init__.py#L125 |
| 14 | +async def update_certifi_certificates(hass: HomeAssistant) -> bool: |
| 15 | + """Update CA certificates in Certifi bundle.""" |
| 16 | + |
| 17 | + certifi_bundle_path = Path(certifi.where()) |
| 18 | + _LOGGER.debug(f"Certifi CA bundle path: {certifi_bundle_path}") |
| 19 | + |
| 20 | + certifi_backup_path = certifi_bundle_path.with_suffix( |
| 21 | + certifi_bundle_path.suffix + ".bak" |
| 22 | + ) |
| 23 | + |
| 24 | + rapidssl_ca_path = Path(__file__).with_name("RapidSSL_TLS_RSA_CA_G1.crt") |
| 25 | + |
| 26 | + if certifi_backup_path.exists(): |
| 27 | + # reset Certifi bundle |
| 28 | + await hass.async_add_executor_job( |
| 29 | + shutil.copyfile, certifi_backup_path, certifi_bundle_path |
| 30 | + ) |
| 31 | + else: |
| 32 | + # backup Certifi bundle |
| 33 | + await hass.async_add_executor_job( |
| 34 | + shutil.copyfile, certifi_bundle_path, certifi_backup_path |
| 35 | + ) |
| 36 | + |
| 37 | + _LOGGER.info("Certifi bundle CA ready.") |
| 38 | + |
| 39 | + cacerts, rapidssl_ca = await asyncio.gather( |
| 40 | + *( |
| 41 | + hass.async_add_executor_job(path.read_text) |
| 42 | + for path in (certifi_bundle_path, rapidssl_ca_path) |
| 43 | + ) |
| 44 | + ) |
| 45 | + |
| 46 | + if rapidssl_ca not in cacerts: |
| 47 | + cert_name = rapidssl_ca_path.stem.replace("_", " ") |
| 48 | + cacerts += f"\n# Haier hOn: {cert_name}\n" |
| 49 | + cacerts += rapidssl_ca |
| 50 | + await hass.async_add_executor_job(certifi_bundle_path.write_text, cacerts) |
| 51 | + |
| 52 | + _LOGGER.info( |
| 53 | + f"{cert_name} -> loaded into Certifi CA bundle. Restart Home Assistant to apply changes." |
| 54 | + ) |
| 55 | + |
| 56 | + return True |
0 commit comments