: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(data-warehouse): add Moxie import source (#84463)
Tom Owersecb19112a679
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/moxie.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/moxie.pyindex 2097e6edac3f..c284fc4b49e9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/moxie.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/moxie.py@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass MoxieSourceConfig(config.Config):- pass+ base_url: str+ api_key: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/moxie/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/moxie/canonical_descriptions.pynew file mode 100644index 000000000000..34526dc2ec58--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/moxie/canonical_descriptions.py@@ -0,0 +1,176 @@+"""Canonical, documentation-sourced descriptions for Moxie endpoints and columns.++Sourced from the Moxie Help Center's Public API Endpoints collection+(https://help.withmoxie.com/en/collections/5482062-public-api-endpoints). Keyed by the resource+names in `settings.py` `ENDPOINTS`, which match the `ExternalDataSchema.name` of a synced Moxie+table. Columns absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "clients": {+ "description": "A client business in the workspace, with its billing details and contacts.",+ "docs_url": "https://help.withmoxie.com/en/articles/8163927-list-clients",+ "columns": {+ "name": "Client business name.",+ "clientType": "Type of client record (e.g. Client, Lead).",+ "initials": "Initials shown for the client's avatar.",+ "color": "Hex color used for the client's avatar.",+ "address1": "First line of the client's address.",+ "address2": "Second line of the client's address.",+ "city": "City of the client's address.",+ "locality": "State or region of the client's address.",+ "postal": "Postal code of the client's address.",+ "country": "Country of the client's address.",+ "website": "Client's website URL.",+ "phone": "Client's phone number.",+ "taxId": "Client's tax identification number.",+ "leadSource": "Where the client/lead was sourced from.",+ "archive": "Whether the client has been archived.",+ "currency": "Currency used for invoicing this client (e.g. USD).",+ "hourlyAmount": "Default hourly rate billed to this client.",+ "roundingIncrement": "Time-tracking rounding increment applied to this client's entries.",+ "stripeClientId": "Stripe customer ID linked to this client, if any.",+ "notes": "Internal notes about the client.",+ "paymentTerms": "Payment terms (days to pay, late fee, who pays card fees).",+ "payInstructions": "Payment instructions shown to the client.",+ "contacts": "Contacts associated with this client.",+ },+ },+ "contacts": {+ "description": "A contact person, optionally linked to a client.",+ "docs_url": "https://help.withmoxie.com/en/articles/8259974-search-contacts",+ "columns": {+ "id": "Unique identifier for the contact.",+ "accountId": "Workspace account ID the contact belongs to.",+ "clientId": "ID of the client this contact belongs to, if any.",+ "clientPortalUserId": "Client portal user ID, if the contact has portal access.",+ "firstName": "Contact's first name.",+ "lastName": "Contact's last name.",+ "role": "Contact's role at the client.",+ "phone": "Contact's phone number.",+ "email": "Contact's email address.",+ "mobile": "Contact's mobile phone number.",+ "notes": "Internal notes about the contact.",+ "defaultContact": "Whether this is the default contact for the client.",+ "invoiceContact": "Whether invoices are sent to this contact.",+ "portalAccess": "Whether this contact has access to the client portal.",+ "importRecordId": "External ID from an imported record, if any.",+ "sampleData": "Whether this is Moxie-generated sample data.",+ },+ },+ "projects": {+ "description": "A project tracked for a client, including its fee schedule and status.",+ "docs_url": "https://help.withmoxie.com/en/articles/8260204-search-projects",+ "columns": {+ "id": "Unique identifier for the project.",+ "accountId": "Workspace account ID the project belongs to.",+ "clientId": "ID of the client this project belongs to.",+ "name": "Project name.",+ "description": "Project description.",+ "active": "Whether the project is active.",+ "startDate": "Date the project starts.",+ "dueDate": "Date the project is due.",+ "dateCreated": "Date and time the project was created.",+ "client": "Client this project belongs to, embedded.",+ "feeSchedule": "Billing structure for the project (hourly, flat fee, or retainer).",+ "proposalId": "ID of the proposal this project was created from, if any.",+ "proposalName": "Name of the proposal this project was created from, if any.",+ "hexColor": "Hex color used for the project.",+ "portalAccess": "Level of client-portal access granted for this project.",+ "showTimeWorkedInPortal": "Whether logged time is visible to the client in the portal.",+ "leadGenArchived": "Whether the project's originating lead has been archived.",+ "sampleData": "Whether this is Moxie-generated sample data.",+ },+ },+ "payable_invoices": {+ "description": "An invoice issued to a client, including its payment status and history.",+ "docs_url": "https://help.withmoxie.com/en/articles/8260252-search-payable-invoices",+ "columns": {+ "id": "Unique identifier for the invoice.",+ "invoiceNumber": "Invoice number.",+ "invoiceNumberFormatted": "Formatted invoice number as shown to the client.",+ "accountId": "Workspace account ID the invoice belongs to.",+ "clientId": "ID of the client the invoice was issued to.",+ "dateCreated": "Date the invoice was created.",+ "dateSent": "Date the invoice was sent.",+ "dateDue": "Date the invoice is due.",+ "dateDueCalculated": "Calculated due date, accounting for payment terms.",+ "datePaid": "Date the invoice was paid in full.",+ "clientInfo": "Client billing details, embedded as of invoice creation.",+ "status": "Invoice status (e.g. SENT, PAID).",+ "invoiceType": "Type of invoice (e.g. STANDARD).",+ "subTotal": "Invoice subtotal before tax and fees.",+ "convenienceFee": "Convenience fee charged on the invoice.",+ "lateFee": "Late payment fee charged on the invoice.",+ "discountAmount": "Discount applied to the invoice.",+ "creditApplied": "Credit applied to the invoice.",+ "tax": "Tax charged on the invoice.",+ "total": "Total amount of the invoice.",+ "localTotal": "Total amount in the client's local currency.",+ "paymentTotal": "Total amount paid so far.",+ "localPaymentTotal": "Total amount paid so far, in the client's local currency.",+ "amountDue": "Remaining amount due.",+ "localAmountDue": "Remaining amount due, in the client's local currency.",+ "currency": "Currency of the invoice.",+ "integrationKeys": "External accounting system IDs (QuickBooks, Xero) linked to this invoice.",+ "viewOnlineUrl": "URL where the client can view the invoice online.",+ "payments": "Payments recorded against this invoice.",+ },+ },+ "email_templates": {+ "description": "Name of an email template configured in the workspace.",+ "docs_url": "https://help.withmoxie.com/en/articles/8260211-list-email-templates",+ "columns": {"name": "Email template name."},+ },+ "invoice_templates": {+ "description": "Name of an invoice template configured in the workspace.",+ "docs_url": "https://help.withmoxie.com/en/articles/8260216-list-invoice-templates",+ "columns": {"name": "Invoice template name."},+ },+ "vendor_names": {+ "description": "Name of a vendor configured in the workspace, used for tracking expenses.",+ "docs_url": "https://help.withmoxie.com/en/articles/8260220-list-vendor-names",+ "columns": {"name": "Vendor name."},+ },+ "form_names": {+ "description": "Name of a form template configured in the workspace.",+ "docs_url": "https://help.withmoxie.com/en/articles/8260225-list-form-names",+ "columns": {"name": "Form name."},+ },+ "pipeline_stages": {+ "description": "A sales pipeline stage configured in the workspace.",+ "docs_url": "https://help.withmoxie.com/en/articles/8260232-list-pipeline-stages",+ "columns": {+ "id": "Unique identifier for the pipeline stage.",+ "label": "Display name of the pipeline stage.",+ "hexColor": "Hex color used for the pipeline stage.",+ "stageType": "Stage category (New, InProgress, OnHold, ClosedWon, ClosedLost, Complete).",+ },+ },+ "task_stages": {+ "description": "A project task stage configured in the workspace.",+ "docs_url": "https://help.withmoxie.com/en/articles/8260242-list-project-task-stages",+ "columns": {+ "id": "Unique identifier for the task stage.",+ "label": "Display name of the task stage.",+ "hexColor": "Hex color used for the task stage.",+ "complete": "Whether tasks in this stage are considered complete.",+ "clientApproval": "Whether tasks in this stage require client approval.",+ },+ },+ "workspace_users": {+ "description": "A user in the workspace, with their role, project access, and feature access.",+ "docs_url": "https://help.withmoxie.com/en/articles/8260260-list-workspace-users",+ "columns": {+ "user_id": "Unique identifier for the user, lifted from the nested user object.",+ "userType": "User's role in the workspace (OWNER, FULL_USER, RESTRICTED_ACCESS, COLLABORATOR).",+ "user": "The user's profile details, embedded.",+ "projectAccess": "Projects this user has been granted access to.",+ "featureAccess": "Workspace features this user can access.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/moxie/moxie.py b/products/warehouse_sources/backend/temporal/data_imports/sources/moxie/moxie.pynew file mode 100644index 000000000000..028e79b1fcac--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/moxie/moxie.py@@ -0,0 +1,196 @@+"""Moxie transport layer.++Moxie (withmoxie.com) is an all-in-one business-management app for freelancers, hosted on a+per-workspace pod (e.g. `pod00.withmoxie.dev`), so the API base URL is a user-supplied credential+rather than a constant. Auth is a single `X-API-KEY` header+(https://help.withmoxie.com/en/articles/8154735-public-api-fundamentals).++Every list/search endpoint returns the full collection as one bare JSON array with no pagination and+no server-side timestamp filter, so every table here is full refresh only. Two endpoint shapes exist:+most return an array of objects, but `emailTemplates`, `invoiceTemplates`, `vendors`, and `formNames`+return an array of bare strings (template/vendor/form names). The framework's per-item `data_map` only+runs on dict items (see `Resource._apply_transforms`), so those four are wrapped into a one-column row+after the fact in `moxie_source`, not declared as a `data_map` on the resource.++Moxie enforces a hard rate limit of 100 Public API requests per 5-minute window per workspace,+returning HTTP 429 when exceeded; the tracked session's transport-level retry already honors+`Retry-After` on a 429, so no extra throttling is added here.+"""++import re+from typing import Any, Optional+from urllib.parse import urlparse++from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import _is_host_safe+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.typing import EndpointResource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.moxie.settings import (+ MOXIE_API_PATH_PREFIX,+ MOXIE_ENDPOINTS,+)++HOST_NOT_ALLOWED_ERROR = "Moxie workspace base URL is not allowed"+HTTP_NOT_ALLOWED_ERROR = "Moxie workspace base URL must use HTTPS"++# (connect, read) timeout: a customer-controlled host that accepts the connection and then never+# responds (or trickles bytes) would otherwise hold an import worker for the activity's full runtime+# budget, since RESTClient passes this straight to `requests` as `timeout=None` when unset.+REQUEST_TIMEOUT_SECONDS = (10.0, 60.0)+++class MoxieHostNotAllowedError(Exception):+ pass+++def normalize_base_url(base_url: Optional[str]) -> str:+ """Turn whatever the user pasted from Connected Apps > Integrations into a full base URL.++ Accepts a bare pod host (`pod00.withmoxie.dev`) or the full URL shown in Moxie's UI+ (`https://pod00.withmoxie.dev/api/public`), with or without a trailing slash.+ """+ raw = (base_url or "").strip()+ if not raw:+ return ""+ if not re.match(r"^https?://", raw, flags=re.IGNORECASE):+ raw = f"https://{raw}"+ raw = raw.rstrip("/")+ if not re.search(r"/api/public$", raw, flags=re.IGNORECASE):+ raw = f"{raw}/api/public"+ return raw+++def _host_of(base_url: str) -> str:+ # `urlparse` treats a backslash (and its `%5c` encoding) as userinfo, so+ # `https://127.0.0.1\@example.com` parses as host `example.com` while requests/urllib3 (per the+ # WHATWG URL rules) treat `\` as a path separator and connect to `127.0.0.1`. Normalize to `/`+ # first so the host we validate is the host the request actually reaches (SSRF bypass guard).+ normalized = base_url.replace("\\", "/").replace("%5c", "/").replace("%5C", "/")+ return (urlparse(normalized).hostname or "").lower()+++def _is_https(base_url: str) -> bool:+ # The API key rides in the X-API-KEY header, so refuse plaintext HTTP to keep an on-path+ # attacker from capturing it.+ return urlparse(base_url).scheme == "https"+++def _flatten_workspace_user(item: dict[str, Any]) -> dict[str, Any]:+ """Lift the nested `user.userId` onto the row root as `user_id`, the only stable per-row key+ List Workspace Users exposes (a nested field can't be declared as a `SourceResponse` primary key).+ """+ user = item.get("user") or {}+ return {**item, "user_id": user.get("userId")}+++def get_resource(endpoint: str) -> EndpointResource:+ config = MOXIE_ENDPOINTS[endpoint]+ resource: EndpointResource = {+ "name": endpoint,+ "write_disposition": "replace",+ "endpoint": {"path": config.path},+ "table_format": "delta",+ }+ if endpoint == "workspace_users":+ resource["data_map"] = _flatten_workspace_user+ return resource+++def moxie_source(+ base_url: Optional[str],+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+) -> SourceResponse:+ resolved_base_url = normalize_base_url(base_url)+ host = _host_of(resolved_base_url)+ config = MOXIE_ENDPOINTS[endpoint]++ rest_config: RESTAPIConfig = {+ "client": {+ "base_url": resolved_base_url,+ "headers": {"Accept": "application/json"},+ "auth": {"type": "api_key", "api_key": api_key, "name": "X-API-KEY", "location": "header"},+ # No pagination is documented on any endpoint — each table is a single bare-array page.+ "paginator": "single_page",+ # Don't follow redirects: a compromised/edited base_url could 3xx to an internal address,+ # bypassing the host check below (SSRF).+ "allow_redirects": False,+ "request_timeout": REQUEST_TIMEOUT_SECONDS,+ },+ "resource_defaults": None,+ "resources": [get_resource(endpoint)],+ }++ wrap_field = config.wrap_scalar_as++ def items() -> Any:+ # Re-check at run time, not just at source-create: the base_url can be edited later and now+ # resolve to an internal address (SSRF / DNS rebinding). Only enforced on cloud.+ host_ok, host_err = _is_host_safe(host, team_id)+ if not host_ok:+ raise MoxieHostNotAllowedError(host_err or HOST_NOT_ALLOWED_ERROR)+ if not _is_https(resolved_base_url):+ raise MoxieHostNotAllowedError(HTTP_NOT_ALLOWED_ERROR)++ for batch in rest_api_resource(rest_config, team_id, job_id, None):+ if wrap_field:+ yield [{wrap_field: value} for value in batch]+ else:+ yield batch++ has_partition_key = config.partition_key is not None+ return SourceResponse(+ name=endpoint,+ items=items,+ primary_keys=config.primary_keys,+ # Full-refresh replace: there's no incremental watermark to checkpoint, but an explicit sort+ # still guards against a page-boundary shuffle on the (single, unpaginated) response.+ sort_mode="asc",+ partition_mode="datetime" if has_partition_key else None,+ partition_format="month" if has_partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )+++def validate_credentials(+ base_url: Optional[str], api_key: str, team_id: Optional[int] = None+) -> tuple[bool, str | None]:+ resolved_base_url = normalize_base_url(base_url)+ host = _host_of(resolved_base_url)++ if not host:+ return False, "That doesn't look like a Moxie workspace base URL."++ # The host is fully customer-controlled (per-workspace pod), so block hosts that resolve to+ # private/internal addresses (SSRF). Only enforced on cloud — see _is_host_safe.+ if team_id is not None:+ host_ok, host_err = _is_host_safe(host, team_id)+ if not host_ok:+ return False, host_err or HOST_NOT_ALLOWED_ERROR++ if not _is_https(resolved_base_url):+ return False, HTTP_NOT_ALLOWED_ERROR++ # List Clients takes no parameters and needs no scope beyond the API key itself, so it's the+ # cheapest probe available and doubles as the request the `clients` table itself makes.+ url = f"{resolved_base_url}{MOXIE_API_PATH_PREFIX}/clients/list"+ is_valid, status = validate_via_probe(+ lambda: make_tracked_session(redact_values=(api_key,)),+ url,+ headers={"X-API-KEY": api_key, "Accept": "application/json"},+ allow_redirects=False,+ )+ if is_valid:+ return True, None+ if status == 401:+ return False, "Moxie rejected the API key. Check the key and workspace base URL, then try again."+ if status == 403:+ return False, "The Moxie API key does not have permission for this workspace."+ return False, "Could not connect to Moxie with the given credentials."diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/moxie/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/moxie/settings.pynew file mode 100644index 000000000000..3986df6375c0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/moxie/settings.py@@ -0,0 +1,84 @@+from dataclasses import field+from typing import Optional++from posthog.dataclasses import frozen++# Moxie's Public API is served from a per-workspace pod host (e.g. `pod00.withmoxie.dev`), captured+# as the `base_url` credential field rather than hardcoded here. This is the path segment every pod+# appends after its host, per the endpoint-specific Help Center articles (List Clients, Search+# Contacts, etc). The overview "Public API Fundamentals" article shows an older `/clients/create`+# path shape with no `/action/` segment, but every endpoint-specific article agrees on `/action/...`,+# so that's what this source targets.+MOXIE_API_PATH_PREFIX = "/action"+++@frozen+class MoxieEndpointConfig:+ name: str+ """Table name we expose to the user (snake_case)."""+ path: str+ """Path relative to `base_url`, including the `/action` prefix."""+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ partition_key: Optional[str] = None+ """Stable creation-time field used for Delta partitioning; None leaves the table unpartitioned."""+ wrap_scalar_as: Optional[str] = None+ """Set when the endpoint returns a bare array of strings (e.g. template names) rather than+ objects, naming the single column each string is wrapped into."""+++# Moxie's Public API (https://help.withmoxie.com/en/collections/5482062-public-api-endpoints) exposes+# no pagination and no server-side timestamp filter on any list/search endpoint, so every table here+# is full refresh only. `clients` uses List Clients rather than Search Clients: Search Clients+# requires a `query` parameter, which can't express "give me everything", while List Clients takes no+# parameters at all. Contacts, Projects, and Payable Invoices only have a Search endpoint, but their+# `query` parameter is documented as optional, so omitting it returns the full collection.+#+# The client object's own documented response omits an `id` field entirely (Contacts, Projects, and+# Payable Invoices all reference a client by `clientId`, so one exists internally) — `name` is the+# best available key. Full refresh replaces the whole table each sync, so this doesn't risk a merge+# blow-up the way a non-unique key would on an incrementally-merged table.+MOXIE_ENDPOINTS: dict[str, MoxieEndpointConfig] = {+ "clients": MoxieEndpointConfig(name="clients", path=f"{MOXIE_API_PATH_PREFIX}/clients/list", primary_keys=["name"]),+ "contacts": MoxieEndpointConfig(name="contacts", path=f"{MOXIE_API_PATH_PREFIX}/contacts/search"),+ "projects": MoxieEndpointConfig(+ name="projects", path=f"{MOXIE_API_PATH_PREFIX}/projects/search", partition_key="dateCreated"+ ),+ "payable_invoices": MoxieEndpointConfig(+ name="payable_invoices",+ path=f"{MOXIE_API_PATH_PREFIX}/payableInvoices/search",+ partition_key="dateCreated",+ ),+ "email_templates": MoxieEndpointConfig(+ name="email_templates",+ path=f"{MOXIE_API_PATH_PREFIX}/emailTemplates/list",+ primary_keys=["name"],+ wrap_scalar_as="name",+ ),+ "invoice_templates": MoxieEndpointConfig(+ name="invoice_templates",+ path=f"{MOXIE_API_PATH_PREFIX}/invoiceTemplates/list",+ primary_keys=["name"],+ wrap_scalar_as="name",+ ),+ "vendor_names": MoxieEndpointConfig(+ name="vendor_names",+ path=f"{MOXIE_API_PATH_PREFIX}/vendors/list",+ primary_keys=["name"],+ wrap_scalar_as="name",+ ),+ "form_names": MoxieEndpointConfig(+ name="form_names",+ path=f"{MOXIE_API_PATH_PREFIX}/formNames/list",+ primary_keys=["name"],+ wrap_scalar_as="name",+ ),+ "pipeline_stages": MoxieEndpointConfig(name="pipeline_stages", path=f"{MOXIE_API_PATH_PREFIX}/pipelineStages/list"),+ "task_stages": MoxieEndpointConfig(name="task_stages", path=f"{MOXIE_API_PATH_PREFIX}/taskStages/list"),+ # Rows are keyed by the nested `user.userId`, flattened onto the row root as `user_id` (see+ # `moxie.py`) since a nested field can't be declared as a primary key.+ "workspace_users": MoxieEndpointConfig(+ name="workspace_users", path=f"{MOXIE_API_PATH_PREFIX}/users/list", primary_keys=["user_id"]+ ),+}++ENDPOINTS = tuple(MOXIE_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/moxie/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/moxie/source.pyindex 768713d2a5df..a70032a141b1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/moxie/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/moxie/source.py@@ -1,30 +1,126 @@-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.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.moxie import MoxieSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.moxie.moxie import (+ HOST_NOT_ALLOWED_ERROR,+ HTTP_NOT_ALLOWED_ERROR,+ moxie_source,+ validate_credentials as validate_moxie_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.moxie.settings import ENDPOINTSfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.registerclass MoxieSource(SimpleSource[MoxieSourceConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ api_docs_url = "https://help.withmoxie.com/en/collections/5482062-public-api-endpoints"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.MOXIE+ @property+ def connection_host_fields(self) -> list[str]:+ # `base_url` is where the stored API key is sent; retargeting it must re-require the key.+ return ["base_url"]++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Moxie rejected the API key. Check the key and workspace base URL in Workspace settings > Connected Apps > Integrations, then reconnect.",+ "403 Client Error": "The Moxie API key does not have permission for this workspace.",+ HOST_NOT_ALLOWED_ERROR: "The Moxie workspace base URL is not allowed. Please use a publicly reachable host.",+ HTTP_NOT_ALLOWED_ERROR: "The Moxie workspace base URL must use HTTPS. Please update it to use https://.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.moxie.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: MoxieSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ # Moxie's Public API exposes no pagination, cursors, or server-side timestamp filters, so+ # every table is full refresh only.+ return build_endpoint_schemas(ENDPOINTS, {}, names)++ def validate_credentials(+ self,+ config: MoxieSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_moxie_credentials(config.base_url, config.api_key, team_id)++ def source_for_pipeline(self, config: MoxieSourceConfig, inputs: SourceInputs) -> SourceResponse:+ return moxie_source(+ base_url=config.base_url,+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.MOXIE,category=DataWarehouseSourceCategory.CRM,label="Moxie",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["freelance crm", "invoicing", "time tracking"],+ caption="""Enter your Moxie workspace base URL and API key to pull your clients, projects, invoices, and more into the PostHog Data warehouse.++Go to **Workspace settings > Connected Apps > Integrations** in Moxie and click **Enable Custom Integration** to see your workspace's base URL and API key.""",iconPath="/static/services/moxie.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="base_url",+ label="Workspace base URL",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="https://pod00.withmoxie.dev/api/public",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/moxie/tests/test_moxie.py b/products/warehouse_sources/backend/temporal/data_imports/sources/moxie/tests/test_moxie.pynew file mode 100644index 000000000000..f14d43c21a11--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/moxie/tests/test_moxie.py@@ -0,0 +1,198 @@+import json+from typing import Any++import pytest+from unittest import mock++from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.moxie import moxie as moxie_module+from products.warehouse_sources.backend.temporal.data_imports.sources.moxie.moxie import (+ MoxieHostNotAllowedError,+ moxie_source,+ normalize_base_url,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.moxie.settings import ENDPOINTS, MOXIE_ENDPOINTS++# RESTClient builds its session via make_tracked_session in the rest_client module.+CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+# validate_credentials builds its own tracked session in the moxie module.+MOXIE_SESSION_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.moxie.moxie.make_tracked_session"+)++BASE_URL = "https://pod00.withmoxie.dev/api/public"+++def _response(body: Any, status: int = 200) -> Response:+ resp = Response()+ resp.status_code = status+ resp._content = json.dumps(body).encode()+ return resp+++def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:+ """Wire a mock session and snapshot each request's URL + auth headers at prepare time."""+ session.headers = {}+ seen: list[dict[str, Any]] = []++ def _prepare(request: Any) -> mock.MagicMock:+ prepared = mock.MagicMock()+ prepared.headers = {}+ if request.auth is not None:+ request.auth(prepared)+ seen.append({"url": request.url, "auth_headers": dict(prepared.headers)})+ return prepared++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return seen+++def _source(endpoint: str, base_url: str = BASE_URL, team_id: int = 1) -> Any:+ return moxie_source(base_url, "test_key", endpoint, team_id=team_id, job_id="j")+++def _batches(source_response: Any) -> list[list[dict[str, Any]]]:+ return [list(page) for page in source_response.items()]+++class TestNormalizeBaseUrl:+ @pytest.mark.parametrize(+ "raw, expected",+ [+ ("https://pod00.withmoxie.dev/api/public", "https://pod00.withmoxie.dev/api/public"),+ ("https://pod00.withmoxie.dev/api/public/", "https://pod00.withmoxie.dev/api/public"),+ ("pod00.withmoxie.dev", "https://pod00.withmoxie.dev/api/public"),+ ("http://pod00.withmoxie.dev", "http://pod00.withmoxie.dev/api/public"),+ (" https://pod00.withmoxie.dev/api/public ", "https://pod00.withmoxie.dev/api/public"),+ ("", ""),+ (None, ""),+ ],+ )+ def test_normalizes_variants(self, raw: str | None, expected: str) -> None:+ assert normalize_base_url(raw) == expected+++class TestMoxieTransport:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_object_endpoint_yields_single_batch_with_api_key_header(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ seen = _wire(session, [_response([{"id": "1"}, {"id": "2"}])])++ batches = _batches(_source("contacts"))++ assert batches == [[{"id": "1"}, {"id": "2"}]]+ # No pagination anywhere on Moxie's API — exactly one request per endpoint.+ assert session.send.call_count == 1+ assert seen[0]["url"] == f"{BASE_URL}/action/contacts/search"+ assert seen[0]["auth_headers"]["X-API-KEY"] == "test_key"++ @pytest.mark.parametrize("endpoint", ["email_templates", "invoice_templates", "vendor_names", "form_names"])+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_scalar_endpoints_wrap_bare_strings_into_rows(self, MockSession: mock.MagicMock, endpoint: str) -> None:+ session = MockSession.return_value+ _wire(session, [_response(["Template A", "Template B"])])++ batches = _batches(_source(endpoint))++ assert batches == [[{"name": "Template A"}, {"name": "Template B"}]]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_workspace_users_flattens_nested_user_id(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ row = {"userType": "OWNER", "user": {"userId": 42, "firstName": "Alex"}}+ _wire(session, [_response([row])])++ batches = _batches(_source("workspace_users"))++ assert batches == [[{**row, "user_id": 42}]]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_host_check_blocks_before_any_request(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ _wire(session, [_response([])])++ with mock.patch.object(moxie_module, "_is_host_safe", return_value=(False, "internal address")):+ with pytest.raises(MoxieHostNotAllowedError, match="internal address"):+ _batches(_source("clients"))++ session.send.assert_not_called()++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_plaintext_http_is_rejected_before_any_request(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ _wire(session, [_response([])])++ with pytest.raises(MoxieHostNotAllowedError, match="HTTPS"):+ _batches(_source("clients", base_url="http://pod00.withmoxie.dev/api/public"))++ session.send.assert_not_called()+++class TestSourceResponseConfig:+ def test_all_endpoints_buildable_with_declared_keys(self) -> None:+ for endpoint in ENDPOINTS:+ response = _source(endpoint)+ assert response.name == endpoint+ assert response.primary_keys == MOXIE_ENDPOINTS[endpoint].primary_keys++ def test_projects_and_invoices_partition_on_a_stable_creation_field(self) -> None:+ for endpoint in ("projects", "payable_invoices"):+ response = _source(endpoint)+ assert response.partition_mode == "datetime"+ assert response.partition_format == "month"+ assert response.partition_keys == ["dateCreated"]++ def test_endpoints_without_a_creation_field_are_unpartitioned(self) -> None:+ for endpoint in ("clients", "contacts", "email_templates", "workspace_users"):+ response = _source(endpoint)+ assert response.partition_mode is None+ assert response.partition_keys is None+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "status, expected_valid",+ [(200, True), (401, False), (403, False), (500, False)],+ )+ @mock.patch(MOXIE_SESSION_PATCH)+ def test_status_mapping(self, mock_session: mock.MagicMock, status: int, expected_valid: bool) -> None:+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=status)+ is_valid, _message = validate_credentials(BASE_URL, "test_key", team_id=1)+ assert is_valid is expected_valid++ @mock.patch(MOXIE_SESSION_PATCH)+ def test_connection_error_returns_false(self, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.get.side_effect = Exception("boom")+ is_valid, _message = validate_credentials(BASE_URL, "test_key", team_id=1)+ assert is_valid is False++ @mock.patch(MOXIE_SESSION_PATCH)+ def test_probes_clients_list_with_api_key_header_and_redaction(self, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)+ validate_credentials(BASE_URL, "test_key", team_id=1)++ call = mock_session.return_value.get.call_args+ called_url = call.args[0] if call.args else call.kwargs["url"]+ assert called_url == f"{BASE_URL}/action/clients/list"+ assert call.kwargs["headers"]["X-API-KEY"] == "test_key"+ # The key must be registered for redaction in tracked telemetry.+ assert mock_session.call_args.kwargs["redact_values"] == ("test_key",)++ def test_blank_base_url_is_rejected(self) -> None:+ is_valid, message = validate_credentials("", "test_key", team_id=1)+ assert is_valid is False+ assert message == "That doesn't look like a Moxie workspace base URL."++ def test_plaintext_http_is_rejected_before_any_request(self) -> None:+ is_valid, message = validate_credentials("http://pod00.withmoxie.dev/api/public", "test_key", team_id=1)+ assert is_valid is False+ assert message is not None and "HTTPS" in message++ def test_host_not_allowed_is_rejected(self) -> None:+ with mock.patch.object(moxie_module, "_is_host_safe", return_value=(False, "internal address")):+ is_valid, message = validate_credentials(BASE_URL, "test_key", team_id=1)+ assert is_valid is False+ assert message == "internal address"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/moxie/tests/test_moxie_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/moxie/tests/test_moxie_source.pynew file mode 100644index 000000000000..44930004eacb--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/moxie/tests/test_moxie_source.py@@ -0,0 +1,117 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.moxie import MoxieSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.moxie.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.moxie.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.moxie.source import MoxieSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestMoxieSource:+ def setup_method(self) -> None:+ self.source = MoxieSource()+ self.team_id = 123+ self.config = MoxieSourceConfig(base_url="https://pod00.withmoxie.dev/api/public", api_key="test_key")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.MOXIE++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "Moxie"+ assert config.label == "Moxie"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # A finished source is visible to users — the scaffold's unreleasedSource flag must be gone.+ assert not config.unreleasedSource+ assert config.iconPath == "/static/services/moxie.png"++ def test_fields_have_expected_types(self) -> None:+ config = self.source.get_source_config+ fields = {f.name: f for f in config.fields if isinstance(f, SourceFieldInputConfig)}+ assert set(fields.keys()) == {"base_url", "api_key"}++ assert fields["base_url"].type == SourceFieldInputConfigType.TEXT+ assert fields["base_url"].required is True+ assert fields["base_url"].secret is False++ assert fields["api_key"].type == SourceFieldInputConfigType.PASSWORD+ assert fields["api_key"].required is True+ assert fields["api_key"].secret is True++ def test_connection_host_fields(self) -> None:+ # base_url carries the API key's destination, so editing it must re-require the secret.+ assert self.source.connection_host_fields == ["base_url"]++ def test_get_schemas_covers_all_endpoints_as_full_refresh(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ assert all(s.supports_incremental is False for s in schemas)+ assert all(s.supports_append is False for s in schemas)+ assert all(s.incremental_fields == [] for s in schemas)++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["clients"])+ assert [s.name for s in schemas] == ["clients"]++ def test_documented_tables_render_for_public_docs(self) -> None:+ # lists_tables_without_credentials=True + static get_schemas means the doc's Supported tables+ # section is populated without a live connection.+ tables = self.source.get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)+ assert all("Full refresh" in t["sync_methods"] for t in tables)++ def test_canonical_descriptions_keyed_by_endpoint_names(self) -> None:+ # A renamed endpoint would silently orphan its curated descriptions.+ assert set(CANONICAL_DESCRIPTIONS.keys()) == set(ENDPOINTS)++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://pod00.withmoxie.dev/api/public/action/clients/list",+ "403 Client Error: Forbidden for url: https://pod00.withmoxie.dev/api/public/action/clients/list",+ "Moxie workspace base URL is not allowed",+ "Moxie workspace base URL must use HTTPS",+ ],+ )+ def test_non_retryable_errors_match_auth_and_host_failures(self, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @pytest.mark.parametrize(+ "unrelated_error",+ ["429 Client Error: Too Many Requests", "500 Server Error", "Connection reset by peer"],+ )+ def test_non_retryable_errors_ignore_transient(self, unrelated_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in unrelated_error for key in non_retryable)++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.moxie.source.validate_moxie_credentials"+ )+ def test_validate_credentials_plumbs_arguments(self, mock_validate: mock.MagicMock) -> None:+ mock_validate.return_value = (True, None)++ result = self.source.validate_credentials(self.config, self.team_id)++ assert result == (True, None)+ mock_validate.assert_called_once_with(self.config.base_url, self.config.api_key, self.team_id)++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.moxie.source.moxie_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_moxie_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "projects"++ self.source.source_for_pipeline(self.config, inputs)++ mock_moxie_source.assert_called_once()+ kwargs = mock_moxie_source.call_args.kwargs+ assert kwargs["base_url"] == self.config.base_url+ assert kwargs["api_key"] == self.config.api_key+ assert kwargs["endpoint"] == "projects"+ assert kwargs["team_id"] is inputs.team_id+ assert kwargs["job_id"] is inputs.job_id