Coverage for custom_components/remote_logger/config_flow.py: 98%

183 statements  

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

1"""Config flow for the remote_logger integration.""" 

2 

3from __future__ import annotations 

4 

5import logging 

6import re 

7from typing import Any 

8 

9from homeassistant.config_entries import ConfigEntry, ConfigFlow, ConfigFlowResult, OptionsFlow 

10from homeassistant.const import CONF_HEADERS, CONF_HOST, CONF_PATH, CONF_PORT, CONF_PROTOCOL, CONF_TOKEN 

11from homeassistant.core import HomeAssistant, callback 

12from homeassistant.data_entry_flow import section 

13from homeassistant.helpers import selector 

14from homeassistant.helpers.aiohttp_client import async_get_clientsession 

15 

16from .compat import vol 

17from .const import ( 

18 BACKEND_OTEL, 

19 BACKEND_SYSLOG, 

20 CONF_BACKEND, 

21 CONF_CUSTOM_EVENTS, 

22 CONF_ENCODING, 

23 CONF_EVENT_BASED_LOGGING, 

24 CONF_LOG_HA_CORE_ACTIVITY, 

25 CONF_LOG_HA_CORE_CHANGES, 

26 CONF_LOG_HA_EVENT_BODY, 

27 CONF_LOG_HA_FULL_STATE_CHANGES, 

28 CONF_LOG_HA_LIFECYCLE, 

29 CONF_LOG_HA_STATE_CHANGES, 

30 CONF_LOG_LEVEL, 

31 CONF_RESOURCE_ATTRIBUTES, 

32 CONF_SUPPRESS_SYSTEM_LOG_EVENT_NAME, 

33 CONF_USE_TLS, 

34 DEFAULT_LOG_LEVEL, 

35 DOMAIN, 

36) 

37from .otel.const import ( 

38 CONF_TOKEN_TYPE, 

39 OTEL_DATA_SCHEMA, 

40 OTLP_LOGS_PATH, 

41 REAUTH_OTEL_DATA_SCHEMA, 

42 TOKEN_TYPE_BEARER, 

43 VALIDATION_MESSAGE, 

44) 

45from .otel.exporter import build_auth_header, parse_headers, parse_resource_attributes 

46from .otel.exporter import validate as otel_validate 

47from .syslog.const import SYSLOG_DATA_SCHEMA 

48from .syslog.exporter import validate as syslog_validate 

49 

50_LOGGER = logging.getLogger(__name__) 

51 

52 

53def _to_list(value: Any) -> list[str]: 

54 """Coerce a stored string (comma/newline-separated) or list to a list of strings.""" 

55 if isinstance(value, list): 

56 return value 

57 if not value: 

58 return [] 

59 return [v.strip() for v in re.split(r"[\n,]+", str(value)) if v.strip()] 

60 

61 

62COMMON_DATA_SCHEMA = vol.Schema({ 

63 vol.Optional(CONF_EVENT_BASED_LOGGING, default=False): selector.BooleanSelector(), 

64 vol.Optional(CONF_LOG_LEVEL, default=DEFAULT_LOG_LEVEL): selector.SelectSelector( 

65 selector.SelectSelectorConfig( 

66 options=["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"], 

67 mode=selector.SelectSelectorMode.DROPDOWN, 

68 ), 

69 ), 

70 vol.Required("ha_standard_events"): section( 

71 vol.Schema({ 

72 vol.Optional(CONF_LOG_HA_LIFECYCLE, default=False): selector.BooleanSelector(), 

73 vol.Optional(CONF_LOG_HA_CORE_CHANGES, default=False): selector.BooleanSelector(), 

74 vol.Optional(CONF_LOG_HA_CORE_ACTIVITY, default=False): selector.BooleanSelector(), 

75 vol.Optional(CONF_LOG_HA_STATE_CHANGES, default=False): selector.BooleanSelector(), 

76 vol.Optional(CONF_LOG_HA_FULL_STATE_CHANGES, default=False): selector.BooleanSelector(), 

77 }), 

78 {"collapsed": False}, 

79 ), 

80 vol.Optional(CONF_LOG_HA_EVENT_BODY, default=True): selector.BooleanSelector(), 

81 vol.Optional(CONF_SUPPRESS_SYSTEM_LOG_EVENT_NAME, default=True): selector.BooleanSelector(), 

82 vol.Optional(CONF_CUSTOM_EVENTS, default=[]): selector.TextSelector(selector.TextSelectorConfig(multiple=True)), 

83}) 

84 

85 

