Skip to content

Enterprise agent platform for building, deploying, and operating AI teammates.

62.4 KB
Raw Blame
"""Regression tests for generic_oauth_login URL construction.

Covers two bugs the PR fixed:
  1. When auth_url already contains a query string, params must be appended
     with '&' (no second '?').
  2. Zoom provider must include `prompt=login` in the redirect URL.
"""

from __future__ import annotations

import base64
import hashlib
from datetime import timedelta
from types import SimpleNamespace
from unittest.mock import Mock
from urllib.parse import parse_qs, urlparse

import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from tests.shared.oauth_browser_fixture import (
    create_access_token,
    generic_oauth_callback,
)
from xagent.core.utils.encryption import _is_encrypted, decrypt_value, encrypt_value
from xagent.web.api.auth import (
    _is_salesforce_provider,
    _resolve_oauth_secret,
    generic_oauth_login,
    verify_token,
)
from xagent.web.builtin_mcp_registry import (
    get_builtin_oauth_provider_rows,
    get_builtin_public_mcp_app,
    get_builtin_public_mcp_app_rows,
)
from xagent.web.models.database import Base
from xagent.web.models.mcp import MCPServer
from xagent.web.models.oauth_provider import OAuthProvider
from xagent.web.models.public_mcp import PublicMCPApp
from xagent.web.models.user import User
from xagent.web.models.user_oauth import UserOAuth
from xagent.web.oauth_provider_quirks import requires_pkce
from xagent.web.services.google_oauth_grants import (
    create_google_oauth_grant_association,
)

XERO_APP_SCOPES = [
    "openid",
    "profile",
    "email",
    "accounting.contacts",
    "accounting.settings",
    "accounting.invoices",
    "accounting.payments",
    "accounting.banktransactions",
    "accounting.manualjournals",
    "accounting.reports.aged.read",
    "accounting.reports.profitandloss.read",
    "accounting.reports.balancesheet.read",
    "accounting.reports.trialbalance.read",
    "offline_access",
]

# ---------- helpers ---------------------------------------------------------


@pytest.fixture()
def db_session(tmp_path):
    """Fresh SQLite DB + a single user for each test."""
    db_path = tmp_path / "test.db"
    engine = create_engine(
        f"sqlite:///{db_path}", connect_args={"check_same_thread": False}
    )
    Base.metadata.create_all(engine)
    SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False)
    db = SessionLocal()

    user = User(username="alice", password_hash="x", is_admin=False)
    db.add(user)
    db.commit()
    db.refresh(user)

    yield db, user
    db.close()
    engine.dispose()


def _token_for(user: User) -> str:
    return create_access_token(
        data={"sub": user.username, "user_id": user.id, "type": "access"},
        expires_delta=timedelta(minutes=5),
    )


def _provider(
    auth_url: str,
    default_scopes=None,
    redirect_uri=None,
    client_id: str = "test-client-id",
):
    """A duck-typed stand-in for the OAuthProvider ORM row."""
    return SimpleNamespace(
        client_id=encrypt_value(client_id),
        auth_url=auth_url,
        redirect_uri=redirect_uri,
        default_scopes=default_scopes or [],
    )


def _location(response) -> str:
    # RedirectResponse stores the target in the Location header.
    return response.headers["location"]


class _MockOAuthResponse:
    def __init__(self, payload: dict):
        self._payload = payload
        self.status_code = 200
        self.text = ""

    def json(self):
        return self._payload


# ---------- the actual regression checks ------------------------------------


def test_xero_provider_defaults(monkeypatch):
    monkeypatch.setenv("XERO_CLIENT_ID", "xero-test-client")
    monkeypatch.setenv("XERO_CLIENT_SECRET", "xero-test-secret")
    monkeypatch.setenv(
        "XERO_REDIRECT_URI", "https://app.example/api/auth/xero/callback"
    )

    provider = next(
        row
        for row in get_builtin_oauth_provider_rows()
        if row["provider_name"] == "xero"
    )

    assert provider == {
        "provider_name": "xero",
        "name": "Xero",
        "client_id": "xero-test-client",
        "client_secret": "xero-test-secret",
        "auth_url": "https://login.xero.com/identity/connect/authorize",
        "token_url": "https://identity.xero.com/connect/token",
        "redirect_uri": "https://app.example/api/auth/xero/callback",
        "userinfo_url": "https://identity.xero.com/connect/userinfo",
        "user_id_path": "sub",
        "email_path": "email",
        "default_scopes": ["openid", "profile", "email"],
    }


def test_xero_catalog_contract():
    app = get_builtin_public_mcp_app("xero")
    assert app is not None
    assert app["transport"] == "oauth"
    assert app["provider_name"] == "xero"
    assert app["category"] == "Operations"
    assert app["is_visible_in_connector"] is True
    assert app["oauth_scopes"] == XERO_APP_SCOPES
    assert app["launch_config"] == {
        "command": "python",
        "args": ["-m", "xagent.web.tools.mcp.xero"],
        "env_mapping": {"XERO_CLIENT_BEARER_TOKEN": "access_token"},
    }


def test_xero_catalog_login_scopes(db_session, monkeypatch):
    db, user = db_session
    monkeypatch.setenv("XERO_CLIENT_ID", "xero-test-client")
    monkeypatch.setenv("XERO_CLIENT_SECRET", "xero-test-secret")
    monkeypatch.setenv(
        "XERO_REDIRECT_URI", "https://app.example/api/auth/xero/callback"
    )
    app = get_builtin_public_mcp_app("xero")
    assert app is not None
    db.add(PublicMCPApp(**app))
    provider = OAuthProvider(
        **next(
            row
            for row in get_builtin_oauth_provider_rows()
            if row["provider_name"] == "xero"
        )
    )
    db.add(provider)
    db.commit()

    response = generic_oauth_login(
        provider="xero",
        token=_token_for(user),
        app_id="xero",
        redirect=None,
        db=db,
        db_provider=provider,
    )

    assert response.status_code == 307
    url = urlparse(_location(response))
    params = parse_qs(url.query)
    assert f"{url.scheme}://{url.netloc}{url.path}" == provider.auth_url
    assert params["client_id"] == ["xero-test-client"]
    assert params["redirect_uri"] == [provider.redirect_uri]
    assert params["response_type"] == ["code"]
    scopes = params["scope"][0].split()
    assert set(scopes) == set(XERO_APP_SCOPES)
    assert len(scopes) == len(set(scopes))
    assert verify_token(params["state"][0])["app_id"] == "xero"


def test_google_drive_login_does_not_reuse_previous_granted_scopes(db_session):
    db, user = db_session
    db.add(
        PublicMCPApp(
            app_id="google-drive",
            name="Google Drive",
            description="Drive",
            transport="oauth",
            provider_name="google",
            category="Support",
            oauth_scopes=["https://www.googleapis.com/auth/drive.file"],
            is_visible_in_connector=True,
            launch_config={},
        )
    )
    db.commit()
    provider = _provider(
        auth_url="https://accounts.google.com/o/oauth2/v2/auth",
        default_scopes=["openid"],
        redirect_uri="https://app.example.com/api/auth/google/callback",
    )

    response = generic_oauth_login(
        provider="google",
        token=_token_for(user),
        app_id="google-drive",
        redirect=None,
        db=db,
        db_provider=provider,
    )

    params = parse_qs(urlparse(_location(response)).query)
    assert params["include_granted_scopes"] == ["false"]
    assert set(params["scope"][0].split()) == {
        "openid",
        "https://www.googleapis.com/auth/drive.file",
    }


