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.

32.7 KB
Raw Blame
from unittest.mock import MagicMock, patch

import pytest
from fastapi import HTTPException

from llm_gateway.baseten import BASETEN_MODELS
from llm_gateway.cloudflare import CLOUDFLARE_ALLOWED_MODELS
from llm_gateway.flags import GLM_MODAL_FLAG
from llm_gateway.inference_routing import is_inference_routed_model
from llm_gateway.modal import is_modal_served_model
from llm_gateway.products.config import (
    ALLOWED_PRODUCTS,
    BEDROCK_MODELS,
    MODEL_ACCESS_FLAGS,
    POSTHOG_AI_DEV_APP_ID,
    POSTHOG_AI_EU_APP_ID,
    POSTHOG_AI_US_APP_ID,
    POSTHOG_CODE_DEV_APP_ID,
    POSTHOG_CODE_EU_APP_ID,
    POSTHOG_CODE_RETIRED_MESSAGE,
    POSTHOG_CODE_US_APP_ID,
    PRODUCT_ALIASES,
    PRODUCTS,
    SIGNALS_DEV_APP_ID,
    TWIG_EU_APP_ID,
    TWIG_US_APP_ID,
    WIZARD_EU_APP_ID,
    WIZARD_US_APP_ID,
    check_free_tier_model_access,
    get_product_config,
    get_required_model_flag,
    resolve_product_alias,
    validate_product,
)
from llm_gateway.products.config import (
    check_product_access as _check_product_access,
)


def check_product_access(
    product: str,
    auth_method: str,
    application_id: str | None,
    model: str | None,
    provider: str | None = None,
    scopes: list[str] | None = None,
) -> tuple[bool, str | None]:
    return _check_product_access(
        product,
        auth_method,
        application_id,
        model,
        provider,
        scopes if scopes is not None else ["internal_run:read"],
    )


class TestGetProductConfig:
    def test_returns_config_for_known_product(self):
        config = get_product_config("llm_gateway")
        assert config is not None
        assert config.allow_api_keys is True

    def test_returns_none_for_unknown_product(self):
        config = get_product_config("unknown_product")
        assert config is None