86def _build_endpoint_url(host: str, port: int, use_tls: bool, path: str = OTLP_LOGS_PATH) -> str: 

87 """Build the full OTLP endpoint URL.""" 

88 scheme = "https" if use_tls else "http" 

89 return f"{scheme}://{host}:{port}{path}" 

90 

91 

92# Connection settings live in entry.data, set by the user step and changed by the reconfigure step; 

93# the options flow only covers the event subscription settings in COMMON_DATA_SCHEMA. 

94OTEL_CONNECTION_KEYS: frozenset[str] = frozenset(str(k) for k in OTEL_DATA_SCHEMA.schema) 

95SYSLOG_CONNECTION_KEYS: frozenset[str] = frozenset(str(k) for k in SYSLOG_DATA_SCHEMA.schema) 

96 

97 

98def _otel_title(host: str, port: int) -> str: 

99 return f"OTLP @ {host}:{port}" 

100 

101 

102def _syslog_title(host: str, port: int, protocol: str) -> str: 

103 return f"Syslog @ {host}:{port} ({protocol.upper()})" 

104 

105 

106async def _async_validate_otel( 

107 hass: HomeAssistant, user_input: dict[str, Any], warn_plain_token: bool = False 

108) -> dict[str, str]: 

109 """Check OTLP form input: header and attribute formats, then a test record to the collector.""" 

110 errors: dict[str, str] = {} 

111 use_tls = user_input[CONF_USE_TLS] 

112 url = _build_endpoint_url(user_input[CONF_HOST], user_input[CONF_PORT], use_tls, user_input.get(CONF_PATH, OTLP_LOGS_PATH)) 

113 

114 # Validate header fields format before connecting 

115 extra_headers: dict[str, str] = {} 

116 token = user_input.get(CONF_TOKEN, "").strip() 

117 if token: 

118 if warn_plain_token and not use_tls: 

119 _LOGGER.warning("remote_logger: token configured without TLS; token will be sent in plain text") 

120 token_type = user_input.get(CONF_TOKEN_TYPE, TOKEN_TYPE_BEARER) 

121 extra_headers["Authorization"] = build_auth_header(token, token_type) 

122 raw_headers = "\n".join(user_input.get(CONF_HEADERS, [])) 

123 if raw_headers: 

124 try: 

125 extra_headers.update(parse_headers(raw_headers)) 

126 except ValueError: 

127 errors[CONF_HEADERS] = "invalid_headers" 

128 

129 # Validate connectivity 

130 if not errors: 

131 session = async_get_clientsession(hass, verify_ssl=use_tls) 

132 errors = await otel_validate(session, url, user_input[CONF_ENCODING], extra_headers or None) 

133 # Validate resource attributes format 

134 if not errors: 

135 raw_attrs = user_input.get(CONF_RESOURCE_ATTRIBUTES, "") 

136 if raw_attrs.strip(): 

137 try: 

138 parse_resource_attributes(raw_attrs) 

139 except ValueError: 

140 errors[CONF_RESOURCE_ATTRIBUTES] = "invalid_attributes" 

141 return errors 

142 

143 

144async def _async_validate_syslog(hass: HomeAssistant, user_input: dict[str, Any]) -> dict[str, str]: 

145 """Check the syslog server can be reached with the form's settings.""" 

146 error = await syslog_validate( 

147 hass, user_input[CONF_HOST], user_input[CONF_PORT], user_input[CONF_PROTOCOL], user_input.get(CONF_USE_TLS, False) 

148 ) 

149 return {"base": error} if error else {} 

150 

151 

152class OtelLogsConfigFlow(ConfigFlow, domain=DOMAIN): 

153 """Handle a config flow for OpenTelemetry Log Exporter.""" 

154 

155 VERSION = 2 

156 # 2.2: sensor unique IDs keyed by entry_id instead of the entry title 

157 # 2.3: connection settings only in data (the options flow used to copy them into options) 

158 MINOR_VERSION = 3 

159 

160 def __init__(self) -> None: 

161 super().__init__() 

162 self._pending_data: dict[str, Any] = {} 

163 

164 @staticmethod 

165 @callback 

166 def async_get_options_flow(config_entry: ConfigEntry) -> OptionsFlow: 

167 """Return the options flow handler.""" 

168 return RemoteLoggerOptionsFlow(config_entry) 

169 

170 async def async_step_user( 

171 self, 

172 user_input: dict[str, Any] | None = None, 

173 ) -> ConfigFlowResult: 

174 """Show menu to choose backend type.""" 