@pytest.mark.parametrize(
    ("associated_scope", "restricted_enabled", "expect_associated_scope"),
    [
        ("scope.catalog.associated", False, True),
        ("https://www.googleapis.com/auth/gmail.modify", False, False),
        ("https://www.googleapis.com/auth/gmail.modify", True, True),
    ],
)
def test_google_shared_login_uses_catalog_scopes_not_stale_mirror(
    db_session,
    monkeypatch,
    associated_scope,
    restricted_enabled,
    expect_associated_scope,
):
    monkeypatch.setenv("XAGENT_GOOGLE_SHARED_OAUTH_GRANTS_ENABLED", "true")
    monkeypatch.setenv(
        "XAGENT_GOOGLE_RESTRICTED_SCOPES_ENABLED", str(restricted_enabled)
    )
    db, user = db_session
    db.add_all(
        [
            PublicMCPApp(
                app_id="test-associated-google-app",
                name="Associated Google App",
                description="Associated app",
                transport="oauth",
                provider_name="google",
                category="Support",
                oauth_scopes=[associated_scope],
                is_visible_in_connector=True,
                launch_config={},
            ),
            PublicMCPApp(
                app_id="test-current-google-app",
                name="Current Google App",
                description="Current app",
                transport="oauth",
                provider_name="google",
                category="Support",
                oauth_scopes=["scope.catalog.current"],
                is_visible_in_connector=True,
                launch_config={},
            ),
        ]
    )
    legacy = UserOAuth(
        user_id=int(user.id),
        provider="test-associated-google-app",
        provider_user_id="subject-a",
        access_token="legacy-access",
        refresh_token="legacy-refresh",
        scope="openid scope.existing",
    )
    shared = UserOAuth(
        user_id=int(user.id),
        provider="google",
        provider_user_id="subject-a",
        access_token="shared-access",
        refresh_token="shared-refresh",
        scope="openid scope.existing",
    )
    db.add_all([legacy, shared])
    db.flush()
    create_google_oauth_grant_association(
        db,
        oauth_account=shared,
        oauth_client_id="test-client-id",
        app_id="test-associated-google-app",
        legacy_oauth_account=legacy,
    )
    db.commit()
    provider = _provider(
        auth_url="https://accounts.google.com/o/oauth2/v2/auth",
        default_scopes=["openid"],
        redirect_uri="https://app.example.com/api/auth/google/callback",
    )

    response = generic_oauth_login(
        provider="google",
        token=_token_for(user),
        app_id="test-current-google-app",
        redirect=None,
        db=db,
        db_provider=provider,
    )

    params = parse_qs(urlparse(_location(response)).query)
    assert params["prompt"] == ["select_account"]
    expected_scopes = {"openid", "scope.catalog.current"}
    if expect_associated_scope:
        expected_scopes.add(associated_scope)
    assert set(params["scope"][0].split()) == expected_scopes
    state = verify_token(params["state"][0])
    assert state["google_shared_mode"] is True
    assert set(state["google_shared_scopes"]) == expected_scopes


@pytest.mark.parametrize("enabled", [False, True])
def test_google_scope_aggregation(db_session, monkeypatch, enabled):
    monkeypatch.setenv("XAGENT_GOOGLE_RESTRICTED_SCOPES_ENABLED", str(enabled))
    db, user = db_session
    db.add(
        PublicMCPApp(
            app_id="google-calendar",
            name="Google Calendar",
            description="Calendar",
            transport="oauth",
            provider_name="google",
            category="Scheduling",
            oauth_scopes=["https://www.googleapis.com/auth/calendar.events"],
            is_visible_in_connector=True,
            launch_config={},
        )
    )
    db.commit()
    provider = _provider(
        auth_url="https://accounts.google.com/o/oauth2/v2/auth",
        default_scopes=["openid"],
        redirect_uri="https://app.example.com/api/auth/google/callback",
    )

    response = generic_oauth_login(
        provider="google",
        token=_token_for(user),
        app_id="google-calendar",
        redirect=None,
        db=db,
        db_provider=provider,
    )

    params = parse_qs(urlparse(_location(response)).query)
    assert params["include_granted_scopes"] == ["true" if enabled else "false"]


def test_auth_url_with_query_uses_ampersand_separator(db_session):
    """If db_provider.auth_url already has '?', params must be appended with '&'."""
    db, user = db_session
    token = _token_for(user)

    provider = _provider(
        auth_url="https://example.com/oauth/authorize?tenant=acme",
        default_scopes=["openid", "profile"],
        redirect_uri="https://app.example.com/cb",
    )

    resp = generic_oauth_login(
        provider="custom",
        token=token,
        app_id=None,
        redirect=None,
        db=db,
        db_provider=provider,
    )
    url = _location(resp)

    # Only one '?' allowed in the whole URL — this is the regression.
    assert url.count("?") == 1, f"second '?' leaked into URL: {url}"

    parsed = urlparse(url)
    base = f"{parsed.scheme}://{parsed.netloc}{parsed.path}"
    qs = parse_qs(parsed.query)

    assert base == "https://example.com/oauth/authorize"
    assert qs["tenant"] == ["acme"], "pre-existing query param dropped"
    assert qs["client_id"] == ["test-client-id"]
    assert qs["redirect_uri"] == ["https://app.example.com/cb"]
    assert qs["response_type"] == ["code"]
    assert "state" in qs


def test_auth_url_without_query_uses_question_mark(db_session):
    db, user = db_session
    token = _token_for(user)

    provider = _provider(
        auth_url="https://example.com/oauth/authorize",
        default_scopes=["openid"],
        redirect_uri="https://app.example.com/cb",
    )

    resp = generic_oauth_login(
        provider="custom",
        token=token,
        app_id=None,
        redirect=None,
        db=db,
        db_provider=provider,
    )
    url = _location(resp)

    assert url.count("?") == 1
    assert url.startswith("https://example.com/oauth/authorize?")


def test_zoom_provider_sets_prompt_login(db_session):
    db, user = db_session
    token = _token_for(user)

    provider = _provider(
        auth_url="https://zoom.us/oauth/authorize",
        default_scopes=["user:read"],
        redirect_uri="https://app.example.com/cb",
    )

    resp = generic_oauth_login(
        provider="zoom",
        token=token,
        app_id=None,
        redirect=None,
        db=db,
        db_provider=provider,
    )
    url = _location(resp)
    qs = parse_qs(urlparse(url).query)

    assert qs.get("prompt") == ["login"], f"zoom prompt missing: {url}"


def test_salesforce_provider_includes_pkce_code_challenge(db_session):
    """Newer Salesforce orgs enforce PKCE on this grant with no per-app
    opt-out; the authorize redirect must carry a code_challenge derived from
    a verifier that (a) round-trips through the signed state token via
    decrypt_value (not left as plaintext in it) and (b) actually matches the
    S256 challenge sent to Salesforce."""
    db, user = db_session
    token = _token_for(user)

    provider = _provider(
        auth_url="https://login.salesforce.com/services/oauth2/authorize",
        default_scopes=["api", "refresh_token", "openid"],
        redirect_uri="https://app.example.com/cb",
    )

    resp = generic_oauth_login(
        provider="salesforce",
        token=token,
        app_id=None,
        redirect=None,
        db=db,
        db_provider=provider,
    )
    qs = parse_qs(urlparse(_location(resp)).query)

    assert qs.get("code_challenge_method") == ["S256"]
    assert "code_challenge" in qs

    state_payload = verify_token(qs["state"][0])
    encrypted_verifier = state_payload["code_verifier"]
    decrypted_verifier = decrypt_value(encrypted_verifier)
    # The real regression this guards: encryption actually changed the
    # value. `encrypted_verifier != qs["code_challenge"][0]` alone proves
    # nothing -- a verifier trivially differs from its own derived S256
    # hash regardless of whether encryption ever ran.
    assert encrypted_verifier != decrypted_verifier
    assert _is_encrypted(encrypted_verifier)

    expected_challenge = (
        base64.urlsafe_b64encode(
            hashlib.sha256(decrypted_verifier.encode("ascii")).digest()
        )
        .decode("ascii")
        .rstrip("=")
    )
    assert qs["code_challenge"][0] == expected_challenge