class TestCheckProductAccess:
    @pytest.mark.parametrize(
        "product,auth_method,application_id,model,expected_allowed,expected_error_contains",
        [
            # llm_gateway allows API keys but rejects OAuth (no app IDs configured)
            ("llm_gateway", "personal_api_key", None, "claude-3-opus", True, None),
            ("llm_gateway", "oauth_access_token", "any-app-id", "gpt-4o", False, "not authorized"),
            ("llm_gateway", "personal_api_key", None, None, True, None),
            (
                "llm_gateway",
                "personal_api_key",
                None,
                "deepseek-ai/deepseek-v4-flash-0731",
                False,
                "not allowed",
            ),
            (
                "review_hog",
                "personal_api_key",
                None,
                "deepseek-ai/deepseek-v4-flash-0731",
                True,
                None,
            ),
            ("llm_gateway", "personal_api_key", None, "zai-org/glm-5.3", False, "not allowed"),
            ("review_hog", "personal_api_key", None, "zai-org/glm-5.3", True, None),
            ("llm_gateway", "personal_api_key", None, "zai-org/glm-5.3-flash", False, "not allowed"),
            ("review_hog", "personal_api_key", None, "zai-org/glm-5.3-flash", True, None),
            (
                "posthog_code",
                "oauth_access_token",
                POSTHOG_CODE_US_APP_ID,
                "zai-org/glm-5.3",
                False,
                "no longer runs on this gateway",
            ),
            # ci allows API keys with any model (used by e2e test runs); OAuth rejected (no app IDs)
            ("ci", "personal_api_key", None, "claude-3-opus", True, None),
            ("ci", "oauth_access_token", "any-app-id", "gpt-4o", False, "not authorized"),
            ("posthog_code", "personal_api_key", None, None, False, "no longer runs on this gateway"),
            ("posthog_code", "oauth_access_token", "invalid-app-id", None, False, "no longer runs on this gateway"),
            (
                "posthog_code",
                "oauth_access_token",
                POSTHOG_CODE_US_APP_ID,
                None,
                False,
                "no longer runs on this gateway",
            ),
            (
                "posthog_code",
                "oauth_access_token",
                POSTHOG_CODE_EU_APP_ID,
                None,
                False,
                "no longer runs on this gateway",
            ),
            (
                "posthog_code",
                "oauth_access_token",
                POSTHOG_CODE_US_APP_ID,
                "deepseek-ai/deepseek-v4-flash-0731",
                False,
                "no longer runs on this gateway",
            ),
            # wizard is retired here: every auth method, including its own apps, gets the upgrade path
            ("wizard", "personal_api_key", None, "claude-3-opus", False, "npx @posthog/wizard@latest"),
            ("wizard", "oauth_access_token", "invalid-app-id", None, False, "npx @posthog/wizard@latest"),
            ("wizard", "oauth_access_token", WIZARD_US_APP_ID, None, False, "npx @posthog/wizard@latest"),
            ("wizard", "oauth_access_token", WIZARD_EU_APP_ID, None, False, "npx @posthog/wizard@latest"),
            # django allows API keys with any model; OAuth rejected (no app IDs configured)
            ("django", "personal_api_key", None, "gpt-4.1-mini", True, None),
            ("django", "personal_api_key", None, "claude-3-opus", True, None),
            ("django", "oauth_access_token", "any-app-id", "gpt-4.1-mini", False, "not authorized"),
            # Custom image scans accept only server-minted OAuth credentials.
            ("custom_image_scans", "personal_api_key", None, "@cf/zai-org/glm-5.2", False, "requires OAuth"),
            (
                "custom_image_scans",
                "oauth_access_token",
                POSTHOG_CODE_US_APP_ID,
                "@cf/zai-org/glm-5.2",
                True,
                None,
            ),
            # The batch trace summarization pipeline lands on this gateway when AI_GATEWAY_URL
            # is unset. Its model missing from this list turns that fallback into a 403 on every
            # call, which silently starves the clusters feature of summaries.
            ("llma_summarization", "personal_api_key", None, "gpt-5-nano", True, None),
            ("llma_summarization", "personal_api_key", None, "gpt-5-mini", True, None),
            ("llma_summarization", "personal_api_key", None, "gpt-4.1-nano", True, None),
            ("llma_summarization", "personal_api_key", None, "gpt-4o", False, "not allowed"),
            # llma_translation allows API keys but only gpt-4.1-mini; OAuth rejected (no app IDs configured)
            ("llma_translation", "personal_api_key", None, "gpt-4.1-mini", True, None),
            ("llma_translation", "personal_api_key", None, "claude-3-opus", False, "not allowed"),
            ("llma_translation", "oauth_access_token", "any-app-id", "gpt-4.1-mini", False, "not authorized"),
            # signals allows API keys (shared gateway key) with any model, and OAuth only from
            # the dedicated Signals app — a posthog_code (Desktop) token must not reach it
            ("signals", "personal_api_key", None, "claude-haiku-4-5", True, None),
            ("signals", "personal_api_key", None, "claude-sonnet-4-5", True, None),
            ("signals", "personal_api_key", None, "claude-3-opus", True, None),
            ("signals", "oauth_access_token", "any-app-id", "claude-haiku-4-5", False, "not authorized"),
            ("signals", "oauth_access_token", SIGNALS_DEV_APP_ID, "claude-haiku-4-5", True, None),
            ("signals", "oauth_access_token", POSTHOG_CODE_US_APP_ID, "claude-haiku-4-5", False, "not authorized"),
            ("signals", "oauth_access_token", POSTHOG_CODE_EU_APP_ID, "claude-sonnet-4-5", False, "not authorized"),
            # conversations: utility prompts (API key) and support-reply sandbox (array OAuth app)
            ("conversations", "personal_api_key", None, "claude-haiku-4-5", True, None),
            ("conversations", "personal_api_key", None, "claude-sonnet-4-6", True, None),
            ("conversations", "personal_api_key", None, "claude-sonnet-5", True, None),
            ("conversations", "personal_api_key", None, "claude-opus-4-8", False, "not allowed"),
            ("conversations", "oauth_access_token", "any-app-id", "claude-sonnet-5", False, "not authorized"),
            ("conversations", "oauth_access_token", POSTHOG_CODE_US_APP_ID, "claude-sonnet-5", True, None),
            ("conversations", "oauth_access_token", POSTHOG_CODE_EU_APP_ID, "claude-sonnet-4-6", True, None),
            # posthog_ai allows API keys with any model and OAuth from the PostHog AI app.
            ("posthog_ai", "personal_api_key", None, "claude-sonnet-4-5", True, None),
            ("posthog_ai", "personal_api_key", None, "gpt-5.3-codex", True, None),
            ("posthog_ai", "oauth_access_token", "any-app-id", "claude-sonnet-4-5", False, "not authorized"),
            ("posthog_ai", "oauth_access_token", POSTHOG_AI_US_APP_ID, "claude-sonnet-4-5", True, None),
            ("posthog_ai", "oauth_access_token", POSTHOG_AI_EU_APP_ID, "gpt-5.3-codex", True, None),
            ("posthog_ai", "oauth_access_token", POSTHOG_AI_DEV_APP_ID, "claude-3-opus", True, None),
            # changelog_bot: shared-key auth, models pinned to the openai/-prefixed ids the curator
            # sends verbatim. Exact-match only: bare ids (no prefix) AND variant suffixes must be
            # rejected, or the cost pin doesn't hold.
            ("changelog_bot", "personal_api_key", None, "openai/gpt-5.6-terra", True, None),
            ("changelog_bot", "personal_api_key", None, "openai/gpt-5.6-sol", True, None),
            ("changelog_bot", "personal_api_key", None, "gpt-5.6-terra", False, "not allowed"),
            ("changelog_bot", "personal_api_key", None, "openai/gpt-5-mini", False, "not allowed"),
            # exact_model_match: a pricier "-pro" variant of a pinned id must NOT slip through startswith.
            ("changelog_bot", "personal_api_key", None, "openai/gpt-5.6-terra-pro", False, "not allowed"),
            ("changelog_bot", "personal_api_key", None, "openai/gpt-5.6-sol-pro", False, "not allowed"),
            ("changelog_bot", "oauth_access_token", "any-app-id", "openai/gpt-5.6-terra", False, "not authorized"),
            # review_hog: shared-key auth, models pinned to the review pipeline's constants —
            # the opus-5 outcome judge and the experiment's Codex arm must stay allowed, and
            # anything off the pin list is rejected.
            ("review_hog", "personal_api_key", None, "claude-opus-5", True, None),
            ("review_hog", "personal_api_key", None, "gpt-5.6-sol", True, None),
            ("review_hog", "personal_api_key", None, "claude-3-opus", False, "not allowed"),
            # unknown product
            ("unknown", "personal_api_key", None, None, False, "Unknown product"),
        ],
    )
    def test_access_combinations(
        self,
        product: str,
        auth_method: str,
        application_id: str | None,
        model: str | None,
        expected_allowed: bool,
        expected_error_contains: str | None,
    ):
        allowed, error = check_product_access(product, auth_method, application_id, model)
        assert allowed == expected_allowed
        if expected_error_contains:
            assert error is not None
            assert expected_error_contains in error

    @pytest.mark.parametrize(
        "model", ["deepseek-ai/deepseek-v4-flash-0731", "zai-org/glm-5.3", "zai-org/glm-5.3-flash"]
    )
    def test_slack_app_rejects_restricted_models_despite_shared_allowlist(self, model: str):
        allowed, error = check_product_access("slack_app", "oauth_access_token", POSTHOG_CODE_US_APP_ID, model)
        assert allowed is False
        assert error is not None
        assert "not allowed" in error

    @pytest.mark.parametrize(
        "model", [" deepseek-ai/deepseek-v4-flash-0731 ", " zai-org/glm-5.3 ", " zai-org/glm-5.3-flash "]
    )
    def test_whitespace_cannot_bypass_restricted_model_products(self, model: str):
        allowed, error = check_product_access("llm_gateway", "personal_api_key", None, model)
        assert allowed is False
        assert error is not None
        assert "not allowed" in error

    @pytest.mark.parametrize(
        "model",
        [
            "claude-opus-4-5-20260101",
            "claude-sonnet-4-5-20250929",
            "claude-haiku-4-5-20251001-v2",
            "gpt-5.2-turbo",
        ],
    )
    def test_background_agents_allows_dated_variants_via_prefix_matching(self, model: str):
        allowed, error = check_product_access(
            "background_agents",
            "oauth_access_token",
            POSTHOG_CODE_US_APP_ID,
            model,
            scopes=["llm_gateway:read", "internal_run:read"],
        )
        assert allowed is True
        assert error is None

    @pytest.mark.parametrize(
        "model",
        [
            "Claude-Opus-4-5",
            "CLAUDE-SONNET-4-5",
            "GPT-5.2",
            "Claude-Haiku-4-5",
        ],
    )
    def test_model_matching_is_case_insensitive(self, model: str):
        allowed, error = check_product_access(
            "background_agents",
            "oauth_access_token",
            POSTHOG_CODE_US_APP_ID,
            model,
            scopes=["llm_gateway:read", "internal_run:read"],
        )
        assert allowed is True
        assert error is None

    @pytest.mark.parametrize("product", ["posthog_code", "twig", "array"])
    @pytest.mark.parametrize(
        "auth_method,application_id",
        [
            ("oauth_access_token", POSTHOG_CODE_US_APP_ID),
            ("oauth_access_token", POSTHOG_CODE_EU_APP_ID),
            ("personal_api_key", None),
        ],
    )
    def test_posthog_code_and_its_aliases_are_retired(self, product: str, auth_method: str, application_id: str | None):
        allowed, error = check_product_access(product, auth_method, application_id, "claude-sonnet-5", scopes=["*"])
        assert allowed is False
        assert error == POSTHOG_CODE_RETIRED_MESSAGE

    @pytest.mark.parametrize(
        "model",
        [
            "claude-opus-4-5",
            "claude-opus-4-6",
            "claude-opus-4-7",
            "claude-opus-4-8",
            "claude-opus-5",
            "claude-fable-5",
            "claude-fable-5-1",
            "claude-sonnet-4-5",
            "claude-sonnet-5",
            "claude-haiku-4-5",
            "gpt-5.3-codex",
            "gpt-5.2",
            "gpt-5-mini",
            "gpt-5.6-luna",
            "gpt-5.6-sol",
            "gpt-6-astra",
            "gpt-6.1-sol",
        ],
    )
    def test_background_agents_allows_configured_models(self, model: str):
        allowed, error = check_product_access("background_agents", "oauth_access_token", POSTHOG_CODE_US_APP_ID, model)
        assert allowed is True
        assert error is None

    @pytest.mark.parametrize(
        "product",
        [
            "llma_labeling",
            "product_analytics",
            "subscriptions",
            "warehouse_custom_source_builder",
            "warehouse_semantic_enrichment",
        ],
    )
    def test_gpt_6_astra_does_not_bypass_pinned_product_models(self, product: str) -> None:
        allowed, error = check_product_access(product, "personal_api_key", None, "gpt-6-astra")
        assert allowed is False
        assert error is not None
        assert "not allowed" in error

    def test_background_agents_rejects_api_keys(self):
        allowed, error = check_product_access("background_agents", "personal_api_key", None, None)
        assert allowed is False
        assert error is not None
        assert "requires OAuth" in error

    def test_background_agents_does_not_allow_claude_sonnet_4_6(self):
        allowed, error = check_product_access(
            "background_agents", "oauth_access_token", POSTHOG_CODE_US_APP_ID, "claude-sonnet-4-6"
        )
        assert allowed is False
        assert error is not None
        assert "not allowed" in error

    @patch(
        "llm_gateway.products.config.get_settings",
        return_value=MagicMock(debug=False, bedrock_region_name="us-east-1"),
    )
    def test_background_agents_allows_claude_sonnet_4_6_via_bedrock_provider(self, mock_get_settings: MagicMock):
        allowed, error = check_product_access(
            "background_agents",
            "oauth_access_token",
            POSTHOG_CODE_US_APP_ID,
            "claude-sonnet-4-6",
            provider="bedrock",
        )
        assert allowed is True
        assert error is None

    @pytest.mark.parametrize("model", sorted(BEDROCK_MODELS))
    def test_background_agents_allows_bedrock_models(self, model: str):
        allowed, error = check_product_access("background_agents", "oauth_access_token", POSTHOG_CODE_US_APP_ID, model)
        assert allowed is True
        assert error is None

    def test_slack_twig_allows_claude_haiku(self):
        allowed, error = check_product_access("slack-twig", "personal_api_key", None, "claude-haiku-4-5")
        assert allowed is True
        assert error is None

    def test_slack_twig_rejects_non_haiku_models(self):
        allowed, error = check_product_access("slack-twig", "personal_api_key", None, "claude-sonnet-4-5")
        assert allowed is False
        assert error is not None
        assert "not allowed" in error

    @pytest.mark.parametrize("model", ["claude-haiku-4-5", "gpt-5.6-luna", "gpt-6-luna"])
    def test_slack_app_routing_allows_its_models_via_api_key(self, model):
        allowed, error = check_product_access("slack_app_routing", "personal_api_key", None, model)
        assert allowed is True
        assert error is None

    def test_slack_app_routing_rejects_non_haiku_models(self):
        allowed, error = check_product_access("slack_app_routing", "personal_api_key", None, "claude-sonnet-4-5")
        assert allowed is False
        assert error is not None
        assert "not allowed" in error

    def test_slack_posthog_code_alias_still_resolves(self):
        # Legacy alias kept for backward compat (old URL paths, Django integration kind).
        allowed, error = check_product_access("slack-posthog-code", "personal_api_key", None, "claude-haiku-4-5")
        assert allowed is True
        assert error is None

    @pytest.mark.parametrize(
        "model",
        [
            "claude-opus-4-7",
            "claude-opus-4-8",
            "claude-opus-5",
            "claude-sonnet-4-6",
            "claude-sonnet-5",
            "claude-haiku-4-5",
            "gpt-5.3-codex",
        ],
    )
    @pytest.mark.parametrize("product", ["slack_app", "workflows"])
    def test_billed_agent_products_allow_agent_models(self, product: str, model: str):
        allowed, error = check_product_access(product, "oauth_access_token", POSTHOG_CODE_US_APP_ID, model)
        assert allowed is True
        assert error is None

    @pytest.mark.parametrize("product", ["slack_app", "workflows"])
    def test_billed_agent_products_reject_api_keys(self, product: str):
        allowed, error = check_product_access(product, "personal_api_key", None, "claude-sonnet-4-6")
        assert allowed is False
        assert error is not None
        assert "requires OAuth" in error

    @pytest.mark.parametrize("product", ["slack_app", "workflows"])
    def test_billed_agent_products_reject_unauthorized_oauth_apps(self, product: str):
        allowed, error = check_product_access(
            product, "oauth_access_token", "00000000-0000-0000-0000-000000000000", "claude-sonnet-4-6"
        )
        assert allowed is False
        assert error is not None
        assert "not authorized" in error

    @pytest.mark.parametrize(
        "application_id",
        [
            POSTHOG_AI_US_APP_ID,
            POSTHOG_AI_EU_APP_ID,
            POSTHOG_AI_DEV_APP_ID,
        ],
    )
    def test_posthog_ai_allows_oauth_apps(self, application_id: str):
        allowed, error = check_product_access("posthog_ai", "oauth_access_token", application_id, "claude-sonnet-4-5")
        assert allowed is True
        assert error is None

    def test_posthog_ai_rejects_posthog_code_oauth_app(self):
        allowed, error = check_product_access(
            "posthog_ai", "oauth_access_token", POSTHOG_CODE_US_APP_ID, "claude-sonnet-4-5"
        )
        assert allowed is False
        assert error is not None
        assert "not authorized" in error


