prefix.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. """X-Forwarded-Prefix and public-URL resolution for reverse-proxied deploys.
  2. Proxies mounting the dashboard at a path inject ``X-Forwarded-Prefix: /hermes``
  3. so the backend can build prefixed URLs (Location headers, OAuth redirect_uri,
  4. cookie Path, SPA asset URLs). An operator-declared ``HERMES_DASHBOARD_PUBLIC_URL``
  5. / ``dashboard.public_url`` is used verbatim for the OAuth redirect_uri instead
  6. (relief valve for unreliable proxy header chains). Single source of truth so
  7. the gate, routes, cookies and SPA mount agree on validation.
  8. """
  9. from __future__ import annotations
  10. import logging
  11. import os
  12. import urllib.parse
  13. from typing import Optional
  14. _log = logging.getLogger(__name__)
  15. # Home Assistant ingress prefixes are already 63 chars before a deployment adds its own
  16. # sub-path; keep a bounded header budget with room for real mounts.
  17. _MAX_PREFIX_LENGTH = 256
  18. # Any of these in a public_url / prefix means a typo or a header-injection attempt: reject the
  19. # whole value, never sanitise.
  20. _REJECT_CHARS = frozenset(('"', "'", "<", ">", " ", "\n", "\r", "\t"))
  21. # ``resolve_public_url`` runs on every authenticated request, so warnings are de-duplicated per
  22. # distinct (source, value) — a changed value warns afresh.
  23. _warned_malformed_public_urls: set = set()
  24. _warned_malformed_prefixes: set = set()
  25. def _warn_once(seen: set, key: tuple, cleaned: str, msg: str, *args) -> None:
  26. if not cleaned or key in seen:
  27. return
  28. seen.add(key)
  29. _log.warning(msg, *args)
  30. def _warn_if_malformed(source: str, raw: str) -> None:
  31. """Warn once when a non-empty public-url value was rejected (almost always a missing scheme;
  32. silently falling back to header reconstruction can yield the wrong scheme behind a proxy)."""
  33. cleaned = raw.strip() if raw else ""
  34. _warn_once(
  35. _warned_malformed_public_urls, (source, cleaned), cleaned,
  36. "%s is set to %r but was ignored because it is not a valid "
  37. "absolute URL — it must include an http:// or https:// scheme "
  38. "(e.g. https://%s). Falling back to reconstructing the OAuth "
  39. "redirect URI from request headers, which may produce the wrong "
  40. "scheme behind a reverse proxy.",
  41. source, cleaned, cleaned.split("://")[-1] or "hermes.example.com")
  42. def _warn_if_malformed_prefix(raw: Optional[str], reason: str) -> None:
  43. """Warn once when a non-empty X-Forwarded-Prefix value is rejected."""
  44. cleaned = raw.strip() if raw else ""
  45. _warn_once(
  46. _warned_malformed_prefixes, (cleaned, reason), cleaned,
  47. "X-Forwarded-Prefix header %r was ignored because %s. "
  48. "Dashboard URLs will be generated without a reverse-proxy path prefix.", cleaned, reason)
  49. def normalise_prefix(raw: Optional[str]) -> str:
  50. """``"/hermes"`` form (no trailing slash) or ``""`` when unset/malformed. ``..``, ``//`` and
  51. injection characters are rejected so a hostile proxy cannot smuggle HTML or traversal."""
  52. p = raw.strip() if raw else ""
  53. if not p:
  54. return ""
  55. if not p.startswith("/"):
  56. p = "/" + p
  57. p = p.rstrip("/")
  58. if "//" in p or ".." in p or any(c in p for c in _REJECT_CHARS):
  59. _warn_if_malformed_prefix(raw, "it contains a disallowed character or path sequence")
  60. return ""
  61. if len(p) > _MAX_PREFIX_LENGTH:
  62. _warn_if_malformed_prefix(raw, f"it is longer than {_MAX_PREFIX_LENGTH} characters")
  63. return ""
  64. return p
  65. def prefix_from_request(request) -> str:
  66. """Normalised ``X-Forwarded-Prefix`` from a Starlette request, or ``""``."""
  67. return normalise_prefix(request.headers.get("x-forwarded-prefix"))
  68. # --- HERMES_DASHBOARD_PUBLIC_URL / dashboard.public_url --------------------
  69. def _normalise_public_url(raw: Optional[str]) -> str:
  70. """Cleaned ``scheme://netloc[/path]`` (trailing slash stripped) or ``""`` when
  71. empty/malformed/injection-suspect (= fall back to request reconstruction)."""
  72. url = raw.strip() if raw else ""
  73. if not url or any(c in url for c in _REJECT_CHARS):
  74. return ""
  75. try:
  76. parsed = urllib.parse.urlparse(url)
  77. except ValueError:
  78. return ""
  79. if parsed.scheme not in {"http", "https"} or not parsed.netloc:
  80. return ""
  81. return url.rstrip("/")
  82. def _load_dashboard_section() -> dict:
  83. """``dashboard`` block of config.yaml as a dict, or ``{}`` when unloadable/absent/non-dict."""
  84. try:
  85. from hermes_cli.config import load_config
  86. except Exception:
  87. return {}
  88. try:
  89. cfg = load_config()
  90. except Exception as exc:
  91. _log.debug("dashboard-auth.prefix: load_config() raised %s; "
  92. "falling back to env-only configuration", exc)
  93. return {}
  94. section = cfg.get("dashboard") if isinstance(cfg, dict) else None
  95. return section if isinstance(section, dict) else {}
  96. def resolve_public_url(state=None) -> str:
  97. """Operator-declared dashboard public URL, or ``""`` (reconstruct from request). Precedence:
  98. ``HERMES_DASHBOARD_PUBLIC_URL`` env (blank counts as unset so a provisioned-but-blank secret
  99. cannot shadow config.yaml), then ``dashboard.public_url``; malformed warns and falls through.
  100. *state* is the serving app's state. A listener that declares its own public URL there
  101. (``listener_public_url``, ``""`` for none: the gateway's Webapp listener, from ``webapp.public_url``)
  102. gets that, and the dashboard's setting is never read for it."""
  103. own = getattr(state, "listener_public_url", None)
  104. if own is not None:
  105. return own
  106. env_raw = os.environ.get("HERMES_DASHBOARD_PUBLIC_URL", "")
  107. env_clean = _normalise_public_url(env_raw)
  108. if env_clean:
  109. return env_clean
  110. _warn_if_malformed("HERMES_DASHBOARD_PUBLIC_URL env var", env_raw)
  111. cfg_raw = str(_load_dashboard_section().get("public_url", ""))
  112. cfg_clean = _normalise_public_url(cfg_raw)
  113. if not cfg_clean:
  114. _warn_if_malformed("dashboard.public_url in config.yaml", cfg_raw)
  115. return cfg_clean