: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(warehouse-sources): implement bing webmaster tools source (#79767)
jake sciottoe437500f3665
diff --git a/frontend/public/services/bing_webmaster_tools.png b/frontend/public/services/bing_webmaster_tools.pngindex c5736e43b50d..266b36fc29b1 100644Binary files a/frontend/public/services/bing_webmaster_tools.png and b/frontend/public/services/bing_webmaster_tools.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 7cd02819089d..20382c3a5003 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -108,6 +108,7 @@ the row lists both.| bigquery | HTTP + gRPC | google-cloud-bigquery + bigquery-storage | ✅ (HTTP + gRPC) || bill_com | HTTP | requests | ✅ || bing_ads | HTTP (vendor SDK, SOAP) | bingads SDK | ⚠️ |+| bing_webmaster_tools | HTTP | requests | ✅ || bitbucket | HTTP | requests | ✅ || bitrise | HTTP | requests | ✅ || bland_ai | HTTP | requests | ✅ |@@ -842,7 +843,6 @@ doesn't conflict with concurrent PRs.- bigeye- billit- billomat-- bing_webmaster_tools- bitly- bitwarden- blackbaud_raisers_edge_nxtdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_webmaster_tools/bing_webmaster_tools.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_webmaster_tools/bing_webmaster_tools.pynew file mode 100644index 000000000000..6dac46cf0a6a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_webmaster_tools/bing_webmaster_tools.py@@ -0,0 +1,308 @@+import re+import datetime as dt+from collections.abc import Iterator+from typing import Any++import requests+from structlog.types import FilteringBoundLogger++from products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConvention+from products.warehouse_sources.backend.temporal.data_imports.sources.bing_webmaster_tools.settings import (+ BASE_URL,+ ENDPOINT_CONFIGS,+)+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.typings import SourceResponse++REQUEST_TIMEOUT_SECONDS = 60++# Credential validation runs synchronously on a web worker during source setup, so bound it more+# tightly than a background sync request.+VALIDATION_TIMEOUT_SECONDS = 30+++class BingWebmasterToolsError(Exception):+ """API-level failure carrying the ApiFault ``Message`` (e.g. InvalidApiKey, NotAuthorized).++ The fault message is part of the exception text so ``get_non_retryable_errors`` can match on+ it. Faults not in that map (e.g. throttling) stay retryable at the activity level.+ """+++# The API key rides the `apikey` query param, so it ends up in the request URL that+# `raise_for_status()` embeds in its message. Redact it so the key never reaches stored errors.+_APIKEY_RE = re.compile(r"([?&]apikey=)[^&\s]+", re.IGNORECASE)++# WCF JSON date, e.g. `/Date(1316156400000-0700)/`: milliseconds since the Unix epoch (UTC),+# optionally followed by the local UTC offset the value was recorded in.+_WCF_DATE_RE = re.compile(r"^/Date\((-?\d+)(?:([+-])(\d{2})(\d{2}))?\)/$")+++def _redact_api_key(text: str) -> str:+ return _APIKEY_RE.sub(r"\1REDACTED", text)+++def parse_wcf_date(value: Any) -> dt.date | None:+ """Parse a WCF JSON date into the calendar date the API meant.++ The milliseconds are the UTC epoch instant of local midnight, so the embedded offset must be+ applied before truncating to a date; dropping it would shift dates recorded in timezones east+ of UTC onto the previous day. Returns None for anything unparseable.+ """+ if not isinstance(value, str):+ return None+ match = _WCF_DATE_RE.match(value.strip())+ if match is None:+ return None+ moment = dt.datetime.fromtimestamp(int(match.group(1)) / 1000, tz=dt.UTC)+ if match.group(2) is not None:+ sign = 1 if match.group(2) == "+" else -1+ moment += sign * dt.timedelta(hours=int(match.group(3)), minutes=int(match.group(4)))+ return moment.date()+++def _api_fault_message(response: requests.Response) -> str | None:+ """Extract the ApiFault ``Message`` (e.g. "InvalidApiKey") from an error body, if present."""+ try:+ body = response.json()+ except ValueError:+ return None+ if not isinstance(body, dict):+ return None+ for candidate in (body, body.get("d")):+ if isinstance(candidate, dict):+ message = candidate.get("Message")+ if isinstance(message, str) and message:+ return message+ return None+++def _request(+ session: requests.Session,+ api_key: str,+ method: str,+ params: dict[str, str] | None = None,+ timeout: int = REQUEST_TIMEOUT_SECONDS,+) -> list[dict[str, Any]]:+ try:+ response = session.get(+ f"{BASE_URL}/{method}",+ params={"apikey": api_key, **(params or {})},+ timeout=timeout,+ )+ except requests.RequestException as exc:+ # Connection and timeout errors embed the full request URL (including `apikey`) in their+ # message, and `str(error)` ends up in logs and the schema's stored error. Re-raise the+ # same type with the key redacted; preserving the type keeps retry classification intact.+ raise type(exc)(_redact_api_key(str(exc))) from None++ if not response.ok:+ fault = _api_fault_message(response)+ if fault is not None:+ raise BingWebmasterToolsError(+ f"Bing Webmaster Tools {method} failed with status {response.status_code}: {fault}"+ )+ try:+ response.raise_for_status()+ except requests.HTTPError as exc:+ # Keep the `... for url: https://ssl.bing.com` shape intact for non-retryable matching,+ # with the key redacted out of the embedded URL.+ raise requests.HTTPError(_redact_api_key(str(exc)), response=exc.response) from None++ try:+ payload = response.json()+ except ValueError:+ raise BingWebmasterToolsError(f"Bing Webmaster Tools {method} returned a non-JSON response")++ # Successful responses wrap the result list in WCF's `d` envelope: `{"d": [...]}`.+ data = payload.get("d") if isinstance(payload, dict) else None+ if not isinstance(data, list):+ raise BingWebmasterToolsError(f"Bing Webmaster Tools {method} returned an unexpected response shape")+ return [item for item in data if isinstance(item, dict)]+++def _site_key(url: str) -> str:+ """Comparison key for site URLs: hosts are case-insensitive and Bing usually lists sites with a+ trailing slash, so compare lowercased and without one."""+ return url.strip().rstrip("/").lower()+++def parse_site_urls(raw: str | None) -> list[str]:+ """Parse the optional site filter field: one URL per line, blanks skipped, duplicates dropped."""+ if not raw:+ return []+ urls: list[str] = []+ seen: set[str] = set()+ for line in raw.splitlines():+ stripped = line.strip()+ if not stripped:+ continue+ key = _site_key(stripped)+ if key in seen:+ continue+ seen.add(key)+ urls.append(stripped)+ return urls+++def select_site_urls(sites: list[dict[str, Any]], site_url_filters: list[str]) -> list[str]:+ """Pick the verified site URLs to sync, honoring the user's optional filter list.++ Stats calls against unverified sites fail, so only verified sites are eligible. A filter entry+ matching no verified site raises: a silent skip would read as "synced fine, zero rows" for a+ site the user explicitly asked for.+ """+ verified = [url for site in sites if site.get("IsVerified") and (url := site.get("Url"))]+ if not site_url_filters:+ return verified++ by_key = {_site_key(url): url for url in verified}+ selected: list[str] = []+ missing: list[str] = []+ for filter_url in site_url_filters:+ matched = by_key.get(_site_key(filter_url))+ if matched is None:+ missing.append(filter_url)+ else:+ selected.append(matched)+ if missing:+ raise ValueError(+ f"These site URLs are not verified sites on the connected account: {', '.join(missing)}. "+ "Enter each site exactly as Bing Webmaster Tools lists it, or clear the field to sync "+ "every verified site."+ )+ return selected+++def _site_row(site: dict[str, Any]) -> dict[str, Any]:+ # AuthenticationCode and DnsVerificationCode are site-ownership verification tokens with no+ # analytics value, so they stay out of the warehouse.+ return {"url": site.get("Url"), "is_verified": bool(site.get("IsVerified", False))}+++def _stats_row(item: dict[str, Any], site_url: str) -> dict[str, Any] | None:+ """Turn one API stats object into a row: snake_case keys, parsed date, stamped site URL.++ Keys are normalized with the same convention the pipeline applies to column names, so the+ declared primary/partition keys match the yielded rows exactly. `date` is part of every stats+ table's primary key, so it is indexed directly: a missing field is a structural API change that+ should fail loudly, while a present-but-malformed value skips the row so a null key never flows+ into the merge.+ """+ row = {NamingConvention.normalize_identifier(key): value for key, value in item.items() if key != "__type"}+ date = parse_wcf_date(row["date"])+ if date is None:+ return None+ row["date"] = date+ row["site_url"] = site_url+ return row+++def get_rows(+ api_key: str,+ endpoint: str,+ site_urls_raw: str | None,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ config = ENDPOINT_CONFIGS[endpoint]+ # One session reused across every call so urllib3 keeps the connection alive. `redact_values`+ # masks the API key wherever the tracked transport logs or samples the request URL.+ session = make_tracked_session(redact_values=(api_key,))+ sites = _request(session, api_key, "GetUserSites")++ if not config.per_site:+ rows = [_site_row(site) for site in sites if site.get("Url")]+ if rows:+ yield rows+ return++ for site_url in select_site_urls(sites, parse_site_urls(site_urls_raw)):+ items = _request(session, api_key, config.method, {"siteUrl": site_url})+ rows = []+ dropped = 0+ for item in items:+ row = _stats_row(item, site_url)+ if row is None:+ dropped += 1+ else:+ rows.append(row)+ if dropped:+ logger.warning(+ "Dropped Bing Webmaster Tools rows with unparseable dates",+ endpoint=endpoint,+ site_url=site_url,+ dropped=dropped,+ )+ if rows:+ yield rows+++def validate_credentials(api_key: str, site_urls_raw: str | None) -> tuple[bool, str | None]:+ """Probe GetUserSites: one cheap call that authenticates the key and returns the site list,+ which also lets the optional site filter be checked against what the account can actually see."""+ session = make_tracked_session(redact_values=(api_key,))+ try:+ sites = _request(session, api_key, "GetUserSites", timeout=VALIDATION_TIMEOUT_SECONDS)+ except BingWebmasterToolsError as exc:+ message = str(exc)+ if "InvalidApiKey" in message or "UserNotFound" in message:+ return False, (+ "Bing Webmaster Tools rejected the API key. Generate a new key under Settings > "+ "API access in Bing Webmaster Tools and try again."+ )+ return False, f"Could not validate the Bing Webmaster Tools connection: {message}"+ except requests.HTTPError as exc:+ status = exc.response.status_code if exc.response is not None else None+ if status in (400, 401, 403):+ return False, (+ "Bing Webmaster Tools rejected the API key. Generate a new key under Settings > "+ "API access in Bing Webmaster Tools and try again."+ )+ return False, "The Bing Webmaster Tools API returned an error. Try again in a few minutes."+ except requests.RequestException:+ return False, "Could not reach the Bing Webmaster Tools API. Please try again."++ try:+ selected = select_site_urls(sites, parse_site_urls(site_urls_raw))+ except ValueError as exc:+ return False, str(exc)++ if not selected:+ return False, (+ "The connected account has no verified sites in Bing Webmaster Tools. Verify a site first, then reconnect."+ )+ return True, None+++def bing_webmaster_tools_source(+ api_key: str,+ endpoint: str,+ site_urls_raw: str | None,+ logger: FilteringBoundLogger,+) -> SourceResponse:+ config = ENDPOINT_CONFIGS[endpoint]++ if not config.per_site:+ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(api_key=api_key, endpoint=endpoint, site_urls_raw=site_urls_raw, logger=logger),+ primary_keys=list(config.primary_keys),+ # A snapshot of the current account state, with no timestamp to order or partition on.+ sort_mode=None,+ )++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(api_key=api_key, endpoint=endpoint, site_urls_raw=site_urls_raw, logger=logger),+ primary_keys=list(config.primary_keys),+ partition_count=1,+ partition_size=1,+ partition_mode="datetime",+ partition_format="month",+ partition_keys=["date"],+ # Bing documents no ordering for these responses, and the multi-site fan-out interleaves+ # date ranges across batches anyway, so no per-batch watermark checkpointing is claimed.+ # The source never consumes the watermark: every sync refetches the full retained window+ # and relies on merge dedupe.+ sort_mode=None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_webmaster_tools/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_webmaster_tools/canonical_descriptions.pynew file mode 100644index 000000000000..1f802eed8a20--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_webmaster_tools/canonical_descriptions.py@@ -0,0 +1,93 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_API_DOCS_BASE = "https://learn.microsoft.com/en-us/dotnet/api/microsoft.bing.webmaster.api.interfaces.iwebmasterapi"++_SITE_URL_COLUMN = {+ "site_url": "The verified site these statistics belong to, as listed in Bing Webmaster Tools.",+}++_DATE_COLUMN = {+ "date": "The day the data point was recorded.",+}++# GetQueryStats and GetPageStats return the same QueryStats shape; for page stats the `query`+# field carries the page URL instead of a search query.+_QUERY_STATS_METRIC_COLUMNS = {+ "impressions": "Number of times the site appeared in Bing search results.",+ "clicks": "Number of clicks on the site's results.",+ "avg_click_position": "Average position of the site's result among impressions that were clicked.",+ "avg_impression_position": "Average position at which the site appeared in search results.",+}++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "sites": {+ "description": "Sites registered on the connected Bing Webmaster Tools account and whether each one is verified.",+ "docs_url": f"{_API_DOCS_BASE}.getusersites",+ "columns": {+ "url": "The site URL as registered in Bing Webmaster Tools.",+ "is_verified": "Whether ownership of the site has been verified.",+ },+ },+ "query_stats": {+ "description": (+ "Traffic statistics for the site's top search queries on Bing. Bing updates this data "+ "weekly and retains about six months."+ ),+ "docs_url": f"{_API_DOCS_BASE}.getquerystats",+ "columns": {+ **_DATE_COLUMN,+ "query": "The search query users typed.",+ **_QUERY_STATS_METRIC_COLUMNS,+ **_SITE_URL_COLUMN,+ },+ },+ "page_stats": {+ "description": (+ "Traffic statistics for the site's top pages on Bing. Bing updates this data weekly "+ "and retains about six months."+ ),+ "docs_url": f"{_API_DOCS_BASE}.getpagestats",+ "columns": {+ **_DATE_COLUMN,+ "query": "The page URL (the API returns pages in its query field).",+ **_QUERY_STATS_METRIC_COLUMNS,+ **_SITE_URL_COLUMN,+ },+ },+ "rank_and_traffic_stats": {+ "description": (+ "Daily impressions and clicks for the site in Bing search. Since March 24, 2023 the "+ "counts cover all Bing verticals: web, chat, news, images, videos, and knowledge panel."+ ),+ "docs_url": f"{_API_DOCS_BASE}.getrankandtrafficstats",+ "columns": {+ **_DATE_COLUMN,+ "impressions": "Number of times the site appeared in Bing search results on this day.",+ "clicks": "Number of clicks on the site's results on this day.",+ **_SITE_URL_COLUMN,+ },+ },+ "crawl_stats": {+ "description": "Daily Bingbot crawl activity for the site over the last six months.",+ "docs_url": f"{_API_DOCS_BASE}.getcrawlstats",+ "columns": {+ **_DATE_COLUMN,+ "crawled_pages": "Number of pages Bingbot crawled.",+ "in_index": "Number of the site's pages in the Bing index.",+ "in_links": "Number of inbound links Bing has discovered to the site.",+ "crawl_errors": "Number of pages that returned a crawl error.",+ "blocked_by_robots_txt": "Number of pages blocked from crawling by robots.txt.",+ "code2xx": "Number of crawled pages that returned an HTTP 2xx status.",+ "code301": "Number of crawled pages that returned an HTTP 301 redirect.",+ "code302": "Number of crawled pages that returned an HTTP 302 redirect.",+ "code4xx": "Number of crawled pages that returned an HTTP 4xx error.",+ "code5xx": "Number of crawled pages that returned an HTTP 5xx error.",+ "all_other_codes": "Number of crawled pages that returned any other HTTP status.",+ "connection_timeout": "Number of crawl attempts that timed out connecting.",+ "dns_failures": "Number of crawl attempts that failed DNS resolution.",+ **_SITE_URL_COLUMN,+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_webmaster_tools/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_webmaster_tools/settings.pynew file mode 100644index 000000000000..36c8fe4caadf--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_webmaster_tools/settings.py@@ -0,0 +1,77 @@+from dataclasses import dataclass, field++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++BASE_URL = "https://ssl.bing.com/webmaster/api.svc/json"++# Every stats row carries `date`, parsed from the API's WCF-serialized `Date` field. The API has no+# server-side time filter (each call returns the full ~6-month window Bing retains), so `date` is+# declared as an incremental field purely to enable the merge sync method: refetched rows dedupe on+# the primary key while rows Bing has already expired stay in the warehouse, accumulating history+# beyond the vendor's retention.+_DATE_INCREMENTAL_FIELDS: list[IncrementalField] = [+ {+ "label": "date",+ "type": IncrementalFieldType.Date,+ "field": "date",+ "field_type": IncrementalFieldType.Date,+ },+]+++@dataclass+class BingWebmasterToolsEndpoint:+ # JSON API operation name, e.g. "GetQueryStats" (https://ssl.bing.com/webmaster/api.svc/json/{method}).+ method: str+ primary_keys: list[str]+ # Per-site endpoints take a `siteUrl` param and are fanned out over every selected verified site,+ # with each row stamped with `site_url` (which is why it leads the primary key).+ per_site: bool = True+ incremental_fields: list[IncrementalField] = field(default_factory=lambda: list(_DATE_INCREMENTAL_FIELDS))+ should_sync_default: bool = True+ description: str | None = None+++ENDPOINT_CONFIGS: dict[str, BingWebmasterToolsEndpoint] = {+ "sites": BingWebmasterToolsEndpoint(+ method="GetUserSites",+ primary_keys=["url"],+ per_site=False,+ incremental_fields=[],+ description="Every site registered on the connected Bing Webmaster Tools account, with its verification status.",+ ),+ "query_stats": BingWebmasterToolsEndpoint(+ method="GetQueryStats",+ primary_keys=["site_url", "date", "query"],+ description=(+ "Traffic statistics for the site's top search queries: impressions, clicks, and average "+ "positions. Bing updates this data weekly and retains about six months."+ ),+ ),+ "page_stats": BingWebmasterToolsEndpoint(+ method="GetPageStats",+ primary_keys=["site_url", "date", "query"],+ description=(+ "Traffic statistics for the site's top pages: impressions, clicks, and average positions. "+ "The page URL is in the query column. Bing updates this data weekly and retains about six months."+ ),+ ),+ "rank_and_traffic_stats": BingWebmasterToolsEndpoint(+ method="GetRankAndTrafficStats",+ primary_keys=["site_url", "date"],+ description=(+ "Daily impressions and clicks for the site across Bing search verticals. "+ "Bing updates this data daily and retains about six months."+ ),+ ),+ "crawl_stats": BingWebmasterToolsEndpoint(+ method="GetCrawlStats",+ primary_keys=["site_url", "date"],+ description=(+ "Daily Bingbot crawl activity for the site: pages crawled, crawl errors, HTTP status code "+ "counts, and pages in the index. Bing retains about six months."+ ),+ ),+}++ENDPOINTS = tuple(ENDPOINT_CONFIGS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_webmaster_tools/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_webmaster_tools/source.pyindex 897936749f3b..0b32ee152dbf 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_webmaster_tools/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_webmaster_tools/source.py@@ -1,13 +1,28 @@-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.bing_webmaster_tools.bing_webmaster_tools import (+ bing_webmaster_tools_source,+ validate_credentials as validate_bing_webmaster_tools_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.bing_webmaster_tools.settings import (+ ENDPOINT_CONFIGS,+)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+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.bingwebmastertools import (BingWebmasterToolsSourceConfig,)@@ -16,17 +31,125 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.registerclass BingWebmasterToolsSource(SimpleSource[BingWebmasterToolsSourceConfig]):+ # `get_schemas` iterates a static endpoint catalog with no I/O, so the table list is safe to+ # render in public docs without credentials.+ lists_tables_without_credentials = True+ # The JSON API (`/webmaster/api.svc/json`) has no version path segment, version header, or dated+ # releases, so the framework's unversioned default stands.+ api_docs_url = "https://learn.microsoft.com/en-us/bingwebmaster/"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.BINGWEBMASTERTOOLS+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ # ApiFault messages (surfaced by `BingWebmasterToolsError`) for credential and access+ # problems are deterministic; throttling faults deliberately stay unmatched so Temporal+ # retries them at the activity level.+ return {+ "InvalidApiKey": "Your Bing Webmaster Tools API key is invalid. Generate a new key under Settings > API access in Bing Webmaster Tools, then reconnect.",+ "UserNotFound": "Bing Webmaster Tools did not recognize the API key. Generate a new key under Settings > API access in Bing Webmaster Tools, then reconnect.",+ "NotAuthorized": "The API key does not have access to this site. Make sure the site is verified on the connected Bing Webmaster Tools account.",+ "401 Client Error": "Your Bing Webmaster Tools API key is invalid or expired. Generate a new key and reconnect.",+ "403 Client Error": "Your Bing Webmaster Tools API key does not have access to this site. Verify the site on the connected account and reconnect.",+ # Fault-less 400s carry the redacted request URL; a 400 from this API is a deterministic+ # rejection of the key or the requested site, not a transient failure.+ "400 Client Error: Bad Request for url: https://ssl.bing.com": "Bing Webmaster Tools rejected the request. Check that the API key is valid and that the connected account can access the configured sites.",+ # A site filter naming a site the account can't see fails every sync until the config+ # changes; the raised message already tells the user how to fix it.+ "not verified sites on the connected account": None,+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.bing_webmaster_tools.canonical_descriptions import ( # noqa: PLC0415 (keeps the descriptions dict off the registry import path; only the enrichment activity reads it)+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: BingWebmasterToolsSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=name,+ # The API has no server-side time filter, so every sync refetches the ~6-month+ # window Bing retains. "Incremental" here means merge-on-primary-key, which keeps+ # rows the vendor has already expired. Append is unsupported because refetching the+ # same window would duplicate it on every sync.+ supports_incremental=bool(endpoint.incremental_fields),+ supports_append=False,+ incremental_fields=endpoint.incremental_fields,+ description=endpoint.description,+ should_sync_default=endpoint.should_sync_default,+ )+ for name, endpoint in ENDPOINT_CONFIGS.items()+ ]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self,+ config: BingWebmasterToolsSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_bing_webmaster_tools_credentials(config.api_key, config.site_urls)++ def source_for_pipeline(self, config: BingWebmasterToolsSourceConfig, inputs: SourceInputs) -> SourceResponse:+ return bing_webmaster_tools_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ site_urls_raw=config.site_urls,+ logger=inputs.logger,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.BING_WEBMASTER_TOOLS,category=DataWarehouseSourceCategory.ANALYTICS,- label="Microsoft (Bing Webmaster Tools)",+ keywords=["bing", "seo", "organic search", "search analytics"],+ label="Bing Webmaster Tools",+ caption="""Sync your site's organic search performance on Bing into the PostHog Data warehouse: top queries, top pages, daily rank and traffic, and crawl statistics.++Generate an API key in [Bing Webmaster Tools](https://www.bing.com/webmasters) under **Settings > API access > API key**. The key is issued per user and covers every verified site on the account.+""",+ releaseStatus=ReleaseStatus.ALPHA,iconPath="/static/services/bing_webmaster_tools.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/bing-webmaster-tools",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="Your Bing Webmaster Tools API key",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="site_urls",+ label="Site URLs",+ type=SourceFieldInputConfigType.TEXTAREA,+ required=False,+ placeholder="https://example.com/",+ secret=False,+ caption=(+ "Optional. One site per line, exactly as Bing Webmaster Tools lists it. "+ "Leave empty to sync every verified site on the account."+ ),+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_webmaster_tools/tests/test_bing_webmaster_tools.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_webmaster_tools/tests/test_bing_webmaster_tools.pynew file mode 100644index 000000000000..d53df6b021b0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_webmaster_tools/tests/test_bing_webmaster_tools.py@@ -0,0 +1,341 @@+import json+import datetime as dt+from typing import Any, Optional++import pytest+from unittest import mock++import requests+import structlog++from products.warehouse_sources.backend.temporal.data_imports.sources.bing_webmaster_tools.bing_webmaster_tools import (+ BingWebmasterToolsError,+ _request,+ _stats_row,+ bing_webmaster_tools_source,+ get_rows,+ parse_site_urls,+ parse_wcf_date,+ select_site_urls,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.bing_webmaster_tools.settings import (+ BASE_URL,+ ENDPOINT_CONFIGS,+ ENDPOINTS,+)++MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.bing_webmaster_tools.bing_webmaster_tools"++_SITES = [+ {+ "__type": "Site:#Microsoft.Bing.Webmaster.Api",+ "Url": "https://example.com/",+ "IsVerified": True,+ "AuthenticationCode": "258CAD36B9EEE22F1CFDEB4C239D26BB",+ "DnsVerificationCode": "258cad36b9eee22f1cfdeb4c239d26bb.example.com",+ },+ {+ "__type": "Site:#Microsoft.Bing.Webmaster.Api",+ "Url": "http://unverified.example.org",+ "IsVerified": False,+ "AuthenticationCode": "AAAA",+ "DnsVerificationCode": "aaaa.unverified.example.org",+ },+]++_QUERY_STATS = [+ {+ "__type": "QueryStats:#Microsoft.Bing.Webmaster.Api",+ "AvgClickPosition": 18,+ "AvgImpressionPosition": 17,+ "Clicks": 15,+ "Date": "/Date(1316156400000-0700)/",+ "Impressions": 100,+ "Query": "query",+ },+]+++def _response(status: int = 200, body: Optional[Any] = None, json_error: bool = False) -> mock.MagicMock:+ resp = mock.MagicMock()+ resp.status_code = status+ resp.ok = 200 <= status < 300+ if json_error:+ resp.json.side_effect = ValueError("no json")+ resp.text = "<html>error</html>"+ else:+ resp.json.return_value = body+ resp.text = json.dumps(body)+ if not resp.ok:+ resp.raise_for_status.side_effect = requests.HTTPError(+ f"{status} Client Error: Bad Request for url: {BASE_URL}/GetUserSites?apikey=super-secret-key",+ response=resp,+ )+ return resp+++def _session(responses: dict[str, mock.MagicMock]) -> mock.MagicMock:+ """Fake tracked session routing by API method name in the request URL."""+ session = mock.MagicMock()++ def _get(url: str, params: Any = None, timeout: Any = None) -> mock.MagicMock:+ method = url.rsplit("/", 1)[-1]+ return responses[method]++ session.get.side_effect = _get+ return session+++class TestParseWcfDate:+ @pytest.mark.parametrize(+ "value, expected",+ [+ # Doc sample: midnight Pacific serialized as UTC millis plus the local offset.+ ("/Date(1316156400000-0700)/", dt.date(2011, 9, 16)),+ # Without the offset the UTC calendar date is what the instant means.+ ("/Date(1316156400000)/", dt.date(2011, 9, 16)),+ # East-of-UTC offset pushes the local date past midnight; ignoring it would+ # yield the previous day.+ ("/Date(82800000+0200)/", dt.date(1970, 1, 2)),+ ],+ )+ def test_parses_wcf_dates(self, value, expected):+ assert parse_wcf_date(value) == expected++ @pytest.mark.parametrize(+ "value",+ ["2011-09-16", "", "/Date()/", "/Date(abc)/", None, 1316156400000, {"Date": "x"}],+ )+ def test_unparseable_returns_none(self, value):+ assert parse_wcf_date(value) is None+++class TestStatsRow:+ def test_normalizes_keys_parses_date_and_stamps_site(self):+ row = _stats_row(_QUERY_STATS[0], "https://example.com/")++ assert row == {+ "avg_click_position": 18,+ "avg_impression_position": 17,+ "clicks": 15,+ "date": dt.date(2011, 9, 16),+ "impressions": 100,+ "query": "query",+ "site_url": "https://example.com/",+ }++ def test_unparseable_date_skips_row(self):+ item = {**_QUERY_STATS[0], "Date": "not-a-date"}++ assert _stats_row(item, "https://example.com/") is None++ def test_missing_date_fails_loudly(self):+ item = {key: value for key, value in _QUERY_STATS[0].items() if key != "Date"}++ with pytest.raises(KeyError):+ _stats_row(item, "https://example.com/")+++class TestSiteSelection:+ @pytest.mark.parametrize(+ "raw, expected",+ [+ (None, []),+ ("", []),+ (" \n \n", []),+ ("https://example.com/", ["https://example.com/"]),+ ("https://a.com/\n\nhttps://b.com", ["https://a.com/", "https://b.com"]),+ # Duplicates (also with slash/case variance) are dropped so one site can't be+ # fanned out twice and seed duplicate primary keys within one sync.+ ("https://a.com/\nhttps://A.com", ["https://a.com/"]),+ ],+ )+ def test_parse_site_urls(self, raw, expected):+ assert parse_site_urls(raw) == expected++ def test_no_filter_selects_only_verified_sites(self):+ assert select_site_urls(_SITES, []) == ["https://example.com/"]++ @pytest.mark.parametrize(+ "filter_url",+ ["https://example.com/", "https://example.com", "HTTPS://EXAMPLE.COM/"],+ )+ def test_filter_matches_leniently_but_returns_registered_form(self, filter_url):+ assert select_site_urls(_SITES, [filter_url]) == ["https://example.com/"]++ def test_filter_matching_no_verified_site_raises(self):+ with pytest.raises(ValueError, match="not verified sites on the connected account"):+ select_site_urls(_SITES, ["http://unverified.example.org"])+++class TestRequest:+ def test_returns_unwrapped_list(self):+ session = _session({"GetUserSites": _response(200, {"d": _SITES})})++ assert _request(session, "key", "GetUserSites") == _SITES++ def test_api_fault_message_is_surfaced(self):+ session = _session({"GetUserSites": _response(400, {"ErrorCode": 3, "Message": "InvalidApiKey"})})++ with pytest.raises(BingWebmasterToolsError, match="InvalidApiKey"):+ _request(session, "key", "GetUserSites")++ def test_faultless_http_error_redacts_api_key(self):+ session = _session({"GetUserSites": _response(400, body=None, json_error=True)})++ with pytest.raises(requests.HTTPError) as exc_info:+ _request(session, "super-secret-key", "GetUserSites")++ assert "super-secret-key" not in str(exc_info.value)+ assert "apikey=REDACTED" in str(exc_info.value)++ @pytest.mark.parametrize("exc_type", [requests.ConnectionError, requests.ReadTimeout])+ def test_transport_error_redacts_api_key(self, exc_type):+ # Connection/timeout errors embed the request URL in their message; the stringified+ # error reaches logs and the schema's stored error, so the key must not survive.+ session = mock.MagicMock()+ session.get.side_effect = exc_type(+ "HTTPSConnectionPool(host='ssl.bing.com', port=443): Max retries exceeded with url: "+ "/webmaster/api.svc/json/GetUserSites?apikey=super-secret-key"+ )++ with pytest.raises(exc_type) as exc_info:+ _request(session, "super-secret-key", "GetUserSites")++ assert "super-secret-key" not in str(exc_info.value)+ assert "apikey=REDACTED" in str(exc_info.value)++ @pytest.mark.parametrize("body", [{"unexpected": True}, {"d": "not-a-list"}, [1, 2], None])+ def test_unexpected_response_shape_raises(self, body):+ session = _session({"GetUserSites": _response(200, body)})++ with pytest.raises(BingWebmasterToolsError, match="unexpected response shape"):+ _request(session, "key", "GetUserSites")+++class TestGetRows:+ def setup_method(self):+ self.logger = structlog.get_logger()++ def test_sites_rows_keep_only_url_and_verification(self):+ # Ownership-verification tokens must not reach the warehouse.+ session = _session({"GetUserSites": _response(200, {"d": _SITES})})++ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ batches = list(get_rows("key", "sites", None, self.logger))++ assert batches == [+ [+ {"url": "https://example.com/", "is_verified": True},+ {"url": "http://unverified.example.org", "is_verified": False},+ ]+ ]++ def test_stats_fan_out_over_verified_sites_only(self):+ session = _session(+ {+ "GetUserSites": _response(200, {"d": _SITES}),+ "GetQueryStats": _response(200, {"d": _QUERY_STATS}),+ }+ )++ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ batches = list(get_rows("key", "query_stats", None, self.logger))++ stats_calls = [call for call in session.get.call_args_list if "GetQueryStats" in call.args[0]]+ assert [call.kwargs["params"]["siteUrl"] for call in stats_calls] == ["https://example.com/"]+ assert batches == [+ [+ {+ "avg_click_position": 18,+ "avg_impression_position": 17,+ "clicks": 15,+ "date": dt.date(2011, 9, 16),+ "impressions": 100,+ "query": "query",+ "site_url": "https://example.com/",+ }+ ]+ ]++ def test_rows_with_unparseable_dates_are_dropped(self):+ bad_row = {**_QUERY_STATS[0], "Date": "garbage", "Query": "other"}+ session = _session(+ {+ "GetUserSites": _response(200, {"d": _SITES}),+ "GetQueryStats": _response(200, {"d": [*_QUERY_STATS, bad_row]}),+ }+ )++ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ batches = list(get_rows("key", "query_stats", None, self.logger))++ assert [row["query"] for batch in batches for row in batch] == ["query"]+++class TestValidateCredentials:+ def _validate(self, response: mock.MagicMock, site_urls: str | None = None) -> tuple[bool, str | None]:+ session = _session({"GetUserSites": response})+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ return validate_credentials("key", site_urls)++ def test_valid_key_with_verified_site(self):+ assert self._validate(_response(200, {"d": _SITES})) == (True, None)++ def test_invalid_api_key_fault_gives_key_guidance(self):+ ok, message = self._validate(_response(400, {"ErrorCode": 3, "Message": "InvalidApiKey"}))++ assert ok is False+ assert message is not None and "API access" in message++ def test_faultless_400_gives_key_guidance(self):+ ok, message = self._validate(_response(400, body=None, json_error=True))++ assert ok is False+ assert message is not None and "rejected the API key" in message++ def test_no_verified_sites_is_actionable(self):+ ok, message = self._validate(_response(200, {"d": [_SITES[1]]}))++ assert ok is False+ assert message is not None and "no verified sites" in message++ def test_filter_matching_nothing_is_actionable(self):+ ok, message = self._validate(_response(200, {"d": _SITES}), site_urls="https://other.example.net")++ assert ok is False+ assert message is not None and "not verified sites" in message++ def test_unreachable_api(self):+ session = mock.MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")++ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ ok, message = validate_credentials("key", None)++ assert ok is False+ assert message is not None and "Could not reach" in message+++class TestSourceResponse:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_primary_keys_match_endpoint_catalog(self, endpoint):+ response = bing_webmaster_tools_source("key", endpoint, None, structlog.get_logger())++ assert response.name == endpoint+ assert response.primary_keys == ENDPOINT_CONFIGS[endpoint].primary_keys+ # Bing documents no response ordering and the multi-site fan-out interleaves date ranges,+ # so no sort mode may be claimed: "asc" would checkpoint a corrupt incremental watermark.+ assert response.sort_mode is None++ def test_stats_tables_partition_on_date(self):+ response = bing_webmaster_tools_source("key", "query_stats", None, structlog.get_logger())++ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["date"]++ def test_sites_table_has_no_partitioning(self):+ response = bing_webmaster_tools_source("key", "sites", None, structlog.get_logger())++ assert response.partition_mode is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bing_webmaster_tools/tests/test_bing_webmaster_tools_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_webmaster_tools/tests/test_bing_webmaster_tools_source.pynew file mode 100644index 000000000000..292adf738771--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bing_webmaster_tools/tests/test_bing_webmaster_tools_source.py@@ -0,0 +1,129 @@+import pytest++import structlog++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.bing_webmaster_tools.settings import (+ ENDPOINT_CONFIGS,+ ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.bing_webmaster_tools.source import (+ BingWebmasterToolsSource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matches+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.bingwebmastertools import (+ BingWebmasterToolsSourceConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType++_STATS_ENDPOINTS = [name for name, endpoint in ENDPOINT_CONFIGS.items() if endpoint.per_site]+++def _make_inputs(schema_name: str) -> SourceInputs:+ return SourceInputs(+ schema_name=schema_name,+ schema_id="schema-id",+ source_id="source-id",+ team_id=123,+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ db_incremental_field_earliest_value=None,+ incremental_field=None,+ incremental_field_type=None,+ job_id="job-id",+ logger=structlog.get_logger(),+ reset_pipeline=False,+ )+++class TestBingWebmasterToolsSource:+ def setup_method(self):+ self.source = BingWebmasterToolsSource()+ self.team_id = 123+ self.config = BingWebmasterToolsSourceConfig(api_key="test-key")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.BINGWEBMASTERTOOLS++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "BingWebmasterTools"+ assert config.label == "Bing Webmaster Tools"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # `unreleasedSource` hides the connector from users entirely; a finished source must not+ # carry it.+ assert not config.unreleasedSource++ def test_get_source_config_fields(self):+ fields = self.source.get_source_config.fields++ by_name = {field.name: field for field in fields if isinstance(field, SourceFieldInputConfig)}+ assert set(by_name) == {"api_key", "site_urls"}++ api_key_field = by_name["api_key"]+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_key_field.required is True+ assert api_key_field.secret is True++ site_urls_field = by_name["site_urls"]+ assert site_urls_field.type == SourceFieldInputConfigType.TEXTAREA+ assert site_urls_field.required is False+ assert site_urls_field.secret is False++ def test_lists_tables_without_credentials(self):+ # Static endpoint catalog with no I/O; must opt in so public docs render the table list.+ assert self.source.lists_tables_without_credentials is True++ def test_get_schemas_lists_all_endpoints(self):+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {schema.name for schema in schemas} == set(ENDPOINTS)++ @pytest.mark.parametrize("endpoint", _STATS_ENDPOINTS)+ def test_stats_schemas_are_merge_only(self, endpoint):+ # Every sync refetches the same ~6-month window, so append would duplicate it; merge on+ # the primary key is the only safe incremental method.+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert schemas[endpoint].supports_incremental is True+ assert schemas[endpoint].supports_append is False+ assert [field["field"] for field in schemas[endpoint].incremental_fields] == ["date"]++ def test_sites_schema_is_full_refresh_only(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert schemas["sites"].supports_incremental is False+ assert schemas["sites"].supports_append is False++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["query_stats"])++ assert [schema.name for schema in schemas] == ["query_stats"]++ @pytest.mark.parametrize(+ "error_message",+ [+ "Bing Webmaster Tools GetUserSites failed with status 400: InvalidApiKey",+ "Bing Webmaster Tools GetQueryStats failed with status 400: NotAuthorized",+ "401 Client Error: Unauthorized for url: https://ssl.bing.com/webmaster/api.svc/json/GetUserSites?apikey=REDACTED",+ "400 Client Error: Bad Request for url: https://ssl.bing.com/webmaster/api.svc/json/GetQueryStats?apikey=REDACTED",+ ],+ )+ def test_non_retryable_errors_cover_credential_failures(self, error_message):+ assert error_message_matches(error_message, self.source.get_non_retryable_errors())++ def test_throttling_faults_stay_retryable(self):+ # A throttling fault must be retried by Temporal, not permanently fail the sync.+ message = "Bing Webmaster Tools GetQueryStats failed with status 429: ThrottleUser"++ assert not error_message_matches(message, self.source.get_non_retryable_errors())++ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_source_for_pipeline_plumbs_schema_name(self, endpoint):+ response = self.source.source_for_pipeline(self.config, _make_inputs(endpoint))++ assert response.name == endpoint+ assert response.primary_keys == ENDPOINT_CONFIGS[endpoint].primary_keysdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/bingwebmastertools.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/bingwebmastertools.pyindex 3eecc9d46c0d..519cd6e8b3c7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/bingwebmastertools.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/bingwebmastertools.py@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass BingWebmasterToolsSourceConfig(config.Config):- pass+ api_key: str+ site_urls: str | None = None