class TestBackwardsCompatibility:
    def test_twig_app_id_constants_are_aliases(self):
        assert TWIG_US_APP_ID == POSTHOG_CODE_US_APP_ID
        assert TWIG_EU_APP_ID == POSTHOG_CODE_EU_APP_ID

    @pytest.mark.parametrize(
        "alias,target",
        [
            ("twig", "posthog_code"),
            ("array", "posthog_code"),
            ("slack-twig", "slack_app_routing"),
            ("slack-posthog-code", "slack_app_routing"),
        ],
    )
    def test_aliases_resolve_to_canonical_product(self, alias: str, target: str):
        assert resolve_product_alias(alias) == target

    def test_twig_alias_returns_same_config_as_posthog_code(self):
        assert get_product_config("twig") is get_product_config("posthog_code")

    def test_array_alias_returns_same_config_as_posthog_code(self):
        assert get_product_config("array") is get_product_config("posthog_code")

    def test_twig_alias_validates_to_posthog_code(self):
        assert validate_product("twig") == "posthog_code"

    def test_array_alias_validates_to_posthog_code(self):
        assert validate_product("array") == "posthog_code"

    def test_slack_aliases_resolve_to_slack_app_routing(self):
        assert get_product_config("slack-twig") is get_product_config("slack_app_routing")
        assert get_product_config("slack-posthog-code") is get_product_config("slack_app_routing")
        assert validate_product("slack-twig") == "slack_app_routing"
        assert validate_product("slack-posthog-code") == "slack_app_routing"