175 return self.async_show_menu( 

176 step_id="user", 

177 menu_options=["otel", "syslog"], 

178 ) 

179 

180 async def async_step_otel(self, user_input: dict[str, Any] | None = None) -> ConfigFlowResult: 

181 """Handle OpenTelemetry OTLP configuration.""" 

182 errors: dict[str, str] = {} 

183 

184 if user_input is not None: 

185 host = user_input[CONF_HOST] 

186 port = user_input[CONF_PORT] 

187 errors = await _async_validate_otel(self.hass, user_input, warn_plain_token=True) 

188 

189 if not errors: 

190 await self.async_set_unique_id(f"{DOMAIN}_{BACKEND_OTEL}_{host}_{port}") 

191 self._abort_if_unique_id_configured() 

192 self._pending_data = {**user_input, CONF_BACKEND: BACKEND_OTEL} 

193 self._pending_data["_title"] = _otel_title(host, port) 

194 return await self.async_step_common() 

195 

196 return self.async_show_form( 

197 step_id="otel", 

198 data_schema=self.add_suggested_values_to_schema(OTEL_DATA_SCHEMA, user_input or {}), 

199 errors=errors, 

200 description_placeholders={"validation_message": VALIDATION_MESSAGE}, 

201 ) 

202 

203 async def async_step_reauth(self, entry_data: dict[str, Any]) -> ConfigFlowResult: 

204 """Initiate reauth after authentication failure.""" 

205 return await self.async_step_reauth_otel() 

206 

207 async def async_step_reauth_otel(self, user_input: dict[str, Any] | None = None) -> ConfigFlowResult: 

208 """Handle re-entry of the bearer token after an authentication failure.""" 

209 reauth_entry = self._get_reauth_entry() 

210 errors: dict[str, str] = {} 

211 

212 if user_input is not None: 

213 token = user_input.get(CONF_TOKEN, "").strip() 

214 extra_headers: dict[str, str] = {} 

215 if token: 

216 token_type = user_input.get(CONF_TOKEN_TYPE, TOKEN_TYPE_BEARER) 

217 extra_headers["Authorization"] = build_auth_header(token, token_type) 

218 raw_headers = "\n".join(reauth_entry.data.get(CONF_HEADERS, [])) 

219 if raw_headers: 

220 extra_headers.update(parse_headers(raw_headers)) 

221 

222 url = _build_endpoint_url( 

223 reauth_entry.data[CONF_HOST], 

224 reauth_entry.data[CONF_PORT], 

225 reauth_entry.data[CONF_USE_TLS], 

226 reauth_entry.data.get(CONF_PATH, OTLP_LOGS_PATH), 

227 ) 

228 session = async_get_clientsession(self.hass, verify_ssl=reauth_entry.data[CONF_USE_TLS]) 

229 errors = await otel_validate(session, url, reauth_entry.data[CONF_ENCODING], extra_headers or None) 

230 if not errors: 

231 # async_update_and_abort, not async_update_reload_and_abort: async_setup_entry 

232 # registers an update listener that already reloads on any entry change. Using the 

233 # "_reload" variant as well is deprecated, and raises from HA 2026.12. 

234 return self.async_update_and_abort( 

235 reauth_entry, 

236 data_updates={ 

237 CONF_TOKEN: user_input[CONF_TOKEN], 

238 CONF_TOKEN_TYPE: user_input.get(CONF_TOKEN_TYPE, TOKEN_TYPE_BEARER), 

239 }, 

240 ) 

241 

242 return self.async_show_form( 

243 step_id="reauth_otel", 

244 data_schema=self.add_suggested_values_to_schema(REAUTH_OTEL_DATA_SCHEMA, user_input or {}), 

245 errors=errors, 

246 description_placeholders={"validation_message": VALIDATION_MESSAGE}, 

247 ) 

248 

249 async def async_step_reconfigure(self, user_input: dict[str, Any] | None = None) -> ConfigFlowResult: 

250 """Change the connection settings of an existing entry. 

251 

252 These are config entry *data*, so HA's guidance is a reconfigure step rather than the 

253 options flow, which covers only the event subscriptions. 

254 """ 

255 if self._get_reconfigure_entry().data.get(CONF_BACKEND) == BACKEND_SYSLOG: 

256 return await self.async_step_reconfigure_syslog() 

257 return await self.async_step_reconfigure_otel() 

258 

259 async def async_step_reconfigure_otel(self, user_input: dict[str, Any] | None = None) -> ConfigFlowResult: 

260 """Change the OTLP collector connection.""" 

