Skip to content

Commit c36def6

Browse files
nftpoetristteknium1
authored andcommitted
fix(photon): scope project_id/node_bin/require_mention/reactions/sidecar config to the active profile under multiplexing
PhotonAdapter.__init__, check_requirements, validate_config, _env_enablement, _markdown_enabled, _reactions_enabled, and _standalone_send in adapter.py, plus load_project_credentials and load_dashboard_project_id in auth.py, all read PHOTON_PROJECT_ID/ PHOTON_NODE_BIN/PHOTON_SIDECAR_PORT/PHOTON_SIDECAR_AUTOSTART/ PHOTON_PROBE_*/PHOTON_REQUIRE_MENTION/PHOTON_MENTION_PATTERNS/ PHOTON_REACTIONS/PHOTON_MARKDOWN/PHOTON_HOME_CHANNEL(_NAME)/ PHOTON_DASHBOARD_PROJECT_ID via raw os.getenv -- only PHOTON_PROJECT_SECRET and PHOTON_SIDECAR_TOKEN were already scoped via _get_scoped_secret. Notably __init__'s project_id read was a stronger variant of the bug (like the IRC fix in this series, item 11): the original `os.getenv("PHOTON_PROJECT_ID") or extra.get("project_id") or stored_id` ordering let a raw env read override even an explicitly configured config.yaml extra -- a secondary profile that set its own project_id via extra would still silently authenticate against the default profile's Spectrum project, because the default profile's project id is always bridged to os.environ under multiplex and env was checked first. _reactions_enabled() and the require_mention/mention_patterns reads in __init__ are exercised on every live inbound message / tapback, not just at construction, so a secondary profile's reaction/mention-gating behavior would be driven by the default profile's settings for the adapter's entire runtime lifetime. Switch every raw PHOTON_* read (except the two already scoped) to _get_scoped_secret(), matching the module's existing helper (already defined identically in both adapter.py and auth.py). Left _dashboard_host()/_spectrum_host() and the interactive device-login flow functions in auth.py untouched -- these are CLI-only management-plane calls (`hermes photon login`/`setup`), not part of the gateway's per-profile adapter construction/connection lifecycle, so they are not reachable under a multiplexed secondary profile's scope; noted as a "Scope note" in the PR body rather than silently expanding scope to unreachable call sites. Adds a new tests/plugins/platforms/photon/test_multiplex_profile_scope.py (9 tests, two classes covering auth.py and adapter.py separately) mirroring the fixture/assertion style established in tests/gateway/test_line_plugin.py's TestMultiplexProfileScope, reusing test_auth.py's tmp_hermes_home isolation pattern so tests don't depend on the real ~/.hermes/auth.json fallback. Mutation-verified: stashed the production fix and confirmed 7 of 9 new tests fail against pre-fix code (the other 2 are non-differentiating regression guards -- unscoped- default-profile-precedence, one per class -- which correctly pass either way). Restored the fix; all 140 tests in tests/plugins/platforms/photon/, the 10 photon-related parametrized tests in test_adapter_startup_secret_scope.py, and the broader test_multiplex_adapter_registry.py / test_adapter_connect_classification.py suites (45 tests) pass.
1 parent 327e904 commit c36def6

3 files changed

Lines changed: 141 additions & 19 deletions

File tree

‎plugins/platforms/photon/adapter.py‎

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -423,10 +423,10 @@ def check_requirements() -> bool:
423423
if not HTTPX_AVAILABLE:
424424
logger.warning("photon: httpx not installed — pip install httpx")
425425
return False
426-
if not shutil.which(os.getenv("PHOTON_NODE_BIN") or "node"):
426+
if not shutil.which(_get_scoped_secret("PHOTON_NODE_BIN") or "node"):
427427
logger.warning(
428428
"photon: node binary '%s' not found on PATH",
429-
os.getenv("PHOTON_NODE_BIN") or "node",
429+
_get_scoped_secret("PHOTON_NODE_BIN") or "node",
430430
)
431431
return False
432432
if not sidecar_deps_installed():
@@ -551,7 +551,7 @@ def _reinstall_sidecar_deps() -> None:
551551