class TestValidateProduct:
    def test_allowed_products_derived_from_products_dict(self):
        assert ALLOWED_PRODUCTS == frozenset(PRODUCTS.keys())

    @pytest.mark.parametrize("product", list(PRODUCTS.keys()))
    def test_valid_product_returns_product(self, product: str):
        assert validate_product(product) == product

    def test_invalid_product_raises_http_exception(self):
        with pytest.raises(HTTPException) as exc_info:
            validate_product("invalid_product")
        assert exc_info.value.status_code == 400
        assert "Invalid product" in exc_info.value.detail

    @pytest.mark.parametrize("alias,target", list(PRODUCT_ALIASES.items()))
    def test_alias_resolves_to_target_product(self, alias: str, target: str):
        assert validate_product(alias) == target

    def test_resolve_product_alias_returns_alias_target(self):
        assert resolve_product_alias("array") == "posthog_code"
        assert resolve_product_alias("twig") == "posthog_code"
        assert resolve_product_alias("slack-twig") == "slack_app_routing"
        assert resolve_product_alias("slack-posthog-code") == "slack_app_routing"

    def test_resolve_product_alias_returns_input_if_not_aliased(self):
        assert resolve_product_alias("wizard") == "wizard"


class TestCheckFreeTierModelAccess:
    @pytest.mark.parametrize(
        "product,model,code_usage_billed,usage_unlimited,expected_allowed",
        [
            # Unbilled org on the Code surface: premium blocked, open model allowed
            ("posthog_code", "claude-fable-5", False, False, False),
            ("posthog_code", "@cf/zai-org/glm-5.2", False, False, True),
            ("posthog_code", "deepseek-ai/deepseek-v4-flash-0731", False, False, True),
            ("posthog_code", "moonshotai/kimi-k3", False, False, True),
            ("posthog_code", "zai-org/glm-5.3-flash", False, False, True),
            # The alias routes are the same surface - a URL spelling must not bypass
            ("array", "claude-fable-5", False, False, False),
            ("twig", "gpt-5.5", False, False, False),
            # Org pays for Desktop usage: everything stays open
            ("posthog_code", "claude-fable-5", True, False, True),
            # Staff bypass mirrors the cost-throttle exemption
            ("posthog_code", "claude-fable-5", False, True, True),
            # Other products keep their own allowlists; the gate is Code-only
            ("llm_gateway", "claude-fable-5", False, False, True),
            # No model in the body: nothing to gate (product allowlist still applies)
            ("posthog_code", None, False, False, True),
        ],
    )
    def test_gate_matrix(
        self,
        product: str,
        model: str | None,
        code_usage_billed: bool,
        usage_unlimited: bool,
        expected_allowed: bool,
    ):
        allowed, error = check_free_tier_model_access(
            product=product,
            model=model,
            provider=None,
            code_usage_billed=code_usage_billed,
            usage_unlimited=usage_unlimited,
        )
        assert allowed is expected_allowed
        if expected_allowed:
            assert error is None
        else:
            assert model is not None and error is not None
            assert model in error
            assert "@cf/zai-org/glm-5.2" in error

    def test_denied_model_alias_variant_is_also_denied(self):
        # The old gate's hole: an exact-match list let date-suffixed aliases
        # through. Prefix matching must not - but a free-listed model's own
        # variants stay allowed.
        allowed, _ = check_free_tier_model_access(
            product="posthog_code",
            model="claude-fable-5-20260301",
            provider=None,
            code_usage_billed=False,
            usage_unlimited=False,
        )
        assert allowed is False
        allowed, _ = check_free_tier_model_access(
            product="posthog_code",
            model="@cf/zai-org/glm-5.2-fp8",
            provider=None,
            code_usage_billed=False,
            usage_unlimited=False,
        )
        assert allowed is True