@pytest.mark.parametrize(
    "provider,expected",
    [
        ("salesforce", True),
        ("SALESFORCE", True),
        ("salesforce-sandbox", True),
        ("salesforce-govcloud", True),
        ("salesforcelite", False),
        ("salesforce2", False),
        ("hubspot", False),
        ("", False),
    ],
)
def test_is_salesforce_provider_requires_exact_name_or_hyphenated_suffix(
    provider, expected
):
    """Anchored to a "-" separator, not a bare prefix: oauth_providers.name
    is admin-settable via POST/PUT /admin/mcp/providers, so a bare
    startswith("salesforce") would also match an unrelated custom provider
    an admin happened to name e.g. "salesforcelite" -- silently routing it
    through PKCE and the instance_url-required guard it has no reason to
    satisfy."""
    assert _is_salesforce_provider(provider) is expected


def test_salesforce_sandbox_provider_includes_pkce_code_challenge(db_session):
    """PKCE is gated on a provider-name *prefix* match
    (_is_salesforce_provider), not exact equality -- specifically so an
    admin-created "salesforce-sandbox" row (example.env's documented
    workaround for sandbox orgs, which have no per-user toggle otherwise)
    also gets it. An exact match here would silently skip PKCE for that row
    and then fail opaquely against a PKCE-enforcing sandbox org."""
    db, user = db_session
    token = _token_for(user)

    provider = _provider(
        auth_url="https://test.salesforce.com/services/oauth2/authorize",
        default_scopes=["api", "refresh_token", "openid"],
        redirect_uri="https://app.example.com/cb",
    )

    resp = generic_oauth_login(
        provider="salesforce-sandbox",
        token=token,
        app_id=None,
        redirect=None,
        db=db,
        db_provider=provider,
    )
    qs = parse_qs(urlparse(_location(resp)).query)

    assert qs.get("code_challenge_method") == ["S256"]
    assert "code_challenge" in qs


def test_employment_hero_provider_includes_pkce_code_challenge(db_session):
    """Employment Hero mandates PKCE on this grant for every app from
    2026-09-14, with no per-app opt-out -- requires_pkce()
    (oauth_provider_quirks.py) covers this provider the same way it covers
    salesforce above, so the authorize redirect must carry a code_challenge
    too."""
    db, user = db_session
    token = _token_for(user)

    provider = _provider(
        auth_url="https://oauth.employmenthero.com/oauth2/authorize",
        default_scopes=[],
        redirect_uri="https://app.example.com/cb",
    )

    resp = generic_oauth_login(
        provider="employment-hero",
        token=token,
        app_id=None,
        redirect=None,
        db=db,
        db_provider=provider,
    )
    qs = parse_qs(urlparse(_location(resp)).query)

    assert qs.get("code_challenge_method") == ["S256"]
    assert "code_challenge" in qs

    state_payload = verify_token(qs["state"][0])
    encrypted_verifier = state_payload["code_verifier"]
    decrypted_verifier = decrypt_value(encrypted_verifier)
    assert encrypted_verifier != decrypted_verifier
    assert _is_encrypted(encrypted_verifier)

    expected_challenge = (
        base64.urlsafe_b64encode(
            hashlib.sha256(decrypted_verifier.encode("ascii")).digest()
        )
        .decode("ascii")
        .rstrip("=")
    )
    assert qs["code_challenge"][0] == expected_challenge


@pytest.mark.parametrize(
    "provider,expected",
    [
        ("salesforce", True),
        ("salesforce-sandbox", True),
        ("employment-hero", True),
        ("EMPLOYMENT-HERO", True),
        ("employment-hero-sandbox", True),
        ("employment-herolite", False),
        ("employment-hero2", False),
        ("hubspot", False),
        ("", False),
    ],
)
def test_requires_pkce_matches_gated_provider_families(provider, expected):
    """requires_pkce() is the shared predicate generic_oauth_login's PKCE
    gate actually calls -- covering it directly (not just indirectly through
    the redirect-URL assertions above) pins the provider-family membership
    list itself, the same anchored-prefix reasoning
    _is_salesforce_provider's own test documents."""
    assert requires_pkce(provider) is expected


def test_salesforce_login_returns_clear_error_when_encryption_key_missing(
    db_session, monkeypatch
):
    """encrypt_value() raises a bare ValueError when ENCRYPTION_KEY is unset
    outside development. Every other provider's login route never calls
    encrypt_value at all, so this misconfiguration would otherwise be
    invisible until the first Salesforce connect attempt -- and uncaught,
    it would 500 with an opaque traceback instead of a clear cause."""
    from xagent.core.utils.encryption import get_cipher

    db, user = db_session
    token = _token_for(user)

    provider = _provider(
        auth_url="https://login.salesforce.com/services/oauth2/authorize",
        default_scopes=["api", "refresh_token", "openid"],
        redirect_uri="https://app.example.com/cb",
    )

    monkeypatch.delenv("ENCRYPTION_KEY", raising=False)
    monkeypatch.setenv("ENVIRONMENT", "production")
    get_cipher.cache_clear()
    try:
        resp = generic_oauth_login(
            provider="salesforce",
            token=token,
            app_id=None,
            redirect=None,
            db=db,
            db_provider=provider,
        )
    finally:
        get_cipher.cache_clear()

    assert resp.status_code == 500
    assert "ENCRYPTION_KEY" in resp.body.decode()


def test_non_salesforce_provider_omits_pkce_code_challenge(db_session):
    db, user = db_session
    token = _token_for(user)

    provider = _provider(
        auth_url="https://example.com/oauth/authorize",
        default_scopes=["openid"],
        redirect_uri="https://app.example.com/cb",
    )

    resp = generic_oauth_login(
        provider="custom",
        token=token,
        app_id=None,
        redirect=None,
        db=db,
        db_provider=provider,
    )
    qs = parse_qs(urlparse(_location(resp)).query)

    assert "code_challenge" not in qs
    assert "code_challenge_method" not in qs
    state_payload = verify_token(qs["state"][0])
    assert "code_verifier" not in state_payload


def test_non_zoom_provider_does_not_set_prompt_login(db_session):
    """Sanity: only Zoom gets prompt=login (Google gets prompt=consent, others none)."""
    db, user = db_session
    token = _token_for(user)

    provider = _provider(
        auth_url="https://example.com/oauth/authorize",
        default_scopes=["openid"],
        redirect_uri="https://app.example.com/cb",
    )

    resp = generic_oauth_login(
        provider="custom",
        token=token,
        app_id=None,
        redirect=None,
        db=db,
        db_provider=provider,
    )
    qs = parse_qs(urlparse(_location(resp)).query)
    assert "prompt" not in qs


def test_meta_login_uses_comma_separated_canonical_scopes_for_builtin_app(
    db_session, monkeypatch
):
    db, user = db_session
    token = _token_for(user)
    monkeypatch.delenv("META_CONFIG_ID", raising=False)
    monkeypatch.delenv("META_LOGIN_CONFIG_ID", raising=False)
    db.add(
        PublicMCPApp(
            app_id="facebook",
            name="Facebook Pages",
            description="Facebook connector",
            transport="oauth",
            provider_name="meta",
            category="Marketing",
            oauth_scopes=["pages_show_list", "pages_manage_posts"],
            is_visible_in_connector=True,
            launch_config={},
        )
    )
    db.commit()

    provider = _provider(
        auth_url="https://www.facebook.com/v25.0/dialog/oauth",
        default_scopes=["public_profile"],
        redirect_uri="https://app.example.com/api/auth/meta/callback",
    )

    resp = generic_oauth_login(
        provider="meta",
        token=token,
        app_id="facebook",
        redirect=None,
        db=db,
        db_provider=provider,
    )
    qs = parse_qs(urlparse(_location(resp)).query)

    assert qs["scope"] == [
        "public_profile,pages_manage_posts,pages_read_engagement,"
        "pages_read_user_content,pages_show_list"
    ]


