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 ip2whois import source (#67806)

Tom Owersf5298953c61b
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 920953a5b905..7a5899d1e45c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -177,6 +177,7 @@ the row lists both.
| incident_io | HTTP | requests | ✅ |
| insightly | HTTP | requests | ✅ |
| intercom | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| ip2whois | HTTP | requests | ✅ |
| iterable | HTTP | requests | ✅ |
| jira | HTTP | requests | ✅ |
| jotform | HTTP | requests | ✅ |
@@ -473,7 +474,6 @@ doesn't conflict with concurrent PRs.
- intruder
- invoiced
- invoiceninja
-- ip2whois
- jamf_pro
- jobber
- jobnimbus
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index a0647ad53148..7a73027b9ea3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -1574,7 +1574,8 @@ class HuntrSourceConfig(config.Config):
@config.config
class IP2WhoisSourceConfig(config.Config):
- pass
+ api_key: str
+ domains: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ip2whois/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ip2whois/canonical_descriptions.py
new file mode 100644
index 000000000000..1ca97a4bdc43
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ip2whois/canonical_descriptions.py
@@ -0,0 +1,32 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions taken from the public IP2WHOIS v2 API documentation. Contact sub-objects (registrant,
+# admin, tech, billing) share the same shape, so their nested fields aren't enumerated here — the
+# top-level object descriptions and docs_url cover them.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "whois": {
+ "description": (
+ "WHOIS registration record for a single domain, from the IP2WHOIS (IP2Location) lookup API. "
+ "One row per configured domain."
+ ),
+ "docs_url": "https://www.ip2whois.com/developers-api",
+ "columns": {
+ "domain": "The domain name that was looked up (the primary key; stamped from the configured domain).",
+ "domain_id": "Registry-assigned unique identifier for the domain.",
+ "status": "Domain status codes reported by the registry (e.g. clientTransferProhibited).",
+ "create_date": "Date the domain was first registered (ISO 8601).",
+ "update_date": "Date the WHOIS record was last updated (ISO 8601).",
+ "expire_date": "Date the domain registration expires (ISO 8601).",
+ "domain_age": "Age of the domain in days since registration.",
+ "whois_server": "WHOIS server that holds the record for this domain.",
+ "registrar": "Registrar details object (iana_id, name, url).",
+ "registrant": "Registrant contact object (name, organization, address, phone, fax, email).",
+ "admin": "Administrative contact object, same shape as registrant.",
+ "tech": "Technical contact object, same shape as registrant.",
+ "billing": "Billing contact object, same shape as registrant.",
+ "nameservers": "List of nameserver hostnames for the domain.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ip2whois/ip2whois.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ip2whois/ip2whois.py
new file mode 100644
index 000000000000..4f2699b50f8a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ip2whois/ip2whois.py
@@ -0,0 +1,259 @@
+import re
+from collections.abc import Iterator
+from typing import Any
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.ip2whois.settings import IP2WHOIS_ENDPOINTS
+
+# Single WHOIS lookup endpoint. Auth is the API key on the `key` query param (the docs also allow a
+# Bearer header — the query param is simpler and equivalent). One domain per request via `domain`.
+IP2WHOIS_BASE_URL = "https://api.ip2whois.com/v2"
+
+REQUEST_TIMEOUT_SECONDS = 30
+MAX_RETRY_ATTEMPTS = 5
+
+# Each domain costs one request on every sync, so cap the configured list to bound worker time and
+# outbound fan-out. The free tier is capped at 500 lookups/month; paid plans raise the quota, so this
+# is set above the free cap while still preventing a malformed/abusive config from tying up the worker.
+MAX_DOMAINS = 1000
+
+# A permissive registrable-domain shape: dot-separated labels of letters/digits/hyphens, ending in an
+# alphabetic TLD. Deliberately lenient (accepts IDNs in punycode form, multi-level TLDs) — it only
+# filters out obvious garbage (spaces, missing dot) so the sync doesn't burn a lookup credit on it.
+_DOMAIN_RE = re.compile(r"^(?=.{1,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$")
+
+# Error codes that are specific to the one domain being looked up (invalid/missing domain), so the
+# sync skips just that entry and keeps going. This is an allow-list on purpose: only 10007 is
+# curl-verified as domain-level, and the full code set for quota/disabled-key states could not be
+# verified without a paid key. Any code NOT listed here — including unknown quota/account errors —
+# fails the run loudly rather than silently swallowing every row, so a full-refresh sync can never
+# replace the table with an empty result off the back of a misclassified account error.
+_DOMAIN_LEVEL_ERROR_CODES: frozenset[int] = frozenset({10007})
+
+
+class IP2WhoisRetryableError(Exception):
+ pass
+
+
+class IP2WhoisAPIError(Exception):
+ pass
+
+
+def normalize_domain(raw: str) -> str | None:
+ """Normalize a single user-entered token into a bare registrable domain, or ``None`` if unusable.
+
+ Accepts a raw hostname or a pasted URL. Strips any scheme, path/query, leading ``www.``, and
+ surrounding punctuation, then lowercases. Returns ``None`` when the result doesn't look like a
+ domain so the caller can skip it rather than spend an API lookup on garbage.
+ """
+ token = raw.strip()
+ if not token:
+ return None
+ # Drop a scheme and everything after the host (path/query/fragment/port), if the user pasted a URL.
+ token = re.sub(r"^[a-z][a-z0-9+.-]*://", "", token, flags=re.IGNORECASE)
+ token = re.split(r"[/?#]", token, maxsplit=1)[0]
+ token = token.split(":", 1)[0]
+ token = token.strip().strip(".").lower()
+ if token.startswith("www."):
+ token = token[4:]
+ if not token or not _DOMAIN_RE.match(token):
+ return None
+ return token
+
+
+def parse_domains(raw: str | None) -> list[str]:
+ """Parse the user's free-text ``domains`` field into a deduped list of registrable domains.
+
+ Tokens may be separated by newlines, commas, or whitespace. Raises ``ValueError`` with an
+ actionable message when nothing usable is found or the list is too long, so the user fixes the
+ config instead of getting a silently empty sync.
+ """
+ if not raw or not raw.strip():
+ raise ValueError("At least one domain is required.")
+
+ seen: set[str] = set()
+ domains: list[str] = []
+ for token in re.split(r"[\s,]+", raw):
+ domain = normalize_domain(token)
+ if domain is None or domain in seen:
+ continue
+ seen.add(domain)
+ domains.append(domain)
+ if len(domains) > MAX_DOMAINS:
+ raise ValueError(f"Too many domains: at most {MAX_DOMAINS} are allowed per source.")
+
+ if not domains:
+ raise ValueError("No valid domains found. Enter one domain per line, e.g. 'example.com'.")
+
+ return domains
+
+
+def _build_url(api_key: str, domain: str) -> str:
+ # `format=json` is the API default, but we pass it explicitly so a change to the default can't
+ # silently switch us to XML.
+ return f"{IP2WHOIS_BASE_URL}?{urlencode({'key': api_key, 'domain': domain, 'format': 'json'})}"
+
+
+def _safe_json(response: requests.Response) -> dict[str, Any]:
+ try:
+ body = response.json()
+ except ValueError:
+ return {}
+ return body if isinstance(body, dict) else {}
+
+
+@retry(
+ retry=retry_if_exception_type((IP2WhoisRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_domain(
+ session: requests.Session,
+ api_key: str,
+ domain: str,
+ logger: FilteringBoundLogger,
+) -> dict[str, Any] | None:
+ """Look up one domain. Returns the WHOIS row, or ``None`` when the failure is specific to this
+ domain (so the rest of the list still syncs). Raises on retryable transport errors and on
+ account-level failures (bad key, exhausted quota, or any unrecognized error) that should fail the
+ whole sync.
+
+ IP2WHOIS returns errors as ``{"error": {"error_code": N, "error_message": "..."}}`` — a bad key
+ is HTTP 401 (code 10001) and an invalid/missing domain is HTTP 400 (code 10007). Only codes in
+ ``_DOMAIN_LEVEL_ERROR_CODES`` skip a single entry; every other error fails the run loudly, so a
+ misclassified account/quota error can never silently empty the (full-refresh) table.
+ """
+ response = session.get(_build_url(api_key, domain), timeout=REQUEST_TIMEOUT_SECONDS)
+
+ # 429 (rate limit) and transient 5xx are retryable; back off and try again.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise IP2WhoisRetryableError(f"IP2WHOIS API error (retryable): status={response.status_code}")
+
+ body = _safe_json(response)
+ error = body.get("error") if isinstance(body.get("error"), dict) else None
+
+ # A rejected key (401/403) can never be satisfied by retrying, and every other domain would fail
+ # the same way, so fail the whole sync. Build the message from the base URL only — the `key` query
+ # param must never reach stored errors/logs. The host prefix is matched by get_non_retryable_errors.
+ if response.status_code in (401, 403):
+ reason = "Unauthorized" if response.status_code == 401 else "Forbidden"
+ raise requests.HTTPError(
+ f"{response.status_code} Client Error: {reason} for url: {IP2WHOIS_BASE_URL}", response=response
+ )
+
+ if error is not None:
+ code = error.get("error_code", "unknown")
+ message = str(error.get("error_message", ""))
+ # Only confirmed domain-level codes skip this one entry; anything else (key/quota/account, or
+ # an unknown code) is fatal for the run — see _DOMAIN_LEVEL_ERROR_CODES.
+ if code in _DOMAIN_LEVEL_ERROR_CODES:
+ logger.warning(f"IP2WHOIS: skipping domain {domain}: [{code}] {message}")
+ return None
+ raise IP2WhoisAPIError(f"IP2WHOIS API error [{code}]: {message}")
+
+ if not response.ok:
+ # A non-2xx with no recognized error envelope can't be attributed to this specific domain, so
+ # fail the run rather than silently dropping rows.
+ raise IP2WhoisAPIError(f"IP2WHOIS API error: unexpected status {response.status_code}")
+
+ # Stamp the queried (normalized) domain as the primary key so it's stable regardless of how the
+ # API echoes it back (casing, IDN form). Keep any `domain` the API returned under `domain` too —
+ # they should match, but the queried value is the one the user controls and will join on.
+ body["domain"] = domain
+ return body
+
+
+def get_rows(
+ api_key: str,
+ domains: list[str],
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ # One session reused across every domain so urllib3 keeps the connection alive. `redact_values`
+ # masks the API key (a query param) from the tracked session's logged URLs and captured samples.
+ session = make_tracked_session(redact_values=(api_key,))
+
+ yielded = 0
+ skipped = 0
+ for domain in domains:
+ row = _fetch_domain(session, api_key, domain, logger)
+ if row is not None:
+ yielded += 1
+ yield [row]
+ else:
+ skipped += 1
+
+ # Full-refresh replaces the table with whatever this run yields. If every configured domain was
+ # skipped we'd silently wipe the table to empty, which hides a real problem (a bad domain list, or
+ # an account error that slipped through as a domain-level skip). Fail loudly instead.
+ if yielded == 0 and skipped > 0:
+ raise IP2WhoisAPIError(
+ f"IP2WHOIS returned no WHOIS data for any of the {skipped} configured domain(s). Every domain "
+ "was rejected — check the domain list and that the account's monthly lookup quota is not exhausted."
+ )
+
+
+def ip2whois_source(
+ api_key: str,
+ endpoint: str,
+ domains_raw: str | None,
+ logger: FilteringBoundLogger,
+) -> SourceResponse:
+ config = IP2WHOIS_ENDPOINTS[endpoint]
+ domains = parse_domains(domains_raw)
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(api_key=api_key, domains=domains, logger=logger),
+ primary_keys=config.primary_keys,
+ # WHOIS is a current-state lookup with no server-side change cursor, so each sync fully
+ # replaces the table. Rows carry a `create_date`, but it's absent/unparseable for some TLDs, so
+ # it's not a safe partition key; the volume (one row per configured domain) is small enough
+ # that partitioning would add cost without benefit.
+ sort_mode="asc",
+ )
+
+
+def validate_credentials(api_key: str, domains_raw: str | None) -> tuple[bool, str | None]:
+ """Probe the lookup endpoint with the first configured domain.
+
+ IP2WHOIS validates the domain param's presence before the key, so a real domain is required to
+ reach the key check. A valid key returns 200 (WHOIS data) or 400 (the probe domain was rejected,
+ but the key was accepted); an invalid/disabled key returns 401/403 (code 10001).
+ """
+ try:
+ domains = parse_domains(domains_raw)
+ except ValueError as exc:
+ return False, str(exc)
+
+ try:
+ session = make_tracked_session(redact_values=(api_key,))
+ response = session.get(_build_url(api_key, domains[0]), timeout=REQUEST_TIMEOUT_SECONDS)
+ except Exception:
+ return False, "Could not reach the IP2WHOIS API. Please try again."
+
+ if response.status_code in (401, 403):
+ return False, (
+ "Your IP2WHOIS API key is invalid or has been disabled. Generate a new key in your "
+ "IP2WHOIS dashboard, then reconnect."
+ )
+
+ body = _safe_json(response)
+ error = body.get("error") if isinstance(body.get("error"), dict) else None
+ if error is not None and "key" in str(error.get("error_message", "")).lower():
+ return False, (
+ "Your IP2WHOIS API key is invalid or has been disabled. Generate a new key in your "
+ "IP2WHOIS dashboard, then reconnect."
+ )
+
+ # 200 (WHOIS data) or 400 (key accepted, probe domain rejected) both prove the key is genuine.
+ if response.status_code in (200, 400):
+ return True, None
+
+ return False, f"The IP2WHOIS API returned an unexpected status code: {response.status_code}"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ip2whois/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ip2whois/settings.py
new file mode 100644
index 000000000000..ef87378013fd
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ip2whois/settings.py
@@ -0,0 +1,30 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+
+@dataclass
+class IP2WhoisEndpointConfig:
+ name: str
+ # WHOIS records are keyed on the domain we looked up. It's injected on every row (see
+ # `ip2whois.py`) so the key is stable regardless of how the API echoes the domain back.
+ primary_keys: list[str] = field(default_factory=lambda: ["domain"])
+ description: Optional[str] = None
+
+
+# IP2WHOIS exposes a single lookup endpoint (`GET /v2?domain=...`) that returns the WHOIS record for
+# one domain per request. There's no list/search endpoint, so the one table is driven by the
+# user-supplied set of domains, one API call each. Full refresh only — the API has no server-side
+# change cursor.
+IP2WHOIS_ENDPOINTS: dict[str, IP2WhoisEndpointConfig] = {
+ "whois": IP2WhoisEndpointConfig(
+ name="whois",
+ primary_keys=["domain"],
+ description=(
+ "WHOIS registration record (registrar, registrant/admin/tech/billing contacts, nameservers, "
+ "and creation/update/expiration dates) for each configured domain. One API lookup per domain "
+ "on every sync; full refresh only."
+ ),
+ ),
+}
+
+ENDPOINTS = tuple(IP2WHOIS_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ip2whois/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ip2whois/source.py
index 038ff5144e49..097a4f469061 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ip2whois/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ip2whois/source.py
@@ -1,19 +1,42 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
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.generated_configs import IP2WhoisSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.ip2whois.ip2whois import (
+ ip2whois_source,
+ validate_credentials as validate_ip2whois_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.ip2whois.settings import (
+ ENDPOINTS,
+ IP2WHOIS_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
class IP2WhoisSource(SimpleSource[IP2WhoisSourceConfig]):
+ # `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
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.IP2WHOIS
@@ -23,8 +46,100 @@ class IP2WhoisSource(SimpleSource[IP2WhoisSourceConfig]):
return SourceConfig(
name=SchemaExternalDataSourceType.IP2_WHOIS,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
- label="IP2Whois",
- iconPath="/static/services/ip2whois.png",
- fields=cast(list[FieldType], []),
+ label="IP2WHOIS",
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ caption="""Enter your IP2WHOIS API key and the domains you want to look up to pull WHOIS registration data into the PostHog Data warehouse.
+
+IP2WHOIS (by IP2Location) is a domain WHOIS lookup API. Create an API key in your [IP2WHOIS dashboard](https://www.ip2whois.com/) — the free tier includes 500 lookups per month.
+
+There is no list endpoint — every request looks up a single domain — so enter one domain per line (commas and spaces also work). For example:
+
+```
+example.com
+posthog.com
+```
+
+Each sync looks up every configured domain once and replaces the table with the current WHOIS record. Every domain costs one lookup against your monthly quota.
+""",
+ iconPath="/static/services/ip2whois.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/ip2whois",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="Your IP2WHOIS API key",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="domains",
+ label="Domains",
+ type=SourceFieldInputConfigType.TEXTAREA,
+ required=True,
+ placeholder="example.com\nposthog.com",
+ secret=False,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.ip2whois.canonical_descriptions import ( # noqa: PLC0415
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # A bad/disabled key surfaces as an HTTP 401 (code 10001, "API key not found") or 403 via
+ # `_fetch_domain`. Retrying can never satisfy a credential problem. Match the stable status
+ # text and base host (the `key` query param is never included in the message).
+ "401 Client Error: Unauthorized for url: https://api.ip2whois.com": "Your IP2WHOIS API key is invalid or has been disabled. Generate a new key in your IP2WHOIS dashboard, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.ip2whois.com": "Your IP2WHOIS API key does not have access to this data. Check the key in your IP2WHOIS dashboard, then reconnect.",
+ # Account-level API errors returned in the JSON error envelope (exhausted monthly quota,
+ # disabled account, and anything else that isn't specific to a single domain) are raised as
+ # IP2WhoisAPIError. These are deterministic within a run, so fail fast rather than retry.
+ "IP2WHOIS API error": "Your IP2WHOIS request was rejected by the API — the account may be disabled or the monthly lookup quota exhausted. Check your IP2WHOIS dashboard, then reconnect or resync.",
+ }
+
+ def get_schemas(
+ self,
+ config: IP2WhoisSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # IP2WHOIS has no server-side change cursor, so the single table is full refresh only.
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ description=IP2WHOIS_ENDPOINTS[endpoint].description,
+ )
+ for endpoint in ENDPOINTS
+ ]
+ 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: IP2WhoisSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_ip2whois_credentials(config.api_key, config.domains)
+
+ def source_for_pipeline(self, config: IP2WhoisSourceConfig, inputs: SourceInputs) -> SourceResponse:
+ return ip2whois_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ domains_raw=config.domains,
+ logger=inputs.logger,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ip2whois/tests/test_ip2whois.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ip2whois/tests/test_ip2whois.py
new file mode 100644
index 000000000000..71d37bf43230
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ip2whois/tests/test_ip2whois.py
@@ -0,0 +1,265 @@
+import json
+from typing import Any, Optional
+
+import pytest
+from unittest import mock
+
+import requests
+import structlog
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.ip2whois.ip2whois import (
+ IP2WHOIS_BASE_URL,
+ MAX_DOMAINS,
+ IP2WhoisAPIError,
+ IP2WhoisRetryableError,
+ _fetch_domain,
+ get_rows,
+ ip2whois_source,
+ normalize_domain,
+ parse_domains,
+ validate_credentials,
+)
+
+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.ip2whois.ip2whois"
+
+
+def _response(status: int = 200, body: Optional[dict[str, Any]] = None) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.status_code = status
+ resp.ok = 200 <= status < 300
+ resp.reason = {200: "OK", 400: "Bad Request", 401: "Unauthorized", 403: "Forbidden"}.get(status, "")
+ resp.json.return_value = body if body is not None else {}
+ resp.text = json.dumps(body if body is not None else {})
+ return resp
+
+
+class TestNormalizeDomain:
+ @pytest.mark.parametrize(
+ "raw, expected",
+ [
+ ("example.com", "example.com"),
+ (" Example.COM ", "example.com"),
+ ("www.example.com", "example.com"),
+ ("https://www.posthog.com/pricing?x=1", "posthog.com"),
+ ("http://foo.bar.baz:8080/path", "foo.bar.baz"),
+ ("a.co", "a.co"),
+ # Unusable tokens normalize to None so the caller skips them (no wasted lookup).
+ ("", None),
+ (" ", None),
+ ("not a domain", None),
+ ("localhost", None),
+ ("just-text", None),
+ ("http://", None),
+ ],
+ )
+ def test_normalize(self, raw, expected):
+ assert normalize_domain(raw) == expected
+
+
+class TestParseDomains:
+ @pytest.mark.parametrize(
+ "raw, expected",
+ [
+ ("example.com", ["example.com"]),
+ ("example.com\nposthog.com", ["example.com", "posthog.com"]),
+ ("example.com, posthog.com", ["example.com", "posthog.com"]),
+ ("example.com posthog.com", ["example.com", "posthog.com"]),
+ # Dedup is case/host normalized and order-preserving.
+ ("example.com\nEXAMPLE.com\nwww.example.com", ["example.com"]),
+ # Invalid tokens are dropped, valid ones kept.
+ ("example.com\ngarbage\nposthog.com", ["example.com", "posthog.com"]),
+ ],
+ )
+ def test_valid(self, raw, expected):
+ assert parse_domains(raw) == expected
+
+ @pytest.mark.parametrize("raw", [None, "", " \n ", "garbage", "not a domain\nlocalhost"])
+ def test_invalid_raises(self, raw):
+ with pytest.raises(ValueError):
+ parse_domains(raw)
+
+ def test_rejects_too_many_domains(self):
+ raw = "\n".join(f"domain{i}.com" for i in range(MAX_DOMAINS + 1))
+ with pytest.raises(ValueError, match="Too many domains"):
+ parse_domains(raw)
+
+
+# tenacity exposes the undecorated function via `__wrapped__`, so status classification can be
+# asserted without waiting through retry backoff.
+_fetch_once = _fetch_domain.__wrapped__ # type: ignore[attr-defined]
+
+
+class TestFetchDomain:
+ def test_success_injects_queried_domain(self):
+ session = mock.MagicMock()
+ # The API echoes an upper-cased domain; the queried (normalized) value must win as the key.
+ session.get.return_value = _response(200, {"domain": "EXAMPLE.COM", "create_date": "1997-09-15T04:00:00Z"})
+
+ row = _fetch_once(session, "secret", "example.com", structlog.get_logger())
+
+ assert row is not None
+ assert row["domain"] == "example.com"
+ assert row["create_date"] == "1997-09-15T04:00:00Z"
+
+ @pytest.mark.parametrize("status", [429, 500, 503])
+ def test_retryable_statuses_raise_retryable(self, status):
+ session = mock.MagicMock()
+ session.get.return_value = _response(status)
+
+ with pytest.raises(IP2WhoisRetryableError):
+ _fetch_once(session, "secret", "example.com", structlog.get_logger())
+
+ @pytest.mark.parametrize("status, reason", [(401, "Unauthorized"), (403, "Forbidden")])
+ def test_auth_errors_raise_http_error_without_key(self, status, reason):
+ session = mock.MagicMock()
+ session.get.return_value = _response(
+ status, {"error": {"error_code": 10001, "error_message": "API key not found."}}
+ )
+
+ with pytest.raises(requests.HTTPError) as exc_info:
+ _fetch_once(session, "SUPERSECRETKEY", "example.com", structlog.get_logger())
+
+ message = str(exc_info.value)
+ # The key must never reach the raised error, but the host prefix that
+ # get_non_retryable_errors matches on must be preserved.
+ assert "SUPERSECRETKEY" not in message
+ assert f"{status} Client Error: {reason} for url: {IP2WHOIS_BASE_URL}" == message
+
+ def test_domain_level_error_is_skipped(self):
+ # A per-domain rejection (HTTP 400, code 10007) must skip just this domain, not fail the sync.
+ session = mock.MagicMock()
+ session.get.return_value = _response(400, {"error": {"error_code": 10007, "error_message": "Invalid domain."}})
+
+ assert _fetch_once(session, "secret", "bad_domain.invalid", structlog.get_logger()) is None
+
+ def test_account_level_error_raises(self):
+ # A 200 body-level error that isn't a domain-level code (e.g. quota) is fatal for the run.
+ session = mock.MagicMock()
+ session.get.return_value = _response(
+ 200, {"error": {"error_code": 10002, "error_message": "Insufficient query."}}
+ )
+
+ with pytest.raises(IP2WhoisAPIError, match=r"\[10002\]"):
+ _fetch_once(session, "secret", "example.com", structlog.get_logger())
+
+ def test_account_error_mentioning_domain_still_raises(self):
+ # Classification is by error code, not message text: an account/quota error whose message
+ # happens to contain "domain" must NOT be mistaken for a per-domain skip (which would silently
+ # empty a full-refresh table). Only codes in the allow-list skip.
+ session = mock.MagicMock()
+ session.get.return_value = _response(
+ 200, {"error": {"error_code": 10004, "error_message": "Domain lookup quota exceeded."}}
+ )
+
+ with pytest.raises(IP2WhoisAPIError, match=r"\[10004\]"):
+ _fetch_once(session, "secret", "example.com", structlog.get_logger())
+
+ def test_unexpected_non_ok_without_envelope_raises(self):
+ # A non-2xx with no error envelope can't be attributed to this domain, so fail loudly rather
+ # than silently dropping the row.
+ session = mock.MagicMock()
+ session.get.return_value = _response(404, {})
+
+ with pytest.raises(IP2WhoisAPIError):
+ _fetch_once(session, "secret", "example.com", structlog.get_logger())
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status, body, expected_valid",
+ [
+ (200, {"domain": "example.com"}, True),
+ # 400 means the probe domain was rejected but the key was accepted.
+ (400, {"error": {"error_code": 10007, "error_message": "Invalid domain."}}, True),
+ (401, {"error": {"error_code": 10001, "error_message": "API key not found."}}, False),
+ (403, {"error": {"error_code": 10001, "error_message": "API key not found."}}, False),
+ # A 200 body-level key error is still an invalid key.
+ (200, {"error": {"error_code": 10001, "error_message": "Invalid API key."}}, False),
+ ],
+ )
+ def test_status_mapping(self, status, body, expected_valid):
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _response(status, body)
+
+ is_valid, _ = validate_credentials("test-key", "example.com")
+
+ assert is_valid is expected_valid
+
+ def test_malformed_domains_is_invalid_without_request(self):
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ is_valid, message = validate_credentials("test-key", "garbage")
+
+ assert is_valid is False
+ assert message is not None
+ mock_session.return_value.get.assert_not_called()
+
+ def test_network_error_is_invalid(self):
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.side_effect = Exception("boom")
+
+ is_valid, message = validate_credentials("test-key", "example.com")
+
+ assert is_valid is False
+ assert message is not None
+
+ def test_probes_first_domain(self):
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _response(200, {"domain": "example.com"})
+
+ validate_credentials("test-key", "example.com\nposthog.com")
+
+ called_url = mock_session.return_value.get.call_args[0][0]
+
+ assert called_url.startswith(IP2WHOIS_BASE_URL)
+ assert "domain=example.com" in called_url
+
+
+class TestGetRows:
+ def test_yields_one_batch_per_domain_and_targets_each(self):
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.side_effect = [
+ _response(200, {"domain": "EXAMPLE.COM"}),
+ _response(200, {"domain": "posthog.com"}),
+ ]
+
+ batches = list(get_rows("test-key", ["example.com", "posthog.com"], structlog.get_logger()))
+
+ assert [batch[0]["domain"] for batch in batches] == ["example.com", "posthog.com"]
+
+ def test_skips_domains_that_return_none(self):
+ # A domain-level rejection drops out; the rest of the list still syncs.
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.side_effect = [
+ _response(400, {"error": {"error_code": 10007, "error_message": "Invalid domain."}}),
+ _response(200, {"domain": "posthog.com"}),
+ ]
+
+ batches = list(get_rows("test-key", ["bad.invalid", "posthog.com"], structlog.get_logger()))
+
+ assert [batch[0]["domain"] for batch in batches] == ["posthog.com"]
+
+ def test_all_domains_skipped_raises_rather_than_emptying_table(self):
+ # Full refresh replaces the table with this run's rows. If every domain is skipped we must fail
+ # loudly, not complete "successfully" with an empty table.
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _response(
+ 400, {"error": {"error_code": 10007, "error_message": "Invalid domain."}}
+ )
+
+ with pytest.raises(IP2WhoisAPIError, match="no WHOIS data"):
+ list(get_rows("test-key", ["bad1.invalid", "bad2.invalid"], structlog.get_logger()))
+
+
+class TestIP2WhoisSource:
+ def test_source_response_shape(self):
+ response = ip2whois_source("test-key", "whois", "example.com", structlog.get_logger())
+
+ assert response.name == "whois"
+ assert response.primary_keys == ["domain"]
+ assert response.sort_mode == "asc"
+ # WHOIS is a current-state lookup, so no partitioning.
+ assert response.partition_mode is None
+
+ def test_invalid_domains_raise(self):
+ with pytest.raises(ValueError):
+ ip2whois_source("test-key", "whois", "garbage", structlog.get_logger())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ip2whois/tests/test_ip2whois_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ip2whois/tests/test_ip2whois_source.py
new file mode 100644
index 000000000000..107a76c3a4c4
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ip2whois/tests/test_ip2whois_source.py
@@ -0,0 +1,133 @@
+import pytest
+from unittest import mock
+
+import structlog
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import IP2WhoisSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.ip2whois.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.ip2whois.source import IP2WhoisSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _make_inputs(schema_name: str = "whois") -> 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 TestIP2WhoisSource:
+ def setup_method(self):
+ self.source = IP2WhoisSource()
+ self.team_id = 123
+ self.config = IP2WhoisSourceConfig(api_key="test-key", domains="example.com")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.IP2WHOIS
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "IP2Whois"
+ assert config.label == "IP2WHOIS"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is True
+ assert config.iconPath == "/static/services/ip2whois.png"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/ip2whois"
+
+ 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", "domains"}
+
+ 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
+
+ domains_field = by_name["domains"]
+ assert domains_field.type == SourceFieldInputConfigType.TEXTAREA
+ assert domains_field.required is True
+ # The domain list is not a secret — it must round-trip on edit rather than be masked.
+ assert domains_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
+
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_get_schemas_is_full_refresh_only(self, endpoint):
+ # IP2WHOIS has no server-side change cursor, so neither incremental nor append is offered.
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ assert schemas[endpoint].supports_incremental is False
+ assert schemas[endpoint].supports_append is False
+ assert schemas[endpoint].incremental_fields == []
+
+ def test_get_schemas_filtered_by_names(self):
+ assert [s.name for s in self.source.get_schemas(self.config, self.team_id, names=["whois"])] == ["whois"]
+ assert self.source.get_schemas(self.config, self.team_id, names=["nonexistent"]) == []
+
+ @pytest.mark.parametrize("status", ["401 Client Error", "403 Client Error"])
+ def test_non_retryable_errors_cover_auth_and_host(self, status):
+ errors = self.source.get_non_retryable_errors()
+
+ assert any(status in key and "https://api.ip2whois.com" in key for key in errors)
+
+ def test_non_retryable_errors_cover_account_level_api_error(self):
+ # Account/quota errors are raised as "IP2WHOIS API error [...]" and must fail fast.
+ assert any("IP2WHOIS API error" in key for key in self.source.get_non_retryable_errors())
+
+ def test_documented_tables_render_without_credentials(self):
+ tables = self.source.get_documented_tables()
+
+ assert {table["name"] for table in tables} == set(ENDPOINTS)
+
+ def test_canonical_descriptions_cover_every_endpoint(self):
+ assert set(self.source.get_canonical_descriptions()) == set(ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ "mock_return, expected_valid, expected_message",
+ [
+ ((True, None), True, None),
+ ((False, "Invalid IP2WHOIS API key"), False, "Invalid IP2WHOIS API key"),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.ip2whois.source.validate_ip2whois_credentials"
+ )
+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):
+ mock_validate.return_value = mock_return
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is expected_valid
+ assert error_message == expected_message
+ mock_validate.assert_called_once_with(self.config.api_key, self.config.domains)
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.ip2whois.source.ip2whois_source")
+ def test_source_for_pipeline_plumbs_args(self, mock_ip2whois_source):
+ inputs = _make_inputs()
+
+ self.source.source_for_pipeline(self.config, inputs)
+
+ mock_ip2whois_source.assert_called_once_with(
+ api_key="test-key",
+ endpoint="whois",
+ domains_raw="example.com",
+ logger=inputs.logger,
+ )