Coverage for src/courtpy/core/secrets.py: 86%

150 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-22 15:51 +0000

1"""Keeps the CourtListener API key secret, outside of projects and packages. 

2 

3The key is never written in a project's settings or in courtpy itself, so it 

4cannot be shared or committed by accident. Store it once, and courtpy finds it 

5whenever it is needed: 

6 

7```python 

8import courtpy 

9 

10courtpy.secrets.set_api_key("your-key") 

11``` 

12 

13or, from a terminal (which asks for the key without showing it): 

14 

15```sh 

16courtpy key set 

17``` 

18 

19`get_api_key` looks for the key in these places, in order, and uses the first 

20one it finds: 

21 

221. The `COURTLISTENER_API_KEY` environment variable. 

232. The system keyring: Windows Credential Manager, the macOS Keychain, or the 

24 Secret Service on Linux (if one is running). 

253. The secrets file in courtpy's configuration folder (see `secrets_path`), 

26 which is in the user's home folder, not in any project. 

274. A `.env` file in the current folder with a line such as 

28 `COURTLISTENER_API_KEY=your-key`. Keep such a file out of version control 

29 (courtpy's own `.gitignore` excludes it). 

30 

31Contents: 

32 MissingAPIKeyError: raised when no API key can be found. 

33 delete_api_key: removes the stored API key. 

34 find_api_key: returns the API key and where it was found. 

35 get_api_key: returns the API key. 

36 mask: hides most of a key so that it can be shown. 

37 secrets_path: returns the path of the secrets file. 

38 set_api_key: stores the API key. 

39 logger: the module's logger, which reports problems with the keyring and 

40 the secrets file. 

41 _FILE_SECTION: the section of the secrets file that holds the key. 

42 _FILE_SETTING: the setting, in `_FILE_SECTION`, that holds the key. 

43 _STORES: the places that `set_api_key` can store the key ("auto", 

44 "keyring", or "file"). 

45 

46""" 

47 

48from __future__ import annotations 

49 

50import contextlib 

51import json 

52import logging 

53import os 

54import pathlib 

55import sys 

56import tomllib 

57from typing import Any 

58 

59from . import options, utilities 

60 

61logger = logging.getLogger(__name__) 

62_STORES: tuple[str, ...] = ('auto', 'keyring', 'file') 

63_FILE_SECTION: str = 'court_listener' 

64_FILE_SETTING: str = 'api_key' 

65 

66 

67class MissingAPIKeyError(LookupError): 

68 """Raised when no CourtListener API key can be found. 

69 

70 Its message explains how to get and store a key. 

71 

72 """ 

73 

74 def __init__(self) -> None: # noqa: D107 

75 message = ( 

76 'no CourtListener API key was found. Get one by signing in to ' 

77 'https://www.courtlistener.com and opening your profile\'s "API" ' 

78 'page. Then store it with "courtpy key set" (in a terminal) or ' 

79 '"courtpy.secrets.set_api_key(...)" (in Python), or set the ' 

80 f'{options._ENV_API_KEY} environment variable. Bulk data does ' 

81 'not need a key.' 

82 ) 

83 super().__init__(message) 

84 

85 

86def delete_api_key() -> list[str]: 

87 """Removes the API key from the keyring and the secrets file. 

88 

89 A key in an environment variable or a `.env` file is not changed. 

90 

91 Returns: 

92 Descriptions of the places the key was removed from. 

93 

94 """ 

95 removed = [] 

96 backend = _keyring() 

97 if backend is not None: 

98 try: 

99 if backend.get_password(*_keyring_names()) is not None: 99 ↛ 104line 99 didn't jump to line 104 because the condition on line 99 was always true

100 backend.delete_password(*_keyring_names()) 

101 removed.append('the system keyring') 

102 except Exception as error: # noqa: BLE001 

103 logger.debug('the keyring could not be changed: %s', error) 

104 path = secrets_path() 

105 contents = _read_file(path) 

106 if contents.get(_FILE_SECTION, {}).get(_FILE_SETTING): 

107 del contents[_FILE_SECTION][_FILE_SETTING] 

108 _write_file(path, contents) 

109 removed.append(str(path)) 

110 return removed 

111 

112 

113def find_api_key() -> tuple[str, str] | None: 

