"""Coercion for ``platform_settings.value`` reads. ``platform_settings.value`` is a JSON column and the admin upsert endpoint takes ``value: Any``, so the same logical setting can arrive as a JSON boolean (``false``), a JSON string (``"false"``), or a number (``0``) depending on who wrote it and how. That matters because the naive read is **fail-open**:: bool(row.value) # "false" -> True A feature flag read that way turns itself ON the moment somebody edits it through a client that sends strings — and the flags this is used for gate employee-facing pushes and automatic revocation, where the wrong direction is the expensive one. Every boolean setting read goes through :func:`as_bool` so the stringly-typed spelling cannot flip a gate open. """ from __future__ import annotations from typing import Any #: Spellings that mean False. Anything not recognised falls back to the #: caller's default rather than to ``bool(value)`` — an unparseable flag #: is "we do not know", and for a gate that means closed. _FALSE_TOKENS = frozenset({ "false", "0", "no", "off", "none", "null", "", "disabled", }) _TRUE_TOKENS = frozenset({"true", "1", "yes", "on", "enabled"}) def as_bool(value: Any, *, default: bool = False) -> bool: """Read a setting as a boolean without failing open. ``None`` and unrecognised values return ``default``; the caller's default is the safe side by construction, because every current caller defaults to "off". """ if value is None: return default if isinstance(value, bool): return value if isinstance(value, (int, float)): return value != 0 if isinstance(value, str): token = value.strip().lower() if token in _TRUE_TOKENS: return True if token in _FALSE_TOKENS: return False return default # A list / dict in a boolean slot is a misconfiguration, not a # truthy value. Non-empty containers would read as True otherwise. return default __all__ = ["as_bool"]