261 entry = self._get_reconfigure_entry() 

262 errors: dict[str, str] = {} 

263 if user_input is not None: 

264 errors = await _async_validate_otel(self.hass, user_input, warn_plain_token=True) 

265 if not errors: 

266 return await self._async_update_connection( 

267 entry, 

268 user_input, 

269 OTEL_CONNECTION_KEYS, 

270 f"{DOMAIN}_{BACKEND_OTEL}_{user_input[CONF_HOST]}_{user_input[CONF_PORT]}", 

271 _otel_title(entry.data[CONF_HOST], entry.data[CONF_PORT]), 

272 _otel_title(user_input[CONF_HOST], user_input[CONF_PORT]), 

273 ) 

274 suggested = user_input or {**entry.data, CONF_HEADERS: _to_list(entry.data.get(CONF_HEADERS, []))} 

275 return self.async_show_form( 

276 step_id="reconfigure_otel", 

277 data_schema=self.add_suggested_values_to_schema(OTEL_DATA_SCHEMA, suggested), 

278 errors=errors, 

279 description_placeholders={"validation_message": VALIDATION_MESSAGE}, 

280 ) 

281 

282 async def async_step_reconfigure_syslog(self, user_input: dict[str, Any] | None = None) -> ConfigFlowResult: 

283 """Change the syslog server connection.""" 

284 entry = self._get_reconfigure_entry() 

285 errors: dict[str, str] = {} 

286 if user_input is not None: 

287 errors = await _async_validate_syslog(self.hass, user_input) 

288 if not errors: 

289 return await self._async_update_connection( 

290 entry, 

291 user_input, 

292 SYSLOG_CONNECTION_KEYS, 

293 entry.unique_id, # one syslog entry only, whatever its server 

294 _syslog_title(entry.data[CONF_HOST], entry.data[CONF_PORT], entry.data[CONF_PROTOCOL]), 

295 _syslog_title(user_input[CONF_HOST], user_input[CONF_PORT], user_input[CONF_PROTOCOL]), 

296 ) 

297 return self.async_show_form( 

298 step_id="reconfigure_syslog", 

299 data_schema=self.add_suggested_values_to_schema(SYSLOG_DATA_SCHEMA, user_input or dict(entry.data)), 

300 errors=errors, 

301 ) 

302 

303 async def _async_update_connection( 

304 self, 

305 entry: ConfigEntry, 

306 user_input: dict[str, Any], 

307 connection_keys: frozenset[str], 

308 unique_id: str | None, 

309 old_default_title: str, 

310 new_default_title: str, 

311 ) -> ConfigFlowResult: 

312 if unique_id != entry.unique_id: 

313 # Pointing at a collector that another entry already exports to 

314 await self.async_set_unique_id(unique_id) 

315 self._abort_if_unique_id_configured() 

316 # Replace every connection key, so an optional field cleared in the form (e.g. the token) 

317 # is removed rather than keeping its old value. 

318 data = {k: v for k, v in entry.data.items() if k not in connection_keys} 

319 # async_update_and_abort, not async_update_reload_and_abort: the update listener reloads 

320 return self.async_update_and_abort( 

321 entry, 

322 unique_id=unique_id, 

323 # Keep a title the user chose; follow the endpoint only if it's still the generated one 

324 title=new_default_title if entry.title == old_default_title else entry.title, 

325 data={**data, **user_input}, 

326 ) 

327 

328 async def async_step_syslog(self, user_input: dict[str, Any] | None = None) -> ConfigFlowResult: 

329 """Handle Syslog RFC 5424 configuration.""" 

330 errors: dict[str, str] = {} 

331 

332 if user_input is not None: 

333 host = user_input[CONF_HOST] 

334 port = user_input[CONF_PORT] 

335 protocol = user_input[CONF_PROTOCOL] 

336 errors = await _async_validate_syslog(self.hass, user_input) 

337 

338 if not errors: 

339 await self.async_set_unique_id(f"{DOMAIN}_{BACKEND_SYSLOG}") 

340 self._abort_if_unique_id_configured() 

341 self._pending_data = {**user_input, CONF_BACKEND: BACKEND_SYSLOG} 

342 self._pending_data["_title"] = _syslog_title(host, port, protocol) 

343 return await self.async_step_common() 

344 

345 return self.async_show_form( 

346 step_id="syslog", 

347 data_schema=self.add_suggested_values_to_schema(SYSLOG_DATA_SCHEMA, user_input or {}), 

348 errors=errors, 

349 ) 

