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 ghost import source (#115730)

Tom Owersc5f287ef0f85
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 0c0ff9578388..0b08d2a39c3d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -371,6 +371,7 @@ the row lists both.
| genesys_cloud | HTTP | requests | ✅ |
| gerrit | HTTP | requests | ✅ |
| getdx | HTTP | requests | ✅ |
+| ghost | HTTP | requests + `rest_source.RESTClient` | ✅ |
| gitbook | HTTP | requests | ✅ |
| gitea | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |
| github | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |
@@ -1187,7 +1188,6 @@ doesn't conflict with concurrent PRs.
- gem
- gerrit
- getstream
-- ghost
- gitea
- gmail
- gnews
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/ghost.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/ghost.py
index 09b8e5b6dcef..859d4306818c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/ghost.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/ghost.py
@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class GhostSourceConfig(config.Config):
- pass
+ admin_domain: str
+ admin_api_key: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ghost/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ghost/canonical_descriptions.py
new file mode 100644
index 000000000000..42e68badfdfe
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ghost/canonical_descriptions.py
@@ -0,0 +1,122 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "members": {
+ "description": "Publication members with subscription details and newsletter engagement totals.",
+ "docs_url": "https://docs.ghost.org/admin-api/members",
+ "columns": {
+ "id": "Unique member identifier in Ghost.",
+ "email": "Member email address.",
+ "status": "Membership status: free, paid, comped, or gift.",
+ "created_at": "Time when Ghost created the member.",
+ "updated_at": "Time when Ghost last updated the member record.",
+ "subscriptions": "Subscription records with Stripe customer identifiers, prices, tiers, and cancellation details.",
+ "tiers": "Membership tiers the member can access.",
+ "labels": "Labels used to group members.",
+ "newsletters": "Newsletters to which the member subscribes.",
+ "email_count": "Total newsletter emails sent to the member.",
+ "email_opened_count": "Total newsletter emails opened by the member.",
+ "email_open_rate": "Email open percentage, or null when too few emails were sent.",
+ "last_seen_at": "Time of the member's most recent site activity.",
+ },
+ },
+ "posts": {
+ "description": "Publication posts with content, publishing status, authors, tags, and email delivery statistics.",
+ "docs_url": "https://docs.ghost.org/admin-api/posts/overview",
+ "columns": {
+ "id": "Unique post identifier in Ghost.",
+ "title": "Post title.",
+ "status": "Publishing status of the post.",
+ "created_at": "Time when Ghost created the post.",
+ "updated_at": "Time when Ghost last updated the post.",
+ "published_at": "Time when Ghost published the post.",
+ "html": "Post content in HTML format.",
+ "lexical": "Post content in the Lexical editor format.",
+ "authors": "Staff users who wrote the post.",
+ "tags": "Tags assigned to the post.",
+ "email": "Newsletter email delivery record and aggregate engagement statistics.",
+ "newsletter": "Newsletter associated with the post.",
+ },
+ },
+ "pages": {
+ "description": "Static publication pages with content, authors, and tags.",
+ "docs_url": "https://docs.ghost.org/admin-api/pages",
+ "columns": {
+ "id": "Unique page identifier in Ghost.",
+ "title": "Page title.",
+ "created_at": "Time when Ghost created the page.",
+ "updated_at": "Time when Ghost last updated the page.",
+ "html": "Page content in HTML format.",
+ "lexical": "Page content in the Lexical editor format.",
+ },
+ },
+ "tiers": {
+ "description": "Membership tiers with subscription prices and benefits.",
+ "docs_url": "https://docs.ghost.org/admin-api/tiers/overview",
+ "columns": {
+ "id": "Unique tier identifier in Ghost.",
+ "name": "Tier name.",
+ "type": "Free or paid membership tier.",
+ "active": "Whether the tier is active.",
+ "created_at": "Time when Ghost created the tier.",
+ "updated_at": "Time when Ghost last updated the tier.",
+ "monthly_price": "Monthly price in the smallest currency unit.",
+ "yearly_price": "Yearly price in the smallest currency unit.",
+ "currency": "Currency code for the tier prices.",
+ "benefits": "Benefits included in the tier.",
+ },
+ },
+ "offers": {
+ "description": "Membership discounts with eligibility, duration, and redemption totals.",
+ "docs_url": "https://docs.ghost.org/admin-api/offers/overview",
+ "columns": {
+ "id": "Unique offer identifier in Ghost.",
+ "name": "Internal offer name.",
+ "type": "Percentage or fixed discount.",
+ "amount": "Discount percentage or amount in the smallest currency unit, according to the offer type.",
+ "status": "Active or archived offer.",
+ "redemption_count": "Number of times the offer was redeemed.",
+ "tier": "Membership tier to which the offer applies.",
+ },
+ },
+ "newsletters": {
+ "description": "Newsletter configuration and sender details.",
+ "docs_url": "https://docs.ghost.org/admin-api/newsletters/overview",
+ "columns": {
+ "id": "Unique newsletter identifier in Ghost.",
+ "name": "Public newsletter name.",
+ "status": "Active or archived newsletter.",
+ "created_at": "Time when Ghost created the newsletter.",
+ "updated_at": "Time when Ghost last updated the newsletter.",
+ "sender_email": "Email address used to send the newsletter.",
+ "subscribe_on_signup": "Whether new members automatically subscribe to the newsletter.",
+ },
+ },
+ "tags": {
+ "description": "Public and internal tags used to organize publication content.",
+ "docs_url": "https://docs.ghost.org/admin-api/tags",
+ "columns": {
+ "id": "Unique tag identifier in Ghost.",
+ "name": "Tag name.",
+ "slug": "Tag identifier used in URLs.",
+ "visibility": "Public or internal tag visibility.",
+ "created_at": "Time when Ghost created the tag.",
+ "updated_at": "Time when Ghost last updated the tag.",
+ },
+ },
+ "users": {
+ "description": "Staff users with author profiles and roles.",
+ "docs_url": "https://docs.ghost.org/admin-api/users",
+ "columns": {
+ "id": "Unique staff user identifier in Ghost.",
+ "name": "Staff user display name.",
+ "slug": "Author identifier used in URLs.",
+ "email": "Staff user email address.",
+ "created_at": "Time when Ghost created the staff user.",
+ "updated_at": "Time when Ghost last updated the staff user.",
+ "roles": "Roles assigned to the staff user.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ghost/ghost.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ghost/ghost.py
new file mode 100644
index 000000000000..1e646a8df5d3
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ghost/ghost.py
@@ -0,0 +1,212 @@
+import re
+from datetime import UTC, datetime
+from typing import TYPE_CHECKING, Any
+from urllib.parse import urlsplit
+
+import jwt
+from requests import PreparedRequest
+from requests.exceptions import HTTPError
+
+from posthog.dataclasses import frozen
+
+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 AuthConfigBase
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ PageNumberPaginator,
+ SinglePagePaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource
+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 (
+ ClientConfig,
+ EndpointResource,
+)
+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
+from products.warehouse_sources.backend.temporal.data_imports.sources.ghost.settings import ENDPOINTS, REQUEST_TIMEOUT
+
+if TYPE_CHECKING:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
+ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.ghost import (
+ GhostSourceConfig,
+ )
+
+AUTH_ERROR = "Your Ghost Admin API key is invalid or expired. Create a new key in Ghost settings and reconnect."
+PERMISSION_ERROR = "Your Ghost Admin API key cannot read this table. Check the integration permissions in Ghost."
+KEY_ERROR = "Enter a Ghost Admin API key in the id:secret format from a custom integration."
+DOMAIN_ERROR = "Enter your Ghost admin domain or HTTPS URL without credentials, a query, or a fragment."
+
+
+class GhostConfigError(ValueError):
+ pass
+
+
+@frozen
+class GhostResumeConfig:
+ page: int = 1
+ finished: bool = False
+
+
+class GhostAdminAuth(AuthConfigBase):
+ def __init__(self, api_key: str) -> None:
+ if not re.fullmatch(r"[0-9a-fA-F]{24}:[0-9a-fA-F]{64}", api_key):
+ raise GhostConfigError(KEY_ERROR)
+ self._api_key = api_key
+ self._key_id, self._secret = api_key.split(":")
+
+ def __call__(self, request: PreparedRequest) -> PreparedRequest:
+ issued_at = int(datetime.now(UTC).timestamp())
+ token = jwt.encode(
+ {"iat": issued_at, "exp": issued_at + 300, "aud": "/admin/"},
+ bytes.fromhex(self._secret),
+ algorithm="HS256",
+ headers={"kid": self._key_id},
+ )
+ request.headers["Authorization"] = f"Ghost {token}"
+ return request
+
+ def secret_values(self) -> tuple[str, ...]:
+ return (self._api_key, self._secret)
+
+
+def ghost_base_url(admin_domain: str) -> str:
+ value = admin_domain.strip().rstrip("/")
+ try:
+ parts = urlsplit(value if "://" in value else f"https://{value}")
+ except ValueError:
+ raise GhostConfigError(DOMAIN_ERROR) from None
+ if (
+ parts.scheme != "https"
+ or not parts.hostname
+ or parts.username is not None
+ or parts.password is not None
+ or parts.query
+ or parts.fragment
+ or any(character in value for character in ("\\", "%", "?", "#"))
+ or any(character.isspace() for character in value)
+ ):
+ raise GhostConfigError(DOMAIN_ERROR)
+ try:
+ if parts.port is not None and parts.port != 443:
+ raise GhostConfigError(DOMAIN_ERROR)
+ except ValueError:
+ raise GhostConfigError(DOMAIN_ERROR) from None
+ path = parts.path.rstrip("/")
+ if path.endswith("/ghost/api/admin"):
+ path = path.removesuffix("/ghost/api/admin")
+ if any(segment in (".", "..") for segment in path.split("/")):
+ raise GhostConfigError(DOMAIN_ERROR)
+ return f"https://{parts.netloc}{path}/ghost/api/admin/"
+
+
+def client_config(config: "GhostSourceConfig", api_version: str) -> ClientConfig:
+ return {
+ "base_url": ghost_base_url(config.admin_domain),
+ "auth": GhostAdminAuth(config.admin_api_key),
+ "headers": {"Accept-Version": api_version, "Accept": "application/json"},
+ "allowed_hosts": [],
+ "allow_redirects": False,
+ "request_timeout": REQUEST_TIMEOUT,
+ }
+
+
+def get_resource(name: str) -> EndpointResource:
+ endpoint = schema_for_resource(ENDPOINTS, name)
+ params: dict[str, Any] = dict(endpoint.params)
+ if endpoint.paginated:
+ params.update({"limit": 100, "order": "created_at asc,id asc"})
+ return {
+ "name": name,
+ "write_disposition": "replace",
+ "endpoint": {
+ "path": f"{name}/",
+ "params": params,
+ "data_selector": name,
+ "data_selector_required": True,
+ "paginator": PageNumberPaginator(base_page=1, total_path="meta.pagination.pages")
+ if endpoint.paginated
+ else "single_page",
+ },
+ }
+
+
+def probe_credentials(
+ config: "GhostSourceConfig", api_version: str, schema_name: str | None
+) -> tuple[bool, str | None]:
+ name = schema_name or "posts"
+ endpoint = schema_for_resource(ENDPOINTS, name)
+ client = RESTClient(
+ base_url=ghost_base_url(config.admin_domain),
+ auth=GhostAdminAuth(config.admin_api_key),
+ headers={"Accept-Version": api_version, "Accept": "application/json"},
+ allowed_hosts=[],
+ allow_redirects=False,
+ request_timeout=REQUEST_TIMEOUT,
+ )
+ params: dict[str, Any] = dict(endpoint.params)
+ if ENDPOINTS[name].paginated:
+ params.update({"limit": 1, "page": 1})
+ try:
+ next(
+ client.paginate(
+ path=f"{name}/",
+ params=params,
+ paginator=SinglePagePaginator(),
+ data_selector=name,
+ data_selector_required=True,
+ )
+ )
+ except HTTPError as error:
+ status = error.response.status_code if error.response is not None else None
+ if status == 401:
+ return False, AUTH_ERROR
+ if status == 403:
+ return (True, None) if schema_name is None else (False, PERMISSION_ERROR)
+ raise
+ finally:
+ client.session.close()
+ return True, None
+
+
+def ghost_source(
+ config: "GhostSourceConfig",
+ inputs: "SourceInputs",
+ manager: "ResumableSourceManager[GhostResumeConfig]",
+ api_version: str,
+) -> SourceResponse:
+ endpoint = schema_for_resource(ENDPOINTS, inputs.schema_name)
+ resume = manager.load_state() if manager.can_resume() else None
+
+ def save_checkpoint(state: dict[str, Any] | None) -> None:
+ manager.save_state(GhostResumeConfig(page=int(state["page"]) if state else 1, finished=state is None))
+
+ resource: Resource | list[dict[str, Any]]
+ if resume and resume.finished:
+ resource = []
+ else:
+ rest_config: RESTAPIConfig = {
+ "client": client_config(config, api_version),
+ "resources": [get_resource(inputs.schema_name)],
+ }
+ resource = rest_api_resource(
+ rest_config,
+ inputs.team_id,
+ inputs.job_id,
+ None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state={"page": resume.page} if resume else None,
+ )
+ return SourceResponse(
+ name=inputs.schema_name,
+ items=lambda: resource,
+ primary_keys=list(endpoint.primary_keys),
+ partition_keys=[endpoint.partition_key] if endpoint.partition_key else list(endpoint.primary_keys),
+ partition_mode="datetime" if endpoint.partition_key else "md5",
+ partition_format="month" if endpoint.partition_key else None,
+ partition_count=None if endpoint.partition_key else 16,
+ sort_mode=None,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ghost/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ghost/settings.py
new file mode 100644
index 000000000000..97892a920e78
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ghost/settings.py
@@ -0,0 +1,47 @@
+from dataclasses import field
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.types import IncrementalField
+
+API_VERSION = "v6.0"
+REQUEST_TIMEOUT = (10, 30)
+
+
+@frozen
+class GhostEndpoint:
+ description: str
+ params: dict[str, str] = field(default_factory=dict)
+ paginated: bool = True
+ primary_keys: tuple[str, ...] = ("id",)
+ partition_key: str | None = "created_at"
+
+
+ENDPOINTS: dict[str, GhostEndpoint] = {
+ "members": GhostEndpoint(
+ description="Members, subscriptions, labels, newsletter subscriptions, and email engagement totals.",
+ params={"include": "tiers"},
+ ),
+ "posts": GhostEndpoint(
+ description="Published, draft, and scheduled posts with authors, tags, and newsletter delivery statistics.",
+ params={"include": "tags,authors,email,newsletter", "formats": "html,lexical"},
+ ),
+ "pages": GhostEndpoint(
+ description="Static pages with content, authors, and tags.",
+ params={"include": "tags,authors", "formats": "html,lexical"},
+ ),
+ "tiers": GhostEndpoint(
+ description="Membership tiers with monthly prices, yearly prices, and benefits.",
+ params={"include": "monthly_price,yearly_price,benefits"},
+ ),
+ # Offers ignore pagination parameters and omit creation timestamps from their response.
+ "offers": GhostEndpoint(
+ description="Subscription discounts and redemption totals.", paginated=False, partition_key=None
+ ),
+ "newsletters": GhostEndpoint(description="Newsletter settings and sender details."),
+ "tags": GhostEndpoint(description="Content tags, including internal tags."),
+ "users": GhostEndpoint(description="Staff users and author profiles."),
+}
+
+# Timestamp filters need verification against a live account before incremental sync can safely use them.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ghost/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ghost/source.py
index b36f456a0a30..fe82fc4f6c6b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ghost/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ghost/source.py
@@ -1,18 +1,63 @@
from typing import cast
+from urllib.parse import urlsplit
-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.facade.source_config import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import ValidateDatabaseHostMixin
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (
+ SourceSchema,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.ghost import GhostSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.ghost.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.ghost.ghost import (
+ AUTH_ERROR,
+ DOMAIN_ERROR,
+ KEY_ERROR,
+ PERMISSION_ERROR,
+ GhostConfigError,
+ GhostResumeConfig,
+ ghost_base_url,
+ ghost_source,
+ probe_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.ghost.settings import (
+ API_VERSION,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class GhostSource(SimpleSource[GhostSourceConfig]):
+class GhostSource(ResumableSource[GhostSourceConfig, GhostResumeConfig], ValidateDatabaseHostMixin):
+ lists_tables_without_credentials = True
+ supported_versions = (API_VERSION,)
+ default_version = API_VERSION
+ api_docs_url = "https://docs.ghost.org/faq/api-versioning"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.GHOST
+ @property
+ def connection_host_fields(self) -> list[str]:
+ return ["admin_domain"]
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
@@ -20,6 +65,89 @@ class GhostSource(SimpleSource[GhostSourceConfig]):
category=DataWarehouseSourceCategory.MARKETING___EMAIL,
label="Ghost (Ghost Foundation)",
iconPath="/static/services/ghost.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/ghost",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="Create a custom integration in Ghost settings. Copy its Admin API key and API URL. Requires Ghost 6 or later.",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="admin_domain",
+ label="Admin domain or API URL",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="https://example.ghost.io",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="admin_api_key",
+ label="Admin API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ secret=True,
+ placeholder="id:secret",
+ ),
+ ],
+ ),
)
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": AUTH_ERROR,
+ "403 Client Error": PERMISSION_ERROR,
+ KEY_ERROR: KEY_ERROR,
+ DOMAIN_ERROR: DOMAIN_ERROR,
+ }
+
+ def validate_credentials(
+ self, config: GhostSourceConfig, team_id: int, schema_name: str | None = None, api_version: str | None = None
+ ) -> tuple[bool, str | None]:
+ if schema_name is not None and schema_name not in ENDPOINTS:
+ return False, "This Ghost table is not supported. Select a table from the source configuration."
+ try:
+ hostname = urlsplit(ghost_base_url(config.admin_domain)).hostname
+ assert hostname is not None
+ valid, error = self.is_database_host_valid(hostname, team_id)
+ if not valid:
+ return False, error
+ return probe_credentials(config, self.resolve_api_version(api_version), schema_name)
+ except GhostConfigError as error:
+ return False, str(error)
+
+ def get_schemas(
+ self,
+ config: GhostSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ names,
+ descriptions={name: endpoint.description for name, endpoint in ENDPOINTS.items()},
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ return CANONICAL_DESCRIPTIONS
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[GhostResumeConfig]:
+ return ResumableSourceManager(inputs, GhostResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: GhostSourceConfig,
+ resumable_source_manager: ResumableSourceManager[GhostResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ # Re-check at sync time: validate_credentials only runs on create/update, so a host that
+ # resolved publicly then may resolve to an internal address later (DNS rebinding).
+ hostname = urlsplit(ghost_base_url(config.admin_domain)).hostname
+ assert hostname is not None
+ host_valid, host_error = self.is_database_host_valid(hostname, inputs.team_id)
+ if not host_valid:
+ raise ValueError(host_error or DOMAIN_ERROR)
+
+ return ghost_source(config, inputs, resumable_source_manager, self.resolve_api_version(inputs.api_version))
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ghost/tests/test_ghost.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ghost/tests/test_ghost.py
new file mode 100644
index 000000000000..958178d5056f
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ghost/tests/test_ghost.py
@@ -0,0 +1,125 @@
+from datetime import UTC, datetime
+
+import pytest
+import time_machine
+
+import jwt
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ RecordedRequest,
+ ScriptedResponse,
+ SourceDriver,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.ghost import GhostSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.ghost.ghost import GhostResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.ghost.source import GhostSource
+
+KEY_ID = "0123456789abcdef01234567"
+KEY_SECRET = "0123456789abcdef" * 4
+API_KEY = f"{KEY_ID}:{KEY_SECRET}"
+
+
+def driver(admin_domain: str = "publication.example.com") -> SourceDriver:
+ return SourceDriver(GhostSource(), GhostSourceConfig(admin_domain=admin_domain, admin_api_key=API_KEY))
+
+
+ ("endpoint", "include", "formats"),
+ [
+ ("members", "tiers", None),
+ ("posts", "tags,authors,email,newsletter", "html,lexical"),
+ ("pages", "tags,authors", "html,lexical"),
+ ("tiers", "monthly_price,yearly_price,benefits", None),
+ ("newsletters", None, None),
+ ("tags", None, None),
+ ("users", None, None),
+ ],
+)
+def test_browse_requests_preserve_rows_and_stop_at_last_page(
+ endpoint: str, include: str | None, formats: str | None
+) -> None:
+ rows = [
+ {"id": "first", "created_at": "2026-01-01T00:00:00.000Z", "subscriptions": [], "email_open_rate": None},
+ {
+ "id": "second",
+ "created_at": "2026-01-02T00:00:00.000Z",
+ "subscriptions": [{"customer": {"id": "cus_example"}}],
+ },
+ ]
+ result = driver("https://publication.example.com/blog/ghost/api/admin/").run(
+ endpoint,
+ [
+ ScriptedResponse(json={endpoint: [rows[0]], "meta": {"pagination": {"page": 1, "pages": 2, "next": 2}}}),
+ ScriptedResponse(json={endpoint: [rows[1]], "meta": {"pagination": {"page": 2, "pages": 2, "next": None}}}),
+ ],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2099-01-01T00:00:00Z",
+ )
+ assert result.raised is None
+ assert result.rows == rows
+ assert result.paths == [f"/blog/ghost/api/admin/{endpoint}/"] * 2
+ assert result.params("page") == ["1", "2"]
+ assert result.params("include") == [include, include]
+ assert result.params("formats") == [formats, formats]
+ assert result.params("filter") == [None, None]
+ assert result.params("order") == ["created_at asc,id asc"] * 2
+ assert result.committed_states == [GhostResumeConfig(page=2), GhostResumeConfig(finished=True)]
+ assert all(request.headers["accept-version"] == "v6.0" for request in result.requests)
+
+
+def test_offers_do_not_repeat_an_unpaginated_response() -> None:
+ rows = [{"id": "offer_example", "tier": {"id": "tier_example"}, "redemption_count": 0}]
+ result = driver().run("offers", [ScriptedResponse(json={"offers": rows})])
+ assert result.raised is None
+ assert result.rows == rows
+ assert result.params("page") == [None]
+ assert result.params("limit") == [None]
+ assert result.committed_states == [GhostResumeConfig(finished=True)]
+
+
+def test_resume_keeps_written_pages_and_does_not_replay_a_finished_run() -> None:
+ first = driver().run(
+ "members",
+ [
+ ScriptedResponse(json={"members": [{"id": "first"}], "meta": {"pagination": {"pages": 2}}}),
+ ScriptedResponse(json={"unexpected": []}),
+ ],
+ )
+ assert first.raised is not None
+ assert first.rows == [{"id": "first"}]
+ assert first.committed_states == [GhostResumeConfig(page=2)]
+ resumed = driver().run(
+ "members",
+ [ScriptedResponse(json={"members": [{"id": "second"}], "meta": {"pagination": {"pages": 2}}})],
+ resume_state=first.committed_states[-1],
+ )
+ assert resumed.raised is None
+ assert resumed.params("page") == ["2"]
+ assert resumed.rows == [{"id": "second"}]
+ finished = driver().run("members", [], resume_state=resumed.committed_states[-1])
+ assert finished.raised is None
+ assert finished.rows == []
+ assert finished.requests == []
+
+
+def test_requests_mint_a_new_signed_token_after_five_minutes() -> None:
+ issued_at: list[int] = []
+ with time_machine.travel(datetime(2026, 1, 1, tzinfo=UTC), tick=False) as clock:
+
+ def respond(request: RecordedRequest) -> ScriptedResponse:
+ scheme, token = request.headers["authorization"].split(" ", 1)
+ assert scheme == "Ghost"
+ payload = jwt.decode(token, bytes.fromhex(KEY_SECRET), algorithms=["HS256"], audience="/admin/")
+ assert jwt.get_unverified_header(token)["kid"] == KEY_ID
+ assert payload["exp"] - payload["iat"] == 300
+ issued_at.append(payload["iat"])
+ clock.shift(360)
+ return ScriptedResponse(
+ json={"members": [{"id": request.param("page")}], "meta": {"pagination": {"pages": 2}}}
+ )
+
+ result = driver().run("members", respond)
+ assert result.raised is None
+ assert issued_at[1] - issued_at[0] == 360
+ assert API_KEY in result.session_options[0]["redact_values"]
+ assert KEY_SECRET in result.session_options[0]["redact_values"]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ghost/tests/test_ghost_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ghost/tests/test_ghost_source.py
new file mode 100644
index 000000000000..22e015d6383b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ghost/tests/test_ghost_source.py
@@ -0,0 +1,101 @@
+import pytest
+from unittest import mock
+
+from requests.exceptions import HTTPError
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ scripted_network,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.ghost import GhostSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.ghost.ghost import (
+ AUTH_ERROR,
+ DOMAIN_ERROR,
+ KEY_ERROR,
+ PERMISSION_ERROR,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.ghost.source import GhostSource
+
+API_KEY = "0123456789abcdef01234567:" + "0123456789abcdef" * 4
+
+
+ ("status", "schema_name", "expected"),
+ [
+ (200, None, (True, None)),
+ (200, "members", (True, None)),
+ (200, "offers", (True, None)),
+ (401, None, (False, AUTH_ERROR)),
+ (403, None, (True, None)),
+ (403, "members", (False, PERMISSION_ERROR)),
+ ],
+)
+def test_credential_probe_maps_auth_errors_and_checks_selected_table(
+ status: int, schema_name: str | None, expected: tuple[bool, str | None]
+) -> None:
+ endpoint = schema_name or "posts"
+ body = {endpoint: []} if status == 200 else {"errors": [{"type": "NoPermissionError", "message": "Access denied."}]}
+ config = GhostSourceConfig(admin_domain="publication.example.com", admin_api_key=API_KEY)
+ with scripted_network([ScriptedResponse(status=status, json=body)]) as network:
+ assert GhostSource().validate_credentials(config, 1, schema_name=schema_name) == expected
+ assert len(network.requests_log) == 1
+ request = network.requests_log[0]
+ assert request.path == f"/ghost/api/admin/{endpoint}/"
+ assert request.param("limit") == (None if endpoint == "offers" else "1")
+
+
+ ("domain", "key", "schema_name", "message"),
+ [
+ ("publication.example.com", "invalid", None, KEY_ERROR),
+ ("publication.example.com", "id:not-hex", None, KEY_ERROR),
+ ("http://publication.example.com", API_KEY, None, DOMAIN_ERROR),
+ ("https://user:[email protected]", API_KEY, None, DOMAIN_ERROR),
+ ("https://publication.example.com/?key=example", API_KEY, None, DOMAIN_ERROR),
+ ("https://publication.example.com/#fragment", API_KEY, None, DOMAIN_ERROR),
+ ("https://publication.example.com:invalid", API_KEY, None, DOMAIN_ERROR),
+ ("https://[invalid", API_KEY, None, DOMAIN_ERROR),
+ ("publication.example.com", API_KEY, "unknown", "This Ghost table is not supported."),
+ ],
+)
+def test_invalid_configuration_fails_before_sending_a_request(
+ domain: str, key: str, schema_name: str | None, message: str
+) -> None:
+ config = GhostSourceConfig(admin_domain=domain, admin_api_key=key)
+ with scripted_network([]) as network:
+ valid, error = GhostSource().validate_credentials(config, 1, schema_name=schema_name)
+ assert valid is False
+ assert error is not None and message in error
+ assert network.requests_log == []
+
+
+def test_unexpected_probe_error_is_not_reported_as_invalid_credentials() -> None:
+ config = GhostSourceConfig(admin_domain="publication.example.com", admin_api_key=API_KEY)
+ with scripted_network([ScriptedResponse(status=404, json={"errors": [{"type": "NotFoundError"}]})]):
+ with pytest.raises(HTTPError):
+ GhostSource().validate_credentials(config, 1)
+
+
+ ("host_valid", "expect_sync"),
+ [(True, True), (False, False)],
+)
+def test_source_for_pipeline_rechecks_the_host_at_sync_time(host_valid: bool, expect_sync: bool) -> None:
+ source = GhostSource()
+ config = GhostSourceConfig(admin_domain="publication.example.com", admin_api_key=API_KEY)
+ inputs = mock.MagicMock(team_id=1)
+ module = "products.warehouse_sources.backend.temporal.data_imports.sources.ghost.source"
+ with (
+ mock.patch.object(
+ source, "is_database_host_valid", return_value=(host_valid, None if host_valid else "Host not allowed")
+ ) as check,
+ mock.patch(f"{module}.ghost_source") as ghost_source,
+ ):
+ if expect_sync:
+ source.source_for_pipeline(config, mock.MagicMock(), inputs)
+ ghost_source.assert_called_once()
+ else:
+ with pytest.raises(ValueError, match="Host not allowed"):
+ source.source_for_pipeline(config, mock.MagicMock(), inputs)
+ ghost_source.assert_not_called()
+ check.assert_called_once_with("publication.example.com", 1)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/source_contract_baseline.txt b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/source_contract_baseline.txt
index 7e5ed6012a91..32f858cf2aa1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/source_contract_baseline.txt
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/source_contract_baseline.txt
@@ -300,6 +300,7 @@ Gcore fail:stall-budget
GcpCloudBilling not-checkable:no-request
Gerrit fail:rate-limit-budget,stall-budget
Getdx fail:stall-budget
+Ghost not-checkable:no-request
Giphy fail:stall-budget
GitBook fail:stall-budget
GitLab fail:rate-limit-budget,stall-budget