: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add CodeScene source (#73187)
Tom Owers9b5c7fe0577d
diff --git a/frontend/public/services/codescene.png b/frontend/public/services/codescene.pngindex c5736e43b50d..d289366c81f3 100644Binary files a/frontend/public/services/codescene.png and b/frontend/public/services/codescene.png differdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 71f0c6f14bfa..2f6f3f2df107 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -131,6 +131,7 @@ the row lists both.| codacy | HTTP | requests | ✅ || codecov | HTTP | requests | ✅ || codefresh | HTTP | requests | ✅ |+| codescene | HTTP | requests + `rest_source.RESTClient` | ✅ || cody | HTTP (CSV reports) | requests | ✅ || cohere | HTTP | requests | ✅ || coin_api | HTTP | requests | ✅ |@@ -845,7 +846,6 @@ doesn't conflict with concurrent PRs.- codacy- codecov- codemagic-- codescene- collibra- companycam- conektadiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/codescene/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/codescene/canonical_descriptions.pynew file mode 100644index 000000000000..fe0482d6c255--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/codescene/canonical_descriptions.py@@ -0,0 +1,38 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "Projects": {+ "description": "A CodeScene project: a configured set of Git repositories analyzed together as one codebase.",+ "docs_url": "https://docs.enterprise.codescene.io/latest/integrations/rest-api.html",+ "columns": {+ "id": "Unique identifier for the project.",+ "name": "Name of the project as configured in CodeScene.",+ },+ },+ "Files": {+ "description": "Per-file Code Health, change frequency, defect, and cost-of-change metrics from a project's latest analysis.",+ "docs_url": "https://docs.enterprise.codescene.io/latest/integrations/rest-api.html",+ "columns": {+ "project_id": "Identifier of the CodeScene project this file belongs to.",+ "name": "Repository-relative path of the file.",+ "code_health": "Code Health score for the file (1-10, 10 being the healthiest).",+ "change_frequency": "How often the file has changed, relative to the rest of the codebase.",+ "lines_of_code": "Number of lines of code in the file.",+ "number_of_defects": "Number of defects (bug-fix commits) recorded against the file.",+ "cost": "Estimated cost-of-change score for the file.",+ },+ },+ "Components": {+ "description": "Architectural components (logical groupings of files) and their aggregate system-health metrics from a project's latest analysis.",+ "docs_url": "https://docs.enterprise.codescene.io/latest/integrations/rest-api.html",+ "columns": {+ "project_id": "Identifier of the CodeScene project this component belongs to.",+ "name": "Name of the architectural component.",+ "system_health": "Aggregate Code Health score for the component.",+ "change_frequency": "How often files in the component have changed, relative to the rest of the codebase.",+ "lines_of_code": "Number of lines of code in the component.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/codescene/codescene.py b/products/warehouse_sources/backend/temporal/data_imports/sources/codescene/codescene.pynew file mode 100644index 000000000000..9c1053444b82--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/codescene/codescene.py@@ -0,0 +1,257 @@+import re+import dataclasses+from collections.abc import Iterable+from typing import Any, Optional, cast+from urllib.parse import urlparse++from requests.exceptions import RequestException++from posthog.cloud_utils import is_cloud++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.codescene.settings import CODESCENE_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import _is_host_safe+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ build_dependent_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ PageNumberPaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ EndpointResource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager++REQUEST_TIMEOUT_SECONDS = 30++DEFAULT_BASE_URL = "https://api.codescene.io/v2"+++class CodesceneResumeConfig:+ # 1-indexed next page to fetch. Only used for the flat (non-fan-out) "Projects"+ # endpoint — dependent (fan-out) resources don't currently support resume.+ next_page: Optional[int] = None+++def normalize_base_url(base_url: str | None) -> str:+ """Turn whatever the user typed into a bare CodeScene API v2 base URL.++ Defaults to CodeScene Cloud. Accepts a bare host, a full URL, or a URL that already+ includes the `/api/v2` (on-prem) or `/v2` (cloud) suffix, and normalizes to just the+ scheme + host (+ port) + the versioned API path.+ """+ cleaned = (base_url or "").strip()+ if not cleaned:+ return DEFAULT_BASE_URL+ if "://" not in cleaned:+ cleaned = f"https://{cleaned}"+ cleaned = cleaned.rstrip("/")+ if cleaned.endswith("/api/v2") or cleaned.endswith("/v2"):+ return cleaned+ return f"{cleaned}/api/v2"+++def hostname_of(base_url: str | None) -> str:+ return urlparse(normalize_base_url(base_url)).hostname or ""+++# urlparse and requests disagree on ambiguous authorities: a backslash (raw or percent-encoded)+# reads as a path separator to requests but not to urlparse, and userinfo lets the visible host+# differ from the one actually dialed. Either lets a URL that looks safe to `_is_host_safe` connect+# somewhere else, so reject them before the host is derived.+_BACKSLASH = re.compile(r"\\|%5c", re.IGNORECASE)+++def _validate_base_url(base_url: str | None) -> tuple[bool, str | None]:+ """Structurally validate a user-supplied CodeScene base URL before it derives a host or carries+ the API token. A blank value means CodeScene Cloud and is always allowed."""+ raw = (base_url or "").strip()+ if not raw:+ return True, None++ normalized = normalize_base_url(base_url)+ if _BACKSLASH.search(raw) or _BACKSLASH.search(normalized):+ return False, "The CodeScene API base URL can't contain backslashes."++ parsed = urlparse(normalized)+ if parsed.scheme not in ("http", "https"):+ return False, "The CodeScene API base URL must start with http:// or https://."+ if not parsed.hostname:+ return False, "The CodeScene API base URL must include a host."+ if parsed.username is not None or parsed.password is not None or "@" in parsed.netloc:+ return False, "The CodeScene API base URL can't include a username or password."+ if parsed.query or parsed.fragment:+ return False, "The CodeScene API base URL can't include a query string or fragment."+ # The token rides in the Authorization header, so on cloud it must never cross plaintext HTTP.+ # Self-hosted instances may reach an internal on-prem server over HTTP.+ if is_cloud() and parsed.scheme != "https":+ return False, "The CodeScene API base URL must use HTTPS."++ return True, None+++def _check_base_url(base_url: str | None, team_id: int) -> tuple[bool, str | None]:+ """Full pre-request gate: structural validation followed by the SSRF host check. Run immediately+ before any credential-bearing request so an edited config or DNS change can't slip past."""+ structural_ok, structural_err = _validate_base_url(base_url)+ if not structural_ok:+ return False, structural_err+ return _is_host_safe(hostname_of(base_url), team_id)+++def _headers(api_token: str) -> dict[str, str]:+ return {"Authorization": f"Bearer {api_token}", "Accept": "application/json"}+++def _client_config(base_url: str | None, api_token: str) -> ClientConfig:+ return {+ "base_url": normalize_base_url(base_url),+ "auth": {"type": "bearer", "token": api_token},+ "headers": {"Accept": "application/json"},+ }+++def _page_paginator() -> PageNumberPaginator:+ # CodeScene's paginated list endpoints default to page 1 and report `max_pages` in the+ # response body so the last page can be detected without an extra empty-page request.+ return PageNumberPaginator(base_page=1, page=1, page_param="page", total_path="max_pages")+++def validate_credentials(api_token: str, base_url: str | None, team_id: int) -> tuple[bool, str | None]:+ host_ok, host_err = _check_base_url(base_url, team_id)+ if not host_ok:+ return False, host_err++ url = f"{normalize_base_url(base_url)}/projects"+ try:+ response = make_tracked_session(redact_values=(api_token,)).get(+ url,+ headers=_headers(api_token),+ params={"page": 1, "page_size": 1},+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ except RequestException as exc:+ return False, str(exc)++ if response.status_code == 200:+ return True, None+ if response.status_code == 401:+ return False, "Invalid CodeScene API token"+ if response.status_code == 403:+ return False, "CodeScene API token does not have the Admin, Architect, or RestApi role required by the API"+ return False, f"Could not connect to CodeScene (HTTP {response.status_code})"+++def _get_resource(endpoint: str) -> EndpointResource:+ config = CODESCENE_ENDPOINTS[endpoint]+ return {+ "name": config.name,+ "table_name": config.name,+ "write_disposition": "replace",+ "endpoint": {+ "path": config.path,+ "params": {"page_size": config.page_size},+ "data_selector": config.data_selector,+ # The wrapper key is documented, so a response without it means the API shape+ # changed — fail loud rather than silently syncing 0 rows.+ "data_selector_required": True,+ "paginator": _page_paginator(),+ },+ "table_format": "delta",+ }+++def _primary_keys(endpoint: str) -> list[str]:+ primary_key = CODESCENE_ENDPOINTS[endpoint].primary_key+ return primary_key if isinstance(primary_key, list) else [primary_key]+++def codescene_source(+ api_token: str,+ base_url: str | None,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[CodesceneResumeConfig],+) -> SourceResponse:+ # Re-check right before issuing requests: validate_credentials ran when the source was first+ # configured, but the config can be edited afterwards and DNS can change, so the SSRF/plaintext+ # guard must hold at sync time too.+ base_url_ok, base_url_err = _check_base_url(base_url, team_id)+ if not base_url_ok:+ raise ValueError(base_url_err)++ endpoint_config = CODESCENE_ENDPOINTS[endpoint]+ client_config = _client_config(base_url, api_token)++ if endpoint_config.fanout:+ parent_config = CODESCENE_ENDPOINTS[endpoint_config.fanout.parent_name]+ # Fan-out resources don't currently support resume in the shared framework — the+ # (usually small) list of projects is re-fetched each run and files/components are+ # replaced wholesale, so no resumable_source_manager state is threaded through here.+ resource = cast(+ Iterable[Any],+ build_dependent_resource(+ endpoint_configs=CODESCENE_ENDPOINTS,+ child_endpoint=endpoint,+ fanout=endpoint_config.fanout,+ client_config=client_config,+ path_format_values={},+ team_id=team_id,+ job_id=job_id,+ db_incremental_field_last_value=None,+ page_size_param="page_size",+ parent_endpoint_extra={+ "data_selector": parent_config.data_selector,+ "data_selector_required": True,+ "paginator": _page_paginator(),+ },+ child_endpoint_extra={+ "data_selector": endpoint_config.data_selector,+ "data_selector_required": True,+ "paginator": _page_paginator(),+ },+ ),+ )+ return SourceResponse(+ name=endpoint_config.name,+ items=lambda: resource,+ primary_keys=_primary_keys(endpoint),+ )++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume_config = resumable_source_manager.load_state()+ if resume_config is not None and resume_config.next_page is not None:+ initial_paginator_state = {"page": resume_config.next_page}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ if state and state.get("page") is not None:+ resumable_source_manager.save_state(CodesceneResumeConfig(next_page=int(state["page"])))++ config: RESTAPIConfig = {+ "client": client_config,+ "resource_defaults": {},+ "resources": [_get_resource(endpoint)],+ }++ resource = rest_api_resource(+ config,+ team_id,+ job_id,+ None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )+ return SourceResponse(+ name=endpoint_config.name,+ items=lambda: resource,+ primary_keys=_primary_keys(endpoint),+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/codescene/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/codescene/settings.pynew file mode 100644index 000000000000..a37aa52bc554--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/codescene/settings.py@@ -0,0 +1,63 @@+from dataclasses import dataclass, field++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)+from products.warehouse_sources.backend.types import IncrementalField++# CodeScene has no documented server-side timestamp filter for these endpoints (the `analyses`+# list/detail shape isn't publicly documented), so every endpoint here is full refresh only.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}+++@dataclass+class CodesceneEndpointConfig:+ name: str+ path: str+ # Key holding the row array in the response body (e.g. `{"projects": [...], "max_pages": 3}`).+ data_selector: str+ primary_key: str | list[str] = "id"+ page_size: int = 100+ fanout: DependentEndpointConfig | None = None+ # No endpoint here has a documented server-side timestamp filter, so every stream is full+ # refresh; these stay empty but satisfy the fan-out helper's endpoint protocol.+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ default_incremental_field: str | None = None+++CODESCENE_ENDPOINTS: dict[str, CodesceneEndpointConfig] = {+ "Projects": CodesceneEndpointConfig(+ name="Projects",+ path="/projects",+ data_selector="projects",+ primary_key="id",+ ),+ "Files": CodesceneEndpointConfig(+ name="Files",+ path="/projects/{project_id}/analyses/latest/files",+ data_selector="files",+ primary_key=["project_id", "name"],+ fanout=DependentEndpointConfig(+ parent_name="Projects",+ resolve_param="project_id",+ resolve_field="id",+ include_from_parent=["id"],+ parent_field_renames={"id": "project_id"},+ ),+ ),+ "Components": CodesceneEndpointConfig(+ name="Components",+ path="/projects/{project_id}/analyses/latest/components",+ data_selector="components",+ primary_key=["project_id", "name"],+ fanout=DependentEndpointConfig(+ parent_name="Projects",+ resolve_param="project_id",+ resolve_field="id",+ include_from_parent=["id"],+ parent_field_renames={"id": "project_id"},+ ),+ ),+}++ENDPOINTS = tuple(CODESCENE_ENDPOINTS)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/codescene/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/codescene/source.pyindex 3ee5d03e8e23..244f86a1be6c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/codescene/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/codescene/source.py@@ -1,13 +1,37 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.codescene.codescene import (+ CodesceneResumeConfig,+ codescene_source,+ validate_credentials as validate_codescene_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.codescene.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.codescene import (CodesceneSourceConfig,)@@ -15,18 +39,103 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class CodesceneSource(SimpleSource[CodesceneSourceConfig]):+class CodesceneSource(ResumableSource[CodesceneSourceConfig, CodesceneResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ supported_versions = ("v2",)+ default_version = "v2"+ api_docs_url = "https://docs.enterprise.codescene.io/latest/integrations/rest-api.html"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.CODESCENE+ @property+ def connection_host_fields(self) -> list[str]:+ # `base_url` is where the stored API token is sent; retargeting it must re-require the token.+ return ["base_url"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.CODESCENE,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="CodeScene",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Sync projects, per-file Code Health metrics, and architectural components from CodeScene.++Create a Personal Access Token from the CodeScene API tokens page with an Admin, Architect, or RestApi role. Leave the API base URL blank to use CodeScene Cloud, or enter your on-prem CodeScene server's API URL (for example `https://codescene.yourcompany.com:3003/api/v2`).""",iconPath="/static/services/codescene.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/codescene",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_token",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="base_url",+ label="API base URL",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="https://api.codescene.io/v2",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.codescene.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Your CodeScene API token is invalid or has expired. Generate a new token from the CodeScene API tokens page, then reconnect.",+ "403 Client Error": "Your CodeScene API token does not have the Admin, Architect, or RestApi role required by the API. Update the token's role, then reconnect.",+ }++ def get_schemas(+ self,+ config: CodesceneSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)++ def validate_credentials(+ self,+ config: CodesceneSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_codescene_credentials(config.api_token, config.base_url, team_id)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CodesceneResumeConfig]:+ return ResumableSourceManager[CodesceneResumeConfig](inputs, CodesceneResumeConfig)++ def source_for_pipeline(+ self,+ config: CodesceneSourceConfig,+ resumable_source_manager: ResumableSourceManager[CodesceneResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return codescene_source(+ api_token=config.api_token,+ base_url=config.base_url,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/codescene/tests/test_codescene.py b/products/warehouse_sources/backend/temporal/data_imports/sources/codescene/tests/test_codescene.pynew file mode 100644index 000000000000..21d4c24b7aee--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/codescene/tests/test_codescene.py@@ -0,0 +1,301 @@+from typing import Any, cast++import pytest+from unittest.mock import MagicMock, Mock, patch++from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.codescene import codescene as codescene_module+from products.warehouse_sources.backend.temporal.data_imports.sources.codescene.codescene import (+ CodesceneResumeConfig,+ codescene_source,+ hostname_of,+ normalize_base_url,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.codescene.settings import CODESCENE_ENDPOINTS+++class _FakeDltResource:+ """Lightweight stand-in for a DltResource returned by rest_api_resources.++ ``process_parent_data_item`` injects parent fields as ``_<parent_resource>_<field>``+ (see ``make_parent_key_name``), so test data should include those prefixed keys to+ exercise the row mappers.+ """++ def __init__(self, name: str, rows: list[dict]) -> None:+ self.name = name+ self._rows = rows++ def add_map(self, mapper: Any) -> "_FakeDltResource":+ self._rows = [mapper(dict(row)) for row in self._rows]+ return self++ def __iter__(self) -> Any:+ return iter(self._rows)+++def _make_fake_manager(can_resume: bool = False, state: CodesceneResumeConfig | None = None) -> MagicMock:+ manager = MagicMock()+ manager.can_resume.return_value = can_resume+ manager.load_state.return_value = state+ return manager+++class TestNormalizeBaseUrl:+ def test_defaults_to_cloud(self) -> None:+ assert normalize_base_url(None) == "https://api.codescene.io/v2"+ assert normalize_base_url("") == "https://api.codescene.io/v2"++ @parameterized.expand(+ [+ ("bare_host", "codescene.example.com:3003", "https://codescene.example.com:3003/api/v2"),+ ("scheme_no_path", "http://codescene.example.com:3003", "http://codescene.example.com:3003/api/v2"),+ (+ "already_has_api_v2",+ "https://codescene.example.com:3003/api/v2",+ "https://codescene.example.com:3003/api/v2",+ ),+ (+ "trailing_slash",+ "https://codescene.example.com:3003/api/v2/",+ "https://codescene.example.com:3003/api/v2",+ ),+ ("cloud_v2_suffix", "https://api.codescene.io/v2/", "https://api.codescene.io/v2"),+ ]+ )+ def test_normalizes_variants(self, _name: str, given: str, expected: str) -> None:+ assert normalize_base_url(given) == expected++ def test_hostname_of(self) -> None:+ assert hostname_of("https://codescene.example.com:3003/api/v2") == "codescene.example.com"+ assert hostname_of(None) == "api.codescene.io"+++class TestValidateCredentials:+ def _patch_session(self, response: Mock) -> Any:+ mock_session = MagicMock()+ mock_session.get.return_value = response+ return patch.object(codescene_module, "make_tracked_session", return_value=mock_session)++ @parameterized.expand(+ [+ ("ok", 200, True, None),+ ("unauthorized", 401, False, "Invalid CodeScene API token"),+ ("forbidden", 403, False, "does not have the Admin, Architect, or RestApi role"),+ ("server_error", 500, False, "Could not connect to CodeScene"),+ ]+ )+ def test_status_mapping(+ self, _name: str, status_code: int, expect_valid: bool, message_fragment: str | None+ ) -> None:+ response = Mock(status_code=status_code)+ with self._patch_session(response):+ valid, message = validate_credentials("token", None, team_id=1)+ assert valid is expect_valid+ if message_fragment:+ assert message_fragment in (message or "")++ def test_request_exception_returns_failure(self) -> None:+ import requests++ mock_session = MagicMock()+ mock_session.get.side_effect = requests.exceptions.ConnectionError("boom")+ with patch.object(codescene_module, "make_tracked_session", return_value=mock_session):+ valid, message = validate_credentials("token", None, team_id=1)+ assert valid is False+ assert "boom" in (message or "")++ def test_blocks_unsafe_host(self) -> None:+ with (+ patch.object(codescene_module, "_is_host_safe", return_value=(False, "internal address")),+ self._patch_session(Mock(status_code=200)) as patched_session,+ ):+ valid, message = validate_credentials("token", "https://10.0.0.1", team_id=1)+ assert valid is False+ assert message == "internal address"+ patched_session.return_value.get.assert_not_called()++ @parameterized.expand(+ [+ # urlparse reads the host as example.com, but requests dials 169.254.169.254 — reject+ # the ambiguous authority before it reaches the host check or carries the token.+ ("percent_encoded_backslash", "http://169.254.169.254%[email protected]"),+ ("raw_backslash", "http://169.254.169.254\\@example.com"),+ ("userinfo", "https://user:[email protected]"),+ ("query_string", "https://codescene.example.com/api/v2?x=1"),+ ("bad_scheme", "ftp://codescene.example.com"),+ ]+ )+ def test_rejects_ambiguous_base_url_without_requesting(self, _name: str, base_url: str) -> None:+ # A structurally invalid URL must be rejected before any credential-bearing request.+ with self._patch_session(Mock(status_code=200)) as patched_session:+ valid, message = validate_credentials("token", base_url, team_id=1)+ assert valid is False+ assert message+ patched_session.return_value.get.assert_not_called()++ def test_cloud_requires_https(self) -> None:+ with (+ patch.object(codescene_module, "is_cloud", return_value=True),+ self._patch_session(Mock(status_code=200)) as patched_session,+ ):+ valid, message = validate_credentials("token", "http://codescene.example.com", team_id=1)+ assert valid is False+ assert message and "HTTPS" in message+ patched_session.return_value.get.assert_not_called()++ def test_self_hosted_allows_http(self) -> None:+ with (+ patch.object(codescene_module, "is_cloud", return_value=False),+ self._patch_session(Mock(status_code=200)) as patched_session,+ ):+ valid, _message = validate_credentials("token", "http://codescene.example.com", team_id=1)+ assert valid is True+ patched_session.return_value.get.assert_called_once()+++class TestCodesceneSourceFlatEndpoint:+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.codescene.codescene.rest_api_resource")+ def test_projects_resource_config(self, mock_rest_api_resource: MagicMock) -> None:+ mock_rest_api_resource.return_value = _FakeDltResource("Projects", [{"id": "p1", "name": "demo"}])++ response = codescene_source(+ api_token="token",+ base_url=None,+ endpoint="Projects",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=_make_fake_manager(),+ )++ assert response.name == "Projects"+ assert response.primary_keys == ["id"]+ config = mock_rest_api_resource.call_args.args[0]+ assert config["client"]["base_url"] == "https://api.codescene.io/v2"+ assert config["client"]["auth"] == {"type": "bearer", "token": "token"}+ resource = config["resources"][0]+ assert resource["endpoint"]["path"] == "/projects"+ assert resource["endpoint"]["params"] == {"page_size": 100}+ assert resource["endpoint"]["data_selector"] == "projects"+ assert resource["endpoint"]["data_selector_required"] is True++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.codescene.codescene.rest_api_resource")+ def test_resume_state_seeds_paginator(self, mock_rest_api_resource: MagicMock) -> None:+ mock_rest_api_resource.return_value = _FakeDltResource("Projects", [])+ manager = _make_fake_manager(can_resume=True, state=CodesceneResumeConfig(next_page=4))++ codescene_source(+ api_token="token",+ base_url=None,+ endpoint="Projects",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=manager,+ )++ assert mock_rest_api_resource.call_args.kwargs["initial_paginator_state"] == {"page": 4}++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.codescene.codescene.rest_api_resource")+ def test_resume_hook_saves_state_only_when_next_page_present(self, mock_rest_api_resource: MagicMock) -> None:+ mock_rest_api_resource.return_value = _FakeDltResource("Projects", [])+ manager = _make_fake_manager()++ codescene_source(+ api_token="token",+ base_url=None,+ endpoint="Projects",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=manager,+ )++ resume_hook = mock_rest_api_resource.call_args.kwargs["resume_hook"]+ resume_hook({"page": 7})+ manager.save_state.assert_called_once_with(CodesceneResumeConfig(next_page=7))++ manager.save_state.reset_mock()+ resume_hook(None)+ manager.save_state.assert_not_called()+++class TestCodesceneSourceFanout:+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources"+ )+ def test_files_fanout_row_format(self, mock_rest_api_resources: MagicMock) -> None:+ mock_rest_api_resources.return_value = [+ _FakeDltResource("Projects", [{"id": "p1", "name": "demo"}]),+ _FakeDltResource(+ "Files",+ [{"name": "src/app.py", "code_health": 8.5, "_Projects_id": "p1"}],+ ),+ ]++ response = codescene_source(+ api_token="token",+ base_url=None,+ endpoint="Files",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=_make_fake_manager(),+ )++ rows = list(cast(Any, response.items()))+ assert rows == [{"name": "src/app.py", "code_health": 8.5, "project_id": "p1"}]+ # A file path is only unique within its own project, so the parent project id is+ # part of the key.+ assert response.primary_keys == ["project_id", "name"]++ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.codescene.codescene.build_dependent_resource"+ )+ def test_files_fanout_wiring(self, mock_build_dependent_resource: MagicMock) -> None:+ mock_build_dependent_resource.return_value = iter([])++ codescene_source(+ api_token="token",+ base_url=None,+ endpoint="Files",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=_make_fake_manager(),+ )++ kwargs = mock_build_dependent_resource.call_args.kwargs+ assert kwargs["page_size_param"] == "page_size"+ assert kwargs["parent_endpoint_extra"]["data_selector"] == "projects"+ assert kwargs["child_endpoint_extra"]["data_selector"] == "files"+ assert kwargs["fanout"] is CODESCENE_ENDPOINTS["Files"].fanout++ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.codescene.codescene.build_dependent_resource"+ )+ def test_components_fanout_wiring(self, mock_build_dependent_resource: MagicMock) -> None:+ mock_build_dependent_resource.return_value = iter([])++ codescene_source(+ api_token="token",+ base_url=None,+ endpoint="Components",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=_make_fake_manager(),+ )++ kwargs = mock_build_dependent_resource.call_args.kwargs+ assert kwargs["child_endpoint_extra"]["data_selector"] == "components"+++class TestCodesceneEndpointCatalog:+ @pytest.mark.parametrize("endpoint", list(CODESCENE_ENDPOINTS))+ def test_every_endpoint_has_primary_key(self, endpoint: str) -> None:+ primary_key = CODESCENE_ENDPOINTS[endpoint].primary_key+ assert primary_key++ def test_fanout_endpoints_key_on_parent_id(self) -> None:+ for endpoint in ("Files", "Components"):+ config = CODESCENE_ENDPOINTS[endpoint]+ assert isinstance(config.primary_key, list)+ assert "project_id" in config.primary_keydiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/codescene/tests/test_codescene_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/codescene/tests/test_codescene_source.pynew file mode 100644index 000000000000..7106842f1047--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/codescene/tests/test_codescene_source.py@@ -0,0 +1,117 @@+import pytest+from unittest import mock++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)++from products.warehouse_sources.backend.temporal.data_imports.sources.codescene.codescene import CodesceneResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.codescene.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.codescene.source import CodesceneSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.codescene import (+ CodesceneSourceConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestCodesceneSource:+ def setup_method(self) -> None:+ self.source = CodesceneSource()+ self.team_id = 123+ self.config = CodesceneSourceConfig(api_token="cs-token", base_url=None)++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.CODESCENE++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "Codescene"+ assert config.label == "CodeScene"+ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.iconPath == "/static/services/codescene.png"+ # The source ships visible — a truthy unreleasedSource hides it from every user.+ assert not config.unreleasedSource++ def test_fields(self) -> None:+ config = self.source.get_source_config+ fields_by_name = {f.name: f for f in config.fields}+ assert set(fields_by_name) == {"api_token", "base_url"}++ api_token_field = fields_by_name["api_token"]+ assert isinstance(api_token_field, SourceFieldInputConfig)+ assert api_token_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_token_field.secret is True+ assert api_token_field.required is True++ base_url_field = fields_by_name["base_url"]+ assert isinstance(base_url_field, SourceFieldInputConfig)+ assert base_url_field.required is False+ assert base_url_field.secret is False++ def test_connection_host_fields(self) -> None:+ assert self.source.connection_host_fields == ["base_url"]++ def test_get_schemas_endpoints(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ def test_get_schemas_full_refresh_only(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ for schema in schemas:+ assert schema.supports_incremental is False+ assert schema.incremental_fields == []++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["Projects"])+ assert [s.name for s in schemas] == ["Projects"]++ @pytest.mark.parametrize(+ "observed_error,expect_match",+ [+ ("401 Client Error: Unauthorized for url: https://api.codescene.io/v2/projects", True),+ ("403 Client Error: Forbidden for url: https://api.codescene.io/v2/projects", True),+ ("500 Server Error: Internal Server Error for url: https://api.codescene.io/v2/projects", False),+ ],+ )+ def test_non_retryable_errors_match_auth_failures_only(self, observed_error: str, expect_match: bool) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable) is expect_match++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.codescene.source.validate_codescene_credentials"+ )+ def test_validate_credentials_plumbs_arguments(self, mock_validate: mock.MagicMock) -> None:+ mock_validate.return_value = (True, None)+ assert self.source.validate_credentials(self.config, self.team_id) == (True, None)+ assert mock_validate.call_args.args == ("cs-token", None, self.team_id)++ def test_get_resumable_source_manager_bound_to_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert manager._data_class is CodesceneResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.codescene.source.codescene_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_codescene_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "Files"+ inputs.team_id = self.team_id+ inputs.job_id = "job-1"+ manager = mock.MagicMock()++ config = CodesceneSourceConfig(api_token="cs-token", base_url="https://codescene.example.com:3003/api/v2")+ self.source.source_for_pipeline(config, manager, inputs)++ kwargs = mock_codescene_source.call_args.kwargs+ assert kwargs["api_token"] == "cs-token"+ assert kwargs["base_url"] == "https://codescene.example.com:3003/api/v2"+ assert kwargs["endpoint"] == "Files"+ assert kwargs["team_id"] == self.team_id+ assert kwargs["job_id"] == "job-1"+ assert kwargs["resumable_source_manager"] is manager++ def test_canonical_descriptions_cover_endpoints(self) -> None:+ descriptions = self.source.get_canonical_descriptions()+ assert set(descriptions.keys()) == set(ENDPOINTS)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/codescene.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/codescene.pyindex 2e5e876f710c..8fafd94ecbac 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/codescene.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/codescene.py@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass CodesceneSourceConfig(config.Config):- pass+ api_token: str+ base_url: str | None = None