class TestServerCredentialRequirement:
    """Internal products driven by server-minted sandbox tokens (background_agents, signals,
    slack_app, workflows, conversations, onboarding) must accept only tokens carrying the internal
    `internal_run:read` marker. Otherwise a user's own OAuth token minted under the same app could
    route around the posthog_code free-tier gate through these products to premium models."""

    _MARKER_SCOPES = ["llm_gateway:read", "task:write", "internal_run:read"]

    # signals no longer accepts the Desktop app, so the marker check is exercised via its own app
    _PRODUCT_APPS = [
        ("background_agents", POSTHOG_CODE_US_APP_ID),
        ("signals", SIGNALS_DEV_APP_ID),
        ("slack_app", POSTHOG_CODE_US_APP_ID),
        ("workflows", POSTHOG_CODE_US_APP_ID),
        ("conversations", POSTHOG_CODE_US_APP_ID),
        ("onboarding", POSTHOG_CODE_US_APP_ID),
    ]

    @pytest.mark.parametrize(("product", "app_id"), _PRODUCT_APPS)
    def test_oauth_without_marker_is_rejected(self, product: str, app_id: str):
        # a user-held token (wildcard scope, no internal marker); claude-sonnet-5 is in every
        # sibling's model list, so the rejection is unambiguously the missing server credential
        allowed, error = check_product_access(product, "oauth_access_token", app_id, "claude-sonnet-5", scopes=["*"])
        assert allowed is False
        assert error is not None and "server-minted" in error

    @pytest.mark.parametrize(("product", "app_id"), _PRODUCT_APPS)
    def test_oauth_with_marker_is_allowed(self, product: str, app_id: str):
        allowed, error = check_product_access(
            product, "oauth_access_token", app_id, "claude-sonnet-5", scopes=self._MARKER_SCOPES
        )
        assert allowed is True
        assert error is None

    def test_personal_api_key_is_not_subject_to_the_marker(self):
        # the shared server-side gateway key reaches signals as a PAK; the check is OAuth-only
        allowed, error = check_product_access(
            "signals", "personal_api_key", None, "claude-sonnet-5", scopes=["llm_gateway:read"]
        )
        assert allowed is True
        assert error is None


