from __future__ import annotations import uuid import pytest from app.core.exceptions import AppException from app.domains.data_access.approval_flow import ( resolve_data_access_group_grant_flow, ) from app.domains.data_access.constants import ( APPROVAL_FLOW_DATA_ACCESS_GROUP_GRANT, ) from app.integrations.models import Integration, IntegrationApprovalFlow async def _seed_feishu_integration( db_session, *, active: bool = True, accept_external_origin: bool = False, flow_key: str = APPROVAL_FLOW_DATA_ACCESS_GROUP_GRANT, ) -> IntegrationApprovalFlow: integration = Integration( id=uuid.uuid4(), kind="chat_approval", provider="feishu", name="Feishu Approval", slug=f"feishu-data-access-{uuid.uuid4().hex[:8]}", enabled=True, is_primary=True, config_public={"app_id": "cli_data_access_test"}, ) db_session.add(integration) await db_session.flush() flow = IntegrationApprovalFlow( id=uuid.uuid4(), integration_id=integration.id, flow_key=flow_key, label="Data access group grant", external_code="DATA-ACCESS-GROUP-GRANT-CODE", payload_schema={"dataset_ids": "widget_dataset_ids"}, active=active, accept_external_origin=accept_external_origin, ) db_session.add(flow) await db_session.commit() return flow @pytest.mark.asyncio async def test_resolves_active_data_access_group_grant_mapping(db_session): await _seed_feishu_integration(db_session) flow = await resolve_data_access_group_grant_flow(session=db_session) assert flow.flow_key == APPROVAL_FLOW_DATA_ACCESS_GROUP_GRANT assert flow.external_code == "DATA-ACCESS-GROUP-GRANT-CODE" assert flow.payload_schema == {"dataset_ids": "widget_dataset_ids"} @pytest.mark.asyncio async def test_missing_data_access_group_grant_mapping_fails_closed(db_session): await _seed_feishu_integration( db_session, flow_key="cloud_scope_request", ) with pytest.raises(AppException) as exc_info: await resolve_data_access_group_grant_flow(session=db_session) assert exc_info.value.code == "APPROVAL_FLOW_NOT_CONFIGURED" assert exc_info.value.status_code == 503 @pytest.mark.asyncio async def test_inactive_data_access_group_grant_mapping_fails_closed(db_session): await _seed_feishu_integration(db_session, active=False) with pytest.raises(AppException) as exc_info: await resolve_data_access_group_grant_flow(session=db_session) assert exc_info.value.code == "APPROVAL_FLOW_NOT_CONFIGURED" assert exc_info.value.status_code == 503 @pytest.mark.asyncio async def test_data_access_flow_rejects_external_feishu_origin(db_session): await _seed_feishu_integration( db_session, accept_external_origin=True, ) with pytest.raises(AppException) as exc_info: await resolve_data_access_group_grant_flow(session=db_session) assert ( exc_info.value.code == "DATA_ACCESS_APPROVAL_FLOW_EXTERNAL_ORIGIN_FORBIDDEN" ) assert exc_info.value.status_code == 503