From c2d8cc1c337e08d30821c6f14c2153248c5062e5 Mon Sep 17 00:00:00 2001 From: Juwen Lie <73946469+juw12@users.noreply.github.com> Date: Fri, 20 Nov 2026 23:35:35 +0700 Subject: [PATCH] Mac: https works on a Mac without the Python the app was built with The built app's OpenSSL looks for certificate authorities in /Library/Frameworks/Python.framework/Versions/3.12/etc/openssl. A Mac that never had that Python has nothing there, so the update check, the update download and a brain on the internet all failed with CERTIFICATE_VERIFY_FAILED (seen on the MacBook Pro 2019 with 1.10.0 and 1.13.0). When Python's own places hold no authority, Buddy now uses the ones macOS ships: /etc/ssl/cert.pem, else Apple's root keychain. Certificate and host name checks stay on. The self-test has a check for it. --- mac/buddy_mac/certs.py | 75 ++++++++++++++++++++++ mac/buddy_mac/core.py | 5 +- mac/buddy_mac/selftest.py | 6 +- mac/buddy_mac/updater.py | 8 ++- mac/tests/fixtures/one-root.pem | 31 +++++++++ mac/tests/test_certs.py | 110 ++++++++++++++++++++++++++++++++ 6 files changed, 231 insertions(+), 4 deletions(-) create mode 100644 mac/buddy_mac/certs.py create mode 100644 mac/tests/fixtures/one-root.pem create mode 100644 mac/tests/test_certs.py diff --git a/mac/buddy_mac/certs.py b/mac/buddy_mac/certs.py new file mode 100644 index 0000000..f2703c2 --- /dev/null +++ b/mac/buddy_mac/certs.py @@ -0,0 +1,75 @@ +"""Which certificate authorities Buddy Lite for Mac trusts for https (no PyObjC here, so it is unit-tested anywhere). + +The built app carries its own OpenSSL, and that OpenSSL looks for the certificate authorities in the folder +of the Python the app was built with (/Library/Frameworks/Python.framework/Versions/3.12/etc/openssl). A Mac +that never had that Python installed has nothing there, so every https call failed with +CERTIFICATE_VERIFY_FAILED: the update check, the update download and the brain. Found on the MacBook Pro 2019 +on 2026-11-20; the tests never saw it because they talk to a brain on this computer and read the update +manifest from a file. + +So: when Python's own places hold no certificate authority, use the ones macOS ships. +""" +from __future__ import annotations + +import logging +import ssl +import subprocess + +# macOS keeps its root certificates as one file here (it is what the system's own curl reads). +MAC_CA_FILE = "/etc/ssl/cert.pem" +# The same roots, straight from the keychain Apple ships. Asked only when the file above is missing or empty. +MAC_ROOT_KEYCHAIN = "/System/Library/Keychains/SystemRootCertificates.keychain" +SECURITY_TIMEOUT_SECONDS = 15 + +_context: ssl.SSLContext | None = None + + +def _authorities(context: ssl.SSLContext) -> int: + return int(context.cert_store_stats().get("x509_ca", 0)) + + +def _keychain_roots() -> str: + """Apple's root certificates as PEM text, or "" when they cannot be read.""" + try: + done = subprocess.run( + ["/usr/bin/security", "find-certificate", "-a", "-p", MAC_ROOT_KEYCHAIN], + capture_output=True, text=True, timeout=SECURITY_TIMEOUT_SECONDS, check=False, + ) + except (OSError, subprocess.SubprocessError): + return "" + return done.stdout if done.returncode == 0 else "" + + +def build_context(ca_file: str = MAC_CA_FILE, keychain_roots=_keychain_roots) -> tuple[ssl.SSLContext, str]: + """An https context that checks certificates, and where its authorities came from: + "python" (the places Python and $SSL_CERT_FILE name), "macos file", "macos keychain" or "none".""" + context = ssl.create_default_context() + if _authorities(context): + return context, "python" + try: + context.load_verify_locations(cafile=ca_file) + except (OSError, ssl.SSLError): + pass + if _authorities(context): + return context, "macos file" + roots = keychain_roots() + if roots: + try: + context.load_verify_locations(cadata=roots) + except (ssl.SSLError, ValueError): + pass + if _authorities(context): + return context, "macos keychain" + return context, "none" + + +def https_context() -> ssl.SSLContext: + """The context every https call of Buddy uses. Made once; the log says where the authorities came from.""" + global _context + if _context is None: + _context, source = build_context() + if source == "none": + logging.warning("https: no certificate authorities found on this Mac, so https calls will fail") + else: + logging.info("https certificates: %s (%d authorities)", source, _authorities(_context)) + return _context diff --git a/mac/buddy_mac/core.py b/mac/buddy_mac/core.py index a4025a9..62e3a10 100644 --- a/mac/buddy_mac/core.py +++ b/mac/buddy_mac/core.py @@ -20,6 +20,8 @@ from dataclasses import dataclass, field from pathlib import Path +from . import certs + APP_NAME = "Buddy" VERSION = "1.13.0" @@ -525,7 +527,8 @@ def _is_loopback_url(url: str) -> bool: def _open(request: urllib.request.Request, timeout: float): if _is_loopback_url(request.full_url): return _DIRECT_OPENER.open(request, timeout=timeout) - return urllib.request.urlopen(request, timeout=timeout) + # The context brings the certificate authorities: the built app has none of its own on most Macs (certs.py). + return urllib.request.urlopen(request, timeout=timeout, context=certs.https_context()) @dataclass diff --git a/mac/buddy_mac/selftest.py b/mac/buddy_mac/selftest.py index 3e9ea6d..eedc61f 100644 --- a/mac/buddy_mac/selftest.py +++ b/mac/buddy_mac/selftest.py @@ -18,7 +18,7 @@ from AppKit import NSApp, NSScreen from PyObjCTools import AppHelper -from . import core, ocr +from . import certs, core, ocr from .app import Controller CANNED_REPLY = ( @@ -86,6 +86,10 @@ def start(self): self.report["checks"]["speech_in_available"] = self.listener.ok self.report["checks"]["speech_out_available"] = self.speaker.ok self.report["checks"]["menu_bar_item"] = self.status_item is not None + # Without certificate authorities no https call works: not the update check, not a brain on the internet. + _, source = certs.build_context() + self.report["https_certificates"] = source + self.report["checks"]["https_certificates"] = source != "none" self._check_island() self._check_text_recognition() self._check_voice_languages() diff --git a/mac/buddy_mac/updater.py b/mac/buddy_mac/updater.py index cf87b4f..0f7e701 100644 --- a/mac/buddy_mac/updater.py +++ b/mac/buddy_mac/updater.py @@ -21,6 +21,8 @@ import urllib.request from pathlib import Path +from . import certs + MANIFEST_URL = "https://juw12.github.io/buddy/latest.json" USER_AGENT = "Buddy-Mac-Updater" @@ -44,8 +46,10 @@ def is_newer(remote, local) -> bool: def _openers(): - yield urllib.request.build_opener() - yield urllib.request.build_opener(urllib.request.ProxyHandler({})) + # Both routes check certificates against the authorities certs.py found (the built app has none of its own). + https = urllib.request.HTTPSHandler(context=certs.https_context()) + yield urllib.request.build_opener(https) + yield urllib.request.build_opener(urllib.request.ProxyHandler({}), https) def _open(url: str, timeout: float): diff --git a/mac/tests/fixtures/one-root.pem b/mac/tests/fixtures/one-root.pem new file mode 100644 index 0000000..b85c803 --- /dev/null +++ b/mac/tests/fixtures/one-root.pem @@ -0,0 +1,31 @@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Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV +HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq +hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL +ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ +3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK +NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5 +ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur +TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC +jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc +oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq +4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA +mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d +emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc= +-----END CERTIFICATE----- diff --git a/mac/tests/test_certs.py b/mac/tests/test_certs.py new file mode 100644 index 0000000..d0364d3 --- /dev/null +++ b/mac/tests/test_certs.py @@ -0,0 +1,110 @@ +"""Buddy Lite for Mac: which certificate authorities https calls trust (runs anywhere, no network).""" +import ssl +import sys +import urllib.request +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from buddy_mac import certs, core, updater # noqa: E402 + +ONE_ROOT = Path(__file__).parent / "fixtures" / "one-root.pem" # ISRG Root X1, a public certificate + + +def _bare_context(): + """What the built app gets on a Mac without the Python it was built with: a context with no authorities.""" + context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + assert context.cert_store_stats()["x509_ca"] == 0 + return context + + +def _never(): + raise AssertionError("the keychain must not be asked") + + +def test_pythons_own_authorities_are_used_when_there_are_some(monkeypatch): + def with_one_root(): + context = _bare_context() + context.load_verify_locations(cafile=str(ONE_ROOT)) + return context + + monkeypatch.setattr(ssl, "create_default_context", with_one_root) + context, source = certs.build_context(ca_file="/nowhere/cert.pem", keychain_roots=_never) + assert source == "python" + assert context.cert_store_stats()["x509_ca"] == 1 + + +def test_the_macos_file_is_used_when_python_has_none(monkeypatch): + monkeypatch.setattr(ssl, "create_default_context", _bare_context) + context, source = certs.build_context(ca_file=str(ONE_ROOT), keychain_roots=_never) + assert source == "macos file" + assert context.cert_store_stats()["x509_ca"] == 1 + assert context.verify_mode == ssl.CERT_REQUIRED and context.check_hostname # still checking + + +def test_the_keychain_is_asked_when_the_file_is_missing(monkeypatch): + monkeypatch.setattr(ssl, "create_default_context", _bare_context) + context, source = certs.build_context(ca_file="/nowhere/cert.pem", + keychain_roots=lambda: ONE_ROOT.read_text(encoding="utf-8")) + assert source == "macos keychain" + assert context.cert_store_stats()["x509_ca"] == 1 + + +def test_nothing_found_is_said_and_never_switches_checking_off(monkeypatch): + monkeypatch.setattr(ssl, "create_default_context", _bare_context) + for roots in ("", "not a certificate"): + context, source = certs.build_context(ca_file="/nowhere/cert.pem", keychain_roots=lambda roots=roots: roots) + assert source == "none" + assert context.cert_store_stats()["x509_ca"] == 0 + assert context.verify_mode == ssl.CERT_REQUIRED and context.check_hostname + + +def test_the_context_is_made_once(monkeypatch): + made = [] + + def build(): + made.append(1) + return _bare_context(), "macos file" + + monkeypatch.setattr(certs, "_context", None) + monkeypatch.setattr(certs, "build_context", build) + assert certs.https_context() is certs.https_context() + assert made == [1] + + +def test_the_brain_call_brings_the_context_and_a_local_brain_does_not(monkeypatch): + marker = _bare_context() + seen = {} + + def fake_urlopen(request, timeout=None, context=None): + seen["context"] = context + return "internet" + + monkeypatch.setattr(certs, "_context", marker) + monkeypatch.setattr(urllib.request, "urlopen", fake_urlopen) + request = urllib.request.Request("https://example.com/v1/chat/completions", b"{}") + assert core._open(request, 5) == "internet" + assert seen["context"] is marker + + class Direct: + def open(self, request, timeout=None): + return "this computer" + + monkeypatch.setattr(core, "_DIRECT_OPENER", Direct()) + seen.clear() + assert core._open(urllib.request.Request("http://127.0.0.1:11434/v1/chat/completions", b"{}"), 5) == "this computer" + assert seen == {} + + +def test_both_update_routes_check_certificates_with_the_context(monkeypatch): + marker = _bare_context() + monkeypatch.setattr(certs, "_context", marker) + openers = list(updater._openers()) + assert len(openers) == 2 + for opener in openers: + https = [handler for handler in opener.handlers if isinstance(handler, urllib.request.HTTPSHandler)] + assert len(https) == 1 + assert https[0]._context is marker + # the second route still goes around a proxy + assert not any(isinstance(handler, urllib.request.ProxyHandler) and handler.proxies + for handler in openers[1].handlers)