Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(slack-app): cache auth verdict and pre-filter dead workspace installs (#64784)

Vojta Bartoš465b6be72f9e
diff --git a/posthog/models/integration.py b/posthog/models/integration.py
index 7019a664f0b4..46d10a7e8479 100644
--- a/posthog/models/integration.py
+++ b/posthog/models/integration.py
@@ -961,6 +961,27 @@ class OauthIntegration:
integration.errors = ""
integration.save()
+ if kind == "slack":
+ # The cached auth verdict in slack_app is per-integration. A
+ # reconnect mints a new bot token, so any stale ``ok=false`` row
+ # from the previous token would silently demote this install for
+ # the remaining cache TTL. Inline-imported to keep the slack_app
+ # module off the core django.setup() path; wrapped so a broken
+ # slack_app build can't take down OAuth completion for every
+ # integration kind.
+ try:
+ from products.slack_app.backend.facade.api import ( # noqa: PLC0415
+ invalidate_slack_integration_auth_state,
+ )
+
+ invalidate_slack_integration_auth_state(integration.id)
+ except Exception:
+ logger.warning(
+ "slack_app_auth_state_invalidation_on_oauth_failed",
+ integration_id=integration.id,
+ exc_info=True,
+ )
+
return integration
def access_token_expired(self, time_threshold: timedelta | None = None) -> bool:
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.py
index b31995619494..8f58842f7a39 100644
--- a/products/slack_app/backend/api.py
+++ b/products/slack_app/backend/api.py
@@ -1142,14 +1142,6 @@ def _notify_missing_slack_scopes(
_post_slack_user_feedback(slack, channel, slack_user_id, thread_ts, text, prefer_thread_message=True)
-# Slack ``users.info`` error codes that mean the stored bot token can no longer talk to
-# Slack on this workspace's behalf. Surfaced as ``token_broken=True`` on the failure log
-# so support can distinguish "needs reconnect" from other API failures at a glance.
-_SLACK_AUTH_FAILURE_CODES = frozenset(
- {"token_revoked", "invalid_auth", "not_authed", "account_inactive", "token_expired"}
-)
-
-
def get_slack_email_for_user(probe_integration: Integration, slack_user_id: str) -> str | None:
"""Best-effort lookup of the Slack user's email via ``users.info``, cache-first then
a fresh hit on miss. Returns ``None`` when Slack doesn't expose an email for the
@@ -1158,7 +1150,17 @@ def get_slack_email_for_user(probe_integration: Integration, slack_user_id: str)
Every termination path emits a distinct structured log so a silent ``None`` can
still be diagnosed from logs alone — historically the failure modes collapsed
onto a downstream ``user_not_found`` warning that hid the actual cause.
+
+ Auth-class ``SlackApiError`` outcomes flip the shared ``slack_auth`` cache to
+ ``ok=false`` so the resolver demotes this install on subsequent mentions
+ rather than pinning every one to a dead token. The success path deliberately
+ does NOT write ``ok=true``: the cache lives in the resolver's ``auth.test``
+ layer, and a DB-cache hit (``SlackUserProfileCache``) proves nothing about
+ the live token. Letting the resolver own the positive verdict keeps the
+ cache truthful.
"""
+ from products.slack_app.backend.services.slack_auth import SLACK_AUTH_FAILURE_CODES, write_auth_state_broken
+
slack_client = SlackIntegration(probe_integration)
try:
user_info = get_slack_user_info(slack_client, probe_integration, slack_user_id)
@@ -1188,7 +1190,9 @@ def get_slack_email_for_user(probe_integration: Integration, slack_user_id: str)
return slack_email
except SlackApiError as exc:
error_code = exc.response.get("error") if exc.response else None
- token_broken = isinstance(error_code, str) and error_code in _SLACK_AUTH_FAILURE_CODES
+ token_broken = isinstance(error_code, str) and error_code in SLACK_AUTH_FAILURE_CODES
+ if token_broken and isinstance(error_code, str):
+ write_auth_state_broken(probe_integration.id, error_code)
logger.warning(
"slack_app_resolve_user_email_failed",
integration_id=probe_integration.id,
diff --git a/products/slack_app/backend/facade/__init__.py b/products/slack_app/backend/facade/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/slack_app/backend/facade/api.py b/products/slack_app/backend/facade/api.py
new file mode 100644
index 000000000000..f48d1aea40f6
--- /dev/null
+++ b/products/slack_app/backend/facade/api.py
@@ -0,0 +1,25 @@
+"""Facade for slack_app.
+
+The ONLY module other products are allowed to import. Keep the surface narrow:
+every function here lives behind a tach contract check, so each addition has a
+cost in cross-product coupling.
+
+Today the facade exists for one job — letting core's OAuth callback invalidate
+the per-integration auth-state cache when a Slack install is reconnected. We
+expose the helper as a stable re-export so the implementation can move around
+inside ``services/`` without breaking core.
+"""
+
+from __future__ import annotations
+
+from products.slack_app.backend.services.slack_auth import invalidate_auth_state
+
+
+def invalidate_slack_integration_auth_state(integration_id: int) -> None:
+ """Drop the cached auth verdict for ``integration_id``.
+
+ Call from core's OAuth completion path so a freshly-reconnected Slack
+ install doesn't get pinned to the stale ``ok=false`` state we wrote when
+ its previous token was revoked.
+ """
+ invalidate_auth_state(integration_id)
diff --git a/products/slack_app/backend/services/integration_resolver.py b/products/slack_app/backend/services/integration_resolver.py
index 5a0e9d6042c1..2470aa381c3b 100644
--- a/products/slack_app/backend/services/integration_resolver.py
+++ b/products/slack_app/backend/services/integration_resolver.py
@@ -168,11 +168,14 @@ def load_integrations(
the routing resolver against them. Thin wrapper around
``resolve_from_candidates`` that owns the candidate query.
"""
+ from products.slack_app.backend.services.slack_auth import check_integrations_auth_and_filter
+
candidates = list(
Integration.objects.filter(kind__in=kinds, integration_id=slack_team_id)
.select_related("team", "team__organization", "created_by")
.order_by("id")
)
+ candidates = check_integrations_auth_and_filter(candidates, slack_user_id=slack_user_id or None)
return resolve_from_candidates(
candidates,
slack_team_id=slack_team_id,
diff --git a/products/slack_app/backend/services/slack_auth.py b/products/slack_app/backend/services/slack_auth.py
new file mode 100644
index 000000000000..3666109442ec
--- /dev/null
+++ b/products/slack_app/backend/services/slack_auth.py
@@ -0,0 +1,294 @@
+"""Per-integration Slack auth-state cache.
+
+Real Slack call outcomes (``users.info``, ``chat.postMessage``, ``auth.test``)
+feed a small Redis-backed verdict that the resolver consults before picking a
+probe. The goal is to skip integrations whose bot token has gone bad — a dead
+install at ``candidates[0]`` (oldest by PK) silently broke every mention for
+the workspace because nothing fell through to a healthier install.
+
+Cache lifecycle:
+
+- **Read**: cheap, never blocks. A miss means "we don't know yet" — the next
+ real call will populate the entry.
+- **Write on success**: every Slack call that proves the token works refreshes
+ ``ok=true``. Opportunistic — we don't run defensive ``auth.test`` calls.
+- **Write on auth-class error**: only the codes in
+ ``products.slack_app.backend.api._SLACK_AUTH_FAILURE_CODES`` (token_revoked,
+ invalid_auth, not_authed, account_inactive, token_expired) flip the cache to
+ ``ok=false``. Transient failures (network, Slack 5xx, rate limits) leave the
+ cache untouched — otherwise a Slack outage would brick every workspace for
+ the full TTL.
+- **Invalidate**: the OAuth reconnect callback hits the facade re-export at
+ ``products.slack_app.backend.facade.api.invalidate_slack_integration_auth_state``
+ to drop the cache key so the next call mints a fresh verdict.
+"""
+
+from dataclasses import dataclass
+from datetime import datetime
+from typing import TYPE_CHECKING
+
+from django.core.cache import cache
+from django.utils import timezone
+
+import structlog
+
+if TYPE_CHECKING:
+ from slack_sdk.errors import SlackApiError
+
+ from posthog.models.integration import Integration
+
+logger = structlog.get_logger(__name__)
+
+# Six hours matches the precedent set by the previous bot-user-id cache —
+# long enough to amortize the per-mention check, short enough that a stale
+# negative verdict self-heals without manual intervention.
+SLACK_AUTH_STATE_CACHE_TTL_SECONDS = 60 * 60 * 6
+
+# Slack error codes that indicate the bot install can no longer authenticate.
+# Shared across the auth-state writers so a single source decides what counts
+# as "negative cache material" — transient/network failures must NOT brick the
+# workspace by writing ``ok=false`` for the full TTL.
+SLACK_AUTH_FAILURE_CODES = frozenset(
+ {"token_revoked", "invalid_auth", "not_authed", "account_inactive", "token_expired"}
+)
+
+
+@dataclass(frozen=True)
+class SlackIntegrationAuthState:
+ ok: bool
+ bot_user_id: str | None
+ error_code: str | None
+ checked_at: datetime
+
+
+def _cache_key(integration_id: int) -> str:
+ return f"slack_app:auth_state:v1:{integration_id}"
+
+
+def get_cached_auth_state(integration_id: int) -> SlackIntegrationAuthState | None:
+ """Return the cached verdict, or ``None`` on miss. Cheap.
+
+ Django's cache backend pickles the dataclass directly; ``isinstance`` guards
+ a value of an unexpected shape (e.g. a future schema migration that hasn't
+ drained the cache) by treating it as a miss instead of crashing the resolver.
+ """
+ raw = cache.get(_cache_key(integration_id))
+ return raw if isinstance(raw, SlackIntegrationAuthState) else None
+
+
+def write_auth_state_ok(integration_id: int, bot_user_id: str | None) -> None:
+ """Mark the install healthy. Called from the resolver's eager ``auth.test``
+ on cache miss; not from per-mention call sites (``get_slack_email_for_user``
+ et al), which leave positive verdicts to the resolver to keep the cache
+ truthful about what the live token can actually do.
+ """
+ cache.set(
+ _cache_key(integration_id),
+ SlackIntegrationAuthState(ok=True, bot_user_id=bot_user_id, error_code=None, checked_at=timezone.now()),
+ timeout=SLACK_AUTH_STATE_CACHE_TTL_SECONDS,
+ )
+
+
+def write_auth_state_broken(integration_id: int, error_code: str) -> None:
+ """Mark the install broken. Callers should only invoke this for auth-class
+ Slack error codes — see ``SLACK_AUTH_FAILURE_CODES``."""
+ cache.set(
+ _cache_key(integration_id),
+ SlackIntegrationAuthState(ok=False, bot_user_id=None, error_code=error_code, checked_at=timezone.now()),
+ timeout=SLACK_AUTH_STATE_CACHE_TTL_SECONDS,
+ )
+ logger.warning(
+ "slack_app_auth_state_marked_broken",
+ integration_id=integration_id,
+ error_code=error_code,
+ )
+
+
+def invalidate_auth_state(integration_id: int) -> None:
+ """Drop the cache entry so the next call mints a fresh verdict. Called by
+ the OAuth reconnect callback via
+ ``products.slack_app.backend.facade.api.invalidate_slack_integration_auth_state``."""
+ cache.delete(_cache_key(integration_id))
+ logger.info("slack_app_auth_state_invalidated", integration_id=integration_id)
+
+
+def classify_slack_api_error(exc: "SlackApiError") -> tuple[str | None, bool]:
+ """Return ``(error_code, is_token_broken)``. Centralizes the
+ ``exc.response.get("error") + membership check`` dance so every call site
+ (resolver eager-check, ``get_slack_email_for_user``, ``get_cached_bot_user_id``)
+ decides "drop this install from the candidate list" against the same rule.
+ ``error_code`` is ``None`` when Slack didn't attach a recognizable error to
+ the exception.
+ """
+ error_code = exc.response.get("error") if exc.response else None
+ if not isinstance(error_code, str):
+ return None, False
+ return error_code, error_code in SLACK_AUTH_FAILURE_CODES
+
+
+def _resolve_one_candidate_state(
+ candidate: "Integration", slack_user_id: str | None
+) -> SlackIntegrationAuthState | None:
+ """Return the auth-state verdict for ``candidate``, populating the cache via
+ ``auth.test`` on miss. Returns ``None`` when the verdict is unknown
+ (transient failure, non-auth-class Slack error). The caller drops these
+ candidates from the resulting list — see ``check_integrations_auth_and_filter``.
+ """
+ cached = get_cached_auth_state(candidate.id)
+ if cached is not None:
+ return cached
+
+ # Inline-imported so the module's pure cache primitives stay importable
+ # without pulling in the Slack SDK + ORM (facade re-export, test fixtures).
+ from slack_sdk.errors import SlackApiError # noqa: PLC0415
+
+ from posthog.models.integration import SlackIntegration # noqa: PLC0415
+
+ try:
+ response = SlackIntegration(candidate).client.auth_test()
+ except SlackApiError as exc:
+ error_code, token_broken = classify_slack_api_error(exc)
+ if token_broken and error_code is not None:
+ write_auth_state_broken(candidate.id, error_code)
+ logger.warning(
+ "slack_app_auth_test_token_broken",
+ integration_id=candidate.id,
+ slack_team_id=candidate.integration_id,
+ slack_user_id=slack_user_id,
+ error_code=error_code,
+ )
+ # Return the state we just wrote rather than re-reading from the
+ # cache: under eviction or a concurrent invalidate the read-back
+ # could come up None, which the caller would treat as "unknown"
+ # and drop a candidate we just confirmed is broken (vs the
+ # symmetric problem on the ok path of dropping a freshly-healthy
+ # candidate). Constructing inline is also one less Redis hop.
+ return SlackIntegrationAuthState(
+ ok=False, bot_user_id=None, error_code=error_code, checked_at=timezone.now()
+ )
+ # Non-auth-class Slack error (``ratelimited``, ``internal_error``, etc):
+ # don't pollute the cache. The candidate is treated as unknown — and
+ # under the current ``drop unhealthy`` contract that means dropped
+ # from this mention's candidate list. The next mention re-probes.
+ logger.warning(
+ "slack_app_auth_test_non_auth_error",
+ integration_id=candidate.id,
+ slack_team_id=candidate.integration_id,
+ slack_user_id=slack_user_id,
+ error_code=error_code,
+ )
+ return None
+ except Exception:
+ # Transient (network blip, Slack 5xx): refusing to brick the workspace
+ # for the full TTL on a one-off failure is intentional. Same as the
+ # non-auth Slack error path above — dropped this mention, retried next.
+ logger.warning(
+ "slack_app_auth_test_transient_failure",
+ integration_id=candidate.id,
+ slack_team_id=candidate.integration_id,
+ slack_user_id=slack_user_id,
+ exc_info=True,
+ )
+ return None
+
+ bot_user_id = response.get("user_id")
+ bot_user_id_value = bot_user_id if isinstance(bot_user_id, str) and bot_user_id else None
+ write_auth_state_ok(candidate.id, bot_user_id_value)
+ # See note on the write_auth_state_broken path above — return the just-
+ # written state rather than re-reading from the cache.
+ return SlackIntegrationAuthState(ok=True, bot_user_id=bot_user_id_value, error_code=None, checked_at=timezone.now())
+
+
+def check_integrations_auth_and_filter(
+ candidates: list["Integration"],
+ *,
+ slack_user_id: str | None = None,
+) -> list["Integration"]:
+ """Check each candidate's bot-token health and return only the healthy ones,
+ sorted with the freshest verdict first.
+
+ Single entry point for the resolver: for every candidate the function
+ consults the cache, runs ``auth.test`` on miss (populating the cache with
+ the result), then drops anything not cached as ``ok=true``.
+
+ Why drop rather than demote: the resolver's precedence ladder
+ (thread mapping > user default > workspace default > sole candidate >
+ picker) only honors a target that's *in the candidate list*. Keeping a
+ broken install in the list — even at the back — lets a stale thread
+ mapping or user-default route every mention through a dead token. Dropping
+ it lets the existing "kind drift" fallback in ``resolve_from_candidates``
+ walk down to the next precedence level naturally.
+
+ Buckets that get **dropped**:
+
+ - **unknown** — cache miss survived eager populate because ``auth.test``
+ transiently errored (Slack 5xx, network blip, ``ratelimited`` /
+ ``internal_error`` from Slack). The cache is left untouched so the next
+ mention retries, but we don't ship the user a probably-broken probe in
+ the meantime.
+ - **broken** — cached ``ok=false``. Recovery paths: the 6h TTL expires,
+ the OAuth reconnect callback invalidates the entry, or a subsequent
+ ``auth.test`` succeeds (the cache also expires naturally).
+
+ **Known trade-off**: a Slack control-plane outage that makes ``auth.test``
+ fail transiently for every install puts the workspace into the empty-result
+ path for the duration of the outage — every Slack surface (mentions,
+ link_shared/unfurl, member_joined_channel onboarding, cross-region routing
+ probe) silently drops events even though the install's stored bot token
+ may still work for other Slack endpoints (``chat.postMessage``,
+ ``chat.unfurl``). The bet is that auth.test failures genuinely correlate
+ with downstream-call failures more often than not, and that "silent drop
+ during a Slack incident" is acceptable for the recovery simplicity it
+ buys. If that bet stops holding, the fix is to expose a per-call-site
+ ``require_healthy`` switch so link_shared / unfurl can opt out.
+
+ Slack ``auth.test`` is Tier 4 (100+/min/workspace) so the per-mention cost
+ is fine even for orgs with many installs on the same workspace. Concurrent
+ mentions racing here just overwrite each other with the same verdict.
+
+ Empty return when every candidate is broken/unknown is intentional and
+ upstream code already handles it: ``_resolve_region_or_terminal_route``
+ routes events to ``ROUTE_NO_INTEGRATION`` when no candidates are present,
+ matching the behavior we'd see if the DB had no rows for this workspace.
+
+ Every failure log includes ``slack_team_id`` (workspace), ``integration_id``
+ (the broken install's PK) and ``slack_user_id`` of the mentioning user (when
+ the caller has it). That's the minimum tuple support needs to pin a customer
+ report to the exact install + token state without grepping through three
+ files of upstream context.
+ """
+ if not candidates:
+ return candidates
+
+ healthy: list[tuple[Integration, datetime]] = []
+ unknown: list[Integration] = []
+ broken: list[Integration] = []
+ for candidate in candidates:
+ state = _resolve_one_candidate_state(candidate, slack_user_id)
+ if state is None:
+ unknown.append(candidate)
+ elif state.ok:
+ healthy.append((candidate, state.checked_at))
+ else:
+ broken.append(candidate)
+
+ healthy.sort(key=lambda pair: pair[1], reverse=True)
+ result = [c for c, _ in healthy]
+ if broken or unknown:
+ # ``candidates`` is workspace-homogeneous (the resolver's DB query
+ # filters by ``integration_id=slack_team_id``), so reading the
+ # workspace ID off any one row is safe. Escalate to ``warning`` only
+ # when the filter left nothing AND we know at least one install is
+ # actually broken — a Slack 5xx that wipes every candidate into the
+ # ``unknown`` bucket would otherwise spam warning logs for every
+ # workspace during a Slack incident.
+ log = logger.warning if not result and broken else logger.info
+ log(
+ "slack_app_load_integrations_filtered",
+ slack_team_id=candidates[0].integration_id,
+ slack_user_id=slack_user_id,
+ broken_integration_ids=[c.id for c in broken],
+ unknown_integration_ids=[c.id for c in unknown],
+ healthy_integration_ids=[c.id for c, _ in healthy],
+ )
+ return result
diff --git a/products/slack_app/backend/services/slack_user_info.py b/products/slack_app/backend/services/slack_user_info.py
index 83dda9a5bc8c..612d8f83b98b 100644
--- a/products/slack_app/backend/services/slack_user_info.py
+++ b/products/slack_app/backend/services/slack_user_info.py
@@ -5,9 +5,10 @@ display names, email-to-user-id mappings, and the `is_bot` flag — and both
are rate-limited. Every lookup goes through `SlackUserProfileCache` in
Postgres so repeated requests don't burn the Slack API quota.
-The bot's own user id (from `auth_test()`) is cached separately in Redis;
-it changes only when a workspace reinstalls the app, so a 6-hour TTL is
-comfortable.
+The bot's own user id (from `auth_test()`) is folded into the shared
+per-integration auth-state cache in `slack_auth`, so a successful
+``auth.test`` doubles as proof the bot token works — no separate cache
+shape for the bot user id alone.
These helpers used to live in `api.py` alongside the HTTP-facing code,
which forced every service-layer caller (`slack_messages.py`,
@@ -19,7 +20,6 @@ keeps `api.py` focused on routes.
from datetime import timedelta
from typing import Any
-from django.core.cache import cache
from django.db.utils import DatabaseError
from django.utils import timezone
@@ -29,11 +29,16 @@ from slack_sdk.errors import SlackApiError
from posthog.models.integration import Integration, SlackIntegration
from products.slack_app.backend.models import SlackUserProfileCache
+from products.slack_app.backend.services.slack_auth import (
+ classify_slack_api_error,
+ get_cached_auth_state,
+ write_auth_state_broken,
+ write_auth_state_ok,
+)
logger = structlog.get_logger(__name__)
SLACK_USER_PROFILE_TTL = timedelta(hours=1)
-SLACK_BOT_USER_ID_CACHE_TTL_SECONDS = 60 * 60 * 6
def _format_slack_user_info_payload(
@@ -205,26 +210,54 @@ def _purge_stale_email_rows(integration: Integration, normalized_email: str, kee
logger.warning("slack_app_slack_user_cache_db_unavailable", integration_id=integration.id)
-def bot_user_id_cache_key(integration_id: int) -> str:
- return f"slack_app:bot_user_id:v1:{integration_id}"
-
-
def get_cached_bot_user_id(slack: SlackIntegration, integration: Integration) -> str | None:
- cache_key = bot_user_id_cache_key(integration.id)
- cached = cache.get(cache_key)
- if isinstance(cached, str) and cached:
- return cached
+ """Return the bot's Slack user id for ``integration``, populating the
+ shared auth-state cache as a side effect.
+
+ Terminal paths:
+
+ - **Cache hit, healthy with bot_user_id** — return it. No Slack call.
+ - **Cache hit, broken** — known dead token; return ``None`` without
+ attempting ``auth.test``. Caller treats this the same as an API failure.
+ - **Cache miss or healthy-without-bot-id** — run ``auth.test``. On success,
+ refresh the cache as ``ok=true`` carrying the bot user id. On an
+ auth-class ``SlackApiError``, mark the cache ``ok=false`` so subsequent
+ mentions skip this install for the TTL. Transient/network errors leave
+ the cache alone — a Slack 5xx shouldn't brick the workspace for 6 hours.
+ """
+ cached = get_cached_auth_state(integration.id)
+ if cached is not None:
+ if cached.ok and cached.bot_user_id is not None:
+ return cached.bot_user_id
+ if not cached.ok:
+ return None
+ # ``ok=True`` without ``bot_user_id`` is rare (auth.test returned ok
+ # without a user_id field). Fall through to ``auth.test`` and refill.
+
try:
response = slack.client.auth_test()
- bot_user_id = response.get("user_id")
+ except SlackApiError as exc:
+ error_code, token_broken = classify_slack_api_error(exc)
+ if token_broken and error_code is not None:
+ write_auth_state_broken(integration.id, error_code)
+ logger.warning(
+ "slack_app_bot_user_id_lookup_failed",
+ integration_id=integration.id,
+ error_code=error_code,
+ exc_info=True,
+ )
+ return None
except Exception:
logger.warning(
"slack_app_bot_user_id_lookup_failed",
integration_id=integration.id,
+ error_code=None,
exc_info=True,
)
return None
+
+ bot_user_id = response.get("user_id")
if not isinstance(bot_user_id, str) or not bot_user_id:
return None
- cache.set(cache_key, bot_user_id, timeout=SLACK_BOT_USER_ID_CACHE_TTL_SECONDS)
+ write_auth_state_ok(integration.id, bot_user_id)
return bot_user_id
diff --git a/products/slack_app/backend/tests/conftest.py b/products/slack_app/backend/tests/conftest.py
new file mode 100644
index 000000000000..b57421ae7a6e
--- /dev/null
+++ b/products/slack_app/backend/tests/conftest.py
@@ -0,0 +1,47 @@
+"""Shared fixtures for slack_app backend tests.
+
+The resolver's ``load_integrations`` now eagerly runs Slack ``auth.test`` on
+cache miss (see ``services/slack_auth.check_integrations_auth_and_filter``).
+Without intervention, every test that constructs an ``Integration`` row but
+doesn't patch the Slack SDK ends up making the resolver try a real Slack call
+with a fake token, which fails, drops the candidate, and breaks downstream
+routing assertions in ways that have nothing to do with what the test is
+actually checking.
+
+This conftest neutralizes that for the whole package: by default, the
+auth-state filter is a pass-through. Tests that actually want to exercise
+the filter (``test_slack_auth.py``, ``TestLoadIntegrationsAuthStateFilter``)
+opt back in by overriding the fixture or asserting against the real flow
+behind a local patch.
+"""
+
+import pytest
+from unittest.mock import patch
+
+
[email protected](autouse=True)
+def _bypass_slack_auth_filter():
+ """Pass-through the resolver's auth-state pre-filter for unit tests.
+
+ The filter's job is to drop integrations whose bot token has gone bad.
+ For tests that pre-construct an ``Integration`` with a stub
+ ``access_token`` and never exercise the OAuth round-trip, the eager
+ ``auth.test`` call would always fail and the resolver would always return
+ an empty candidate list. That's the wrong default — most tests want to
+ exercise *routing* against the integrations they created, not the
+ auth-state mechanism itself.
+
+ Tests that DO want to exercise the filter (``test_slack_auth.py``,
+ ``TestLoadIntegrationsAuthStateFilter`` in ``test_integration_resolver.py``)
+ stop this fixture from taking effect by patching at the module the
+ resolver imports from — see those files for the pattern.
+ """
+ # ``load_integrations`` inline-imports ``check_integrations_auth_and_filter``
+ # from ``slack_auth``, so we patch at the source module rather than at the
+ # resolver's import site (the import re-runs on every call and would miss
+ # an import-site patch).
+ with patch(
+ "products.slack_app.backend.services.slack_auth.check_integrations_auth_and_filter",
+ side_effect=lambda candidates, **_: candidates,
+ ):
+ yield
diff --git a/products/slack_app/backend/tests/test_channel_onboarding_routing.py b/products/slack_app/backend/tests/test_channel_onboarding_routing.py
index a097987a4830..88f01e0a63b5 100644
--- a/products/slack_app/backend/tests/test_channel_onboarding_routing.py
+++ b/products/slack_app/backend/tests/test_channel_onboarding_routing.py
@@ -16,7 +16,7 @@ from products.slack_app.backend.api import (
_channel_onboarding_cache_key,
route_posthog_code_event_to_relevant_region,
)
-from products.slack_app.backend.services.slack_user_info import bot_user_id_cache_key
+from products.slack_app.backend.services.slack_auth import get_cached_auth_state
@override_settings(DEBUG=False, CLOUD_DEPLOYMENT="US")
@@ -46,6 +46,17 @@ class TestMemberJoinedChannelRouting(TestCase):
config={"scope": ",".join(sorted(REQUIRED_SLACK_SCOPES))},
sensitive_config={"access_token": "xoxb-test"},
)
+ # ``load_integrations`` now eagerly calls ``auth.test`` on cache miss.
+ # These tests patch ``products.slack_app.backend.api.SlackIntegration``
+ # but the resolver imports SlackIntegration from
+ # ``posthog.models.integration`` directly, so the patch doesn't catch
+ # the resolver's call. Pre-populate the cache with ``ok=true`` so the
+ # resolver short-circuits; ``bot_user_id=None`` keeps
+ # ``get_cached_bot_user_id`` falling through to the (mocked)
+ # ``auth.test`` call the onboarding flow expects.
+ from products.slack_app.backend.services.slack_auth import write_auth_state_ok
+
+ write_auth_state_ok(self.integration.id, bot_user_id=None)
def _request(self):
return self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com")
@@ -165,4 +176,7 @@ class TestMemberJoinedChannelRouting(TestCase):
route_posthog_code_event_to_relevant_region(self._request(), self._event(channel="C_OTHER"), self.SLACK_TEAM_ID)
assert instance.client.auth_test.call_count == 1
- assert cache.get(bot_user_id_cache_key(self.integration.id)) == self.BOT_USER_ID
+ cached_state = get_cached_auth_state(self.integration.id)
+ assert cached_state is not None
+ assert cached_state.ok is True
+ assert cached_state.bot_user_id == self.BOT_USER_ID
diff --git a/products/slack_app/backend/tests/test_get_slack_email_for_user.py b/products/slack_app/backend/tests/test_get_slack_email_for_user.py
index d4fc240884fa..ee99cbaf2cc3 100644
--- a/products/slack_app/backend/tests/test_get_slack_email_for_user.py
+++ b/products/slack_app/backend/tests/test_get_slack_email_for_user.py
@@ -137,3 +137,85 @@ class TestGetSlackEmailForUser:
# log filter for "needs reconnect" cleanly excludes them.
assert all("'error_code': None" in r.message for r in failed)
assert all("'token_broken': False" in r.message for r in failed)
+
+
+class TestAuthStateSideEffects:
+ """The resolver pre-filter (``load_integrations``) consumes the cached
+ verdict that these calls write. Success path → ``ok=true``; auth-class
+ error → ``ok=false``; transient/non-auth error → no write so a Slack
+ outage doesn't brick the workspace."""
+
+ @pytest.fixture(autouse=True)
+ def _clear_cache(self):
+ from django.core.cache import cache
+
+ cache.clear()
+ yield
+ cache.clear()
+
+ @patch("posthog.models.integration.WebClient")
+ def test_success_does_not_touch_auth_state(self, mock_webclient_class, integration):
+ # The positive cache verdict is owned by the resolver's eager
+ # ``auth.test`` layer. A successful ``users.info`` can hit the DB cache
+ # (``SlackUserProfileCache``) without touching Slack at all, so it
+ # proves nothing about the live token — letting it refresh the cache
+ # would defeat the negative-cache mechanism the PR exists to provide.
+ from products.slack_app.backend.services.slack_auth import get_cached_auth_state
+
+ mock_client = MagicMock()
+ mock_webclient_class.return_value = mock_client
+ mock_client.users_info.return_value = _make_slack_response(
+ {"ok": True, "user": {"id": "U1", "profile": {"email": "[email protected]"}}}
+ )
+
+ get_slack_email_for_user(integration, "U1")
+
+ assert get_cached_auth_state(integration.id) is None
+
+ @pytest.mark.parametrize(
+ "error_code",
+ ["token_revoked", "invalid_auth", "not_authed", "account_inactive", "token_expired"],
+ )
+ @patch("posthog.models.integration.WebClient")
+ def test_auth_class_error_writes_broken_state(self, mock_webclient_class, integration, error_code):
+ from products.slack_app.backend.services.slack_auth import get_cached_auth_state
+
+ mock_client = MagicMock()
+ mock_webclient_class.return_value = mock_client
+ mock_client.users_info.side_effect = _slack_api_error(error_code)
+
+ get_slack_email_for_user(integration, "U1")
+
+ state = get_cached_auth_state(integration.id)
+ assert state is not None
+ assert state.ok is False
+ assert state.error_code == error_code
+
+ @patch("posthog.models.integration.WebClient")
+ def test_non_auth_slack_error_does_not_touch_cache(self, mock_webclient_class, integration):
+ # ``user_not_found`` says nothing about token validity, so leaving the
+ # cache untouched keeps the resolver from demoting a healthy install
+ # based on an unrelated mention failing.
+ from products.slack_app.backend.services.slack_auth import get_cached_auth_state
+
+ mock_client = MagicMock()
+ mock_webclient_class.return_value = mock_client
+ mock_client.users_info.side_effect = _slack_api_error("user_not_found")
+
+ get_slack_email_for_user(integration, "U1")
+
+ assert get_cached_auth_state(integration.id) is None
+
+ @patch("posthog.models.integration.WebClient")
+ def test_transient_exception_does_not_touch_cache(self, mock_webclient_class, integration):
+ # Network blips and Slack 5xx must not brick the workspace by writing
+ # a negative verdict for the full TTL.
+ from products.slack_app.backend.services.slack_auth import get_cached_auth_state
+
+ mock_client = MagicMock()
+ mock_webclient_class.return_value = mock_client
+ mock_client.users_info.side_effect = RuntimeError("boom")
+
+ get_slack_email_for_user(integration, "U1")
+
+ assert get_cached_auth_state(integration.id) is None
diff --git a/products/slack_app/backend/tests/test_integration_resolver.py b/products/slack_app/backend/tests/test_integration_resolver.py
index 932c17e2eb9a..1dd1c2961e6b 100644
--- a/products/slack_app/backend/tests/test_integration_resolver.py
+++ b/products/slack_app/backend/tests/test_integration_resolver.py
@@ -17,6 +17,11 @@ SLACK_USER = "U001"
class TestResolveIntegration:
@pytest.fixture(autouse=True)
def setup(self, db):
+ from django.core.cache import cache
+
+ from products.slack_app.backend.services.slack_auth import write_auth_state_ok
+
+ cache.clear()
self.organization = Organization.objects.create(name="Org")
self.team_a = Team.objects.create(organization=self.organization, name="A")
self.team_b = Team.objects.create(organization=self.organization, name="B")
@@ -37,6 +42,17 @@ class TestResolveIntegration:
integration_id="T_OTHER",
sensitive_config={"access_token": "xoxb-other"},
)
+ # These tests assert routing precedence (thread > user_default > etc),
+ # not auth-state filtering. Pre-seed every WORKSPACE-scoped integration
+ # as healthy so ``load_integrations``' eager ``auth.test`` short-circuits
+ # on cache hit and the precedence ladder is exercised against a stable
+ # full candidate list. ``integration_other_workspace`` is intentionally
+ # not seeded — it has a different ``integration_id`` and never enters
+ # the candidate set.
+ for integration in (self.integration_a, self.integration_b, self.integration_c):
+ write_auth_state_ok(integration.id, bot_user_id="U_BOT")
+ yield
+ cache.clear()
def _mk_integration(self, team: Team) -> Integration:
return Integration.objects.create(
@@ -415,3 +431,237 @@ class TestResolveIntegration:
assert result.source == "sole_candidate"
assert result.integration == self.integration_a
+
+
+class TestLoadIntegrationsAuthStateFilter:
+ """Covers the eager auth-check + cache-driven ordering in ``load_integrations``.
+
+ Scenario mirrors a real customer case: an org has three Slack rows for the
+ same workspace, one of them has a revoked bot token, the resolver used to
+ pick that one as ``candidates[0]`` and silently broke every mention. The
+ consolidated ``check_integrations_auth_and_filter`` ranks the healthy ones
+ first so the dead probe never makes it to index 0.
+ """
+
+ @pytest.fixture(autouse=True)
+ def _bypass_slack_auth_filter(self):
+ """Override the conftest's auto-bypass so this class exercises the real
+ filter — that's the whole point of the class."""
+ yield
+
+ @pytest.fixture(autouse=True)
+ def setup(self, db):
+ from unittest.mock import MagicMock, patch
+
+ from django.core.cache import cache
+
+ cache.clear()
+ self.organization = Organization.objects.create(name="Org")
+ self.team_old = Team.objects.create(organization=self.organization, name="Old")
+ self.team_mid = Team.objects.create(organization=self.organization, name="Mid")
+ self.team_new = Team.objects.create(organization=self.organization, name="New")
+ # Order rows by creation so the PK ascending order matches the team
+ # names; downstream assertions rely on this implicit ordering.
+ self.integration_old = self._mk_integration(self.team_old)
+ self.integration_mid = self._mk_integration(self.team_mid)
+ self.integration_new = self._mk_integration(self.team_new)
+ # Mock ``auth.test`` to a healthy response by default; individual tests
+ # override ``side_effect`` / ``return_value`` to simulate the failure
+ # they care about. Without the mock, ``load_integrations`` would try
+ # to hit the real Slack API every time the cache is cold. Context
+ # manager so a failure inside ``yield`` still cleans up (manual
+ # ``start()/stop()`` would leak the patch into sibling tests).
+ with patch("posthog.models.integration.WebClient") as mock_webclient_class:
+ mock_client = MagicMock()
+ mock_webclient_class.return_value = mock_client
+ mock_client.auth_test.return_value = {"user_id": "U_BOT"}
+ self.mock_auth_test = mock_client.auth_test
+ yield
+ cache.clear()
+
+ def _mk_integration(self, team: Team) -> Integration:
+ return Integration.objects.create(
+ team=team,
+ kind="slack",
+ integration_id=WORKSPACE,
+ sensitive_config={"access_token": "xoxb"},
+ )
+
+ def _candidate_ids(self, result_candidates: list[Integration]) -> list[int]:
+ return [c.id for c in result_candidates]
+
+ def test_cold_cache_runs_auth_test_per_candidate_and_caches_verdict(self):
+ from products.slack_app.backend.services.slack_auth import get_cached_auth_state
+
+ result = load_integrations(slack_team_id=WORKSPACE, kinds=["slack"], slack_user_id=SLACK_USER)
+
+ # auth.test fired once per candidate — eager populate is the point of
+ # the new design.
+ assert self.mock_auth_test.call_count == 3
+ # All three are returned (just possibly in different timestamp order).
+ assert {c.id for c in result.candidates} == {
+ self.integration_old.id,
+ self.integration_mid.id,
+ self.integration_new.id,
+ }
+ # Cache now carries a healthy verdict for each, including the bot user id.
+ for integration in (self.integration_old, self.integration_mid, self.integration_new):
+ state = get_cached_auth_state(integration.id)
+ assert state is not None
+ assert state.ok is True
+ assert state.bot_user_id == "U_BOT"
+
+ def test_warm_cache_skips_auth_test(self):
+ from products.slack_app.backend.services.slack_auth import write_auth_state_ok
+
+ write_auth_state_ok(self.integration_old.id, bot_user_id="U_BOT")
+ write_auth_state_ok(self.integration_mid.id, bot_user_id="U_BOT")
+ write_auth_state_ok(self.integration_new.id, bot_user_id="U_BOT")
+
+ load_integrations(slack_team_id=WORKSPACE, kinds=["slack"], slack_user_id=SLACK_USER)
+
+ assert self.mock_auth_test.call_count == 0
+
+ def test_invalid_auth_drops_install_from_candidates(self):
+ from slack_sdk.errors import SlackApiError
+
+ # ``old`` install fails auth.test with invalid_auth — exactly the
+ # production case for the original ticket. ``mid`` and ``new`` succeed
+ # so the resolver should keep them and drop ``old`` entirely (not
+ # demote to the back, otherwise the resolver's precedence ladder would
+ # still pin a stale thread mapping or user-default to it).
+ healthy_response = {"user_id": "U_BOT"}
+ self.mock_auth_test.side_effect = [
+ SlackApiError("invalid_auth", response={"ok": False, "error": "invalid_auth"}),
+ healthy_response,
+ healthy_response,
+ ]
+
+ result = load_integrations(slack_team_id=WORKSPACE, kinds=["slack"], slack_user_id=SLACK_USER)
+
+ ids = self._candidate_ids(result.candidates)
+ assert self.integration_old.id not in ids
+ assert set(ids) == {self.integration_mid.id, self.integration_new.id}
+
+ def test_freshest_healthy_wins_over_warm_older_entry(self):
+ # ``new`` was confirmed healthy most recently; ``old`` and ``mid``
+ # were checked an hour ago. Matches the "customer just reconnected
+ # one of three installs" scenario.
+ from datetime import timedelta
+
+ from django.core.cache import cache as django_cache
+ from django.utils import timezone
+
+ from products.slack_app.backend.services.slack_auth import (
+ SLACK_AUTH_STATE_CACHE_TTL_SECONDS,
+ SlackIntegrationAuthState,
+ _cache_key,
+ )
+
+ an_hour_ago = timezone.now() - timedelta(hours=1)
+ for integration in (self.integration_old, self.integration_mid):
+ django_cache.set(
+ _cache_key(integration.id),
+ SlackIntegrationAuthState(ok=True, bot_user_id="U_BOT", error_code=None, checked_at=an_hour_ago),
+ timeout=SLACK_AUTH_STATE_CACHE_TTL_SECONDS,
+ )
+ django_cache.set(
+ _cache_key(self.integration_new.id),
+ SlackIntegrationAuthState(ok=True, bot_user_id="U_BOT", error_code=None, checked_at=timezone.now()),
+ timeout=SLACK_AUTH_STATE_CACHE_TTL_SECONDS,
+ )
+
+ result = load_integrations(slack_team_id=WORKSPACE, kinds=["slack"], slack_user_id=SLACK_USER)
+
+ assert result.candidates[0].id == self.integration_new.id
+ assert self.mock_auth_test.call_count == 0 # all cached, no API calls
+
+ def test_all_broken_returns_empty(self):
+ # When every candidate is cached as broken, return an empty list.
+ # Upstream code (``_resolve_region_or_terminal_route``) treats an empty
+ # candidate set the same way it'd handle a workspace with no rows at
+ # all — falls through to ``ROUTE_NO_INTEGRATION``. Recovery paths:
+ # the 6h TTL expires, OAuth reconnect invalidates the cache, or a
+ # subsequent ``auth.test`` succeeds.
+ from products.slack_app.backend.services.slack_auth import write_auth_state_broken
+
+ write_auth_state_broken(self.integration_old.id, error_code="invalid_auth")
+ write_auth_state_broken(self.integration_mid.id, error_code="invalid_auth")
+ write_auth_state_broken(self.integration_new.id, error_code="invalid_auth")
+
+ result = load_integrations(slack_team_id=WORKSPACE, kinds=["slack"], slack_user_id=SLACK_USER)
+
+ assert result.candidates == []
+
+ def test_transient_auth_test_error_drops_candidate(self):
+ # A transient ``auth.test`` failure (Slack 5xx, network blip) leaves
+ # the cache untouched but still drops the candidate from THIS
+ # invocation's result — we have no proof the token works, so we don't
+ # ship the user a probably-broken probe. The next mention retries.
+ from products.slack_app.backend.services.slack_auth import get_cached_auth_state
+
+ self.mock_auth_test.side_effect = RuntimeError("boom")
+
+ result = load_integrations(slack_team_id=WORKSPACE, kinds=["slack"], slack_user_id=SLACK_USER)
+
+ assert result.candidates == []
+ # Cache untouched: next mention retries instead of inheriting a stale
+ # negative verdict.
+ assert get_cached_auth_state(self.integration_old.id) is None
+
+ def test_broken_thread_mapping_falls_through_to_healthy_sibling(self):
+ # Reproduces the production case: a thread mapping pins routing to an
+ # install whose token has since been revoked. With ``drop`` semantics
+ # the resolver's "out-of-set" handling in ``resolve_from_candidates``
+ # walks past the dead mapping rather than honoring a target the bot
+ # can't actually reach.
+ #
+ # Setup deliberately leaves only ONE healthy sibling (``new``): ``old``
+ # is broken and dropped, ``mid`` is also marked broken so the auth
+ # filter strips it too. That collapses the candidate list to ``[new]``
+ # and the resolver falls through past the dead thread mapping to
+ # ``sole_candidate``. Without this constraint the assertion below
+ # would have to accept ``needs_picker`` with an empty ``integration``,
+ # which can pass vacuously if the resolver silently breaks.
+ from products.slack_app.backend.models import SlackThreadTaskMapping
+ from products.slack_app.backend.services.slack_auth import write_auth_state_broken, write_auth_state_ok
+
+ write_auth_state_broken(self.integration_old.id, error_code="invalid_auth")
+ write_auth_state_broken(self.integration_mid.id, error_code="invalid_auth")
+ write_auth_state_ok(self.integration_new.id, bot_user_id="U_NEW_BOT")
+
+ # Thread mapping points at the broken ``old`` install. ``team`` /
+ # ``task`` / ``task_run`` aren't relevant to this test's assertions —
+ # we only need a mapping row that resolves the mapped integration.
+ # ``Task`` / ``TaskRun`` are looked up via the app registry to dodge
+ # the circular-import that fires when ``products.tasks`` is imported
+ # at module top from this products.slack_app test file.
+ Task = apps.get_model("tasks", "Task")
+ TaskRun = apps.get_model("tasks", "TaskRun")
+ task = Task.objects.create(team=self.team_old, title="t")
+ task_run = TaskRun.objects.create(team=self.team_old, task=task)
+ SlackThreadTaskMapping.objects.create(
+ team=self.team_old,
+ integration=self.integration_old,
+ slack_workspace_id=WORKSPACE,
+ channel="C1",
+ thread_ts="123.456",
+ task=task,
+ task_run=task_run,
+ mentioning_slack_user_id=SLACK_USER,
+ )
+
+ result = load_integrations(
+ slack_team_id=WORKSPACE,
+ kinds=["slack"],
+ slack_user_id=SLACK_USER,
+ channel="C1",
+ thread_ts="123.456",
+ )
+
+ # The healthy sibling is the one the resolver routes to. Strong
+ # assertions (instead of ``!= integration_old``) so a regression that
+ # returns ``None`` or picks the wrong install fails loudly.
+ assert {c.id for c in result.candidates} == {self.integration_new.id}
+ assert result.integration == self.integration_new
+ assert result.source == "sole_candidate"
diff --git a/products/slack_app/backend/tests/test_slack_auth.py b/products/slack_app/backend/tests/test_slack_auth.py
new file mode 100644
index 000000000000..94f169c26d4b
--- /dev/null
+++ b/products/slack_app/backend/tests/test_slack_auth.py
@@ -0,0 +1,128 @@
+from datetime import timedelta
+
+import pytest
+
+from django.core.cache import cache
+from django.utils import timezone
+
+from products.slack_app.backend.services.slack_auth import (
+ SLACK_AUTH_STATE_CACHE_TTL_SECONDS,
+ get_cached_auth_state,
+ invalidate_auth_state,
+ write_auth_state_broken,
+ write_auth_state_ok,
+)
+
+
[email protected](autouse=True)
+def _clear_cache():
+ cache.clear()
+ yield
+ cache.clear()
+
+
+class TestSlackAuthState:
+ def test_get_returns_none_on_miss(self):
+ assert get_cached_auth_state(1) is None
+
+ def test_write_ok_round_trip(self):
+ write_auth_state_ok(42, bot_user_id="U_BOT")
+
+ state = get_cached_auth_state(42)
+ assert state is not None
+ assert state.ok is True
+ assert state.bot_user_id == "U_BOT"
+ assert state.error_code is None
+ # ``checked_at`` is "now-ish"; assert a generous window so the test
+ # isn't flaky on slow runners.
+ assert abs((timezone.now() - state.checked_at).total_seconds()) < 5
+
+ def test_write_ok_without_bot_user_id_lets_callers_request_one_later(self):
+ # ``get_slack_email_for_user`` writes ``ok=true`` from a successful
+ # ``users.info`` (which doesn't expose the bot id). ``bot_user_id``
+ # stays ``None`` so a later ``get_cached_bot_user_id`` knows to fall
+ # through to ``auth.test`` instead of returning ``None``.
+ write_auth_state_ok(7, bot_user_id=None)
+
+ state = get_cached_auth_state(7)
+ assert state is not None
+ assert state.ok is True
+ assert state.bot_user_id is None
+
+ def test_write_broken_round_trip(self):
+ write_auth_state_broken(99, error_code="invalid_auth")
+
+ state = get_cached_auth_state(99)
+ assert state is not None
+ assert state.ok is False
+ assert state.error_code == "invalid_auth"
+ assert state.bot_user_id is None
+
+ def test_write_broken_then_ok_overrides_to_healthy(self):
+ # OAuth reconnect path: previous token was revoked → cached as broken,
+ # next successful call flips the cache back. The negative verdict
+ # must not stick around once a healthy call lands.
+ write_auth_state_broken(5, error_code="token_revoked")
+ write_auth_state_ok(5, bot_user_id="U_FRESH")
+
+ state = get_cached_auth_state(5)
+ assert state is not None
+ assert state.ok is True
+ assert state.bot_user_id == "U_FRESH"
+ assert state.error_code is None
+
+ def test_write_ok_then_broken_overrides_to_broken(self):
+ # Token rotation outside our control: was healthy, just got revoked.
+ # Cache flips to broken so the resolver demotes the install.
+ write_auth_state_ok(5, bot_user_id="U_OLD")
+ write_auth_state_broken(5, error_code="invalid_auth")
+
+ state = get_cached_auth_state(5)
+ assert state is not None
+ assert state.ok is False
+ assert state.error_code == "invalid_auth"
+
+ def test_invalidate_drops_existing_entry(self):
+ write_auth_state_ok(11, bot_user_id="U_BOT")
+ assert get_cached_auth_state(11) is not None
+
+ invalidate_auth_state(11)
+
+ assert get_cached_auth_state(11) is None
+
+ def test_invalidate_is_safe_on_miss(self):
+ # OAuth callback runs on every reconnect; it shouldn't blow up if
+ # nothing was cached yet.
+ invalidate_auth_state(404)
+ assert get_cached_auth_state(404) is None
+
+ def test_keys_are_per_integration(self):
+ write_auth_state_ok(1, bot_user_id="U_ONE")
+ write_auth_state_broken(2, error_code="invalid_auth")
+
+ one = get_cached_auth_state(1)
+ two = get_cached_auth_state(2)
+ assert one is not None and one.ok is True and one.bot_user_id == "U_ONE"
+ assert two is not None and two.ok is False and two.error_code == "invalid_auth"
+
+ def test_garbage_in_cache_is_ignored(self):
+ # If a future code version writes a different shape (or older code
+ # wrote a dict literal here), we should treat it as a cache miss
+ # rather than crash the resolver.
+ from products.slack_app.backend.services.slack_auth import _cache_key
+
+ cache.set(_cache_key(77), {"unexpected": "shape"}, timeout=60)
+
+ assert get_cached_auth_state(77) is None
+
+ def test_ttl_is_set(self):
+ # Sanity: we don't accidentally write entries with no TTL.
+ write_auth_state_ok(8, bot_user_id="U_BOT")
+
+ from products.slack_app.backend.services.slack_auth import _cache_key
+
+ ttl = cache.ttl(_cache_key(8)) if hasattr(cache, "ttl") else None
+ if ttl is not None:
+ # Django cache backends that expose ``.ttl()`` should report a
+ # value close to the configured constant.
+ assert ttl <= timedelta(seconds=SLACK_AUTH_STATE_CACHE_TTL_SECONDS).total_seconds()