_CODE_APP_IDS = frozenset({POSTHOG_CODE_DEV_APP_ID, POSTHOG_CODE_EU_APP_ID, POSTHOG_CODE_US_APP_ID})
_CODE_APP_PRODUCTS = [
    name
    for name, config in PRODUCTS.items()
    if config.allowed_application_ids and config.allowed_application_ids & _CODE_APP_IDS
]


class TestServerCredentialConfigInvariant:
    # Derived from PRODUCTS rather than hand-enumerated: requires_server_credential
    # defaults to False, so a future product added to the Code OAuth app without it
    # would silently reopen the premium-model escape the marker closes. It must fail
    # here instead.
    @pytest.mark.parametrize("product", [p for p in _CODE_APP_PRODUCTS if p != "posthog_code"])
    def test_internal_code_app_products_require_a_server_credential(self, product: str):
        assert PRODUCTS[product].requires_server_credential, (
            f"'{product}' accepts the PostHog Desktop OAuth app but doesn't require a server-minted "
            "credential, so a user's own Desktop OAuth token could reach it and route around the "
            "posthog_code free-tier model gate"
        )

    def test_posthog_code_is_the_only_code_app_product_open_to_user_tokens(self):
        # desktop users hold marker-less Code tokens; requiring the marker on the
        # user-facing product would lock them all out. Membership is asserted so a
        # broken _CODE_APP_PRODUCTS derivation can't quietly hollow out this class.
        assert "posthog_code" in _CODE_APP_PRODUCTS
        assert PRODUCTS["posthog_code"].requires_server_credential is False