552552
def validate_config(cfg: PlatformConfig) -> bool:
553553
extra = cfg.extra or {}
554-
project_id = extra.get("project_id") or os.getenv("PHOTON_PROJECT_ID")
554+
project_id = extra.get("project_id") or _get_scoped_secret("PHOTON_PROJECT_ID")
555555
project_secret = extra.get("project_secret") or _get_scoped_secret("PHOTON_PROJECT_SECRET")
556556
if not project_id or not project_secret:
557557
# Fall back to auth.json
@@ -574,11 +574,11 @@ def _env_enablement() -> Optional[dict]:
574574
if not (project_id and project_secret):
575575
return None
576576
seed: dict = {"project_id": project_id, "project_secret": project_secret}
577-
home = os.getenv("PHOTON_HOME_CHANNEL", "").strip()
577+
home = _get_scoped_secret("PHOTON_HOME_CHANNEL", "").strip()
578578
if home:
579579
seed["home_channel"] = {
580580
"chat_id": home,
581-
"name": os.getenv("PHOTON_HOME_CHANNEL_NAME", "Home"),
581+
"name": _get_scoped_secret("PHOTON_HOME_CHANNEL_NAME", "Home"),
582582
}
583583
return seed
584584

@@ -591,7 +591,7 @@ def _markdown_enabled() -> bool:
591591
``PHOTON_MARKDOWN=false`` is the kill-switch back to stripped plain
592592
text without a release.
593593
"""
594-
return os.getenv("PHOTON_MARKDOWN", "true").strip().lower() not in {
594+
return _get_scoped_secret("PHOTON_MARKDOWN", "true").strip().lower() not in {
595595
"false", "0", "no",
596596
}
597597

@@ -729,7 +729,7 @@ def __init__(self, config: PlatformConfig):
729729
# the spectrum-ts SDK authenticates with.
730730
stored_id, stored_sec = load_project_credentials()
731731
self._project_id: str = (
732-
os.getenv("PHOTON_PROJECT_ID")
732+
_get_scoped_secret("PHOTON_PROJECT_ID")
733733
or extra.get("project_id")
734734
or stored_id
735735
or ""
@@ -743,17 +743,17 @@ def __init__(self, config: PlatformConfig):
743743

744744
# Sidecar
745745
self._sidecar_port = _coerce_port(
746-
extra.get("sidecar_port") or os.getenv("PHOTON_SIDECAR_PORT"),
746+
extra.get("sidecar_port") or _get_scoped_secret("PHOTON_SIDECAR_PORT"),
747747
_DEFAULT_SIDECAR_PORT,
748748
)
749749
self._sidecar_bind = _DEFAULT_SIDECAR_BIND
750750
self._sidecar_token = (
751751
_get_scoped_secret("PHOTON_SIDECAR_TOKEN") or secrets.token_hex(16)
752752
)
753753
self._autostart_sidecar = str(
754-
os.getenv("PHOTON_SIDECAR_AUTOSTART", "true")
754+
_get_scoped_secret("PHOTON_SIDECAR_AUTOSTART", "true")
755755
).lower() not in ("0", "false", "no")
756-
self._node_bin = os.getenv("PHOTON_NODE_BIN") or shutil.which("node") or "node"
756+
self._node_bin = _get_scoped_secret("PHOTON_NODE_BIN") or shutil.which("node") or "node"
757757

758758
# Presence watchdog. spectrum-ts only reconnects when its inbound
759759
# iterator throws or ends; a half-open ("zombie") gRPC socket makes the
@@ -776,21 +776,21 @@ def __init__(self, config: PlatformConfig):
776776
self._probe_interval = _coerce_float(
777777
_first_set(
778778
extra.get("probe_interval_seconds"),
779-
os.getenv("PHOTON_PROBE_INTERVAL_SECONDS"),
779+
_get_scoped_secret("PHOTON_PROBE_INTERVAL_SECONDS"),
780780
),
781781
600.0,
782782
)
783783
self._probe_timeout = _coerce_float(
784784
_first_set(
785785
extra.get("probe_timeout_seconds"),
786-
os.getenv("PHOTON_PROBE_TIMEOUT_SECONDS"),
786+
_get_scoped_secret("PHOTON_PROBE_TIMEOUT_SECONDS"),
787787
),
788788
10.0,
789789
)
790790
self._probe_max_failures = _coerce_int(
791791
_first_set(
792792
extra.get("probe_max_failures"),
793-
os.getenv("PHOTON_PROBE_MAX_FAILURES"),
793+
_get_scoped_secret("PHOTON_PROBE_MAX_FAILURES"),
794794
),
795795
3,
796796
)
@@ -843,14 +843,14 @@ def __init__(self, config: PlatformConfig):
843843
# always processed. Config key wins, then env var.
844844
_require_mention = extra.get("require_mention")
845845
if _require_mention is None:
846-
_require_mention = os.getenv("PHOTON_REQUIRE_MENTION")
846+
_require_mention = _get_scoped_secret("PHOTON_REQUIRE_MENTION")
847847
self.require_mention = str(_require_mention).strip().lower() in {
848848
"true", "1", "yes", "on",
849849
}
850850
self._mention_patterns = self._compile_mention_patterns(
851851
extra["mention_patterns"]
852852
if "mention_patterns" in extra
853-
else os.getenv("PHOTON_MENTION_PATTERNS")
853+
else _get_scoped_secret("PHOTON_MENTION_PATTERNS")
854854
)
855855

856856
# -- Group-mention gating (parity with BlueBubbles) -------------------
@@ -2274,7 +2274,7 @@ def _is_recent_richlink_preview(self, chat_id: str, content: Dict[str, Any]) ->
22742274
return True
22752275

22762276
def _reactions_enabled(self) -> bool:
2277-
return os.getenv("PHOTON_REACTIONS", "false").strip().lower() in {
2277+
return _get_scoped_secret("PHOTON_REACTIONS", "false").strip().lower() in {
22782278
"true", "1", "yes", "on",
22792279
}
22802280

@@ -2805,7 +2805,7 @@ async def _standalone_send(
28052805
if not HTTPX_AVAILABLE:
28062806
return {"error": "httpx not installed"}
28072807
port = _coerce_port(
2808-
(pconfig.extra or {}).get("sidecar_port") or os.getenv("PHOTON_SIDECAR_PORT"),
2808+
(pconfig.extra or {}).get("sidecar_port") or _get_scoped_secret("PHOTON_SIDECAR_PORT"),
28092809
_DEFAULT_SIDECAR_PORT,
28102810
)
28112811
token = _get_scoped_secret("PHOTON_SIDECAR_TOKEN")

‎plugins/platforms/photon/auth.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -254,7 +254,7 @@ def load_project_credentials() -> Tuple[Optional[str], Optional[str]]:
254254
use. This is the pair the Node sidecar feeds to ``spectrum-ts``; the id
255255
is the unified project id (dashboard id == spectrumProjectId).
256256
"""
257-
env_id = os.getenv("PHOTON_PROJECT_ID")
257+
env_id = _get_scoped_secret("PHOTON_PROJECT_ID")
258258
env_sec = _get_scoped_secret("PHOTON_PROJECT_SECRET")
259259
if env_id and env_sec:
260260
return env_id, env_sec
@@ -277,7 +277,7 @@ def load_dashboard_project_id() -> Optional[str]:
277277
rewrote (it now 404s), while the Spectrum id always matches the live row.
278278
Falls back to the legacy keys for older records.
279279
"""
280-
env_id = os.getenv("PHOTON_DASHBOARD_PROJECT_ID")
280+
env_id = _get_scoped_secret("PHOTON_DASHBOARD_PROJECT_ID")
281281
if env_id:
282282
return env_id
283283
auth = _load_auth()
Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
"""Multiplex secondary-profile scope tests for the Photon adapter + auth module.
2+
3+
__init__'s project_id, check_requirements'/validate_config's node_bin/
4+
project_id, _env_enablement's home_channel, _reactions_enabled's
5+
PHOTON_REACTIONS, __init__'s require_mention, and _standalone_send's
6+
sidecar_port, plus auth.py's load_project_credentials/
7+
load_dashboard_project_id, all previously read raw os.getenv
8+
unconditionally (only PHOTON_PROJECT_SECRET/PHOTON_SIDECAR_TOKEN were
9+
already scoped via _get_scoped_secret). Under gateway.multiplex_profiles,
10+
os.environ holds the DEFAULT profile's YAML-to-env bridge output -- a
11+
secondary profile with its own (different or absent) Photon config could
12+
silently authenticate against the default profile's Spectrum project, or
13+
have its mention-gating/reaction behavior driven by the default profile's
14+
settings.
15+
16+
Notably project_id was a stronger variant of the bug (like the IRC fix in
17+
this series): __init__'s original
18+
`os.getenv("PHOTON_PROJECT_ID") or extra.get("project_id") or stored_id`
19+
ordering let a raw env read override even an explicitly configured
20+
config.yaml extra.
21+
22+
Mirrors the LINE/DingTalk/IRC/Mattermost fix for #98738.
23+
"""
24+
from __future__ import annotations
25+
26+
import os
27+
from pathlib import Path
28+
29+
import pytest
30+
31+
from gateway.config import PlatformConfig
32+
from plugins.platforms.photon import auth as photon_auth
33+
from plugins.platforms.photon.adapter import PhotonAdapter
34+
35+
_PHOTON_ENV = (
36+
"PHOTON_PROJECT_ID",
37+
"PHOTON_PROJECT_SECRET",
38+
"PHOTON_DASHBOARD_PROJECT_ID",
39+
"PHOTON_REQUIRE_MENTION",
40+
"PHOTON_REACTIONS",
41+
"PHOTON_HOME_CHANNEL",
42+
"PHOTON_HOME_CHANNEL_NAME",
43+
"PHOTON_SIDECAR_PORT",
44+
)
45+
46+
47+
@pytest.fixture
48+
def tmp_hermes_home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
49+
"""Isolate from the real ~/.hermes/auth.json fallback in load_project_credentials()."""
50+
home = tmp_path / "hermes"
51+
home.mkdir()
52+
monkeypatch.setenv("HERMES_HOME", str(home))
53+
for key in _PHOTON_ENV:
54+
monkeypatch.delenv(key, raising=False)
55+
yield home
56+
for key in _PHOTON_ENV:
57+
os.environ.pop(key, None)
58+
59+
60+
@pytest.fixture
61+
def multiplex_scope():
62+
"""Install multiplex + a secondary-profile secret scope; restore after."""
63+
tokens = []
64+
65+
def install(scope=None):
66+
from agent.secret_scope import set_multiplex_active, set_secret_scope
67+
68+
set_multiplex_active(True)
69+
tokens.append(set_secret_scope(scope or {}))
70+
return tokens[-1]
71+
72+
yield install
73+
74+
from agent.secret_scope import reset_secret_scope, set_multiplex_active
75+
76+
for token in reversed(tokens):
77+
reset_secret_scope(token)
78+
set_multiplex_active(False)
79+
80+
81+
@pytest.fixture
82+
def default_profile_env(monkeypatch):
83+
"""The default profile's YAML-to-env bridge output in os.environ."""
84+
monkeypatch.setenv("PHOTON_PROJECT_ID", "default-project-id")
85+
monkeypatch.setenv("PHOTON_PROJECT_SECRET", "default-project-secret")
86+
monkeypatch.setenv("PHOTON_REQUIRE_MENTION", "true")
87+
monkeypatch.setenv("PHOTON_REACTIONS", "true")
88+
89+
90+
class TestAuthMultiplexProfileScope:
91+
"""load_project_credentials / load_dashboard_project_id (auth.py)."""
92+
93+
def test_scoped_miss_does_not_leak_default_project_id(
94+
self, tmp_hermes_home, multiplex_scope, default_profile_env
95+
):
96+
multiplex_scope({"SOMETHING_ELSE": "x"})
97+
sid, secret = photon_auth.load_project_credentials()
98+
assert sid is None
99+
assert secret is None
100+
adapter = PhotonAdapter(PlatformConfig(enabled=True, extra={}))
101+
assert adapter._project_id == ""
102+
assert adapter.require_mention is False
103+
assert adapter._reactions_enabled() is False
104+
105+
class TestAdapterMultiplexProfileScope:
106+
"""PhotonAdapter.__init__ / _env_enablement / _reactions_enabled (adapter.py)."""
107+
108+
def test_secondary_extra_wins_over_default_profile_env(
109+
self, tmp_hermes_home, multiplex_scope, default_profile_env
110+
):
111+
"""A secondary profile's own config.yaml extra project_id must be
112+
authoritative -- not the default profile's bridged env value. The
113+
pre-fix ordering (raw os.getenv checked BEFORE extra) meant even an
114+
explicit extra config was silently overridden."""
115+
multiplex_scope({"PHOTON_PROJECT_SECRET": "profile-secret"})
116+
cfg = PlatformConfig(
117+
enabled=True,
118+
extra={"project_id": "profile-project-id"},
119+
)
120+
adapter = PhotonAdapter(cfg)
121+
assert adapter._project_id == "profile-project-id"
122+

0 commit comments

Comments
 (0)