114 """Returns the API key and a description of where it was found. 

115 

116 Returns: 

117 The key and where it was found, or `None` if there is no key in any of 

118 the places that `get_api_key` looks. 

119 

120 """ 

121 value = os.environ.get(options._ENV_API_KEY, '').strip() 

122 if value: 

123 return value, f'the {options._ENV_API_KEY} environment variable' 

124 backend = _keyring() 

125 if backend is not None: 

126 try: 

127 value = (backend.get_password(*_keyring_names()) or '').strip() 

128 except Exception as error: # noqa: BLE001 

129 logger.debug('the keyring could not be read: %s', error) 

130 value = '' 

131 if value: 

132 return value, 'the system keyring' 

133 path = secrets_path() 

134 value = str( 

135 _read_file(path).get(_FILE_SECTION, {}).get(_FILE_SETTING, '')).strip() 

136 if value: 

137 return value, str(path) 

138 dotenv = pathlib.Path.cwd() / '.env' 

139 value = _read_dotenv(dotenv).get(options._ENV_API_KEY, '').strip() 

140 if value: 

141 return value, str(dotenv) 

142 return None 

143 

144 

145def get_api_key(required: bool = True) -> str | None: 

146 """Returns the CourtListener API key. 

147 

148 Args: 

149 required: whether to raise an error if there is no key. Defaults to 

150 `True`. 

151 

152 Raises: 

153 MissingAPIKeyError: if there is no key and `required` is `True`. 

154 

155 Returns: 

156 The key, or `None` if there is no key and `required` is `False`. 

157 

158 """ 

159 found = find_api_key() 

160 if found is None: 

161 if required: 

162 raise MissingAPIKeyError 

163 return None 

164 return found[0] 

165 

166 

167def mask(key: str) -> str: 

168 """Hides most of `key` so that it can be shown. 

169 

170 Args: 

171 key: a secret. 

172 

173 Returns: 

174 The first and last four characters of `key`, with dots between them, 

175 or only dots if `key` is short. 

176 

177 """ 

178 dot = chr(0x2022) 

179 if len(key) <= 12: 

180 return dot * len(key) 

181 return key[:4] + dot * 8 + key[-4:] 

182 

183 

184def secrets_path() -> pathlib.Path: 

185 """Returns the path of the secrets file. 

186 

187 Returns: 

188 "secrets.toml" in the folder from `utilities.config_folder`. 

189 

190 """ 

191 return utilities.config_folder() / 'secrets.toml' 

192 

193 

194def set_api_key(key: str, *, store: str = 'auto') -> str: 

195 """Stores the CourtListener API key outside of any project. 

196 

197 Args: 

198 key: the API key, from the "API" page of a CourtListener profile. 

199 store: "keyring" for the system keyring, "file" for the secrets file 

200 (see `secrets_path`), or "auto" (the default) for the keyring if 

201 one is available and the file otherwise. 

202 

203 Raises: 

204 RuntimeError: if `store` is "keyring" and the keyring cannot be used. 

205 ValueError: if `key` is blank or `store` is not one of those. 

206 

207 Returns: 

208 A description of where the key was stored. 

209 

210 """ 

211 key = key.strip() 

212 if not key: 

213 message = 'the API key is blank' 

214 raise ValueError(message) 

215 if key.lower().startswith('token '): 

216 # People often copy the whole header value. 

217 key = key[6:].strip() 

218 if store not in _STORES: 

219 message = f'store must be one of {list(_STORES)}, not {store!r}' 

220 raise ValueError(message) 

221 if store in ('auto', 'keyring'): 

222 backend = _keyring() 

223 try: 

224 if backend is None: 

225 message = 'no system keyring is available' 

226 raise RuntimeError(message) # noqa: TRY301 

227 backend.set_password(*_keyring_names(), key) 

228 except Exception as error: 

229 if store == 'keyring': 

230 message = f'the key could not be stored in the keyring: {error}' 

231 raise RuntimeError(message) from error 

232 logger.info( 

233 'the keyring is not available (%s), so a file is used', error) 

234 else: 

235 return 'the system keyring' 

236 path = secrets_path() 

237 contents = _read_file(path) 

238 contents.setdefault(_FILE_SECTION, {})[_FILE_SETTING] = key 

