-
Notifications
You must be signed in to change notification settings - Fork 159
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
allow trusting certificate from custom certificate authorities
- Loading branch information
Showing
3 changed files
with
56 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
import base64 | ||
import os | ||
|
||
import certifi | ||
|
||
CUSTOM_CERTIFICATE_PATH = "/tmp/custom_ca.pem" | ||
|
||
|
||
def append_custom_certificate(custom_ca: str) -> None: | ||
with open(certifi.where(), "ab") as outfile: | ||
outfile.write(base64.b64decode(custom_ca)) | ||
|
||
os.environ["WEBSOCKET_CLIENT_CA_BUNDLE"] = certifi.where() | ||
|
||
|
||
def create_temporary_certificate(custom_ca: str) -> None: | ||
with open(certifi.where(), "rb") as base_cert: | ||
base_cert_content = base_cert.read() | ||
|
||
with open(CUSTOM_CERTIFICATE_PATH, "wb") as outfile: | ||
outfile.write(base_cert_content) | ||
outfile.write(base64.b64decode(custom_ca)) | ||
|
||
os.environ["REQUESTS_CA_BUNDLE"] = CUSTOM_CERTIFICATE_PATH | ||
os.environ["WEBSOCKET_CLIENT_CA_BUNDLE"] = CUSTOM_CERTIFICATE_PATH | ||
certifi.where = lambda: CUSTOM_CERTIFICATE_PATH | ||
|
||
|
||
def add_custom_certificate(custom_ca: str) -> bool: | ||
if not custom_ca: | ||
return False | ||
|
||
# NOTE: Sometimes (Openshift) the certifi.where() is not writable, so we need to | ||
# use a temporary file in case of PermissionError. | ||
try: | ||
append_custom_certificate(custom_ca) | ||
except PermissionError: | ||
create_temporary_certificate(custom_ca) | ||
|
||
return True |