class TestModelAccessFlag:
    # The open-weights models run on the claude and pi harnesses and are offered to every
    # caller. Their rollout flags outlived the rollout, and the gate fails closed, so a
    # caller the flag service could not answer for lost them.
    @pytest.mark.parametrize(
        "model",
        [
            None,
            "",
            "gpt-5.2",
            "claude-opus-5",
            "@cf/zai-org/glm-5.2",
            "moonshotai/kimi-k3",
            "MoonshotAI/Kimi-K3",
            "  moonshotai/kimi-k3  ",
            "deepseek-ai/deepseek-v4-flash-0731",
            "DeepSeek-AI/DeepSeek-V4-Flash-0731",
            "zai-org/glm-5.3",
            "ZAI-Org/GLM-5.3",
            "zai-org/glm-5.3-flash",
            "ZAI-Org/GLM-5.3-Flash",
        ],
    )
    def test_ungated_models_need_no_flag(self, model: str | None):
        assert get_required_model_flag(model) is None

    def test_every_gated_model_has_its_own_flag(self):
        # An entitlement must not be widened for one model by proxy of another, and the GLM
        # Baseten routing flag is not an entitlement at all.
        flags = list(MODEL_ACCESS_FLAGS.values())
        assert len(flags) == len(set(flags))
        assert GLM_MODAL_FLAG not in flags

    @pytest.mark.parametrize(
        "model",
        [
            "moonshotai/kimi-k3",
            "deepseek-ai/deepseek-v4-flash-0731",
            "zai-org/glm-5.3",
            "zai-org/glm-5.3-flash",
        ],
    )
    def test_suffixed_vendor_model_ids_reach_no_backend(self, model: str):
        # Product allowlists prefix-match, so a suffixed id (e.g. zai-org/glm-5.3x) passes the
        # allowlist while naming a model nobody serves. Routing exactness is what keeps such
        # an id unserved.
        suffixed = f"{model}x"
        assert not is_inference_routed_model(suffixed)
        assert suffixed not in BASETEN_MODELS
        assert not is_modal_served_model(suffixed)
        assert suffixed not in CLOUDFLARE_ALLOWED_MODELS


