Skip to content

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

feat(data-warehouse): implement the clarifai import source (#112212)

Tom Owers49dd9d1e9582
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 5c91fb73f802..d5ed656835a1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -197,6 +197,7 @@ the row lists both.
| checkmarx | HTTP | requests | ✅ |
| checkout_com | HTTP | requests | ✅ |
| churnkey | HTTP | requests | ✅ |
+| clarifai | HTTP | requests | ✅ |
| clever | HTTP | requests + `rest_source.RESTClient` | ✅ |
| cliniko | HTTP | requests + `rest_source.RESTClient` | ✅ |
| clip | HTTP | requests | ✅ |
@@ -1039,7 +1040,6 @@ doesn't conflict with concurrent PRs.
- cin7
- circle_so
- cisco_meraki
-- clarifai
- classy
- clazar
- cleartax
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clarifai/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clarifai/canonical_descriptions.py
new file mode 100644
index 000000000000..f3a8d2a09d7c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clarifai/canonical_descriptions.py
@@ -0,0 +1,45 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "models": {
+ "description": "Models in the selected Clarifai app, including details of their latest versions.",
+ "docs_url": "https://docs.clarifai.com/create/models/manage/",
+ "columns": {
+ "id": "Model identifier within the app.",
+ "name": "Model name.",
+ "app_id": "Identifier of the app that contains the model.",
+ "user_id": "Identifier of the model owner.",
+ "model_version": "Details of the latest model version.",
+ },
+ },
+ "workflows": {
+ "description": "Workflows that connect models in the selected Clarifai app.",
+ "docs_url": "https://docs.clarifai.com/create/workflows/manage/",
+ "columns": {
+ "id": "Workflow identifier within the app.",
+ "nodes": "Model nodes and their connections in the workflow.",
+ },
+ },
+ "datasets": {
+ "description": "Datasets that organize inputs in the selected Clarifai app.",
+ "docs_url": "https://docs.clarifai.com/create/datasets/manage/",
+ "columns": {
+ "id": "Dataset identifier within the app.",
+ "description": "Description of the dataset.",
+ "metadata": "Custom metadata attached to the dataset.",
+ },
+ },
+ "concepts": {
+ "description": "Concept labels in the selected Clarifai app.",
+ "docs_url": "https://docs.clarifai.com/create/concepts/manage/",
+ "columns": {
+ "id": "Concept identifier within the app.",
+ "name": "Concept name.",
+ "language": "Language of the concept name.",
+ "created_at": "Time when the concept was created.",
+ "app_id": "Identifier of the app that contains the concept.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clarifai/clarifai.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clarifai/clarifai.py
new file mode 100644
index 000000000000..4f60a39b46aa
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clarifai/clarifai.py
@@ -0,0 +1,202 @@
+import re
+from typing import Any, cast
+from urllib.parse import urlsplit
+
+from requests import Response
+from requests.exceptions import HTTPError
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.clarifai.settings import (
+ AUTH_ERROR,
+ DEFAULT_API_HOST,
+ ENDPOINTS,
+ HOST_ERROR,
+ PAGE_SIZE,
+ PERMISSION_ERROR,
+ PRIMARY_KEYS,
+ RESOURCE_ERROR,
+)
+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 ValidateDatabaseHostMixin
+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.rest_client import (
+ RESTClientRetryableError,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import PaginatorConfig
+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 (
+ UNKNOWN_RESOURCE_PREFIX,
+ UnknownResourceError,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.clarifai import (
+ ClarifaiSourceConfig,
+)
+
+
+@frozen
+class ClarifaiResumeConfig:
+ page: int
+
+
+class ClarifaiAPIError(ValueError):
+ def __init__(self, code: int, message: str) -> None:
+ self.code = code
+ super().__init__(message)
+
+
+class ClarifaiClient(ValidateDatabaseHostMixin):
+ def __init__(self, config: ClarifaiSourceConfig, team_id: int, api_version: str) -> None:
+ host = (config.api_host or DEFAULT_API_HOST).strip().rstrip("/")
+ try:
+ parts = urlsplit(host)
+ valid_host = (
+ parts.scheme == "https"
+ and parts.hostname
+ and not parts.username
+ and not parts.password
+ and not parts.path
+ and not parts.query
+ and not parts.fragment
+ and not any(character.isspace() for character in host)
+ and "\\" not in host
+ and (parts.port is None or 0 < parts.port <= 65535)
+ )
+ except ValueError:
+ valid_host = False
+ if not valid_host:
+ raise ValueError(HOST_ERROR)
+ host_valid, _ = self.is_database_host_valid(parts.hostname or "", team_id)
+ if not host_valid:
+ raise ValueError(HOST_ERROR)
+ for value in (config.user_id, config.app_id):
+ if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]*", value):
+ raise ValueError(
+ "Enter a valid Clarifai user ID and app ID. Use letters, numbers, periods, hyphens, or underscores."
+ )
+ self.config = config
+ self.team_id = team_id
+ self.base_url = f"{host}/{api_version}/users/{config.user_id}/apps/{config.app_id}/"
+
+ @staticmethod
+ def check_response(response: Response, **kwargs: object) -> Response:
+ if not 200 <= response.status_code < 300:
+ return response
+ try:
+ body = response.json()
+ except ValueError:
+ raise RESTClientRetryableError("Clarifai returned an invalid JSON response.") from None
+ status = body.get("status") if isinstance(body, dict) else None
+ code = status.get("code") if isinstance(status, dict) else None
+ if code in (10000, 10001, 10002):
+ return response
+ if code in (10030, 11003, 11005):
+ raise RESTClientRetryableError("Clarifai is busy or has reached its request limit. Try again later.")
+ if code in (11001, 11002, 11008, 11009, 11200):
+ raise ClarifaiAPIError(code, AUTH_ERROR)
+ if code == 11007:
+ raise ClarifaiAPIError(code, PERMISSION_ERROR)
+ if code == 11101:
+ raise ClarifaiAPIError(code, RESOURCE_ERROR)
+ if code in (11000, 11004, 11006):
+ raise ClarifaiAPIError(
+ code, "Clarifai account access is limited. Check your account plan and usage limits."
+ )
+ raise ValueError("Clarifai returned an unsuccessful response. Check the API status and try again.")
+
+ def resource_config(self, endpoint: str, *, probe: bool = False) -> RESTAPIConfig:
+ if endpoint not in ENDPOINTS:
+ raise UnknownResourceError(f"{UNKNOWN_RESOURCE_PREFIX} {endpoint}")
+ session = make_tracked_session(redact_values=(self.config.personal_access_token,), allow_redirects=False)
+ # Clarifai reports API failures in the JSON status, including responses with HTTP 200.
+ session.hooks["response"].append(self.check_response)
+ return {
+ "client": {
+ "base_url": self.base_url,
+ "auth": {
+ "type": "api_key",
+ "name": "Authorization",
+ "api_key": f"Key {self.config.personal_access_token}",
+ },
+ "session": session,
+ "allowed_hosts": [],
+ "allow_redirects": False,
+ "request_timeout": (10, 60),
+ # PageNumberPaginatorConfig and the runtime constructor currently disagree on this field name.
+ "paginator": "single_page"
+ if probe
+ else cast(PaginatorConfig, {"type": "page_number", "base_page": 1, "total_path": None}),
+ },
+ "resources": [
+ {
+ "name": endpoint,
+ "endpoint": {
+ "path": endpoint,
+ "data_selector": endpoint,
+ "params": {"page": 1, "per_page": 1 if probe else PAGE_SIZE},
+ },
+ }
+ ],
+ }
+
+ def source(
+ self,
+ endpoint: str,
+ job_id: str,
+ manager: ResumableSourceManager[ClarifaiResumeConfig],
+ ) -> SourceResponse:
+ resume = manager.load_state() if manager.can_resume() else None
+
+ def save_checkpoint(state: dict[str, Any] | None) -> None:
+ if state is not None:
+ manager.save_state(ClarifaiResumeConfig(page=int(state["page"])))
+
+ resource = rest_api_resource(
+ self.resource_config(endpoint),
+ team_id=self.team_id,
+ job_id=job_id,
+ db_incremental_field_last_value=None,
+ initial_paginator_state={"page": resume.page} if resume else None,
+ resume_hook=save_checkpoint,
+ )
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: resource,
+ primary_keys=PRIMARY_KEYS,
+ sort_mode=None,
+ on_complete=manager.clear_state,
+ )
+
+
+def validate_credentials(
+ config: ClarifaiSourceConfig, team_id: int, schema_name: str | None, api_version: str
+) -> tuple[bool, str | None]:
+ try:
+ client = ClarifaiClient(config, team_id, api_version)
+ resource = rest_api_resource(
+ client.resource_config(schema_name or "models", probe=True),
+ team_id=team_id,
+ job_id="",
+ db_incremental_field_last_value=None,
+ )
+ list(resource)
+ except ClarifaiAPIError as error:
+ if error.code == 11007 and schema_name is None:
+ return True, None
+ return False, str(error)
+ except HTTPError as error:
+ status = error.response.status_code if error.response is not None else None
+ if status == 401:
+ return False, AUTH_ERROR
+ if status == 403:
+ return (True, None) if schema_name is None else (False, PERMISSION_ERROR)
+ if status == 404:
+ return False, RESOURCE_ERROR
+ raise
+ except ValueError as error:
+ return False, str(error)
+ return True, None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clarifai/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clarifai/settings.py
new file mode 100644
index 000000000000..4c406b774ee8
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clarifai/settings.py
@@ -0,0 +1,11 @@
+DEFAULT_API_HOST = "https://api.clarifai.com"
+PAGE_SIZE = 128
+ENDPOINTS = ("models", "workflows", "datasets", "concepts")
+PRIMARY_KEYS = ["id"]
+
+AUTH_ERROR = "Clarifai rejected the token. Check your personal access token and app access."
+PERMISSION_ERROR = (
+ "The Clarifai token lacks permission. Grant read access to the selected resource and its list endpoint."
+)
+HOST_ERROR = "Enter a public HTTPS API host without a path, query, or credentials."
+RESOURCE_ERROR = "Clarifai could not find the resource. Check the user ID and app ID."
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clarifai/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clarifai/source.py
index 977d1ac6b828..ab488ba06b82 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clarifai/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clarifai/source.py
@@ -1,8 +1,38 @@
from typing import cast
-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.facade.source_config import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.clarifai.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.clarifai.clarifai import (
+ ClarifaiClient,
+ ClarifaiResumeConfig,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.clarifai.settings import (
+ AUTH_ERROR,
+ ENDPOINTS,
+ HOST_ERROR,
+ PERMISSION_ERROR,
+ RESOURCE_ERROR,
+)
+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.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.clarifai import (
ClarifaiSourceConfig,
)
@@ -10,11 +40,69 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class ClarifaiSource(SimpleSource[ClarifaiSourceConfig]):
+class ClarifaiSource(ResumableSource[ClarifaiSourceConfig, ClarifaiResumeConfig]):
+ lists_tables_without_credentials = True
+ supported_versions = ("v2",)
+ default_version = "v2"
+ api_docs_url = "https://docs.clarifai.com/resources/api-overview/"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.CLARIFAI
+ @property
+ def connection_host_fields(self) -> list[str]:
+ return ["api_host"]
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": AUTH_ERROR,
+ "403 Client Error": PERMISSION_ERROR,
+ "404 Client Error": RESOURCE_ERROR,
+ AUTH_ERROR: AUTH_ERROR,
+ PERMISSION_ERROR: PERMISSION_ERROR,
+ RESOURCE_ERROR: RESOURCE_ERROR,
+ HOST_ERROR: HOST_ERROR,
+ "Clarifai account access is limited": "Check your Clarifai account plan and usage limits.",
+ "Enter a valid Clarifai user ID and app ID": "Check your Clarifai user ID and app ID.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: ClarifaiSourceConfig,
+ 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, {}, names)
+
+ def validate_credentials(
+ self,
+ config: ClarifaiSourceConfig,
+ team_id: int,
+ schema_name: str | None = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_credentials(config, team_id, schema_name, self.resolve_api_version(api_version))
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ClarifaiResumeConfig]:
+ return ResumableSourceManager(inputs, ClarifaiResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: ClarifaiSourceConfig,
+ resumable_source_manager: ResumableSourceManager[ClarifaiResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return ClarifaiClient(config, inputs.team_id, self.resolve_api_version(inputs.api_version)).source(
+ inputs.schema_name, inputs.job_id, resumable_source_manager
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
@@ -22,6 +110,49 @@ class ClarifaiSource(SimpleSource[ClarifaiSourceConfig]):
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Clarifai",
iconPath="/static/services/clarifai.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://docs.clarifai.com/control/authentication/pat/",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption=(
+ "Create a personal access token in Clarifai under Settings > Secrets. "
+ "Grant read access for models, workflows, datasets, and concepts that you want to sync. "
+ "Allow their ListModels, ListWorkflows, ListDatasets, and ListConcepts endpoints. "
+ "Enter the user ID and app ID of the app owner."
+ ),
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="personal_access_token",
+ label="Personal access token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="user_id",
+ label="User ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="example-user",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="app_id",
+ label="App ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="example-app",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_host",
+ label="API host",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="https://api.clarifai.com",
+ secret=False,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clarifai/tests/test_clarifai.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clarifai/tests/test_clarifai.py
new file mode 100644
index 000000000000..58b29c9689b4
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clarifai/tests/test_clarifai.py
@@ -0,0 +1,286 @@
+from collections.abc import Iterable
+from typing import Any, cast
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests_mock
+from requests.exceptions import HTTPError
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.clarifai.clarifai import (
+ ClarifaiClient,
+ ClarifaiResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.clarifai.source import ClarifaiSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (
+ RESTClientRetryableError,
+)
+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 UnknownResourceError
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.clarifai import (
+ ClarifaiSourceConfig,
+)
+
+BASE_URL = "https://api.clarifai.com/v2/users/example-user/apps/example-app/"
+
+
+def config() -> ClarifaiSourceConfig:
+ return ClarifaiSourceConfig(personal_access_token="fake-clarifai-pat", user_id="example-user", app_id="example-app")
+
+
+def manager() -> MagicMock:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+ return manager
+
+
+class TestClarifaiTransport:
+ @pytest.mark.parametrize("endpoint", ["models", "workflows", "datasets", "concepts"])
+ @pytest.mark.parametrize("resume_page", [None, 4])
+ def test_pagination_and_resume(
+ self, config: ClarifaiSourceConfig, manager: MagicMock, endpoint: str, resume_page: int | None
+ ) -> None:
+ if resume_page is not None:
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = ClarifaiResumeConfig(page=resume_page)
+ first_page = resume_page or 1
+ with requests_mock.Mocker() as http:
+ http.get(
+ BASE_URL + endpoint,
+ [
+ {"json": {"status": {"code": 10000}, endpoint: [{"id": "row-1"}]}},
+ {"json": {"status": {"code": 10000}, endpoint: [{"id": "row-2"}]}},
+ {"json": {"status": {"code": 10000}, endpoint: []}},
+ ],
+ )
+ response = ClarifaiClient(config, 42, "v2").source(endpoint, "test-job", manager)
+ rows = [row for page in cast(Iterable[list[dict[str, Any]]], response.items()) for row in page]
+ assert rows == [{"id": "row-1"}, {"id": "row-2"}]
+ assert [request.qs for request in http.request_history] == [
+ {"page": [str(page)], "per_page": ["128"]} for page in range(first_page, first_page + 3)
+ ]
+ assert all(request.headers["Authorization"] == "Key fake-clarifai-pat" for request in http.request_history)
+ assert all(request.timeout == (10, 60) for request in http.request_history)
+ assert [call.args[0] for call in manager.save_state.call_args_list] == [
+ ClarifaiResumeConfig(page=first_page + 1),
+ ClarifaiResumeConfig(page=first_page + 2),
+ ]
+ assert response.on_complete is not None
+ response.on_complete()
+ manager.clear_state.assert_called_once_with()
+
+ @pytest.mark.parametrize("terminal", [{"models": []}, {}])
+ def test_empty_success_stops(
+ self, config: ClarifaiSourceConfig, manager: MagicMock, terminal: dict[str, object]
+ ) -> None:
+ with requests_mock.Mocker() as http:
+ http.get(BASE_URL + "models", json={"status": {"code": 10000}, **terminal})
+ response = ClarifaiClient(config, 42, "v2").source("models", "test-job", manager)
+ assert not any(cast(Iterable[Any], response.items()))
+ assert http.call_count == 1
+ manager.save_state.assert_not_called()
+
+ @pytest.mark.parametrize(
+ ("http_status", "api_status", "message"),
+ [
+ (401, 11008, "401 Client Error"),
+ (403, 11007, "403 Client Error"),
+ (404, 11101, "404 Client Error"),
+ (200, 11001, "Clarifai rejected the token"),
+ (200, 11002, "Clarifai rejected the token"),
+ (200, 11008, "Clarifai rejected the token"),
+ (200, 11009, "Clarifai rejected the token"),
+ (200, 11200, "Clarifai rejected the token"),
+ (200, 11007, "The Clarifai token lacks permission"),
+ (200, 11101, "Clarifai could not find the resource"),
+ (200, 11000, "Clarifai account access is limited"),
+ (200, 11004, "Clarifai account access is limited"),
+ (200, 11006, "Clarifai account access is limited"),
+ ],
+ )
+ def test_permanent_errors(
+ self, config: ClarifaiSourceConfig, manager: MagicMock, http_status: int, api_status: int, message: str
+ ) -> None:
+ with requests_mock.Mocker() as http:
+ http.get(BASE_URL + "models", status_code=http_status, json={"status": {"code": api_status}})
+ with pytest.raises((HTTPError, ValueError), match=message) as error:
+ list(
+ cast(
+ Iterable[Any],
+ ClarifaiClient(config, 42, "v2").source("models", "test-job", manager).items(),
+ )
+ )
+ assert any(pattern in str(error.value) for pattern in ClarifaiSource().get_non_retryable_errors())
+ assert http.call_count == 1
+ manager.save_state.assert_not_called()
+
+ @pytest.mark.parametrize(
+ ("http_status", "api_status"), [(200, 10030), (200, 11003), (200, 11005), (429, 11005), (503, 10020)]
+ )
+ def test_transient_errors_retry(
+ self, config: ClarifaiSourceConfig, manager: MagicMock, http_status: int, api_status: int
+ ) -> None:
+ with (
+ requests_mock.Mocker() as http,
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.RESTClient._send_request.retry.sleep"
+ ),
+ ):
+ http.get(BASE_URL + "models", status_code=http_status, json={"status": {"code": api_status}})
+ with pytest.raises(RESTClientRetryableError):
+ list(
+ cast(
+ Iterable[Any],
+ ClarifaiClient(config, 42, "v2").source("models", "test-job", manager).items(),
+ )
+ )
+ assert http.call_count == 5
+ manager.save_state.assert_not_called()
+
+ @pytest.mark.parametrize(
+ "body", [{}, {"status": {"code": 10020}}, {"status": {"code": 10010}}, {"status": {"code": 99999}}]
+ )
+ def test_unsuccessful_response_is_not_empty_data(
+ self, config: ClarifaiSourceConfig, manager: MagicMock, body: dict[str, object]
+ ) -> None:
+ with requests_mock.Mocker() as http:
+ http.get(BASE_URL + "models", json=body)
+ with pytest.raises(ValueError, match="unsuccessful response"):
+ list(
+ cast(
+ Iterable[Any],
+ ClarifaiClient(config, 42, "v2").source("models", "test-job", manager).items(),
+ )
+ )
+ manager.save_state.assert_not_called()
+
+ def test_redirect_is_not_followed(self, config: ClarifaiSourceConfig, manager: MagicMock) -> None:
+ with requests_mock.Mocker() as http:
+ http.get(BASE_URL + "models", status_code=302, headers={"Location": "https://other.example.com/"})
+ with pytest.raises(ValueError, match="redirect"):
+ list(
+ cast(
+ Iterable[Any],
+ ClarifaiClient(config, 42, "v2").source("models", "test-job", manager).items(),
+ )
+ )
+ assert http.call_count == 1
+
+ def test_unknown_endpoint_does_not_request(self, config: ClarifaiSourceConfig, manager: MagicMock) -> None:
+ with requests_mock.Mocker() as http:
+ with pytest.raises(UnknownResourceError):
+ ClarifaiClient(config, 42, "v2").source("unknown", "test-job", manager)
+ assert http.call_count == 0
+
+
+class TestClarifaiCredentials:
+ @pytest.mark.parametrize(
+ ("http_status", "api_status", "schema_name", "valid", "message"),
+ [
+ (200, 10000, None, True, None),
+ (200, 10001, None, True, None),
+ (200, 10002, "datasets", True, None),
+ (401, 11008, None, False, "Clarifai rejected the token"),
+ (403, 11007, None, True, None),
+ (403, 11007, "datasets", False, "The Clarifai token lacks permission"),
+ (200, 11008, None, False, "Clarifai rejected the token"),
+ (200, 11007, None, True, None),
+ (200, 11007, "datasets", False, "The Clarifai token lacks permission"),
+ (404, 11101, None, False, "Clarifai could not find the resource"),
+ ],
+ )
+ def test_probe_status_mapping(
+ self,
+ config: ClarifaiSourceConfig,
+ http_status: int,
+ api_status: int,
+ schema_name: str | None,
+ valid: bool,
+ message: str | None,
+ ) -> None:
+ endpoint = schema_name or "models"
+ with requests_mock.Mocker() as http:
+ http.get(BASE_URL + endpoint, status_code=http_status, json={"status": {"code": api_status}, endpoint: []})
+ result, error = ClarifaiSource().validate_credentials(config, 42, schema_name)
+ assert result is valid
+ assert error is None if message is None else message in (error or "")
+ assert http.call_count == 1
+ assert http.last_request is not None
+ assert http.last_request.qs == {"page": ["1"], "per_page": ["1"]}
+ assert http.last_request.headers["Authorization"] == "Key fake-clarifai-pat"
+
+ @pytest.mark.parametrize("http_status", [400, 429, 500])
+ def test_probe_does_not_disguise_other_errors(self, config: ClarifaiSourceConfig, http_status: int) -> None:
+ with (
+ requests_mock.Mocker() as http,
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.RESTClient._send_request.retry.sleep"
+ ),
+ ):
+ http.get(BASE_URL + "models", status_code=http_status, json={"status": {"code": 10020}})
+ with pytest.raises((HTTPError, RESTClientRetryableError)):
+ ClarifaiSource().validate_credentials(config, 42)
+
+ @pytest.mark.parametrize(
+ "host",
+ [
+ "http://example.com",
+ "https://user:[email protected]",
+ "https://example.com/path",
+ "https://example.com?q=x",
+ "https://example.com#x",
+ "https://example.com:bad",
+ "https://[bad",
+ "https://example.com\\@other.example.com",
+ "https://exa mple.com",
+ ],
+ )
+ def test_rejects_invalid_host(self, config: ClarifaiSourceConfig, host: str) -> None:
+ config.api_host = host
+ with requests_mock.Mocker() as http:
+ valid, error = ClarifaiSource().validate_credentials(config, 42)
+ assert not valid
+ assert error is not None and "public HTTPS API host" in error
+ assert http.call_count == 0
+
+ @pytest.mark.parametrize("address", ["127.0.0.1", "10.0.0.1", "169.254.169.254", "::1"])
+ def test_rejects_internal_host(self, config: ClarifaiSourceConfig, address: str) -> None:
+ config.api_host = "https://clarifai.example.com"
+ with (
+ requests_mock.Mocker() as http,
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins.is_cloud",
+ return_value=True,
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins.get_instance_region",
+ return_value="US",
+ ),
+ patch("socket.getaddrinfo", return_value=[(2, 1, 6, "", (address, 443))]),
+ ):
+ valid, error = ClarifaiSource().validate_credentials(config, 42)
+ assert not valid
+ assert error is not None and "public HTTPS API host" in error
+ assert http.call_count == 0
+
+ @pytest.mark.parametrize("host", ["https://clarifai.example.com", "https://clarifai.example.com:8443/"])
+ def test_custom_host(self, config: ClarifaiSourceConfig, host: str) -> None:
+ config.api_host = host
+ with requests_mock.Mocker() as http:
+ http.get(
+ host.rstrip("/") + "/v2/users/example-user/apps/example-app/models", json={"status": {"code": 10000}}
+ )
+ assert ClarifaiSource().validate_credentials(config, 42) == (True, None)
+ assert http.call_count == 1
+
+ @pytest.mark.parametrize("field", ["user_id", "app_id"])
+ @pytest.mark.parametrize("value", ["", "..", "../other", "user?query=yes"])
+ def test_rejects_path_injection(self, config: ClarifaiSourceConfig, field: str, value: str) -> None:
+ setattr(config, field, value)
+ with requests_mock.Mocker() as http:
+ valid, error = ClarifaiSource().validate_credentials(config, 42)
+ assert not valid
+ assert error is not None and "valid Clarifai user ID" in error
+ assert http.call_count == 0
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/clarifai.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/clarifai.py
index 3924a87cdfdd..59be167194b2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/clarifai.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/clarifai.py
@@ -6,4 +6,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class ClarifaiSourceConfig(config.Config):
- pass
+ personal_access_token: str
+ user_id: str
+ app_id: str
+ api_host: str | None = None