def test_meta_ads_login_requests_ads_read_scope_without_config_id(
    db_session, monkeypatch
):
    db, user = db_session
    token = _token_for(user)
    monkeypatch.delenv("META_CONFIG_ID", raising=False)
    monkeypatch.delenv("META_ADS_CONFIG_ID", raising=False)
    db.add(
        PublicMCPApp(
            app_id="meta-ads",
            name="Meta Ads",
            description="Meta Ads connector",
            transport="oauth",
            provider_name="meta",
            category="Marketing",
            oauth_scopes=["ads_read"],
            is_visible_in_connector=True,
            launch_config={},
        )
    )
    db.commit()

    provider = _provider(
        auth_url="https://www.facebook.com/v25.0/dialog/oauth",
        default_scopes=["public_profile"],
        redirect_uri="https://app.example.com/api/auth/meta/callback",
    )

    resp = generic_oauth_login(
        provider="meta",
        token=token,
        app_id="meta-ads",
        redirect=None,
        db=db,
        db_provider=provider,
    )
    qs = parse_qs(urlparse(_location(resp)).query)

    assert qs["scope"] == ["public_profile,ads_read"]
    assert "config_id" not in qs


def test_github_login_requests_exact_canonical_scope(db_session):
    """The requested scope must be exactly the provider's default_scopes
    ("read:user") merged with the github app row's canonical oauth_scopes
    ("repo", "user:email", sorted) -- read:org must NOT reappear even if a
    stale/incorrect DB row still lists it, since get_app_by_id overlays the
    canonical registry's oauth_scopes for a builtin app_id regardless of
    what is persisted."""
    db, user = db_session
    token = _token_for(user)
    db.add(
        PublicMCPApp(
            app_id="github",
            name="GitHub",
            description="GitHub connector",
            transport="oauth",
            provider_name="github",
            category="Development",
            # Deliberately stale/wrong to prove the registry, not this
            # row's oauth_scopes, is what actually gets requested.
            oauth_scopes=["repo", "read:org", "user:email"],
            is_visible_in_connector=True,
            launch_config={},
        )
    )
    db.commit()

    provider = _provider(
        auth_url="https://github.com/login/oauth/authorize",
        default_scopes=["read:user"],
        redirect_uri="https://app.example.com/api/auth/github/callback",
    )

    resp = generic_oauth_login(
        provider="github",
        token=token,
        app_id="github",
        redirect=None,
        db=db,
        db_provider=provider,
    )
    qs = parse_qs(urlparse(_location(resp)).query)

    assert qs["scope"] == ["read:user repo user:email"]


def test_employment_hero_login_requests_exact_canonical_scope(db_session):
    """Employment Hero has no default_scopes of its own (every scope it
    needs lives entirely on the app row's oauth_scopes) -- the only test
    covering its login route before this ran with app_id=None, bypassing
    this app-level scope-merge path (and the canonical-registry overlay
    test_github_login_requests_exact_canonical_scope above exercises)
    entirely. Verified by sabotage: deleting a scope from the registry row
    produced zero failures anywhere in the oauth + employment-hero suite
    before this test existed."""
    db, user = db_session
    token = _token_for(user)
    db.add(
        PublicMCPApp(
            app_id="employment-hero",
            name="Employment Hero",
            description="Employment Hero connector",
            transport="oauth",
            provider_name="employment-hero",
            category="HR",
            # Deliberately stale/wrong to prove the registry, not this
            # row's oauth_scopes, is what actually gets requested.
            oauth_scopes=["organisations:list"],
            is_visible_in_connector=True,
            launch_config={},
        )
    )
    db.commit()

    provider = _provider(
        auth_url="https://oauth.employmenthero.com/oauth2/authorize",
        default_scopes=[],
        redirect_uri="https://app.example.com/api/auth/employment-hero/callback",
    )

    resp = generic_oauth_login(
        provider="employment-hero",
        token=token,
        app_id="employment-hero",
        redirect=None,
        db=db,
        db_provider=provider,
    )
    qs = parse_qs(urlparse(_location(resp)).query)

    assert qs["scope"] == [
        "employees:list employees:show leave_balances:list "
        "leave_categories:list leave_requests:approve leave_requests:create "
        "leave_requests:list organisations:list teams:list timesheet_entries:list"
    ]


def test_bare_github_login_config_error_takes_precedence_over_bare_route_guard(
    db_session,
):
    """A bare (app_id-less) login persists to the exact same
    UserOAuth.provider="github" key an app-scoped login uses, since
    github's app_id and provider name are the same string. Left unblocked,
    re-running this route would silently replace a fully-scoped
    connection's grant with an identity-only one on the next callback --
    that guard exists and still runs before any state token is minted.

    But the guard is checked AFTER config/auth resolution, not before: a
    misconfigured provider (missing client_id) must still get the
    actionable CLIENT_ID config error, not a 404 that would incorrectly
    read as "this route doesn't support a normal connect attempt" to an
    operator debugging their setup."""
    db, user = db_session
    token = _token_for(user)

    provider = _provider(
        auth_url="https://github.com/login/oauth/authorize",
        default_scopes=["read:user"],
        redirect_uri="https://app.example.com/api/auth/github/callback",
        client_id="",  # deliberately unconfigured
    )

    resp = generic_oauth_login(
        provider="github",
        token=token,
        app_id=None,
        redirect=None,
        db=db,
        db_provider=provider,
    )

    assert resp.status_code == 500
    assert "GITHUB_CLIENT_ID" in resp.body.decode()


def test_bare_github_login_unauthenticated_gets_401_not_404(db_session):
    """Same ordering point as the config-error case above: an
    unauthenticated bare-route request must get the generic 401, not a 404
    that implies the route itself is unsupported."""
    db, _user = db_session

    provider = _provider(
        auth_url="https://github.com/login/oauth/authorize",
        default_scopes=["read:user"],
        redirect_uri="https://app.example.com/api/auth/github/callback",
    )

    resp = generic_oauth_login(
        provider="github",
        token=None,
        app_id=None,
        redirect=None,
        db=db,
        db_provider=provider,
    )

    assert resp.status_code == 401


def test_bare_github_login_is_rejected_once_authenticated_and_configured(db_session):
    """Once config and auth both resolve cleanly, the bare-route guard for
    providers requiring an app-scoped grant still fires -- before any
    state token is minted, which is the property it actually needs to
    hold."""
    db, user = db_session
    token = _token_for(user)

    provider = _provider(
        auth_url="https://github.com/login/oauth/authorize",
        default_scopes=["read:user"],
        redirect_uri="https://app.example.com/api/auth/github/callback",
    )

    resp = generic_oauth_login(
        provider="github",
        token=token,
        app_id=None,
        redirect=None,
        db=db,
        db_provider=provider,
    )

    assert resp.status_code == 404


