Coverage for src/governed_harness/forges/transport.py: 59%

75 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-12 16:06 +0000

1"""How a forge provider reaches its REST API (#56). 

2 

3* ``HttpTransport``: HTTPS with the forge's authentication header; the token is read from an 

4 environment variable when the transport is built and is never logged, stored or put in an 

5 error message. 

6* ``CliTransport``: the forge's own CLI (``gh api`` for GitHub, ``glab api`` for GitLab), with 

7 the authentication the CLI already has. 

8 

9Tests inject a fake transport; nothing in the harness's test suite reaches the network.""" 

10 

11from __future__ import annotations 

12 

13import base64 

14import json 

15import os 

16import shutil 

17import subprocess # nosec B404 - gh or glab api with a fixed argv, no shell 

18import urllib.error 

19import urllib.request 

20from dataclasses import dataclass, field 

21from typing import Any, Protocol 

22 

23from governed_harness.delivery.publisher import PublishError 

24from governed_harness.domain.errors import ConfigurationError 

25 

26_TIMEOUT_SECONDS = 30 

27_JSON = "application/json" 

28 

29DEFAULT_TOKEN_ENV: dict[str, str] = { 

30 "github": "GITHUB_TOKEN", 

31 "gitlab": "GITLAB_TOKEN", 

32 "bitbucket": "BITBUCKET_TOKEN", 

33 "azure-devops": "AZURE_DEVOPS_TOKEN", 

34 "gitea": "GITEA_TOKEN", 

35} 

36"""The environment variable each forge reads its token from unless ``tokenEnv`` names another.""" 

37 

38CLI_EXECUTABLES: dict[str, str] = {"github": "gh", "gitlab": "glab"} 

39"""Forges with a CLI that can call the REST API with its own authentication.""" 

40 

41 

42class Transport(Protocol): 

43 def request(self, method: str, path: str, body: Any = None) -> Any: 

44 """Send a REST request to ``path`` and return the decoded response.""" 

45 

46 

47@dataclass 

48class HttpTransport: 

49 """HTTPS with headers built once; the token only lives in the headers.""" 

50 

51 api_url: str 

52 headers: dict[str, str] = field(repr=False) 

53 

54 def request(self, method: str, path: str, body: Any = None) -> Any: 

55 url = f"{self.api_url}/{path.lstrip('/')}" 

56 data = json.dumps(body).encode("utf-8") if body is not None else None 

57 request = urllib.request.Request( # noqa: S310 - the URL is https (validated in config) 

58 url, 

59 data=data, 

60 method=method, 

61 headers={ 

62 "Content-Type": _JSON, 

63 "User-Agent": "governed-harness", 

64 **self.headers, 

65 }, 

66 ) 

67 try: 

68 with urllib.request.urlopen(request, timeout=_TIMEOUT_SECONDS) as response: # noqa: S310 # nosec B310 

69 text = response.read().decode("utf-8", "replace") 

70 except urllib.error.HTTPError as error: 

71 raise PublishError( 

72 f"{method} {path.split('?')[0]} returned HTTP {error.code}" 

73 ) from error 

74 except OSError as error: # URLError is an OSError 

75 raise PublishError(f"{method} {path.split('?')[0]} failed: {error}") from error 

76 return json.loads(text) if text.strip() else None 

77 

78 

79@dataclass 

80class CliTransport: 

81 """``<cli> api --method M PATH --input -``: the CLI's own authentication.""" 

82 

83 executable: str 

84 

85 def request(self, method: str, path: str, body: Any = None) -> Any: 

86 if shutil.which(self.executable) is None: 

87 raise PublishError(f"{self.executable} is not on PATH; use the api transport") 

88 args = [self.executable, "api", "--method", method, path] 

89 if body is not None: 

90 args += ["--input", "-"] 

91 try: 

92 result = subprocess.run( # nosec B603 - fixed argv, no shell 

93 args, 

94 input=json.dumps(body).encode("utf-8") if body is not None else None, 

95 capture_output=True, 

96 check=False, 

97 timeout=_TIMEOUT_SECONDS, 

98 ) 

99 except (OSError, subprocess.SubprocessError) as error: 

100 raise PublishError(f"{self.executable} api could not run: {error}") from error 

101 if result.returncode != 0: 

102 message = result.stderr.decode("utf-8", "replace").strip()[:300] 

103 raise PublishError(f"{self.executable} api {method} {path} failed: {message}") 

104 text = result.stdout.decode("utf-8", "replace").strip() 

105 return json.loads(text) if text else None 

106 

107 

108def auth_headers(kind: str, token: str) -> dict[str, str]: 

109 """The authentication header of each forge's REST API.""" 

110 if kind == "github": 110 ↛ 111line 110 didn't jump to line 111 because the condition on line 110 was never true

111 return { 

112 "Accept": "application/vnd.github+json", 

113 "Authorization": f"Bearer {token}", 

114 "X-GitHub-Api-Version": "2022-11-28", 

115 } 

116 if kind == "gitlab": 

117 return {"PRIVATE-TOKEN": token} 

118 if kind == "bitbucket": 118 ↛ 119line 118 didn't jump to line 119 because the condition on line 118 was never true

119 return {"Authorization": f"Bearer {token}", "Accept": _JSON} 

120 if kind == "azure-devops": 120 ↛ 123line 120 didn't jump to line 123 because the condition on line 120 was always true

121 basic = base64.b64encode(f":{token}".encode()).decode("ascii") 

122 return {"Authorization": f"Basic {basic}", "Accept": _JSON} 

123 return {"Authorization": f"token {token}", "Accept": _JSON} 

124 

125 

126def build_transport( 

127 kind: str, transport: str, api_url: str, token_env: str | None = None 

128) -> Transport: 

129 """The transport of a forge: its CLI, or HTTPS with the token from the environment.""" 

130 if transport == "cli": 

131 executable = CLI_EXECUTABLES.get(kind) 

132 if executable is None: 132 ↛ 134line 132 didn't jump to line 134 because the condition on line 132 was always true

133 raise ConfigurationError(f"the {kind} forge has no CLI transport; use transport: api") 

134 return CliTransport(executable) 

135 name = token_env or DEFAULT_TOKEN_ENV[kind] 

136 token = os.environ.get(name) 

137 if not token: 

138 raise ConfigurationError( 

139 f"the api transport reads the {kind} token from {name}, which is not set" 

140 ) 

141 return HttpTransport(api_url, auth_headers(kind, token)) 

142 

143 

144__all__ = [ 

145 "CLI_EXECUTABLES", 

146 "DEFAULT_TOKEN_ENV", 

147 "CliTransport", 

148 "HttpTransport", 

149 "Transport", 

150 "auth_headers", 

151 "build_transport", 

152]