class TestSignalsApplicationIsolation:
    @pytest.mark.parametrize(
        ("product", "expected_allowed"),
        [
            ("signals", True),
            ("posthog_code", False),
            ("background_agents", False),
            ("slack_app", False),
        ],
    )
    @patch("llm_gateway.products.config.get_settings", return_value=MagicMock(debug=False))
    def test_signals_app_reaches_only_the_signals_product(
        self, mock_get_settings: MagicMock, product: str, expected_allowed: bool
    ):
        # The point of the separate application: a Signals run's token must not be spendable as
        # posthog_code (which bills the customer) or as background_agents (a looser budget), both
        # of which it could reach while Signals shared the Desktop app.
        allowed, _ = check_product_access(product, "oauth_access_token", SIGNALS_DEV_APP_ID, None)
        assert allowed is expected_allowed


class TestRetiredProduct:
    @patch("llm_gateway.products.config.get_settings", return_value=MagicMock(debug=True))
    def test_a_retired_product_is_refused_in_debug_mode_too(self, _settings):
        # Debug skips the application-id check, which must not reopen a retired product.
        allowed, error = check_product_access("wizard", "oauth_access_token", WIZARD_US_APP_ID, None)
        assert allowed is False
        assert error is not None
        assert "npx @posthog/wizard@latest" in error