def test_bare_login_for_unrestricted_provider_still_proceeds(db_session):
    """Sanity: the bare-route guard is scoped to
    APPS_REQUIRING_APP_SCOPED_OAUTH_GRANT members only -- an ordinary
    provider's bare login (no collision risk) must be unaffected."""
    db, user = db_session
    token = _token_for(user)

    provider = _provider(
        auth_url="https://login.microsoftonline.com/common/oauth2/v2.0/authorize",
        default_scopes=["User.Read"],
        redirect_uri="https://app.example.com/cb",
    )

    resp = generic_oauth_login(
        provider="microsoft",
        token=token,
        app_id=None,
        redirect=None,
        db=db,
        db_provider=provider,
    )

    assert resp.status_code == 307


def test_planner_catalog_login_requests_tasks_scope(db_session):
    db, user = db_session
    token = _token_for(user)
    planner = get_builtin_public_mcp_app("planner")
    assert planner is not None
    db.add(PublicMCPApp(**planner))
    db.commit()

    provider = _provider(
        auth_url="https://login.microsoftonline.com/common/oauth2/v2.0/authorize",
        default_scopes=["User.Read"],
        redirect_uri="https://app.example.com/cb",
    )
    response = generic_oauth_login(
        provider="microsoft",
        token=token,
        app_id="planner",
        redirect=None,
        db=db,
        db_provider=provider,
    )

    query = parse_qs(urlparse(_location(response)).query)
    assert set(query["scope"][0].split()) == {
        "Tasks.ReadWrite",
        "Team.ReadBasic.All",
        "User.Read",
        "offline_access",
    }


def test_excel_login_requests_refresh_permission(db_session):
    db, user = db_session
    token = _token_for(user)
    excel_row = get_builtin_public_mcp_app("excel")
    assert excel_row is not None
    db.add(PublicMCPApp(**excel_row))
    db.commit()
    provider = _provider(
        auth_url="https://login.microsoftonline.com/common/oauth2/v2.0/authorize",
        default_scopes=["User.Read"],
        redirect_uri="https://app.example.com/api/auth/microsoft/callback",
    )

    resp = generic_oauth_login(
        provider="microsoft",
        token=token,
        app_id="excel",
        redirect=None,
        db=db,
        db_provider=provider,
    )

    assert resp.status_code == 307
    scopes = parse_qs(urlparse(_location(resp)).query)["scope"][0].split()
    assert set(scopes) == {"User.Read", "Files.ReadWrite", "offline_access"}


MICROSOFT_APP_IDS = sorted(
    row["app_id"]
    for row in get_builtin_public_mcp_app_rows()
    if row["provider_name"] == "microsoft"
)


def test_microsoft_app_id_discovery_is_not_empty():
    # Guard against the registry filter silently matching nothing, which
    # would let the parametrized test below pass vacuously.
    assert {
        "excel",
        "onedrive",
        "outlook",
        "planner",
        "powerpoint",
        "sharepoint",
        "teams",
        "word",
    } <= set(MICROSOFT_APP_IDS)


@pytest.mark.parametrize("app_id", MICROSOFT_APP_IDS)
def test_every_microsoft_app_login_requests_refresh_permission(db_session, app_id):
    """Microsoft only issues a refresh_token when offline_access is requested,
    and the provider's default_scopes (User.Read) do not include it, so every
    Microsoft connector must ask for it itself or its grant dies with the
    first access token."""
    db, user = db_session
    token = _token_for(user)
    app_row = get_builtin_public_mcp_app(app_id)
    assert app_row is not None
    db.add(PublicMCPApp(**app_row))
    db.commit()
    provider = _provider(
        auth_url="https://login.microsoftonline.com/common/oauth2/v2.0/authorize",
        default_scopes=["User.Read"],
        redirect_uri="https://app.example.com/api/auth/microsoft/callback",
    )

    resp = generic_oauth_login(
        provider="microsoft",
        token=token,
        app_id=app_id,
        redirect=None,
        db=db,
        db_provider=provider,
    )

    assert resp.status_code == 307
    scopes = parse_qs(urlparse(_location(resp)).query)["scope"][0].split()
    assert "offline_access" in scopes


def test_bare_microsoft_callback_skips_excel_but_connects_eligible_sibling(
    db_session, monkeypatch
):
    """A User.Read-only provider grant must not provision the Excel app."""
    from xagent.web.api import auth as auth_api

    db, user = db_session
    db.add_all(
        [
            PublicMCPApp(
                app_id="excel",
                name="Excel",
                transport="oauth",
                provider_name="microsoft",
                oauth_scopes=["Files.ReadWrite"],
                is_visible_in_connector=True,
                launch_config={"command": "python", "args": ["-m", "excel"]},
            ),
            PublicMCPApp(
                app_id="microsoft-profile",
                name="Microsoft Profile",
                transport="oauth",
                provider_name="microsoft",
                oauth_scopes=["User.Read"],
                is_visible_in_connector=True,
                launch_config={"command": "python", "args": ["-m", "profile"]},
            ),
        ]
    )
    db.commit()
    state = create_access_token(
        data={"type": "oauth_state", "user_id": user.id, "provider": "microsoft"},
        expires_delta=timedelta(minutes=10),
    )
    request = SimpleNamespace(query_params={"code": "code", "state": state})
    monkeypatch.setattr(
        auth_api.requests,
        "post",
        Mock(
            return_value=_MockOAuthResponse(
                {
                    "access_token": "user-read-token",
                    "token_type": "Bearer",
                    "scope": "User.Read",
                    "expires_in": 3600,
                }
            )
        ),
    )
    monkeypatch.setattr(
        auth_api.requests,
        "get",
        Mock(
            return_value=_MockOAuthResponse(
                {"id": "microsoft-user-1", "mail": "[email protected]"}
            )
        ),
    )
    provider = SimpleNamespace(
        provider_name="microsoft",
        client_id=encrypt_value("microsoft-client-id"),
        client_secret=encrypt_value("microsoft-client-secret"),
        token_url="https://login.microsoftonline.com/common/oauth2/v2.0/token",
        redirect_uri="https://app.example.com/api/auth/microsoft/callback",
        userinfo_url="https://graph.microsoft.com/v1.0/me",
        user_id_path="id",
        email_path="mail",
        default_scopes=["User.Read"],
    )

    response = generic_oauth_callback("microsoft", request, db, provider)

    assert response.status_code == 200
    assert (
        db.query(UserOAuth)
        .filter(UserOAuth.user_id == user.id, UserOAuth.provider == "microsoft")
        .one()
        .access_token
        == "user-read-token"
    )
    server_names = {server.name for server in db.query(MCPServer).all()}
    assert "Microsoft Profile" in server_names
    assert "Excel" not in server_names


def test_app_without_optional_scopes_sends_no_optional_scope_param(
    db_session, monkeypatch
):
    """An app without optional scopes must not send a stray provider param."""
    db, user = db_session
    token = _token_for(user)
    monkeypatch.delenv("META_CONFIG_ID", raising=False)
    monkeypatch.delenv("META_LOGIN_CONFIG_ID", raising=False)
    db.add(
        PublicMCPApp(
            app_id="facebook",
            name="Facebook Pages",
            description="Facebook connector",
            transport="oauth",
            provider_name="meta",
            category="Marketing",
            oauth_scopes=["pages_show_list"],
            is_visible_in_connector=True,
            launch_config={},
        )
    )
    db.commit()

    provider = _provider(
        auth_url="https://www.facebook.com/v25.0/dialog/oauth",
        default_scopes=["public_profile"],
        redirect_uri="https://app.example.com/api/auth/meta/callback",
    )

    resp = generic_oauth_login(
        provider="meta",
        token=token,
        app_id="facebook",
        redirect=None,
        db=db,
        db_provider=provider,
    )
    qs = parse_qs(urlparse(_location(resp)).query)

    assert "optional_scope" not in qs