350 

351 async def async_step_common(self, user_input: dict[str, Any] | None = None) -> ConfigFlowResult: 

352 """Configure common event subscription options.""" 

353 errors: dict[str, str] = {} 

354 if user_input is not None: 

355 flat: dict[str, Any] = {k: v for k, v in user_input.items() if not isinstance(v, dict)} 

356 for v in user_input.values(): 

357 if isinstance(v, dict): 

358 flat.update(v) 

359 if flat.get(CONF_LOG_HA_STATE_CHANGES) and flat.get(CONF_LOG_HA_FULL_STATE_CHANGES): 

360 errors[CONF_LOG_HA_FULL_STATE_CHANGES] = "state_changes_exclusive" 

361 else: 

362 title = self._pending_data.pop("_title") 

363 return self.async_create_entry( 

364 title=title, 

365 data={**self._pending_data, **flat}, 

366 ) 

367 

368 return self.async_show_form( 

369 step_id="common", 

370 data_schema=self.add_suggested_values_to_schema(COMMON_DATA_SCHEMA, user_input or {}), 

371 errors=errors, 

372 description_placeholders={ 

373 "learn_more": "[Learn about HA events](https://www.home-assistant.io/docs/configuration/events/)", 

374 }, 

375 ) 

376 

377 

378class RemoteLoggerOptionsFlow(OptionsFlow): 

379 """Allow editing event subscriptions after setup. Connection settings use the reconfigure step.""" 

380 

381 def __init__(self, config_entry: ConfigEntry) -> None: 

382 self._config_entry = config_entry 

383 

384 async def async_step_init(self, user_input: dict[str, Any] | None = None) -> ConfigFlowResult: 

385 """Show the event subscription form.""" 

386 return await self.async_step_events() 

387 

388 async def async_step_events(self, user_input: dict[str, Any] | None = None) -> ConfigFlowResult: 

389 """Handle event subscription options.""" 

390 errors: dict[str, str] = {} 

391 if user_input is not None: 

392 flat: dict[str, Any] = {k: v for k, v in user_input.items() if not isinstance(v, dict)} 

393 for v in user_input.values(): 

394 if isinstance(v, dict): 

395 flat.update(v) 

396 if flat.get(CONF_LOG_HA_STATE_CHANGES) and flat.get(CONF_LOG_HA_FULL_STATE_CHANGES): 

397 errors[CONF_LOG_HA_FULL_STATE_CHANGES] = "state_changes_exclusive" 

398 else: 

399 return self.async_create_entry(title="", data=flat) 

400 

401 if user_input is not None: 

402 suggested = user_input 

403 else: 

404 merged = {**self._config_entry.data, **self._config_entry.options} 

405 suggested = { 

406 CONF_EVENT_BASED_LOGGING: merged.get(CONF_EVENT_BASED_LOGGING, False), 

407 CONF_LOG_LEVEL: merged.get(CONF_LOG_LEVEL, DEFAULT_LOG_LEVEL), 

408 "ha_standard_events": { 

409 CONF_LOG_HA_LIFECYCLE: merged.get(CONF_LOG_HA_LIFECYCLE, False), 

410 CONF_LOG_HA_CORE_CHANGES: merged.get(CONF_LOG_HA_CORE_CHANGES, False), 

411 CONF_LOG_HA_CORE_ACTIVITY: merged.get(CONF_LOG_HA_CORE_ACTIVITY, False), 

412 CONF_LOG_HA_STATE_CHANGES: merged.get(CONF_LOG_HA_STATE_CHANGES, False), 

413 CONF_LOG_HA_FULL_STATE_CHANGES: merged.get(CONF_LOG_HA_FULL_STATE_CHANGES, False), 

414 }, 

415 CONF_LOG_HA_EVENT_BODY: merged.get(CONF_LOG_HA_EVENT_BODY, False), 

416 CONF_SUPPRESS_SYSTEM_LOG_EVENT_NAME: merged.get(CONF_SUPPRESS_SYSTEM_LOG_EVENT_NAME, True), 

417 CONF_CUSTOM_EVENTS: _to_list(merged.get(CONF_CUSTOM_EVENTS, [])), 

418 } 

419 return self.async_show_form( 

420 step_id="events", 

421 data_schema=self.add_suggested_values_to_schema(COMMON_DATA_SCHEMA, suggested), 

422 errors=errors, 

423 description_placeholders={ 

424 "learn_more": "[Learn about HA events](https://www.home-assistant.io/docs/configuration/events/)", 

425 }, 

426 )