Coverage for /usr/local/lib/python3.10/site-packages/opal_common-0.0.0-py3.10.egg/opal_common/git_utils/env.py: 22%

28 statements  

« prev     ^ index     » next       coverage.py v7.15.2, created at 2026-10-10 11:54 +0000

1import os 

2from pathlib import Path 

3 

4from opal_common.config import opal_common_config 

5 

6SSH_PREFIX = "ssh://" 

7GIT_SSH_USER_PREFIX = "git@" 

8 

9 

10def save_ssh_key_to_pem_file(key: str) -> Path: 

11 key = key.replace("_", "\n") 

12 if not key.endswith("\n"): 

13 key = key + "\n" # pem file must end with newline 

14 key_path = os.path.expanduser(opal_common_config.GIT_SSH_KEY_FILE) 

15 parent_directory = os.path.dirname(key_path) 

16 if not os.path.exists(parent_directory): 

17 os.makedirs(parent_directory, exist_ok=True) 

18 with open(key_path, "w") as f: 

19 f.write(key) 

20 os.chmod(key_path, 0o600) 

21 return Path(key_path) 

22 

23 

24def is_ssh_repo_url(repo_url: str): 

25 """Return True if the repo url uses SSH authentication. 

26 

27 (see: 

28 https://docs.github.com/en/github/authenticating-to-github/connecting-to-github-with-ssh) 

29 """ 

30 return repo_url.startswith(SSH_PREFIX) or repo_url.startswith(GIT_SSH_USER_PREFIX) 

31 

32 

33def provide_git_ssh_environment(url: str, ssh_key: str): 

34 """Provides git SSH configuration via GIT_SSH_COMMAND. 

35 

36 the git ssh config will be provided only if the following conditions are met: 

37 - the repo url is a git ssh url 

38 - an ssh private key is provided in Repo Cloner __init__ 

39 """ 

40 if not is_ssh_repo_url(url) or ssh_key is None: 

41 return {} # no ssh config 

42 git_ssh_identity_file = save_ssh_key_to_pem_file(ssh_key) 

43 env = { 

44 "GIT_SSH_COMMAND": f"ssh -o StrictHostKeyChecking=no -o IdentitiesOnly=yes -i {git_ssh_identity_file}", 

45 } 

46 # This function only runs for SSH clones (non-SSH urls early-return above), 

47 # so the value of gating GIT_TRACE / GIT_CURL_VERBOSE here is reducing the 

48 # verbose SSH protocol noise / host disclosure git dumps to stderr (which 

49 # OPAL captures into its logs) - not closing an HTTP Authorization-header 

50 # leak, since SSH uses key auth, not HTTP headers. (HTTPS clones, where 

51 # GIT_CURL_VERBOSE would dump Authorization headers, never enter this path; 

52 # that would have to be handled where the HTTPS clone env is built.) 

53 # Only enable verbose tracing when diagnosis logging is explicitly turned on. 

54 if opal_common_config.LOG_DIAGNOSE: 

55 env["GIT_TRACE"] = "1" 

56 env["GIT_CURL_VERBOSE"] = "1" 

57 return env