def test_patched_builtin_optional_scopes_are_sent_to_authorize_endpoint(
    db_session, monkeypatch
):
    """Keep the optional-scope path covered even when no current builtin uses it."""
    import xagent.web.mcp_apps as mcp_apps_module

    db, user = db_session
    token = _token_for(user)
    original_lookup = mcp_apps_module.get_builtin_execution_fields_and_optional_scopes

    def fake_lookup(app_id):
        execution_fields, optional_scopes = original_lookup(app_id)
        if app_id == "optional-test":
            execution_fields = {
                "name": "Optional Test",
                "transport": "oauth",
                "provider_name": "test-provider",
                "oauth_scopes": ["required.scope"],
                "launch_config": {},
            }
            optional_scopes = ["optional.scope"]
        return execution_fields, optional_scopes

    monkeypatch.setattr(
        mcp_apps_module,
        "get_builtin_execution_fields_and_optional_scopes",
        fake_lookup,
    )
    db.add(
        PublicMCPApp(
            app_id="optional-test",
            name="Optional Test",
            description="Optional scope test connector",
            transport="oauth",
            provider_name="test-provider",
            category="Testing",
            oauth_scopes=["required.scope"],
            is_visible_in_connector=True,
            launch_config={},
        )
    )
    db.commit()

    provider = _provider(
        auth_url="https://provider.example.com/authorize",
        default_scopes=["identity.scope"],
        redirect_uri="https://app.example.com/api/auth/test-provider/callback",
    )

    resp = generic_oauth_login(
        provider="test-provider",
        token=token,
        app_id="optional-test",
        redirect=None,
        db=db,
        db_provider=provider,
    )
    qs = parse_qs(urlparse(_location(resp)).query)

    assert qs["scope"] == ["identity.scope required.scope"]
    assert qs["optional_scope"] == ["optional.scope"]


def test_meta_login_uses_config_id_without_scope_when_configured(
    db_session, monkeypatch
):
    db, user = db_session
    token = _token_for(user)
    monkeypatch.setenv("META_CONFIG_ID", "1234567890")
    db.add(
        PublicMCPApp(
            app_id="instagram",
            name="Instagram",
            description="Instagram connector",
            transport="oauth",
            provider_name="meta",
            category="Marketing",
            oauth_scopes=["instagram_basic", "instagram_content_publish"],
            is_visible_in_connector=True,
            launch_config={},
        )
    )
    db.commit()

    provider = _provider(
        auth_url="https://www.facebook.com/v25.0/dialog/oauth",
        default_scopes=["public_profile"],
        redirect_uri="https://app.example.com/api/auth/meta/callback",
    )

    resp = generic_oauth_login(
        provider="meta",
        token=token,
        app_id="instagram",
        redirect=None,
        db=db,
        db_provider=provider,
    )
    qs = parse_qs(urlparse(_location(resp)).query)

    assert qs["config_id"] == ["1234567890"]
    assert "scope" not in qs
    assert "optional_scope" not in qs


def test_meta_login_suppresses_optional_scope_under_config_id(db_session, monkeypatch):
    """config_id mode discards the registry's scope list entirely (the Meta
    Login Configuration is the sole source of truth) - optional_scope must
    be suppressed the same way scope already is, even for an app that DOES
    declare optional_oauth_scopes. No builtin meta-provider app declares
    optional_oauth_scopes today, so the registry lookup is patched to
    simulate one rather than asserting a coincidence of current data."""
    import xagent.web.mcp_apps as mcp_apps_module
    from xagent.web.builtin_mcp_registry import (
        get_builtin_execution_fields_and_optional_scopes,
    )

    def fake_lookup(app_id):
        execution_fields, _ = get_builtin_execution_fields_and_optional_scopes(app_id)
        optional_scopes = ["some_tier_gated_scope"] if app_id == "facebook" else []
        return execution_fields, optional_scopes

    db, user = db_session
    token = _token_for(user)
    monkeypatch.setenv("META_CONFIG_ID", "1234567890")
    monkeypatch.setattr(
        mcp_apps_module,
        "get_builtin_execution_fields_and_optional_scopes",
        fake_lookup,
    )
    db.add(
        PublicMCPApp(
            app_id="facebook",
            name="Facebook Pages",
            description="Facebook connector",
            transport="oauth",
            provider_name="meta",
            category="Marketing",
            oauth_scopes=["pages_show_list"],
            is_visible_in_connector=True,
            launch_config={},
        )
    )
    db.commit()

    provider = _provider(
        auth_url="https://www.facebook.com/v25.0/dialog/oauth",
        default_scopes=["public_profile"],
        redirect_uri="https://app.example.com/api/auth/meta/callback",
    )

    resp = generic_oauth_login(
        provider="meta",
        token=token,
        app_id="facebook",
        redirect=None,
        db=db,
        db_provider=provider,
    )
    qs = parse_qs(urlparse(_location(resp)).query)

    assert qs["config_id"] == ["1234567890"]
    assert "scope" not in qs
    assert "optional_scope" not in qs


def test_meta_login_uses_config_id_without_scope_for_facebook(db_session, monkeypatch):
    """Facebook Pages via config_id: pages_read_user_content is NOT requested.

    In this mode the Login Configuration in the Meta App Dashboard is the sole
    source of truth for granted permissions (see META_CONFIG_ID in example.env)
    - our builtin registry scopes are not sent at all. This test documents that
    gap so a future change to the request-scope path doesn't silently mask it.
    """
    db, user = db_session
    token = _token_for(user)
    monkeypatch.setenv("META_CONFIG_ID", "1234567890")
    db.add(
        PublicMCPApp(
            app_id="facebook",
            name="Facebook Pages",
            description="Facebook connector",
            transport="oauth",
            provider_name="meta",
            category="Marketing",
            oauth_scopes=[
                "pages_show_list",
                "pages_read_engagement",
                "pages_manage_posts",
                "pages_read_user_content",
            ],
            is_visible_in_connector=True,
            launch_config={},
        )
    )
    db.commit()

    provider = _provider(
        auth_url="https://www.facebook.com/v25.0/dialog/oauth",
        default_scopes=["public_profile"],
        redirect_uri="https://app.example.com/api/auth/meta/callback",
    )

    resp = generic_oauth_login(
        provider="meta",
        token=token,
        app_id="facebook",
        redirect=None,
        db=db,
        db_provider=provider,
    )
    qs = parse_qs(urlparse(_location(resp)).query)

    assert qs["config_id"] == ["1234567890"]
    assert "scope" not in qs
    assert "optional_scope" not in qs


def test_facebook_login_uses_its_own_config_id_override(db_session, monkeypatch):
    """Mirrors the meta-ads override test below for META_FACEBOOK_CONFIG_ID,
    which had no dedicated coverage of its own."""
    db, user = db_session
    token = _token_for(user)
    monkeypatch.setenv("META_CONFIG_ID", "shared-config-id")
    monkeypatch.setenv("META_FACEBOOK_CONFIG_ID", "facebook-only-config-id")
    db.add(
        PublicMCPApp(
            app_id="facebook",
            name="Facebook Pages",
            description="Facebook connector",
            transport="oauth",
            provider_name="meta",
            category="Marketing",
            oauth_scopes=["pages_show_list"],
            is_visible_in_connector=True,
            launch_config={},
        )
    )
    db.commit()

    provider = _provider(
        auth_url="https://www.facebook.com/v25.0/dialog/oauth",
        default_scopes=["public_profile"],
        redirect_uri="https://app.example.com/api/auth/meta/callback",
    )

    resp = generic_oauth_login(
        provider="meta",
        token=token,
        app_id="facebook",
        redirect=None,
        db=db,
        db_provider=provider,
    )
    qs = parse_qs(urlparse(_location(resp)).query)

    assert qs["config_id"] == ["facebook-only-config-id"]


