Coverage for execution/secrets.py: 100%

107 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""Secret resolution (V6.6.5, #348): where a credential comes from, without ever printing it. 

2 

3A secret has a NAME (`IB_PASSWORD`, `COINBASE_API_SECRET`, `POSTGRES_DSN`, ...) and is looked up, first match wins, in: 

4 

51. a file named by `AETHER_<NAME>_FILE` (the Docker and Kubernetes convention), 

62. the Docker secret `/run/secrets/aether_<name>`, 

73. the environment variable `AETHER_<NAME>` (what every service read before; with only that set, nothing changes), 

84. the OS keyring, service `aether-quant`, user `<NAME>` (`aq secrets set NAME`; only when the `keyring` package is installed). 

9 

10An account other than `default` reads `AETHER_<ACCOUNT>_<NAME>` (and the matching file, Docker secret and keyring entry), so 

11two accounts never share a credential by accident. Values travel as `SecretValue`, whose repr and str are `***`; only 

12`reveal()` returns the text. This module is pure: the environment, the file reader and the keyring come in as arguments 

13(`execution/secrets_io.py` passes the real ones). 

14""" 

15 

16from __future__ import annotations 

17 

18import hmac 

19import re 

20from collections.abc import Callable, Iterable, Mapping 

21from dataclasses import dataclass 

22from typing import Literal 

23 

24__all__ = [ 

25 "SECRET_NAMES", "KEYRING_SERVICE", "SecretValue", "SecretRef", "ResolvedSecret", "parse_ref", "env_prefix", "default_refs", "resolve_secret", "redact", "redact_url", 

26 "secret_status", 

27] 

28 

29SECRET_NAMES: tuple[str, ...] = ( 

30 "IB_ACCOUNT", "IB_USER_NAME", "IB_PASSWORD", "IB_TRADING_MODE", "COINBASE_API_KEY", "COINBASE_API_SECRET", "POSTGRES_DSN", "REDIS_URL", 

31 "TELEGRAM_BOT_TOKEN", "TELEGRAM_CHAT_ID", "POLYGON_API_KEY", "IEX_CLOUD_API_KEY", 

32) 

33KEYRING_SERVICE = "aether-quant" 

34DOCKER_SECRETS_DIR = "/run/secrets" 

35_ACCOUNT_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,31}$") 

36 

37 

38class SecretValue: 

39 """A credential that never shows itself: `repr`, `str` and f-strings give `***`. `reveal()` returns the text.""" 

40 

41 __slots__ = ("_value",) 

42 

43 def __init__(self, value: str) -> None: 

44 self._value = str(value) 

45 

46 def reveal(self) -> str: 

47 return self._value 

48 

49 def __repr__(self) -> str: 

50 return "SecretValue('***')" 

51 

52 def __str__(self) -> str: 

53 return "***" 

54 

55 def __format__(self, spec: str) -> str: 

56 return "***" 

57 

58 def __bool__(self) -> bool: 

59 return bool(self._value) 

60 

61 def __eq__(self, other: object) -> bool: 

62 if not isinstance(other, SecretValue): 

63 return NotImplemented 

64 return hmac.compare_digest(self._value.encode("utf-8"), other._value.encode("utf-8")) 

65 

66 def __hash__(self) -> int: 

67 return hash(("SecretValue", len(self._value))) 

68 

69 def __reduce__(self): 

70 raise TypeError("a SecretValue is not pickled or copied out of the process") 

71 

72 

73@dataclass(frozen=True) 

74class SecretRef: 

75 """Where to look: `env:AETHER_IB_PASSWORD`, `file:/run/secrets/aether_ib_password` or `keyring:aether-quant/IB_PASSWORD`.""" 

76 

77 scheme: Literal["env", "file", "keyring"] 

78 target: str 

79 

80 def __str__(self) -> str: 

81 return f"{self.scheme}:{self.target}" 

82 

83 

84@dataclass(frozen=True) 

85class ResolvedSecret: 

86 """The outcome of one lookup. `value` is None when nothing matched; `source` names the ref that did.""" 

87 

88 name: str 

89 value: SecretValue | None 

90 source: str | None 

91 

92 

93def parse_ref(text: str) -> SecretRef: 

94 """`scheme:target` to a `SecretRef`. A literal value is refused: secrets are never written into config.""" 

95 scheme, sep, target = str(text).partition(":") 

96 if not sep or not target or scheme not in ("env", "file", "keyring"): 

97 raise ValueError(f"not a secret reference (env:, file: or keyring:): {text!r}") 

98 return SecretRef(scheme, target) # type: ignore[arg-type] 

99 

100 

101def env_prefix(account_id: str | None) -> str: 

102 """`AETHER_` for the default account, `AETHER_<ACCOUNT>_` for any other (dashes become underscores).""" 

103 if not account_id or account_id == "default": 

104 return "AETHER_" 

105 if not _ACCOUNT_RE.match(account_id): 

106 raise ValueError(f"bad account id {account_id!r}") 

107 return f"AETHER_{account_id.upper().replace('-', '_')}_" 

108 

109 

110def default_refs(name: str, account_id: str | None = None, env: Mapping[str, str] | None = None) -> tuple[SecretRef, ...]: 

111 """The lookup order for one secret (see the module docstring).""" 

112 if not re.match(r"^[A-Z][A-Z0-9_]*$", str(name)): 

113 raise ValueError(f"bad secret name {name!r}") 

114 variable = f"{env_prefix(account_id)}{name}" 

115 refs: list[SecretRef] = [] 

116 file_variable = f"{variable}_FILE" 

117 if env is not None and env.get(file_variable): 

118 refs.append(SecretRef("file", env[file_variable])) 

119 refs.append(SecretRef("file", f"{DOCKER_SECRETS_DIR}/{variable.lower()}")) 

120 refs.append(SecretRef("env", variable)) 

121 keyring_user = name if not account_id or account_id == "default" else f"{account_id}/{name}" 

122 refs.append(SecretRef("keyring", f"{KEYRING_SERVICE}/{keyring_user}")) 

123 return tuple(refs) 

124 

125 

126def resolve_secret( 

127 name: str, 

128 *, 

129 account_id: str | None = None, 

130 env: Mapping[str, str], 

131 read_file: Callable[[str], str | None], 

132 keyring_get: Callable[[str, str], str | None] | None = None, 

133) -> ResolvedSecret: 

134 """The first non-empty value along `default_refs`. A file's trailing newline is dropped; a reader that raises counts as 

135 "not there", never as a crash.""" 

136 for ref in default_refs(name, account_id, env): 

137 value: str | None = None 

138 try: 

139 if ref.scheme == "env": 

140 value = env.get(ref.target) 

141 elif ref.scheme == "file": 

142 value = read_file(ref.target) 

143 value = value.rstrip("\r\n") if value is not None else None 

144 elif keyring_get is not None: 

145 service, _, user = ref.target.partition("/") 

146 value = keyring_get(service, user) 

147 except Exception: 

148 value = None 

149 if value: 

150 return ResolvedSecret(name, SecretValue(value), str(ref)) 

151 return ResolvedSecret(name, None, None) 

152 

153 

154def redact_url(url: object) -> str: 

155 """`url` with the password of its user info masked (`redis://:***@host:6379/0`), for logs. A URL without one, or text 

156 that is not a URL, comes back as it was.""" 

157 text = str(url) 

158 scheme, sep, rest = text.partition("://") 

159 authority, slash, path = rest.partition("/") 

160 if not sep or "@" not in authority: 

161 return text 

162 # the host follows the LAST @ of the authority: a password may contain @ (V6.6.7, #363: the first @ leaked its tail) 

163 userinfo, _, host = authority.rpartition("@") 

164 user, colon, _password = userinfo.partition(":") 

165 return f"{scheme}://{user}{':***' if colon else ''}@{host}{slash}{path}" 

166 

167 

168def redact(text: str, values: Iterable[SecretValue | str | None]) -> str: 

169 """`text` with every occurrence of every secret value replaced by `***`, longest first (so a value that contains another 

170 is hidden whole). Values shorter than 4 characters are left alone: masking `1` would mangle every number.""" 

171 secrets = sorted({(value.reveal() if isinstance(value, SecretValue) else str(value)) for value in values if value}, key=len, reverse=True) 

172 out = str(text) 

173 for secret in secrets: 

174 if len(secret) >= 4: 

175 out = out.replace(secret, "***") 

176 return out 

177 

178 

179def secret_status(resolved: Iterable[ResolvedSecret]) -> list[dict[str, str | bool]]: 

180 """Names and sources only, never values: what `aq secrets status` prints and the readiness scorecard reads. A secret 

181 from a file or the keyring counts as `stored_safely`; one from a plain environment variable does not.""" 

182 rows: list[dict[str, str | bool]] = [] 

183 for item in resolved: 

184 source = item.source or "" 

185 rows.append({ 

186 "name": item.name, "resolved": item.value is not None, "source": source.split(":", 1)[0] if source else "", 

187 "where": source, "stored_safely": source.startswith(("file:", "keyring:")), 

188 }) 

189 return rows