1# Copyright (C) 2024 The Android Open Source Project 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14 15"""Custom locater for CA_CERTS files.""" 16 17import atexit 18import importlib.resources 19import os 20import pathlib 21import shutil 22import tempfile 23from httplib2 import certs 24 25 26def get() -> str: 27 """Locate the ca_certs.txt file. 28 29 The httplib2 library will look for local ca_certs_locater module to override 30 the default location for the ca_certs.txt file. We override it here to load 31 via resources for python binary built with embedded launcher. 32 33 Returns: 34 The file location returned as a string. 35 """ 36 try: 37 with importlib.resources.as_file( 38 importlib.resources.files('httplib2').joinpath('cacerts.txt') 39 ) as cacerts: 40 _, tmp_file = tempfile.mkstemp(suffix='cacerts.txt') 41 tmp_cacerts_path = pathlib.Path(tmp_file) 42 atexit.register(lambda: tmp_cacerts_path.unlink()) 43 shutil.copyfile(cacerts, tmp_cacerts_path) 44 return tmp_cacerts_path.as_posix() 45 except (ModuleNotFoundError, FileNotFoundError): 46 # Not running with embedded launcher 47 return certs.BUILTIN_CA_CERTS 48