def test_instagram_login_uses_its_own_config_id_override(db_session, monkeypatch):
    """Mirrors the meta-ads override test below for META_INSTAGRAM_CONFIG_ID,
    which had no dedicated coverage of its own."""
    db, user = db_session
    token = _token_for(user)
    monkeypatch.setenv("META_CONFIG_ID", "shared-config-id")
    monkeypatch.setenv("META_INSTAGRAM_CONFIG_ID", "instagram-only-config-id")
    db.add(
        PublicMCPApp(
            app_id="instagram",
            name="Instagram",
            description="Instagram connector",
            transport="oauth",
            provider_name="meta",
            category="Marketing",
            oauth_scopes=["instagram_basic"],
            is_visible_in_connector=True,
            launch_config={},
        )
    )
    db.commit()

    provider = _provider(
        auth_url="https://www.facebook.com/v25.0/dialog/oauth",
        default_scopes=["public_profile"],
        redirect_uri="https://app.example.com/api/auth/meta/callback",
    )

    resp = generic_oauth_login(
        provider="meta",
        token=token,
        app_id="instagram",
        redirect=None,
        db=db,
        db_provider=provider,
    )
    qs = parse_qs(urlparse(_location(resp)).query)

    assert qs["config_id"] == ["instagram-only-config-id"]


def test_meta_ads_login_uses_its_own_config_id_override(db_session, monkeypatch):
    """A dedicated META_ADS_CONFIG_ID must take precedence over the shared
    META_CONFIG_ID for the meta-ads app -- otherwise widening the one shared
    Login Configuration to include ads_read would also hand that permission
    to Facebook/Instagram tokens issued from the same configuration."""
    db, user = db_session
    token = _token_for(user)
    monkeypatch.setenv("META_CONFIG_ID", "shared-config-id")
    monkeypatch.setenv("META_ADS_CONFIG_ID", "ads-only-config-id")
    db.add(
        PublicMCPApp(
            app_id="meta-ads",
            name="Meta Ads",
            description="Meta Ads connector",
            transport="oauth",
            provider_name="meta",
            category="Marketing",
            oauth_scopes=["ads_read"],
            is_visible_in_connector=True,
            launch_config={},
        )
    )
    db.commit()

    provider = _provider(
        auth_url="https://www.facebook.com/v25.0/dialog/oauth",
        default_scopes=["public_profile"],
        redirect_uri="https://app.example.com/api/auth/meta/callback",
    )

    resp = generic_oauth_login(
        provider="meta",
        token=token,
        app_id="meta-ads",
        redirect=None,
        db=db,
        db_provider=provider,
    )
    qs = parse_qs(urlparse(_location(resp)).query)

    assert qs["config_id"] == ["ads-only-config-id"]
    assert "scope" not in qs


def test_meta_ads_login_falls_back_to_shared_config_id_when_unset(
    db_session, monkeypatch
):
    """Without a dedicated META_ADS_CONFIG_ID, Meta Ads still falls back to
    the shared META_CONFIG_ID -- preserving existing deployments that
    haven't split their Login Configurations out per app."""
    db, user = db_session
    token = _token_for(user)
    monkeypatch.setenv("META_CONFIG_ID", "shared-config-id")
    monkeypatch.delenv("META_ADS_CONFIG_ID", raising=False)
    db.add(
        PublicMCPApp(
            app_id="meta-ads",
            name="Meta Ads",
            description="Meta Ads connector",
            transport="oauth",
            provider_name="meta",
            category="Marketing",
            oauth_scopes=["ads_read"],
            is_visible_in_connector=True,
            launch_config={},
        )
    )
    db.commit()

    provider = _provider(
        auth_url="https://www.facebook.com/v25.0/dialog/oauth",
        default_scopes=["public_profile"],
        redirect_uri="https://app.example.com/api/auth/meta/callback",
    )

    resp = generic_oauth_login(
        provider="meta",
        token=token,
        app_id="meta-ads",
        redirect=None,
        db=db,
        db_provider=provider,
    )
    qs = parse_qs(urlparse(_location(resp)).query)

    assert qs["config_id"] == ["shared-config-id"]


def test_meta_ads_login_config_id_override_survives_admin_app_id_casing(
    db_session, monkeypatch
):
    """An admin-created app row's app_id is free-form (e.g. "Meta Ads" with
    a space/capitals, still normalizing to "meta-ads" for the app-scoped
    OAuth grant policy in mcp_apps.py). The config_id override lookup must
    normalize the same way, or a differently-cased app_id would silently
    miss META_ADS_CONFIG_ID and fall back to the shared META_CONFIG_ID --
    reintroducing exactly the cross-app capability sharing the per-app
    override exists to prevent."""
    db, user = db_session
    token = _token_for(user)
    monkeypatch.setenv("META_CONFIG_ID", "shared-config-id")
    monkeypatch.setenv("META_ADS_CONFIG_ID", "ads-only-config-id")
    db.add(
        PublicMCPApp(
            app_id="Meta Ads",
            name="Meta Ads",
            description="Meta Ads connector",
            transport="oauth",
            provider_name="meta",
            category="Marketing",
            oauth_scopes=["ads_read"],
            is_visible_in_connector=True,
            launch_config={},
        )
    )
    db.commit()

    provider = _provider(
        auth_url="https://www.facebook.com/v25.0/dialog/oauth",
        default_scopes=["public_profile"],
        redirect_uri="https://app.example.com/api/auth/meta/callback",
    )

    resp = generic_oauth_login(
        provider="meta",
        token=token,
        app_id="Meta Ads",
        redirect=None,
        db=db,
        db_provider=provider,
    )
    qs = parse_qs(urlparse(_location(resp)).query)

    assert qs["config_id"] == ["ads-only-config-id"]


def test_whatsapp_login_uses_its_own_config_id_override(db_session, monkeypatch):
    """A dedicated META_WHATSAPP_CONFIG_ID must take precedence over the
    shared META_CONFIG_ID for the whatsapp app -- otherwise widening the one
    shared Login Configuration to include WhatsApp's business_management /
    whatsapp_business_management / whatsapp_business_messaging scopes would
    also hand those permissions to Facebook/Instagram/Meta Ads tokens issued
    from the same configuration."""
    db, user = db_session
    token = _token_for(user)
    monkeypatch.setenv("META_CONFIG_ID", "shared-config-id")
    monkeypatch.setenv("META_WHATSAPP_CONFIG_ID", "whatsapp-only-config-id")
    db.add(
        PublicMCPApp(
            app_id="whatsapp",
            name="WhatsApp Business",
            description="WhatsApp connector",
            transport="oauth",
            provider_name="meta",
            category="Marketing",
            oauth_scopes=["whatsapp_business_messaging"],
            is_visible_in_connector=True,
            launch_config={},
        )
    )
    db.commit()

    provider = _provider(
        auth_url="https://www.facebook.com/v25.0/dialog/oauth",
        default_scopes=["public_profile"],
        redirect_uri="https://app.example.com/api/auth/meta/callback",
    )

    resp = generic_oauth_login(
        provider="meta",
        token=token,
        app_id="whatsapp",
        redirect=None,
        db=db,
        db_provider=provider,
    )
    qs = parse_qs(urlparse(_location(resp)).query)

    assert qs["config_id"] == ["whatsapp-only-config-id"]
    assert "scope" not in qs


