Coverage for execution/lean_config_render.py: 100%

76 statements  

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

1"""Render a secret-bearing runtime Lean config from env vars (Phase V2-22 security). 

2 

3The tracked `lean.json` is the full stock Lean template with EVERY brokerage/ 

4API-secret field left empty (`ib-password`, `polygon-api-key`, … all `""`), so 

5it is safe to share - anyone who pulls the repo gets the usable config structure 

6but none of the keys. Lean itself does **not** expand environment variables 

7inside `lean.json` (verified against the Lean CLI's own 

8`components/config/lean_config_manager.py` - values are read literally), so 

9"put `${VAR}` in the field" does not work: the literal string would be sent to 

10the broker. Instead this module renders a gitignored `lean.live.json` that 

11overlays the real secret values (pulled from `.env.live` / `AETHER_*` env vars) 

12onto the empty template, and live/paper deployment points Lean at that rendered 

13file via `--lean-config`. Backtests are untouched - they use the plain, empty 

14`lean.json`. 

15 

16Pure/IO split, matching execution/live_credentials(_io).py: 

17- `render_lean_config()` / `parse_env_file()` are pure (no disk, no os.environ, 

18 never return secret VALUES - only the field NAMES that were filled). 

19- `load_env_file()` / `write_rendered_config()` are the thin IO wrappers. 

20""" 

21 

22from __future__ import annotations 

23 

24import json 

25import os 

26from collections.abc import Mapping 

27from pathlib import Path 

28 

29# lean.json field -> environment variable that supplies its value. 

30# Deliberately a small, explicit allow-list (IB live creds + the two data-feed 

31# keys this project actually uses) rather than "fill anything that looks like a 

32# secret" - rendering only touches fields we know how to source, and leaves the 

33# rest of the stock template untouched. Extend here (and in .env.live.example) 

34# when a new provider is adopted. 

35SECRET_ENV_MAP: dict[str, str] = { 

36 "ib-account": "AETHER_IB_ACCOUNT", 

37 "ib-user-name": "AETHER_IB_USER_NAME", 

38 "ib-password": "AETHER_IB_PASSWORD", 

39 "ib-trading-mode": "AETHER_IB_TRADING_MODE", 

40 "polygon-api-key": "AETHER_POLYGON_API_KEY", 

41 "iex-cloud-api-key": "AETHER_IEX_CLOUD_API_KEY", 

42 # V6.6.5 (#348): the crypto sleeve's venue (#192). Lean's Coinbase brokerage reads these two fields. 

43 "coinbase-api-key": "AETHER_COINBASE_API_KEY", 

44 "coinbase-api-secret": "AETHER_COINBASE_API_SECRET", 

45} 

46 

47 

48def account_env_name(env_name: str, account_id: str | None) -> str: 

49 """`AETHER_IB_PASSWORD` for the default account, `AETHER_<ACCOUNT>_IB_PASSWORD` for another (V6.6.5, #349).""" 

50 from execution.secrets import env_prefix 

51 

52 return env_prefix(account_id) + env_name[len("AETHER_"):] 

53 

54 

55def parse_env_file(text: str) -> dict[str, str]: 

56 """Minimal `.env` parser (no python-dotenv dependency, mirroring this 

57 codebase's deferred/optional-import style). Handles `KEY=VALUE`, blank 

58 lines, `#` comments, surrounding quotes, and a leading `export `. Later 

59 duplicate keys win. Never raises on a malformed line - it is skipped.""" 

60 result: dict[str, str] = {} 

61 for raw in text.splitlines(): 

62 line = raw.strip() 

63 if not line or line.startswith("#"): 

64 continue 

65 if line.startswith("export "): 

66 line = line[len("export "):].lstrip() 

67 if "=" not in line: 

68 continue 

69 key, value = line.split("=", 1) 

70 key = key.strip() 

71 if not key: 

72 continue 

73 value = value.strip() 

74 if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'": 

75 value = value[1:-1] 

76 result[key] = value 

77 return result 

78 

79 

80def render_lean_config( 

81 base_config: Mapping[str, object], env: Mapping[str, str], account_id: str | None = None 

82) -> tuple[dict, list[str]]: 

83 """Pure render. Returns `(rendered_config, filled_field_names)`. 

84 

85 Overlays onto a copy of `base_config` every `SECRET_ENV_MAP` field whose 

86 env var is present and non-empty (after strip). Fields whose env var is 

87 unset/blank are left exactly as they were in the template. The returned 

88 list contains only the lean.json FIELD names that were populated - never 

89 the secret values - so callers can safely log/report it. 

90 """ 

91 rendered = dict(base_config) 

92 filled: list[str] = [] 

93 for field, env_name in SECRET_ENV_MAP.items(): 

94 value = str(env.get(account_env_name(env_name, account_id), "")).strip() 

95 if value: 

96 rendered[field] = value 

