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 ahrefs import source (#111909)

Tom Owersb4cc77c60359
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 d7acfab1e779..2352a2b656e8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -62,6 +62,7 @@ the row lists both.
| agilecrm | HTTP | requests | ✅ |
| aha | HTTP | requests | ✅ |
| aha_ideas | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| ahrefs | HTTP | requests | ✅ |
| airbrake | HTTP | requests | ✅ |
| aircall | HTTP | requests | ✅ |
| airops | HTTP | requests | ✅ |
@@ -909,7 +910,6 @@ doesn't conflict with concurrent PRs.
- adapty
- adobe_commerce
- adp_workforce_now
-- ahrefs
- aikido_security
- airbridge
- airbyte
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/ahrefs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/ahrefs.py
new file mode 100644
index 000000000000..02b8632ab1b3
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/ahrefs.py
@@ -0,0 +1,117 @@
+from collections.abc import Iterator
+from typing import cast
+
+import structlog
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.ahrefs.settings import (
+ API_BASE_URL,
+ ENDPOINTS,
+ MAX_PAGE_ROWS,
+ NON_RETRYABLE_ERRORS,
+)
+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.auth import BearerTokenAuth
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.config_setup import (
+ create_response_hooks,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ SinglePagePaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import RESTClient
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ResponseAction
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import schema_for_resource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+
+logger = structlog.get_logger(__name__)
+
+RESPONSE_ACTIONS: list[ResponseAction] = [
+ cast(
+ ResponseAction,
+ {"status_code": status, "content": content, "action": "raise", "message": "ahrefs_quota_exceeded"},
+ )
+ for status in (400, 403)
+ for content in ("units", "Units", "quota", "Quota")
+]
+RESPONSE_ACTIONS.extend(
+ [
+ {"status_code": 402, "action": "raise", "message": "ahrefs_quota_exceeded"},
+ {"status_code": 401, "action": "raise", "message": "ahrefs_invalid_api_key"},
+ {"status_code": 403, "action": "raise", "message": "ahrefs_access_denied"},
+ ]
+)
+
+
+def validate_credentials(api_key: str) -> tuple[bool, str | None]:
+ client = RESTClient(
+ base_url=API_BASE_URL,
+ auth=BearerTokenAuth(token=api_key),
+ max_retry_attempts=1,
+ request_timeout=(10, 60),
+ )
+ try:
+ list(
+ client.paginate(
+ path="subscription-info/limits-and-usage",
+ params={"output": "json"},
+ data_selector="limits_and_usage",
+ data_selector_required=True,
+ paginator=SinglePagePaginator(),
+ hooks=create_response_hooks(RESPONSE_ACTIONS),
+ )
+ )
+ except ValueError as error:
+ message = NON_RETRYABLE_ERRORS.get(str(error))
+ if message is None:
+ raise
+ return False, message
+ return True, None
+
+
+def ahrefs_source(api_key: str, project_id: str, endpoint: str, team_id: int, job_id: str) -> SourceResponse:
+ settings = schema_for_resource(ENDPOINTS, endpoint)
+ normalized_project_id = str(int(project_id))
+
+ def add_project_id(row: dict[str, object]) -> dict[str, object]:
+ return {**row, "project_id": normalized_project_id}
+
+ config: RESTAPIConfig = {
+ "client": {
+ "base_url": API_BASE_URL,
+ "auth": {"type": "bearer", "token": api_key},
+ "paginator": "single_page",
+ "request_timeout": (10, 60),
+ },
+ "resources": [
+ {
+ "name": endpoint,
+ "write_disposition": "replace",
+ "endpoint": {
+ "path": settings["path"],
+ "data_selector": settings["data_selector"],
+ "data_selector_required": True,
+ "params": {"output": "json", "project_id": normalized_project_id, **settings["params"]},
+ "response_actions": RESPONSE_ACTIONS,
+ },
+ "data_map": add_project_id,
+ }
+ ],
+ }
+ resource = rest_api_resource(config, team_id, job_id, None)
+
+ def items() -> Iterator[list[dict[str, object]]]:
+ for page in resource:
+ if endpoint == "site_audit_pages" and len(page) >= MAX_PAGE_ROWS:
+ logger.info("ahrefs_page_sample_limit_reached", team_id=team_id, limit=MAX_PAGE_ROWS)
+ page = page[:MAX_PAGE_ROWS]
+ yield page
+
+ return SourceResponse(
+ name=endpoint,
+ items=items,
+ primary_keys=settings["primary_keys"],
+ sort_mode=None,
+ supports_resume=False,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/canonical_descriptions.py
new file mode 100644
index 000000000000..f9d91508f1a7
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/canonical_descriptions.py
@@ -0,0 +1,49 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "site_audit_health_scores": {
+ "description": "Site Audit health scores and totals for the selected project's latest completed crawl.",
+ "docs_url": "https://docs.ahrefs.com/en/api/reference/site-audit/get-projects",
+ "columns": {
+ "project_id": "Identifier of the selected Site Audit project.",
+ "project_name": "Name of the project.",
+ "date": "Time when the last completed crawl finished, in GMT.",
+ "health_score": "Proportion of internal URLs without errors in the last completed crawl.",
+ "status": "Status of the most recent finished crawl.",
+ "target_url": "Target URL for the project.",
+ "target_mode": "Scope of the target: exact URL, prefix, domain, or subdomains.",
+ "target_protocol": "Target protocol: HTTP, HTTPS, or both.",
+ "total": "Total number of internal URLs crawled.",
+ "urls_with_errors": "Number of internal URLs with errors.",
+ "urls_with_warnings": "Number of internal URLs with warnings.",
+ "urls_with_notices": "Number of internal URLs with notices.",
+ },
+ },
+ "site_audit_issues": {
+ "description": "Issue summaries and affected URL counts from the selected Site Audit project's latest crawl.",
+ "docs_url": "https://docs.ahrefs.com/en/api/reference/site-audit/get-issues",
+ "columns": {
+ "project_id": "Identifier of the selected Site Audit project.",
+ "issue_id": "Identifier of the issue type.",
+ "name": "Name of the issue.",
+ "category": "Site Audit category for the issue.",
+ "importance": "Issue severity: Error, Warning, or Notice.",
+ "crawled": "Number of URLs currently affected by the issue.",
+ "is_indexable": "Whether the issue applies only to indexable pages.",
+ },
+ },
+ "site_audit_pages": {
+ "description": "A sample of up to 100 pages from the latest Site Audit crawl, ordered by URL.",
+ "docs_url": "https://docs.ahrefs.com/en/api/reference/site-audit/get-page-explorer",
+ "columns": {
+ "project_id": "Identifier of the selected Site Audit project.",
+ "url": "Address of the crawled page or resource.",
+ "http_code": "HTTP status code returned by the URL.",
+ "title": "Page titles found during the crawl.",
+ "depth": "Minimum number of clicks from the crawl's starting page, including redirects.",
+ "is_html": "Whether the resource has an HTML content type.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/settings.py
new file mode 100644
index 000000000000..08979cdd35e0
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/settings.py
@@ -0,0 +1,54 @@
+from typing import TypedDict
+
+API_BASE_URL = "https://api.ahrefs.com/v3"
+MAX_PAGE_ROWS = 100
+
+
+class EndpointSettings(TypedDict):
+ path: str
+ data_selector: str
+ primary_keys: list[str]
+ params: dict[str, str | int]
+ description: str
+
+
+ENDPOINTS: dict[str, EndpointSettings] = {
+ "site_audit_health_scores": {
+ "path": "site-audit/projects",
+ "data_selector": "healthscores",
+ "primary_keys": ["project_id"],
+ "params": {},
+ "description": "Health score and crawl totals for the selected Site Audit project.",
+ },
+ "site_audit_issues": {
+ "path": "site-audit/issues",
+ "data_selector": "issues",
+ "primary_keys": ["project_id", "issue_id"],
+ "params": {},
+ "description": "Issue summaries from the latest crawl of the selected Site Audit project.",
+ },
+ "site_audit_pages": {
+ "path": "site-audit/page-explorer",
+ "data_selector": "pages",
+ "primary_keys": ["project_id", "url"],
+ "params": {
+ "select": "url,http_code,title,depth,is_html",
+ "limit": MAX_PAGE_ROWS,
+ "order_by": "url:asc",
+ },
+ "description": f"The first {MAX_PAGE_ROWS} crawled URLs, ordered by URL. Requires verified project ownership.",
+ },
+}
+
+AUTH_ERROR = "Ahrefs authentication failed. Check your API key in Account settings > API keys."
+ACCESS_ERROR = "Ahrefs denied access. Check your plan, project access, and verified ownership for page data."
+QUOTA_ERROR = "Ahrefs API units are exhausted. Increase your API key or workspace limit, or wait for renewal."
+
+NON_RETRYABLE_ERRORS: dict[str, str | None] = {
+ "ahrefs_invalid_api_key": AUTH_ERROR,
+ "ahrefs_access_denied": ACCESS_ERROR,
+ "ahrefs_quota_exceeded": QUOTA_ERROR,
+ "401 Client Error": AUTH_ERROR,
+ "403 Client Error": ACCESS_ERROR,
+ "402 Client Error": QUOTA_ERROR,
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/source.py
index 5c1997478db5..fc7a37fbdf14 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/source.py
@@ -1,18 +1,82 @@
from typing import cast
-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig
+from products.warehouse_sources.backend.facade.source_config import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.ahrefs.ahrefs import (
+ ahrefs_source,
+ validate_credentials as validate_ahrefs_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.ahrefs.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.ahrefs.settings import (
+ ENDPOINTS,
+ MAX_PAGE_ROWS,
+ NON_RETRYABLE_ERRORS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+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.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.ahrefs import AhrefsSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
class AhrefsSource(SimpleSource[AhrefsSourceConfig]):
+ lists_tables_without_credentials = True
+ supported_versions = ("v3",)
+ default_version = "v3"
+ api_docs_url = "https://docs.ahrefs.com/en/api/docs/introduction"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.AHREFS
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return NON_RETRYABLE_ERRORS
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: AhrefsSourceConfig,
+ 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, descriptions={name: endpoint["description"] for name, endpoint in ENDPOINTS.items()}
+ )
+
+ def validate_credentials(
+ self,
+ config: AhrefsSourceConfig,
+ team_id: int,
+ schema_name: str | None = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ if not config.project_id.isascii() or not config.project_id.isdigit() or int(config.project_id) <= 0:
+ return False, "Enter a positive Site Audit project ID from your Ahrefs project URL."
+ return validate_ahrefs_credentials(config.api_key)
+
+ def source_for_pipeline(self, config: AhrefsSourceConfig, inputs: SourceInputs) -> SourceResponse:
+ return ahrefs_source(config.api_key, config.project_id, inputs.schema_name, inputs.team_id, inputs.job_id)
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
@@ -20,6 +84,35 @@ class AhrefsSource(SimpleSource[AhrefsSourceConfig]):
category=DataWarehouseSourceCategory.ANALYTICS,
label="Ahrefs",
iconPath="/static/services/ahrefs.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption=(
+ "Requires an Ahrefs Lite plan or higher. "
+ "Create an API key in [Account settings > API keys](https://app.ahrefs.com/account/api-keys). "
+ "Syncs use your account's API units. Health scores are free. "
+ "Issues and pages each cost 50 units per request. "
+ f"Each sync imports the latest crawl, with a sample of up to {MAX_PAGE_ROWS} pages. "
+ "Page data requires verified project ownership."
+ ),
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="project_id",
+ label="Site Audit project ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="123456",
+ secret=False,
+ caption="Use the ID from https://app.ahrefs.com/site-audit/123456.",
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/tests/test_ahrefs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/tests/test_ahrefs.py
new file mode 100644
index 000000000000..2ea526e1e254
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/tests/test_ahrefs.py
@@ -0,0 +1,191 @@
+import json
+from collections.abc import Iterable, Iterator
+from typing import Any, cast
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from requests import Response, Session
+from requests.exceptions import HTTPError
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.ahrefs.ahrefs import (
+ ahrefs_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.ahrefs.source import AhrefsSource
+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.schema import UnknownResourceError
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.ahrefs import AhrefsSourceConfig
+
+CLIENT_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client"
+SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.ahrefs.ahrefs"
+
+
+def response(body: object, status: int = 200) -> Response:
+ result = Response()
+ result.status_code = status
+ result.reason = "OK" if status == 200 else "Error"
+ result._content = json.dumps(body).encode()
+ result.headers["Content-Type"] = "application/json"
+ result.url = "https://api.ahrefs.com/v3/site-audit/issues"
+ return result
+
+
+def send() -> Iterator[MagicMock]:
+ with Session() as session:
+ with (
+ patch(f"{CLIENT_MODULE}.make_tracked_session", return_value=session),
+ patch.object(session, "send") as mock,
+ ):
+ yield mock
+
+
+ ("table", "path", "selector", "row", "expected_params"),
+ [
+ (
+ "site_audit_health_scores",
+ "projects",
+ "healthscores",
+ {"project_id": "123", "health_score": 95, "date": None},
+ {},
+ ),
+ (
+ "site_audit_issues",
+ "issues",
+ "issues",
+ {"issue_id": "missing_title", "crawled": 3},
+ {},
+ ),
+ (
+ "site_audit_pages",
+ "page-explorer",
+ "pages",
+ {"url": "https://example.com/", "http_code": 200, "title": ["Example"]},
+ {"limit": ["100"], "select": ["url,http_code,title,depth,is_html"], "order_by": ["url:asc"]},
+ ),
+ ],
+)
[email protected]("empty", [False, True])
+def test_snapshot_request_and_terminal_page(
+ send: MagicMock,
+ table: str,
+ path: str,
+ selector: str,
+ row: dict[str, object],
+ expected_params: dict[str, list[str]],
+ empty: bool,
+) -> None:
+ send.return_value = response({selector: [] if empty else [row], "next": "https://example.com/ignored"})
+ inputs = MagicMock(spec=SourceInputs)
+ inputs.schema_name = table
+ inputs.team_id = 1
+ inputs.job_id = "test-job"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2026-01-01"
+ result = AhrefsSource().source_for_pipeline(AhrefsSourceConfig(api_key="test-key", project_id="00123"), inputs)
+
+ assert list(cast(Iterable[Any], result.items())) == ([] if empty else [[{**row, "project_id": "123"}]])
+ send.assert_called_once()
+ assert send.call_args.kwargs["timeout"] == (10, 60)
+ request = send.call_args.args[0]
+ assert request.method == "GET"
+ assert request.headers["Authorization"] == "Bearer test-key"
+ assert urlparse(request.url).path == f"/v3/site-audit/{path}"
+ assert parse_qs(urlparse(request.url).query) == {
+ "output": ["json"],
+ "project_id": ["123"],
+ **expected_params,
+ }
+
+
[email protected]("count", [99, 100, 101])
+def test_page_sample_cap(send: MagicMock, count: int) -> None:
+ rows = [{"url": f"https://example.com/{i}"} for i in range(count)]
+ send.return_value = response({"pages": rows})
+ with patch(f"{SOURCE_MODULE}.logger") as logger:
+ result = ahrefs_source("test-key", "123", "site_audit_pages", 1, "test-job")
+ actual = [row for page in cast(Iterable[Any], result.items()) for row in page]
+ assert actual == [{**row, "project_id": "123"} for row in rows[:100]]
+ assert logger.info.call_count == int(count >= 100)
+ send.assert_called_once()
+
+
+ ("status", "body", "message"),
+ [
+ (401, {"error": "Invalid API key"}, "Check your API key"),
+ (403, ["Error", "Forbidden"], "Check your plan"),
+ (403, {"error": "Insufficient API units"}, "API units are exhausted"),
+ (400, {"error": "API units limit exceeded"}, "API units are exhausted"),
+ (403, {"error": "Quota exceeded"}, "API units are exhausted"),
+ (402, {"error": "Payment required"}, "API units are exhausted"),
+ ],
+)
+def test_credential_and_sync_error_mapping(send: MagicMock, status: int, body: object, message: str) -> None:
+ send.return_value = response(body, status)
+ valid, error = validate_credentials("test-key")
+ assert valid is False
+ assert error is not None and message in error
+ send.assert_called_once()
+ send.reset_mock()
+
+ with pytest.raises(ValueError) as raised:
+ list(cast(Iterable[Any], ahrefs_source("test-key", "123", "site_audit_issues", 1, "test-job").items()))
+ mapped = AhrefsSource().get_non_retryable_errors()[str(raised.value)]
+ assert mapped is not None and message in mapped
+ send.assert_called_once()
+
+
+def test_free_credential_probe(send: MagicMock) -> None:
+ send.return_value = response({"limits_and_usage": {"subscription": "Lite", "units_usage_api_key": 0}})
+ assert validate_credentials("test-key") == (True, None)
+ send.assert_called_once()
+ request = send.call_args.args[0]
+ assert request.headers["Authorization"] == "Bearer test-key"
+ assert request.url == "https://api.ahrefs.com/v3/subscription-info/limits-and-usage?output=json"
+ assert send.call_args.kwargs["timeout"] == (10, 60)
+
+
[email protected]("status", [429, 500, 503])
+def test_transient_probe_failure_is_not_invalid_credentials(send: MagicMock, status: int) -> None:
+ send.return_value = response({"error": "Try later"}, status)
+ with pytest.raises(RESTClientRetryableError):
+ validate_credentials("test-key")
+ send.assert_called_once()
+
+
[email protected]("status", [429, 500, 503])
+def test_sync_retries_transient_failure(send: MagicMock, status: int) -> None:
+ send.side_effect = [response({"error": "Try later"}, status), response({"issues": [{"issue_id": "missing_title"}]})]
+ with patch("tenacity.nap.time.sleep"):
+ result = list(cast(Iterable[Any], ahrefs_source("test-key", "123", "site_audit_issues", 1, "test-job").items()))
+ assert result == [[{"issue_id": "missing_title", "project_id": "123"}]]
+ assert send.call_count == 2
+
+
+def test_unrecognized_probe_error_propagates(send: MagicMock) -> None:
+ send.return_value = response({"error": "Invalid request"}, 400)
+ with pytest.raises(HTTPError):
+ validate_credentials("test-key")
+
+
[email protected]("probe", [False, True])
+def test_missing_response_envelope_fails(send: MagicMock, probe: bool) -> None:
+ send.return_value = response({"unexpected": []})
+ with pytest.raises(ValueError, match="matched nothing"):
+ if probe:
+ validate_credentials("test-key")
+ else:
+ list(cast(Iterable[Any], ahrefs_source("test-key", "123", "site_audit_issues", 1, "test-job").items()))
+
+
+def test_unknown_table_fails_before_request(send: MagicMock) -> None:
+ with pytest.raises(UnknownResourceError):
+ ahrefs_source("test-key", "123", "unknown", 1, "test-job")
+ send.assert_not_called()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/tests/test_ahrefs_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/tests/test_ahrefs_source.py
new file mode 100644
index 000000000000..e81e60712027
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ahrefs/tests/test_ahrefs_source.py
@@ -0,0 +1,33 @@
+import pytest
+from unittest.mock import patch
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.ahrefs.source import AhrefsSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.ahrefs import AhrefsSourceConfig
+
+
[email protected]("project_id", ["", "0", "-1", "1.5", "https://example.com/123", "123", " 123 "])
+def test_invalid_project_id_prevents_probe(project_id: str) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.ahrefs.source.validate_ahrefs_credentials"
+ ) as validate:
+ valid, message = AhrefsSource().validate_credentials(
+ AhrefsSourceConfig(api_key="test-key", project_id=project_id), 1
+ )
+ assert valid is False
+ assert message == "Enter a positive Site Audit project ID from your Ahrefs project URL."
+ validate.assert_not_called()
+
+
[email protected]("project_id", ["123", "00123"])
+def test_valid_project_id_reaches_probe(project_id: str) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.ahrefs.source.validate_ahrefs_credentials",
+ return_value=(True, None),
+ ) as validate:
+ assert AhrefsSource().validate_credentials(
+ AhrefsSourceConfig(api_key="test-key", project_id=project_id), 1
+ ) == (
+ True,
+ None,
+ )
+ validate.assert_called_once_with("test-key")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/ahrefs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/ahrefs.py
index 8653d3977454..7259ee34a9fe 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/ahrefs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/ahrefs.py
@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class AhrefsSourceConfig(config.Config):
- pass
+ api_key: str
+ project_id: str