239 _write_file(path, contents) 

240 return str(path) 

241 

242 

243""" Private Functions """ 

244 

245 

246def _keyring() -> Any: 

247 """Returns the `keyring` module, if it has a usable backend. 

248 

249 The module is imported here, rather than at the top of the module, so 

250 that a problem with the keyring (which some systems lack) only matters 

251 when the keyring is used. Any error while importing it or finding its 

252 backend means that there is no usable keyring. 

253 

254 Returns: 

255 The module, or `None` if it is not installed or has no backend that 

256 stores secrets (as on a Linux server without a Secret Service). 

257 

258 """ 

259 try: 

260 import keyring # noqa: PLC0415 

261 import keyring.backends.fail # noqa: PLC0415 

262 except Exception: # noqa: BLE001 

263 return None 

264 try: 

265 backend = keyring.get_keyring() 

266 except Exception: # noqa: BLE001 

267 return None 

268 if isinstance(backend, keyring.backends.fail.Keyring): 

269 return None 

270 if getattr(backend, 'priority', 1) <= 0: 

271 return None 

272 return keyring 

273 

274 

275def _keyring_names() -> tuple[str, str]: 

276 """Returns the service and user name of the key in the keyring. 

277 

278 A keyring stores each password under a service and a user name. They are 

279 read from `options` each time, so that a project can change them. 

280 

281 Returns: 

282 `options._KEYRING_SERVICE` and `options._KEYRING_USERNAME`, in the 

283 order the keyring's functions take them. 

284 

285 """ 

286 return options._KEYRING_SERVICE, options._KEYRING_USERNAME 

287 

288 

289def _read_dotenv(path: pathlib.Path) -> dict[str, str]: 

290 """Returns the settings in a `.env` file. 

291 

292 Args: 

293 path: path to the file. 

294 

295 Returns: 

296 The settings, by name. Lines such as `NAME=value` and 

297 `export NAME="value"` are read, and comments are ignored. An empty 

298 `dict` is returned if there is no file. 

299 

300 """ 

301 if not path.is_file(): 

302 return {} 

303 found = {} 

304 for line in path.read_text(encoding = 'utf-8-sig').splitlines(): 

305 line = line.strip() # noqa: PLW2901 

306 if not line or line.startswith('#') or '=' not in line: 

307 continue 

308 name, value = line.removeprefix('export ').split('=', 1) 

309 found[name.strip()] = value.strip().strip('"').strip("'") 

310 return found 

311 

312 

313def _read_file(path: pathlib.Path) -> dict[str, Any]: 

314 """Returns the contents of the secrets file. 

315 

316 Args: 

317 path: path to the file. 

318 

319 Returns: 

320 The contents, or an empty `dict` if there is no file or it cannot be 

321 read. 

322 

323 """ 

324 if not path.is_file(): 

325 return {} 

326 try: 

327 with path.open('rb') as file: 

328 return tomllib.load(file) 

329 except (OSError, tomllib.TOMLDecodeError) as error: 

330 logger.warning('the secrets file %s could not be read: %s', path, error) 

331 return {} 

332 

333 

334def _write_file(path: pathlib.Path, contents: dict[str, Any]) -> None: 

335 """Writes the secrets file, readable only by its owner. 

336 

337 Args: 

338 path: path to the file. 

339 contents: sections of settings to write. Values are written as 

340 strings. 

341 

342 """ 

343 path.parent.mkdir(parents = True, exist_ok = True) 

344 lines = [ 

345 '# Secrets for courtpy. Keep this file private: do not share it or', 

346 '# copy it into a project.'] 

347 for section, settings in contents.items(): 

348 if not isinstance(settings, dict) or not settings: 

349 continue 

350 lines.extend(['', f'[{section}]']) 

351 for name, value in settings.items(): 

352 # A JSON string is also a valid TOML string. 

353 lines.append(f'{name} = {json.dumps(str(value))}') 

354 path.write_text('\n'.join(lines) + '\n', encoding = 'utf-8') 

355 if sys.platform != 'win32': 355 ↛ exitline 355 didn't return from function '_write_file' because the condition on line 355 was always true

356 # Windows keeps each user's application data private already. 

357 with contextlib.suppress(OSError): 

358 path.chmod(0o600)