97 filled.append(field) 

98 return rendered, filled 

99 

100 

101def load_env_file(path: str | Path) -> dict[str, str]: 

102 """Read a `.env`-style file into a dict. Missing file -> empty dict.""" 

103 p = Path(path) 

104 if not p.exists(): 

105 return {} 

106 return parse_env_file(p.read_text(encoding="utf-8")) 

107 

108 

109def build_render_environment( 

110 env_file: str | Path | None = None, 

111 os_environ: Mapping[str, str] | None = None, 

112 account_id: str | None = None, 

113 stored: Mapping[str, str] | None = None, 

114) -> dict[str, str]: 

115 """Merge a `.env.live` file (if given/exists) under the real process 

116 environment - process env wins, so an explicitly-exported `AETHER_*` 

117 overrides the file, matching docker-compose's own `.env` precedence. 

118 V6.6.5 (#348): a secret stored in a `*_FILE` file, a Docker secret or the keyring wins over both (`stored`, from 

119 `stored_secret_environment`); pass `stored={}` to skip that lookup.""" 

120 merged: dict[str, str] = {} 

121 if env_file is not None: 

122 merged.update(load_env_file(env_file)) 

123 merged.update(dict(os_environ if os_environ is not None else os.environ)) 

124 merged.update(dict(stored if stored is not None else stored_secret_environment(account_id))) 

125 return merged 

126 

127 

128def stored_secret_environment(account_id: str | None = None) -> dict[str, str]: 

129 """{env var: value} for each rendered secret found in a file, a Docker secret or the keyring (not plain env).""" 

130 from execution.secrets_io import load_secret 

131 

132 out: dict[str, str] = {} 

133 for env_name in SECRET_ENV_MAP.values(): 

134 resolved = load_secret(env_name[len("AETHER_"):], account_id) 

135 if resolved.value is not None and resolved.source and not resolved.source.startswith("env:"): 

136 out[account_env_name(env_name, account_id)] = resolved.value.reveal() 

137 return out 

138 

139 

140def write_rendered_config( 

141 base_path: str | Path, 

142 out_path: str | Path, 

143 env: Mapping[str, str], 

144 account_id: str | None = None, 

145) -> list[str]: 

146 """Read the empty template at `base_path`, render with `env`, write the 

147 secret-bearing result to `out_path` (pretty JSON). Returns the list of 

148 filled field names (never values). Raises FileNotFoundError if the template 

149 is missing - never silently writes an all-empty file that would look valid. 

150 """ 

151 base = Path(base_path) 

152 if not base.exists(): 

153 raise FileNotFoundError(f"Lean config template not found: {base}") 

154 base_config = json.loads(base.read_text(encoding="utf-8")) 

155 rendered, filled = render_lean_config(base_config, env, account_id) 

156 Path(out_path).write_text( 

157 json.dumps(rendered, indent=4) + "\n", encoding="utf-8" 

158 ) 

159 return filled 

160 

161 

162def validate_live_crypto_route(config: Mapping[str, object], filled_fields: list[str] | tuple[str, ...]) -> list[str]: 

163 """Advisory warnings about trading crypto through the configured live brokerage (V6.1.0, Problems.md #192). 

164 

165 The rendered live config fills Interactive Brokers credentials (`ib-*`). QuantConnect's Interactive Brokers 

166 brokerage does not support crypto (QuantConnect forum, "when will the interactivebrokersbrokeragemodel support 

167 crypto", staff answer "Interactive Brokers does not support crypto"; LEAN PR #8446 still open), while the book prices 

168 Coinbase fees (`CoinbaseFeeModel`, cash account) and the backtest fills on Lean's Coinbase market. So when crypto 

169 trading is enabled and the live credentials are IB's, a live or paper deploy would route crypto orders to a venue that 

170 cannot fill them. Pure and advisory: it never changes trading. Returns [] when there is nothing to flag.""" 

171 phase_v2 = dict(config.get("phase_v2", {}) or {}) 

172 assets = (config.get("phase1", {}) or {}).get("universe", {}).get("assets", []) or [] 

173 crypto_in_universe = any(str(a.get("asset_class") or a.get("security_type")) == "crypto" for a in assets) 

174 crypto_trades = crypto_in_universe and bool(phase_v2.get("crypto_risk", {}).get("enabled", True)) 

175 if not crypto_trades: 

176 return [] 

177 uses_ib = any(str(field).startswith("ib-") for field in filled_fields) 

178 if not uses_ib: 

179 return [] 

180 return [ 

181 "crypto is in the trading universe but the live credentials are Interactive Brokers': QuantConnect's IB brokerage " 

182 "does not support crypto, so crypto orders would not fill there. Trade crypto through a crypto brokerage " 

183 "(Coinbase, cash account, the venue the fee model prices) or switch the crypto classes off before a live deploy." 

184 ]