def test_whatsapp_login_falls_back_to_shared_config_id_when_unset(
    db_session, monkeypatch
):
    """Mirrors the meta-ads equivalent above: without a dedicated
    META_WHATSAPP_CONFIG_ID, whatsapp still falls back to the shared
    META_CONFIG_ID -- preserving existing deployments that haven't split
    their Login Configurations out per app."""
    db, user = db_session
    token = _token_for(user)
    monkeypatch.setenv("META_CONFIG_ID", "shared-config-id")
    monkeypatch.delenv("META_WHATSAPP_CONFIG_ID", raising=False)
    db.add(
        PublicMCPApp(
            app_id="whatsapp",
            name="WhatsApp Business",
            description="WhatsApp connector",
            transport="oauth",
            provider_name="meta",
            category="Marketing",
            oauth_scopes=["whatsapp_business_messaging"],
            is_visible_in_connector=True,
            launch_config={},
        )
    )
    db.commit()

    provider = _provider(
        auth_url="https://www.facebook.com/v25.0/dialog/oauth",
        default_scopes=["public_profile"],
        redirect_uri="https://app.example.com/api/auth/meta/callback",
    )

    resp = generic_oauth_login(
        provider="meta",
        token=token,
        app_id="whatsapp",
        redirect=None,
        db=db,
        db_provider=provider,
    )
    qs = parse_qs(urlparse(_location(resp)).query)

    assert qs["config_id"] == ["shared-config-id"]


def test_whatsapp_login_config_id_override_survives_admin_app_id_casing(
    db_session, monkeypatch
):
    """Mirrors the meta-ads equivalent above: an admin-created app row's
    app_id is free-form (e.g. "WhatsApp" with different casing/spacing,
    still normalizing to "whatsapp" for the app-scoped OAuth grant policy in
    mcp_apps.py). The config_id override lookup must normalize the same
    way, or a differently-cased app_id would silently miss
    META_WHATSAPP_CONFIG_ID and fall back to the shared META_CONFIG_ID."""
    db, user = db_session
    token = _token_for(user)
    monkeypatch.setenv("META_CONFIG_ID", "shared-config-id")
    monkeypatch.setenv("META_WHATSAPP_CONFIG_ID", "whatsapp-only-config-id")
    db.add(
        PublicMCPApp(
            app_id="WhatsApp",
            name="WhatsApp Business",
            description="WhatsApp connector",
            transport="oauth",
            provider_name="meta",
            category="Marketing",
            oauth_scopes=["whatsapp_business_messaging"],
            is_visible_in_connector=True,
            launch_config={},
        )
    )
    db.commit()

    provider = _provider(
        auth_url="https://www.facebook.com/v25.0/dialog/oauth",
        default_scopes=["public_profile"],
        redirect_uri="https://app.example.com/api/auth/meta/callback",
    )

    resp = generic_oauth_login(
        provider="meta",
        token=token,
        app_id="WhatsApp",
        redirect=None,
        db=db,
        db_provider=provider,
    )
    qs = parse_qs(urlparse(_location(resp)).query)

    assert qs["config_id"] == ["whatsapp-only-config-id"]


def test_meta_login_ignores_undocumented_legacy_config_id_alias(
    db_session, monkeypatch
):
    db, user = db_session
    token = _token_for(user)
    monkeypatch.delenv("META_CONFIG_ID", raising=False)
    monkeypatch.setenv("META_LOGIN_CONFIG_ID", "legacy-config-id")

    provider = _provider(
        auth_url="https://www.facebook.com/v25.0/dialog/oauth",
        default_scopes=["public_profile"],
        redirect_uri="https://app.example.com/api/auth/meta/callback",
    )

    resp = generic_oauth_login(
        provider="meta",
        token=token,
        app_id=None,
        redirect=None,
        db=db,
        db_provider=provider,
    )
    qs = parse_qs(urlparse(_location(resp)).query)

    assert "config_id" not in qs
    assert qs["scope"] == ["public_profile"]


def test_login_uses_env_client_id_when_provider_client_id_is_empty(
    db_session, monkeypatch
):
    db, user = db_session
    token = _token_for(user)
    monkeypatch.setenv("MICROSOFT_CLIENT_ID", "env-client-id")

    provider = _provider(
        auth_url="https://login.microsoftonline.com/common/oauth2/v2.0/authorize",
        default_scopes=["User.Read"],
        redirect_uri="https://app.example.com/cb",
        client_id="",
    )

    resp = generic_oauth_login(
        provider="microsoft",
        token=token,
        app_id=None,
        redirect=None,
        db=db,
        db_provider=provider,
    )
    qs = parse_qs(urlparse(_location(resp)).query)

    assert qs["client_id"] == ["env-client-id"]


@pytest.mark.parametrize("encrypted_value", [None, ""])
def test_resolve_oauth_secret_uses_env_without_decrypting_empty_values(
    encrypted_value, monkeypatch
):
    from xagent.core.utils import encryption

    def fail_on_empty_decrypt(value: str) -> str:
        if not value:
            raise ValueError("empty values should not be decrypted")
        return "db-secret"

    monkeypatch.setattr(encryption, "decrypt_value", fail_on_empty_decrypt)
    monkeypatch.setenv("MICROSOFT_CLIENT_SECRET", "env-secret")

    assert (
        _resolve_oauth_secret("microsoft", encrypted_value, "CLIENT_SECRET")
        == "env-secret"
    )


def test_resolve_oauth_secret_normalizes_hyphenated_provider_env_name(monkeypatch):
    """A hyphenated provider_name (e.g. "employment-hero", or an admin-
    created "-sandbox" variant of any family) must map to the same
    underscored env var name every deployment already documents -- env vars
    can't contain "-" at all, so an unnormalized lookup (EMPLOYMENT-HERO_...)
    would never match anything a real deployment could set, permanently
    breaking this fallback for every hyphenated provider."""
    monkeypatch.setenv("EMPLOYMENT_HERO_CLIENT_SECRET", "env-secret")

    assert (
        _resolve_oauth_secret("employment-hero", None, "CLIENT_SECRET") == "env-secret"
    )


def test_login_fails_locally_when_client_id_is_missing(db_session, monkeypatch):
    db, user = db_session
    token = _token_for(user)
    monkeypatch.delenv("MICROSOFT_CLIENT_ID", raising=False)

    provider = _provider(
        auth_url="https://login.microsoftonline.com/common/oauth2/v2.0/authorize",
        default_scopes=["User.Read"],
        redirect_uri="https://app.example.com/cb",
        client_id="",
    )

    resp = generic_oauth_login(
        provider="microsoft",
        token=token,
        app_id=None,
        redirect=None,
        db=db,
        db_provider=provider,
    )

    assert resp.status_code == 500
    assert "MICROSOFT_CLIENT_ID" in resp.body.decode()


def test_deputy_login_sends_scope_and_omits_pkce(db_session):
    """generic_oauth_login has no Deputy-specific branch (its
    longlife_refresh_token scope flows through the existing generic
    default_scopes -> scope_str path) -- this locks that in, since nothing
    previously exercised generic_oauth_login with provider="deputy" at
    all (only the callback side had coverage)."""
    db, user = db_session
    token = _token_for(user)

    provider = _provider(
        auth_url="https://once.deputy.com/my/oauth/login",
        default_scopes=["longlife_refresh_token"],
        redirect_uri="https://app.example.com/api/auth/deputy/callback",
    )

    resp = generic_oauth_login(
        provider="deputy",
        token=token,
        app_id=None,
        redirect=None,
        db=db,
        db_provider=provider,
    )
    location = _location(resp)
    qs = parse_qs(urlparse(location).query)

    assert location.startswith("https://once.deputy.com/my/oauth/login?")
    assert qs.get("scope") == ["longlife_refresh_token"]
    assert qs.get("response_type") == ["code"]
    assert "code_challenge" not in qs
    assert "code_challenge_method" not in qs
    state_payload = verify_token(qs["state"][0])
    assert "code_verifier" not in state_payload